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.

277 lines
7.8 KiB

  1. """
  2. Provides zone tracking functionality for the AD2USB device family.
  3. """
  4. import time
  5. from .event import event
  6. from . import messages
  7. class Zone(object):
  8. """
  9. Representation of a panel zone.
  10. """
  11. CLEAR = 0
  12. """Status indicating that the zone is cleared."""
  13. FAULT = 1
  14. """Status indicating that the zone is faulted."""
  15. CHECK = 2 # Wire fault
  16. """Status indicating that there is a wiring issue with the zone."""
  17. STATUS = { CLEAR: 'CLEAR', FAULT: 'FAULT', CHECK: 'CHECK' }
  18. def __init__(self, zone=0, name='', status=CLEAR):
  19. """
  20. Constructor
  21. :param zone: The zone number.
  22. :type zone: int
  23. :param name: Human readable zone name.
  24. :type name: str
  25. :param status: Initial zone state.
  26. :type status: int
  27. """
  28. self.zone = zone
  29. self.name = name
  30. self.status = status
  31. self.timestamp = time.time()
  32. def __str__(self):
  33. """
  34. String conversion operator.
  35. """
  36. return 'Zone {0} {1}'.format(self.zone, self.name)
  37. def __repr__(self):
  38. """
  39. Human readable representation operator.
  40. """
  41. return 'Zone({0}, {1}, ts {2})'.format(self.zone, Zone.STATUS[self.status], self.timestamp)
  42. class Zonetracker(object):
  43. """
  44. Handles tracking of zone and their statuses.
  45. """
  46. on_fault = event.Event('Called when the device detects a zone fault.')
  47. on_restore = event.Event('Called when the device detects that a fault is restored.')
  48. EXPIRE = 30
  49. """Zone expiration timeout."""
  50. def __init__(self):
  51. """
  52. Constructor
  53. """
  54. self._zones = {}
  55. self._zones_faulted = []
  56. self._last_zone_fault = 0
  57. def update(self, message):
  58. """
  59. Update zone statuses based on the current message.
  60. :param message: Message to use to update the zone tracking.
  61. :type message: Message or ExpanderMessage
  62. """
  63. zone = -1
  64. if isinstance(message, messages.ExpanderMessage):
  65. if message.type == messages.ExpanderMessage.ZONE:
  66. zone = self._expander_to_zone(int(message.address), int(message.channel))
  67. status = Zone.CLEAR
  68. if int(message.value) == 1:
  69. status = Zone.FAULT
  70. elif int(message.value) == 2:
  71. status = Zone.CHECK
  72. try:
  73. self._update_zone(zone, status=status)
  74. except IndexError:
  75. self._add_zone(zone, status=status)
  76. else:
  77. # Panel is ready, restore all zones.
  78. if message.ready:
  79. for idx, z in enumerate(self._zones_faulted):
  80. self._update_zone(z, Zone.CLEAR)
  81. self._last_zone_fault = 0
  82. # Process fault
  83. elif "FAULT" in message.text or message.check_zone:
  84. # Apparently this representation can be both base 10
  85. # or base 16, depending on where the message came
  86. # from.
  87. try:
  88. zone = int(message.numeric_code)
  89. except ValueError:
  90. zone = int(message.numeric_code, 16)
  91. # Add new zones and clear expired ones.
  92. if zone in self._zones_faulted:
  93. self._update_zone(zone)
  94. self._clear_zones(zone)
  95. else:
  96. status = Zone.FAULT
  97. if message.check_zone:
  98. status = Zone.CHECK
  99. self._add_zone(zone, status=status)
  100. self._zones_faulted.append(zone)
  101. self._zones_faulted.sort()
  102. # Save our spot for the next message.
  103. self._last_zone_fault = zone
  104. self._clear_expired_zones()
  105. def _clear_zones(self, zone):
  106. """
  107. Clear all expired zones from our status list.
  108. :param zone: current zone being processed.
  109. :type zone: int
  110. """
  111. cleared_zones = []
  112. found_last = found_new = at_end = False
  113. # First pass: Find our start spot.
  114. it = iter(self._zones_faulted)
  115. try:
  116. while not found_last:
  117. z = it.next()
  118. if z == self._last_zone_fault:
  119. found_last = True
  120. break
  121. except StopIteration:
  122. at_end = True
  123. # Continue until we find our end point and add zones in
  124. # between to our clear list.
  125. try:
  126. while not at_end and not found_new:
  127. z = it.next()
  128. if z == zone:
  129. found_new = True
  130. break
  131. else:
  132. cleared_zones += [z]
  133. except StopIteration:
  134. pass
  135. # Second pass: roll through the list again if we didn't find
  136. # our end point and remove everything until we do.
  137. if not found_new:
  138. it = iter(self._zones_faulted)
  139. try:
  140. while not found_new:
  141. z = it.next()
  142. if z == zone:
  143. found_new = True
  144. break
  145. else:
  146. cleared_zones += [z]
  147. except StopIteration:
  148. pass
  149. # Actually remove the zones and trigger the restores.
  150. for idx, z in enumerate(cleared_zones):
  151. self._update_zone(z, Zone.CLEAR)
  152. def _clear_expired_zones(self):
  153. """
  154. Update zone status for all expired zones.
  155. """
  156. zones = []
  157. for z in self._zones.keys():
  158. zones += [z]
  159. for z in zones:
  160. if self._zones[z].status != Zone.CLEAR and self._zone_expired(z):
  161. self._update_zone(z, Zone.CLEAR)
  162. def _add_zone(self, zone, name='', status=Zone.CLEAR):
  163. """
  164. Adds a zone to the internal zone list.
  165. :param zone: The zone number.
  166. :type zone: int
  167. :param name: Human readable zone name.
  168. :type name: str
  169. :param status: The zone status.
  170. :type status: int
  171. """
  172. if not zone in self._zones:
  173. self._zones[zone] = Zone(zone=zone, name=name, status=status)
  174. if status != Zone.CLEAR:
  175. self.on_fault(zone)
  176. def _update_zone(self, zone, status=None):
  177. """
  178. Updates a zones status.
  179. :param zone: The zone number.
  180. :type zone: int
  181. :param status: The zone status.
  182. :type status: int
  183. :raises: IndexError
  184. """
  185. if not zone in self._zones:
  186. raise IndexError('Zone does not exist and cannot be updated: %d', zone)
  187. if status is not None:
  188. self._zones[zone].status = status
  189. self._zones[zone].timestamp = time.time()
  190. if status == Zone.CLEAR:
  191. if zone in self._zones_faulted:
  192. self._zones_faulted.remove(zone)
  193. self.on_restore(zone)
  194. def _zone_expired(self, zone):
  195. """
  196. Determine if a zone is expired or not.
  197. :param zone: The zone number.
  198. :type zone: int
  199. :returns: Whether or not the zone is expired.
  200. """
  201. if time.time() > self._zones[zone].timestamp + Zonetracker.EXPIRE:
  202. return True
  203. return False
  204. def _expander_to_zone(self, address, channel):
  205. """
  206. Convert an address and channel into a zone number.
  207. :param address: The expander address
  208. :type address: int
  209. :param channel: The channel
  210. :type channel: int
  211. :returns: The zone number associated with an address and channel.
  212. """
  213. # TODO: This is going to need to be reworked to support the larger
  214. # panels without fixed addressing on the expanders.
  215. idx = address - 7 # Expanders start at address 7.
  216. return address + channel + (idx * 7) + 1