#!/usr/bin/env python
# -*- encoding: utf-8 -*-
'''
@文件    :canConnect.py
@时间    :2021/12/09 13:47:58
@作者    :None
@版本    :1.0
@说明    :CAN连接驱动
'''


from ctypes.util import find_library
from sys import platform
import ctypes
from ctypes import c_ubyte, c_uint, c_ushort, c_char
from utils.log_signal import LogSignal
from utils.resource import resource_path, resource_path_extend

if platform == "win64":
    zlg_can_dll = resource_path("config\\ControlCAN.dll")
    ZLGCAN = ctypes.windll.LoadLibrary(zlg_can_dll)
    pcan_dll = resource_path("config\\PCANBasic.dll")
    PCAN = ctypes.windll.LoadLibrary(pcan_dll)
elif platform == "win32":
    zlg_can_dll = resource_path("config\\ControlCAN.dll")
    ZLGCAN = ctypes.windll.LoadLibrary(zlg_can_dll)
    pcan_dll = resource_path("config\\PCANBasic.dll")
    PCAN = ctypes.windll.LoadLibrary(pcan_dll)
elif platform == "linux":
    zlg_can_dll = resource_path("config/linux/libusbcan.so")
    ZLGCAN = ctypes.cdll.LoadLibrary(zlg_can_dll)
else:
    ZLGCAN = ctypes.cdll.LoadLibrary(find_library("libPCBUSB.0.12.1.dylib"))
    pcan_dll = resource_path("config/libPCBUSB.0.12.1.dylib")
    PCAN = ctypes.cdll.LoadLibrary(pcan_dll)

ubyte_array = c_ubyte * 8
ubyte_3array = c_ubyte * 3

# can type
CANTYPE = {
    'USBCAN-I': 3,
    'USBCAN-II': 4,
}

# can mode
NORMAL_MODE = 0
LISTEN_MODE = 1

# filter type
SINGLE_FILTER = 0
DOUBLE_FILTER = 1

# status
STATUS_OK = 1

# sendtype
SEND_NORMAL = 0
SEND_SINGLE = 1
SELF_SEND_RECV = 2
SELF_SEND_RECV_SINGLE = 3


class VCI_INIT_CONFIG(ctypes.Structure):
    _fields_ = [("AccCode", c_uint),  # 验收码。SJA1000的帧过滤验收码。对经过屏蔽码过滤为“有关位”进行匹配，全部匹配成功后，此帧可以被接收。
                # 屏蔽码。SJA1000的帧过滤屏蔽码。对接收的CAN帧ID进行过滤，对应位为0的是“有关位”，对应位为1的是“无关位”。屏蔽码推荐设置为0xFFFFFFFF，即全部接收。
                ("AccMask", c_uint),
                # 保留
                ("Reserved", c_uint),
                # 滤波方式
                ("Filter", c_ubyte),
                # 波特率定时器 0
                ("Timing0", c_ubyte),
                # 波特率定时器 1
                ("Timing1", c_ubyte),
                # 模式。=0表示正常模式（相当于正常节点），=1表示只听模式（只接收，不影响总线），=2表示自发自收模式（环回模式）。
                ("Mode", c_ubyte)
                ]


# VCI_CAN_OBJ结构体是CAN帧结构体，即1个结构体表示一个帧的数据结构。在发送函数VCI_Transmit和接收函数VCI_Receive中，被用来传送CAN信息帧。
class VCI_CAN_OBJ(ctypes.Structure):
    _fields_ = [("ID", c_uint),  # 帧ID。32位变量，数据格式为靠右对齐
                # 设备接收到某一帧的时间标识。时间标示从CAN卡上电开始计时，计时单位为0.1ms。
                ("TimeStamp", c_uint),
                # 是否使用时间标识，为1时TimeStamp有效，TimeFlag和TimeStamp只在此帧为接收帧时有意义。
                ("TimeFlag", c_ubyte),
                # 发送帧类型。=0时为正常发送（发送失败会自动重发，重发时间为4秒，4秒内没有发出则取消）；=1时为单次发送（只发送一次，发送失败不会自动重发，总线只产生一帧数据）；其它值无效。
                ("SendType", c_ubyte),
                # 是否是远程帧。=0时为为数据帧，=1时为远程帧（数据段空）。
                ("RemoteFlag", c_ubyte),
                # 是否是扩展帧。=0时为标准帧（11位ID），=1时为扩展帧（29位ID）。
                ("ExternFlag", c_ubyte),
                # 数据长度 DLC (<=8)，即CAN帧Data有几个字节。约束了后面Data[8]中的有效字节
                ("DataLen", c_ubyte),
                ("Data", c_ubyte * 8),
                # CAN帧的数据。由于CAN规定了最大是8个字节，所以这里预留了8个字节的空间，受DataLen约束。如DataLen定义为3，即Data[0]、Data[1]、Data[2]是有效的
                ("Reserved", c_ubyte * 3)  # 系统保留
                ]


class PVCI_ERR_INFO(ctypes.Structure):
    _fields_ = [("ErrorCode", c_uint),
                ("PassiveErrData", c_ubyte * 3),
                ("ArLostErrData", c_ubyte)
                ]


baudRateConfig = {
    '5Kbps': {'time0': 0xBF, 'time1': 0xFF},
    '10Kbps': {'time0': 0x31, 'time1': 0x1C},
    '20Kbps': {'time0': 0x18, 'time1': 0x1C},
    '40Kbps': {'time0': 0x87, 'time1': 0xFF},
    '50Kbps': {'time0': 0x09, 'time1': 0x1C},
    '80Kbps': {'time0': 0x83, 'time1': 0xFF},
    '100Kbps': {'time0': 0x04, 'time1': 0x1C},
    '125Kbps': {'time0': 0x03, 'time1': 0x1C},
    '200Kbps': {'time0': 0x81, 'time1': 0xFA},
    '250Kbps': {'time0': 0x01, 'time1': 0x1C},
    '400Kbps': {'time0': 0x80, 'time1': 0xFA},
    '500Kbps': {'time0': 0x00, 'time1': 0x1C},
    '666Kbps': {'time0': 0x80, 'time1': 0xB6},
    '800Kbps': {'time0': 0x00, 'time1': 0x16},
    '1000Kbps': {'time0': 0x00, 'time1': 0x14},
}

# PCAN
#///////////////////////////////////////////////////////////
# Type definitions
#///////////////////////////////////////////////////////////

TPCANHandle                   = c_ushort    # Represents a PCAN hardware channel handle
TPCANStatus                   = int         # Represents a PCAN status/error code
TPCANParameter                = c_ubyte     # Represents a PCAN parameter to be read or set
TPCANDevice                   = c_ubyte     # Represents a PCAN device
TPCANMessageType              = c_ubyte     # Represents the type of a PCAN message
TPCANType                     = c_ubyte     # Represents the type of PCAN hardware to be initialized
TPCANMode                     = c_ubyte     # Represents a PCAN filter mode
TPCANBaudrate                 = c_ushort    # Represents a PCAN Baud rate register value

#///////////////////////////////////////////////////////////
# Value definitions
#///////////////////////////////////////////////////////////

# Currently defined and supported PCAN channels
#
PCAN_NONEBUS                  = TPCANHandle(0x00)  # Undefined/default value for a PCAN bus
                             
PCAN_ISABUS1                  = TPCANHandle(0x21)  # PCAN-ISA interface, channel 1
PCAN_ISABUS2                  = TPCANHandle(0x22)  # PCAN-ISA interface, channel 2
PCAN_ISABUS3                  = TPCANHandle(0x23)  # PCAN-ISA interface, channel 3
PCAN_ISABUS4                  = TPCANHandle(0x24)  # PCAN-ISA interface, channel 4
PCAN_ISABUS5                  = TPCANHandle(0x25)  # PCAN-ISA interface, channel 5
PCAN_ISABUS6                  = TPCANHandle(0x26)  # PCAN-ISA interface, channel 6
PCAN_ISABUS7                  = TPCANHandle(0x27)  # PCAN-ISA interface, channel 7
PCAN_ISABUS8                  = TPCANHandle(0x28)  # PCAN-ISA interface, channel 8
                             
PCAN_DNGBUS1                  = TPCANHandle(0x31)  # PCAN-Dongle/LPT interface, channel 1
                             
PCAN_PCIBUS1                  = TPCANHandle(0x41)  # PCAN-PCI interface, channel 1
PCAN_PCIBUS2                  = TPCANHandle(0x42)  # PCAN-PCI interface, channel 2
PCAN_PCIBUS3                  = TPCANHandle(0x43)  # PCAN-PCI interface, channel 3
PCAN_PCIBUS4                  = TPCANHandle(0x44)  # PCAN-PCI interface, channel 4
PCAN_PCIBUS5                  = TPCANHandle(0x45)  # PCAN-PCI interface, channel 5
PCAN_PCIBUS6                  = TPCANHandle(0x46)  # PCAN-PCI interface, channel 6
PCAN_PCIBUS7                  = TPCANHandle(0x47)  # PCAN-PCI interface, channel 7
PCAN_PCIBUS8                  = TPCANHandle(0x48)  # PCAN-PCI interface, channel 8
PCAN_PCIBUS9                  = TPCANHandle(0x409)  # PCAN-PCI interface, channel 9
PCAN_PCIBUS10                 = TPCANHandle(0x40A)  # PCAN-PCI interface, channel 10
PCAN_PCIBUS11                 = TPCANHandle(0x40B)  # PCAN-PCI interface, channel 11
PCAN_PCIBUS12                 = TPCANHandle(0x40C)  # PCAN-PCI interface, channel 12
PCAN_PCIBUS13                 = TPCANHandle(0x40D)  # PCAN-PCI interface, channel 13
PCAN_PCIBUS14                 = TPCANHandle(0x40E)  # PCAN-PCI interface, channel 14
PCAN_PCIBUS15                 = TPCANHandle(0x40F)  # PCAN-PCI interface, channel 15
PCAN_PCIBUS16                 = TPCANHandle(0x410)  # PCAN-PCI interface, channel 16
                             
PCAN_USBBUS1                  = TPCANHandle(0x51)  # PCAN-USB interface, channel 1
PCAN_USBBUS2                  = TPCANHandle(0x52)  # PCAN-USB interface, channel 2
PCAN_USBBUS3                  = TPCANHandle(0x53)  # PCAN-USB interface, channel 3
PCAN_USBBUS4                  = TPCANHandle(0x54)  # PCAN-USB interface, channel 4
PCAN_USBBUS5                  = TPCANHandle(0x55)  # PCAN-USB interface, channel 5
PCAN_USBBUS6                  = TPCANHandle(0x56)  # PCAN-USB interface, channel 6
PCAN_USBBUS7                  = TPCANHandle(0x57)  # PCAN-USB interface, channel 7
PCAN_USBBUS8                  = TPCANHandle(0x58)  # PCAN-USB interface, channel 8
PCAN_USBBUS9                  = TPCANHandle(0x509)  # PCAN-USB interface, channel 9
PCAN_USBBUS10                 = TPCANHandle(0x50A)  # PCAN-USB interface, channel 10
PCAN_USBBUS11                 = TPCANHandle(0x50B)  # PCAN-USB interface, channel 11
PCAN_USBBUS12                 = TPCANHandle(0x50C)  # PCAN-USB interface, channel 12
PCAN_USBBUS13                 = TPCANHandle(0x50D)  # PCAN-USB interface, channel 13
PCAN_USBBUS14                 = TPCANHandle(0x50E)  # PCAN-USB interface, channel 14
PCAN_USBBUS15                 = TPCANHandle(0x50F)  # PCAN-USB interface, channel 15
PCAN_USBBUS16                 = TPCANHandle(0x510)  # PCAN-USB interface, channel 16
                             
PCAN_PCCBUS1                  = TPCANHandle(0x61)  # PCAN-PC Card interface, channel 1
PCAN_PCCBUS2                  = TPCANHandle(0x62)  # PCAN-PC Card interface, channel 2

PCAN_LANBUS1                  = TPCANHandle(0x801)  # PCAN-LAN interface, channel 1
PCAN_LANBUS2                  = TPCANHandle(0x802)  # PCAN-LAN interface, channel 2
PCAN_LANBUS3                  = TPCANHandle(0x803)  # PCAN-LAN interface, channel 3
PCAN_LANBUS4                  = TPCANHandle(0x804)  # PCAN-LAN interface, channel 4
PCAN_LANBUS5                  = TPCANHandle(0x805)  # PCAN-LAN interface, channel 5
PCAN_LANBUS6                  = TPCANHandle(0x806)  # PCAN-LAN interface, channel 6
PCAN_LANBUS7                  = TPCANHandle(0x807)  # PCAN-LAN interface, channel 7
PCAN_LANBUS8                  = TPCANHandle(0x808)  # PCAN-LAN interface, channel 8
PCAN_LANBUS9                  = TPCANHandle(0x809)  # PCAN-LAN interface, channel 9
PCAN_LANBUS10                 = TPCANHandle(0x80A)  # PCAN-LAN interface, channel 10
PCAN_LANBUS11                 = TPCANHandle(0x80B)  # PCAN-LAN interface, channel 11
PCAN_LANBUS12                 = TPCANHandle(0x80C)  # PCAN-LAN interface, channel 12
PCAN_LANBUS13                 = TPCANHandle(0x80D)  # PCAN-LAN interface, channel 13
PCAN_LANBUS14                 = TPCANHandle(0x80E)  # PCAN-LAN interface, channel 14
PCAN_LANBUS15                 = TPCANHandle(0x80F)  # PCAN-LAN interface, channel 15
PCAN_LANBUS16                 = TPCANHandle(0x810)  # PCAN-LAN interface, channel 16

# Represent the PCAN error and status codes 
#
PCAN_ERROR_OK                 = TPCANStatus(0x00000)  # No error 
PCAN_ERROR_XMTFULL            = TPCANStatus(0x00001)  # Transmit buffer in CAN controller is full
PCAN_ERROR_OVERRUN            = TPCANStatus(0x00002)  # CAN controller was read too late
PCAN_ERROR_BUSLIGHT           = TPCANStatus(0x00004)  # Bus error: an error counter reached the 'light' limit
PCAN_ERROR_BUSHEAVY           = TPCANStatus(0x00008)  # Bus error: an error counter reached the 'heavy' limit
PCAN_ERROR_BUSWARNING         = TPCANStatus(PCAN_ERROR_BUSHEAVY) # Bus error: an error counter reached the 'warning' limit
PCAN_ERROR_BUSPASSIVE         = TPCANStatus(0x40000)  # Bus error: the CAN controller is error passive
PCAN_ERROR_BUSOFF             = TPCANStatus(0x00010)  # Bus error: the CAN controller is in bus-off state
PCAN_ERROR_ANYBUSERR          = TPCANStatus(PCAN_ERROR_BUSWARNING | PCAN_ERROR_BUSLIGHT | PCAN_ERROR_BUSHEAVY | PCAN_ERROR_BUSOFF | PCAN_ERROR_BUSPASSIVE) # Mask for all bus errors
PCAN_ERROR_QRCVEMPTY          = TPCANStatus(0x00020)  # Receive queue is empty
PCAN_ERROR_QOVERRUN           = TPCANStatus(0x00040)  # Receive queue was read too late
PCAN_ERROR_QXMTFULL           = TPCANStatus(0x00080)  # Transmit queue is full
PCAN_ERROR_REGTEST            = TPCANStatus(0x00100)  # Test of the CAN controller hardware registers failed (no hardware found)
PCAN_ERROR_NODRIVER           = TPCANStatus(0x00200)  # Driver not loaded
PCAN_ERROR_HWINUSE            = TPCANStatus(0x00400)  # Hardware already in use by a Net
PCAN_ERROR_NETINUSE           = TPCANStatus(0x00800)  # A Client is already connected to the Net
PCAN_ERROR_ILLHW              = TPCANStatus(0x01400)  # Hardware handle is invalid
PCAN_ERROR_ILLNET             = TPCANStatus(0x01800)  # Net handle is invalid
PCAN_ERROR_ILLCLIENT          = TPCANStatus(0x01C00)  # Client handle is invalid
PCAN_ERROR_ILLHANDLE          = TPCANStatus(PCAN_ERROR_ILLHW | PCAN_ERROR_ILLNET | PCAN_ERROR_ILLCLIENT) # Mask for all handle errors
PCAN_ERROR_RESOURCE           = TPCANStatus(0x02000)  # Resource (FIFO, Client, timeout) cannot be created
PCAN_ERROR_ILLPARAMTYPE       = TPCANStatus(0x04000)  # Invalid parameter
PCAN_ERROR_ILLPARAMVAL        = TPCANStatus(0x08000)  # Invalid parameter value
PCAN_ERROR_UNKNOWN            = TPCANStatus(0x10000)  # Unknown error
PCAN_ERROR_ILLDATA            = TPCANStatus(0x20000)  # Invalid data, function, or action
PCAN_ERROR_ILLMODE            = TPCANStatus(0x80000)  # Driver object state is wrong for the attempted operation
PCAN_ERROR_CAUTION            = TPCANStatus(0x2000000)# An operation was successfully carried out, however, irregularities were registered
PCAN_ERROR_INITIALIZE         = TPCANStatus(0x4000000)# Channel is not initialized [Value was changed from 0x40000 to 0x4000000]
PCAN_ERROR_ILLOPERATION       = TPCANStatus(0x8000000)# Invalid operation [Value was changed from 0x80000 to 0x8000000]

# PCAN devices
#
PCAN_NONE                     = TPCANDevice(0x00)  # Undefined, unknown or not selected PCAN device value
PCAN_PEAKCAN                  = TPCANDevice(0x01)  # PCAN Non-PnP devices. NOT USED WITHIN PCAN-Basic API
PCAN_ISA                      = TPCANDevice(0x02)  # PCAN-ISA, PCAN-PC/104, and PCAN-PC/104-Plus
PCAN_DNG                      = TPCANDevice(0x03)  # PCAN-Dongle
PCAN_PCI                      = TPCANDevice(0x04)  # PCAN-PCI, PCAN-cPCI, PCAN-miniPCI, and PCAN-PCI Express
PCAN_USB                      = TPCANDevice(0x05)  # PCAN-USB and PCAN-USB Pro
PCAN_PCC                      = TPCANDevice(0x06)  # PCAN-PC Card
PCAN_VIRTUAL                  = TPCANDevice(0x07)  # PCAN Virtual hardware. NOT USED WITHIN PCAN-Basic API
PCAN_LAN                      = TPCANDevice(0x08)  # PCAN Gateway devices

# PCAN parameters
#
PCAN_DEVICE_ID                 = TPCANParameter(0x01)  # Device identifier parameter
PCAN_5VOLTS_POWER              = TPCANParameter(0x02)  # 5-Volt power parameter
PCAN_RECEIVE_EVENT             = TPCANParameter(0x03)  # PCAN receive event handler parameter
PCAN_MESSAGE_FILTER            = TPCANParameter(0x04)  # PCAN message filter parameter
PCAN_API_VERSION               = TPCANParameter(0x05)  # PCAN-Basic API version parameter
PCAN_CHANNEL_VERSION           = TPCANParameter(0x06)  # PCAN device channel version parameter
PCAN_BUSOFF_AUTORESET          = TPCANParameter(0x07)  # PCAN Reset-On-Busoff parameter
PCAN_LISTEN_ONLY               = TPCANParameter(0x08)  # PCAN Listen-Only parameter
PCAN_LOG_LOCATION              = TPCANParameter(0x09)  # Directory path for log files
PCAN_LOG_STATUS                = TPCANParameter(0x0A)  # Debug-Log activation status
PCAN_LOG_CONFIGURE             = TPCANParameter(0x0B)  # Configuration of the debugged information (LOG_FUNCTION_***)
PCAN_LOG_TEXT                  = TPCANParameter(0x0C)  # Custom insertion of text into the log file
PCAN_CHANNEL_CONDITION         = TPCANParameter(0x0D)  # Availability status of a PCAN-Channel
PCAN_HARDWARE_NAME             = TPCANParameter(0x0E)  # PCAN hardware name parameter
PCAN_RECEIVE_STATUS            = TPCANParameter(0x0F)  # Message reception status of a PCAN-Channel
PCAN_CONTROLLER_NUMBER         = TPCANParameter(0x10)  # CAN-Controller number of a PCAN-Channel
PCAN_TRACE_LOCATION            = TPCANParameter(0x11)  # Directory path for PCAN trace files
PCAN_TRACE_STATUS              = TPCANParameter(0x12)  # CAN tracing activation status
PCAN_TRACE_SIZE                = TPCANParameter(0x13)  # Configuration of the maximum file size of a CAN trace
PCAN_TRACE_CONFIGURE           = TPCANParameter(0x14)  # Configuration of the trace file storing mode (TRACE_FILE_***)
PCAN_CHANNEL_IDENTIFYING       = TPCANParameter(0x15)  # Physical identification of a USB based PCAN-Channel by blinking its associated LED
PCAN_CHANNEL_FEATURES          = TPCANParameter(0x16)  # Capabilities of a PCAN device (FEATURE_***)
PCAN_BITRATE_ADAPTING          = TPCANParameter(0x17)  # Using of an existing bit rate (PCAN-View connected to a channel)
PCAN_BITRATE_INFO              = TPCANParameter(0x18)  # Configured bit rate as Btr0Btr1 value
PCAN_BITRATE_INFO_FD           = TPCANParameter(0x19)  # Configured bit rate as TPCANBitrateFD string
PCAN_BUSSPEED_NOMINAL          = TPCANParameter(0x1A)  # Configured nominal CAN Bus speed as Bits per seconds
PCAN_BUSSPEED_DATA             = TPCANParameter(0x1B)  # Configured CAN data speed as Bits per seconds
PCAN_IP_ADDRESS                = TPCANParameter(0x1C)  # Remote address of a LAN channel as string in IPv4 format
PCAN_LAN_SERVICE_STATUS        = TPCANParameter(0x1D)  # Status of the Virtual PCAN-Gateway Service
PCAN_ALLOW_STATUS_FRAMES       = TPCANParameter(0x1E)  # Status messages reception status within a PCAN-Channel
PCAN_ALLOW_RTR_FRAMES          = TPCANParameter(0x1F)  # RTR messages reception status within a PCAN-Channel
PCAN_ALLOW_ERROR_FRAMES        = TPCANParameter(0x20)  # Error messages reception status within a PCAN-Channel
PCAN_INTERFRAME_DELAY          = TPCANParameter(0x21)  # Delay, in microseconds, between sending frames
PCAN_ACCEPTANCE_FILTER_11BIT   = TPCANParameter(0x22)  # Filter over code and mask patterns for 11-Bit messages
PCAN_ACCEPTANCE_FILTER_29BIT   = TPCANParameter(0x23)  # Filter over code and mask patterns for 29-Bit messages
PCAN_IO_DIGITAL_CONFIGURATION  = TPCANParameter(0x24)  # Output mode of 32 digital I/O pin of a PCAN-USB Chip. 1: Output-Active 0 : Output Inactive
PCAN_IO_DIGITAL_VALUE          = TPCANParameter(0x25)  # Value assigned to a 32 digital I/O pins of a PCAN-USB Chip
PCAN_IO_DIGITAL_SET            = TPCANParameter(0x26)  # Value assigned to a 32 digital I/O pins of a PCAN-USB Chip - Multiple digital I/O pins to 1 = High
PCAN_IO_DIGITAL_CLEAR          = TPCANParameter(0x27)  # Clear multiple digital I/O pins to 0
PCAN_IO_ANALOG_VALUE           = TPCANParameter(0x28)  # Get value of a single analog input pin
PCAN_FIRMWARE_VERSION          = TPCANParameter(0x29)  # Get the version of the firmware used by the device associated with a PCAN-Channel
PCAN_ATTACHED_CHANNELS_COUNT   = TPCANParameter(0x2A)  # Get the amount of PCAN channels attached to a system
PCAN_ATTACHED_CHANNELS         = TPCANParameter(0x2B)  # Get information about PCAN channels attached to a system
PCAN_ALLOW_ECHO_FRAMES         = TPCANParameter(0x2C)  # Echo messages reception status within a PCAN-Channel
PCAN_DEVICE_PART_NUMBER        = TPCANParameter(0x2D)  # Get the part number associated to a device

# DEPRECATED parameters
#
PCAN_DEVICE_NUMBER             = PCAN_DEVICE_ID        # DEPRECATED. Use PCAN_DEVICE_ID instead

# PCAN parameter values
#
PCAN_PARAMETER_OFF            = int(0x00)  # The PCAN parameter is not set (inactive)
PCAN_PARAMETER_ON             = int(0x01)  # The PCAN parameter is set (active)
PCAN_FILTER_CLOSE             = int(0x00)  # The PCAN filter is closed. No messages will be received
PCAN_FILTER_OPEN              = int(0x01)  # The PCAN filter is fully opened. All messages will be received
PCAN_FILTER_CUSTOM            = int(0x02)  # The PCAN filter is custom configured. Only registered messages will be received
PCAN_CHANNEL_UNAVAILABLE      = int(0x00)  # The PCAN-Channel handle is illegal, or its associated hardware is not available
PCAN_CHANNEL_AVAILABLE        = int(0x01)  # The PCAN-Channel handle is available to be connected (PnP Hardware: it means furthermore that the hardware is plugged-in)
PCAN_CHANNEL_OCCUPIED         = int(0x02)  # The PCAN-Channel handle is valid, and is already being used
PCAN_CHANNEL_PCANVIEW         = PCAN_CHANNEL_AVAILABLE | PCAN_CHANNEL_OCCUPIED  # The PCAN-Channel handle is already being used by a PCAN-View application, but is available to connect
                              
LOG_FUNCTION_DEFAULT          = int(0x00)   # Logs system exceptions / errors
LOG_FUNCTION_ENTRY            = int(0x01)   # Logs the entries to the PCAN-Basic API functions 
LOG_FUNCTION_PARAMETERS       = int(0x02)   # Logs the parameters passed to the PCAN-Basic API functions 
LOG_FUNCTION_LEAVE            = int(0x04)   # Logs the exits from the PCAN-Basic API functions 
LOG_FUNCTION_WRITE            = int(0x08)   # Logs the CAN messages passed to the CAN_Write function
LOG_FUNCTION_READ             = int(0x10)   # Logs the CAN messages received within the CAN_Read function
LOG_FUNCTION_ALL              = int(0xFFFF) # Logs all possible information within the PCAN-Basic API functions
                              
TRACE_FILE_SINGLE             = int(0x00)  # A single file is written until it size reaches PAN_TRACE_SIZE
TRACE_FILE_SEGMENTED          = int(0x01)  # Traced data is distributed in several files with size PAN_TRACE_SIZE
TRACE_FILE_DATE               = int(0x02)  # Includes the date into the name of the trace file
TRACE_FILE_TIME               = int(0x04)  # Includes the start time into the name of the trace file
TRACE_FILE_OVERWRITE          = int(0x80)  # Causes the overwriting of available traces (same name)
TRACE_FILE_DATA_LENGTH        = int(0x100) # Causes using the data length column ('l') instead of the DLC column ('L') in the trace file
                              
FEATURE_FD_CAPABLE            = int(0x01)  # Device supports flexible data-rate (CAN-FD)
FEATURE_DELAY_CAPABLE         = int(0x02)  # Device supports a delay between sending frames (FPGA based USB devices)
FEATURE_IO_CAPABLE            = int(0x04)  # Device supports I/O functionality for electronic circuits (USB-Chip devices)
                              
SERVICE_STATUS_STOPPED        = int(0x01)  # The service is not running
SERVICE_STATUS_RUNNING        = int(0x04)  # The service is running

# Other constants
#
MAX_LENGTH_HARDWARE_NAME      = int(33)    # Maximum length of the name of a device: 32 characters + terminator
MAX_LENGTH_VERSION_STRING     = int(256)   # Maximum length of a version string: 255 characters + terminator
                              
# PCAN message types          
#                             
PCAN_MESSAGE_STANDARD         = TPCANMessageType(0x00)  # The PCAN message is a CAN Standard Frame (11-bit identifier)
PCAN_MESSAGE_RTR              = TPCANMessageType(0x01)  # The PCAN message is a CAN Remote-Transfer-Request Frame
PCAN_MESSAGE_EXTENDED         = TPCANMessageType(0x02)  # The PCAN message is a CAN Extended Frame (29-bit identifier)
PCAN_MESSAGE_FD               = TPCANMessageType(0x04)  # The PCAN message represents a FD frame in terms of CiA Specs
PCAN_MESSAGE_BRS              = TPCANMessageType(0x08)  # The PCAN message represents a FD bit rate switch (CAN data at a higher bit rate)
PCAN_MESSAGE_ESI              = TPCANMessageType(0x10)  # The PCAN message represents a FD error state indicator(CAN FD transmitter was error active)
PCAN_MESSAGE_ECHO             = TPCANMessageType(0x20)  # The PCAN message represents an echo CAN Frame
PCAN_MESSAGE_ERRFRAME         = TPCANMessageType(0x40)  # The PCAN message represents an error frame
PCAN_MESSAGE_STATUS           = TPCANMessageType(0x80)  # The PCAN message represents a PCAN status message

# LookUp Parameters
#
LOOKUP_DEVICE_TYPE            = b"devicetype"           # Lookup channel by Device type (see PCAN devices e.g. PCAN_USB)
LOOKUP_DEVICE_ID              = b"deviceid"             # Lookup channel by device id
LOOKUP_CONTROLLER_NUMBER      = b"controllernumber"     # Lookup channel by CAN controller 0-based index
LOOKUP_IP_ADDRESS             = b"ipaddress"            # Lookup channel by IP address (LAN channels only)

# Frame Type / Initialization Mode
#
PCAN_MODE_STANDARD            = PCAN_MESSAGE_STANDARD  
PCAN_MODE_EXTENDED            = PCAN_MESSAGE_EXTENDED  

# Baud rate codes = BTR0/BTR1 register values for the CAN controller.
# You can define your own Baud rate with the BTROBTR1 register.
# Take a look at www.peak-system.com for our free software "BAUDTOOL" 
# to calculate the BTROBTR1 register for every bit rate and sample point.
#
PCAN_BAUD_1M                  = TPCANBaudrate(0x0014) #   1 MBit/s
PCAN_BAUD_800K                = TPCANBaudrate(0x0016) # 800 kBit/s
PCAN_BAUD_500K                = TPCANBaudrate(0x001C) # 500 kBit/s
PCAN_BAUD_250K                = TPCANBaudrate(0x011C) # 250 kBit/s
PCAN_BAUD_125K                = TPCANBaudrate(0x031C) # 125 kBit/s
PCAN_BAUD_100K                = TPCANBaudrate(0x432F) # 100 kBit/s
PCAN_BAUD_95K                 = TPCANBaudrate(0xC34E) #  95,238 kBit/s
PCAN_BAUD_83K                 = TPCANBaudrate(0x852B) #  83,333 kBit/s
PCAN_BAUD_50K                 = TPCANBaudrate(0x472F) #  50 kBit/s
PCAN_BAUD_47K                 = TPCANBaudrate(0x1414) #  47,619 kBit/s
PCAN_BAUD_33K                 = TPCANBaudrate(0x8B2F) #  33,333 kBit/s
PCAN_BAUD_20K                 = TPCANBaudrate(0x532F) #  20 kBit/s
PCAN_BAUD_10K                 = TPCANBaudrate(0x672F) #  10 kBit/s
PCAN_BAUD_5K                  = TPCANBaudrate(0x7F7F) #   5 kBit/s

# Supported Non-PnP Hardware types
#
PZLGCAN_ISA                 = TPCANType(0x01)  # PCAN-ISA 82C200
PZLGCAN_ISA_SJA             = TPCANType(0x09)  # PCAN-ISA SJA1000
PZLGCAN_ISA_PHYTEC          = TPCANType(0x04)  # PHYTEC ISA 
PZLGCAN_DNG                 = TPCANType(0x02)  # PCAN-Dongle 82C200
PZLGCAN_DNG_EPP             = TPCANType(0x03)  # PCAN-Dongle EPP 82C200
PZLGCAN_DNG_SJA             = TPCANType(0x05)  # PCAN-Dongle SJA1000
PZLGCAN_DNG_SJA_EPP         = TPCANType(0x06)  # PCAN-Dongle EPP SJA1000
 
# Represents a PCAN message
#
class TPCANMsg (ctypes.Structure):
    """
    Represents a PCAN message
    """
    _fields_ = [ ("ID",      c_uint),           # 11/29-bit message identifier
                 ("MSGTYPE", TPCANMessageType), # Type of the message
                 ("LEN",     c_ubyte),          # Data Length Code of the message (0..8)
                 ("DATA",    c_ubyte * 8) ]     # Data of the message (DATA[0]..DATA[7])

# Represents a timestamp of a received PCAN message
# Total Microseconds = micros + 1000 * millis + 0x100000000 * 1000 * millis_overflow
#
class TPCANTimestamp (ctypes.Structure):
    """
    Represents a timestamp of a received PCAN message
    Total Microseconds = micros + 1000 * millis + 0x100000000 * 1000 * millis_overflow
    """
    _fields_ = [ ("millis",          c_uint),    # Base-value: milliseconds: 0.. 2^32-1
                 ("millis_overflow", c_ushort),  # Roll-arounds of millis
                 ("micros",          c_ushort) ] # Microseconds: 0..999


class MessageDeal:
    def __init__(self):
        self.can_connect = 0

    def set_can_board(self, can_type, canIndex, canChannel, canBaudrate):
        if can_type == 0:
            self.canType = CANTYPE['USBCAN-II']
            self.can_connect = 0
        else:
            self.canType = PCAN_USBBUS1
            self.can_connect = 1

        self.canIndex = canIndex
        self.canChannel = canChannel
        self.canBaudrate = canBaudrate

    def open_device(self):
        if self.can_connect:
            if self.canBaudrate == "125Kbps":
                ret = PCAN.CAN_Initialize(self.canType, PCAN_BAUD_125K ,0,0,0)
            elif self.canBaudrate == "250Kbps":
                ret = PCAN.CAN_Initialize(self.canType, PCAN_BAUD_250K ,0,0,0)
            else:
                ret = PCAN.CAN_Initialize(self.canType, PCAN_BAUD_500K ,0,0,0)
            if TPCANStatus(ret) != PCAN_ERROR_OK:
                return False
            return True
        else:
            if (STATUS_OK != ZLGCAN.VCI_OpenDevice(self.canType, self.canChannel, self.canChannel)):
                return False 
            _vci_initconfig = VCI_INIT_CONFIG(0x00000000, 0xFFFFFFFF, 0, DOUBLE_FILTER,
                                          baudRateConfig[self.canBaudrate]['time0'],
                                          baudRateConfig[self.canBaudrate]['time1'],
                                          NORMAL_MODE)
            if (STATUS_OK != ZLGCAN.VCI_InitCAN(self.canType, self.canIndex, self.canChannel, ctypes.byref(_vci_initconfig))):
                return False

            if (STATUS_OK != ZLGCAN.VCI_StartCAN(self.canType, self.canIndex, self.canChannel)):
                return False
            
            return True

    def get_undeal_number(self):
        if self.can_connect:
            return 1
        else:
            return ZLGCAN.VCI_GetReceiveNum(self.canType, self.canIndex, self.canChannel)

    def receive(self, number=1):
        if self.can_connect:
            msg = TPCANMsg()
            timestamp = TPCANTimestamp()
            res = PCAN.CAN_Read(self.canType,ctypes.byref(msg),ctypes.byref(timestamp))
            if (res != PCAN_ERROR_QRCVEMPTY):
                return 1, msg.ID, msg.DATA
            else:
                return 0, 0, 0
        else:
            objs = (VCI_CAN_OBJ * number)()
            ret = ZLGCAN.VCI_Receive(self.canType, self.canIndex, self.canChannel, ctypes.byref(objs), number, 10)
            if (ret > 0):
                for i in range(0, ret):
                    return 1, objs[i].ID, objs[i].Data
            else:
                return 0, 0, 0      


    def send(self, ID, data, data_len=8):
        if self.can_connect:
            msg = TPCANMsg()
            msg.ID = ID
            msg.LEN = data_len
            if (ID > 0x7FF):
                msg.MSGTYPE = PCAN_MESSAGE_EXTENDED
            else:
                msg.MSGTYPE = PCAN_MESSAGE_STANDARD
            if len(data) < 8:
                data += (8 - len(data)) * [0]

            msg.DATA = (c_ubyte * 8)(data[0], data[1], data[2], data[3], data[4], data[5], data[6], data[7])
            send_status = PCAN.CAN_Write(self.canType,ctypes.byref(msg))
            if (TPCANStatus(send_status) != PCAN_ERROR_OK):
                return False
            else:
                return True
        else:
            vci_can_obj = VCI_CAN_OBJ()
            vci_can_obj.ID = ID
            vci_can_obj.DataLen = data_len
            vci_can_obj.SendType = SEND_NORMAL
            if (ID > 0x7FF):
                vci_can_obj.ExternFlag = 1
            else:
                vci_can_obj.ExternFlag = 0
            vci_can_obj.RemoteFlag = 0

            if len(data) < 8:
                data += (8 - len(data)) * [0]

            vci_can_obj.Data = (c_ubyte * 8)(data[0], data[1], data[2], data[3], data[4], data[5], data[6], data[7])
            ret = ZLGCAN.VCI_Transmit(self.canType, self.canIndex, self.canChannel, ctypes.byref(vci_can_obj), 1)
            if ret != STATUS_OK:
                return False
            else:
                return True

    def read_err_info(self):
        errInfo = PVCI_ERR_INFO(0, ubyte_3array(0, 0, 0), 0)
        ZLGCAN.VCI_ReadErrInfo(self.canType, self.canIndex, self.canChannel, ctypes.byref(errInfo))
        LogSignal.print_log_signal().log_emit(errInfo.ErrorCode, errInfo.PassiveErrData[0], errInfo.PassiveErrData[1], errInfo.PassiveErrData[2], errInfo.ArLostErrData)

    def close_can(self):
        if self.can_connect:
            PCAN.CAN_Uninitialize(self.canType)
        else:
            ZLGCAN.VCI_ClearBuffer(self.canType, self.canIndex, self.canChannel)
            ZLGCAN.VCI_CloseDevice(self.canType, self.canIndex)
