Smarthome Functionen
Você não pode selecionar mais de 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.

__init__.py 34KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010
  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 function.videv import base as 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. RX_KEYS = [KEY_BATTERY, KEY_BATTERY_LOW, KEY_LINKQUALITY, KEY_OCCUPANCY, KEY_UNMOUNTED, KEY_VOLTAGE]
  382. def __init__(self, mqtt_client, topic):
  383. super().__init__(mqtt_client, topic)
  384. #
  385. self.add_callback(self.KEY_BATTERY_LOW, True, self.__warning__, True)
  386. #
  387. # WARNING CALL
  388. #
  389. def __warning__(self, client, key, data):
  390. w = warning(self.topic, warning.TYPE_BATTERY_LOW, "Battery low (%.1f%%)", self.get(self.KEY_BATTERY) or math.nan)
  391. self.logger.warning(w)
  392. self.set(self.KEY_WARNING, w)
  393. #
  394. # RX
  395. #
  396. @property
  397. def linkquality(self):
  398. """rv: numeric value"""
  399. return self.get(self.KEY_LINKQUALITY)
  400. @property
  401. def battery(self):
  402. """rv: numeric value"""
  403. return self.get(self.KEY_BATTERY)
  404. class my_powerplug(base):
  405. """ Communication (MQTT)
  406. my_powerplug
  407. +- output
  408. +- 1 [True, False] <- status
  409. | +- set [True, False, "toggle"] <- command
  410. +- 2 [True, False] <- status
  411. | +- set [True, False, "toggle"] <- command
  412. +- 3 [True, False] <- status
  413. | +- set [True, False, "toggle"] <- command
  414. +- 4 [True, False] <- status
  415. | +- set [True, False, "toggle"] <- command
  416. +- all
  417. +- set [True, False, "toggle"] <- command
  418. """
  419. KEY_OUTPUT_0 = "output/1"
  420. KEY_OUTPUT_1 = "output/2"
  421. KEY_OUTPUT_2 = "output/3"
  422. KEY_OUTPUT_3 = "output/4"
  423. KEY_OUTPUT_ALL = "output/all"
  424. KEY_OUTPUT_LIST = [KEY_OUTPUT_0, KEY_OUTPUT_1, KEY_OUTPUT_2, KEY_OUTPUT_3]
  425. #
  426. TX_TYPE = base.TX_VALUE
  427. #
  428. RX_KEYS = [KEY_OUTPUT_0, KEY_OUTPUT_1, KEY_OUTPUT_2, KEY_OUTPUT_3]
  429. def __init__(self, mqtt_client, topic):
  430. super().__init__(mqtt_client, topic)
  431. #
  432. # RX
  433. #
  434. @property
  435. def output_0(self):
  436. """rv: [True, False]"""
  437. return self.get(self.KEY_OUTPUT_0)
  438. @property
  439. def output_1(self):
  440. """rv: [True, False]"""
  441. return self.get(self.KEY_OUTPUT_1)
  442. @property
  443. def output_2(self):
  444. """rv: [True, False]"""
  445. return self.get(self.KEY_OUTPUT_2)
  446. @property
  447. def output_3(self):
  448. """rv: [True, False]"""
  449. return self.get(self.KEY_OUTPUT_3)
  450. #
  451. # TX
  452. #
  453. def set_output(self, key, state):
  454. if key in self.KEY_OUTPUT_LIST:
  455. self.send_command(key, state)
  456. else:
  457. logging.error("Unknown key to set the output!")
  458. def set_output_0(self, state):
  459. """state: [True, False]"""
  460. self.send_command(self.KEY_OUTPUT_0, state)
  461. def set_output_0_mcb(self, device, key, data):
  462. self.logger.log(logging.INFO if data != self.output_0 else logging.DEBUG, "Changing output 0 to %s", str(data))
  463. self.set_output_0(data)
  464. def toggle_output_0_mcb(self, device, key, data):
  465. self.logger.info("Toggeling output 0")
  466. self.set_output_0(not self.output_0)
  467. def set_output_1(self, state):
  468. """state: [True, False]"""
  469. self.send_command(self.KEY_OUTPUT_1, state)
  470. def set_output_1_mcb(self, device, key, data):
  471. self.logger.log(logging.INFO if data != self.output_1 else logging.DEBUG, "Changing output 1 to %s", str(data))
  472. self.set_output_1(data)
  473. def toggle_output_1_mcb(self, device, key, data):
  474. self.logger.info("Toggeling output 1")
  475. self.set_output_1(not self.output_1)
  476. def set_output_2(self, state):
  477. """state: [True, False]"""
  478. self.send_command(self.KEY_OUTPUT_2, state)
  479. def set_output_2_mcb(self, device, key, data):
  480. self.logger.log(logging.INFO if data != self.output_2 else logging.DEBUG, "Changing output 2 to %s", str(data))
  481. self.set_output_2(data)
  482. def toggle_output_2_mcb(self, device, key, data):
  483. self.logger.info("Toggeling output 2")
  484. self.set_output_2(not self.output_2)
  485. def set_output_3(self, state):
  486. """state: [True, False]"""
  487. self.send_command(self.KEY_OUTPUT_3, state)
  488. def set_output_3_mcb(self, device, key, data):
  489. self.logger.log(logging.INFO if data != self.output_3 else logging.DEBUG, "Changing output 3 to %s", str(data))
  490. self.set_output_3(data)
  491. def toggle_output_3_mcb(self, device, key, data):
  492. self.logger.info("Toggeling output 3")
  493. self.set_output_3(not self.output_3)
  494. def set_output_all(self, state):
  495. """state: [True, False, 'toggle']"""
  496. self.send_command(self.KEY_OUTPUT_ALL, state)
  497. def set_output_all_mcb(self, device, key, data):
  498. self.logger.info("Changing all outputs to %s", str(data))
  499. self.set_output_all(data)
  500. def all_off(self):
  501. self.set_output_all(False)
  502. class tradfri_light(base):
  503. """ Communication (MQTT)
  504. tradfri_light {
  505. | "state": ["ON" / "OFF" / "TOGGLE"]
  506. | "linkquality": [0...255] lqi
  507. | "brightness": [0...254]
  508. | "color_mode": ["color_temp"]
  509. | "color_temp": ["coolest", "cool", "neutral", "warm", "warmest", 250...454]
  510. | "color_temp_startup": ["coolest", "cool", "neutral", "warm", "warmest", "previous", 250...454]
  511. | "update": []
  512. | }
  513. +- get {
  514. | "state": ""
  515. | }
  516. +- set {
  517. "state": ["ON" / "OFF"]
  518. "brightness": [0...256]
  519. "color_temp": [250...454]
  520. "transition": [0...] seconds
  521. "brightness_move": [-X...0...X] X/s
  522. "brightness_step": [-X...0...X]
  523. "color_temp_move": [-X...0...X] X/s
  524. "color_temp_step": [-X...0...X]
  525. }
  526. """
  527. KEY_LINKQUALITY = "linkquality"
  528. KEY_OUTPUT_0 = "state"
  529. KEY_BRIGHTNESS = "brightness"
  530. KEY_COLOR_TEMP = "color_temp"
  531. KEY_BRIGHTNESS_FADE = "brightness_move"
  532. #
  533. TX_TYPE = base.TX_DICT
  534. TX_FILTER_DATA_KEYS = [KEY_OUTPUT_0, KEY_BRIGHTNESS, KEY_COLOR_TEMP, KEY_BRIGHTNESS_FADE]
  535. #
  536. RX_KEYS = [KEY_LINKQUALITY, KEY_OUTPUT_0, KEY_BRIGHTNESS, KEY_COLOR_TEMP]
  537. RX_IGNORE_KEYS = ['update', 'color_mode', 'color_temp_startup']
  538. RX_FILTER_DATA_KEYS = [KEY_OUTPUT_0, KEY_BRIGHTNESS, KEY_COLOR_TEMP]
  539. def __init__(self, mqtt_client, topic):
  540. super().__init__(mqtt_client, topic)
  541. def __device_to_instance_filter__(self, key, data):
  542. if key == self.KEY_BRIGHTNESS:
  543. return int(round((data - 1) * 100 / 253, 0))
  544. elif key == self.KEY_COLOR_TEMP:
  545. return int(round((data - 250) * 10 / 204, 0))
  546. return super().__device_to_instance_filter__(key, data)
  547. def __instance_to_device_filter__(self, key, data):
  548. if key == self.KEY_BRIGHTNESS:
  549. return int(round(data * 253 / 100 + 1, 0))
  550. elif key == self.KEY_COLOR_TEMP:
  551. return int(round(data * 204 / 10 + 250, 0))
  552. return super().__instance_to_device_filter__(key, data)
  553. #
  554. # RX
  555. #
  556. @property
  557. def output_0(self):
  558. """rv: [True, False]"""
  559. return self.get(self.KEY_OUTPUT_0, False)
  560. @property
  561. def linkquality(self):
  562. """rv: numeric value"""
  563. return self.get(self.KEY_LINKQUALITY, 0)
  564. @property
  565. def brightness(self):
  566. """rv: numeric value [0%, ..., 100%]"""
  567. return self.get(self.KEY_BRIGHTNESS, 0)
  568. @property
  569. def color_temp(self):
  570. """rv: numeric value [0, ..., 10]"""
  571. return self.get(self.KEY_COLOR_TEMP, 0)
  572. #
  573. # TX
  574. #
  575. def request_data(self, device=None, key=None, data=None):
  576. self.mqtt_client.send(self.topic + "/get", '{"%s": ""}' % self.KEY_OUTPUT_0)
  577. def set_output_0(self, state):
  578. """state: [True, False]"""
  579. self.send_command(self.KEY_OUTPUT_0, state)
  580. def set_output_0_mcb(self, device, key, data):
  581. self.logger.log(logging.INFO if data != self.output_0 else logging.DEBUG, "Changing output 0 to %s", str(data))
  582. self.set_output_0(data)
  583. def toggle_output_0_mcb(self, device, key, data):
  584. self.logger.info("Toggeling output 0")
  585. self.set_output_0(not self.output_0)
  586. def set_brightness(self, brightness):
  587. """brightness: [0, ..., 100]"""
  588. self.send_command(self.KEY_BRIGHTNESS, brightness)
  589. def set_brightness_mcb(self, device, key, data):
  590. self.logger.log(logging.INFO if data != self.brightness else logging.DEBUG, "Changing brightness to %s", str(data))
  591. self.set_brightness(data)
  592. def default_inc(self, speed=40):
  593. self.send_command(self.KEY_BRIGHTNESS_FADE, speed)
  594. def default_dec(self, speed=-40):
  595. self.default_inc(speed)
  596. def default_stop(self):
  597. self.default_inc(0)
  598. def set_color_temp(self, color_temp):
  599. """color_temp: [0, ..., 10]"""
  600. self.send_command(self.KEY_COLOR_TEMP, color_temp)
  601. def set_color_temp_mcb(self, device, key, data):
  602. self.logger.log(logging.INFO if data != self.color_temp else logging.DEBUG, "Changing color temperature to %s", str(data))
  603. self.set_color_temp(data)
  604. def all_off(self):
  605. if self.output_0:
  606. self.set_output_0(False)
  607. class tradfri_button(base):
  608. """ Communication (MQTT)
  609. tradfri_button {
  610. "action": [
  611. "arrow_left_click",
  612. "arrow_left_hold",
  613. "arrow_left_release",
  614. "arrow_right_click",
  615. "arrow_right_hold",
  616. "arrow_right_release",
  617. "brightness_down_click",
  618. "brightness_down_hold",
  619. "brightness_down_release",
  620. "brightness_up_click",
  621. "brightness_up_hold",
  622. "brightness_up_release",
  623. "toggle"
  624. ]
  625. "action_duration": [0...] s
  626. "battery": [0...100] %
  627. "linkquality": [0...255] lqi
  628. "update": []
  629. }
  630. """
  631. ACTION_TOGGLE = "toggle"
  632. ACTION_BRIGHTNESS_UP = "brightness_up_click"
  633. ACTION_BRIGHTNESS_DOWN = "brightness_down_click"
  634. ACTION_RIGHT = "arrow_right_click"
  635. ACTION_LEFT = "arrow_left_click"
  636. ACTION_BRIGHTNESS_UP_LONG = "brightness_up_hold"
  637. ACTION_BRIGHTNESS_UP_RELEASE = "brightness_up_release"
  638. ACTION_BRIGHTNESS_DOWN_LONG = "brightness_down_hold"
  639. ACTION_BRIGHTNESS_DOWN_RELEASE = "brightness_down_release"
  640. ACTION_RIGHT_LONG = "arrow_right_hold"
  641. ACTION_RIGHT_RELEASE = "arrow_right_release"
  642. ACTION_LEFT_LONG = "arrow_left_hold"
  643. ACTION_LEFT_RELEASE = "arrow_left_release"
  644. #
  645. KEY_LINKQUALITY = "linkquality"
  646. KEY_BATTERY = "battery"
  647. KEY_ACTION = "action"
  648. KEY_ACTION_DURATION = "action_duration"
  649. #
  650. RX_KEYS = [KEY_LINKQUALITY, KEY_BATTERY, KEY_ACTION]
  651. RX_IGNORE_KEYS = ['update', KEY_ACTION_DURATION]
  652. def __init__(self, mqtt_client, topic):
  653. super().__init__(mqtt_client, topic)
  654. #
  655. self.add_callback(self.KEY_BATTERY, None, self.__warning__, True)
  656. self.__battery_warning__ = False
  657. #
  658. # WARNING CALL
  659. #
  660. def __warning__(self, client, key, data):
  661. if data <= BATTERY_WARN_LEVEL:
  662. if not self.__battery_warning__:
  663. w = warning(self.topic, warning.TYPE_BATTERY_LOW, "Battery low (%.1f%%)", data)
  664. self.logger.warning(w)
  665. self.set(self.KEY_WARNING, w)
  666. else:
  667. self.__battery_warning__ = False
  668. #
  669. # RX
  670. #
  671. @property
  672. def action(self):
  673. """rv: action_txt"""
  674. return self.get(self.KEY_ACTION)
  675. class brennenstuhl_heatingvalve(base):
  676. """ Communication (MQTT)
  677. brennenstuhl_heatingvalve {
  678. | "away_mode": ["ON", "OFF"]
  679. | "battery": [0...100] %
  680. | "child_lock": ["LOCK", "UNLOCK"]
  681. | "current_heating_setpoint": [5...30] °C
  682. | "linkquality": [0...255] lqi
  683. | "local_temperature": [numeric] °C
  684. | "preset": ["manual", ...]
  685. | "system_mode": ["heat", ...]
  686. | "valve_detection": ["ON", "OFF"]
  687. | "window_detection": ["ON", "OFF"]
  688. | }
  689. +- set {
  690. "away_mode": ["ON", "OFF", "TOGGLE"]
  691. "child_lock": ["LOCK", "UNLOCK"]
  692. "current_heating_setpoint": [5...30] °C
  693. "preset": ["manual", ...]
  694. "system_mode": ["heat", ...]
  695. "valve_detection": ["ON", "OFF", "TOGGLE"]
  696. "window_detection": ["ON", "OFF", "TOGGLE"]
  697. }
  698. """
  699. KEY_LINKQUALITY = "linkquality"
  700. KEY_BATTERY = "battery"
  701. KEY_HEATING_SETPOINT = "current_heating_setpoint"
  702. KEY_TEMPERATURE = "local_temperature"
  703. #
  704. KEY_AWAY_MODE = "away_mode"
  705. KEY_CHILD_LOCK = "child_lock"
  706. KEY_PRESET = "preset"
  707. KEY_SYSTEM_MODE = "system_mode"
  708. KEY_VALVE_DETECTION = "valve_detection"
  709. KEY_WINDOW_DETECTION = "window_detection"
  710. #
  711. TX_TYPE = base.TX_DICT
  712. #
  713. RX_KEYS = [KEY_LINKQUALITY, KEY_BATTERY, KEY_HEATING_SETPOINT, KEY_TEMPERATURE]
  714. RX_IGNORE_KEYS = [KEY_AWAY_MODE, KEY_CHILD_LOCK, KEY_PRESET, KEY_SYSTEM_MODE, KEY_VALVE_DETECTION, KEY_WINDOW_DETECTION]
  715. def __init__(self, mqtt_client, topic):
  716. super().__init__(mqtt_client, topic)
  717. self.mqtt_client.send(self.topic + '/' + self.TX_TOPIC, json.dumps({self.KEY_WINDOW_DETECTION: "ON",
  718. self.KEY_CHILD_LOCK: "UNLOCK", self.KEY_VALVE_DETECTION: "ON", self.KEY_SYSTEM_MODE: "heat", self.KEY_PRESET: "manual"}))
  719. #
  720. self.add_callback(self.KEY_BATTERY, None, self.__warning__, True)
  721. self.__battery_warning__ = False
  722. #
  723. # WARNING CALL
  724. #
  725. def __warning__(self, client, key, data):
  726. if data <= BATTERY_WARN_LEVEL:
  727. if not self.__battery_warning__:
  728. self.__battery_warning__ = True
  729. w = warning(self.topic, warning.TYPE_BATTERY_LOW, "Battery low (%.1f%%)", data)
  730. self.logger.warning(w)
  731. self.set(self.KEY_WARNING, w)
  732. else:
  733. self.__battery_warning__ = False
  734. #
  735. # RX
  736. #
  737. @property
  738. def linkqulity(self):
  739. return self.get(self.KEY_LINKQUALITY)
  740. @property
  741. def heating_setpoint(self):
  742. return self.get(self.KEY_HEATING_SETPOINT)
  743. @property
  744. def temperature(self):
  745. return self.get(self.KEY_TEMPERATURE)
  746. #
  747. # TX
  748. #
  749. def set_heating_setpoint(self, setpoint):
  750. self.send_command(self.KEY_HEATING_SETPOINT, setpoint)
  751. def set_heating_setpoint_mcb(self, device, key, data):
  752. self.logger.info("Changing heating setpoint to %s", str(data))
  753. self.set_heating_setpoint(data)
  754. class remote(base):
  755. """ Communication (MQTT)
  756. remote (RAS5) <- command
  757. +- CD [dc]
  758. +- LINE1 [dc]
  759. +- LINE2 [dc]
  760. +- LINE3 [dc]
  761. +- MUTE [dc]
  762. +- POWER [dc]
  763. +- VOLDOWN [dc]
  764. +- VOLUP [dc]
  765. +- PHONO [dc]
  766. +- DOCK [dc]
  767. remote (EUR642100) <- command
  768. +- OPEN_CLOSE [dc]
  769. +- VOLDOWN [dc]
  770. +- VOLUP [dc]
  771. +- ONE [dc]
  772. +- TWO [dc]
  773. +- THREE [dc]
  774. +- FOUR [dc]
  775. +- FIVE [dc]
  776. +- SIX [dc]
  777. +- SEVEN [dc]
  778. +- EIGHT [dc]
  779. +- NINE [dc]
  780. +- ZERO [dc]
  781. +- TEN [dc]
  782. +- TEN_PLUS [dc]
  783. +- PROGRAM [dc]
  784. +- CLEAR [dc]
  785. +- RECALL [dc]
  786. +- TIME_MODE [dc]
  787. +- A_B_REPEAT [dc]
  788. +- REPEAT [dc]
  789. +- RANDOM [dc]
  790. +- AUTO_CUE [dc]
  791. +- TAPE_LENGTH [dc]
  792. +- SIDE_A_B [dc]
  793. +- TIME_FADE [dc]
  794. +- PEAK_SEARCH [dc]
  795. +- SEARCH_BACK [dc]
  796. +- SEARCH_FOR [dc]
  797. +- TRACK_NEXT [dc]
  798. +- TRACK_PREV [dc]
  799. +- STOP [dc]
  800. +- PAUSE [dc]
  801. +- PLAY [dc]
  802. """
  803. KEY_CD = "CD"
  804. KEY_LINE1 = "LINE1"
  805. KEY_LINE3 = "LINE3"
  806. KEY_MUTE = "MUTE"
  807. KEY_POWER = "POWER"
  808. KEY_VOLDOWN = "VOLDOWN"
  809. KEY_VOLUP = "VOLUP"
  810. #
  811. TX_TOPIC = ''
  812. TX_TYPE = base.TX_VALUE
  813. #
  814. RX_IGNORE_TOPICS = [KEY_CD, KEY_LINE1, KEY_LINE3, KEY_MUTE, KEY_POWER, KEY_VOLUP, KEY_VOLDOWN]
  815. def set_cd(self, device=None, key=None, data=None):
  816. self.send_command(self.KEY_CD, None)
  817. def set_line1(self, device=None, key=None, data=None):
  818. self.send_command(self.KEY_LINE1, None)
  819. def set_line3(self, device=None, key=None, data=None):
  820. self.send_command(self.KEY_LINE3, None)
  821. def set_mute(self, device=None, key=None, data=None):
  822. self.send_command(self.KEY_MUTE, None)
  823. def set_power(self, device=None, key=None, data=None):
  824. self.send_command(self.KEY_POWER, None)
  825. def set_volume_up(self, data=False):
  826. """data: [True, False]"""
  827. self.send_command(self.KEY_VOLUP, data)
  828. def set_volume_down(self, data=False):
  829. """data: [True, False]"""
  830. self.send_command(self.KEY_VOLDOWN, data)
  831. def default_inc(self, device=None, key=None, data=None):
  832. self.set_volume_up(True)
  833. def default_dec(self, device=None, key=None, data=None):
  834. self.set_volume_down(True)
  835. def default_stop(self, device=None, key=None, data=None):
  836. self.set_volume_up(False)
  837. class audio_status(base):
  838. """ Communication (MQTT)
  839. audio_status
  840. +- state [True, False] <- status
  841. +- title [text] <- status
  842. """
  843. KEY_STATE = "state"
  844. KEY_TITLE = "title"
  845. #
  846. TX_TYPE = base.TX_VALUE
  847. #
  848. RX_KEYS = [KEY_STATE, KEY_TITLE]
  849. def set_state(self, num, data):
  850. """data: [True, False]"""
  851. self.send_command(self.KEY_STATE + "/" + str(num), data)
  852. def set_state_mcb(self, device, key, data):
  853. self.logger.info("Changing state to %s", str(data))
  854. self.set_state(data)