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.

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