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.

704 lines
21 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 collections import OrderedDict
  9. from .event import event
  10. from . import devices
  11. from . import util
  12. class Overseer(object):
  13. """
  14. Factory for creation of AD2USB devices as well as provide4s attach/detach events."
  15. """
  16. # Factory events
  17. on_attached = event.Event('Called when an AD2USB device has been detected.')
  18. on_detached = event.Event('Called when an AD2USB device has been removed.')
  19. __devices = []
  20. @classmethod
  21. def find_all(cls):
  22. """
  23. Returns all AD2USB devices located on the system.
  24. """
  25. cls.__devices = devices.USBDevice.find_all()
  26. return cls.__devices
  27. @classmethod
  28. def devices(cls):
  29. """
  30. Returns a cached list of AD2USB devices located on the system.
  31. """
  32. return cls.__devices
  33. @classmethod
  34. def create(cls, device=None):
  35. """
  36. Factory method that returns the requested AD2USB device, or the first device.
  37. """
  38. cls.find_all()
  39. if len(cls.__devices) == 0:
  40. raise util.NoDeviceError('No AD2USB devices present.')
  41. if device is None:
  42. device = cls.__devices[0]
  43. vendor, product, sernum, ifcount, description = device
  44. device = devices.USBDevice(serial=sernum, description=description)
  45. return AD2USB(device)
  46. def __init__(self, attached_event=None, detached_event=None):
  47. """
  48. Constructor
  49. """
  50. self._detect_thread = Overseer.DetectThread(self)
  51. if attached_event:
  52. self.on_attached += attached_event
  53. if detached_event:
  54. self.on_detached += detached_event
  55. Overseer.find_all()
  56. self.start()
  57. def close(self):
  58. """
  59. Clean up and shut down.
  60. """
  61. self.stop()
  62. def start(self):
  63. """
  64. Starts the detection thread, if not already running.
  65. """
  66. if not self._detect_thread.is_alive():
  67. self._detect_thread.start()
  68. def stop(self):
  69. """
  70. Stops the detection thread.
  71. """
  72. self._detect_thread.stop()
  73. def get_device(self, device=None):
  74. """
  75. Factory method that returns the requested AD2USB device, or the first device.
  76. """
  77. return Overseer.create(device)
  78. class DetectThread(threading.Thread):
  79. """
  80. Thread that handles detection of added/removed devices.
  81. """
  82. def __init__(self, overseer):
  83. """
  84. Constructor
  85. """
  86. threading.Thread.__init__(self)
  87. self._overseer = overseer
  88. self._running = False
  89. def stop(self):
  90. """
  91. Stops the thread.
  92. """
  93. self._running = False
  94. def run(self):
  95. """
  96. The actual detection process.
  97. """
  98. self._running = True
  99. last_devices = set()
  100. while self._running:
  101. try:
  102. Overseer.find_all()
  103. current_devices = set(Overseer.devices())
  104. new_devices = [d for d in current_devices if d not in last_devices]
  105. removed_devices = [d for d in last_devices if d not in current_devices]
  106. last_devices = current_devices
  107. for d in new_devices:
  108. self._overseer.on_attached(d)
  109. for d in removed_devices:
  110. self._overseer.on_detached(d)
  111. except util.CommError, err:
  112. pass
  113. time.sleep(0.25)
  114. class AD2USB(object):
  115. """
  116. High-level wrapper around AD2USB/AD2SERIAL devices.
  117. """
  118. # High-level Events
  119. on_arm = event.Event('Called when the panel is armed.')
  120. on_disarm = event.Event('Called when the panel is disarmed.')
  121. on_power_changed = event.Event('Called when panel power switches between AC and DC.')
  122. on_alarm = event.Event('Called when the alarm is triggered.')
  123. on_fire = event.Event('Called when a fire is detected.')
  124. on_bypass = event.Event('Called when a zone is bypassed.')
  125. on_boot = event.Event('Called when the device finishes bootings.')
  126. on_config_received = event.Event('Called when the device receives its configuration.')
  127. on_fault = event.Event('Called when the device detects a zone fault.')
  128. on_restore = event.Event('Called when the device detects that a fault is restored.')
  129. # Mid-level Events
  130. on_message = event.Event('Called when a message has been received from the device.')
  131. # Low-level Events
  132. on_open = event.Event('Called when the device has been opened.')
  133. on_close = event.Event('Called when the device has been closed.')
  134. on_read = event.Event('Called when a line has been read from the device.')
  135. on_write = event.Event('Called when data has been written to the device.')
  136. # Constants
  137. F1 = unichr(1) + unichr(1) + unichr(1)
  138. F2 = unichr(2) + unichr(2) + unichr(2)
  139. F3 = unichr(3) + unichr(3) + unichr(3)
  140. F4 = unichr(4) + unichr(4) + unichr(4)
  141. ZONE_EXPIRE = 30
  142. def __init__(self, device):
  143. """
  144. Constructor
  145. """
  146. self._device = device
  147. self._power_status = None
  148. self._alarm_status = None
  149. self._bypass_status = None
  150. self._armed_status = None
  151. self._fire_status = None
  152. self._zones_faulted = []
  153. self._last_zone_fault = 0
  154. self.address = 18
  155. self.configbits = 0xFF00
  156. self.address_mask = 0x00000000
  157. self.emulate_zone = [False for x in range(5)]
  158. self.emulate_relay = [False for x in range(4)]
  159. self.emulate_lrr = False
  160. self.deduplicate = False
  161. @property
  162. def id(self):
  163. """
  164. The ID of the AD2USB device.
  165. """
  166. return self._device.id
  167. def open(self, baudrate=None, interface=None, index=None, no_reader_thread=False):
  168. """
  169. Opens the device.
  170. """
  171. self._wire_events()
  172. self._device.open(baudrate=baudrate, interface=interface, index=index, no_reader_thread=no_reader_thread)
  173. def close(self):
  174. """
  175. Closes the device.
  176. """
  177. self._device.close()
  178. del self._device
  179. self._device = None
  180. def get_config(self):
  181. """
  182. Retrieves the configuration from the device.
  183. """
  184. self._device.write("C\r")
  185. def save_config(self):
  186. """
  187. Sets configuration entries on the device.
  188. """
  189. config_string = ''
  190. # HACK: Both of these methods are ugly.. but I can't think of an elegant way of doing it.
  191. #config_string += 'ADDRESS={0}&'.format(self.address)
  192. #config_string += 'CONFIGBITS={0:x}&'.format(self.configbits)
  193. #config_string += 'MASK={0:x}&'.format(self.address_mask)
  194. #config_string += 'EXP={0}&'.format(''.join(['Y' if z else 'N' for z in self.emulate_zone]))
  195. #config_string += 'REL={0}&'.format(''.join(['Y' if r else 'N' for r in self.emulate_relay]))
  196. #config_string += 'LRR={0}&'.format('Y' if self.emulate_lrr else 'N')
  197. #config_string += 'DEDUPLICATE={0}'.format('Y' if self.deduplicate else 'N')
  198. config_entries = []
  199. config_entries.append(('ADDRESS', '{0}'.format(self.address)))
  200. config_entries.append(('CONFIGBITS', '{0:x}'.format(self.configbits)))
  201. config_entries.append(('MASK', '{0:x}'.format(self.address_mask)))
  202. config_entries.append(('EXP', ''.join(['Y' if z else 'N' for z in self.emulate_zone])))
  203. config_entries.append(('REL', ''.join(['Y' if r else 'N' for r in self.emulate_relay])))
  204. config_entries.append(('LRR', 'Y' if self.emulate_lrr else 'N'))
  205. config_entries.append(('DEDUPLICATE', 'Y' if self.deduplicate else 'N'))
  206. config_string = '&'.join(['='.join(t) for t in config_entries])
  207. self._device.write("C{0}\r".format(config_string))
  208. def reboot(self):
  209. """
  210. Reboots the device.
  211. """
  212. self._device.write('=')
  213. def fault_zone(self, zone, simulate_wire_problem=False):
  214. """
  215. Faults a zone if we are emulating a zone expander.
  216. """
  217. status = 2 if simulate_wire_problem else 1
  218. self._device.write("L{0:02}{1}\r".format(zone, status))
  219. def clear_zone(self, zone):
  220. """
  221. Clears a zone if we are emulating a zone expander.
  222. """
  223. self._device.write("L{0:02}0\r".format(zone))
  224. def _wire_events(self):
  225. """
  226. Wires up the internal device events.
  227. """
  228. self._device.on_open += self._on_open
  229. self._device.on_close += self._on_close
  230. self._device.on_read += self._on_read
  231. self._device.on_write += self._on_write
  232. def _handle_message(self, data):
  233. """
  234. Parses messages from the panel.
  235. """
  236. if data is None:
  237. return None
  238. msg = None
  239. if data[0] != '!':
  240. msg = Message(data)
  241. if self.address_mask & msg.mask > 0:
  242. self._update_internal_states(msg)
  243. else: # specialty messages
  244. header = data[0:4]
  245. if header == '!EXP' or header == '!REL':
  246. msg = ExpanderMessage(data)
  247. elif header == '!RFX':
  248. msg = RFMessage(data)
  249. elif header == '!LRR':
  250. msg = LRRMessage(data)
  251. elif data.startswith('!Ready'):
  252. self.on_boot()
  253. elif data.startswith('!CONFIG'):
  254. self._handle_config(data)
  255. return msg
  256. def _handle_config(self, data):
  257. """
  258. Handles received configuration data.
  259. """
  260. _, config_string = data.split('>')
  261. for setting in config_string.split('&'):
  262. k, v = setting.split('=')
  263. if k == 'ADDRESS':
  264. self.address = int(v)
  265. elif k == 'CONFIGBITS':
  266. self.configbits = int(v, 16)
  267. elif k == 'MASK':
  268. self.address_mask = int(v, 16)
  269. elif k == 'EXP':
  270. for z in range(5):
  271. self.emulate_zone[z] = True if v[z] == 'Y' else False
  272. elif k == 'REL':
  273. for r in range(4):
  274. self.emulate_relay[r] = True if v[r] == 'Y' else False
  275. elif k == 'LRR':
  276. self.emulate_lrr = True if v == 'Y' else False
  277. elif k == 'DEDUPLICATE':
  278. self.deduplicate = True if v == 'Y' else False
  279. self.on_config_received()
  280. def _update_internal_states(self, message):
  281. """
  282. Updates internal device states.
  283. """
  284. if message.ac_power != self._power_status:
  285. self._power_status, old_status = message.ac_power, self._power_status
  286. if old_status is not None:
  287. self.on_power_changed(self._power_status)
  288. if message.alarm_sounding != self._alarm_status:
  289. self._alarm_status, old_status = message.alarm_sounding, self._alarm_status
  290. if old_status is not None:
  291. self.on_alarm(self._alarm_status)
  292. if message.zone_bypassed != self._bypass_status:
  293. self._bypass_status, old_status = message.zone_bypassed, self._bypass_status
  294. if old_status is not None:
  295. self.on_bypass(self._bypass_status)
  296. if (message.armed_away | message.armed_home) != self._armed_status:
  297. self._armed_status, old_status = message.armed_away | message.armed_home, self._armed_status
  298. if old_status is not None:
  299. if self._armed_status:
  300. self.on_arm()
  301. else:
  302. self.on_disarm()
  303. if message.fire_alarm != self._fire_status:
  304. self._fire_status, old_status = message.fire_alarm, self._fire_status
  305. if old_status is not None:
  306. self.on_fire(self._fire_status)
  307. self._update_zone_status(message)
  308. def _update_zone_status(self, message):
  309. """
  310. Update zone statuses based on the current message.
  311. """
  312. # Retrieve a list of faults.
  313. # NOTE: This only happens on first boot or after exiting programming mode.
  314. if "Hit * for faults" in message.text:
  315. self._device.write('*')
  316. return
  317. # Panel is ready, restore all zones.
  318. if message.ready:
  319. for idx, z in enumerate(self._zones_faulted):
  320. self.on_restore(z)
  321. del self._zones_faulted[:]
  322. self._last_zone_fault = 0
  323. # Process fault
  324. elif "FAULT" in message.text:
  325. zone = -1
  326. # Apparently this representation can be both base 10
  327. # or base 16, depending on where the message came
  328. # from.
  329. try:
  330. zone = int(message.numeric_code)
  331. except ValueError:
  332. zone = int(message.numeric_code, 16)
  333. # Add new zones and clear expired ones.
  334. if zone in self._zones_faulted:
  335. self._clear_expired_zones(zone)
  336. else:
  337. self._zones_faulted.append(zone)
  338. self._zones_faulted.sort()
  339. self.on_fault(zone)
  340. # Save our spot for the next message.
  341. self._last_zone_fault = zone
  342. def _clear_expired_zones(self, zone):
  343. """
  344. Clear all expired zones from our status list.
  345. """
  346. cleared_zones = []
  347. found_last, found_new, at_end = False, False, False
  348. # First pass: Find our start spot.
  349. it = iter(self._zones_faulted)
  350. try:
  351. while not found_last:
  352. z = it.next()
  353. if z == self._last_zone_fault:
  354. found_last = True
  355. break
  356. except StopIteration:
  357. at_end = True
  358. # Continue until we find our end point and add zones in
  359. # between to our clear list.
  360. try:
  361. while not at_end and not found_new:
  362. z = it.next()
  363. if z == zone:
  364. found_new = True
  365. break
  366. else:
  367. cleared_zones += [z]
  368. except StopIteration:
  369. pass
  370. # Second pass: roll through the list again if we didn't find
  371. # our end point and remove everything until we do.
  372. if not found_new:
  373. it = iter(self._zones_faulted)
  374. try:
  375. while not found_new:
  376. z = it.next()
  377. if z == zone:
  378. found_new = True
  379. break
  380. else:
  381. cleared_zones += [z]
  382. except StopIteration:
  383. pass
  384. # Actually remove the zones and trigger the restores.
  385. for idx, z in enumerate(cleared_zones):
  386. self._zones_faulted.remove(z)
  387. self.on_restore(z)
  388. def _on_open(self, sender, args):
  389. """
  390. Internal handler for opening the device.
  391. """
  392. self.on_open(args)
  393. def _on_close(self, sender, args):
  394. """
  395. Internal handler for closing the device.
  396. """
  397. self.on_close(args)
  398. def _on_read(self, sender, args):
  399. """
  400. Internal handler for reading from the device.
  401. """
  402. self.on_read(args)
  403. msg = self._handle_message(args)
  404. if msg:
  405. self.on_message(msg)
  406. def _on_write(self, sender, args):
  407. """
  408. Internal handler for writing to the device.
  409. """
  410. self.on_write(args)
  411. class Message(object):
  412. """
  413. Represents a message from the alarm panel.
  414. """
  415. def __init__(self, data=None):
  416. """
  417. Constructor
  418. """
  419. self.ready = False
  420. self.armed_away = False
  421. self.armed_home = False
  422. self.backlight_on = False
  423. self.programming_mode = False
  424. self.beeps = -1
  425. self.zone_bypassed = False
  426. self.ac_power = False
  427. self.chime_on = False
  428. self.alarm_event_occurred = False
  429. self.alarm_sounding = False
  430. self.battery_low = False
  431. self.entry_delay_off = False
  432. self.fire_alarm = False
  433. self.check_zone = False
  434. self.perimeter_only = False
  435. self.numeric_code = ""
  436. self.text = ""
  437. self.cursor_location = -1
  438. self.data = ""
  439. self.mask = ""
  440. self.bitfield = ""
  441. self.panel_data = ""
  442. self._regex = re.compile('("(?:[^"]|"")*"|[^,]*),("(?:[^"]|"")*"|[^,]*),("(?:[^"]|"")*"|[^,]*),("(?:[^"]|"")*"|[^,]*)')
  443. if data is not None:
  444. self._parse_message(data)
  445. def _parse_message(self, data):
  446. """
  447. Parse the message from the device.
  448. """
  449. m = self._regex.match(data)
  450. if m is None:
  451. raise util.InvalidMessageError('Received invalid message: {0}'.format(data))
  452. self.bitfield, self.numeric_code, self.panel_data, alpha = m.group(1, 2, 3, 4)
  453. self.mask = int(self.panel_data[3:3+8], 16)
  454. self.data = data
  455. self.ready = not self.bitfield[1:2] == "0"
  456. self.armed_away = not self.bitfield[2:3] == "0"
  457. self.armed_home = not self.bitfield[3:4] == "0"
  458. self.backlight_on = not self.bitfield[4:5] == "0"
  459. self.programming_mode = not self.bitfield[5:6] == "0"
  460. self.beeps = int(self.bitfield[6:7], 16)
  461. self.zone_bypassed = not self.bitfield[7:8] == "0"
  462. self.ac_power = not self.bitfield[8:9] == "0"
  463. self.chime_on = not self.bitfield[9:10] == "0"
  464. self.alarm_event_occurred = not self.bitfield[10:11] == "0"
  465. self.alarm_sounding = not self.bitfield[11:12] == "0"
  466. self.battery_low = not self.bitfield[12:13] == "0"
  467. self.entry_delay_off = not self.bitfield[13:14] == "0"
  468. self.fire_alarm = not self.bitfield[14:15] == "0"
  469. self.check_zone = not self.bitfield[15:16] == "0"
  470. self.perimeter_only = not self.bitfield[16:17] == "0"
  471. # bits 17-20 unused.
  472. self.text = alpha.strip('"')
  473. if int(self.panel_data[19:21], 16) & 0x01 > 0:
  474. self.cursor_location = int(self.bitfield[21:23], 16) # Alpha character index that the cursor is on.
  475. def __str__(self):
  476. """
  477. String conversion operator.
  478. """
  479. 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)
  480. class ExpanderMessage(object):
  481. """
  482. Represents a message from a zone or relay expansion module.
  483. """
  484. ZONE = 0
  485. RELAY = 1
  486. def __init__(self, data=None):
  487. """
  488. Constructor
  489. """
  490. self.type = None
  491. self.address = None
  492. self.channel = None
  493. self.value = None
  494. self.raw = None
  495. if data is not None:
  496. self._parse_message(data)
  497. def __str__(self):
  498. """
  499. String conversion operator.
  500. """
  501. expander_type = 'UNKWN'
  502. if self.type == ExpanderMessage.ZONE:
  503. expander_type = 'ZONE'
  504. elif self.type == ExpanderMessage.RELAY:
  505. expander_type = 'RELAY'
  506. return 'exp > [{0: <5}] {1}/{2} -- {3}'.format(expander_type, self.address, self.channel, self.value)
  507. def _parse_message(self, data):
  508. """
  509. Parse the raw message from the device.
  510. """
  511. header, values = data.split(':')
  512. address, channel, value = values.split(',')
  513. self.raw = data
  514. self.address = address
  515. self.channel = channel
  516. self.value = value
  517. if header == '!EXP':
  518. self.type = ExpanderMessage.ZONE
  519. elif header == '!REL':
  520. self.type = ExpanderMessage.RELAY
  521. class RFMessage(object):
  522. """
  523. Represents a message from an RF receiver.
  524. """
  525. def __init__(self, data=None):
  526. """
  527. Constructor
  528. """
  529. self.raw = None
  530. self.serial_number = None
  531. self.value = None
  532. if data is not None:
  533. self._parse_message(data)
  534. def __str__(self):
  535. """
  536. String conversion operator.
  537. """
  538. return 'rf > {0}: {1}'.format(self.serial_number, self.value)
  539. def _parse_message(self, data):
  540. """
  541. Parses the raw message from the device.
  542. """
  543. self.raw = data
  544. _, values = data.split(':')
  545. self.serial_number, self.value = values.split(',')
  546. class LRRMessage(object):
  547. """
  548. Represent a message from a Long Range Radio.
  549. """
  550. def __init__(self, data=None):
  551. """
  552. Constructor
  553. """
  554. self.raw = None
  555. self._event_data = None
  556. self._partition = None
  557. self._event_type = None
  558. if data is not None:
  559. self._parse_message(data)
  560. def __str__(self):
  561. """
  562. String conversion operator.
  563. """
  564. return 'lrr > {0} @ {1} -- {2}'.format()
  565. def _parse_message(self, data):
  566. """
  567. Parses the raw message from the device.
  568. """
  569. self.raw = data
  570. _, values = data.split(':')
  571. self._event_data, self._partition, self._event_type = values.split(',')