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.

__init__.py 14KB

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