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.

687 lines
23 KiB

  1. """
  2. Provides the main AlarmDecoder class.
  3. .. _AlarmDecoder: http://www.alarmdecoder.com
  4. .. moduleauthor:: Scott Petersen <scott@nutech.com>
  5. """
  6. import time
  7. import re
  8. from .event import event
  9. from .util import InvalidMessageError
  10. from .messages import Message, ExpanderMessage, RFMessage, LRRMessage
  11. from .zonetracking import Zonetracker
  12. from .panels import PANEL_TYPES, ADEMCO, DSC
  13. class AlarmDecoder(object):
  14. """
  15. High-level wrapper around `AlarmDecoder`_ (AD2) devices.
  16. """
  17. # High-level Events
  18. on_arm = event.Event("This event is called when the panel is armed.\n\n**Callback definition:** *def callback(device)*")
  19. on_disarm = event.Event("This event is called when the panel is disarmed.\n\n**Callback definition:** *def callback(device)*")
  20. on_power_changed = event.Event("This event is called when panel power switches between AC and DC.\n\n**Callback definition:** *def callback(device, status)*")
  21. on_alarm = event.Event("This event is called when the alarm is triggered.\n\n**Callback definition:** *def callback(device, zone)*")
  22. on_alarm_restored = event.Event("This event is called when the alarm stops sounding.\n\n**Callback definition:** *def callback(device, zone)*")
  23. on_fire = event.Event("This event is called when a fire is detected.\n\n**Callback definition:** *def callback(device, status)*")
  24. on_bypass = event.Event("This event is called when a zone is bypassed. \n\n\n\n**Callback definition:** *def callback(device, status)*")
  25. on_boot = event.Event("This event is called when the device finishes booting.\n\n**Callback definition:** *def callback(device)*")
  26. on_config_received = event.Event("This event is called when the device receives its configuration. \n\n**Callback definition:** *def callback(device)*")
  27. on_zone_fault = event.Event("This event is called when :py:class:`~alarmdecoder.zonetracking.Zonetracker` detects a zone fault.\n\n**Callback definition:** *def callback(device, zone)*")
  28. on_zone_restore = event.Event("This event is called when :py:class:`~alarmdecoder.zonetracking.Zonetracker` detects that a fault is restored.\n\n**Callback definition:** *def callback(device, zone)*")
  29. on_low_battery = event.Event("This event is called when the device detects a low battery.\n\n**Callback definition:** *def callback(device, status)*")
  30. on_panic = event.Event("This event is called when the device detects a panic.\n\n**Callback definition:** *def callback(device, status)*")
  31. on_relay_changed = event.Event("This event is called when a relay is opened or closed on an expander board.\n\n**Callback definition:** *def callback(device, message)*")
  32. # Mid-level Events
  33. on_message = event.Event("This event is called when standard panel :py:class:`~alarmdecoder.messages.Message` is received.\n\n**Callback definition:** *def callback(device, message)*")
  34. on_expander_message = event.Event("This event is called when an :py:class:`~alarmdecoder.messages.ExpanderMessage` is received.\n\n**Callback definition:** *def callback(device, message)*")
  35. on_lrr_message = event.Event("This event is called when an :py:class:`~alarmdecoder.messages.LRRMessage` is received.\n\n**Callback definition:** *def callback(device, message)*")
  36. on_rfx_message = event.Event("This event is called when an :py:class:`~alarmdecoder.messages.RFMessage` is received.\n\n**Callback definition:** *def callback(device, message)*")
  37. on_sending_received = event.Event("This event is called when a !Sending.done message is received from the AlarmDecoder.\n\n**Callback definition:** *def callback(device, status, message)*")
  38. # Low-level Events
  39. on_open = event.Event("This event is called when the device has been opened.\n\n**Callback definition:** *def callback(device)*")
  40. on_close = event.Event("This event is called when the device has been closed.\n\n**Callback definition:** *def callback(device)*")
  41. on_read = event.Event("This event is called when a line has been read from the device.\n\n**Callback definition:** *def callback(device, data)*")
  42. on_write = event.Event("This event is called when data has been written to the device.\n\n**Callback definition:** *def callback(device, data)*")
  43. # Constants
  44. KEY_F1 = unichr(1) + unichr(1) + unichr(1)
  45. """Represents panel function key #1"""
  46. KEY_F2 = unichr(2) + unichr(2) + unichr(2)
  47. """Represents panel function key #2"""
  48. KEY_F3 = unichr(3) + unichr(3) + unichr(3)
  49. """Represents panel function key #3"""
  50. KEY_F4 = unichr(4) + unichr(4) + unichr(4)
  51. """Represents panel function key #4"""
  52. KEY_PANIC = unichr(5) + unichr(5) + unichr(5)
  53. """Represents a panic keypress"""
  54. BATTERY_TIMEOUT = 30
  55. """Default timeout (in seconds) before the battery status reverts."""
  56. FIRE_TIMEOUT = 30
  57. """Default tTimeout (in seconds) before the fire status reverts."""
  58. # Attributes
  59. address = 18
  60. """The keypad address in use by the device."""
  61. configbits = 0xFF00
  62. """The configuration bits set on the device."""
  63. address_mask = 0xFFFFFFFF
  64. """The address mask configured on the device."""
  65. emulate_zone = [False for _ in range(5)]
  66. """List containing the devices zone emulation status."""
  67. emulate_relay = [False for _ in range(4)]
  68. """List containing the devices relay emulation status."""
  69. emulate_lrr = False
  70. """The status of the devices LRR emulation."""
  71. deduplicate = False
  72. """The status of message deduplication as configured on the device."""
  73. mode = ADEMCO
  74. """The panel mode that the AlarmDecoder is in. Currently supports ADEMCO and DSC."""
  75. def __init__(self, device):
  76. """
  77. Constructor
  78. :param device: The low-level device used for this `AlarmDecoder`_
  79. interface.
  80. :type device: Device
  81. """
  82. self._device = device
  83. self._zonetracker = Zonetracker(self)
  84. self._battery_timeout = AlarmDecoder.BATTERY_TIMEOUT
  85. self._fire_timeout = AlarmDecoder.FIRE_TIMEOUT
  86. self._power_status = None
  87. self._alarm_status = None
  88. self._bypass_status = None
  89. self._armed_status = None
  90. self._fire_status = (False, 0)
  91. self._battery_status = (False, 0)
  92. self._panic_status = False
  93. self._relay_status = {}
  94. self._internal_address_mask = 0xFFFFFFFF
  95. self.address = 18
  96. self.configbits = 0xFF00
  97. self.address_mask = 0xFFFFFFFF
  98. self.emulate_zone = [False for x in range(5)]
  99. self.emulate_relay = [False for x in range(4)]
  100. self.emulate_lrr = False
  101. self.deduplicate = False
  102. self.mode = ADEMCO
  103. def __enter__(self):
  104. """
  105. Support for context manager __enter__.
  106. """
  107. return self
  108. def __exit__(self, exc_type, exc_value, traceback):
  109. """
  110. Support for context manager __exit__.
  111. """
  112. self.close()
  113. return False
  114. @property
  115. def id(self):
  116. """
  117. The ID of the `AlarmDecoder`_ device.
  118. :returns: identification string for the device
  119. """
  120. return self._device.id
  121. @property
  122. def battery_timeout(self):
  123. """
  124. Retrieves the timeout for restoring the battery status, in seconds.
  125. :returns: battery status timeout
  126. """
  127. return self._battery_timeout
  128. @battery_timeout.setter
  129. def battery_timeout(self, value):
  130. """
  131. Sets the timeout for restoring the battery status, in seconds.
  132. :param value: timeout in seconds
  133. :type value: int
  134. """
  135. self._battery_timeout = value
  136. @property
  137. def fire_timeout(self):
  138. """
  139. Retrieves the timeout for restoring the fire status, in seconds.
  140. :returns: fire status timeout
  141. """
  142. return self._fire_timeout
  143. @fire_timeout.setter
  144. def fire_timeout(self, value):
  145. """
  146. Sets the timeout for restoring the fire status, in seconds.
  147. :param value: timeout in seconds
  148. :type value: int
  149. """
  150. self._fire_timeout = value
  151. @property
  152. def internal_address_mask(self):
  153. """
  154. Retrieves the address mask used for updating internal status.
  155. :returns: address mask
  156. """
  157. return self._internal_address_mask
  158. @internal_address_mask.setter
  159. def internal_address_mask(self, value):
  160. """
  161. Sets the address mask used internally for updating status.
  162. :param value: address mask
  163. :type value: int
  164. """
  165. self._internal_address_mask = value
  166. def open(self, baudrate=None, no_reader_thread=False):
  167. """
  168. Opens the device.
  169. :param baudrate: baudrate used for the device. Defaults to the lower-level device default.
  170. :type baudrate: int
  171. :param no_reader_thread: Specifies whether or not the automatic reader
  172. thread should be started.
  173. :type no_reader_thread: bool
  174. """
  175. self._wire_events()
  176. self._device.open(baudrate=baudrate, no_reader_thread=no_reader_thread)
  177. return self
  178. def close(self):
  179. """
  180. Closes the device.
  181. """
  182. if self._device:
  183. self._device.close()
  184. del self._device
  185. self._device = None
  186. def send(self, data):
  187. """
  188. Sends data to the `AlarmDecoder`_ device.
  189. :param data: data to send
  190. :type data: string
  191. """
  192. if self._device:
  193. self._device.write(str(data))
  194. def get_config(self):
  195. """
  196. Retrieves the configuration from the device. Called automatically by :py:meth:`_on_open`.
  197. """
  198. self.send("C\r")
  199. def save_config(self):
  200. """
  201. Sets configuration entries on the device.
  202. """
  203. self.send("C{0}\r".format(self.get_config_string()))
  204. def get_config_string(self):
  205. config_entries = []
  206. # HACK: This is ugly.. but I can't think of an elegant way of doing it.
  207. config_entries.append(('ADDRESS', '{0}'.format(self.address)))
  208. config_entries.append(('CONFIGBITS', '{0:x}'.format(self.configbits)))
  209. config_entries.append(('MASK', '{0:x}'.format(self.address_mask)))
  210. config_entries.append(('EXP',
  211. ''.join(['Y' if z else 'N' for z in self.emulate_zone])))
  212. config_entries.append(('REL',
  213. ''.join(['Y' if r else 'N' for r in self.emulate_relay])))
  214. config_entries.append(('LRR', 'Y' if self.emulate_lrr else 'N'))
  215. config_entries.append(('DEDUPLICATE', 'Y' if self.deduplicate else 'N'))
  216. config_entries.append(('MODE', PANEL_TYPES.keys()[PANEL_TYPES.values().index(self.mode)]))
  217. return '&'.join(['='.join(t) for t in config_entries])
  218. def reboot(self):
  219. """
  220. Reboots the device.
  221. """
  222. self.send('=')
  223. def fault_zone(self, zone, simulate_wire_problem=False):
  224. """
  225. Faults a zone if we are emulating a zone expander.
  226. :param zone: zone to fault
  227. :type zone: int
  228. :param simulate_wire_problem: Whether or not to simulate a wire fault
  229. :type simulate_wire_problem: bool
  230. """
  231. # Allow ourselves to also be passed an address/channel combination
  232. # for zone expanders.
  233. #
  234. # Format (expander index, channel)
  235. if isinstance(zone, tuple):
  236. expander_idx, channel = zone
  237. zone = self._zonetracker.expander_to_zone(expander_idx, channel)
  238. status = 2 if simulate_wire_problem else 1
  239. self.send("L{0:02}{1}\r".format(zone, status))
  240. def clear_zone(self, zone):
  241. """
  242. Clears a zone if we are emulating a zone expander.
  243. :param zone: zone to clear
  244. :type zone: int
  245. """
  246. self.send("L{0:02}0\r".format(zone))
  247. def _wire_events(self):
  248. """
  249. Wires up the internal device events.
  250. """
  251. self._device.on_open += self._on_open
  252. self._device.on_close += self._on_close
  253. self._device.on_read += self._on_read
  254. self._device.on_write += self._on_write
  255. self._zonetracker.on_fault += self._on_zone_fault
  256. self._zonetracker.on_restore += self._on_zone_restore
  257. def _handle_message(self, data):
  258. """
  259. Parses keypad messages from the panel.
  260. :param data: keypad data to parse
  261. :type data: string
  262. :returns: :py:class:`~alarmdecoder.messages.Message`
  263. """
  264. if data is not None:
  265. data = data.lstrip('\0')
  266. if data is None or data == '':
  267. raise InvalidMessageError()
  268. msg = None
  269. header = data[0:4]
  270. if header[0] != '!' or header == '!KPM':
  271. msg = self._handle_keypad_message(data)
  272. elif header == '!EXP' or header == '!REL':
  273. msg = self._handle_expander_message(data)
  274. elif header == '!RFX':
  275. msg = self._handle_rfx(data)
  276. elif header == '!LRR':
  277. msg = self._handle_lrr(data)
  278. elif data.startswith('!Ready'):
  279. self.on_boot()
  280. elif data.startswith('!CONFIG'):
  281. self._handle_config(data)
  282. elif data.startswith('!Sending'):
  283. self._handle_sending(data)
  284. return msg
  285. def _handle_keypad_message(self, data):
  286. """
  287. Handle keypad messages.
  288. :param data: keypad message to parse
  289. :type data: string
  290. :returns: :py:class:`~alarmdecoder.messages.Message`
  291. """
  292. msg = Message(data)
  293. if self._internal_address_mask & msg.mask > 0:
  294. self._update_internal_states(msg)
  295. self.on_message(message=msg)
  296. return msg
  297. def _handle_expander_message(self, data):
  298. """
  299. Handle expander messages.
  300. :param data: expander message to parse
  301. :type data: string
  302. :returns: :py:class:`~alarmdecoder.messages.ExpanderMessage`
  303. """
  304. msg = ExpanderMessage(data)
  305. self._update_internal_states(msg)
  306. self.on_expander_message(message=msg)
  307. return msg
  308. def _handle_rfx(self, data):
  309. """
  310. Handle RF messages.
  311. :param data: RF message to parse
  312. :type data: string
  313. :returns: :py:class:`~alarmdecoder.messages.RFMessage`
  314. """
  315. msg = RFMessage(data)
  316. self.on_rfx_message(message=msg)
  317. return msg
  318. def _handle_lrr(self, data):
  319. """
  320. Handle Long Range Radio messages.
  321. :param data: LRR message to parse
  322. :type data: string
  323. :returns: :py:class:`~alarmdecoder.messages.LRRMessage`
  324. """
  325. msg = LRRMessage(data)
  326. if msg.event_type == 'ALARM_PANIC':
  327. self._panic_status = True
  328. self.on_panic(status=True)
  329. elif msg.event_type == 'CANCEL':
  330. if self._panic_status is True:
  331. self._panic_status = False
  332. self.on_panic(status=False)
  333. self.on_lrr_message(message=msg)
  334. return msg
  335. def _handle_config(self, data):
  336. """
  337. Handles received configuration data.
  338. :param data: Configuration string to parse
  339. :type data: string
  340. """
  341. _, config_string = data.split('>')
  342. for setting in config_string.split('&'):
  343. key, val = setting.split('=')
  344. if key == 'ADDRESS':
  345. self.address = int(val)
  346. elif key == 'CONFIGBITS':
  347. self.configbits = int(val, 16)
  348. elif key == 'MASK':
  349. self.address_mask = int(val, 16)
  350. elif key == 'EXP':
  351. self.emulate_zone = [val[z] == 'Y' for z in range(5)]
  352. elif key == 'REL':
  353. self.emulate_relay = [val[r] == 'Y' for r in range(4)]
  354. elif key == 'LRR':
  355. self.emulate_lrr = (val == 'Y')
  356. elif key == 'DEDUPLICATE':
  357. self.deduplicate = (val == 'Y')
  358. elif key == 'MODE':
  359. self.mode = PANEL_TYPES[val]
  360. self.on_config_received()
  361. def _handle_sending(self, data):
  362. """
  363. Handles results of a keypress send.
  364. :param data: Sending string to parse
  365. :type data: string
  366. """
  367. matches = re.match('^!Sending(\.{1,5})done.*', data)
  368. if matches is not None:
  369. good_send = False
  370. if len(matches.group(1)) < 5:
  371. good_send = True
  372. self.on_sending_received(status=good_send, message=data)
  373. def _update_internal_states(self, message):
  374. """
  375. Updates internal device states.
  376. :param message: :py:class:`~alarmdecoder.messages.Message` to update internal states with
  377. :type message: :py:class:`~alarmdecoder.messages.Message`, :py:class:`~alarmdecoder.messages.ExpanderMessage`, :py:class:`~alarmdecoder.messages.LRRMessage`, or :py:class:`~alarmdecoder.messages.RFMessage`
  378. """
  379. if isinstance(message, Message):
  380. self._update_power_status(message)
  381. self._update_alarm_status(message)
  382. self._update_zone_bypass_status(message)
  383. self._update_armed_status(message)
  384. self._update_battery_status(message)
  385. self._update_fire_status(message)
  386. elif isinstance(message, ExpanderMessage):
  387. self._update_expander_status(message)
  388. self._update_zone_tracker(message)
  389. def _update_power_status(self, message):
  390. """
  391. Uses the provided message to update the AC power state.
  392. :param message: message to use to update
  393. :type message: :py:class:`~alarmdecoder.messages.Message`
  394. :returns: bool indicating the new status
  395. """
  396. if message.ac_power != self._power_status:
  397. self._power_status, old_status = message.ac_power, self._power_status
  398. if old_status is not None:
  399. self.on_power_changed(status=self._power_status)
  400. return self._power_status
  401. def _update_alarm_status(self, message):
  402. """
  403. Uses the provided message to update the alarm state.
  404. :param message: message to use to update
  405. :type message: :py:class:`~alarmdecoder.messages.Message`
  406. :returns: bool indicating the new status
  407. """
  408. if message.alarm_sounding != self._alarm_status:
  409. self._alarm_status, old_status = message.alarm_sounding, self._alarm_status
  410. if old_status is not None:
  411. if self._alarm_status:
  412. self.on_alarm(zone=message.numeric_code)
  413. else:
  414. self.on_alarm_restored(zone=message.numeric_code)
  415. return self._alarm_status
  416. def _update_zone_bypass_status(self, message):
  417. """
  418. Uses the provided message to update the zone bypass state.
  419. :param message: message to use to update
  420. :type message: :py:class:`~alarmdecoder.messages.Message`
  421. :returns: bool indicating the new status
  422. """
  423. if message.zone_bypassed != self._bypass_status:
  424. self._bypass_status, old_status = message.zone_bypassed, self._bypass_status
  425. if old_status is not None:
  426. self.on_bypass(status=self._bypass_status)
  427. return self._bypass_status
  428. def _update_armed_status(self, message):
  429. """
  430. Uses the provided message to update the armed state.
  431. :param message: message to use to update
  432. :type message: :py:class:`~alarmdecoder.messages.Message`
  433. :returns: bool indicating the new status
  434. """
  435. message_status = message.armed_away | message.armed_home
  436. if message_status != self._armed_status:
  437. self._armed_status, old_status = message_status, self._armed_status
  438. if old_status is not None:
  439. if self._armed_status:
  440. self.on_arm()
  441. else:
  442. self.on_disarm()
  443. return self._armed_status
  444. def _update_battery_status(self, message):
  445. """
  446. Uses the provided message to update the battery state.
  447. :param message: message to use to update
  448. :type message: :py:class:`~alarmdecoder.messages.Message`
  449. :returns: boolean indicating the new status
  450. """
  451. last_status, last_update = self._battery_status
  452. if message.battery_low == last_status:
  453. self._battery_status = (last_status, time.time())
  454. else:
  455. if message.battery_low is True or time.time() > last_update + self._battery_timeout:
  456. self._battery_status = (message.battery_low, time.time())
  457. self.on_low_battery(status=message.battery_low)
  458. return self._battery_status[0]
  459. def _update_fire_status(self, message):
  460. """
  461. Uses the provided message to update the fire alarm state.
  462. :param message: message to use to update
  463. :type message: :py:class:`~alarmdecoder.messages.Message`
  464. :returns: boolean indicating the new status
  465. """
  466. last_status, last_update = self._fire_status
  467. if message.fire_alarm == last_status:
  468. self._fire_status = (last_status, time.time())
  469. else:
  470. if message.fire_alarm is True or time.time() > last_update + self._fire_timeout:
  471. self._fire_status = (message.fire_alarm, time.time())
  472. self.on_fire(status=message.fire_alarm)
  473. return self._fire_status[0]
  474. def _update_expander_status(self, message):
  475. """
  476. Uses the provided message to update the expander states.
  477. :param message: message to use to update
  478. :type message: :py:class:`~alarmdecoder.messages.ExpanderMessage`
  479. :returns: boolean indicating the new status
  480. """
  481. if message.type == ExpanderMessage.RELAY:
  482. self._relay_status[(message.address, message.channel)] = message.value
  483. self.on_relay_changed(message=message)
  484. return self._relay_status[(message.address, message.channel)]
  485. def _update_zone_tracker(self, message):
  486. """
  487. Trigger an update of the :py:class:`~alarmdecoder.messages.Zonetracker`.
  488. :param message: message to update the zonetracker with
  489. :type message: :py:class:`~alarmdecoder.messages.Message`, :py:class:`~alarmdecoder.messages.ExpanderMessage`, :py:class:`~alarmdecoder.messages.LRRMessage`, or :py:class:`~alarmdecoder.messages.RFMessage`
  490. """
  491. # Retrieve a list of faults.
  492. # NOTE: This only happens on first boot or after exiting programming mode.
  493. if isinstance(message, Message):
  494. if not message.ready and "Hit * for faults" in message.text:
  495. self.send('*')
  496. return
  497. self._zonetracker.update(message)
  498. def _on_open(self, sender, *args, **kwargs):
  499. """
  500. Internal handler for opening the device.
  501. """
  502. self.get_config()
  503. self.on_open()
  504. def _on_close(self, sender, *args, **kwargs):
  505. """
  506. Internal handler for closing the device.
  507. """
  508. self.on_close()
  509. def _on_read(self, sender, *args, **kwargs):
  510. """
  511. Internal handler for reading from the device.
  512. """
  513. data = kwargs.get('data', None)
  514. self.on_read(data=data)
  515. self._handle_message(data)
  516. def _on_write(self, sender, *args, **kwargs):
  517. """
  518. Internal handler for writing to the device.
  519. """
  520. self.on_write(data=kwargs.get('data', None))
  521. def _on_zone_fault(self, sender, *args, **kwargs):
  522. """
  523. Internal handler for zone faults.
  524. """
  525. self.on_zone_fault(*args, **kwargs)
  526. def _on_zone_restore(self, sender, *args, **kwargs):
  527. """
  528. Internal handler for zone restoration.
  529. """
  530. self.on_zone_restore(*args, **kwargs)