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.

847 lines
29 KiB

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