using System;
using System.Runtime.InteropServices;

public enum CcanConst
{
	//================================================================
	// Parameters
	//================================================================
	//----------------------------------------
	// Monitor mode
	//----------------------------------------
	CCAN_MONITOR_OFF					= 0,		// Monitor mode OFF
	CCAN_MONITOR_ON						= 1,		// Monitor mode ON
	//----------------------------------------
	// Message type
	//----------------------------------------
	CCAN_MSG_TYPE_DISABLE				= 0x00,		// All messages are valid
	CCAN_MSG_TYPE_CAN					= 0x01,		// CAN message
	CCAN_MSG_TYPE_CAN_FD				= 0x02,		// CAN FD message
	CCAN_MSG_TYPE_REMOTE_FRAME			= 0x04,		// Remote frame
	CCAN_MSG_TYPE_BITRATE_SWITCH		= 0x08,		// Bitrate switch
	CCAN_MSG_TYPE_STANDARD_FORMAT		= 0x10,		// Standard format
	CCAN_MSG_TYPE_EXTENDED_FORMAT		= 0x20,		// Extended format
	//----------------------------------------
	// CAN bus error
	//----------------------------------------
	CCAN_STATUS_ERR_BIT					= 0x01,		// Bit error
	CCAN_STATUS_ERR_FORM				= 0x02,		// Form error
	CCAN_STATUS_ERR_STUFF				= 0x03,		// Stuff error
	CCAN_STATUS_ERR_ACK					= 0x04,		// ACK error
	CCAN_STATUS_ERR_CRC					= 0x05,		// CRC error
	CCAN_STATUS_ERR_OTHER				= 0x06,		// Other error
	//----------------------------------------
	// Channel status
	//----------------------------------------
	CCAN_CH_STATUS_ERR_ACTIVE			= 0x0000,	// Error active
	CCAN_CH_STATUS_ERR_PASSIVE 			= 0x0001,	// Error passive
	CCAN_CH_STATUS_BUS_OFF				= 0x0002,	// Bus off
	//----------------------------------------
	// Event type
	//----------------------------------------
	CCAN_EVENT_RECEIVE					= 0x01,		// Receive event

	//================================================================
	// Error codes
	//================================================================
	// Initialize Error
	// Common
	CAN_ERR_SUCCESS						= 0,		// Normal completed
	CAN_ERR_INI_RESOURCE				= 1,		// Invalid resource reference specified
	CAN_ERR_INI_INTERRUPT				= 2,		// Invalid interrupt routine registered
	CAN_ERR_INI_MEMORY					= 3,		// Invalid memory allocationed
	CAN_ERR_INI_REGISTRY				= 4,		// Invalid registry accesse
	CAN_ERR_SYS_RECOVERED_FROM_STANDBY	= 7,		// Execute CanResetDevice function because the device has recovered from standby mode.
	CAN_ERR_INI_NOT_FOUND_SYS_FILE		= 8,		// Because the ccan.sys file is not found, it is not possible to initialize it.
	CAN_ERR_INI_DLL_FILE_VERSION		= 9,		// Because version information on the ccan.dll file cannot be acquired, it is not possible to initialize it.
	CAN_ERR_INI_SYS_FILE_VERSION		= 10,		// Because version information on the ccan.sys file cannot be acquired, it is not possible to initialize it.
	CAN_ERR_INI_NO_MATCH_DRV_VERSION	= 11,		// Because version information on ccan.dll and ccan.sys is different, it is not possible to initialize it.

	// DLL Error
	// Common
	CAN_ERR_DLL_DEVICE_NAME				= 10000,	// Invalid device name specified.
	CAN_ERR_DLL_INVALID_ID				= 10001,	// Invalid ID specified.
	CAN_ERR_DLL_CALL_DRIVER				= 10002,	// Not call the driver.(Invalid device I/O controller)
	CAN_ERR_DLL_CREATE_FILE				= 10003,	// Not create the file.(Invalid CreateFile)
	CAN_ERR_DLL_CLOSE_FILE				= 10004,	// Not close the file.(Invalid CloseFile)
	CAN_ERR_DLL_CREATE_THREAD			= 10005,	// Not create the thread.(Invalid CreateThread)
	CAN_ERR_INFO_INVALID_DEVICE			= 10050,	// Invalid device infomation specified .Please check the spell.
	CAN_ERR_INFO_NOT_FIND_DEVICE		= 10051,	// Not find the available device
	CAN_ERR_INFO_INVALID_INFOTYPE		= 10052,	// Specified device infomation type beyond the limit
	CAN_ERR_INFO_NOT_FOUND_DEVINFO		= 10053,	// No device information was found in the information retrieval.
	// CAN
	CAN_ERR_DLL_BUFF_ADDRESS			= 10100,	// Invalid data buffer address
	CAN_ERR_DLL_HWND					= 10200,	// Window handle beyond the limit
	CAN_ERR_DLL_EVENT_TYPE				= 10300,	// Trigger kind beyond the limit
	CAN_ERR_DLL_CALLBACK				= 10400,	// Invalid callback function address.

	// SYS Error
	// Common
	CAN_ERR_SYS_MEMORY					= 20000,	// Not secure memory
	CAN_ERR_SYS_NOT_SUPPORTED			= 20001,	// This board couldn't use this function
	CAN_ERR_SYS_BOARD_EXECUTING			= 20002,	// Board is behaving, not execute
	CAN_ERR_SYS_USING_OTHER_PROCESS		= 20003,	// Other process is using the device, not execute
	CAN_ERR_SYS_NOT_FOUND_PROCESS_DATA	= 20004,	// Process information is not found.
	// CAN
	CAN_ERR_SYS_MONITOR_MODE			= 20100,	// Monitor mode is out of the settable range.
	CAN_ERR_SYS_CH_NO					= 20101,	// The channel number is out of the settable range.
	CAN_ERR_SYS_DATA_FRAME_FORMAT		= 20102,	// Data frame format is out of the settable range.
	CAN_ERR_SYS_BITRATE					= 20110,	// Bit rate is out of the settable range.
	CAN_ERR_SYS_TOTAL_TQ				= 20111,	// Total TQ is out of the settable range.
	CAN_ERR_SYS_TSEG1					= 20120,	// Time segment 1 is outside the settable range.
	CAN_ERR_SYS_SJW						= 20121,	// Sync jump width is out of the settable range.
	CAN_ERR_SYS_TSEG2					= 20122,	// Time segment 2 is outside the settable range.
	CAN_ERR_SYS_ARB_BITRATE				= 20130,	// Arbitration bit rate is outside the settable range.
	CAN_ERR_SYS_ARB_TSEG1				= 20131,	// Arbitration time segment 1 is outside the settable range.
	CAN_ERR_SYS_ARB_SJW					= 20132,	// Arbitration synchronous jump width is outside the settable range.
	CAN_ERR_SYS_ARB_TSEG2				= 20133,	// Arbitration time segment 2 is outside the settable range.
	CAN_ERR_SYS_DATA_BITRATE			= 20140,	// Bit rate is out of the settable range.
	CAN_ERR_SYS_DATA_TSEG1				= 20141,	// Data time segment 1 is outside the settable range.
	CAN_ERR_SYS_DATA_SJW				= 20142,	// Data synchronization jump width is outside the settable range.
	CAN_ERR_SYS_DATA_TSEG2				= 20143,	// Data time segment 2 is outside the settable range.
	CAN_ERR_SYS_MESSAGE_NUM				= 20150,	// Number of messages is out of the settable range.
	CAN_ERR_SYS_MESSAGE_TYPE			= 20151,	// Message type is outside the settable range.
	CAN_ERR_SYS_DATA_LEN				= 20160,	// Data length is outside the settable range.
	CAN_ERR_SYS_CAN_ID					= 20170,	// CAN ID is outside the settable range.
	CAN_ERR_SYS_TIMEOUT_TIME			= 20180,	// Timeout time is outside the settable range.
	CAN_ERR_SYS_BUSON					= 20200,	// Cannot execute because the bus on.
	CAN_ERR_SYS_REC_FIFO_OVERFLOW		= 20220,	// Receive FIFO overflowed.
	CAN_ERR_SYS_DEVICE_ACCESS			= 20500,	// The device could not be accessed normally.
}

namespace CcanCs
{
	unsafe public delegate void PCAN_EVENT_CALLBACK(short Id, int wParam, int lParam, void *Param);

	public class Ccan
	{
		//----------------------------------------
		// Common function
		//----------------------------------------
		[DllImport("ccan.dll")] static extern int CanInit(string DeviceName, ref short Id);
		[DllImport("ccan.dll")] static extern int CanExit(short Id);
		[DllImport("ccan.dll")] static extern int CanResetDevice(short Id);
		[DllImport("ccan.dll")] static extern int CanGetErrorString(int ErrorCode, System.Text.StringBuilder ErrorString);

		//----------------------------------------
		// Information acquisition function
		//----------------------------------------
		[DllImport("ccan.dll")] static extern int CanQueryDeviceName(short Index, System.Text.StringBuilder DeviceName, System.Text.StringBuilder Device);
		[DllImport("ccan.dll")] static extern int CanGetMaxChannels(short Id, ref ushort CanChannelNum, ref ushort CanFdChannelNum);

		//----------------------------------------
		// Setup and get setup functions
		//----------------------------------------
		[DllImport("ccan.dll")] static extern int CanResetDeviceTickCount(short Id);
		[DllImport("ccan.dll")] static extern int CanSetChannelAcceptance(short Id, ushort ChannelNo, uint MessageTypeMask, uint CanIdMask, uint CanIdCode);
		[DllImport("ccan.dll")] static extern int CanGetChannelAcceptance(short Id, ushort ChannelNo, ref uint MessageTypeMask, ref uint CanIdMask, ref uint CanIdCode);
		[DllImport("ccan.dll")] static extern int CanSetCanTiming(short Id, ushort ChannelNo, uint Bitrate, ushort TSeg1, ushort SJW, ushort TSeg2);
		[DllImport("ccan.dll")] static extern int CanGetCanTiming(short Id, ushort ChannelNo, ref uint Bitrate, ref ushort TSeg1, ref ushort SJW, ref ushort TSeg2);
		[DllImport("ccan.dll")] static extern int CanSetCanFdTiming(short Id, ushort ChannelNo, uint ArbBitrate, ushort ArbTSeg1, ushort ArbSJW, ushort ArbTSeg2, uint DataBitrate, ushort DataTSeg1, ushort DataSJW, ushort DataTSeg2);
		[DllImport("ccan.dll")] static extern int CanGetCanFdTiming(short Id, ushort ChannelNo, ref uint ArbBitrate, ref ushort ArbTSeg1, ref ushort ArbSJW, ref ushort ArbTSeg2, ref uint DataBitrate, ref ushort DataTSeg1, ref ushort DataSJW, ref ushort DataTSeg2);
		[DllImport("ccan.dll")] static extern int CanSetMonitorMode(short Id, ushort ChannelNo, ushort MonitorMode);
		[DllImport("ccan.dll")] static extern int CanSetTimeout(short Id, uint Timeout);
		[DllImport("ccan.dll")] static extern int CanGetTimeout(short Id, ref uint Timeout);

		//----------------------------------------
		// Bus control function
		//----------------------------------------
		[DllImport("ccan.dll")] static extern int CanBusConnect(short Id, ushort ChannelNo);
		[DllImport("ccan.dll")] static extern int CanBusDisconnect(short Id, ushort ChannelNo);

		//----------------------------------------
		// Communication function
		//----------------------------------------
		[DllImport("ccan.dll")] static extern int CanTransmit(short Id, ushort ChannelNo, uint MessageNum, [MarshalAs(UnmanagedType.LPArray)] uint[] MessageType, [MarshalAs(UnmanagedType.LPArray)] uint[] CanId, [MarshalAs(UnmanagedType.LPArray)] ushort[] DataLength, [MarshalAs(UnmanagedType.LPArray)] byte[,] Data);
		[DllImport("ccan.dll")] static extern int CanReceive(short Id, ushort ChannelNo, ref uint MessageNum, [MarshalAs(UnmanagedType.LPArray)] uint[] MessageType, [MarshalAs(UnmanagedType.LPArray)] uint[] CanId, [MarshalAs(UnmanagedType.LPArray)] ushort[] DataLength, [MarshalAs(UnmanagedType.LPArray)] byte[,] Data, [MarshalAs(UnmanagedType.LPArray)] uint[] ErrorCode, [MarshalAs(UnmanagedType.LPArray)] ulong[] TickCount);
		[DllImport("ccan.dll")] static extern int CanGetChannelStatus(short Id, ushort ChannelNo, ref ushort ChannelStatus, ref ushort TxErrorCount, ref ushort RxErrorCount);

		//----------------------------------------
		// Event function
		//----------------------------------------
		[DllImport("ccan.dll")] unsafe static extern int CanNotifyEvent(short Id, ushort ChannelNo, ushort EventType, IntPtr CallBackProc, void *Param);
		[DllImport("ccan.dll")] static extern int CanStopNotifyEvent(short Id, ushort ChannelNo, ushort EventType);

		//----------------------------------------
		// Constructor
		//----------------------------------------
		public Ccan()
		{
		}

		//----------------------------------------
		// Common function
		//----------------------------------------
		public int Init(string DeviceName, out short Id)
		{
			Id = 0;
			int ret	= CanInit(DeviceName, ref Id);
			return	ret;
		}
		public int Exit(short Id)
		{
			int ret = CanExit(Id);
			return ret;
		}
		public int ResetDevice(short Id)
		{
			int ret = CanResetDevice(Id);
			return ret;
		}
		public int GetErrorString(int ErrorCode, out string ErrorString)
		{
			ErrorString = new String('0', 1);
			System.Text.StringBuilder errorstring = new System.Text.StringBuilder(256);
			int ret = CanGetErrorString(ErrorCode, errorstring);
			if(ret == 0)
			{
				ErrorString = errorstring.ToString();
			}
			return ret;
		}

		//----------------------------------------
		// Information acquisition function
		//----------------------------------------
		public int QueryDeviceName(short Index, out string DeviceName, out string Device)
		{
			DeviceName = new String('0',1);
			Device = new String('0',1);
			System.Text.StringBuilder devicename = new System.Text.StringBuilder(256);
			System.Text.StringBuilder device = new System.Text.StringBuilder(256);
			int ret = CanQueryDeviceName(Index, devicename, device);
			if(ret == 0)
			{
				DeviceName = devicename.ToString();
				Device = device.ToString();
			}
			return ret;
		}
		public int GetMaxChannels(short Id, out ushort CanChannelNum, out ushort CanFdChannelNum)
		{
			CanChannelNum = 0;
			CanFdChannelNum = 0;
			int ret = CanGetMaxChannels(Id, ref CanChannelNum, ref CanFdChannelNum);
			return ret;
		}


		//----------------------------------------
		// Setup and get setup functions
		//----------------------------------------
		public int ResetDeviceTickCount(short Id)
		{
			int ret = CanResetDeviceTickCount(Id);
			return ret;
		}
		public int SetChannelAcceptance(short Id, ushort ChannelNo, uint MessageTypeMask, uint CanIdMask, uint CanIdCode)
		{
			int ret = CanSetChannelAcceptance(Id, ChannelNo, MessageTypeMask, CanIdMask, CanIdCode);
			return ret;
		}
		public int GetChannelAcceptance(short Id, ushort ChannelNo, out uint MessageTypeMask, out uint CanIdMask, out uint CanIdCode)
		{
			MessageTypeMask = 0;
			CanIdMask = 0;
			CanIdCode = 0;
			int ret = CanGetChannelAcceptance(Id, ChannelNo, ref MessageTypeMask, ref CanIdMask, ref CanIdCode);
			return ret;
		}
		public int SetCanTiming(short Id, ushort ChannelNo, uint Bitrate, ushort TSeg1, ushort SJW, ushort TSeg2)
		{
			int ret = CanSetCanTiming(Id, ChannelNo, Bitrate, TSeg1, SJW, TSeg2);
			return ret;
		}
		public int GetCanTiming(short Id, ushort ChannelNo, out uint Bitrate, out ushort TSeg1, out ushort SJW, out ushort TSeg2)
		{
			Bitrate = 0;
			TSeg1 = 0;
			SJW = 0;
			TSeg2 = 0;
			int ret = CanGetCanTiming(Id, ChannelNo, ref Bitrate, ref TSeg1, ref SJW, ref TSeg2);
			return ret;
		}
		public int SetCanFdTiming(short Id, ushort ChannelNo, uint ArbBitrate, ushort ArbTSeg1, ushort ArbSJW, ushort ArbTSeg2, uint DataBitrate, ushort DataTSeg1, ushort DataSJW, ushort DataTSeg2)
		{
			int ret = CanSetCanFdTiming(Id, ChannelNo, ArbBitrate, ArbTSeg1, ArbSJW, ArbTSeg2, DataBitrate, DataTSeg1, DataSJW, DataTSeg2);
			return ret;
		}
		public int GetCanFdTiming(short Id, ushort ChannelNo, out uint ArbBitrate, out ushort ArbTSeg1, out ushort ArbSJW, out ushort ArbTSeg2, out uint DataBitrate, out ushort DataTSeg1, out ushort DataSJW, out ushort DataTSeg2)
		{
			ArbBitrate = 0;
			ArbTSeg1 = 0;
			ArbSJW = 0;
			ArbTSeg2 = 0;
			DataBitrate = 0;
			DataTSeg1 = 0;
			DataSJW = 0;
			DataTSeg2 = 0;
			int ret = CanGetCanFdTiming(Id, ChannelNo, ref ArbBitrate, ref ArbTSeg1, ref ArbSJW, ref ArbTSeg2, ref DataBitrate, ref DataTSeg1, ref DataSJW, ref DataTSeg2);
			return ret;
		}
		public int SetMonitorMode(short Id, ushort ChannelNo, ushort MonitorMode)
		{
			int ret = CanSetMonitorMode(Id, ChannelNo, MonitorMode);
			return ret;
		}
		public int SetTimeout(short Id, uint Timeout)
		{
			int ret = CanSetTimeout(Id, Timeout);
			return ret;
		}
		public int GetTimeout(short Id, out uint Timeout)
		{
			Timeout = 0;
			int ret = CanGetTimeout(Id, ref Timeout);
			return ret;
		}

		//----------------------------------------
		// Bus control function
		//----------------------------------------
		public int BusConnect(short Id, ushort ChannelNo)
		{
			int ret = CanBusConnect(Id, ChannelNo);
			return ret;
		}
		public int BusDisconnect(short Id, ushort ChannelNo)
		{
			int ret = CanBusDisconnect(Id, ChannelNo);
			return ret;
		}

		//----------------------------------------
		// Communication function
		//----------------------------------------
		public int Transmit(short Id, ushort ChannelNo, uint MessageNum, uint[] MessageType, uint[] CanId, ushort[] DataLength, byte[,] Data)
		{
			int ret = CanTransmit(Id, ChannelNo, MessageNum, MessageType, CanId, DataLength, Data);
			return ret;
		}
		public int Receive(short Id, ushort ChannelNo, ref uint MessageNum, ref uint[] MessageType, ref uint[] CanId, ref ushort[] DataLength, ref byte[,] Data, ref uint[] ErrorCode, ref ulong[] TickCount)
		{
			int ret = CanReceive(Id, ChannelNo, ref MessageNum, MessageType, CanId, DataLength, Data, ErrorCode, TickCount);
			return ret;
		}
		public int GetChannelStatus(short Id, ushort ChannelNo, out ushort ChannelStatus, out ushort TxErrorCount, out ushort RxErrorCount)
		{
			ChannelStatus = 0;
			TxErrorCount = 0;
			RxErrorCount = 0;
			int ret = CanGetChannelStatus(Id, ChannelNo, ref ChannelStatus, ref TxErrorCount, ref RxErrorCount);
			return ret;
		}

		//----------------------------------------
		// Event function
		//----------------------------------------
		unsafe public int NotifyEvent(short Id, ushort ChannelNo, ushort EventType, IntPtr CallBackProc, void *Param)
		{
			int ret = CanNotifyEvent(Id, ChannelNo, EventType, CallBackProc, Param);
			return ret;
		}
		public int StopNotifyEvent(short Id, ushort ChannelNo, ushort EventType)
		{
			int ret = CanStopNotifyEvent(Id, ChannelNo, EventType);
			return ret;
		}
	}
}
