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.

530 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, no_reader_thread=False):
  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. if not no_reader_thread:
  119. self._read_thread.start()
  120. self.on_open((self._serial_number, self._description))
  121. def close(self):
  122. """
  123. Closes the device.
  124. """
  125. try:
  126. self._running = False
  127. self._read_thread.stop()
  128. self._device.close()
  129. # HACK: Probably should fork pyftdi and make this call in .close().
  130. self._device.usb_dev.attach_kernel_driver(self._interface)
  131. except (FtdiError, usb.core.USBError):
  132. pass
  133. self.on_close()
  134. def is_reader_alive(self):
  135. """
  136. Indicates whether or not the reader thread is alive.
  137. """
  138. return self._read_thread.is_alive()
  139. def stop_reader(self):
  140. """
  141. Stops the reader thread.
  142. """
  143. self._read_thread.stop()
  144. def write(self, data):
  145. """
  146. Writes data to the device.
  147. """
  148. self._device.write_data(data)
  149. self.on_write(data)
  150. def read(self):
  151. """
  152. Reads a single character from the device.
  153. """
  154. return self._device.read_data(1)
  155. def read_line(self, timeout=0.0):
  156. """
  157. Reads a line from the device.
  158. """
  159. start_time = time.time()
  160. got_line = False
  161. ret = None
  162. try:
  163. while self._running:
  164. buf = self._device.read_data(1)
  165. if buf != '':
  166. self._buffer += buf
  167. if buf == "\n":
  168. if len(self._buffer) > 1:
  169. if self._buffer[-2] == "\r":
  170. self._buffer = self._buffer[:-2]
  171. # ignore if we just got \r\n with nothing else in the buffer.
  172. if len(self._buffer) != 0:
  173. got_line = True
  174. break
  175. else:
  176. self._buffer = self._buffer[:-1]
  177. if timeout > 0 and time.time() - start_time > timeout:
  178. raise util.TimeoutError('Timeout while waiting for line terminator.')
  179. except (usb.core.USBError, FtdiError), err:
  180. raise util.CommError('Error reading from AD2USB device: {0}'.format(str(err)))
  181. else:
  182. if got_line:
  183. ret = self._buffer
  184. self._buffer = ''
  185. self.on_read(ret)
  186. return ret
  187. class SerialDevice(Device):
  188. """
  189. AD2USB or AD2SERIAL device exposed with the pyserial interface.
  190. """
  191. # Constants
  192. BAUDRATE = 19200
  193. @staticmethod
  194. def find_all():
  195. """
  196. Returns all serial ports present.
  197. """
  198. devices = []
  199. try:
  200. devices = serial.tools.list_ports.comports()
  201. except Exception, err:
  202. raise util.CommError('Error enumerating AD2SERIAL devices: {0}'.format(str(err)))
  203. return devices
  204. def __init__(self, interface=None):
  205. """
  206. Constructor
  207. """
  208. Device.__init__(self)
  209. self._device = serial.Serial(timeout=0) # Timeout = non-blocking to match pyftdi.
  210. self._read_thread = Device.ReadThread(self)
  211. self._buffer = ''
  212. self._running = False
  213. self._interface = interface
  214. def __del__(self):
  215. """
  216. Destructor
  217. """
  218. pass
  219. def open(self, baudrate=BAUDRATE, interface=None, index=None, no_reader_thread=False):
  220. """
  221. Opens the device.
  222. """
  223. # Set up the defaults
  224. if baudrate is None:
  225. baudrate = SerialDevice.BAUDRATE
  226. if self._interface is None and interface is None:
  227. raise util.NoDeviceError('No AD2SERIAL device interface specified.')
  228. if interface is not None:
  229. self._interface = interface
  230. self._device.baudrate = baudrate
  231. self._device.port = self._interface
  232. # Open the device and start up the reader thread.
  233. try:
  234. self._device.open()
  235. except (serial.SerialException, ValueError), err:
  236. self.on_close()
  237. raise util.NoDeviceError('Error opening AD2SERIAL device on port {0}.'.format(interface))
  238. else:
  239. self._running = True
  240. self.on_open((None, "AD2SERIAL")) # TODO: Fixme.
  241. if not no_reader_thread:
  242. self._read_thread.start()
  243. def close(self):
  244. """
  245. Closes the device.
  246. """
  247. try:
  248. self._running = False
  249. self._read_thread.stop()
  250. self._device.close()
  251. except Exception, err:
  252. pass
  253. self.on_close()
  254. def is_reader_alive(self):
  255. """
  256. Indicates whether or not the reader thread is alive.
  257. """
  258. return self._read_thread.is_alive()
  259. def stop_reader(self):
  260. """
  261. Stops the reader thread.
  262. """
  263. self._read_thread.stop()
  264. def write(self, data):
  265. """
  266. Writes data to the device.
  267. """
  268. try:
  269. self._device.write(data)
  270. except serial.SerialTimeoutException, err:
  271. pass
  272. else:
  273. self.on_write(data)
  274. def read(self):
  275. """
  276. Reads a single character from the device.
  277. """
  278. return self._device.read(1)
  279. def read_line(self, timeout=0.0):
  280. """
  281. Reads a line from the device.
  282. """
  283. start_time = time.time()
  284. got_line = False
  285. ret = None
  286. try:
  287. while self._running:
  288. buf = self._device.read(1)
  289. if buf != '' and buf != "\xff": # AD2SERIAL specifically apparently sends down \xFF on boot.
  290. self._buffer += buf
  291. if buf == "\n":
  292. if len(self._buffer) > 1:
  293. if self._buffer[-2] == "\r":
  294. self._buffer = self._buffer[:-2]
  295. # ignore if we just got \r\n with nothing else in the buffer.
  296. if len(self._buffer) != 0:
  297. got_line = True
  298. break
  299. else:
  300. self._buffer = self._buffer[:-1]
  301. if timeout > 0 and time.time() - start_time > timeout:
  302. raise util.TimeoutError('Timeout while waiting for line terminator.')
  303. except (OSError, serial.SerialException), err:
  304. raise util.CommError('Error reading from AD2SERIAL device: {0}'.format(str(err)))
  305. else:
  306. if got_line:
  307. ret = self._buffer
  308. self._buffer = ''
  309. self.on_read(ret)
  310. return ret
  311. class SocketDevice(Device):
  312. """
  313. Device that supports communication with an AD2USB that is exposed via ser2sock or another
  314. Serial to IP interface.
  315. """
  316. def __init__(self, interface=None):
  317. """
  318. Constructor
  319. """
  320. self._host = "localhost"
  321. self._port = 10000
  322. self._device = None
  323. self._buffer = ''
  324. self._running = False
  325. self._read_thread = Device.ReadThread(self)
  326. def __del__(self):
  327. """
  328. Destructor
  329. """
  330. pass
  331. def open(self, baudrate=None, interface=None, index=0, no_reader_thread=False):
  332. """
  333. Opens the device.
  334. """
  335. if interface is not None:
  336. self._host, self._port = interface
  337. try:
  338. self._device = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  339. self._device.connect((self._host, self._port))
  340. except socket.error, err:
  341. self.on_close()
  342. traceback.print_exc(err) # TEMP
  343. else:
  344. self._running = True
  345. self.on_open((None, "AD2SOCKET")) # TEMP: Change me.
  346. if not no_reader_thread:
  347. self._read_thread.start()
  348. def close(self):
  349. """
  350. Closes the device.
  351. """
  352. self._running = False
  353. try:
  354. self._read_thread.stop()
  355. self._device.shutdown(socket.SHUT_RDWR) # Make sure that it closes immediately.
  356. self._device.close()
  357. except:
  358. pass
  359. self.on_close()
  360. def is_reader_alive(self):
  361. """
  362. Indicates whether or not the reader thread is alive.
  363. """
  364. return self._read_thread.is_alive()
  365. def stop_reader(self):
  366. """
  367. Stops the reader thread.
  368. """
  369. self._read_thread.stop()
  370. def write(self, data):
  371. """
  372. Writes data to the device.
  373. """
  374. data_sent = self._device.send(data)
  375. if data_sent == 0:
  376. raise util.CommError('Error while sending data.')
  377. else:
  378. self.on_write(data)
  379. return data_sent
  380. def read(self):
  381. """
  382. Reads a single character from the device.
  383. """
  384. try:
  385. data = self._device.recv(1)
  386. except socket.error, err:
  387. raise util.CommError('Error while reading from device: {0}'.format(str(err)))
  388. # ??? - Should we trigger an on_read here as well?
  389. return data
  390. def read_line(self, timeout=0.0):
  391. """
  392. Reads a line from the device.
  393. """
  394. start_time = time.time()
  395. got_line = False
  396. ret = None
  397. try:
  398. while self._running:
  399. buf = self._device.recv(1)
  400. if buf != '':
  401. self._buffer += buf
  402. if buf == "\n":
  403. if len(self._buffer) > 1:
  404. if self._buffer[-2] == "\r":
  405. self._buffer = self._buffer[:-2]
  406. # ignore if we just got \r\n with nothing else in the buffer.
  407. if len(self._buffer) != 0:
  408. got_line = True
  409. break
  410. else:
  411. self._buffer = self._buffer[:-1]
  412. if timeout > 0 and time.time() - start_time > timeout:
  413. raise util.TimeoutError('Timeout while waiting for line terminator.')
  414. except socket.error, err:
  415. raise util.CommError('Error reading from Socket device: {0}'.format(str(err)))
  416. else:
  417. if got_line:
  418. ret = self._buffer
  419. self._buffer = ''
  420. self.on_read(ret)
  421. return ret