can.py 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583
  1. #!/usr/bin/env python
  2. # -*- encoding: utf-8 -*-
  3. import csv
  4. import os
  5. from ctypes.util import find_library
  6. from sys import platform
  7. import ctypes
  8. from ctypes import c_ubyte, c_uint, c_ushort, c_char
  9. from utils.qt import QDateTime
  10. from utils.resource import resource_path
  11. if platform == "win64":
  12. zlg_can_dll = resource_path("config\\ControlCAN.dll")
  13. ZLGCAN = ctypes.windll.LoadLibrary(zlg_can_dll)
  14. pcan_dll = resource_path("config\\PCANBasic.dll")
  15. PCAN = ctypes.windll.LoadLibrary(pcan_dll)
  16. elif platform == "win32":
  17. zlg_can_dll = resource_path("config\\ControlCAN.dll")
  18. ZLGCAN = ctypes.windll.LoadLibrary(zlg_can_dll)
  19. pcan_dll = resource_path("config\\PCANBasic.dll")
  20. PCAN = ctypes.windll.LoadLibrary(pcan_dll)
  21. elif platform == "linux":
  22. zlg_can_dll = resource_path("config/linux/libusbcan.so")
  23. ZLGCAN = ctypes.cdll.LoadLibrary(zlg_can_dll)
  24. else:
  25. ZLGCAN = ctypes.cdll.LoadLibrary(find_library("libPCBUSB.0.12.1.dylib"))
  26. pcan_dll = resource_path("config/libPCBUSB.0.12.1.dylib")
  27. PCAN = ctypes.cdll.LoadLibrary(pcan_dll)
  28. ubyte_array = c_ubyte * 8
  29. ubyte_3array = c_ubyte * 3
  30. # can type
  31. CANTYPE = {
  32. 'USBCAN-I': 3,
  33. 'USBCAN-II': 4,
  34. }
  35. # can mode
  36. NORMAL_MODE = 0
  37. LISTEN_MODE = 1
  38. # filter type
  39. SINGLE_FILTER = 0
  40. DOUBLE_FILTER = 1
  41. # status
  42. STATUS_OK = 1
  43. # sendtype
  44. SEND_NORMAL = 0
  45. SEND_SINGLE = 1
  46. SELF_SEND_RECV = 2
  47. SELF_SEND_RECV_SINGLE = 3
  48. class VCI_INIT_CONFIG(ctypes.Structure):
  49. _fields_ = [("AccCode", c_uint), # 验收码。SJA1000的帧过滤验收码。对经过屏蔽码过滤为“有关位”进行匹配,全部匹配成功后,此帧可以被接收。
  50. # 屏蔽码。SJA1000的帧过滤屏蔽码。对接收的CAN帧ID进行过滤,对应位为0的是“有关位”,对应位为1的是“无关位”。屏蔽码推荐设置为0xFFFFFFFF,即全部接收。
  51. ("AccMask", c_uint),
  52. # 保留
  53. ("Reserved", c_uint),
  54. # 滤波方式
  55. ("Filter", c_ubyte),
  56. # 波特率定时器 0
  57. ("Timing0", c_ubyte),
  58. # 波特率定时器 1
  59. ("Timing1", c_ubyte),
  60. # 模式。=0表示正常模式(相当于正常节点),=1表示只听模式(只接收,不影响总线),=2表示自发自收模式(环回模式)。
  61. ("Mode", c_ubyte)
  62. ]
  63. # VCI_CAN_OBJ结构体是CAN帧结构体,即1个结构体表示一个帧的数据结构。在发送函数VCI_Transmit和接收函数VCI_Receive中,被用来传送CAN信息帧。
  64. class VCI_CAN_OBJ(ctypes.Structure):
  65. _fields_ = [("ID", c_uint), # 帧ID。32位变量,数据格式为靠右对齐
  66. # 设备接收到某一帧的时间标识。时间标示从CAN卡上电开始计时,计时单位为0.1ms。
  67. ("TimeStamp", c_uint),
  68. # 是否使用时间标识,为1时TimeStamp有效,TimeFlag和TimeStamp只在此帧为接收帧时有意义。
  69. ("TimeFlag", c_ubyte),
  70. # 发送帧类型。=0时为正常发送(发送失败会自动重发,重发时间为4秒,4秒内没有发出则取消);=1时为单次发送(只发送一次,发送失败不会自动重发,总线只产生一帧数据);其它值无效。
  71. ("SendType", c_ubyte),
  72. # 是否是远程帧。=0时为为数据帧,=1时为远程帧(数据段空)。
  73. ("RemoteFlag", c_ubyte),
  74. # 是否是扩展帧。=0时为标准帧(11位ID),=1时为扩展帧(29位ID)。
  75. ("ExternFlag", c_ubyte),
  76. # 数据长度 DLC (<=8),即CAN帧Data有几个字节。约束了后面Data[8]中的有效字节
  77. ("DataLen", c_ubyte),
  78. ("Data", c_ubyte * 8),
  79. # CAN帧的数据。由于CAN规定了最大是8个字节,所以这里预留了8个字节的空间,受DataLen约束。如DataLen定义为3,即Data[0]、Data[1]、Data[2]是有效的
  80. ("Reserved", c_ubyte * 3) # 系统保留
  81. ]
  82. class PVCI_ERR_INFO(ctypes.Structure):
  83. _fields_ = [("ErrorCode", c_uint),
  84. ("PassiveErrData", c_ubyte * 3),
  85. ("ArLostErrData", c_ubyte)
  86. ]
  87. baudRateConfig = {
  88. '5Kbps': {'time0': 0xBF, 'time1': 0xFF},
  89. '10Kbps': {'time0': 0x31, 'time1': 0x1C},
  90. '20Kbps': {'time0': 0x18, 'time1': 0x1C},
  91. '40Kbps': {'time0': 0x87, 'time1': 0xFF},
  92. '50Kbps': {'time0': 0x09, 'time1': 0x1C},
  93. '80Kbps': {'time0': 0x83, 'time1': 0xFF},
  94. '100Kbps': {'time0': 0x04, 'time1': 0x1C},
  95. '125Kbps': {'time0': 0x03, 'time1': 0x1C},
  96. '200Kbps': {'time0': 0x81, 'time1': 0xFA},
  97. '250Kbps': {'time0': 0x01, 'time1': 0x1C},
  98. '400Kbps': {'time0': 0x80, 'time1': 0xFA},
  99. '500Kbps': {'time0': 0x00, 'time1': 0x1C},
  100. '666Kbps': {'time0': 0x80, 'time1': 0xB6},
  101. '800Kbps': {'time0': 0x00, 'time1': 0x16},
  102. '1000Kbps': {'time0': 0x00, 'time1': 0x14},
  103. }
  104. # PCAN
  105. #///////////////////////////////////////////////////////////
  106. # Type definitions
  107. #///////////////////////////////////////////////////////////
  108. TPCANHandle = c_ushort # Represents a PCAN hardware channel handle
  109. TPCANStatus = int # Represents a PCAN status/error code
  110. TPCANParameter = c_ubyte # Represents a PCAN parameter to be read or set
  111. TPCANDevice = c_ubyte # Represents a PCAN device
  112. TPCANMessageType = c_ubyte # Represents the type of a PCAN message
  113. TPCANType = c_ubyte # Represents the type of PCAN hardware to be initialized
  114. TPCANMode = c_ubyte # Represents a PCAN filter mode
  115. TPCANBaudrate = c_ushort # Represents a PCAN Baud rate register value
  116. #///////////////////////////////////////////////////////////
  117. # Value definitions
  118. #///////////////////////////////////////////////////////////
  119. # Currently defined and supported PCAN channels
  120. #
  121. PCAN_NONEBUS = TPCANHandle(0x00) # Undefined/default value for a PCAN bus
  122. PCAN_ISABUS1 = TPCANHandle(0x21) # PCAN-ISA interface, channel 1
  123. PCAN_ISABUS2 = TPCANHandle(0x22) # PCAN-ISA interface, channel 2
  124. PCAN_ISABUS3 = TPCANHandle(0x23) # PCAN-ISA interface, channel 3
  125. PCAN_ISABUS4 = TPCANHandle(0x24) # PCAN-ISA interface, channel 4
  126. PCAN_ISABUS5 = TPCANHandle(0x25) # PCAN-ISA interface, channel 5
  127. PCAN_ISABUS6 = TPCANHandle(0x26) # PCAN-ISA interface, channel 6
  128. PCAN_ISABUS7 = TPCANHandle(0x27) # PCAN-ISA interface, channel 7
  129. PCAN_ISABUS8 = TPCANHandle(0x28) # PCAN-ISA interface, channel 8
  130. PCAN_DNGBUS1 = TPCANHandle(0x31) # PCAN-Dongle/LPT interface, channel 1
  131. PCAN_PCIBUS1 = TPCANHandle(0x41) # PCAN-PCI interface, channel 1
  132. PCAN_PCIBUS2 = TPCANHandle(0x42) # PCAN-PCI interface, channel 2
  133. PCAN_PCIBUS3 = TPCANHandle(0x43) # PCAN-PCI interface, channel 3
  134. PCAN_PCIBUS4 = TPCANHandle(0x44) # PCAN-PCI interface, channel 4
  135. PCAN_PCIBUS5 = TPCANHandle(0x45) # PCAN-PCI interface, channel 5
  136. PCAN_PCIBUS6 = TPCANHandle(0x46) # PCAN-PCI interface, channel 6
  137. PCAN_PCIBUS7 = TPCANHandle(0x47) # PCAN-PCI interface, channel 7
  138. PCAN_PCIBUS8 = TPCANHandle(0x48) # PCAN-PCI interface, channel 8
  139. PCAN_PCIBUS9 = TPCANHandle(0x409) # PCAN-PCI interface, channel 9
  140. PCAN_PCIBUS10 = TPCANHandle(0x40A) # PCAN-PCI interface, channel 10
  141. PCAN_PCIBUS11 = TPCANHandle(0x40B) # PCAN-PCI interface, channel 11
  142. PCAN_PCIBUS12 = TPCANHandle(0x40C) # PCAN-PCI interface, channel 12
  143. PCAN_PCIBUS13 = TPCANHandle(0x40D) # PCAN-PCI interface, channel 13
  144. PCAN_PCIBUS14 = TPCANHandle(0x40E) # PCAN-PCI interface, channel 14
  145. PCAN_PCIBUS15 = TPCANHandle(0x40F) # PCAN-PCI interface, channel 15
  146. PCAN_PCIBUS16 = TPCANHandle(0x410) # PCAN-PCI interface, channel 16
  147. PCAN_USBBUS1 = TPCANHandle(0x51) # PCAN-USB interface, channel 1
  148. PCAN_USBBUS2 = TPCANHandle(0x52) # PCAN-USB interface, channel 2
  149. PCAN_USBBUS3 = TPCANHandle(0x53) # PCAN-USB interface, channel 3
  150. PCAN_USBBUS4 = TPCANHandle(0x54) # PCAN-USB interface, channel 4
  151. PCAN_USBBUS5 = TPCANHandle(0x55) # PCAN-USB interface, channel 5
  152. PCAN_USBBUS6 = TPCANHandle(0x56) # PCAN-USB interface, channel 6
  153. PCAN_USBBUS7 = TPCANHandle(0x57) # PCAN-USB interface, channel 7
  154. PCAN_USBBUS8 = TPCANHandle(0x58) # PCAN-USB interface, channel 8
  155. PCAN_USBBUS9 = TPCANHandle(0x509) # PCAN-USB interface, channel 9
  156. PCAN_USBBUS10 = TPCANHandle(0x50A) # PCAN-USB interface, channel 10
  157. PCAN_USBBUS11 = TPCANHandle(0x50B) # PCAN-USB interface, channel 11
  158. PCAN_USBBUS12 = TPCANHandle(0x50C) # PCAN-USB interface, channel 12
  159. PCAN_USBBUS13 = TPCANHandle(0x50D) # PCAN-USB interface, channel 13
  160. PCAN_USBBUS14 = TPCANHandle(0x50E) # PCAN-USB interface, channel 14
  161. PCAN_USBBUS15 = TPCANHandle(0x50F) # PCAN-USB interface, channel 15
  162. PCAN_USBBUS16 = TPCANHandle(0x510) # PCAN-USB interface, channel 16
  163. PCAN_PCCBUS1 = TPCANHandle(0x61) # PCAN-PC Card interface, channel 1
  164. PCAN_PCCBUS2 = TPCANHandle(0x62) # PCAN-PC Card interface, channel 2
  165. PCAN_LANBUS1 = TPCANHandle(0x801) # PCAN-LAN interface, channel 1
  166. PCAN_LANBUS2 = TPCANHandle(0x802) # PCAN-LAN interface, channel 2
  167. PCAN_LANBUS3 = TPCANHandle(0x803) # PCAN-LAN interface, channel 3
  168. PCAN_LANBUS4 = TPCANHandle(0x804) # PCAN-LAN interface, channel 4
  169. PCAN_LANBUS5 = TPCANHandle(0x805) # PCAN-LAN interface, channel 5
  170. PCAN_LANBUS6 = TPCANHandle(0x806) # PCAN-LAN interface, channel 6
  171. PCAN_LANBUS7 = TPCANHandle(0x807) # PCAN-LAN interface, channel 7
  172. PCAN_LANBUS8 = TPCANHandle(0x808) # PCAN-LAN interface, channel 8
  173. PCAN_LANBUS9 = TPCANHandle(0x809) # PCAN-LAN interface, channel 9
  174. PCAN_LANBUS10 = TPCANHandle(0x80A) # PCAN-LAN interface, channel 10
  175. PCAN_LANBUS11 = TPCANHandle(0x80B) # PCAN-LAN interface, channel 11
  176. PCAN_LANBUS12 = TPCANHandle(0x80C) # PCAN-LAN interface, channel 12
  177. PCAN_LANBUS13 = TPCANHandle(0x80D) # PCAN-LAN interface, channel 13
  178. PCAN_LANBUS14 = TPCANHandle(0x80E) # PCAN-LAN interface, channel 14
  179. PCAN_LANBUS15 = TPCANHandle(0x80F) # PCAN-LAN interface, channel 15
  180. PCAN_LANBUS16 = TPCANHandle(0x810) # PCAN-LAN interface, channel 16
  181. # Represent the PCAN error and status codes
  182. #
  183. PCAN_ERROR_OK = TPCANStatus(0x00000) # No error
  184. PCAN_ERROR_XMTFULL = TPCANStatus(0x00001) # Transmit buffer in CAN controller is full
  185. PCAN_ERROR_OVERRUN = TPCANStatus(0x00002) # CAN controller was read too late
  186. PCAN_ERROR_BUSLIGHT = TPCANStatus(0x00004) # Bus error: an error counter reached the 'light' limit
  187. PCAN_ERROR_BUSHEAVY = TPCANStatus(0x00008) # Bus error: an error counter reached the 'heavy' limit
  188. PCAN_ERROR_BUSWARNING = TPCANStatus(PCAN_ERROR_BUSHEAVY) # Bus error: an error counter reached the 'warning' limit
  189. PCAN_ERROR_BUSPASSIVE = TPCANStatus(0x40000) # Bus error: the CAN controller is error passive
  190. PCAN_ERROR_BUSOFF = TPCANStatus(0x00010) # Bus error: the CAN controller is in bus-off state
  191. PCAN_ERROR_ANYBUSERR = TPCANStatus(PCAN_ERROR_BUSWARNING | PCAN_ERROR_BUSLIGHT | PCAN_ERROR_BUSHEAVY | PCAN_ERROR_BUSOFF | PCAN_ERROR_BUSPASSIVE) # Mask for all bus errors
  192. PCAN_ERROR_QRCVEMPTY = TPCANStatus(0x00020) # Receive queue is empty
  193. PCAN_ERROR_QOVERRUN = TPCANStatus(0x00040) # Receive queue was read too late
  194. PCAN_ERROR_QXMTFULL = TPCANStatus(0x00080) # Transmit queue is full
  195. PCAN_ERROR_REGTEST = TPCANStatus(0x00100) # Test of the CAN controller hardware registers failed (no hardware found)
  196. PCAN_ERROR_NODRIVER = TPCANStatus(0x00200) # Driver not loaded
  197. PCAN_ERROR_HWINUSE = TPCANStatus(0x00400) # Hardware already in use by a Net
  198. PCAN_ERROR_NETINUSE = TPCANStatus(0x00800) # A Client is already connected to the Net
  199. PCAN_ERROR_ILLHW = TPCANStatus(0x01400) # Hardware handle is invalid
  200. PCAN_ERROR_ILLNET = TPCANStatus(0x01800) # Net handle is invalid
  201. PCAN_ERROR_ILLCLIENT = TPCANStatus(0x01C00) # Client handle is invalid
  202. PCAN_ERROR_ILLHANDLE = TPCANStatus(PCAN_ERROR_ILLHW | PCAN_ERROR_ILLNET | PCAN_ERROR_ILLCLIENT) # Mask for all handle errors
  203. PCAN_ERROR_RESOURCE = TPCANStatus(0x02000) # Resource (FIFO, Client, timeout) cannot be created
  204. PCAN_ERROR_ILLPARAMTYPE = TPCANStatus(0x04000) # Invalid parameter
  205. PCAN_ERROR_ILLPARAMVAL = TPCANStatus(0x08000) # Invalid parameter value
  206. PCAN_ERROR_UNKNOWN = TPCANStatus(0x10000) # Unknown error
  207. PCAN_ERROR_ILLDATA = TPCANStatus(0x20000) # Invalid data, function, or action
  208. PCAN_ERROR_ILLMODE = TPCANStatus(0x80000) # Driver object state is wrong for the attempted operation
  209. PCAN_ERROR_CAUTION = TPCANStatus(0x2000000)# An operation was successfully carried out, however, irregularities were registered
  210. PCAN_ERROR_INITIALIZE = TPCANStatus(0x4000000)# Channel is not initialized [Value was changed from 0x40000 to 0x4000000]
  211. PCAN_ERROR_ILLOPERATION = TPCANStatus(0x8000000)# Invalid operation [Value was changed from 0x80000 to 0x8000000]
  212. # PCAN devices
  213. #
  214. PCAN_NONE = TPCANDevice(0x00) # Undefined, unknown or not selected PCAN device value
  215. PCAN_PEAKCAN = TPCANDevice(0x01) # PCAN Non-PnP devices. NOT USED WITHIN PCAN-Basic API
  216. PCAN_ISA = TPCANDevice(0x02) # PCAN-ISA, PCAN-PC/104, and PCAN-PC/104-Plus
  217. PCAN_DNG = TPCANDevice(0x03) # PCAN-Dongle
  218. PCAN_PCI = TPCANDevice(0x04) # PCAN-PCI, PCAN-cPCI, PCAN-miniPCI, and PCAN-PCI Express
  219. PCAN_USB = TPCANDevice(0x05) # PCAN-USB and PCAN-USB Pro
  220. PCAN_PCC = TPCANDevice(0x06) # PCAN-PC Card
  221. PCAN_VIRTUAL = TPCANDevice(0x07) # PCAN Virtual hardware. NOT USED WITHIN PCAN-Basic API
  222. PCAN_LAN = TPCANDevice(0x08) # PCAN Gateway devices
  223. # PCAN parameters
  224. #
  225. PCAN_DEVICE_ID = TPCANParameter(0x01) # Device identifier parameter
  226. PCAN_5VOLTS_POWER = TPCANParameter(0x02) # 5-Volt power parameter
  227. PCAN_RECEIVE_EVENT = TPCANParameter(0x03) # PCAN receive event handler parameter
  228. PCAN_MESSAGE_FILTER = TPCANParameter(0x04) # PCAN message filter parameter
  229. PCAN_API_VERSION = TPCANParameter(0x05) # PCAN-Basic API version parameter
  230. PCAN_CHANNEL_VERSION = TPCANParameter(0x06) # PCAN device channel version parameter
  231. PCAN_BUSOFF_AUTORESET = TPCANParameter(0x07) # PCAN Reset-On-Busoff parameter
  232. PCAN_LISTEN_ONLY = TPCANParameter(0x08) # PCAN Listen-Only parameter
  233. PCAN_LOG_LOCATION = TPCANParameter(0x09) # Directory path for log files
  234. PCAN_LOG_STATUS = TPCANParameter(0x0A) # Debug-Log activation status
  235. PCAN_LOG_CONFIGURE = TPCANParameter(0x0B) # Configuration of the debugged information (LOG_FUNCTION_***)
  236. PCAN_LOG_TEXT = TPCANParameter(0x0C) # Custom insertion of text into the log file
  237. PCAN_CHANNEL_CONDITION = TPCANParameter(0x0D) # Availability status of a PCAN-Channel
  238. PCAN_HARDWARE_NAME = TPCANParameter(0x0E) # PCAN hardware name parameter
  239. PCAN_RECEIVE_STATUS = TPCANParameter(0x0F) # Message reception status of a PCAN-Channel
  240. PCAN_CONTROLLER_NUMBER = TPCANParameter(0x10) # CAN-Controller number of a PCAN-Channel
  241. PCAN_TRACE_LOCATION = TPCANParameter(0x11) # Directory path for PCAN trace files
  242. PCAN_TRACE_STATUS = TPCANParameter(0x12) # CAN tracing activation status
  243. PCAN_TRACE_SIZE = TPCANParameter(0x13) # Configuration of the maximum file size of a CAN trace
  244. PCAN_TRACE_CONFIGURE = TPCANParameter(0x14) # Configuration of the trace file storing mode (TRACE_FILE_***)
  245. PCAN_CHANNEL_IDENTIFYING = TPCANParameter(0x15) # Physical identification of a USB based PCAN-Channel by blinking its associated LED
  246. PCAN_CHANNEL_FEATURES = TPCANParameter(0x16) # Capabilities of a PCAN device (FEATURE_***)
  247. PCAN_BITRATE_ADAPTING = TPCANParameter(0x17) # Using of an existing bit rate (PCAN-View connected to a channel)
  248. PCAN_BITRATE_INFO = TPCANParameter(0x18) # Configured bit rate as Btr0Btr1 value
  249. PCAN_BITRATE_INFO_FD = TPCANParameter(0x19) # Configured bit rate as TPCANBitrateFD string
  250. PCAN_BUSSPEED_NOMINAL = TPCANParameter(0x1A) # Configured nominal CAN Bus speed as Bits per seconds
  251. PCAN_BUSSPEED_DATA = TPCANParameter(0x1B) # Configured CAN data speed as Bits per seconds
  252. PCAN_IP_ADDRESS = TPCANParameter(0x1C) # Remote address of a LAN channel as string in IPv4 format
  253. PCAN_LAN_SERVICE_STATUS = TPCANParameter(0x1D) # Status of the Virtual PCAN-Gateway Service
  254. PCAN_ALLOW_STATUS_FRAMES = TPCANParameter(0x1E) # Status messages reception status within a PCAN-Channel
  255. PCAN_ALLOW_RTR_FRAMES = TPCANParameter(0x1F) # RTR messages reception status within a PCAN-Channel
  256. PCAN_ALLOW_ERROR_FRAMES = TPCANParameter(0x20) # Error messages reception status within a PCAN-Channel
  257. PCAN_INTERFRAME_DELAY = TPCANParameter(0x21) # Delay, in microseconds, between sending frames
  258. PCAN_ACCEPTANCE_FILTER_11BIT = TPCANParameter(0x22) # Filter over code and mask patterns for 11-Bit messages
  259. PCAN_ACCEPTANCE_FILTER_29BIT = TPCANParameter(0x23) # Filter over code and mask patterns for 29-Bit messages
  260. 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
  261. PCAN_IO_DIGITAL_VALUE = TPCANParameter(0x25) # Value assigned to a 32 digital I/O pins of a PCAN-USB Chip
  262. 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
  263. PCAN_IO_DIGITAL_CLEAR = TPCANParameter(0x27) # Clear multiple digital I/O pins to 0
  264. PCAN_IO_ANALOG_VALUE = TPCANParameter(0x28) # Get value of a single analog input pin
  265. PCAN_FIRMWARE_VERSION = TPCANParameter(0x29) # Get the version of the firmware used by the device associated with a PCAN-Channel
  266. PCAN_ATTACHED_CHANNELS_COUNT = TPCANParameter(0x2A) # Get the amount of PCAN channels attached to a system
  267. PCAN_ATTACHED_CHANNELS = TPCANParameter(0x2B) # Get information about PCAN channels attached to a system
  268. PCAN_ALLOW_ECHO_FRAMES = TPCANParameter(0x2C) # Echo messages reception status within a PCAN-Channel
  269. PCAN_DEVICE_PART_NUMBER = TPCANParameter(0x2D) # Get the part number associated to a device
  270. # DEPRECATED parameters
  271. #
  272. PCAN_DEVICE_NUMBER = PCAN_DEVICE_ID # DEPRECATED. Use PCAN_DEVICE_ID instead
  273. # PCAN parameter values
  274. #
  275. PCAN_PARAMETER_OFF = int(0x00) # The PCAN parameter is not set (inactive)
  276. PCAN_PARAMETER_ON = int(0x01) # The PCAN parameter is set (active)
  277. PCAN_FILTER_CLOSE = int(0x00) # The PCAN filter is closed. No messages will be received
  278. PCAN_FILTER_OPEN = int(0x01) # The PCAN filter is fully opened. All messages will be received
  279. PCAN_FILTER_CUSTOM = int(0x02) # The PCAN filter is custom configured. Only registered messages will be received
  280. PCAN_CHANNEL_UNAVAILABLE = int(0x00) # The PCAN-Channel handle is illegal, or its associated hardware is not available
  281. 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)
  282. PCAN_CHANNEL_OCCUPIED = int(0x02) # The PCAN-Channel handle is valid, and is already being used
  283. 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
  284. LOG_FUNCTION_DEFAULT = int(0x00) # Logs system exceptions / errors
  285. LOG_FUNCTION_ENTRY = int(0x01) # Logs the entries to the PCAN-Basic API functions
  286. LOG_FUNCTION_PARAMETERS = int(0x02) # Logs the parameters passed to the PCAN-Basic API functions
  287. LOG_FUNCTION_LEAVE = int(0x04) # Logs the exits from the PCAN-Basic API functions
  288. LOG_FUNCTION_WRITE = int(0x08) # Logs the CAN messages passed to the CAN_Write function
  289. LOG_FUNCTION_READ = int(0x10) # Logs the CAN messages received within the CAN_Read function
  290. LOG_FUNCTION_ALL = int(0xFFFF) # Logs all possible information within the PCAN-Basic API functions
  291. TRACE_FILE_SINGLE = int(0x00) # A single file is written until it size reaches PAN_TRACE_SIZE
  292. TRACE_FILE_SEGMENTED = int(0x01) # Traced data is distributed in several files with size PAN_TRACE_SIZE
  293. TRACE_FILE_DATE = int(0x02) # Includes the date into the name of the trace file
  294. TRACE_FILE_TIME = int(0x04) # Includes the start time into the name of the trace file
  295. TRACE_FILE_OVERWRITE = int(0x80) # Causes the overwriting of available traces (same name)
  296. TRACE_FILE_DATA_LENGTH = int(0x100) # Causes using the data length column ('l') instead of the DLC column ('L') in the trace file
  297. FEATURE_FD_CAPABLE = int(0x01) # Device supports flexible data-rate (CAN-FD)
  298. FEATURE_DELAY_CAPABLE = int(0x02) # Device supports a delay between sending frames (FPGA based USB devices)
  299. FEATURE_IO_CAPABLE = int(0x04) # Device supports I/O functionality for electronic circuits (USB-Chip devices)
  300. SERVICE_STATUS_STOPPED = int(0x01) # The service is not running
  301. SERVICE_STATUS_RUNNING = int(0x04) # The service is running
  302. # Other constants
  303. #
  304. MAX_LENGTH_HARDWARE_NAME = int(33) # Maximum length of the name of a device: 32 characters + terminator
  305. MAX_LENGTH_VERSION_STRING = int(256) # Maximum length of a version string: 255 characters + terminator
  306. # PCAN message types
  307. #
  308. PCAN_MESSAGE_STANDARD = TPCANMessageType(0x00) # The PCAN message is a CAN Standard Frame (11-bit identifier)
  309. PCAN_MESSAGE_RTR = TPCANMessageType(0x01) # The PCAN message is a CAN Remote-Transfer-Request Frame
  310. PCAN_MESSAGE_EXTENDED = TPCANMessageType(0x02) # The PCAN message is a CAN Extended Frame (29-bit identifier)
  311. PCAN_MESSAGE_FD = TPCANMessageType(0x04) # The PCAN message represents a FD frame in terms of CiA Specs
  312. PCAN_MESSAGE_BRS = TPCANMessageType(0x08) # The PCAN message represents a FD bit rate switch (CAN data at a higher bit rate)
  313. PCAN_MESSAGE_ESI = TPCANMessageType(0x10) # The PCAN message represents a FD error state indicator(CAN FD transmitter was error active)
  314. PCAN_MESSAGE_ECHO = TPCANMessageType(0x20) # The PCAN message represents an echo CAN Frame
  315. PCAN_MESSAGE_ERRFRAME = TPCANMessageType(0x40) # The PCAN message represents an error frame
  316. PCAN_MESSAGE_STATUS = TPCANMessageType(0x80) # The PCAN message represents a PCAN status message
  317. # LookUp Parameters
  318. #
  319. LOOKUP_DEVICE_TYPE = b"devicetype" # Lookup channel by Device type (see PCAN devices e.g. PCAN_USB)
  320. LOOKUP_DEVICE_ID = b"deviceid" # Lookup channel by device id
  321. LOOKUP_CONTROLLER_NUMBER = b"controllernumber" # Lookup channel by CAN controller 0-based index
  322. LOOKUP_IP_ADDRESS = b"ipaddress" # Lookup channel by IP address (LAN channels only)
  323. # Frame Type / Initialization Mode
  324. #
  325. PCAN_MODE_STANDARD = PCAN_MESSAGE_STANDARD
  326. PCAN_MODE_EXTENDED = PCAN_MESSAGE_EXTENDED
  327. # Baud rate codes = BTR0/BTR1 register values for the CAN controller.
  328. # You can define your own Baud rate with the BTROBTR1 register.
  329. # Take a look at www.peak-system.com for our free software "BAUDTOOL"
  330. # to calculate the BTROBTR1 register for every bit rate and sample point.
  331. #
  332. PCAN_BAUD_1M = TPCANBaudrate(0x0014) # 1 MBit/s
  333. PCAN_BAUD_800K = TPCANBaudrate(0x0016) # 800 kBit/s
  334. PCAN_BAUD_500K = TPCANBaudrate(0x001C) # 500 kBit/s
  335. PCAN_BAUD_250K = TPCANBaudrate(0x011C) # 250 kBit/s
  336. PCAN_BAUD_125K = TPCANBaudrate(0x031C) # 125 kBit/s
  337. PCAN_BAUD_100K = TPCANBaudrate(0x432F) # 100 kBit/s
  338. PCAN_BAUD_95K = TPCANBaudrate(0xC34E) # 95,238 kBit/s
  339. PCAN_BAUD_83K = TPCANBaudrate(0x852B) # 83,333 kBit/s
  340. PCAN_BAUD_50K = TPCANBaudrate(0x472F) # 50 kBit/s
  341. PCAN_BAUD_47K = TPCANBaudrate(0x1414) # 47,619 kBit/s
  342. PCAN_BAUD_33K = TPCANBaudrate(0x8B2F) # 33,333 kBit/s
  343. PCAN_BAUD_20K = TPCANBaudrate(0x532F) # 20 kBit/s
  344. PCAN_BAUD_10K = TPCANBaudrate(0x672F) # 10 kBit/s
  345. PCAN_BAUD_5K = TPCANBaudrate(0x7F7F) # 5 kBit/s
  346. # Supported Non-PnP Hardware types
  347. #
  348. PZLGCAN_ISA = TPCANType(0x01) # PCAN-ISA 82C200
  349. PZLGCAN_ISA_SJA = TPCANType(0x09) # PCAN-ISA SJA1000
  350. PZLGCAN_ISA_PHYTEC = TPCANType(0x04) # PHYTEC ISA
  351. PZLGCAN_DNG = TPCANType(0x02) # PCAN-Dongle 82C200
  352. PZLGCAN_DNG_EPP = TPCANType(0x03) # PCAN-Dongle EPP 82C200
  353. PZLGCAN_DNG_SJA = TPCANType(0x05) # PCAN-Dongle SJA1000
  354. PZLGCAN_DNG_SJA_EPP = TPCANType(0x06) # PCAN-Dongle EPP SJA1000
  355. # Represents a PCAN message
  356. #
  357. class TPCANMsg (ctypes.Structure):
  358. """
  359. Represents a PCAN message
  360. """
  361. _fields_ = [ ("ID", c_uint), # 11/29-bit message identifier
  362. ("MSGTYPE", TPCANMessageType), # Type of the message
  363. ("LEN", c_ubyte), # Data Length Code of the message (0..8)
  364. ("DATA", c_ubyte * 8) ] # Data of the message (DATA[0]..DATA[7])
  365. # Represents a timestamp of a received PCAN message
  366. # Total Microseconds = micros + 1000 * millis + 0x100000000 * 1000 * millis_overflow
  367. #
  368. class TPCANTimestamp (ctypes.Structure):
  369. """
  370. Represents a timestamp of a received PCAN message
  371. Total Microseconds = micros + 1000 * millis + 0x100000000 * 1000 * millis_overflow
  372. """
  373. _fields_ = [ ("millis", c_uint), # Base-value: milliseconds: 0.. 2^32-1
  374. ("millis_overflow", c_ushort), # Roll-arounds of millis
  375. ("micros", c_ushort) ] # Microseconds: 0..999
  376. class MessageDeal:
  377. def __init__(self):
  378. self.can_connect = 0
  379. self.index = 0
  380. self.can_file = ""
  381. def set_can_board(self, can_type, canIndex, canChannel, canBaudrate):
  382. if can_type == 0:
  383. self.canType = CANTYPE['USBCAN-II']
  384. self.can_connect = 0
  385. else:
  386. self.canType = PCAN_USBBUS1
  387. self.can_connect = 1
  388. self.canIndex = canIndex
  389. self.canChannel = canChannel
  390. self.canBaudrate = canBaudrate
  391. def open_device(self):
  392. if self.can_connect:
  393. if self.canBaudrate == "125Kbps":
  394. ret = PCAN.CAN_Initialize(self.canType, PCAN_BAUD_125K ,0,0,0)
  395. elif self.canBaudrate == "250Kbps":
  396. ret = PCAN.CAN_Initialize(self.canType, PCAN_BAUD_250K ,0,0,0)
  397. else:
  398. ret = PCAN.CAN_Initialize(self.canType, PCAN_BAUD_500K ,0,0,0)
  399. if TPCANStatus(ret) != PCAN_ERROR_OK:
  400. return False
  401. time_str = "/CAN_RawDataFile_" + QDateTime.currentDateTime().toString("yyyy_MM_dd_HH_mm_ss") + '.csv'
  402. time_str_path = resource_path("DataDirectory")
  403. if not os.path.exists(time_str_path):
  404. os.mkdir(time_str_path)
  405. self.can_file = time_str_path + time_str
  406. # self.can_file = resource_path(time_str)
  407. return True
  408. else:
  409. if (STATUS_OK != ZLGCAN.VCI_OpenDevice(self.canType, self.canChannel, self.canChannel)):
  410. return False
  411. _vci_initconfig = VCI_INIT_CONFIG(0x00000000, 0xFFFFFFFF, 0, DOUBLE_FILTER,
  412. baudRateConfig[self.canBaudrate]['time0'],
  413. baudRateConfig[self.canBaudrate]['time1'],
  414. NORMAL_MODE)
  415. if (STATUS_OK != ZLGCAN.VCI_InitCAN(self.canType, self.canIndex, self.canChannel, ctypes.byref(_vci_initconfig))):
  416. return False
  417. if (STATUS_OK != ZLGCAN.VCI_StartCAN(self.canType, self.canIndex, self.canChannel)):
  418. return False
  419. time_str = "/CAN_RawDataFile_" + QDateTime.currentDateTime().toString("yyyy_MM_dd_HH_mm_ss") + '.csv'
  420. time_str_path = resource_path("DataDirectory")
  421. if not os.path.exists(time_str_path):
  422. os.mkdir(time_str_path)
  423. self.can_file = time_str_path + time_str
  424. return True
  425. def get_undeal_number(self):
  426. if self.can_connect:
  427. return 1
  428. else:
  429. return ZLGCAN.VCI_GetReceiveNum(self.canType, self.canIndex, self.canChannel)
  430. def receive(self, number=1):
  431. if self.can_connect:
  432. msg = TPCANMsg()
  433. timestamp = TPCANTimestamp()
  434. res = PCAN.CAN_Read(self.canType,ctypes.byref(msg),ctypes.byref(timestamp))
  435. if (res != PCAN_ERROR_QRCVEMPTY):
  436. self.format_msg_data(self.index, msg.ID, msg.LEN, msg.DATA, 1)
  437. self.index += 1
  438. return 1, msg.ID, msg.DATA
  439. else:
  440. return 0, 0, 0
  441. else:
  442. objs = (VCI_CAN_OBJ * number)()
  443. ret = ZLGCAN.VCI_Receive(self.canType, self.canIndex, self.canChannel, ctypes.byref(objs), number, 10)
  444. if (ret > 0):
  445. for i in range(0, ret):
  446. self.format_msg_data(self.index, objs[i].ID, objs[i].DataLen, objs[i].Data, 1)
  447. self.index += 1
  448. return 1, objs[i].ID, objs[i].Data
  449. else:
  450. return 0, 0, 0
  451. def send(self, ID, data, data_len=8):
  452. if self.can_connect:
  453. msg = TPCANMsg()
  454. msg.ID = ID
  455. msg.LEN = data_len
  456. if (ID > 0x7FF):
  457. msg.MSGTYPE = PCAN_MESSAGE_EXTENDED
  458. else:
  459. msg.MSGTYPE = PCAN_MESSAGE_STANDARD
  460. if len(data) < 8:
  461. data += (8 - len(data)) * [0]
  462. msg.DATA = (c_ubyte * 8)(data[0], data[1], data[2], data[3], data[4], data[5], data[6], data[7])
  463. send_status = PCAN.CAN_Write(self.canType,ctypes.byref(msg))
  464. if (TPCANStatus(send_status) != PCAN_ERROR_OK):
  465. return False
  466. else:
  467. self.format_msg_data(self.index, msg.ID, msg.LEN, msg.DATA, 0)
  468. self.index += 1
  469. return True
  470. else:
  471. vci_can_obj = VCI_CAN_OBJ()
  472. vci_can_obj.ID = ID
  473. vci_can_obj.DataLen = data_len
  474. vci_can_obj.SendType = SEND_NORMAL
  475. if (ID > 0x7FF):
  476. vci_can_obj.ExternFlag = 1
  477. else:
  478. vci_can_obj.ExternFlag = 0
  479. vci_can_obj.RemoteFlag = 0
  480. if len(data) < 8:
  481. data += (8 - len(data)) * [0]
  482. vci_can_obj.Data = (c_ubyte * 8)(data[0], data[1], data[2], data[3], data[4], data[5], data[6], data[7])
  483. ret = ZLGCAN.VCI_Transmit(self.canType, self.canIndex, self.canChannel, ctypes.byref(vci_can_obj), 1)
  484. if ret != STATUS_OK:
  485. return False
  486. else:
  487. self.format_msg_data(self.index, vci_can_obj.ID, vci_can_obj.DataLen, vci_can_obj.Data, 0)
  488. self.index += 1
  489. return True
  490. def read_err_info(self):
  491. errInfo = PVCI_ERR_INFO(0, ubyte_3array(0, 0, 0), 0)
  492. ZLGCAN.VCI_ReadErrInfo(self.canType, self.canIndex, self.canChannel, ctypes.byref(errInfo))
  493. def close_can(self):
  494. if self.can_connect:
  495. PCAN.CAN_Uninitialize(self.canType)
  496. else:
  497. ZLGCAN.VCI_ClearBuffer(self.canType, self.canIndex, self.canChannel)
  498. ZLGCAN.VCI_CloseDevice(self.canType, self.canIndex)
  499. def format_msg_data(self, index, id, len, can_data, received):
  500. data = []
  501. can_rec_time = QDateTime.currentDateTime().toString("yyyy-MM-dd HH:mm:ss.zzz")
  502. data.append('{0:0>7}'.format(index))
  503. data.append(can_rec_time)
  504. data.append('接收' if received else '发送')
  505. data.append(str.upper('0x' + '{:0>8x}'.format(id)).replace('X', 'x'))
  506. data.append(len)
  507. data.append(' '.join(['{:0>2x}'.format(a) for a in list(can_data)]))
  508. if os.path.exists(self.can_file):
  509. with open(self.can_file, 'a') as csvfile:
  510. writer = csv.writer(csvfile, dialect='excel', lineterminator='\n')
  511. writer.writerow(data)
  512. else:
  513. time_str = "/CAN_RawDataFile_" + QDateTime.currentDateTime().toString("yyyy_MM_dd_HH_mm_ss") + '.csv'
  514. time_str_path = resource_path("DataDirectory")
  515. if not os.path.exists(time_str_path):
  516. os.mkdir(time_str_path)
  517. self.can_file = time_str_path + time_str
  518. with open(self.can_file, 'w') as csvfile:
  519. writer = csv.writer(csvfile, dialect='excel', lineterminator='\n')
  520. header = ["序号", "时间戳", "收/发", "CAN ID", "CAN LEN", "CAN DATA"]
  521. writer.writerow(header)
  522. writer.writerow(data)