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.

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