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.

916 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. """
  215. Opens the device.
  216. :param baudrate: baudrate used for the device. Defaults to the lower-level device default.
  217. :type baudrate: int
  218. :param no_reader_thread: Specifies whether or not the automatic reader
  219. thread should be started.
  220. :type no_reader_thread: bool
  221. """
  222. self._wire_events()
  223. self._device.open(baudrate=baudrate, no_reader_thread=no_reader_thread)
  224. return self
  225. def close(self):
  226. """
  227. Closes the device.
  228. """
  229. if self._device:
  230. self._device.close()
  231. del self._device
  232. self._device = None
  233. def send(self, data):
  234. """
  235. Sends data to the `AlarmDecoder`_ device.
  236. :param data: data to send
  237. :type data: string
  238. """
  239. if self._device:
  240. if isinstance(data, str):
  241. data = str.encode(data)
  242. # Hack to support unicode under Python 2.x
  243. if sys.version_info < (3,):
  244. if isinstance(data, unicode):
  245. data = bytes(data)
  246. self._device.write(data)
  247. def get_config(self):
  248. """
  249. Retrieves the configuration from the device. Called automatically by :py:meth:`_on_open`.
  250. """
  251. self.send("C\r")
  252. def save_config(self):
  253. """
  254. Sets configuration entries on the device.
  255. """
  256. self.send("C{0}\r".format(self.get_config_string()))
  257. def get_config_string(self):
  258. """
  259. Build a configuration string that's compatible with the AlarmDecoder configuration
  260. command from the current values in the object.
  261. :returns: string
  262. """
  263. config_entries = []
  264. # HACK: This is ugly.. but I can't think of an elegant way of doing it.
  265. config_entries.append(('ADDRESS', '{0}'.format(self.address)))
  266. config_entries.append(('CONFIGBITS', '{0:x}'.format(self.configbits)))
  267. config_entries.append(('MASK', '{0:x}'.format(self.address_mask)))
  268. config_entries.append(('EXP',
  269. ''.join(['Y' if z else 'N' for z in self.emulate_zone])))
  270. config_entries.append(('REL',
  271. ''.join(['Y' if r else 'N' for r in self.emulate_relay])))
  272. config_entries.append(('LRR', 'Y' if self.emulate_lrr else 'N'))
  273. config_entries.append(('DEDUPLICATE', 'Y' if self.deduplicate else 'N'))
  274. config_entries.append(('MODE', list(PANEL_TYPES)[list(PANEL_TYPES.values()).index(self.mode)]))
  275. config_entries.append(('COM', 'Y' if self.emulate_com else 'N'))
  276. config_string = '&'.join(['='.join(t) for t in config_entries])
  277. return '&'.join(['='.join(t) for t in config_entries])
  278. def get_version(self):
  279. """
  280. Retrieves the version string from the device. Called automatically by :py:meth:`_on_open`.
  281. """
  282. self.send("V\r")
  283. def reboot(self):
  284. """
  285. Reboots the device.
  286. """
  287. self.send('=')
  288. def fault_zone(self, zone, simulate_wire_problem=False):
  289. """
  290. Faults a zone if we are emulating a zone expander.
  291. :param zone: zone to fault
  292. :type zone: int
  293. :param simulate_wire_problem: Whether or not to simulate a wire fault
  294. :type simulate_wire_problem: bool
  295. """
  296. # Allow ourselves to also be passed an address/channel combination
  297. # for zone expanders.
  298. #
  299. # Format (expander index, channel)
  300. if isinstance(zone, tuple):
  301. expander_idx, channel = zone
  302. zone = self._zonetracker.expander_to_zone(expander_idx, channel)
  303. status = 2 if simulate_wire_problem else 1
  304. self.send("L{0:02}{1}\r".format(zone, status))
  305. def clear_zone(self, zone):
  306. """
  307. Clears a zone if we are emulating a zone expander.
  308. :param zone: zone to clear
  309. :type zone: int
  310. """
  311. self.send("L{0:02}0\r".format(zone))
  312. def _wire_events(self):
  313. """
  314. Wires up the internal device events.
  315. """
  316. self._device.on_open += self._on_open
  317. self._device.on_close += self._on_close
  318. self._device.on_read += self._on_read
  319. self._device.on_write += self._on_write
  320. self._zonetracker.on_fault += self._on_zone_fault
  321. self._zonetracker.on_restore += self._on_zone_restore
  322. def _handle_message(self, data):
  323. """
  324. Parses keypad messages from the panel.
  325. :param data: keypad data to parse
  326. :type data: string
  327. :returns: :py:class:`~alarmdecoder.messages.Message`
  328. """
  329. data = data.decode('utf-8')
  330. if data is not None:
  331. data = data.lstrip('\0')
  332. if data is None or data == '':
  333. raise InvalidMessageError()
  334. msg = None
  335. header = data[0:4]
  336. if header[0] != '!' or header == '!KPM':
  337. msg = self._handle_keypad_message(data)
  338. elif header == '!EXP' or header == '!REL':
  339. msg = self._handle_expander_message(data)
  340. elif header == '!RFX':
  341. msg = self._handle_rfx(data)
  342. elif header == '!LRR':
  343. msg = self._handle_lrr(data)
  344. elif header == '!AUI':
  345. msg = self._handle_aui(data)
  346. elif data.startswith('!Ready'):
  347. self.on_boot()
  348. elif data.startswith('!CONFIG'):
  349. self._handle_config(data)
  350. elif data.startswith('!VER'):
  351. self._handle_version(data)
  352. elif data.startswith('!Sending'):
  353. self._handle_sending(data)
  354. return msg
  355. def _handle_keypad_message(self, data):
  356. """
  357. Handle keypad messages.
  358. :param data: keypad message to parse
  359. :type data: string
  360. :returns: :py:class:`~alarmdecoder.messages.Message`
  361. """
  362. msg = Message(data)
  363. if self._internal_address_mask & msg.mask > 0:
  364. if not self._ignore_message_states:
  365. self._update_internal_states(msg)
  366. else:
  367. self._update_fire_status(status=None)
  368. self.on_message(message=msg)
  369. return msg
  370. def _handle_expander_message(self, data):
  371. """
  372. Handle expander messages.
  373. :param data: expander message to parse
  374. :type data: string
  375. :returns: :py:class:`~alarmdecoder.messages.ExpanderMessage`
  376. """
  377. msg = ExpanderMessage(data)
  378. self._update_internal_states(msg)
  379. self.on_expander_message(message=msg)
  380. return msg
  381. def _handle_rfx(self, data):
  382. """
  383. Handle RF messages.
  384. :param data: RF message to parse
  385. :type data: string
  386. :returns: :py:class:`~alarmdecoder.messages.RFMessage`
  387. """
  388. msg = RFMessage(data)
  389. self.on_rfx_message(message=msg)
  390. return msg
  391. def _handle_lrr(self, data):
  392. """
  393. Handle Long Range Radio messages.
  394. :param data: LRR message to parse
  395. :type data: string
  396. :returns: :py:class:`~alarmdecoder.messages.LRRMessage`
  397. """
  398. msg = LRRMessage(data)
  399. self._lrr_system.update(msg)
  400. self.on_lrr_message(message=msg)
  401. return msg
  402. def _handle_aui(self, data):
  403. """
  404. Handle AUI messages.
  405. :param data: RF message to parse
  406. :type data: string
  407. :returns: :py:class`~alarmdecoder.messages.AUIMessage`
  408. """
  409. msg = AUIMessage(data)
  410. self.on_aui_message(message=msg)
  411. return msg
  412. def _handle_version(self, data):
  413. """
  414. Handles received version data.
  415. :param data: Version string to parse
  416. :type data: string
  417. """
  418. _, version_string = data.split(':')
  419. version_parts = version_string.split(',')
  420. self.serial_number = version_parts[0]
  421. self.version_number = version_parts[1]
  422. self.version_flags = version_parts[2]
  423. def _handle_config(self, data):
  424. """
  425. Handles received configuration data.
  426. :param data: Configuration string to parse
  427. :type data: string
  428. """
  429. _, config_string = data.split('>')
  430. for setting in config_string.split('&'):
  431. key, val = setting.split('=')
  432. if key == 'ADDRESS':
  433. self.address = int(val)
  434. elif key == 'CONFIGBITS':
  435. self.configbits = int(val, 16)
  436. elif key == 'MASK':
  437. self.address_mask = int(val, 16)
  438. elif key == 'EXP':
  439. self.emulate_zone = [val[z] == 'Y' for z in list(range(5))]
  440. elif key == 'REL':
  441. self.emulate_relay = [val[r] == 'Y' for r in list(range(4))]
  442. elif key == 'LRR':
  443. self.emulate_lrr = (val == 'Y')
  444. elif key == 'DEDUPLICATE':
  445. self.deduplicate = (val == 'Y')
  446. elif key == 'MODE':
  447. self.mode = PANEL_TYPES[val]
  448. elif key == 'COM':
  449. self.emulate_com = (val == 'Y')
  450. self.on_config_received()
  451. def _handle_sending(self, data):
  452. """
  453. Handles results of a keypress send.
  454. :param data: Sending string to parse
  455. :type data: string
  456. """
  457. matches = re.match('^!Sending(\.{1,5})done.*', data)
  458. if matches is not None:
  459. good_send = False
  460. if len(matches.group(1)) < 5:
  461. good_send = True
  462. self.on_sending_received(status=good_send, message=data)
  463. def _update_internal_states(self, message):
  464. """
  465. Updates internal device states.
  466. :param message: :py:class:`~alarmdecoder.messages.Message` to update internal states with
  467. :type message: :py:class:`~alarmdecoder.messages.Message`, :py:class:`~alarmdecoder.messages.ExpanderMessage`, :py:class:`~alarmdecoder.messages.LRRMessage`, or :py:class:`~alarmdecoder.messages.RFMessage`
  468. """
  469. if isinstance(message, Message) and not self._ignore_message_states:
  470. self._update_power_status(message)
  471. self._update_alarm_status(message)
  472. self._update_zone_bypass_status(message)
  473. self._update_armed_status(message)
  474. self._update_battery_status(message)
  475. self._update_fire_status(message)
  476. elif isinstance(message, ExpanderMessage):
  477. self._update_expander_status(message)
  478. self._update_zone_tracker(message)
  479. def _update_power_status(self, message=None, status=None):
  480. """
  481. Uses the provided message to update the AC power state.
  482. :param message: message to use to update
  483. :type message: :py:class:`~alarmdecoder.messages.Message`
  484. :param status: power status, overrides message bits.
  485. :type status: bool
  486. :returns: bool indicating the new status
  487. """
  488. power_status = status
  489. if isinstance(message, Message):
  490. power_status = message.ac_power
  491. if power_status is None:
  492. return
  493. if power_status != self._power_status:
  494. self._power_status, old_status = power_status, self._power_status
  495. if old_status is not None:
  496. self.on_power_changed(status=self._power_status)
  497. return self._power_status
  498. def _update_alarm_status(self, message=None, status=None, zone=None, user=None):
  499. """
  500. Uses the provided message to update the alarm state.
  501. :param message: message to use to update
  502. :type message: :py:class:`~alarmdecoder.messages.Message`
  503. :param status: alarm status, overrides message bits.
  504. :type status: bool
  505. :param user: user associated with alarm event
  506. :type user: string
  507. :returns: bool indicating the new status
  508. """
  509. alarm_status = status
  510. alarm_zone = zone
  511. if isinstance(message, Message):
  512. alarm_status = message.alarm_sounding
  513. alarm_zone = message.parse_numeric_code()
  514. if alarm_status != self._alarm_status:
  515. self._alarm_status, old_status = alarm_status, self._alarm_status
  516. if old_status is not None or status is not None:
  517. if self._alarm_status:
  518. self.on_alarm(zone=alarm_zone)
  519. else:
  520. self.on_alarm_restored(zone=alarm_zone, user=user)
  521. return self._alarm_status
  522. def _update_zone_bypass_status(self, message=None, status=None, zone=None):
  523. """
  524. Uses the provided message to update the zone bypass state.
  525. :param message: message to use to update
  526. :type message: :py:class:`~alarmdecoder.messages.Message`
  527. :param status: bypass status, overrides message bits.
  528. :type status: bool
  529. :param zone: zone associated with bypass event
  530. :type zone: int
  531. :returns: bool indicating the new status
  532. """
  533. bypass_status = status
  534. if isinstance(message, Message):
  535. bypass_status = message.zone_bypassed
  536. if bypass_status is None:
  537. return
  538. old_bypass_status = self._bypass_status.get(zone, None)
  539. if bypass_status != old_bypass_status:
  540. if bypass_status == False and zone is None:
  541. self._bypass_status = {}
  542. else:
  543. self._bypass_status[zone] = bypass_status
  544. if old_bypass_status is not None or message is None or (old_bypass_status is None and bypass_status is True):
  545. self.on_bypass(status=bypass_status, zone=zone)
  546. return bypass_status
  547. def _update_armed_status(self, message=None, status=None, status_stay=None):
  548. """
  549. Uses the provided message to update the armed state.
  550. :param message: message to use to update
  551. :type message: :py:class:`~alarmdecoder.messages.Message`
  552. :param status: armed status, overrides message bits
  553. :type status: bool
  554. :param status_stay: armed stay status, overrides message bits
  555. :type status_stay: bool
  556. :returns: bool indicating the new status
  557. """
  558. arm_status = status
  559. stay_status = status_stay
  560. if isinstance(message, Message):
  561. arm_status = message.armed_away
  562. stay_status = message.armed_home
  563. if arm_status is None or stay_status is None:
  564. return
  565. self._armed_status, old_status = arm_status, self._armed_status
  566. self._armed_stay, old_stay = stay_status, self._armed_stay
  567. if arm_status != old_status or stay_status != old_stay:
  568. if old_status is not None or message is None:
  569. if self._armed_status or self._armed_stay:
  570. self.on_arm(stay=stay_status)
  571. else:
  572. self.on_disarm()
  573. return self._armed_status or self._armed_stay
  574. def _update_battery_status(self, message=None, status=None):
  575. """
  576. Uses the provided message to update the battery state.
  577. :param message: message to use to update
  578. :type message: :py:class:`~alarmdecoder.messages.Message`
  579. :param status: battery status, overrides message bits
  580. :type status: bool
  581. :returns: boolean indicating the new status
  582. """
  583. battery_status = status
  584. if isinstance(message, Message):
  585. battery_status = message.battery_low
  586. if battery_status is None:
  587. return
  588. last_status, last_update = self._battery_status
  589. if battery_status == last_status:
  590. self._battery_status = (last_status, time.time())
  591. else:
  592. if battery_status is True or time.time() > last_update + self._battery_timeout:
  593. self._battery_status = (battery_status, time.time())
  594. self.on_low_battery(status=battery_status)
  595. return self._battery_status[0]
  596. def _update_fire_status(self, message=None, status=None):
  597. """
  598. Uses the provided message to update the fire alarm state.
  599. :param message: message to use to update
  600. :type message: :py:class:`~alarmdecoder.messages.Message`
  601. :param status: fire status, overrides message bits
  602. :type status: bool
  603. :returns: boolean indicating the new status
  604. """
  605. is_lrr = status is not None
  606. fire_status = status
  607. if isinstance(message, Message):
  608. fire_status = message.fire_alarm
  609. last_status, last_update = self._fire_status
  610. if self._fire_state == FireState.NONE:
  611. # Always move to a FIRE state if detected
  612. if fire_status == True:
  613. self._fire_state = FireState.ALARM
  614. self._fire_status = (fire_status, time.time())
  615. self.on_fire(status=FireState.ALARM)
  616. elif self._fire_state == FireState.ALARM:
  617. # If we've received an LRR CANCEL message, move to ACKNOWLEDGED
  618. if is_lrr and fire_status == False:
  619. self._fire_state = FireState.ACKNOWLEDGED
  620. self._fire_status = (fire_status, time.time())
  621. self.on_fire(status=FireState.ACKNOWLEDGED)
  622. else:
  623. # Handle bouncing status changes and timeout in order to revert back to NONE.
  624. if last_status != fire_status or fire_status == True:
  625. self._fire_status = (fire_status, time.time())
  626. if fire_status == False and time.time() > last_update + self._fire_timeout:
  627. self._fire_state = FireState.NONE
  628. self.on_fire(status=FireState.NONE)
  629. elif self._fire_state == FireState.ACKNOWLEDGED:
  630. # If we've received a second LRR FIRE message after a CANCEL, revert back to FIRE and trigger another event.
  631. if is_lrr and fire_status == True:
  632. self._fire_state = FireState.ALARM
  633. self._fire_status = (fire_status, time.time())
  634. self.on_fire(status=FireState.ALARM)
  635. else:
  636. # Handle bouncing status changes and timeout in order to revert back to NONE.
  637. if last_status != fire_status or fire_status == True:
  638. self._fire_status = (fire_status, time.time())
  639. if fire_status != True and time.time() > last_update + self._fire_timeout:
  640. self._fire_state = FireState.NONE
  641. self.on_fire(status=FireState.NONE)
  642. return self._fire_state == FireState.ALARM
  643. def _update_panic_status(self, status=None):
  644. """
  645. Updates the panic status of the alarm panel.
  646. :param status: status to use to update
  647. :type status: boolean
  648. :returns: boolean indicating the new status
  649. """
  650. if status is None:
  651. return
  652. if status != self._panic_status:
  653. self._panic_status, old_status = status, self._panic_status
  654. if old_status is not None:
  655. self.on_panic(status=self._panic_status)
  656. return self._panic_status
  657. def _update_expander_status(self, message):
  658. """
  659. Uses the provided message to update the expander states.
  660. :param message: message to use to update
  661. :type message: :py:class:`~alarmdecoder.messages.ExpanderMessage`
  662. :returns: boolean indicating the new status
  663. """
  664. if message.type == ExpanderMessage.RELAY:
  665. self._relay_status[(message.address, message.channel)] = message.value
  666. self.on_relay_changed(message=message)
  667. return self._relay_status[(message.address, message.channel)]
  668. def _update_zone_tracker(self, message):
  669. """
  670. Trigger an update of the :py:class:`~alarmdecoder.messages.Zonetracker`.
  671. :param message: message to update the zonetracker with
  672. :type message: :py:class:`~alarmdecoder.messages.Message`, :py:class:`~alarmdecoder.messages.ExpanderMessage`, :py:class:`~alarmdecoder.messages.LRRMessage`, or :py:class:`~alarmdecoder.messages.RFMessage`
  673. """
  674. # Retrieve a list of faults.
  675. # NOTE: This only happens on first boot or after exiting programming mode.
  676. if isinstance(message, Message):
  677. if not message.ready and ("Hit * for faults" in message.text or "Press * to show faults" in message.text):
  678. if time.time() > self.last_fault_expansion + self.fault_expansion_time_limit:
  679. self.last_fault_expansion = time.time()
  680. self.send('*')
  681. return
  682. self._zonetracker.update(message)
  683. def _on_open(self, sender, *args, **kwargs):
  684. """
  685. Internal handler for opening the device.
  686. """
  687. self.get_config()
  688. self.get_version()
  689. self.on_open()
  690. def _on_close(self, sender, *args, **kwargs):
  691. """
  692. Internal handler for closing the device.
  693. """
  694. self.on_close()
  695. def _on_read(self, sender, *args, **kwargs):
  696. """
  697. Internal handler for reading from the device.
  698. """
  699. data = kwargs.get('data', None)
  700. self.on_read(data=data)
  701. self._handle_message(data)
  702. def _on_write(self, sender, *args, **kwargs):
  703. """
  704. Internal handler for writing to the device.
  705. """
  706. self.on_write(data=kwargs.get('data', None))
  707. def _on_zone_fault(self, sender, *args, **kwargs):
  708. """
  709. Internal handler for zone faults.
  710. """
  711. self.on_zone_fault(*args, **kwargs)
  712. def _on_zone_restore(self, sender, *args, **kwargs):
  713. """
  714. Internal handler for zone restoration.
  715. """
  716. self.on_zone_restore(*args, **kwargs)