Smarthome Functionen
Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324
  1. #!/usr/bin/env python
  2. # -*- coding: utf-8 -*-
  3. #
  4. """
  5. Virtual Device(s)
  6. Targets:
  7. * MQTT-Interface to control joined devices as one virtual device
  8. * Primary signal routing
  9. * No functionality should be implemented here
  10. """
  11. from base import mqtt_base
  12. from function.rooms import room, room_collection
  13. import json
  14. import time
  15. try:
  16. from config import APP_NAME as ROOT_LOGGER_NAME
  17. except ImportError:
  18. ROOT_LOGGER_NAME = 'root'
  19. class base(mqtt_base):
  20. KEY_INFO = '__info__'
  21. #
  22. SET_TOPIC = "set"
  23. def __init__(self, mqtt_client, topic, default_values=None):
  24. super().__init__(mqtt_client, topic, default_values=default_values)
  25. self.__display_dict__ = {}
  26. self.__control_dict__ = {}
  27. self.__capabilities__ = None
  28. def add_display(self, my_key, ext_device, ext_key, on_change_only=True):
  29. """
  30. listen to data changes of ext_device and update videv information
  31. """
  32. if ext_device.__class__.__name__ == "group":
  33. # store information to identify callback from ext_device
  34. self.__display_dict__[(id(ext_device[0]), ext_key)] = my_key
  35. # register a callback to listen for data from external device
  36. ext_device[0].add_callback(ext_key, None, self.__rx_ext_device_data__, on_change_only)
  37. else:
  38. # store information to identify callback from ext_device
  39. self.__display_dict__[(id(ext_device), ext_key)] = my_key
  40. # register a callback to listen for data from external device
  41. ext_device.add_callback(ext_key, None, self.__rx_ext_device_data__, on_change_only)
  42. # send default data to videv interface
  43. def __rx_ext_device_data__(self, ext_device, ext_key, data):
  44. my_key = self.__display_dict__[(id(ext_device), ext_key)]
  45. self.set(my_key, data)
  46. self.__tx__(my_key, data)
  47. def __tx__(self, key, data):
  48. if type(data) not in (str, ):
  49. data = json.dumps(data)
  50. self.mqtt_client.send('/'.join([self.topic, key]), data)
  51. self.__tx_capabilities__()
  52. def __tx_capabilities__(self):
  53. self.mqtt_client.send(self.topic + '/' + self.KEY_INFO, json.dumps(self.capabilities))
  54. def add_control(self, my_key, ext_device, ext_key, on_change_only=True):
  55. """
  56. listen to videv information and pass data to ext_device
  57. """
  58. self[my_key] = None
  59. # store information to identify callback from videv
  60. self.__control_dict__[my_key] = (ext_device, ext_key, on_change_only)
  61. # add callback for videv changes
  62. self.mqtt_client.add_callback('/'.join([self.topic, my_key, self.SET_TOPIC]), self.__rx_videv_data__)
  63. def __rx_videv_data__(self, client, userdata, message):
  64. my_key = message.topic.split('/')[-2]
  65. try:
  66. data = json.loads(message.payload)
  67. except json.decoder.JSONDecodeError:
  68. data = message.payload
  69. ext_device, ext_key, on_change_only = self.__control_dict__[my_key]
  70. if my_key in self.keys():
  71. if data != self[my_key] or not on_change_only:
  72. ext_device.send_command(ext_key, data)
  73. else:
  74. self.logger.info("Ignoring rx message with topic %s", message.topic)
  75. def add_routing(self, my_key, ext_device, ext_key, on_change_only_disp=True, on_change_only_videv=True):
  76. """
  77. listen to data changes of ext_device and update videv information
  78. and
  79. listen to videv information and pass data to ext_device
  80. """
  81. # add display
  82. self.add_display(my_key, ext_device, ext_key, on_change_only_disp)
  83. self.add_control(my_key, ext_device, ext_key, on_change_only_videv)
  84. @property
  85. def capabilities(self):
  86. if self.__capabilities__ is None:
  87. self.__capabilities__ = {}
  88. self.__capabilities__['__type__'] = self.__class__.__name__
  89. for key in self.__control_dict__:
  90. if not key in self.__capabilities__:
  91. self.__capabilities__[key] = {}
  92. self.__capabilities__[key]['control'] = True
  93. for key in self.__display_dict__.values():
  94. if not key in self.__capabilities__:
  95. self.__capabilities__[key] = {}
  96. self.__capabilities__[key]['display'] = True
  97. return self.__capabilities__
  98. class videv_switching(base):
  99. KEY_STATE = 'state'
  100. def __init__(self, mqtt_client, topic, sw_device, sw_key):
  101. super().__init__(mqtt_client, topic)
  102. self.add_routing(self.KEY_STATE, sw_device, sw_key)
  103. #
  104. self.__tx_capabilities__()
  105. class videv_switching_timer(base):
  106. KEY_STATE = 'state'
  107. KEY_TIMER = 'timer'
  108. def __init__(self, mqtt_client, topic, sw_device, sw_key, tm_device, tm_key):
  109. super().__init__(mqtt_client, topic)
  110. self.add_routing(self.KEY_STATE, sw_device, sw_key)
  111. self.add_display(self.KEY_TIMER, tm_device, tm_key)
  112. #
  113. self.__tx_capabilities__()
  114. class videv_switching_motion(base):
  115. KEY_STATE = 'state'
  116. #
  117. KEY_TIMER = 'timer'
  118. KEY_MOTION_SENSOR = 'motion_%d'
  119. def __init__(self, mqtt_client, topic, sw_device, sw_key, motion_function):
  120. self.motion_sensors = motion_function.motion_sensors
  121. #
  122. super().__init__(mqtt_client, topic)
  123. self.add_routing(self.KEY_STATE, sw_device, sw_key)
  124. self.add_display(self.KEY_TIMER, motion_function, motion_function.KEY_TIMER)
  125. # motion sensor state
  126. for index, motion_sensor in enumerate(self.motion_sensors):
  127. self.add_display(self.KEY_MOTION_SENSOR % index, motion_sensor, motion_sensor.KEY_OCCUPANCY)
  128. #
  129. self.__tx_capabilities__()
  130. class videv_switch_brightness(base):
  131. KEY_STATE = 'state'
  132. KEY_BRIGHTNESS = 'brightness'
  133. def __init__(self, mqtt_client, topic, sw_device, sw_key, br_device, br_key):
  134. super().__init__(mqtt_client, topic)
  135. self.add_routing(self.KEY_STATE, sw_device, sw_key)
  136. self.add_routing(self.KEY_BRIGHTNESS, br_device, br_key)
  137. #
  138. self.__tx_capabilities__()
  139. class videv_switch_brightness_color_temp(base):
  140. KEY_STATE = 'state'
  141. KEY_BRIGHTNESS = 'brightness'
  142. KEY_COLOR_TEMP = 'color_temp'
  143. def __init__(self, mqtt_client, topic, sw_device, sw_key, br_device, br_key, ct_device, ct_key):
  144. super().__init__(mqtt_client, topic)
  145. self.add_routing(self.KEY_STATE, sw_device, sw_key)
  146. self.add_routing(self.KEY_BRIGHTNESS, br_device, br_key)
  147. self.add_routing(self.KEY_COLOR_TEMP, ct_device, ct_key)
  148. #
  149. self.__tx_capabilities__()
  150. class videv_heating(base):
  151. KEY_USER_TEMPERATURE_SETPOINT = 'user_temperature_setpoint'
  152. KEY_VALVE_TEMPERATURE_SETPOINT = 'valve_temperature_setpoint'
  153. KEY_AWAY_MODE = 'away_mode'
  154. KEY_SUMMER_MODE = 'summer_mode'
  155. KEY_START_BOOST = 'start_boost'
  156. KEY_SET_DEFAULT_TEMPERATURE = 'set_default_temperature'
  157. KEY_BOOST_TIMER = 'boost_timer'
  158. #
  159. KEY_TEMPERATURE = 'temperature'
  160. def __init__(self, mqtt_client, topic, heating_function):
  161. super().__init__(mqtt_client, topic)
  162. #
  163. self.add_routing(self.KEY_USER_TEMPERATURE_SETPOINT, heating_function, heating_function.KEY_USER_TEMPERATURE_SETPOINT)
  164. self.add_routing(self.KEY_AWAY_MODE, heating_function, heating_function.KEY_AWAY_MODE)
  165. self.add_routing(self.KEY_SUMMER_MODE, heating_function, heating_function.KEY_SUMMER_MODE)
  166. #
  167. self.add_control(self.KEY_START_BOOST, heating_function, heating_function.KEY_START_BOOST, False)
  168. self.add_control(self.KEY_SET_DEFAULT_TEMPERATURE, heating_function, heating_function.KEY_SET_DEFAULT_TEMPERATURE, False)
  169. #
  170. self.add_display(self.KEY_VALVE_TEMPERATURE_SETPOINT, heating_function, heating_function.KEY_TEMPERATURE_SETPOINT)
  171. self.add_display(self.KEY_BOOST_TIMER, heating_function, heating_function.KEY_BOOST_TIMER)
  172. self.add_display(self.KEY_TEMPERATURE, heating_function, heating_function.KEY_TEMPERATURE_CURRENT, False)
  173. #
  174. self.__tx_capabilities__()
  175. class videv_multistate(base):
  176. KEY_STATE = 'state_%d'
  177. def __init__(self, mqtt_client, topic, key_for_device, device, num_states, default_values=None):
  178. super().__init__(mqtt_client, topic)
  179. self.num_states = num_states
  180. # send default values
  181. for i in range(0, num_states):
  182. self.__tx__(self.KEY_STATE % i, False)
  183. #
  184. device.add_callback(key_for_device, None, self.__index_rx__, True)
  185. #
  186. self.__tx_capabilities__()
  187. def __index_rx__(self, device, key, data):
  188. for i in range(0, self.num_states):
  189. self.__tx__(self.KEY_STATE % i, i == data)
  190. #
  191. self.__tx_capabilities__()
  192. class videv_audio_player(base):
  193. KEY_ACTIVE_PLAYER = 'player_%d'
  194. KEY_TITLE = 'title'
  195. NO_TITLE = '---'
  196. def __init__(self, mqtt_client, topic, *args):
  197. super().__init__(mqtt_client, topic)
  198. for i, device in enumerate(args):
  199. self.add_display(self.KEY_ACTIVE_PLAYER % i, device, device.KEY_STATE)
  200. #
  201. for audio_device in args:
  202. audio_device.add_callback(audio_device.KEY_TITLE, None, self.__title_rx__, True)
  203. #
  204. self.__tx_capabilities__()
  205. def __title_rx__(self, device, key, data):
  206. self.__tx__(self.KEY_TITLE, data or self.NO_TITLE)
  207. @property
  208. def capabilities(self):
  209. super().capabilities
  210. self.__capabilities__[self.KEY_TITLE] = {'display': True}
  211. return self.__capabilities__
  212. class videv_warnings(base):
  213. MAX_WARNINGS = 10
  214. KEY_WARNING = 'html_short'
  215. def __init__(self, mqtt_client, topic, default_values=None):
  216. super().__init__(mqtt_client, topic, default_values)
  217. self.__warnings__ = []
  218. def warningcollector(self, client, key, data):
  219. self.__warnings__.append(data)
  220. self.__warnings__ = self.__warnings__[-self.MAX_WARNINGS:]
  221. txt = "<br><br>".join([time.asctime(w[w.KEY_TM]) + "<br>" + w[w.KEY_TEXT] + "<br>" + w[w.KEY_ID] for w in self.__warnings__])
  222. self.__tx__(self.KEY_WARNING, txt)
  223. class all_off(base):
  224. ALLOWED_CLASSES = (room, room_collection, )
  225. def __init__(self, mqtt_client, topic, room_collection):
  226. super().__init__(mqtt_client, topic)
  227. self.__room_collection__ = room_collection
  228. # init __inst_dict__
  229. self.__inst_dict__ = {}
  230. self.__add_instances__("all", self.__room_collection__)
  231. # register mqtt callbacks for all my keys
  232. for key in self.__inst_dict__:
  233. mqtt_client.add_callback(topic + "/" + key, self.all_off)
  234. #
  235. self.__tx_capabilities__()
  236. def __check_inst_capabilities__(self, name, inst):
  237. # fits to specified classes
  238. if isinstance(inst, self.ALLOWED_CLASSES):
  239. try:
  240. # all_off method is callable
  241. return callable(inst.all_off)
  242. except AttributeError:
  243. # all_off method does not exist
  244. return False
  245. return False
  246. def __add_instances__(self, name, inst, level=0):
  247. if self.__check_inst_capabilities__(name, inst):
  248. # add given instance to my __inst_dict__
  249. self.__inst_dict__[name] = inst
  250. # iterate over all attribute names of instance
  251. for sub_name in dir(inst):
  252. # attribute name is not private
  253. if not sub_name.startswith("__"):
  254. sub = getattr(inst, sub_name)
  255. # recurse with this object
  256. if level == 0:
  257. self.__add_instances__(sub_name, sub, level=level+1)
  258. else:
  259. self.__add_instances__(name + "/" + sub_name, sub, level=level+1)
  260. def all_off(self, client, userdata, message):
  261. key = message.topic[len(self.topic) + 1:]
  262. self.__inst_dict__[key].all_off()
  263. self.__tx_capabilities__()
  264. @property
  265. def capabilities(self):
  266. if self.__capabilities__ is None:
  267. self.__capabilities__ = {}
  268. self.__capabilities__['__type__'] = self.__class__.__name__
  269. for key in self.__inst_dict__:
  270. self.__capabilities__[key] = {}
  271. self.__capabilities__[key]['control'] = True
  272. return self.__capabilities__