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.

433 lines
14 KiB

  1. """
  2. Provides the full AD2 class and factory.
  3. .. moduleauthor:: Scott Petersen <scott@nutech.com>
  4. """
  5. import time
  6. import threading
  7. from .event import event
  8. from .util import CommError, NoDeviceError
  9. from .messages import Message, ExpanderMessage, RFMessage, LRRMessage
  10. from .zonetracking import Zonetracker
  11. class AD2(object):
  12. """
  13. High-level wrapper around AD2 devices.
  14. """
  15. # High-level Events
  16. on_arm = event.Event('Called when the panel is armed.')
  17. on_disarm = event.Event('Called when the panel is disarmed.')
  18. on_power_changed = event.Event('Called when panel power switches between AC and DC.')
  19. on_alarm = event.Event('Called when the alarm is triggered.')
  20. on_fire = event.Event('Called when a fire is detected.')
  21. on_bypass = event.Event('Called when a zone is bypassed.')
  22. on_boot = event.Event('Called when the device finishes bootings.')
  23. on_config_received = event.Event('Called when the device receives its configuration.')
  24. on_zone_fault = event.Event('Called when the device detects a zone fault.')
  25. on_zone_restore = event.Event('Called when the device detects that a fault is restored.')
  26. on_low_battery = event.Event('Called when the device detects a low battery.')
  27. on_panic = event.Event('Called when the device detects a panic.')
  28. on_relay_changed = event.Event('Called when a relay is opened or closed on an expander board.')
  29. # Mid-level Events
  30. on_message = event.Event('Called when a message has been received from the device.')
  31. on_lrr_message = event.Event('Called when an LRR message is received.')
  32. on_rfx_message = event.Event('Called when an RFX message is received.')
  33. # Low-level Events
  34. on_open = event.Event('Called when the device has been opened.')
  35. on_close = event.Event('Called when the device has been closed.')
  36. on_read = event.Event('Called when a line has been read from the device.')
  37. on_write = event.Event('Called when data has been written to the device.')
  38. # Constants
  39. F1 = unichr(1) + unichr(1) + unichr(1)
  40. """Represents panel function key #1"""
  41. F2 = unichr(2) + unichr(2) + unichr(2)
  42. """Represents panel function key #2"""
  43. F3 = unichr(3) + unichr(3) + unichr(3)
  44. """Represents panel function key #3"""
  45. F4 = unichr(4) + unichr(4) + unichr(4)
  46. """Represents panel function key #4"""
  47. BATTERY_TIMEOUT = 30
  48. """Timeout before the battery status reverts."""
  49. FIRE_TIMEOUT = 30
  50. """Timeout before the fire status reverts."""
  51. def __init__(self, device):
  52. """
  53. Constructor
  54. :param device: The low-level device used for this AD2 interface.
  55. :type device: Device
  56. """
  57. self._device = device
  58. self._zonetracker = Zonetracker()
  59. self._power_status = None
  60. self._alarm_status = None
  61. self._bypass_status = None
  62. self._armed_status = None
  63. self._fire_status = (False, 0)
  64. self._battery_status = (False, 0)
  65. self._panic_status = None
  66. self._relay_status = {}
  67. self.address = 18
  68. self.configbits = 0xFF00
  69. self.address_mask = 0x00000000
  70. self.emulate_zone = [False for x in range(5)]
  71. self.emulate_relay = [False for x in range(4)]
  72. self.emulate_lrr = False
  73. self.deduplicate = False
  74. @property
  75. def id(self):
  76. """
  77. The ID of the AD2 device.
  78. :returns: The identification string for the device.
  79. """
  80. return self._device.id
  81. def open(self, baudrate=None, no_reader_thread=False):
  82. """
  83. Opens the device.
  84. :param baudrate: The baudrate used for the device.
  85. :type baudrate: int
  86. :param no_reader_thread: Specifies whether or not the automatic reader thread should be started or not
  87. :type no_reader_thread: bool
  88. """
  89. self._wire_events()
  90. self._device.open(baudrate=baudrate, no_reader_thread=no_reader_thread)
  91. def close(self):
  92. """
  93. Closes the device.
  94. """
  95. if self._device:
  96. self._device.close()
  97. del self._device
  98. self._device = None
  99. def send(self, data):
  100. """
  101. Sends data to the AD2 device.
  102. :param data: The data to send.
  103. :type data: str
  104. """
  105. if self._device:
  106. self._device.write(data)
  107. def get_config(self):
  108. """
  109. Retrieves the configuration from the device.
  110. """
  111. self.send("C\r")
  112. def save_config(self):
  113. """
  114. Sets configuration entries on the device.
  115. """
  116. config_string = ''
  117. # HACK: Both of these methods are ugly.. but I can't think of an elegant way of doing it.
  118. #config_string += 'ADDRESS={0}&'.format(self.address)
  119. #config_string += 'CONFIGBITS={0:x}&'.format(self.configbits)
  120. #config_string += 'MASK={0:x}&'.format(self.address_mask)
  121. #config_string += 'EXP={0}&'.format(''.join(['Y' if z else 'N' for z in self.emulate_zone]))
  122. #config_string += 'REL={0}&'.format(''.join(['Y' if r else 'N' for r in self.emulate_relay]))
  123. #config_string += 'LRR={0}&'.format('Y' if self.emulate_lrr else 'N')
  124. #config_string += 'DEDUPLICATE={0}'.format('Y' if self.deduplicate else 'N')
  125. config_entries = []
  126. config_entries.append(('ADDRESS', '{0}'.format(self.address)))
  127. config_entries.append(('CONFIGBITS', '{0:x}'.format(self.configbits)))
  128. config_entries.append(('MASK', '{0:x}'.format(self.address_mask)))
  129. config_entries.append(('EXP', ''.join(['Y' if z else 'N' for z in self.emulate_zone])))
  130. config_entries.append(('REL', ''.join(['Y' if r else 'N' for r in self.emulate_relay])))
  131. config_entries.append(('LRR', 'Y' if self.emulate_lrr else 'N'))
  132. config_entries.append(('DEDUPLICATE', 'Y' if self.deduplicate else 'N'))
  133. config_string = '&'.join(['='.join(t) for t in config_entries])
  134. self.send("C{0}\r".format(config_string))
  135. def reboot(self):
  136. """
  137. Reboots the device.
  138. """
  139. self.send('=')
  140. def fault_zone(self, zone, simulate_wire_problem=False):
  141. """
  142. Faults a zone if we are emulating a zone expander.
  143. :param zone: The zone to fault.
  144. :type zone: int
  145. :param simulate_wire_problem: Whether or not to simulate a wire fault.
  146. :type simulate_wire_problem: bool
  147. """
  148. # Allow ourselves to also be passed an address/channel combination
  149. # for zone expanders.
  150. #
  151. # Format (expander index, channel)
  152. if isinstance(zone, tuple):
  153. zone = self._zonetracker._expander_to_zone(*zone)
  154. status = 2 if simulate_wire_problem else 1
  155. self.send("L{0:02}{1}\r".format(zone, status))
  156. def clear_zone(self, zone):
  157. """
  158. Clears a zone if we are emulating a zone expander.
  159. :param zone: The zone to clear.
  160. :type zone: int
  161. """
  162. self.send("L{0:02}0\r".format(zone))
  163. def _wire_events(self):
  164. """
  165. Wires up the internal device events.
  166. """
  167. self._device.on_open += self._on_open
  168. self._device.on_close += self._on_close
  169. self._device.on_read += self._on_read
  170. self._device.on_write += self._on_write
  171. self._zonetracker.on_fault += self._on_zone_fault
  172. self._zonetracker.on_restore += self._on_zone_restore
  173. def _handle_message(self, data):
  174. """
  175. Parses messages from the panel.
  176. :param data: Panel data to parse.
  177. :type data: str
  178. :returns: An object representing the message.
  179. """
  180. if data is None:
  181. raise InvalidMessageError()
  182. msg = None
  183. header = data[0:4]
  184. if header[0] != '!' or header == '!KPE':
  185. msg = Message(data)
  186. if self.address_mask & msg.mask > 0:
  187. self._update_internal_states(msg)
  188. elif header == '!EXP' or header == '!REL':
  189. msg = ExpanderMessage(data)
  190. self._update_internal_states(msg)
  191. elif header == '!RFX':
  192. msg = self._handle_rfx(data)
  193. elif header == '!LRR':
  194. msg = self._handle_lrr(data)
  195. elif data.startswith('!Ready'):
  196. self.on_boot()
  197. elif data.startswith('!CONFIG'):
  198. self._handle_config(data)
  199. return msg
  200. def _handle_rfx(self, data):
  201. """
  202. Handle RF messages.
  203. :param data: RF message to parse.
  204. :type data: str
  205. :returns: An object representing the RF message.
  206. """
  207. msg = RFMessage(data)
  208. self.on_rfx_message(message=msg)
  209. return msg
  210. def _handle_lrr(self, data):
  211. """
  212. Handle Long Range Radio messages.
  213. :param data: LRR message to parse.
  214. :type data: str
  215. :returns: An object representing the LRR message.
  216. """
  217. msg = LRRMessage(data)
  218. if msg.event_type == 'ALARM_PANIC':
  219. self._panic_status = True
  220. self.on_panic(status=True)
  221. elif msg.event_type == 'CANCEL':
  222. if self._panic_status == True:
  223. self._panic_status = False
  224. self.on_panic(status=False)
  225. self.on_lrr_message(message=msg)
  226. return msg
  227. def _handle_config(self, data):
  228. """
  229. Handles received configuration data.
  230. :param data: Configuration string to parse.
  231. :type data: str
  232. """
  233. _, config_string = data.split('>')
  234. for setting in config_string.split('&'):
  235. k, v = setting.split('=')
  236. if k == 'ADDRESS':
  237. self.address = int(v)
  238. elif k == 'CONFIGBITS':
  239. self.configbits = int(v, 16)
  240. elif k == 'MASK':
  241. self.address_mask = int(v, 16)
  242. elif k == 'EXP':
  243. for z in range(5):
  244. self.emulate_zone[z] = (v[z] == 'Y')
  245. elif k == 'REL':
  246. for r in range(4):
  247. self.emulate_relay[r] = (v[r] == 'Y')
  248. elif k == 'LRR':
  249. self.emulate_lrr = (v == 'Y')
  250. elif k == 'DEDUPLICATE':
  251. self.deduplicate = (v == 'Y')
  252. self.on_config_received()
  253. def _update_internal_states(self, message):
  254. """
  255. Updates internal device states.
  256. :param message: Message to update internal states with.
  257. :type message: Message, ExpanderMessage, LRRMessage, or RFMessage
  258. """
  259. if isinstance(message, Message):
  260. if message.ac_power != self._power_status:
  261. self._power_status, old_status = message.ac_power, self._power_status
  262. if old_status is not None:
  263. self.on_power_changed(status=self._power_status)
  264. if message.alarm_sounding != self._alarm_status:
  265. self._alarm_status, old_status = message.alarm_sounding, self._alarm_status
  266. if old_status is not None:
  267. self.on_alarm(status=self._alarm_status)
  268. if message.zone_bypassed != self._bypass_status:
  269. self._bypass_status, old_status = message.zone_bypassed, self._bypass_status
  270. if old_status is not None:
  271. self.on_bypass(status=self._bypass_status)
  272. if (message.armed_away | message.armed_home) != self._armed_status:
  273. self._armed_status, old_status = message.armed_away | message.armed_home, self._armed_status
  274. if old_status is not None:
  275. if self._armed_status:
  276. self.on_arm()
  277. else:
  278. self.on_disarm()
  279. if message.battery_low == self._battery_status[0]:
  280. self._battery_status = (self._battery_status[0], time.time())
  281. else:
  282. if message.battery_low == True or time.time() > self._battery_status[1] + AD2.BATTERY_TIMEOUT:
  283. self._battery_status = (message.battery_low, time.time())
  284. self.on_low_battery(status=self._battery_status)
  285. if message.fire_alarm == self._fire_status[0]:
  286. self._fire_status = (self._fire_status[0], time.time())
  287. else:
  288. if message.fire_alarm == True or time.time() > self._fire_status[1] + AD2.FIRE_TIMEOUT:
  289. self._fire_status = (message.fire_alarm, time.time())
  290. self.on_fire(status=self._fire_status)
  291. elif isinstance(message, ExpanderMessage):
  292. if message.type == ExpanderMessage.RELAY:
  293. self._relay_status[(message.address, message.channel)] = message.value
  294. self.on_relay_changed(message=message)
  295. self._update_zone_tracker(message)
  296. def _update_zone_tracker(self, message):
  297. """
  298. Trigger an update of the zonetracker.
  299. :param message: The message to update the zonetracker with.
  300. :type message: Message, ExpanderMessage, LRRMessage, or RFMessage
  301. """
  302. # Retrieve a list of faults.
  303. # NOTE: This only happens on first boot or after exiting programming mode.
  304. if isinstance(message, Message):
  305. if not message.ready and "Hit * for faults" in message.text:
  306. self.send('*')
  307. return
  308. self._zonetracker.update(message)
  309. def _on_open(self, sender, *args, **kwargs):
  310. """
  311. Internal handler for opening the device.
  312. """
  313. self.on_open(args, kwargs)
  314. def _on_close(self, sender, *args, **kwargs):
  315. """
  316. Internal handler for closing the device.
  317. """
  318. self.on_close(args, kwargs)
  319. def _on_read(self, sender, *args, **kwargs):
  320. """
  321. Internal handler for reading from the device.
  322. """
  323. self.on_read(args, kwargs)
  324. msg = self._handle_message(kwargs['data'])
  325. if msg:
  326. self.on_message(message=msg)
  327. def _on_write(self, sender, *args, **kwargs):
  328. """
  329. Internal handler for writing to the device.
  330. """
  331. self.on_write(args, kwargs)
  332. def _on_zone_fault(self, sender, *args, **kwargs):
  333. """
  334. Internal handler for zone faults.
  335. """
  336. self.on_zone_fault(*args, **kwargs)
  337. def _on_zone_restore(self, sender, *args, **kwargs):
  338. """
  339. Internal handler for zone restoration.
  340. """
  341. self.on_zone_restore(*args, **kwargs)