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.

496 lines
14 KiB

  1. """
  2. Provides the full AD2USB class and factory.
  3. """
  4. import time
  5. import threading
  6. import re
  7. from .event import event
  8. from . import devices
  9. from . import util
  10. class Overseer(object):
  11. """
  12. Factory for creation of AD2USB devices as well as provide4s attach/detach events."
  13. """
  14. # Factory events
  15. on_attached = event.Event('Called when an AD2USB device has been detected.')
  16. on_detached = event.Event('Called when an AD2USB device has been removed.')
  17. __devices = []
  18. @classmethod
  19. def find_all(cls):
  20. """
  21. Returns all AD2USB devices located on the system.
  22. """
  23. cls.__devices = devices.USBDevice.find_all()
  24. return cls.__devices
  25. @classmethod
  26. def devices(cls):
  27. """
  28. Returns a cached list of AD2USB devices located on the system.
  29. """
  30. return cls.__devices
  31. @classmethod
  32. def create(cls, device=None):
  33. """
  34. Factory method that returns the requested AD2USB device, or the first device.
  35. """
  36. cls.find_all()
  37. if len(cls.__devices) == 0:
  38. raise util.NoDeviceError('No AD2USB devices present.')
  39. if device is None:
  40. device = cls.__devices[0]
  41. vendor, product, sernum, ifcount, description = device
  42. device = devices.USBDevice(serial=sernum, description=description)
  43. return AD2USB(device)
  44. def __init__(self, attached_event=None, detached_event=None):
  45. """
  46. Constructor
  47. """
  48. self._detect_thread = Overseer.DetectThread(self)
  49. if attached_event:
  50. self.on_attached += attached_event
  51. if detached_event:
  52. self.on_detached += detached_event
  53. Overseer.find_all()
  54. self.start()
  55. def close(self):
  56. """
  57. Clean up and shut down.
  58. """
  59. self.stop()
  60. def start(self):
  61. """
  62. Starts the detection thread, if not already running.
  63. """
  64. if not self._detect_thread.is_alive():
  65. self._detect_thread.start()
  66. def stop(self):
  67. """
  68. Stops the detection thread.
  69. """
  70. self._detect_thread.stop()
  71. def get_device(self, device=None):
  72. """
  73. Factory method that returns the requested AD2USB device, or the first device.
  74. """
  75. return Overseer.create(device)
  76. class DetectThread(threading.Thread):
  77. """
  78. Thread that handles detection of added/removed devices.
  79. """
  80. def __init__(self, overseer):
  81. """
  82. Constructor
  83. """
  84. threading.Thread.__init__(self)
  85. self._overseer = overseer
  86. self._running = False
  87. def stop(self):
  88. """
  89. Stops the thread.
  90. """
  91. self._running = False
  92. def run(self):
  93. """
  94. The actual detection process.
  95. """
  96. self._running = True
  97. last_devices = set()
  98. while self._running:
  99. try:
  100. Overseer.find_all()
  101. current_devices = set(Overseer.devices())
  102. new_devices = [d for d in current_devices if d not in last_devices]
  103. removed_devices = [d for d in last_devices if d not in current_devices]
  104. last_devices = current_devices
  105. for d in new_devices:
  106. self._overseer.on_attached(d)
  107. for d in removed_devices:
  108. self._overseer.on_detached(d)
  109. except util.CommError, err:
  110. pass
  111. time.sleep(0.25)
  112. class AD2USB(object):
  113. """
  114. High-level wrapper around AD2USB/AD2SERIAL devices.
  115. """
  116. # High-level Events
  117. on_status_changed = event.Event('Called when the panel status changes.')
  118. on_power_changed = event.Event('Called when panel power switches between AC and DC.')
  119. on_alarm = event.Event('Called when the alarm is triggered.')
  120. on_bypass = event.Event('Called when a zone is bypassed.')
  121. on_boot = event.Event('Called when the device finishes bootings.')
  122. on_config_received = event.Event('Called when the device receives its configuration.')
  123. # Mid-level Events
  124. on_message = event.Event('Called when a message has been received from the device.')
  125. # Low-level Events
  126. on_open = event.Event('Called when the device has been opened.')
  127. on_close = event.Event('Called when the device has been closed.')
  128. on_read = event.Event('Called when a line has been read from the device.')
  129. on_write = event.Event('Called when data has been written to the device.')
  130. # Constants
  131. F1 = unichr(1) + unichr(1) + unichr(1)
  132. F2 = unichr(2) + unichr(2) + unichr(2)
  133. F3 = unichr(3) + unichr(3) + unichr(3)
  134. F4 = unichr(4) + unichr(4) + unichr(4)
  135. def __init__(self, device):
  136. """
  137. Constructor
  138. """
  139. self._device = device
  140. self._power_status = None
  141. self._alarm_status = None
  142. self._bypass_status = None
  143. self._settings = {}
  144. self._address_mask = 0xFF80 # TEMP
  145. def open(self, baudrate=None, interface=None, index=None, no_reader_thread=False):
  146. """
  147. Opens the device.
  148. """
  149. self._wire_events()
  150. self._device.open(baudrate=baudrate, interface=interface, index=index, no_reader_thread=no_reader_thread)
  151. def close(self):
  152. """
  153. Closes the device.
  154. """
  155. self._device.close()
  156. self._device = None
  157. def get_config(self):
  158. """
  159. Retrieves the configuration from the device.
  160. """
  161. self._device.write("C\r")
  162. def set_config(self, settings):
  163. """
  164. """
  165. pass
  166. def reboot(self):
  167. """
  168. Reboots the device.
  169. """
  170. self._device.write('=')
  171. @property
  172. def id(self):
  173. return self._device.id
  174. def _wire_events(self):
  175. """
  176. Wires up the internal device events.
  177. """
  178. self._device.on_open += self._on_open
  179. self._device.on_close += self._on_close
  180. self._device.on_read += self._on_read
  181. self._device.on_write += self._on_write
  182. def _handle_message(self, data):
  183. """
  184. Parses messages from the panel.
  185. """
  186. if data is None:
  187. return None
  188. msg = None
  189. if data[0] != '!':
  190. msg = Message(data)
  191. if self._address_mask & msg.mask > 0:
  192. self._update_internal_states(msg)
  193. else: # specialty messages
  194. header = data[0:4]
  195. if header == '!EXP' or header == '!REL':
  196. msg = ExpanderMessage(data)
  197. elif header == '!RFX':
  198. msg = RFMessage(data)
  199. elif header == '!LRR':
  200. msg = LRRMessage(data)
  201. elif data.startswith('!Ready'):
  202. self.on_boot()
  203. elif data.startswith('!CONFIG'):
  204. self._handle_config(data)
  205. return msg
  206. def _handle_config(self, data):
  207. _, config_string = data.split('>')
  208. for setting in config_string.split('&'):
  209. k, v = setting.split('=')
  210. self._settings[k] = v
  211. self.on_config_received(self._settings)
  212. def _update_internal_states(self, message):
  213. if message.ac_power != self._power_status:
  214. self._power_status, old_status = message.ac_power, self._power_status
  215. if old_status is not None:
  216. self.on_power_changed(self._power_status)
  217. if message.alarm_sounding != self._alarm_status:
  218. self._alarm_status, old_status = message.alarm_sounding, self._alarm_status
  219. if old_status is not None:
  220. self.on_alarm(self._alarm_status)
  221. if message.zone_bypassed != self._bypass_status:
  222. self._bypass_status, old_status = message.zone_bypassed, self._bypass_status
  223. if old_status is not None:
  224. self.on_bypass(self._bypass_status)
  225. def _on_open(self, sender, args):
  226. """
  227. Internal handler for opening the device.
  228. """
  229. self.on_open(args)
  230. def _on_close(self, sender, args):
  231. """
  232. Internal handler for closing the device.
  233. """
  234. self.on_close(args)
  235. def _on_read(self, sender, args):
  236. """
  237. Internal handler for reading from the device.
  238. """
  239. self.on_read(args)
  240. msg = self._handle_message(args)
  241. if msg:
  242. self.on_message(msg)
  243. def _on_write(self, sender, args):
  244. """
  245. Internal handler for writing to the device.
  246. """
  247. self.on_write(args)
  248. class Message(object):
  249. """
  250. Represents a message from the alarm panel.
  251. """
  252. def __init__(self, data=None):
  253. """
  254. Constructor
  255. """
  256. self.ready = False
  257. self.armed_away = False
  258. self.armed_home = False
  259. self.backlight_on = False
  260. self.programming_mode = False
  261. self.beeps = -1
  262. self.zone_bypassed = False
  263. self.ac_power = False
  264. self.chime_on = False
  265. self.alarm_event_occurred = False
  266. self.alarm_sounding = False
  267. self.numeric_code = ""
  268. self.text = ""
  269. self.cursor_location = -1
  270. self.data = ""
  271. self.mask = ""
  272. self.bitfield = ""
  273. self.panel_data = ""
  274. self._regex = re.compile('("(?:[^"]|"")*"|[^,]*),("(?:[^"]|"")*"|[^,]*),("(?:[^"]|"")*"|[^,]*),("(?:[^"]|"")*"|[^,]*)')
  275. if data is not None:
  276. self._parse_message(data)
  277. def _parse_message(self, data):
  278. """
  279. Parse the message from the device.
  280. """
  281. m = self._regex.match(data)
  282. if m is None:
  283. raise util.InvalidMessageError('Received invalid message: {0}'.format(data))
  284. self.bitfield, self.numeric_code, self.panel_data, alpha = m.group(1, 2, 3, 4)
  285. self.mask = int(self.panel_data[3:3+8], 16)
  286. self.data = data
  287. self.ready = not self.bitfield[1:2] == "0"
  288. self.armed_away = not self.bitfield[2:3] == "0"
  289. self.armed_home = not self.bitfield[3:4] == "0"
  290. self.backlight_on = not self.bitfield[4:5] == "0"
  291. self.programming_mode = not self.bitfield[5:6] == "0"
  292. self.beeps = int(self.bitfield[6:7], 16)
  293. self.zone_bypassed = not self.bitfield[7:8] == "0"
  294. self.ac_power = not self.bitfield[8:9] == "0"
  295. self.chime_on = not self.bitfield[9:10] == "0"
  296. self.alarm_event_occurred = not self.bitfield[10:11] == "0"
  297. self.alarm_sounding = not self.bitfield[11:12] == "0"
  298. self.text = alpha.strip('"')
  299. if int(self.panel_data[19:21], 16) & 0x01 > 0:
  300. self.cursor_location = int(self.bitfield[21:23], 16) # Alpha character index that the cursor is on.
  301. def __str__(self):
  302. """
  303. String conversion operator.
  304. """
  305. return 'msg > {0:0<9} [{1}{2}{3}] -- ({4}) {5}'.format(hex(self.mask), 1 if self.ready else 0, 1 if self.armed_away else 0, 1 if self.armed_home else 0, self.numeric_code, self.text)
  306. class ExpanderMessage(object):
  307. """
  308. Represents a message from a zone or relay expansion module.
  309. """
  310. ZONE = 0
  311. RELAY = 1
  312. def __init__(self, data=None):
  313. """
  314. Constructor
  315. """
  316. self.type = None
  317. self.address = None
  318. self.channel = None
  319. self.value = None
  320. self.raw = None
  321. if data is not None:
  322. self._parse_message(data)
  323. def __str__(self):
  324. """
  325. String conversion operator.
  326. """
  327. expander_type = 'UNKWN'
  328. if self.type == ExpanderMessage.ZONE:
  329. expander_type = 'ZONE'
  330. elif self.type == ExpanderMessage.RELAY:
  331. expander_type = 'RELAY'
  332. return 'exp > [{0: <5}] {1}/{2} -- {3}'.format(expander_type, self.address, self.channel, self.value)
  333. def _parse_message(self, data):
  334. """
  335. Parse the raw message from the device.
  336. """
  337. header, values = data.split(':')
  338. address, channel, value = values.split(',')
  339. self.raw = data
  340. self.address = address
  341. self.channel = channel
  342. self.value = value
  343. if header == '!EXP':
  344. self.type = ExpanderMessage.ZONE
  345. elif header == '!REL':
  346. self.type = ExpanderMessage.RELAY
  347. class RFMessage(object):
  348. """
  349. Represents a message from an RF receiver.
  350. """
  351. def __init__(self, data=None):
  352. """
  353. Constructor
  354. """
  355. self.raw = None
  356. self.serial_number = None
  357. self.value = None
  358. if data is not None:
  359. self._parse_message(data)
  360. def __str__(self):
  361. """
  362. String conversion operator.
  363. """
  364. return 'rf > {0}: {1}'.format(self.serial_number, self.value)
  365. def _parse_message(self, data):
  366. """
  367. Parses the raw message from the device.
  368. """
  369. self.raw = data
  370. _, values = data.split(':')
  371. self.serial_number, self.value = values.split(',')
  372. class LRRMessage(object):
  373. """
  374. Represent a message from a Long Range Radio.
  375. """
  376. def __init__(self, data=None):
  377. """
  378. Constructor
  379. """
  380. self.raw = None
  381. self._event_data = None
  382. self._partition = None
  383. self._event_type = None
  384. if data is not None:
  385. self._parse_message(data)
  386. def __str__(self):
  387. """
  388. String conversion operator.
  389. """
  390. return 'lrr > {0} @ {1} -- {2}'.format()
  391. def _parse_message(self, data):
  392. """
  393. Parses the raw message from the device.
  394. """
  395. self.raw = data
  396. _, values = data.split(':')
  397. self._event_data, self._partition, self._event_type = values.split(',')