Smarthome Functionen
選択できるのは25トピックまでです。 トピックは、先頭が英数字で、英数字とダッシュ('-')を使用した35文字以内のものにしてください。

__init__.py 14KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516
  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. RX_IGNORE_KEYS = ['temperature_f']
  168. RX_FILTER_DATA_KEYS = [KEY_INPUT_0, KEY_INPUT_1,
  169. KEY_OUTPUT_0, KEY_OUTPUT_1, KEY_OVERTEMPERATURE]
  170. def __init__(self, mqtt_client, topic):
  171. super().__init__(mqtt_client, topic)
  172. #
  173. # WARNING CALL
  174. #
  175. def warning_call_condition(self):
  176. return self.get(self.KEY_OVERTEMPERATURE)
  177. def warning_text(self):
  178. if self.overtemperature:
  179. if self.temperature is not None:
  180. return "Overtemperature detected for %s. Temperature was %.1f°C." % (self.topic, self.temperature)
  181. else:
  182. return "Overtemperature detected for %s." % self.topic
  183. #
  184. # RX
  185. #
  186. @property
  187. def output_0(self):
  188. """rv: [True, False]"""
  189. return self.get(self.KEY_OUTPUT_0)
  190. @property
  191. def output_1(self):
  192. """rv: [True, False]"""
  193. return self.get(self.KEY_OUTPUT_1)
  194. @property
  195. def input_0(self):
  196. """rv: [True, False]"""
  197. return self.get(self.KEY_INPUT_0)
  198. @property
  199. def input_1(self):
  200. """rv: [True, False]"""
  201. return self.get(self.KEY_INPUT_1)
  202. @property
  203. def temperature(self):
  204. """rv: numeric value"""
  205. return self.get(self.KEY_TEMPERATURE)
  206. #
  207. # TX
  208. #
  209. def set_output_0(self, state):
  210. """state: [True, False, 'toggle']"""
  211. self.pack(self.KEY_OUTPUT_0, state)
  212. def set_output_1(self, state):
  213. """state: [True, False, 'toggle']"""
  214. self.pack(self.KEY_OUTPUT_1, state)
  215. class silvercrest_powerplug(base):
  216. KEY_LINKQUALITY = "linkquality"
  217. KEY_OUTPUT_0 = "state"
  218. #
  219. TX_TOPIC = 'set'
  220. TX_TYPE = base.TX_DICT
  221. TX_FILTER_DATA_KEYS = [KEY_OUTPUT_0]
  222. #
  223. RX_KEYS = [KEY_LINKQUALITY, KEY_OUTPUT_0]
  224. RX_IGNORE_TOPICS = [TX_TOPIC]
  225. RX_IGNORE_KEYS = []
  226. RX_FILTER_DATA_KEYS = [KEY_OUTPUT_0]
  227. def __init__(self, mqtt_client, topic):
  228. super().__init__(mqtt_client, topic)
  229. #
  230. # RX
  231. #
  232. @property
  233. def output_0(self):
  234. """rv: [True, False]"""
  235. return self.get(self.KEY_OUTPUT_0)
  236. @property
  237. def linkquality(self):
  238. """rv: numeric value"""
  239. return self.get(self.KEY_LINKQUALITY)
  240. #
  241. # TX
  242. #
  243. def set_output_0(self, state):
  244. """state: [True, False, 'toggle']"""
  245. self.pack(self.KEY_OUTPUT_0, state)
  246. class my_powerplug(base):
  247. KEY_OUTPUT_0 = "output/1"
  248. KEY_OUTPUT_1 = "output/2"
  249. KEY_OUTPUT_2 = "output/3"
  250. KEY_OUTPUT_3 = "output/4"
  251. KEY_OUTPUT_ALL = "output/all"
  252. #
  253. TX_TOPIC = 'set'
  254. TX_TYPE = base.TX_VALUE
  255. #
  256. RX_KEYS = [KEY_OUTPUT_0, KEY_OUTPUT_1, KEY_OUTPUT_2, KEY_OUTPUT_3]
  257. RX_IGNORE_TOPICS = [KEY_OUTPUT_0 + "/" + TX_TOPIC, KEY_OUTPUT_1 + "/" + TX_TOPIC,
  258. KEY_OUTPUT_2 + "/" + TX_TOPIC, KEY_OUTPUT_3 + "/" + TX_TOPIC]
  259. RX_IGNORE_KEYS = []
  260. RX_FILTER_DATA_KEYS = []
  261. def __init__(self, mqtt_client, topic):
  262. super().__init__(mqtt_client, topic)
  263. #
  264. # RX
  265. #
  266. @property
  267. def output_0(self):
  268. """rv: [True, False]"""
  269. return self.get(self.KEY_OUTPUT_0)
  270. @property
  271. def output_1(self):
  272. """rv: [True, False]"""
  273. return self.get(self.KEY_OUTPUT_1)
  274. @property
  275. def output_2(self):
  276. """rv: [True, False]"""
  277. return self.get(self.KEY_OUTPUT_2)
  278. @property
  279. def output_3(self):
  280. """rv: [True, False]"""
  281. return self.get(self.KEY_OUTPUT_3)
  282. #
  283. # TX
  284. #
  285. def set_output_0(self, state):
  286. """state: [True, False, 'toggle']"""
  287. self.pack(self.KEY_OUTPUT_0, state)
  288. def set_output_1(self, state):
  289. """state: [True, False, 'toggle']"""
  290. self.pack(self.KEY_OUTPUT_1, state)
  291. def set_output_2(self, state):
  292. """state: [True, False, 'toggle']"""
  293. self.pack(self.KEY_OUTPUT_2, state)
  294. def set_output_3(self, state):
  295. """state: [True, False, 'toggle']"""
  296. self.pack(self.KEY_OUTPUT_3, state)
  297. def set_output_all(self, state):
  298. """state: [True, False, 'toggle']"""
  299. self.pack(self.KEY_OUTPUT_ALL, state)
  300. class tradfri_light(base):
  301. KEY_LINKQUALITY = "linkquality"
  302. KEY_OUTPUT_0 = "state"
  303. KEY_BRIGHTNESS = "brightness"
  304. KEY_COLOR_TEMP = "color_temp"
  305. #
  306. TX_TOPIC = 'set'
  307. TX_TYPE = base.TX_DICT
  308. TX_FILTER_DATA_KEYS = [KEY_OUTPUT_0, KEY_BRIGHTNESS, KEY_COLOR_TEMP]
  309. #
  310. RX_KEYS = [KEY_LINKQUALITY, KEY_OUTPUT_0, KEY_BRIGHTNESS, KEY_COLOR_TEMP]
  311. RX_IGNORE_TOPICS = [TX_TOPIC]
  312. RX_IGNORE_KEYS = ['update', 'color_mode']
  313. RX_FILTER_DATA_KEYS = [KEY_OUTPUT_0, KEY_BRIGHTNESS, KEY_COLOR_TEMP]
  314. def __init__(self, mqtt_client, topic):
  315. super().__init__(mqtt_client, topic)
  316. def unpack_filter(self, key):
  317. if key == self.KEY_BRIGHTNESS:
  318. self[key] = (self[key] - 1) * 100 / 254
  319. elif key == self.KEY_COLOR_TEMP:
  320. self[key] = (self[key] - 250) * 100 / 204
  321. else:
  322. super().unpack_filter(key)
  323. def pack_filter(self, key, data):
  324. if key == self.KEY_BRIGHTNESS:
  325. return data * 254 / 100 + 1
  326. elif key == self.KEY_COLOR_TEMP:
  327. return data * 204 / 100 + 250
  328. else:
  329. return super().pack_filter(key, data)
  330. #
  331. # RX
  332. #
  333. @property
  334. def output_0(self):
  335. """rv: [True, False]"""
  336. return self.get(self.KEY_OUTPUT_0, False)
  337. @property
  338. def linkquality(self):
  339. """rv: numeric value"""
  340. return self.get(self.KEY_LINKQUALITY, 0)
  341. @property
  342. def brightness(self):
  343. """rv: numeric value [0%, ..., 100%"""
  344. return self.get(self.KEY_BRIGHTNESS, 0)
  345. @property
  346. def color_temp(self):
  347. """rv: numeric value [0%, ..., 100%"""
  348. return self.get(self.KEY_COLOR_TEMP, 0)
  349. #
  350. # TX
  351. #
  352. def set_output_0(self, state):
  353. """state: [True, False, 'toggle']"""
  354. self.pack(self.KEY_OUTPUT_0, state)
  355. def set_brightness(self, brightness):
  356. """brightness: [0, ..., 100]"""
  357. self.pack(self.KEY_BRIGHTNESS, brightness)
  358. def set_color_temp(self, color_temp):
  359. """color_temp: [0, ..., 100]"""
  360. self.pack(self.KEY_COLOR_TEMP, color_temp)
  361. class tradfri_button(base):
  362. KEY_LINKQUALITY = "linkquality"
  363. KEY_BATTERY = "battery"
  364. KEY_ACTION = "action"
  365. #
  366. RX_LOG_INFO_ALWAYS_KEYS = [KEY_ACTION]
  367. RX_KEYS = [KEY_LINKQUALITY, KEY_BATTERY, KEY_ACTION]
  368. RX_IGNORE_TOPICS = []
  369. RX_IGNORE_KEYS = ['update']
  370. RX_FILTER_DATA_KEYS = []
  371. def __init__(self, mqtt_client, topic):
  372. super().__init__(mqtt_client, topic)
  373. #
  374. # RX
  375. #
  376. @property
  377. def action(self):
  378. """rv: action_txt"""
  379. return self.get(self.KEY_ACTION)
  380. #
  381. # WARNING CALL
  382. #
  383. def warning_call_condition(self):
  384. return self.get(self.KEY_BATTERY) <= BATTERY_WARN_LEVEL
  385. def warning_text(self):
  386. return "Low battery level detected for %s. Battery level was %.0f%%." % (self.topic, self.get(self.KEY_BATTERY))
  387. class nodered_gui(base):
  388. KEY_FEEDBACK = "feedback"
  389. KEY_ENABLE = "enable"
  390. KEY_STATE = "state"
  391. KEY_BRIGHTNESS = "brightness"
  392. KEY_COLOR_TEMP = "color_temp"
  393. #
  394. TX_TOPIC = 'set'
  395. TX_TYPE = base.TX_VALUE
  396. TX_FILTER_DATA_KEYS = []
  397. #
  398. RX_LOG_INFO_ALWAYS_KEYS = []
  399. RX_KEYS = [KEY_STATE, KEY_BRIGHTNESS, KEY_COLOR_TEMP]
  400. RX_IGNORE_TOPICS = [KEY_FEEDBACK + '/' + TX_TOPIC, KEY_ENABLE + '/' + TX_TOPIC]
  401. RX_FILTER_DATA_KEYS = []
  402. def __init__(self, mqtt_client, topic):
  403. super().__init__(mqtt_client, topic)
  404. #
  405. # RX
  406. #
  407. @property
  408. def state(self):
  409. """rv: [True, False]"""
  410. return self.get(self.KEY_STATE)
  411. @property
  412. def brightness(self):
  413. """rv: [0, ..., 100]"""
  414. return self.get(self.KEY_BRIGHTNESS)
  415. @property
  416. def color_temp(self):
  417. """rv: [0, ..., 100]"""
  418. return self.get(self.KEY_COLOR_TEMP)
  419. #
  420. # TX
  421. #
  422. def set_feedback(self, data):
  423. self.pack(self.KEY_FEEDBACK, data)
  424. def enable(self, data):
  425. """data: [True, False]"""
  426. self.pack(self.KEY_ENABLE, data)