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.

553 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. @property
  152. def id(self):
  153. return self._device.id
  154. def open(self, baudrate=None, interface=None, index=None, no_reader_thread=False):
  155. """
  156. Opens the device.
  157. """
  158. self._wire_events()
  159. self._device.open(baudrate=baudrate, interface=interface, index=index, no_reader_thread=no_reader_thread)
  160. def close(self):
  161. """
  162. Closes the device.
  163. """
  164. self._device.close()
  165. self._device = None
  166. def get_config(self):
  167. """
  168. Retrieves the configuration from the device.
  169. """
  170. self._device.write("C\r")
  171. def save_config(self):
  172. """
  173. Sets configuration entries on the device.
  174. """
  175. config_string = ''
  176. # HACK: Both of these methods are ugly.. but I can't think of an elegant way of doing it.
  177. #config_string += 'ADDRESS={0}&'.format(self.address)
  178. #config_string += 'CONFIGBITS={0:x}&'.format(self.configbits)
  179. #config_string += 'MASK={0:x}&'.format(self.address_mask)
  180. #config_string += 'EXP={0}&'.format(''.join(['Y' if z else 'N' for z in self.emulate_zone]))
  181. #config_string += 'REL={0}&'.format(''.join(['Y' if r else 'N' for r in self.emulate_relay]))
  182. #config_string += 'LRR={0}&'.format('Y' if self.emulate_lrr else 'N')
  183. #config_string += 'DEDUPLICATE={0}'.format('Y' if self.deduplicate else 'N')
  184. config_entries = []
  185. config_entries.append(('ADDRESS', '{0}'.format(self.address)))
  186. config_entries.append(('CONFIGBITS', '{0:x}'.format(self.configbits)))
  187. config_entries.append(('MASK', '{0:x}'.format(self.address_mask)))
  188. config_entries.append(('EXP', ''.join(['Y' if z else 'N' for z in self.emulate_zone])))
  189. config_entries.append(('REL', ''.join(['Y' if r else 'N' for r in self.emulate_relay])))
  190. config_entries.append(('LRR', 'Y' if self.emulate_lrr else 'N'))
  191. config_entries.append(('DEDUPLICATE', 'Y' if self.deduplicate else 'N'))
  192. config_string = '&'.join(['='.join(t) for t in config_entries])
  193. self._device.write("C{0}\r".format(config_string))
  194. def reboot(self):
  195. """
  196. Reboots the device.
  197. """
  198. self._device.write('=')
  199. def fault_zone(self, zone, simulate_wire_problem=False):
  200. """
  201. Faults a zone if we are emulating a zone expander.
  202. """
  203. status = 2 if simulate_wire_problem else 1
  204. self._device.write("L{0:02}{1}".format(zone, status))
  205. def clear_zone(self, zone):
  206. """
  207. Clears a zone if we are emulating a zone expander.
  208. """
  209. self._device.write("L{0:02}0".format(zone))
  210. def _wire_events(self):
  211. """
  212. Wires up the internal device events.
  213. """
  214. self._device.on_open += self._on_open
  215. self._device.on_close += self._on_close
  216. self._device.on_read += self._on_read
  217. self._device.on_write += self._on_write
  218. def _handle_message(self, data):
  219. """
  220. Parses messages from the panel.
  221. """
  222. if data is None:
  223. return None
  224. msg = None
  225. if data[0] != '!':
  226. msg = Message(data)
  227. if self.address_mask & msg.mask > 0:
  228. self._update_internal_states(msg)
  229. else: # specialty messages
  230. header = data[0:4]
  231. if header == '!EXP' or header == '!REL':
  232. msg = ExpanderMessage(data)
  233. elif header == '!RFX':
  234. msg = RFMessage(data)
  235. elif header == '!LRR':
  236. msg = LRRMessage(data)
  237. elif data.startswith('!Ready'):
  238. self.on_boot()
  239. elif data.startswith('!CONFIG'):
  240. self._handle_config(data)
  241. return msg
  242. def _handle_config(self, data):
  243. _, config_string = data.split('>')
  244. for setting in config_string.split('&'):
  245. k, v = setting.split('=')
  246. if k == 'ADDRESS':
  247. self.address = int(v)
  248. elif k == 'CONFIGBITS':
  249. self.configbits = int(v, 16)
  250. elif k == 'MASK':
  251. self.address_mask = int(v, 16)
  252. elif k == 'EXP':
  253. for z in range(5):
  254. self.emulate_zone[z] = True if v[z] == 'Y' else False
  255. elif k == 'REL':
  256. for r in range(4):
  257. self.emulate_relay[r] = True if v[r] == 'Y' else False
  258. elif k == 'LRR':
  259. self.emulate_lrr = True if v == 'Y' else False
  260. elif k == 'DEDUPLICATE':
  261. self.deduplicate = True if v == 'Y' else False
  262. self.on_config_received()
  263. def _update_internal_states(self, message):
  264. if message.ac_power != self._power_status:
  265. self._power_status, old_status = message.ac_power, self._power_status
  266. if old_status is not None:
  267. self.on_power_changed(self._power_status)
  268. if message.alarm_sounding != self._alarm_status:
  269. self._alarm_status, old_status = message.alarm_sounding, self._alarm_status
  270. if old_status is not None:
  271. self.on_alarm(self._alarm_status)
  272. if message.zone_bypassed != self._bypass_status:
  273. self._bypass_status, old_status = message.zone_bypassed, self._bypass_status
  274. if old_status is not None:
  275. self.on_bypass(self._bypass_status)
  276. def _on_open(self, sender, args):
  277. """
  278. Internal handler for opening the device.
  279. """
  280. self.on_open(args)
  281. def _on_close(self, sender, args):
  282. """
  283. Internal handler for closing the device.
  284. """
  285. self.on_close(args)
  286. def _on_read(self, sender, args):
  287. """
  288. Internal handler for reading from the device.
  289. """
  290. self.on_read(args)
  291. msg = self._handle_message(args)
  292. if msg:
  293. self.on_message(msg)
  294. def _on_write(self, sender, args):
  295. """
  296. Internal handler for writing to the device.
  297. """
  298. self.on_write(args)
  299. class Message(object):
  300. """
  301. Represents a message from the alarm panel.
  302. """
  303. def __init__(self, data=None):
  304. """
  305. Constructor
  306. """
  307. self.ready = False
  308. self.armed_away = False
  309. self.armed_home = False
  310. self.backlight_on = False
  311. self.programming_mode = False
  312. self.beeps = -1
  313. self.zone_bypassed = False
  314. self.ac_power = False
  315. self.chime_on = False
  316. self.alarm_event_occurred = False
  317. self.alarm_sounding = False
  318. self.numeric_code = ""
  319. self.text = ""
  320. self.cursor_location = -1
  321. self.data = ""
  322. self.mask = ""
  323. self.bitfield = ""
  324. self.panel_data = ""
  325. self._regex = re.compile('("(?:[^"]|"")*"|[^,]*),("(?:[^"]|"")*"|[^,]*),("(?:[^"]|"")*"|[^,]*),("(?:[^"]|"")*"|[^,]*)')
  326. if data is not None:
  327. self._parse_message(data)
  328. def _parse_message(self, data):
  329. """
  330. Parse the message from the device.
  331. """
  332. m = self._regex.match(data)
  333. if m is None:
  334. raise util.InvalidMessageError('Received invalid message: {0}'.format(data))
  335. self.bitfield, self.numeric_code, self.panel_data, alpha = m.group(1, 2, 3, 4)
  336. self.mask = int(self.panel_data[3:3+8], 16)
  337. self.data = data
  338. self.ready = not self.bitfield[1:2] == "0"
  339. self.armed_away = not self.bitfield[2:3] == "0"
  340. self.armed_home = not self.bitfield[3:4] == "0"
  341. self.backlight_on = not self.bitfield[4:5] == "0"
  342. self.programming_mode = not self.bitfield[5:6] == "0"
  343. self.beeps = int(self.bitfield[6:7], 16)
  344. self.zone_bypassed = not self.bitfield[7:8] == "0"
  345. self.ac_power = not self.bitfield[8:9] == "0"
  346. self.chime_on = not self.bitfield[9:10] == "0"
  347. self.alarm_event_occurred = not self.bitfield[10:11] == "0"
  348. self.alarm_sounding = not self.bitfield[11:12] == "0"
  349. self.text = alpha.strip('"')
  350. if int(self.panel_data[19:21], 16) & 0x01 > 0:
  351. self.cursor_location = int(self.bitfield[21:23], 16) # Alpha character index that the cursor is on.
  352. def __str__(self):
  353. """
  354. String conversion operator.
  355. """
  356. 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)
  357. class ExpanderMessage(object):
  358. """
  359. Represents a message from a zone or relay expansion module.
  360. """
  361. ZONE = 0
  362. RELAY = 1
  363. def __init__(self, data=None):
  364. """
  365. Constructor
  366. """
  367. self.type = None
  368. self.address = None
  369. self.channel = None
  370. self.value = None
  371. self.raw = None
  372. if data is not None:
  373. self._parse_message(data)
  374. def __str__(self):
  375. """
  376. String conversion operator.
  377. """
  378. expander_type = 'UNKWN'
  379. if self.type == ExpanderMessage.ZONE:
  380. expander_type = 'ZONE'
  381. elif self.type == ExpanderMessage.RELAY:
  382. expander_type = 'RELAY'
  383. return 'exp > [{0: <5}] {1}/{2} -- {3}'.format(expander_type, self.address, self.channel, self.value)
  384. def _parse_message(self, data):
  385. """
  386. Parse the raw message from the device.
  387. """
  388. header, values = data.split(':')
  389. address, channel, value = values.split(',')
  390. self.raw = data
  391. self.address = address
  392. self.channel = channel
  393. self.value = value
  394. if header == '!EXP':
  395. self.type = ExpanderMessage.ZONE
  396. elif header == '!REL':
  397. self.type = ExpanderMessage.RELAY
  398. class RFMessage(object):
  399. """
  400. Represents a message from an RF receiver.
  401. """
  402. def __init__(self, data=None):
  403. """
  404. Constructor
  405. """
  406. self.raw = None
  407. self.serial_number = None
  408. self.value = None
  409. if data is not None:
  410. self._parse_message(data)
  411. def __str__(self):
  412. """
  413. String conversion operator.
  414. """
  415. return 'rf > {0}: {1}'.format(self.serial_number, self.value)
  416. def _parse_message(self, data):
  417. """
  418. Parses the raw message from the device.
  419. """
  420. self.raw = data
  421. _, values = data.split(':')
  422. self.serial_number, self.value = values.split(',')
  423. class LRRMessage(object):
  424. """
  425. Represent a message from a Long Range Radio.
  426. """
  427. def __init__(self, data=None):
  428. """
  429. Constructor
  430. """
  431. self.raw = None
  432. self._event_data = None
  433. self._partition = None
  434. self._event_type = None
  435. if data is not None:
  436. self._parse_message(data)
  437. def __str__(self):
  438. """
  439. String conversion operator.
  440. """
  441. return 'lrr > {0} @ {1} -- {2}'.format()
  442. def _parse_message(self, data):
  443. """
  444. Parses the raw message from the device.
  445. """
  446. self.raw = data
  447. _, values = data.split(':')
  448. self._event_data, self._partition, self._event_type = values.split(',')