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.

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