A clone of: https://github.com/nutechsoftware/alarmdecoder This is requires as they dropped support for older firmware releases w/o building in backward compatibility code, and they had previously hardcoded pyserial to a python2 only version.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

508 lines
14 KiB

  1. """
  2. Contains different types of devices belonging to the AD2USB family.
  3. """
  4. import usb.core
  5. import usb.util
  6. import time
  7. import threading
  8. import serial
  9. import serial.tools.list_ports
  10. import socket
  11. import traceback
  12. from pyftdi.pyftdi.ftdi import *
  13. from pyftdi.pyftdi.usbtools import *
  14. from . import util
  15. from .event import event
  16. class Device(object):
  17. """
  18. Generic parent device to all AD2USB products.
  19. """
  20. # Generic device events
  21. on_open = event.Event('Called when the device has been opened')
  22. on_close = event.Event('Called when the device has been closed')
  23. on_read = event.Event('Called when a line has been read from the device')
  24. on_write = event.Event('Called when data has been written to the device')
  25. def __init__(self):
  26. pass
  27. def __del__(self):
  28. pass
  29. class ReadThread(threading.Thread):
  30. """
  31. Reader thread which processes messages from the device.
  32. """
  33. def __init__(self, device):
  34. """
  35. Constructor
  36. """
  37. threading.Thread.__init__(self)
  38. self._device = device
  39. self._running = False
  40. def stop(self):
  41. """
  42. Stops the running thread.
  43. """
  44. self._running = False
  45. def run(self):
  46. """
  47. The actual read process.
  48. """
  49. self._running = True
  50. while self._running:
  51. try:
  52. self._device.read_line(timeout=10)
  53. except util.CommError, err:
  54. traceback.print_exc(err) # TEMP
  55. except util.TimeoutError, err:
  56. pass
  57. time.sleep(0.01)
  58. class USBDevice(Device):
  59. """
  60. AD2USB device exposed with PyFTDI's interface.
  61. """
  62. # Constants
  63. FTDI_VENDOR_ID = 0x0403
  64. FTDI_PRODUCT_ID = 0x6001
  65. BAUDRATE = 115200
  66. @staticmethod
  67. def find_all():
  68. """
  69. Returns all FTDI devices matching our vendor and product IDs.
  70. """
  71. devices = []
  72. try:
  73. devices = Ftdi.find_all([(USBDevice.FTDI_VENDOR_ID, USBDevice.FTDI_PRODUCT_ID)], nocache=True)
  74. except (usb.core.USBError, FtdiError), err:
  75. raise util.CommError('Error enumerating AD2USB devices: {0}'.format(str(err)))
  76. return devices
  77. def __init__(self, vid=FTDI_VENDOR_ID, pid=FTDI_PRODUCT_ID, serial=None, description=None, interface=0):
  78. """
  79. Constructor
  80. """
  81. Device.__init__(self)
  82. self._vendor_id = vid
  83. self._product_id = pid
  84. self._serial_number = serial
  85. self._description = description
  86. self._buffer = ''
  87. self._device = Ftdi()
  88. self._running = False
  89. self._interface = interface
  90. self._read_thread = Device.ReadThread(self)
  91. def open(self, baudrate=BAUDRATE, interface=None, index=0):
  92. """
  93. Opens the device.
  94. """
  95. # Set up defaults
  96. if baudrate is None:
  97. baudrate = USBDevice.BAUDRATE
  98. if self._interface is None and interface is None:
  99. self._interface = 0
  100. if interface is not None:
  101. self._interface = interface
  102. if index is None:
  103. index = 0
  104. # Open the device and start up the thread.
  105. try:
  106. self._device.open(self._vendor_id,
  107. self._product_id,
  108. self._interface,
  109. index,
  110. self._serial_number,
  111. self._description)
  112. self._device.set_baudrate(baudrate)
  113. except (usb.core.USBError, FtdiError), err:
  114. self.on_close()
  115. raise util.CommError('Error opening AD2USB device: {0}'.format(str(err)))
  116. else:
  117. self._running = True
  118. self._read_thread.start()
  119. self.on_open((self._serial_number, self._description))
  120. def close(self):
  121. """
  122. Closes the device.
  123. """
  124. try:
  125. self._running = False
  126. self._read_thread.stop()
  127. self._device.close()
  128. # HACK: Probably should fork pyftdi and make this call in .close().
  129. self._device.usb_dev.attach_kernel_driver(self._interface)
  130. except (FtdiError, usb.core.USBError):
  131. pass
  132. self.on_close()
  133. def close_reader(self):
  134. """
  135. Stops the reader thread.
  136. """
  137. self._read_thread.stop()
  138. def write(self, data):
  139. """
  140. Writes data to the device.
  141. """
  142. self._device.write_data(data)
  143. self.on_write(data)
  144. def read(self):
  145. """
  146. Reads a single character from the device.
  147. """
  148. return self._device.read_data(1)
  149. def read_line(self, timeout=0.0):
  150. """
  151. Reads a line from the device.
  152. """
  153. start_time = time.time()
  154. got_line = False
  155. ret = None
  156. try:
  157. while self._running:
  158. buf = self._device.read_data(1)
  159. if buf != '':
  160. self._buffer += buf
  161. if buf == "\n":
  162. if len(self._buffer) > 1:
  163. if self._buffer[-2] == "\r":
  164. self._buffer = self._buffer[:-2]
  165. # ignore if we just got \r\n with nothing else in the buffer.
  166. if len(self._buffer) != 0:
  167. got_line = True
  168. break
  169. else:
  170. self._buffer = self._buffer[:-1]
  171. if timeout > 0 and time.time() - start_time > timeout:
  172. raise util.TimeoutError('Timeout while waiting for line terminator.')
  173. except (usb.core.USBError, FtdiError), err:
  174. raise util.CommError('Error reading from AD2USB device: {0}'.format(str(err)))
  175. else:
  176. if got_line:
  177. ret = self._buffer
  178. self._buffer = ''
  179. self.on_read(ret)
  180. return ret
  181. class SerialDevice(Device):
  182. """
  183. AD2USB or AD2SERIAL device exposed with the pyserial interface.
  184. """
  185. # Constants
  186. BAUDRATE = 19200
  187. @staticmethod
  188. def find_all():
  189. """
  190. Returns all serial ports present.
  191. """
  192. devices = []
  193. try:
  194. devices = serial.tools.list_ports.comports()
  195. except Exception, err:
  196. raise util.CommError('Error enumerating AD2SERIAL devices: {0}'.format(str(err)))
  197. return devices
  198. def __init__(self, interface=None):
  199. """
  200. Constructor
  201. """
  202. Device.__init__(self)
  203. self._device = serial.Serial(timeout=0) # Timeout = non-blocking to match pyftdi.
  204. self._read_thread = Device.ReadThread(self)
  205. self._buffer = ''
  206. self._running = False
  207. self._interface = interface
  208. def __del__(self):
  209. """
  210. Destructor
  211. """
  212. pass
  213. def open(self, baudrate=BAUDRATE, interface=None, index=None):
  214. """
  215. Opens the device.
  216. """
  217. # Set up the defaults
  218. if baudrate is None:
  219. baudrate = SerialDevice.BAUDRATE
  220. if self._interface is None and interface is None:
  221. raise util.NoDeviceError('No AD2SERIAL device interface specified.')
  222. if interface is not None:
  223. self._interface = interface
  224. self._device.baudrate = baudrate
  225. self._device.port = self._interface
  226. # Open the device and start up the reader thread.
  227. try:
  228. self._device.open()
  229. except (serial.SerialException, ValueError), err:
  230. self.on_close()
  231. raise util.NoDeviceError('Error opening AD2SERIAL device on port {0}.'.format(interface))
  232. else:
  233. self._running = True
  234. self.on_open((None, "AD2SERIAL")) # TODO: Fixme.
  235. self._read_thread.start()
  236. def close(self):
  237. """
  238. Closes the device.
  239. """
  240. try:
  241. self._running = False
  242. self._read_thread.stop()
  243. self._device.close()
  244. except Exception, err:
  245. pass
  246. self.on_close()
  247. def close_reader(self):
  248. """
  249. Stops the reader thread.
  250. """
  251. self._read_thread.stop()
  252. def write(self, data):
  253. """
  254. Writes data to the device.
  255. """
  256. try:
  257. self._device.write(data)
  258. except serial.SerialTimeoutException, err:
  259. pass
  260. else:
  261. self.on_write(data)
  262. def read(self):
  263. """
  264. Reads a single character from the device.
  265. """
  266. return self._device.read(1)
  267. def read_line(self, timeout=0.0):
  268. """
  269. Reads a line from the device.
  270. """
  271. start_time = time.time()
  272. got_line = False
  273. ret = None
  274. try:
  275. while self._running:
  276. buf = self._device.read(1)
  277. if buf != '' and buf != "\xff": # AD2SERIAL specifically apparently sends down \xFF on boot.
  278. self._buffer += buf
  279. if buf == "\n":
  280. if len(self._buffer) > 1:
  281. if self._buffer[-2] == "\r":
  282. self._buffer = self._buffer[:-2]
  283. # ignore if we just got \r\n with nothing else in the buffer.
  284. if len(self._buffer) != 0:
  285. got_line = True
  286. break
  287. else:
  288. self._buffer = self._buffer[:-1]
  289. if timeout > 0 and time.time() - start_time > timeout:
  290. raise util.TimeoutError('Timeout while waiting for line terminator.')
  291. except (OSError, serial.SerialException), err:
  292. raise util.CommError('Error reading from AD2SERIAL device: {0}'.format(str(err)))
  293. else:
  294. if got_line:
  295. ret = self._buffer
  296. self._buffer = ''
  297. self.on_read(ret)
  298. return ret
  299. class SocketDevice(Device):
  300. """
  301. Device that supports communication with an AD2USB that is exposed via ser2sock or another
  302. Serial to IP interface.
  303. """
  304. def __init__(self, interface=None):
  305. """
  306. Constructor
  307. """
  308. self._host = "localhost"
  309. self._port = 10000
  310. self._device = None
  311. self._buffer = ''
  312. self._running = False
  313. self._read_thread = Device.ReadThread(self)
  314. def __del__(self):
  315. """
  316. Destructor
  317. """
  318. pass
  319. def open(self, baudrate=None, interface=None, index=0):
  320. """
  321. Opens the device.
  322. """
  323. if interface is not None:
  324. self._host, self._port = interface
  325. try:
  326. self._device = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  327. self._device.connect((self._host, self._port))
  328. except socket.error, err:
  329. self.on_close()
  330. traceback.print_exc(err) # TEMP
  331. else:
  332. self._running = True
  333. self.on_open((None, "AD2SOCKET")) # TEMP: Change me.
  334. self._read_thread.start()
  335. def close(self):
  336. """
  337. Closes the device.
  338. """
  339. self._running = False
  340. try:
  341. self._read_thread.stop()
  342. self._device.shutdown(socket.SHUT_RDWR) # Make sure that it closes immediately.
  343. self._device.close()
  344. except:
  345. pass
  346. self.on_close()
  347. def close_reader(self):
  348. """
  349. Stops the reader thread.
  350. """
  351. self._read_thread.stop()
  352. def write(self, data):
  353. """
  354. Writes data to the device.
  355. """
  356. data_sent = self._device.send(data)
  357. if data_sent == 0:
  358. raise util.CommError('Error while sending data.')
  359. else:
  360. self.on_write(data)
  361. return data_sent
  362. def read(self):
  363. """
  364. Reads a single character from the device.
  365. """
  366. try:
  367. data = self._device.recv(1)
  368. except socket.error, err:
  369. raise util.CommError('Error while reading from device: {0}'.format(str(err)))
  370. # ??? - Should we trigger an on_read here as well?
  371. return data
  372. def read_line(self, timeout=0.0):
  373. """
  374. Reads a line from the device.
  375. """
  376. start_time = time.time()
  377. got_line = False
  378. ret = None
  379. try:
  380. while self._running:
  381. buf = self._device.recv(1)
  382. if buf != '':
  383. self._buffer += buf
  384. if buf == "\n":
  385. if len(self._buffer) > 1:
  386. if self._buffer[-2] == "\r":
  387. self._buffer = self._buffer[:-2]
  388. # ignore if we just got \r\n with nothing else in the buffer.
  389. if len(self._buffer) != 0:
  390. got_line = True
  391. break
  392. else:
  393. self._buffer = self._buffer[:-1]
  394. if timeout > 0 and time.time() - start_time > timeout:
  395. raise util.TimeoutError('Timeout while waiting for line terminator.')
  396. except socket.error, err:
  397. raise util.CommError('Error reading from Socket device: {0}'.format(str(err)))
  398. else:
  399. if got_line:
  400. ret = self._buffer
  401. self._buffer = ''
  402. self.on_read(ret)
  403. return ret