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.

539 lines
16 KiB

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