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.

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