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.

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012
  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. from base import mqtt_base
  19. from base import videv_base
  20. import json
  21. import logging
  22. import math
  23. import task
  24. import time
  25. try:
  26. from config import APP_NAME as ROOT_LOGGER_NAME
  27. except ImportError:
  28. ROOT_LOGGER_NAME = 'root'
  29. BATTERY_WARN_LEVEL = 10
  30. class warning(dict):
  31. TYPE_BATTERY_LOW = 1
  32. TYPE_OVERTEMPERATURE = 2
  33. #
  34. KEY_ID = 'id'
  35. KEY_TYPE = 'type'
  36. KEY_TEXT = 'text'
  37. KEY_TM = 'tm'
  38. def __init__(self, identification, type, text, args):
  39. super().__init__({
  40. self.KEY_ID: identification,
  41. self.KEY_TYPE: type,
  42. self.KEY_TEXT: text % args,
  43. self.KEY_TM: time.localtime(),
  44. })
  45. def __str__(self):
  46. return time.asctime(self.get(self.KEY_TM)) + ": " + self[self.KEY_TEXT] + " - " + self[self.KEY_ID]
  47. def is_json(data):
  48. try:
  49. json.loads(data)
  50. except json.decoder.JSONDecodeError:
  51. return False
  52. else:
  53. return True
  54. class group(object):
  55. def __init__(self, *args):
  56. super().__init__()
  57. self._members = args
  58. self._iter_counter = 0
  59. #
  60. self.methods = []
  61. for method in [m for m in args[0].__class__.__dict__.keys()]:
  62. if not method.startswith('_') and callable(getattr(args[0], method)): # add all public callable attributes to the list
  63. self.methods.append(method)
  64. #
  65. for member in self:
  66. methods = [m for m in member.__class__.__dict__.keys() if not m.startswith(
  67. '_') if not m.startswith('_') and callable(getattr(args[0], m))]
  68. if self.methods != methods:
  69. raise ValueError("All given instances needs to have same attributes:", self.methods, methods)
  70. def __iter__(self):
  71. return self
  72. def __next__(self):
  73. if self._iter_counter < len(self):
  74. self._iter_counter += 1
  75. return self._members[self._iter_counter - 1]
  76. self._iter_counter = 0
  77. raise StopIteration
  78. def __getitem__(self, i):
  79. return self._members[i]
  80. def __len__(self):
  81. return len(self._members)
  82. def __getattribute__(self, name):
  83. def group_execution(*args, **kwargs):
  84. for member in self[:]:
  85. m = getattr(member, name)
  86. m(*args, **kwargs)
  87. try:
  88. rv = super().__getattribute__(name)
  89. except AttributeError:
  90. return group_execution
  91. else:
  92. return rv
  93. class base(mqtt_base):
  94. TX_TOPIC = "set"
  95. TX_VALUE = 0
  96. TX_DICT = 1
  97. TX_TYPE = -1
  98. TX_FILTER_DATA_KEYS = []
  99. #
  100. RX_KEYS = []
  101. RX_IGNORE_TOPICS = []
  102. RX_IGNORE_KEYS = []
  103. RX_FILTER_DATA_KEYS = []
  104. #
  105. KEY_WARNING = '__WARNING__'
  106. def __init__(self, mqtt_client, topic):
  107. super().__init__(mqtt_client, topic, default_values=dict.fromkeys(self.RX_KEYS + [self.KEY_WARNING]))
  108. # data storage
  109. # initialisations
  110. mqtt_client.add_callback(topic=self.topic, callback=self.receive_callback)
  111. mqtt_client.add_callback(topic=self.topic+"/#", callback=self.receive_callback)
  112. def set(self, key, data, block_callback=[]):
  113. if key in self.RX_IGNORE_KEYS:
  114. pass # ignore these keys
  115. elif key in self.RX_KEYS or key == self.KEY_WARNING:
  116. return super().set(key, data, block_callback)
  117. else:
  118. self.logger.warning("Unexpected key %s", key)
  119. def receive_callback(self, client, userdata, message):
  120. if message.topic != self.topic + '/' + videv_base.KEY_INFO:
  121. content_key = message.topic[len(self.topic) + 1:]
  122. if content_key not in self.RX_IGNORE_TOPICS and (not message.topic.endswith(self.TX_TOPIC) or len(self.TX_TOPIC) == 0):
  123. self.logger.debug("Unpacking content_key \"%s\" from message.", content_key)
  124. if is_json(message.payload):
  125. data = json.loads(message.payload)
  126. if type(data) is dict:
  127. for key in data:
  128. self.set(key, self.__device_to_instance_filter__(key, data[key]))
  129. else:
  130. self.set(content_key, self.__device_to_instance_filter__(content_key, data))
  131. # String
  132. else:
  133. self.set(content_key, self.__device_to_instance_filter__(content_key, message.payload.decode('utf-8')))
  134. else:
  135. self.logger.debug("Ignoring topic %s", content_key)
  136. def __device_to_instance_filter__(self, key, data):
  137. if key in self.RX_FILTER_DATA_KEYS:
  138. if data in [1, 'on', 'ON']:
  139. return True
  140. elif data in [0, 'off', 'OFF']:
  141. return False
  142. return data
  143. def __instance_to_device_filter__(self, key, data):
  144. if key in self.TX_FILTER_DATA_KEYS:
  145. if data is True:
  146. return "on"
  147. elif data is False:
  148. return "off"
  149. return data
  150. def send_command(self, key, data):
  151. data = self.__instance_to_device_filter__(key, data)
  152. if self.TX_TOPIC is not None:
  153. if self.TX_TYPE < 0:
  154. self.logger.error("Unknown tx type. Set TX_TYPE of class to a known value")
  155. else:
  156. self.logger.debug("Sending data for %s - %s", key, str(data))
  157. if self.TX_TYPE == self.TX_DICT:
  158. self.mqtt_client.send('/'.join([self.topic, self.TX_TOPIC]), json.dumps({key: data}))
  159. else:
  160. if type(data) not in [str, bytes]:
  161. data = json.dumps(data)
  162. self.mqtt_client.send('/'.join([self.topic, key, self.TX_TOPIC] if len(self.TX_TOPIC) > 0 else [self.topic, key]), data)
  163. else:
  164. self.logger.error("Unknown tx toptic. Set TX_TOPIC of class to a known value")
  165. class shelly(base):
  166. """ Communication (MQTT)
  167. shelly
  168. +- relay
  169. | +- 0 ["on" / "off"] <- status
  170. | | +- command ["on"/ "off"] <- command
  171. | | +- energy [numeric] <- status
  172. | +- 1 ["on" / "off"] <- status
  173. | +- command ["on"/ "off"] <- command
  174. | +- energy [numeric] <- status
  175. +- input
  176. | +- 0 [0 / 1] <- status
  177. | +- 1 [0 / 1] <- status
  178. +- input_event
  179. | +- 0 <- status
  180. | +- 1 <- status
  181. +- logpush
  182. | +- 0 [0 / 1] <- status
  183. | +- 1 [0 / 1] <- status
  184. +- temperature [numeric] °C <- status
  185. +- temperature_f [numeric] F <- status
  186. +- overtemperature [0 / 1] <- status
  187. +- id <- status
  188. +- model <- status
  189. +- mac <- status
  190. +- ip <- status
  191. +- new_fw <- status
  192. +- fw_ver <- status
  193. """
  194. KEY_OUTPUT_0 = "relay/0"
  195. KEY_OUTPUT_1 = "relay/1"
  196. KEY_INPUT_0 = "input/0"
  197. KEY_INPUT_1 = "input/1"
  198. KEY_LONGPUSH_0 = "longpush/0"
  199. KEY_LONGPUSH_1 = "longpush/1"
  200. KEY_TEMPERATURE = "temperature"
  201. KEY_OVERTEMPERATURE = "overtemperature"
  202. KEY_ID = "id"
  203. KEY_MODEL = "model"
  204. KEY_MAC = "mac"
  205. KEY_IP = "ip"
  206. KEY_NEW_FIRMWARE = "new_fw"
  207. KEY_FIRMWARE_VERSION = "fw_ver"
  208. #
  209. TX_TOPIC = "command"
  210. TX_TYPE = base.TX_VALUE
  211. TX_FILTER_DATA_KEYS = [KEY_OUTPUT_0, KEY_OUTPUT_1]
  212. #
  213. RX_KEYS = [KEY_OUTPUT_0, KEY_OUTPUT_1, KEY_INPUT_0, KEY_INPUT_1, KEY_LONGPUSH_0, KEY_LONGPUSH_1, KEY_OVERTEMPERATURE, KEY_TEMPERATURE,
  214. KEY_ID, KEY_MODEL, KEY_MAC, KEY_IP, KEY_NEW_FIRMWARE, KEY_FIRMWARE_VERSION]
  215. RX_IGNORE_TOPICS = [KEY_OUTPUT_0 + '/' + "energy", KEY_OUTPUT_1 + '/' + "energy", 'input_event/0', 'input_event/1']
  216. RX_IGNORE_KEYS = ['temperature_f']
  217. RX_FILTER_DATA_KEYS = [KEY_INPUT_0, KEY_INPUT_1, KEY_LONGPUSH_0, KEY_LONGPUSH_1, KEY_OUTPUT_0, KEY_OUTPUT_1, KEY_OVERTEMPERATURE]
  218. def __init__(self, mqtt_client, topic):
  219. super().__init__(mqtt_client, topic)
  220. #
  221. self.output_key_delayed = None
  222. self.delayed_flash_task = task.delayed(0.3, self.flash_task)
  223. self.delayed_off_task = task.delayed(0.3, self.off_task)
  224. #
  225. self.add_callback(self.KEY_OVERTEMPERATURE, True, self.__warning__, True)
  226. #
  227. self.all_off_requested = False
  228. def flash_task(self, *args):
  229. if self.flash_active:
  230. self.send_command(self.output_key_delayed, not self.get(self.output_key_delayed))
  231. self.output_key_delayed = None
  232. if self.all_off_requested:
  233. self.delayed_off_task.run()
  234. def off_task(self, *args):
  235. self.all_off()
  236. @property
  237. def flash_active(self):
  238. return self.output_key_delayed is not None
  239. #
  240. # WARNING CALL
  241. #
  242. def __warning__(self, client, key, data):
  243. w = warning(self.topic, warning.TYPE_OVERTEMPERATURE, "Temperature to high (%.1f°C)", self.get(self.KEY_TEMPERATURE) or math.nan)
  244. self.logger.warning(w)
  245. self.set(self.KEY_WARNING, w)
  246. #
  247. # RX
  248. #
  249. @property
  250. def output_0(self):
  251. """rv: [True, False]"""
  252. return self.get(self.KEY_OUTPUT_0)
  253. @property
  254. def output_1(self):
  255. """rv: [True, False]"""
  256. return self.get(self.KEY_OUTPUT_1)
  257. @property
  258. def input_0(self):
  259. """rv: [True, False]"""
  260. return self.get(self.KEY_INPUT_0)
  261. @property
  262. def input_1(self):
  263. """rv: [True, False]"""
  264. return self.get(self.KEY_INPUT_1)
  265. @property
  266. def longpush_0(self):
  267. """rv: [True, False]"""
  268. return self.get(self.KEY_LONGPUSH_0)
  269. @property
  270. def longpush_1(self):
  271. """rv: [True, False]"""
  272. return self.get(self.KEY_LONGPUSH_1)
  273. @property
  274. def temperature(self):
  275. """rv: numeric value"""
  276. return self.get(self.KEY_TEMPERATURE)
  277. #
  278. # TX
  279. #
  280. def set_output_0(self, state):
  281. """state: [True, False]"""
  282. self.send_command(self.KEY_OUTPUT_0, state)
  283. def set_output_0_mcb(self, device, key, data):
  284. self.logger.log(logging.INFO if data != self.output_0 else logging.DEBUG, "Changing output 0 to %s", str(data))
  285. self.set_output_0(data)
  286. def toggle_output_0_mcb(self, device, key, data):
  287. self.logger.info("Toggeling output 0")
  288. self.set_output_0(not self.output_0)
  289. def set_output_1(self, state):
  290. """state: [True, False]"""
  291. self.send_command(self.KEY_OUTPUT_1, state)
  292. def set_output_1_mcb(self, device, key, data):
  293. self.logger.log(logging.INFO if data != self.output_1 else logging.DEBUG, "Changing output 1 to %s", str(data))
  294. self.set_output_1(data)
  295. def toggle_output_1_mcb(self, device, key, data):
  296. self.logger.info("Toggeling output 1")
  297. self.set_output_1(not self.output_1)
  298. def flash_0_mcb(self, device, key, data):
  299. self.output_key_delayed = self.KEY_OUTPUT_0
  300. self.toggle_output_0_mcb(device, key, data)
  301. self.delayed_flash_task.run()
  302. def flash_1_mcb(self, device, key, data):
  303. self.output_key_delayed = self.KEY_OUTPUT_1
  304. self.toggle_output_1_mcb(device, key, data)
  305. self.delayed_flash_task.run()
  306. def all_off(self):
  307. if self.flash_active:
  308. self.all_off_requested = True
  309. else:
  310. if self.output_0:
  311. self.set_output_0(False)
  312. if self.output_1:
  313. self.set_output_1(False)
  314. class silvercrest_powerplug(base):
  315. """ Communication (MQTT)
  316. silvercrest_powerplug {
  317. | "state": ["ON" / "OFF"]
  318. | "linkquality": [0...255] lqi
  319. | }
  320. +- get {
  321. | "state": ""
  322. | }
  323. +- set {
  324. "state": ["ON" / "OFF"]
  325. }
  326. """
  327. KEY_LINKQUALITY = "linkquality"
  328. KEY_OUTPUT_0 = "state"
  329. #
  330. TX_TYPE = base.TX_DICT
  331. TX_FILTER_DATA_KEYS = [KEY_OUTPUT_0]
  332. #
  333. RX_KEYS = [KEY_LINKQUALITY, KEY_OUTPUT_0]
  334. RX_FILTER_DATA_KEYS = [KEY_OUTPUT_0]
  335. def __init__(self, mqtt_client, topic):
  336. super().__init__(mqtt_client, topic)
  337. #
  338. # RX
  339. #
  340. @property
  341. def output_0(self):
  342. """rv: [True, False]"""
  343. return self.get(self.KEY_OUTPUT_0)
  344. @property
  345. def linkquality(self):
  346. """rv: numeric value"""
  347. return self.get(self.KEY_LINKQUALITY)
  348. #
  349. # TX
  350. #
  351. def set_output_0(self, state):
  352. """state: [True, False]"""
  353. self.send_command(self.KEY_OUTPUT_0, state)
  354. def set_output_0_mcb(self, device, key, data):
  355. self.logger.log(logging.INFO if data != self.output_0 else logging.DEBUG, "Changing output 0 to %s", str(data))
  356. self.set_output_0(data)
  357. def toggle_output_0_mcb(self, device, key, data):
  358. self.logger.info("Toggeling output 0")
  359. self.set_output_0(not self.output_0)
  360. def all_off(self):
  361. if self.output_0:
  362. self.set_output_0(False)
  363. class silvercrest_motion_sensor(base):
  364. """ Communication (MQTT)
  365. silvercrest_motion_sensor {
  366. battery: [0...100] %
  367. battery_low: [True, False]
  368. linkquality: [0...255] lqi
  369. occupancy: [True, False]
  370. tamper: [True, False]
  371. voltage: [0...] mV
  372. }
  373. """
  374. KEY_BATTERY = "battery"
  375. KEY_BATTERY_LOW = "battery_low"
  376. KEY_LINKQUALITY = "linkquality"
  377. KEY_OCCUPANCY = "occupancy"
  378. KEY_UNMOUNTED = "tamper"
  379. KEY_VOLTAGE = "voltage"
  380. #
  381. TX_TYPE = base.TX_DICT
  382. #
  383. RX_KEYS = [KEY_BATTERY, KEY_BATTERY_LOW, KEY_LINKQUALITY, KEY_OCCUPANCY, KEY_UNMOUNTED, KEY_VOLTAGE]
  384. def __init__(self, mqtt_client, topic):
  385. super().__init__(mqtt_client, topic)
  386. #
  387. self.add_callback(self.KEY_BATTERY_LOW, True, self.__warning__, True)
  388. #
  389. # WARNING CALL
  390. #
  391. def __warning__(self, client, key, data):
  392. w = warning(self.topic, warning.TYPE_BATTERY_LOW, "Battery low (%.1f%%)", self.get(self.KEY_BATTERY) or math.nan)
  393. self.logger.warning(w)
  394. self.set(self.KEY_WARNING, w)
  395. #
  396. # RX
  397. #
  398. @property
  399. def linkquality(self):
  400. """rv: numeric value"""
  401. return self.get(self.KEY_LINKQUALITY)
  402. @property
  403. def battery(self):
  404. """rv: numeric value"""
  405. return self.get(self.KEY_BATTERY)
  406. class my_powerplug(base):
  407. """ Communication (MQTT)
  408. my_powerplug
  409. +- output
  410. +- 1 [True, False] <- status
  411. | +- set [True, False, "toggle"] <- command
  412. +- 2 [True, False] <- status
  413. | +- set [True, False, "toggle"] <- command
  414. +- 3 [True, False] <- status
  415. | +- set [True, False, "toggle"] <- command
  416. +- 4 [True, False] <- status
  417. | +- set [True, False, "toggle"] <- command
  418. +- all
  419. +- set [True, False, "toggle"] <- command
  420. """
  421. KEY_OUTPUT_0 = "output/1"
  422. KEY_OUTPUT_1 = "output/2"
  423. KEY_OUTPUT_2 = "output/3"
  424. KEY_OUTPUT_3 = "output/4"
  425. KEY_OUTPUT_ALL = "output/all"
  426. KEY_OUTPUT_LIST = [KEY_OUTPUT_0, KEY_OUTPUT_1, KEY_OUTPUT_2, KEY_OUTPUT_3]
  427. #
  428. TX_TYPE = base.TX_VALUE
  429. #
  430. RX_KEYS = [KEY_OUTPUT_0, KEY_OUTPUT_1, KEY_OUTPUT_2, KEY_OUTPUT_3]
  431. def __init__(self, mqtt_client, topic):
  432. super().__init__(mqtt_client, topic)
  433. #
  434. # RX
  435. #
  436. @property
  437. def output_0(self):
  438. """rv: [True, False]"""
  439. return self.get(self.KEY_OUTPUT_0)
  440. @property
  441. def output_1(self):
  442. """rv: [True, False]"""
  443. return self.get(self.KEY_OUTPUT_1)
  444. @property
  445. def output_2(self):
  446. """rv: [True, False]"""
  447. return self.get(self.KEY_OUTPUT_2)
  448. @property
  449. def output_3(self):
  450. """rv: [True, False]"""
  451. return self.get(self.KEY_OUTPUT_3)
  452. #
  453. # TX
  454. #
  455. def set_output(self, key, state):
  456. if key in self.KEY_OUTPUT_LIST:
  457. self.send_command(key, state)
  458. else:
  459. logging.error("Unknown key to set the output!")
  460. def set_output_0(self, state):
  461. """state: [True, False]"""
  462. self.send_command(self.KEY_OUTPUT_0, state)
  463. def set_output_0_mcb(self, device, key, data):
  464. self.logger.log(logging.INFO if data != self.output_0 else logging.DEBUG, "Changing output 0 to %s", str(data))
  465. self.set_output_0(data)
  466. def toggle_output_0_mcb(self, device, key, data):
  467. self.logger.info("Toggeling output 0")
  468. self.set_output_0(not self.output_0)
  469. def set_output_1(self, state):
  470. """state: [True, False]"""
  471. self.send_command(self.KEY_OUTPUT_1, state)
  472. def set_output_1_mcb(self, device, key, data):
  473. self.logger.log(logging.INFO if data != self.output_1 else logging.DEBUG, "Changing output 1 to %s", str(data))
  474. self.set_output_1(data)
  475. def toggle_output_1_mcb(self, device, key, data):
  476. self.logger.info("Toggeling output 1")
  477. self.set_output_1(not self.output_1)
  478. def set_output_2(self, state):
  479. """state: [True, False]"""
  480. self.send_command(self.KEY_OUTPUT_2, state)
  481. def set_output_2_mcb(self, device, key, data):
  482. self.logger.log(logging.INFO if data != self.output_2 else logging.DEBUG, "Changing output 2 to %s", str(data))
  483. self.set_output_2(data)
  484. def toggle_output_2_mcb(self, device, key, data):
  485. self.logger.info("Toggeling output 2")
  486. self.set_output_2(not self.output_2)
  487. def set_output_3(self, state):
  488. """state: [True, False]"""
  489. self.send_command(self.KEY_OUTPUT_3, state)
  490. def set_output_3_mcb(self, device, key, data):
  491. self.logger.log(logging.INFO if data != self.output_3 else logging.DEBUG, "Changing output 3 to %s", str(data))
  492. self.set_output_3(data)
  493. def toggle_output_3_mcb(self, device, key, data):
  494. self.logger.info("Toggeling output 3")
  495. self.set_output_3(not self.output_3)
  496. def set_output_all(self, state):
  497. """state: [True, False, 'toggle']"""
  498. self.send_command(self.KEY_OUTPUT_ALL, state)
  499. def set_output_all_mcb(self, device, key, data):
  500. self.logger.info("Changing all outputs to %s", str(data))
  501. self.set_output_all(data)
  502. def all_off(self):
  503. self.set_output_all(False)
  504. class tradfri_light(base):
  505. """ Communication (MQTT)
  506. tradfri_light {
  507. | "state": ["ON" / "OFF" / "TOGGLE"]
  508. | "linkquality": [0...255] lqi
  509. | "brightness": [0...254]
  510. | "color_mode": ["color_temp"]
  511. | "color_temp": ["coolest", "cool", "neutral", "warm", "warmest", 250...454]
  512. | "color_temp_startup": ["coolest", "cool", "neutral", "warm", "warmest", "previous", 250...454]
  513. | "update": []
  514. | }
  515. +- get {
  516. | "state": ""
  517. | }
  518. +- set {
  519. "state": ["ON" / "OFF"]
  520. "brightness": [0...256]
  521. "color_temp": [250...454]
  522. "transition": [0...] seconds
  523. "brightness_move": [-X...0...X] X/s
  524. "brightness_step": [-X...0...X]
  525. "color_temp_move": [-X...0...X] X/s
  526. "color_temp_step": [-X...0...X]
  527. }
  528. """
  529. KEY_LINKQUALITY = "linkquality"
  530. KEY_OUTPUT_0 = "state"
  531. KEY_BRIGHTNESS = "brightness"
  532. KEY_COLOR_TEMP = "color_temp"
  533. KEY_BRIGHTNESS_FADE = "brightness_move"
  534. #
  535. TX_TYPE = base.TX_DICT
  536. TX_FILTER_DATA_KEYS = [KEY_OUTPUT_0, KEY_BRIGHTNESS, KEY_COLOR_TEMP, KEY_BRIGHTNESS_FADE]
  537. #
  538. RX_KEYS = [KEY_LINKQUALITY, KEY_OUTPUT_0, KEY_BRIGHTNESS, KEY_COLOR_TEMP]
  539. RX_IGNORE_KEYS = ['update', 'color_mode', 'color_temp_startup']
  540. RX_FILTER_DATA_KEYS = [KEY_OUTPUT_0, KEY_BRIGHTNESS, KEY_COLOR_TEMP]
  541. def __init__(self, mqtt_client, topic):
  542. super().__init__(mqtt_client, topic)
  543. def __device_to_instance_filter__(self, key, data):
  544. if key == self.KEY_BRIGHTNESS:
  545. return int(round((data - 1) * 100 / 253, 0))
  546. elif key == self.KEY_COLOR_TEMP:
  547. return int(round((data - 250) * 10 / 204, 0))
  548. return super().__device_to_instance_filter__(key, data)
  549. def __instance_to_device_filter__(self, key, data):
  550. if key == self.KEY_BRIGHTNESS:
  551. return int(round(data * 253 / 100 + 1, 0))
  552. elif key == self.KEY_COLOR_TEMP:
  553. return int(round(data * 204 / 10 + 250, 0))
  554. return super().__instance_to_device_filter__(key, data)
  555. #
  556. # RX
  557. #
  558. @property
  559. def output_0(self):
  560. """rv: [True, False]"""
  561. return self.get(self.KEY_OUTPUT_0, False)
  562. @property
  563. def linkquality(self):
  564. """rv: numeric value"""
  565. return self.get(self.KEY_LINKQUALITY, 0)
  566. @property
  567. def brightness(self):
  568. """rv: numeric value [0%, ..., 100%]"""
  569. return self.get(self.KEY_BRIGHTNESS, 0)
  570. @property
  571. def color_temp(self):
  572. """rv: numeric value [0, ..., 10]"""
  573. return self.get(self.KEY_COLOR_TEMP, 0)
  574. #
  575. # TX
  576. #
  577. def request_data(self, device=None, key=None, data=None):
  578. self.mqtt_client.send(self.topic + "/get", '{"%s": ""}' % self.KEY_OUTPUT_0)
  579. def set_output_0(self, state):
  580. """state: [True, False]"""
  581. self.send_command(self.KEY_OUTPUT_0, state)
  582. def set_output_0_mcb(self, device, key, data):
  583. self.logger.log(logging.INFO if data != self.output_0 else logging.DEBUG, "Changing output 0 to %s", str(data))
  584. self.set_output_0(data)
  585. def toggle_output_0_mcb(self, device, key, data):
  586. self.logger.info("Toggeling output 0")
  587. self.set_output_0(not self.output_0)
  588. def set_brightness(self, brightness):
  589. """brightness: [0, ..., 100]"""
  590. self.send_command(self.KEY_BRIGHTNESS, brightness)
  591. def set_brightness_mcb(self, device, key, data):
  592. self.logger.log(logging.INFO if data != self.brightness else logging.DEBUG, "Changing brightness to %s", str(data))
  593. self.set_brightness(data)
  594. def default_inc(self, speed=40):
  595. self.send_command(self.KEY_BRIGHTNESS_FADE, speed)
  596. def default_dec(self, speed=-40):
  597. self.default_inc(speed)
  598. def default_stop(self):
  599. self.default_inc(0)
  600. def set_color_temp(self, color_temp):
  601. """color_temp: [0, ..., 10]"""
  602. self.send_command(self.KEY_COLOR_TEMP, color_temp)
  603. def set_color_temp_mcb(self, device, key, data):
  604. self.logger.log(logging.INFO if data != self.color_temp else logging.DEBUG, "Changing color temperature to %s", str(data))
  605. self.set_color_temp(data)
  606. def all_off(self):
  607. if self.output_0:
  608. self.set_output_0(False)
  609. class tradfri_button(base):
  610. """ Communication (MQTT)
  611. tradfri_button {
  612. "action": [
  613. "arrow_left_click",
  614. "arrow_left_hold",
  615. "arrow_left_release",
  616. "arrow_right_click",
  617. "arrow_right_hold",
  618. "arrow_right_release",
  619. "brightness_down_click",
  620. "brightness_down_hold",
  621. "brightness_down_release",
  622. "brightness_up_click",
  623. "brightness_up_hold",
  624. "brightness_up_release",
  625. "toggle"
  626. ]
  627. "action_duration": [0...] s
  628. "battery": [0...100] %
  629. "linkquality": [0...255] lqi
  630. "update": []
  631. }
  632. """
  633. ACTION_TOGGLE = "toggle"
  634. ACTION_BRIGHTNESS_UP = "brightness_up_click"
  635. ACTION_BRIGHTNESS_DOWN = "brightness_down_click"
  636. ACTION_RIGHT = "arrow_right_click"
  637. ACTION_LEFT = "arrow_left_click"
  638. ACTION_BRIGHTNESS_UP_LONG = "brightness_up_hold"
  639. ACTION_BRIGHTNESS_UP_RELEASE = "brightness_up_release"
  640. ACTION_BRIGHTNESS_DOWN_LONG = "brightness_down_hold"
  641. ACTION_BRIGHTNESS_DOWN_RELEASE = "brightness_down_release"
  642. ACTION_RIGHT_LONG = "arrow_right_hold"
  643. ACTION_RIGHT_RELEASE = "arrow_right_release"
  644. ACTION_LEFT_LONG = "arrow_left_hold"
  645. ACTION_LEFT_RELEASE = "arrow_left_release"
  646. #
  647. KEY_LINKQUALITY = "linkquality"
  648. KEY_BATTERY = "battery"
  649. KEY_ACTION = "action"
  650. KEY_ACTION_DURATION = "action_duration"
  651. #
  652. RX_KEYS = [KEY_LINKQUALITY, KEY_BATTERY, KEY_ACTION]
  653. RX_IGNORE_KEYS = ['update', KEY_ACTION_DURATION]
  654. def __init__(self, mqtt_client, topic):
  655. super().__init__(mqtt_client, topic)
  656. #
  657. self.add_callback(self.KEY_BATTERY, None, self.__warning__, True)
  658. self.__battery_warning__ = False
  659. #
  660. # WARNING CALL
  661. #
  662. def __warning__(self, client, key, data):
  663. if data <= BATTERY_WARN_LEVEL:
  664. if not self.__battery_warning__:
  665. w = warning(self.topic, warning.TYPE_BATTERY_LOW, "Battery low (%.1f%%)", data)
  666. self.logger.warning(w)
  667. self.set(self.KEY_WARNING, w)
  668. else:
  669. self.__battery_warning__ = False
  670. #
  671. # RX
  672. #
  673. @property
  674. def action(self):
  675. """rv: action_txt"""
  676. return self.get(self.KEY_ACTION)
  677. class brennenstuhl_heatingvalve(base):
  678. """ Communication (MQTT)
  679. brennenstuhl_heatingvalve {
  680. | "away_mode": ["ON", "OFF"]
  681. | "battery": [0...100] %
  682. | "child_lock": ["LOCK", "UNLOCK"]
  683. | "current_heating_setpoint": [5...30] °C
  684. | "linkquality": [0...255] lqi
  685. | "local_temperature": [numeric] °C
  686. | "preset": ["manual", ...]
  687. | "system_mode": ["heat", ...]
  688. | "valve_detection": ["ON", "OFF"]
  689. | "window_detection": ["ON", "OFF"]
  690. | }
  691. +- set {
  692. "away_mode": ["ON", "OFF", "TOGGLE"]
  693. "child_lock": ["LOCK", "UNLOCK"]
  694. "current_heating_setpoint": [5...30] °C
  695. "preset": ["manual", ...]
  696. "system_mode": ["heat", ...]
  697. "valve_detection": ["ON", "OFF", "TOGGLE"]
  698. "window_detection": ["ON", "OFF", "TOGGLE"]
  699. }
  700. """
  701. KEY_LINKQUALITY = "linkquality"
  702. KEY_BATTERY = "battery"
  703. KEY_HEATING_SETPOINT = "current_heating_setpoint"
  704. KEY_TEMPERATURE = "local_temperature"
  705. #
  706. KEY_AWAY_MODE = "away_mode"
  707. KEY_CHILD_LOCK = "child_lock"
  708. KEY_PRESET = "preset"
  709. KEY_SYSTEM_MODE = "system_mode"
  710. KEY_VALVE_DETECTION = "valve_detection"
  711. KEY_WINDOW_DETECTION = "window_detection"
  712. #
  713. TX_TYPE = base.TX_DICT
  714. #
  715. RX_KEYS = [KEY_LINKQUALITY, KEY_BATTERY, KEY_HEATING_SETPOINT, KEY_TEMPERATURE]
  716. RX_IGNORE_KEYS = [KEY_AWAY_MODE, KEY_CHILD_LOCK, KEY_PRESET, KEY_SYSTEM_MODE, KEY_VALVE_DETECTION, KEY_WINDOW_DETECTION]
  717. def __init__(self, mqtt_client, topic):
  718. super().__init__(mqtt_client, topic)
  719. self.mqtt_client.send(self.topic + '/' + self.TX_TOPIC, json.dumps({self.KEY_WINDOW_DETECTION: "ON",
  720. self.KEY_CHILD_LOCK: "UNLOCK", self.KEY_VALVE_DETECTION: "ON", self.KEY_SYSTEM_MODE: "heat", self.KEY_PRESET: "manual"}))
  721. #
  722. self.add_callback(self.KEY_BATTERY, None, self.__warning__, True)
  723. self.__battery_warning__ = False
  724. #
  725. # WARNING CALL
  726. #
  727. def __warning__(self, client, key, data):
  728. if data <= BATTERY_WARN_LEVEL:
  729. if not self.__battery_warning__:
  730. self.__battery_warning__ = True
  731. w = warning(self.topic, warning.TYPE_BATTERY_LOW, "Battery low (%.1f%%)", data)
  732. self.logger.warning(w)
  733. self.set(self.KEY_WARNING, w)
  734. else:
  735. self.__battery_warning__ = False
  736. #
  737. # RX
  738. #
  739. @property
  740. def linkqulity(self):
  741. return self.get(self.KEY_LINKQUALITY)
  742. @property
  743. def heating_setpoint(self):
  744. return self.get(self.KEY_HEATING_SETPOINT)
  745. @property
  746. def temperature(self):
  747. return self.get(self.KEY_TEMPERATURE)
  748. #
  749. # TX
  750. #
  751. def set_heating_setpoint(self, setpoint):
  752. self.send_command(self.KEY_HEATING_SETPOINT, setpoint)
  753. def set_heating_setpoint_mcb(self, device, key, data):
  754. self.logger.info("Changing heating setpoint to %s", str(data))
  755. self.set_heating_setpoint(data)
  756. class remote(base):
  757. """ Communication (MQTT)
  758. remote (RAS5) <- command
  759. +- CD [dc]
  760. +- LINE1 [dc]
  761. +- LINE2 [dc]
  762. +- LINE3 [dc]
  763. +- MUTE [dc]
  764. +- POWER [dc]
  765. +- VOLDOWN [dc]
  766. +- VOLUP [dc]
  767. +- PHONO [dc]
  768. +- DOCK [dc]
  769. remote (EUR642100) <- command
  770. +- OPEN_CLOSE [dc]
  771. +- VOLDOWN [dc]
  772. +- VOLUP [dc]
  773. +- ONE [dc]
  774. +- TWO [dc]
  775. +- THREE [dc]
  776. +- FOUR [dc]
  777. +- FIVE [dc]
  778. +- SIX [dc]
  779. +- SEVEN [dc]
  780. +- EIGHT [dc]
  781. +- NINE [dc]
  782. +- ZERO [dc]
  783. +- TEN [dc]
  784. +- TEN_PLUS [dc]
  785. +- PROGRAM [dc]
  786. +- CLEAR [dc]
  787. +- RECALL [dc]
  788. +- TIME_MODE [dc]
  789. +- A_B_REPEAT [dc]
  790. +- REPEAT [dc]
  791. +- RANDOM [dc]
  792. +- AUTO_CUE [dc]
  793. +- TAPE_LENGTH [dc]
  794. +- SIDE_A_B [dc]
  795. +- TIME_FADE [dc]
  796. +- PEAK_SEARCH [dc]
  797. +- SEARCH_BACK [dc]
  798. +- SEARCH_FOR [dc]
  799. +- TRACK_NEXT [dc]
  800. +- TRACK_PREV [dc]
  801. +- STOP [dc]
  802. +- PAUSE [dc]
  803. +- PLAY [dc]
  804. """
  805. KEY_CD = "CD"
  806. KEY_LINE1 = "LINE1"
  807. KEY_LINE3 = "LINE3"
  808. KEY_MUTE = "MUTE"
  809. KEY_POWER = "POWER"
  810. KEY_VOLDOWN = "VOLDOWN"
  811. KEY_VOLUP = "VOLUP"
  812. #
  813. TX_TOPIC = ''
  814. TX_TYPE = base.TX_VALUE
  815. #
  816. RX_IGNORE_TOPICS = [KEY_CD, KEY_LINE1, KEY_LINE3, KEY_MUTE, KEY_POWER, KEY_VOLUP, KEY_VOLDOWN]
  817. def set_cd(self, device=None, key=None, data=None):
  818. self.send_command(self.KEY_CD, None)
  819. def set_line1(self, device=None, key=None, data=None):
  820. self.send_command(self.KEY_LINE1, None)
  821. def set_line3(self, device=None, key=None, data=None):
  822. self.send_command(self.KEY_LINE3, None)
  823. def set_mute(self, device=None, key=None, data=None):
  824. self.send_command(self.KEY_MUTE, None)
  825. def set_power(self, device=None, key=None, data=None):
  826. self.send_command(self.KEY_POWER, None)
  827. def set_volume_up(self, data=False):
  828. """data: [True, False]"""
  829. self.send_command(self.KEY_VOLUP, data)
  830. def set_volume_down(self, data=False):
  831. """data: [True, False]"""
  832. self.send_command(self.KEY_VOLDOWN, data)
  833. def default_inc(self, device=None, key=None, data=None):
  834. self.set_volume_up(True)
  835. def default_dec(self, device=None, key=None, data=None):
  836. self.set_volume_down(True)
  837. def default_stop(self, device=None, key=None, data=None):
  838. self.set_volume_up(False)
  839. class audio_status(base):
  840. """ Communication (MQTT)
  841. audio_status
  842. +- state [True, False] <- status
  843. +- title [text] <- status
  844. """
  845. KEY_STATE = "state"
  846. KEY_TITLE = "title"
  847. #
  848. TX_TYPE = base.TX_VALUE
  849. #
  850. RX_KEYS = [KEY_STATE, KEY_TITLE]
  851. def set_state(self, num, data):
  852. """data: [True, False]"""
  853. self.send_command(self.KEY_STATE + "/" + str(num), data)
  854. def set_state_mcb(self, device, key, data):
  855. self.logger.info("Changing state to %s", str(data))
  856. self.set_state(data)