Smarthome Functionen
Ви не можете вибрати більше 25 тем Теми мають розпочинатися з літери або цифри, можуть містити дефіси (-) і не повинні перевищувати 35 символів.

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818
  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. KEY_OUTPUT_0 = "relay/0"
  167. KEY_OUTPUT_1 = "relay/1"
  168. KEY_INPUT_0 = "input/0"
  169. KEY_INPUT_1 = "input/1"
  170. KEY_LONGPUSH_0 = "longpush/0"
  171. KEY_LONGPUSH_1 = "longpush/1"
  172. KEY_TEMPERATURE = "temperature"
  173. KEY_OVERTEMPERATURE = "overtemperature"
  174. KEY_ID = "id"
  175. KEY_MODEL = "model"
  176. KEY_MAC = "mac"
  177. KEY_IP = "ip"
  178. KEY_NEW_FIRMWARE = "new_fw"
  179. KEY_FIRMWARE_VERSION = "fw_ver"
  180. #
  181. TX_TOPIC = "command"
  182. TX_TYPE = base.TX_VALUE
  183. TX_FILTER_DATA_KEYS = [KEY_OUTPUT_0, KEY_OUTPUT_1]
  184. #
  185. RX_KEYS = [KEY_OUTPUT_0, KEY_OUTPUT_1, KEY_INPUT_0, KEY_INPUT_1, KEY_LONGPUSH_0, KEY_LONGPUSH_1, KEY_OVERTEMPERATURE, KEY_TEMPERATURE,
  186. KEY_ID, KEY_MODEL, KEY_MAC, KEY_IP, KEY_NEW_FIRMWARE, KEY_FIRMWARE_VERSION]
  187. RX_IGNORE_TOPICS = [KEY_OUTPUT_0 + '/' + "energy", KEY_OUTPUT_1 + '/' + "energy", 'input_event/0', 'input_event/1']
  188. RX_IGNORE_KEYS = ['temperature_f']
  189. RX_FILTER_DATA_KEYS = [KEY_INPUT_0, KEY_INPUT_1, KEY_LONGPUSH_0, KEY_LONGPUSH_1, KEY_OUTPUT_0, KEY_OUTPUT_1, KEY_OVERTEMPERATURE]
  190. def __init__(self, mqtt_client, topic):
  191. super().__init__(mqtt_client, topic)
  192. #
  193. self.output_key_delayed = None
  194. self.delayed_flash_task = task.delayed(0.3, self.flash_task)
  195. self.delayed_off_task = task.delayed(0.3, self.off_task)
  196. #
  197. self.add_callback(self.KEY_OVERTEMPERATURE, True, self.__warning__, True)
  198. #
  199. self.all_off_requested = False
  200. def flash_task(self, *args):
  201. if self.flash_active:
  202. self.send_command(self.output_key_delayed, not self.get(self.output_key_delayed))
  203. self.output_key_delayed = None
  204. if self.all_off_requested:
  205. self.delayed_off_task.run()
  206. def off_task(self, *args):
  207. self.all_off()
  208. @property
  209. def flash_active(self):
  210. return self.output_key_delayed is not None
  211. #
  212. # WARNING CALL
  213. #
  214. def __warning__(self, client, key, data):
  215. w = warning(self.topic, warning.TYPE_OVERTEMPERATURE, "Temperature to high (%.1f°C)", self.get(self.KEY_TEMPERATURE) or math.nan)
  216. self.logger.warning(w)
  217. self.set(self.KEY_WARNING, w)
  218. #
  219. # RX
  220. #
  221. @property
  222. def output_0(self):
  223. """rv: [True, False]"""
  224. return self.get(self.KEY_OUTPUT_0)
  225. @property
  226. def output_1(self):
  227. """rv: [True, False]"""
  228. return self.get(self.KEY_OUTPUT_1)
  229. @property
  230. def input_0(self):
  231. """rv: [True, False]"""
  232. return self.get(self.KEY_INPUT_0)
  233. @property
  234. def input_1(self):
  235. """rv: [True, False]"""
  236. return self.get(self.KEY_INPUT_1)
  237. @property
  238. def longpush_0(self):
  239. """rv: [True, False]"""
  240. return self.get(self.KEY_LONGPUSH_0)
  241. @property
  242. def longpush_1(self):
  243. """rv: [True, False]"""
  244. return self.get(self.KEY_LONGPUSH_1)
  245. @property
  246. def temperature(self):
  247. """rv: numeric value"""
  248. return self.get(self.KEY_TEMPERATURE)
  249. #
  250. # TX
  251. #
  252. def set_output_0(self, state):
  253. """state: [True, False]"""
  254. self.send_command(self.KEY_OUTPUT_0, state)
  255. def set_output_0_mcb(self, device, key, data):
  256. self.logger.log(logging.INFO if data != self.output_0 else logging.DEBUG, "Changing output 0 to %s", str(data))
  257. self.set_output_0(data)
  258. def toggle_output_0_mcb(self, device, key, data):
  259. self.logger.info("Toggeling output 0")
  260. self.set_output_0(not self.output_0)
  261. def set_output_1(self, state):
  262. """state: [True, False]"""
  263. self.send_command(self.KEY_OUTPUT_1, state)
  264. def set_output_1_mcb(self, device, key, data):
  265. self.logger.log(logging.INFO if data != self.output_1 else logging.DEBUG, "Changing output 1 to %s", str(data))
  266. self.set_output_1(data)
  267. def toggle_output_1_mcb(self, device, key, data):
  268. self.logger.info("Toggeling output 1")
  269. self.set_output_1(not self.output_1)
  270. def flash_0_mcb(self, device, key, data):
  271. self.output_key_delayed = self.KEY_OUTPUT_0
  272. self.toggle_output_0_mcb(device, key, data)
  273. self.delayed_flash_task.run()
  274. def flash_1_mcb(self, device, key, data):
  275. self.output_key_delayed = self.KEY_OUTPUT_1
  276. self.toggle_output_1_mcb(device, key, data)
  277. self.delayed_flash_task.run()
  278. def all_off(self):
  279. if self.flash_active:
  280. self.all_off_requested = True
  281. else:
  282. if self.output_0:
  283. self.set_output_0(False)
  284. if self.output_1:
  285. self.set_output_1(False)
  286. class silvercrest_powerplug(base):
  287. KEY_LINKQUALITY = "linkquality"
  288. KEY_OUTPUT_0 = "state"
  289. #
  290. TX_TYPE = base.TX_DICT
  291. TX_FILTER_DATA_KEYS = [KEY_OUTPUT_0]
  292. #
  293. RX_KEYS = [KEY_LINKQUALITY, KEY_OUTPUT_0]
  294. RX_FILTER_DATA_KEYS = [KEY_OUTPUT_0]
  295. def __init__(self, mqtt_client, topic):
  296. super().__init__(mqtt_client, topic)
  297. #
  298. # RX
  299. #
  300. @property
  301. def output_0(self):
  302. """rv: [True, False]"""
  303. return self.get(self.KEY_OUTPUT_0)
  304. @property
  305. def linkquality(self):
  306. """rv: numeric value"""
  307. return self.get(self.KEY_LINKQUALITY)
  308. #
  309. # TX
  310. #
  311. def set_output_0(self, state):
  312. """state: [True, False]"""
  313. self.send_command(self.KEY_OUTPUT_0, state)
  314. def set_output_0_mcb(self, device, key, data):
  315. self.logger.log(logging.INFO if data != self.output_0 else logging.DEBUG, "Changing output 0 to %s", str(data))
  316. self.set_output_0(data)
  317. def toggle_output_0_mcb(self, device, key, data):
  318. self.logger.info("Toggeling output 0")
  319. self.set_output_0(not self.output_0)
  320. def all_off(self):
  321. if self.output_0:
  322. self.set_output_0(False)
  323. class silvercrest_motion_sensor(base):
  324. KEY_BATTERY = "battery"
  325. KEY_BATTERY_LOW = "battery_low"
  326. KEY_LINKQUALITY = "linkquality"
  327. KEY_OCCUPANCY = "occupancy"
  328. KEY_UNMOUNTED = "tamper"
  329. KEY_VOLTAGE = "voltage"
  330. #
  331. RX_KEYS = [KEY_BATTERY, KEY_BATTERY_LOW, KEY_LINKQUALITY, KEY_OCCUPANCY, KEY_UNMOUNTED, KEY_VOLTAGE]
  332. def __init__(self, mqtt_client, topic):
  333. super().__init__(mqtt_client, topic)
  334. #
  335. self.add_callback(self.KEY_BATTERY_LOW, True, self.__warning__, True)
  336. #
  337. # WARNING CALL
  338. #
  339. def __warning__(self, client, key, data):
  340. w = warning(self.topic, warning.TYPE_BATTERY_LOW, "Battery low (%.1f%%)", self.get(self.KEY_BATTERY) or math.nan)
  341. self.logger.warning(w)
  342. self.set(self.KEY_WARNING, w)
  343. #
  344. # RX
  345. #
  346. @property
  347. def linkquality(self):
  348. """rv: numeric value"""
  349. return self.get(self.KEY_LINKQUALITY)
  350. @property
  351. def battery(self):
  352. """rv: numeric value"""
  353. return self.get(self.KEY_BATTERY)
  354. class my_powerplug(base):
  355. KEY_OUTPUT_0 = "output/1"
  356. KEY_OUTPUT_1 = "output/2"
  357. KEY_OUTPUT_2 = "output/3"
  358. KEY_OUTPUT_3 = "output/4"
  359. KEY_OUTPUT_ALL = "output/all"
  360. KEY_OUTPUT_LIST = [KEY_OUTPUT_0, KEY_OUTPUT_1, KEY_OUTPUT_2, KEY_OUTPUT_3]
  361. #
  362. TX_TYPE = base.TX_VALUE
  363. #
  364. RX_KEYS = [KEY_OUTPUT_0, KEY_OUTPUT_1, KEY_OUTPUT_2, KEY_OUTPUT_3]
  365. def __init__(self, mqtt_client, topic):
  366. super().__init__(mqtt_client, topic)
  367. #
  368. # RX
  369. #
  370. @property
  371. def output_0(self):
  372. """rv: [True, False]"""
  373. return self.get(self.KEY_OUTPUT_0)
  374. @property
  375. def output_1(self):
  376. """rv: [True, False]"""
  377. return self.get(self.KEY_OUTPUT_1)
  378. @property
  379. def output_2(self):
  380. """rv: [True, False]"""
  381. return self.get(self.KEY_OUTPUT_2)
  382. @property
  383. def output_3(self):
  384. """rv: [True, False]"""
  385. return self.get(self.KEY_OUTPUT_3)
  386. #
  387. # TX
  388. #
  389. def set_output(self, key, state):
  390. if key in self.KEY_OUTPUT_LIST:
  391. self.send_command(key, state)
  392. else:
  393. logging.error("Unknown key to set the output!")
  394. def set_output_0(self, state):
  395. """state: [True, False]"""
  396. self.send_command(self.KEY_OUTPUT_0, state)
  397. def set_output_0_mcb(self, device, key, data):
  398. self.logger.log(logging.INFO if data != self.output_0 else logging.DEBUG, "Changing output 0 to %s", str(data))
  399. self.set_output_0(data)
  400. def toggle_output_0_mcb(self, device, key, data):
  401. self.logger.info("Toggeling output 0")
  402. self.set_output_0(not self.output_0)
  403. def set_output_1(self, state):
  404. """state: [True, False]"""
  405. self.send_command(self.KEY_OUTPUT_1, state)
  406. def set_output_1_mcb(self, device, key, data):
  407. self.logger.log(logging.INFO if data != self.output_1 else logging.DEBUG, "Changing output 1 to %s", str(data))
  408. self.set_output_1(data)
  409. def toggle_output_1_mcb(self, device, key, data):
  410. self.logger.info("Toggeling output 1")
  411. self.set_output_1(not self.output_1)
  412. def set_output_2(self, state):
  413. """state: [True, False]"""
  414. self.send_command(self.KEY_OUTPUT_2, state)
  415. def set_output_2_mcb(self, device, key, data):
  416. self.logger.log(logging.INFO if data != self.output_2 else logging.DEBUG, "Changing output 2 to %s", str(data))
  417. self.set_output_2(data)
  418. def toggle_output_2_mcb(self, device, key, data):
  419. self.logger.info("Toggeling output 2")
  420. self.set_output_2(not self.output_2)
  421. def set_output_3(self, state):
  422. """state: [True, False]"""
  423. self.send_command(self.KEY_OUTPUT_3, state)
  424. def set_output_3_mcb(self, device, key, data):
  425. self.logger.log(logging.INFO if data != self.output_3 else logging.DEBUG, "Changing output 3 to %s", str(data))
  426. self.set_output_3(data)
  427. def toggle_output_3_mcb(self, device, key, data):
  428. self.logger.info("Toggeling output 3")
  429. self.set_output_3(not self.output_3)
  430. def set_output_all(self, state):
  431. """state: [True, False, 'toggle']"""
  432. self.send_command(self.KEY_OUTPUT_ALL, state)
  433. def set_output_all_mcb(self, device, key, data):
  434. self.logger.info("Changing all outputs to %s", str(data))
  435. self.set_output_all(data)
  436. def all_off(self):
  437. self.set_output_all(False)
  438. class tradfri_light(base):
  439. KEY_LINKQUALITY = "linkquality"
  440. KEY_OUTPUT_0 = "state"
  441. KEY_BRIGHTNESS = "brightness"
  442. KEY_COLOR_TEMP = "color_temp"
  443. KEY_BRIGHTNESS_FADE = "brightness_move"
  444. #
  445. TX_TYPE = base.TX_DICT
  446. TX_FILTER_DATA_KEYS = [KEY_OUTPUT_0, KEY_BRIGHTNESS, KEY_COLOR_TEMP, KEY_BRIGHTNESS_FADE]
  447. #
  448. RX_KEYS = [KEY_LINKQUALITY, KEY_OUTPUT_0, KEY_BRIGHTNESS, KEY_COLOR_TEMP]
  449. RX_IGNORE_KEYS = ['update', 'color_mode', 'color_temp_startup']
  450. RX_FILTER_DATA_KEYS = [KEY_OUTPUT_0, KEY_BRIGHTNESS, KEY_COLOR_TEMP]
  451. def __init__(self, mqtt_client, topic):
  452. super().__init__(mqtt_client, topic)
  453. def __device_to_instance_filter__(self, key, data):
  454. if key == self.KEY_BRIGHTNESS:
  455. return int(round((data - 1) * 100 / 253, 0))
  456. elif key == self.KEY_COLOR_TEMP:
  457. return int(round((data - 250) * 10 / 204, 0))
  458. return super().__device_to_instance_filter__(key, data)
  459. def __instance_to_device_filter__(self, key, data):
  460. if key == self.KEY_BRIGHTNESS:
  461. return int(round(data * 253 / 100 + 1, 0))
  462. elif key == self.KEY_COLOR_TEMP:
  463. return int(round(data * 204 / 10 + 250, 0))
  464. return super().__instance_to_device_filter__(key, data)
  465. #
  466. # RX
  467. #
  468. @property
  469. def output_0(self):
  470. """rv: [True, False]"""
  471. return self.get(self.KEY_OUTPUT_0, False)
  472. @property
  473. def linkquality(self):
  474. """rv: numeric value"""
  475. return self.get(self.KEY_LINKQUALITY, 0)
  476. @property
  477. def brightness(self):
  478. """rv: numeric value [0%, ..., 100%]"""
  479. return self.get(self.KEY_BRIGHTNESS, 0)
  480. @property
  481. def color_temp(self):
  482. """rv: numeric value [0, ..., 10]"""
  483. return self.get(self.KEY_COLOR_TEMP, 0)
  484. #
  485. # TX
  486. #
  487. def request_data(self, device=None, key=None, data=None):
  488. self.mqtt_client.send(self.topic + "/get", '{"%s": ""}' % self.KEY_OUTPUT_0)
  489. def set_output_0(self, state):
  490. """state: [True, False]"""
  491. self.send_command(self.KEY_OUTPUT_0, state)
  492. def set_output_0_mcb(self, device, key, data):
  493. self.logger.log(logging.INFO if data != self.output_0 else logging.DEBUG, "Changing output 0 to %s", str(data))
  494. self.set_output_0(data)
  495. def toggle_output_0_mcb(self, device, key, data):
  496. self.logger.info("Toggeling output 0")
  497. self.set_output_0(not self.output_0)
  498. def set_brightness(self, brightness):
  499. """brightness: [0, ..., 100]"""
  500. self.send_command(self.KEY_BRIGHTNESS, brightness)
  501. def set_brightness_mcb(self, device, key, data):
  502. self.logger.log(logging.INFO if data != self.brightness else logging.DEBUG, "Changing brightness to %s", str(data))
  503. self.set_brightness(data)
  504. def default_inc(self, speed=40):
  505. self.send_command(self.KEY_BRIGHTNESS_FADE, speed)
  506. def default_dec(self, speed=-40):
  507. self.default_inc(speed)
  508. def default_stop(self):
  509. self.default_inc(0)
  510. def set_color_temp(self, color_temp):
  511. """color_temp: [0, ..., 10]"""
  512. self.send_command(self.KEY_COLOR_TEMP, color_temp)
  513. def set_color_temp_mcb(self, device, key, data):
  514. self.logger.log(logging.INFO if data != self.color_temp else logging.DEBUG, "Changing color temperature to %s", str(data))
  515. self.set_color_temp(data)
  516. def all_off(self):
  517. if self.output_0:
  518. self.set_output_0(False)
  519. class tradfri_button(base):
  520. ACTION_TOGGLE = "toggle"
  521. ACTION_BRIGHTNESS_UP = "brightness_up_click"
  522. ACTION_BRIGHTNESS_DOWN = "brightness_down_click"
  523. ACTION_RIGHT = "arrow_right_click"
  524. ACTION_LEFT = "arrow_left_click"
  525. ACTION_BRIGHTNESS_UP_LONG = "brightness_up_hold"
  526. ACTION_BRIGHTNESS_UP_RELEASE = "brightness_up_release"
  527. ACTION_BRIGHTNESS_DOWN_LONG = "brightness_down_hold"
  528. ACTION_BRIGHTNESS_DOWN_RELEASE = "brightness_down_release"
  529. ACTION_RIGHT_LONG = "arrow_right_hold"
  530. ACTION_RIGHT_RELEASE = "arrow_right_release"
  531. ACTION_LEFT_LONG = "arrow_left_hold"
  532. ACTION_LEFT_RELEASE = "arrow_left_release"
  533. #
  534. KEY_LINKQUALITY = "linkquality"
  535. KEY_BATTERY = "battery"
  536. KEY_ACTION = "action"
  537. KEY_ACTION_DURATION = "action_duration"
  538. #
  539. RX_KEYS = [KEY_LINKQUALITY, KEY_BATTERY, KEY_ACTION]
  540. RX_IGNORE_KEYS = ['update', KEY_ACTION_DURATION]
  541. def __init__(self, mqtt_client, topic):
  542. super().__init__(mqtt_client, topic)
  543. #
  544. self.add_callback(self.KEY_BATTERY, None, self.__warning__, True)
  545. self.__battery_warning__ = False
  546. #
  547. # WARNING CALL
  548. #
  549. def __warning__(self, client, key, data):
  550. if data <= BATTERY_WARN_LEVEL:
  551. if not self.__battery_warning__:
  552. w = warning(self.topic, warning.TYPE_BATTERY_LOW, "Battery low (%.1f%%)", data)
  553. self.logger.warning(w)
  554. self.set(self.KEY_WARNING, w)
  555. else:
  556. self.__battery_warning__ = False
  557. #
  558. # RX
  559. #
  560. @property
  561. def action(self):
  562. """rv: action_txt"""
  563. return self.get(self.KEY_ACTION)
  564. class brennenstuhl_heatingvalve(base):
  565. KEY_LINKQUALITY = "linkquality"
  566. KEY_BATTERY = "battery"
  567. KEY_HEATING_SETPOINT = "current_heating_setpoint"
  568. KEY_TEMPERATURE = "local_temperature"
  569. #
  570. KEY_AWAY_MODE = "away_mode"
  571. KEY_CHILD_LOCK = "child_lock"
  572. KEY_PRESET = "preset"
  573. KEY_SYSTEM_MODE = "system_mode"
  574. KEY_VALVE_DETECTION = "valve_detection"
  575. KEY_WINDOW_DETECTION = "window_detection"
  576. #
  577. TX_TYPE = base.TX_DICT
  578. #
  579. RX_KEYS = [KEY_LINKQUALITY, KEY_BATTERY, KEY_HEATING_SETPOINT, KEY_TEMPERATURE]
  580. RX_IGNORE_KEYS = [KEY_AWAY_MODE, KEY_CHILD_LOCK, KEY_PRESET, KEY_SYSTEM_MODE, KEY_VALVE_DETECTION, KEY_WINDOW_DETECTION]
  581. def __init__(self, mqtt_client, topic):
  582. super().__init__(mqtt_client, topic)
  583. self.mqtt_client.send(self.topic + '/' + self.TX_TOPIC, json.dumps({self.KEY_WINDOW_DETECTION: "ON",
  584. self.KEY_CHILD_LOCK: "UNLOCK", self.KEY_VALVE_DETECTION: "ON", self.KEY_SYSTEM_MODE: "heat", self.KEY_PRESET: "manual"}))
  585. #
  586. self.add_callback(self.KEY_BATTERY, None, self.__warning__, True)
  587. self.__battery_warning__ = False
  588. #
  589. # WARNING CALL
  590. #
  591. def __warning__(self, client, key, data):
  592. if data <= BATTERY_WARN_LEVEL:
  593. if not self.__battery_warning__:
  594. self.__battery_warning__ = True
  595. w = warning(self.topic, warning.TYPE_BATTERY_LOW, "Battery low (%.1f%%)", data)
  596. self.logger.warning(w)
  597. self.set(self.KEY_WARNING, w)
  598. else:
  599. self.__battery_warning__ = False
  600. #
  601. # RX
  602. #
  603. @property
  604. def linkqulity(self):
  605. return self.get(self.KEY_LINKQUALITY)
  606. @property
  607. def heating_setpoint(self):
  608. return self.get(self.KEY_HEATING_SETPOINT)
  609. @property
  610. def temperature(self):
  611. return self.get(self.KEY_TEMPERATURE)
  612. #
  613. # TX
  614. #
  615. def set_heating_setpoint(self, setpoint):
  616. self.send_command(self.KEY_HEATING_SETPOINT, setpoint)
  617. def set_heating_setpoint_mcb(self, device, key, data):
  618. self.logger.info("Changing heating setpoint to %s", str(data))
  619. self.set_heating_setpoint(data)
  620. class remote(base):
  621. KEY_CD = "CD"
  622. KEY_LINE1 = "LINE1"
  623. KEY_LINE3 = "LINE3"
  624. KEY_MUTE = "MUTE"
  625. KEY_POWER = "POWER"
  626. KEY_VOLDOWN = "VOLDOWN"
  627. KEY_VOLUP = "VOLUP"
  628. #
  629. TX_TOPIC = ''
  630. TX_TYPE = base.TX_VALUE
  631. #
  632. RX_IGNORE_TOPICS = [KEY_CD, KEY_LINE1, KEY_LINE3, KEY_MUTE, KEY_POWER, KEY_VOLUP, KEY_VOLDOWN]
  633. def set_cd(self, device=None, key=None, data=None):
  634. self.send_command(self.KEY_CD, None)
  635. def set_line1(self, device=None, key=None, data=None):
  636. self.send_command(self.KEY_LINE1, None)
  637. def set_line3(self, device=None, key=None, data=None):
  638. self.send_command(self.KEY_LINE3, None)
  639. def set_mute(self, device=None, key=None, data=None):
  640. self.send_command(self.KEY_MUTE, None)
  641. def set_power(self, device=None, key=None, data=None):
  642. self.send_command(self.KEY_POWER, None)
  643. def set_volume_up(self, data=False):
  644. """data: [True, False]"""
  645. self.send_command(self.KEY_VOLUP, data)
  646. def set_volume_down(self, data=False):
  647. """data: [True, False]"""
  648. self.send_command(self.KEY_VOLDOWN, data)
  649. def default_inc(self, device=None, key=None, data=None):
  650. self.set_volume_up(True)
  651. def default_dec(self, device=None, key=None, data=None):
  652. self.set_volume_down(True)
  653. def default_stop(self, device=None, key=None, data=None):
  654. self.set_volume_up(False)
  655. class status(base):
  656. KEY_STATE = "state"
  657. #
  658. TX_TYPE = base.TX_VALUE
  659. #
  660. RX_KEYS = [KEY_STATE]
  661. def set_state(self, num, data):
  662. """data: [True, False]"""
  663. self.send_command(self.KEY_STATE + "/" + str(num), data)
  664. def set_state_mcb(self, device, key, data):
  665. self.logger.info("Changing state to %s", str(data))
  666. self.set_state(data)
  667. class audio_status(status):
  668. KEY_TITLE = "title"
  669. #
  670. RX_KEYS = [status.KEY_STATE, KEY_TITLE]