can.py 34 KB

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