Smarthome Functionen
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.

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461
  1. #!/usr/bin/env python
  2. # -*- coding: utf-8 -*-
  3. #
  4. """
  5. devices (DEVICES)
  6. ===========
  7. **Author:**
  8. * Dirk Alders <sudo-dirk@mount-mockery.de>
  9. **Description:**
  10. This Module supports smarthome devices
  11. **Submodules:**
  12. * :mod:`shelly`
  13. * :mod:`silvercrest_powerplug`
  14. **Unittest:**
  15. See also the :download:`unittest <devices/_testresults_/unittest.pdf>` documentation.
  16. **Module Documentation:**
  17. """
  18. __DEPENDENCIES__ = []
  19. import json
  20. import logging
  21. try:
  22. from config import APP_NAME as ROOT_LOGGER_NAME
  23. except ImportError:
  24. ROOT_LOGGER_NAME = 'root'
  25. logger = logging.getLogger(ROOT_LOGGER_NAME).getChild(__name__)
  26. BATTERY_WARN_LEVEL = 5
  27. def is_json(data):
  28. try:
  29. json.loads(data)
  30. except json.decoder.JSONDecodeError:
  31. return False
  32. else:
  33. return True
  34. class base(dict):
  35. TX_TOPIC = None
  36. TX_VALUE = 0
  37. TX_DICT = 1
  38. TX_TYPE = -1
  39. TX_FILTER_DATA_KEYS = []
  40. #
  41. RX_LOG_INFO_ALWAYS_KEYS = []
  42. RX_KEYS = []
  43. RX_IGNORE_TOPICS = []
  44. RX_IGNORE_KEYS = []
  45. RX_FILTER_DATA_KEYS = []
  46. def __init__(self, mqtt_client, topic):
  47. # data storage
  48. self.mqtt_client = mqtt_client
  49. self.topic = topic
  50. # initialisations
  51. dict.__init__(self)
  52. mqtt_client.add_callback(
  53. topic=self.topic, callback=self.receive_callback)
  54. mqtt_client.add_callback(
  55. topic=self.topic+"/#", callback=self.receive_callback)
  56. #
  57. self.callback_list = []
  58. self.warning_callback = None
  59. def receive_callback(self, client, userdata, message):
  60. self.unpack(message)
  61. def unpack_filter(self, key):
  62. if key in self.RX_FILTER_DATA_KEYS:
  63. if self.get(key) == 1 or self.get(key) == 'on' or self.get(key) == 'ON':
  64. self[key] = True
  65. elif self.get(key) == 0 or self.get(key) == 'off' or self.get(key) == 'OFF':
  66. self[key] = False
  67. def unpack_single_value(self, key, data):
  68. prev_value = self.get(key)
  69. if key in self.RX_KEYS:
  70. self[key] = data
  71. # Filter, if needed
  72. self.unpack_filter(key)
  73. logger.log(logging.INFO if key in self.RX_LOG_INFO_ALWAYS_KEYS or prev_value != self.get(key) else logging.DEBUG,
  74. "Received data for (%s) %s - %s", self.topic, key, str(self.get(key)))
  75. self.callback_caller(key, self[key])
  76. elif key not in self.RX_IGNORE_KEYS:
  77. logger.warning('Got a message with unparsed content "%s"', key)
  78. else:
  79. logger.debug("Ignoring key %s", key)
  80. def unpack(self, message):
  81. content_key = message.topic[len(self.topic) + 1:]
  82. if content_key not in self.RX_IGNORE_TOPICS:
  83. logger.debug("Unpacking content_key \"%s\" from message.", content_key)
  84. if is_json(message.payload):
  85. data = json.loads(message.payload)
  86. if type(data) is dict:
  87. for key in data:
  88. self.unpack_single_value(key, data[key])
  89. else:
  90. self.unpack_single_value(content_key, data)
  91. # String
  92. else:
  93. self.unpack_single_value(
  94. content_key, message.payload.decode('utf-8'))
  95. self.warning_caller()
  96. else:
  97. logger.debug("Ignoring topic %s", content_key)
  98. def pack_filter(self, key, data):
  99. if key in self.TX_FILTER_DATA_KEYS:
  100. if data is True:
  101. return "on"
  102. elif data is False:
  103. return "off"
  104. else:
  105. return data
  106. return data
  107. def pack(self, key, data):
  108. data = self.pack_filter(key, data)
  109. if self.TX_TOPIC is not None:
  110. if self.TX_TYPE < 0:
  111. logger.error(
  112. "Unknown tx type. Set TX_TYPE of class to a known value")
  113. else:
  114. if self.TX_TYPE == self.TX_DICT:
  115. self.mqtt_client.send('/'.join([self.topic, self.TX_TOPIC]), json.dumps({key: data}))
  116. else:
  117. if type(data) not in [str, bytes]:
  118. data = json.dumps(data)
  119. self.mqtt_client.send('/'.join([self.topic, key, self.TX_TOPIC]), data)
  120. else:
  121. logger.error(
  122. "Unknown tx toptic. Set TX_TOPIC of class to a known value")
  123. def add_callback(self, key, data, callback):
  124. """
  125. key: key or None for all keys
  126. data: data or None for all data
  127. """
  128. cb_tup = (key, data, callback)
  129. if cb_tup not in self.callback_list:
  130. self.callback_list.append(cb_tup)
  131. def add_warning_callback(self, callback):
  132. self.warning_callback = callback
  133. def warning_call_condition(self):
  134. return False
  135. def callback_caller(self, key, data):
  136. for cb_key, cb_data, callback in self.callback_list:
  137. if (cb_key == key or cb_key is None) and (cb_data == data or cb_data is None):
  138. callback(self, key, data)
  139. def warning_caller(self):
  140. if self.warning_call_condition():
  141. warn_txt = self.warning_text()
  142. logger.warning(warn_txt)
  143. if self.warning_callback is not None:
  144. self.warning_callback(self, warn_txt)
  145. def warning_text(self, data):
  146. return "default warning text - replace parent warning_text function"
  147. class shelly(base):
  148. KEY_OUTPUT_0 = "relay/0"
  149. KEY_OUTPUT_1 = "relay/1"
  150. KEY_INPUT_0 = "input/0"
  151. KEY_INPUT_1 = "input/1"
  152. KEY_TEMPERATURE = "temperature"
  153. KEY_OVERTEMPERATURE = "overtemperature"
  154. #
  155. TX_TOPIC = 'command'
  156. TX_TYPE = base.TX_VALUE
  157. TX_FILTER_DATA_KEYS = [KEY_OUTPUT_0, KEY_OUTPUT_1]
  158. #
  159. RX_KEYS = [KEY_OUTPUT_0, KEY_OUTPUT_1, KEY_INPUT_0,
  160. KEY_INPUT_1, KEY_OVERTEMPERATURE, KEY_TEMPERATURE]
  161. RX_IGNORE_TOPICS = [KEY_OUTPUT_0 + '/' + TX_TOPIC, KEY_OUTPUT_1 + '/' + TX_TOPIC,
  162. KEY_OUTPUT_0 + '/' + "energy", KEY_OUTPUT_1 + '/' + "energy"]
  163. RX_IGNORE_KEYS = ['temperature_f']
  164. RX_FILTER_DATA_KEYS = [KEY_INPUT_0, KEY_INPUT_1,
  165. KEY_OUTPUT_0, KEY_OUTPUT_1, KEY_OVERTEMPERATURE]
  166. def __init__(self, mqtt_client, topic):
  167. super().__init__(mqtt_client, topic)
  168. #
  169. # WARNING CALL
  170. #
  171. def warning_call_condition(self):
  172. return self.get(self.KEY_OVERTEMPERATURE)
  173. def warning_text(self):
  174. if self.overtemperature:
  175. if self.temperature is not None:
  176. return "Overtemperature detected for %s. Temperature was %.1f°C." % (self.topic, self.temperature)
  177. else:
  178. return "Overtemperature detected for %s." % self.topic
  179. #
  180. # RX
  181. #
  182. @property
  183. def output_0(self):
  184. """rv: [True, False]"""
  185. return self.get(self.KEY_OUTPUT_0)
  186. @property
  187. def output_1(self):
  188. """rv: [True, False]"""
  189. return self.get(self.KEY_OUTPUT_1)
  190. @property
  191. def input_0(self):
  192. """rv: [True, False]"""
  193. return self.get(self.KEY_INPUT_0)
  194. @property
  195. def input_1(self):
  196. """rv: [True, False]"""
  197. return self.get(self.KEY_INPUT_1)
  198. @property
  199. def temperature(self):
  200. """rv: numeric value"""
  201. return self.get(self.KEY_TEMPERATURE)
  202. #
  203. # TX
  204. #
  205. def set_output_0(self, state):
  206. """state: [True, False, 'toggle']"""
  207. self.pack(self.KEY_OUTPUT_0, state)
  208. def set_output_1(self, state):
  209. """state: [True, False, 'toggle']"""
  210. self.pack(self.KEY_OUTPUT_1, state)
  211. class silvercrest_powerplug(base):
  212. KEY_LINKQUALITY = "linkquality"
  213. KEY_OUTPUT_0 = "state"
  214. #
  215. TX_TOPIC = 'set'
  216. TX_TYPE = base.TX_DICT
  217. TX_FILTER_DATA_KEYS = [KEY_OUTPUT_0]
  218. #
  219. RX_KEYS = [KEY_LINKQUALITY, KEY_OUTPUT_0]
  220. RX_IGNORE_TOPICS = [TX_TOPIC]
  221. RX_IGNORE_KEYS = []
  222. RX_FILTER_DATA_KEYS = [KEY_OUTPUT_0]
  223. def __init__(self, mqtt_client, topic):
  224. super().__init__(mqtt_client, topic)
  225. #
  226. # RX
  227. #
  228. @property
  229. def output_0(self):
  230. """rv: [True, False]"""
  231. return self.get(self.KEY_OUTPUT_0)
  232. @property
  233. def linkquality(self):
  234. """rv: numeric value"""
  235. return self.get(self.KEY_LINKQUALITY)
  236. #
  237. # TX
  238. #
  239. def set_output_0(self, state):
  240. """state: [True, False, 'toggle']"""
  241. self.pack(self.KEY_OUTPUT_0, state)
  242. class my_powerplug(base):
  243. KEY_OUTPUT_0 = "output/1"
  244. KEY_OUTPUT_1 = "output/2"
  245. KEY_OUTPUT_2 = "output/3"
  246. KEY_OUTPUT_3 = "output/4"
  247. KEY_OUTPUT_ALL = "output/all"
  248. #
  249. TX_TOPIC = 'set'
  250. TX_TYPE = base.TX_VALUE
  251. #
  252. RX_KEYS = [KEY_OUTPUT_0, KEY_OUTPUT_1, KEY_OUTPUT_2, KEY_OUTPUT_3]
  253. RX_IGNORE_TOPICS = [KEY_OUTPUT_0 + "/" + TX_TOPIC, KEY_OUTPUT_1 + "/" + TX_TOPIC,
  254. KEY_OUTPUT_2 + "/" + TX_TOPIC, KEY_OUTPUT_3 + "/" + TX_TOPIC]
  255. RX_IGNORE_KEYS = []
  256. RX_FILTER_DATA_KEYS = []
  257. def __init__(self, mqtt_client, topic):
  258. super().__init__(mqtt_client, topic)
  259. #
  260. # RX
  261. #
  262. @property
  263. def output_0(self):
  264. """rv: [True, False]"""
  265. return self.get(self.KEY_OUTPUT_0)
  266. @property
  267. def output_1(self):
  268. """rv: [True, False]"""
  269. return self.get(self.KEY_OUTPUT_1)
  270. @property
  271. def output_2(self):
  272. """rv: [True, False]"""
  273. return self.get(self.KEY_OUTPUT_2)
  274. @property
  275. def output_3(self):
  276. """rv: [True, False]"""
  277. return self.get(self.KEY_OUTPUT_3)
  278. #
  279. # TX
  280. #
  281. def set_output_0(self, state):
  282. """state: [True, False, 'toggle']"""
  283. self.pack(self.KEY_OUTPUT_0, state)
  284. def set_output_1(self, state):
  285. """state: [True, False, 'toggle']"""
  286. self.pack(self.KEY_OUTPUT_1, state)
  287. def set_output_2(self, state):
  288. """state: [True, False, 'toggle']"""
  289. self.pack(self.KEY_OUTPUT_2, state)
  290. def set_output_3(self, state):
  291. """state: [True, False, 'toggle']"""
  292. self.pack(self.KEY_OUTPUT_3, state)
  293. def set_output_all(self, state):
  294. """state: [True, False, 'toggle']"""
  295. self.pack(self.KEY_OUTPUT_ALL, state)
  296. class tradfri_light(base):
  297. KEY_LINKQUALITY = "linkquality"
  298. KEY_OUTPUT_0 = "state"
  299. KEY_BRIGHTNESS = "brightness"
  300. KEY_COLOR_TEMP = "color_temp"
  301. #
  302. TX_TOPIC = 'set'
  303. TX_TYPE = base.TX_DICT
  304. TX_FILTER_DATA_KEYS = [KEY_OUTPUT_0, KEY_BRIGHTNESS, KEY_COLOR_TEMP]
  305. #
  306. RX_KEYS = [KEY_LINKQUALITY, KEY_OUTPUT_0, KEY_BRIGHTNESS, KEY_COLOR_TEMP]
  307. RX_IGNORE_TOPICS = [TX_TOPIC]
  308. RX_IGNORE_KEYS = ['update', 'color_mode']
  309. RX_FILTER_DATA_KEYS = [KEY_OUTPUT_0, KEY_BRIGHTNESS, KEY_COLOR_TEMP]
  310. def __init__(self, mqtt_client, topic):
  311. super().__init__(mqtt_client, topic)
  312. def unpack_filter(self, key):
  313. if key == self.KEY_BRIGHTNESS:
  314. self[key] = self[key] * 100 / 256
  315. elif key == self.KEY_COLOR_TEMP:
  316. self[key] = (self[key] - 250) * 100 / 204
  317. else:
  318. super().unpack_filter(key)
  319. def pack_filter(self, key, data):
  320. if key == self.KEY_BRIGHTNESS:
  321. return data * 256 / 100
  322. elif key == self.KEY_COLOR_TEMP:
  323. return data * 204 / 100 + 250
  324. else:
  325. return super().pack_filter(key, data)
  326. #
  327. # RX
  328. #
  329. @property
  330. def output_0(self):
  331. """rv: [True, False]"""
  332. return self.get(self.KEY_OUTPUT_0)
  333. @property
  334. def linkquality(self):
  335. """rv: numeric value"""
  336. return self.get(self.KEY_LINKQUALITY)
  337. @property
  338. def brightness(self):
  339. """rv: numeric value [0%, ..., 100%"""
  340. return self.get(self.KEY_BRIGHTNESS)
  341. @property
  342. def color_temp(self):
  343. """rv: numeric value [0%, ..., 100%"""
  344. return self.get(self.KEY_COLOR_TEMP)
  345. #
  346. # TX
  347. #
  348. def set_output_0(self, state):
  349. """state: [True, False, 'toggle']"""
  350. self.pack(self.KEY_OUTPUT_0, state)
  351. def set_brightness(self, brightness):
  352. """brightness: [0, ..., 100]"""
  353. self.pack(self.KEY_BRIGHTNESS, brightness)
  354. def set_color_temp(self, color_temp):
  355. """color_temp: [0, ..., 100]"""
  356. self.pack(self.KEY_COLOR_TEMP, color_temp)
  357. class tradfri_button(base):
  358. KEY_LINKQUALITY = "linkquality"
  359. KEY_BATTERY = "battery"
  360. KEY_ACTION = "action"
  361. #
  362. RX_LOG_INFO_ALWAYS_KEYS = [KEY_ACTION]
  363. RX_KEYS = [KEY_LINKQUALITY, KEY_BATTERY, KEY_ACTION]
  364. RX_IGNORE_TOPICS = []
  365. RX_IGNORE_KEYS = ['update']
  366. RX_FILTER_DATA_KEYS = []
  367. def __init__(self, mqtt_client, topic):
  368. super().__init__(mqtt_client, topic)
  369. #
  370. # RX
  371. #
  372. @property
  373. def action(self):
  374. """rv: action_txt"""
  375. return self.get(self.KEY_ACTION)
  376. #
  377. # WARNING CALL
  378. #
  379. def warning_call_condition(self):
  380. return self.get(self.KEY_BATTERY) <= BATTERY_WARN_LEVEL
  381. def warning_text(self):
  382. return "Low battery level detected for %s. Battery level was %.0f%%." % (self.topic, self.get(self.KEY_BATTERY))