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.

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