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.

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