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

__init__.py 17KB

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