Smarthome Functionen
Nevar pievienot vairāk kā 25 tēmas Tēmai ir jāsākas ar burtu vai ciparu, tā var saturēt domu zīmes ('-') un var būt līdz 35 simboliem gara.

__init__.py 25KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832
  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. import json
  19. import logging
  20. import task
  21. try:
  22. from config import APP_NAME as ROOT_LOGGER_NAME
  23. except ImportError:
  24. ROOT_LOGGER_NAME = 'root'
  25. BATTERY_WARN_LEVEL = 5
  26. def is_json(data):
  27. try:
  28. json.loads(data)
  29. except json.decoder.JSONDecodeError:
  30. return False
  31. else:
  32. return True
  33. class group(object):
  34. def __init__(self, *args):
  35. super().__init__()
  36. self._members = args
  37. self._iter_counter = 0
  38. #
  39. self.methods = []
  40. for method in [m for m in args[0].__class__.__dict__.keys()]:
  41. if not method.startswith('_') and callable(getattr(args[0], method)): # add all public callable attributes to the list
  42. self.methods.append(method)
  43. #
  44. for member in self:
  45. methods = [m for m in member.__class__.__dict__.keys() if not m.startswith(
  46. '_') if not m.startswith('_') and callable(getattr(args[0], m))]
  47. if self.methods != methods:
  48. raise ValueError("All given instances needs to have same attributes:", self.methods, methods)
  49. def __iter__(self):
  50. return self
  51. def __next__(self):
  52. if self._iter_counter < len(self):
  53. self._iter_counter += 1
  54. return self._members[self._iter_counter - 1]
  55. self._iter_counter = 0
  56. raise StopIteration
  57. def __getitem__(self, i):
  58. return self._members[i]
  59. def __len__(self):
  60. return len(self._members)
  61. def __getattribute__(self, name):
  62. def group_execution(*args, **kwargs):
  63. for member in self[:]:
  64. m = getattr(member, name)
  65. m(*args, **kwargs)
  66. try:
  67. rv = super().__getattribute__(name)
  68. except AttributeError:
  69. return group_execution
  70. else:
  71. return rv
  72. class base(dict):
  73. TX_TOPIC = "set"
  74. TX_VALUE = 0
  75. TX_DICT = 1
  76. TX_TYPE = -1
  77. TX_FILTER_DATA_KEYS = []
  78. #
  79. RX_KEYS = []
  80. RX_IGNORE_TOPICS = []
  81. RX_IGNORE_KEYS = []
  82. RX_FILTER_DATA_KEYS = []
  83. def __init__(self, mqtt_client, topic):
  84. # data storage
  85. self.mqtt_client = mqtt_client
  86. self.topic = topic
  87. self.logger = logging.getLogger(ROOT_LOGGER_NAME).getChild(__name__)
  88. for entry in self.topic.split('/'):
  89. self.logger = self.logger.getChild(entry)
  90. # initialisations
  91. dict.__init__(self)
  92. mqtt_client.add_callback(
  93. topic=self.topic, callback=self.receive_callback)
  94. mqtt_client.add_callback(
  95. topic=self.topic+"/#", callback=self.receive_callback)
  96. #
  97. self.callback_list = []
  98. self.warning_callback = None
  99. #
  100. self.__previous__ = {}
  101. def receive_callback(self, client, userdata, message):
  102. self.unpack(message)
  103. def unpack_filter(self, key):
  104. if key in self.RX_FILTER_DATA_KEYS:
  105. if self.get(key) == 1 or self.get(key) == 'on' or self.get(key) == 'ON':
  106. self[key] = True
  107. elif self.get(key) == 0 or self.get(key) == 'off' or self.get(key) == 'OFF':
  108. self[key] = False
  109. def unpack_single_value(self, key, data):
  110. prev_value = self.get(key)
  111. if key in self.RX_KEYS:
  112. self[key] = data
  113. self.__previous__[key] = prev_value
  114. # Filter, if needed
  115. self.unpack_filter(key)
  116. self.logger.debug("Received data %s - %s", key, str(self.get(key)))
  117. self.callback_caller(key, self[key], self.get(key) != self.__previous__.get(key))
  118. elif key not in self.RX_IGNORE_KEYS:
  119. self.logger.warning('Got a message with unparsed content: "%s - %s"', key, str(data))
  120. else:
  121. self.logger.debug("Ignoring key %s", key)
  122. def unpack(self, message):
  123. content_key = message.topic[len(self.topic) + 1:]
  124. if content_key not in self.RX_IGNORE_TOPICS and (not message.topic.endswith(self.TX_TOPIC) or len(self.TX_TOPIC) == 0):
  125. self.logger.debug("Unpacking content_key \"%s\" from message.", content_key)
  126. if is_json(message.payload):
  127. data = json.loads(message.payload)
  128. if type(data) is dict:
  129. for key in data:
  130. self.unpack_single_value(key, data[key])
  131. else:
  132. self.unpack_single_value(content_key, data)
  133. # String
  134. else:
  135. self.unpack_single_value(
  136. content_key, message.payload.decode('utf-8'))
  137. self.warning_caller()
  138. else:
  139. self.logger.debug("Ignoring topic %s", content_key)
  140. def pack_filter(self, key, data):
  141. if key in self.TX_FILTER_DATA_KEYS:
  142. if data is True:
  143. return "on"
  144. elif data is False:
  145. return "off"
  146. else:
  147. return data
  148. return data
  149. def set(self, key, data):
  150. self.pack(key, data)
  151. def pack(self, key, data):
  152. data = self.pack_filter(key, data)
  153. if self.TX_TOPIC is not None:
  154. if self.TX_TYPE < 0:
  155. self.logger.error("Unknown tx type. Set TX_TYPE of class to a known value")
  156. else:
  157. self.logger.debug("Sending data for %s - %s", key, str(data))
  158. if self.TX_TYPE == self.TX_DICT:
  159. self.mqtt_client.send('/'.join([self.topic, self.TX_TOPIC]), json.dumps({key: data}))
  160. else:
  161. if type(data) not in [str, bytes]:
  162. data = json.dumps(data)
  163. self.mqtt_client.send('/'.join([self.topic, key, self.TX_TOPIC] if len(self.TX_TOPIC) > 0 else [self.topic, key]), data)
  164. else:
  165. self.logger.error("Unknown tx toptic. Set TX_TOPIC of class to a known value")
  166. def add_callback(self, key, data, callback, on_change_only=False):
  167. """
  168. key: key or None for all keys
  169. data: data or None for all data
  170. """
  171. cb_tup = (key, data, callback, on_change_only)
  172. if cb_tup not in self.callback_list:
  173. self.callback_list.append(cb_tup)
  174. def add_warning_callback(self, callback):
  175. self.warning_callback = callback
  176. def warning_call_condition(self):
  177. return False
  178. def callback_caller(self, key, data, value_changed):
  179. for cb_key, cb_data, callback, on_change_only in self.callback_list:
  180. if (cb_key == key or cb_key is None) and (cb_data == data or cb_data is None) and callback is not None:
  181. if not on_change_only or value_changed:
  182. callback(self, key, data)
  183. def warning_caller(self):
  184. if self.warning_call_condition():
  185. warn_txt = self.warning_text()
  186. self.logger.warning(warn_txt)
  187. if self.warning_callback is not None:
  188. self.warning_callback(self, warn_txt)
  189. def warning_text(self):
  190. return "default warning text - replace parent warning_text function"
  191. def previous_value(self, key):
  192. return self.__previous__.get(key)
  193. class shelly(base):
  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.all_off_requested = False
  226. def flash_task(self, *args):
  227. if self.flash_active:
  228. self.pack(self.output_key_delayed, not self.get(self.output_key_delayed))
  229. self.output_key_delayed = None
  230. if self.all_off_requested:
  231. self.delayed_off_task.run()
  232. def off_task(self, *args):
  233. self.all_off()
  234. @property
  235. def flash_active(self):
  236. return self.output_key_delayed is not None
  237. #
  238. # WARNING CALL
  239. #
  240. def warning_call_condition(self):
  241. return self.get(self.KEY_OVERTEMPERATURE)
  242. def warning_text(self):
  243. if self.overtemperature:
  244. if self.temperature is not None:
  245. return "Overtemperature detected for %s. Temperature was %.1f°C." % (self.topic, self.temperature)
  246. else:
  247. return "Overtemperature detected for %s." % self.topic
  248. #
  249. # RX
  250. #
  251. @property
  252. def output_0(self):
  253. """rv: [True, False]"""
  254. return self.get(self.KEY_OUTPUT_0)
  255. @property
  256. def output_1(self):
  257. """rv: [True, False]"""
  258. return self.get(self.KEY_OUTPUT_1)
  259. @property
  260. def input_0(self):
  261. """rv: [True, False]"""
  262. return self.get(self.KEY_INPUT_0)
  263. @property
  264. def input_1(self):
  265. """rv: [True, False]"""
  266. return self.get(self.KEY_INPUT_1)
  267. @property
  268. def longpush_0(self):
  269. """rv: [True, False]"""
  270. return self.get(self.KEY_LONGPUSH_0)
  271. @property
  272. def longpush_1(self):
  273. """rv: [True, False]"""
  274. return self.get(self.KEY_LONGPUSH_1)
  275. @property
  276. def temperature(self):
  277. """rv: numeric value"""
  278. return self.get(self.KEY_TEMPERATURE)
  279. #
  280. # TX
  281. #
  282. def set_output_0(self, state):
  283. """state: [True, False, 'toggle']"""
  284. self.pack(self.KEY_OUTPUT_0, state)
  285. def set_output_0_mcb(self, device, key, data):
  286. self.logger.log(logging.INFO if data != self.output_0 else logging.DEBUG, "Changing output 0 to %s", str(data))
  287. self.set_output_0(data)
  288. def toggle_output_0_mcb(self, device, key, data):
  289. self.logger.info("Toggeling output 0")
  290. self.set_output_0('toggle')
  291. def set_output_1(self, state):
  292. """state: [True, False, 'toggle']"""
  293. self.pack(self.KEY_OUTPUT_1, state)
  294. def set_output_1_mcb(self, device, key, data):
  295. self.logger.log(logging.INFO if data != self.output_1 else logging.DEBUG, "Changing output 1 to %s", str(data))
  296. self.set_output_1(data)
  297. def toggle_output_1_mcb(self, device, key, data):
  298. self.logger.info("Toggeling output 1")
  299. self.set_output_1('toggle')
  300. def flash_0_mcb(self, device, key, data):
  301. self.output_key_delayed = self.KEY_OUTPUT_0
  302. self.toggle_output_0_mcb(device, key, data)
  303. self.delayed_flash_task.run()
  304. def flash_1_mcb(self, device, key, data):
  305. self.output_key_delayed = self.KEY_OUTPUT_1
  306. self.toggle_output_1_mcb(device, key, data)
  307. self.delayed_flash_task.run()
  308. def all_off(self):
  309. if self.flash_active:
  310. self.all_off_requested = True
  311. else:
  312. self.set_output_0(False)
  313. self.set_output_1(False)
  314. class silvercrest_powerplug(base):
  315. KEY_LINKQUALITY = "linkquality"
  316. KEY_OUTPUT_0 = "state"
  317. #
  318. TX_TYPE = base.TX_DICT
  319. TX_FILTER_DATA_KEYS = [KEY_OUTPUT_0]
  320. #
  321. RX_KEYS = [KEY_LINKQUALITY, KEY_OUTPUT_0]
  322. RX_FILTER_DATA_KEYS = [KEY_OUTPUT_0]
  323. def __init__(self, mqtt_client, topic):
  324. super().__init__(mqtt_client, topic)
  325. #
  326. # RX
  327. #
  328. @property
  329. def output_0(self):
  330. """rv: [True, False]"""
  331. return self.get(self.KEY_OUTPUT_0)
  332. @property
  333. def linkquality(self):
  334. """rv: numeric value"""
  335. return self.get(self.KEY_LINKQUALITY)
  336. #
  337. # TX
  338. #
  339. def set_output_0(self, state):
  340. """state: [True, False, 'toggle']"""
  341. self.pack(self.KEY_OUTPUT_0, state)
  342. def set_output_0_mcb(self, device, key, data):
  343. self.logger.log(logging.INFO if data != self.output_0 else logging.DEBUG, "Changing output 0 to %s", str(data))
  344. self.set_output_0(data)
  345. def toggle_output_0_mcb(self, device, key, data):
  346. self.logger.info("Toggeling output 0")
  347. self.set_output_0('toggle')
  348. def all_off(self):
  349. self.set_output_0(False)
  350. class silvercrest_motion_sensor(base):
  351. KEY_BATTERY = "battery"
  352. KEY_BATTERY_LOW = "battery_low"
  353. KEY_LINKQUALITY = "linkquality"
  354. KEY_OCCUPANCY = "occupancy"
  355. KEY_UNMOUNTED = "tamper"
  356. KEY_VOLTAGE = "voltage"
  357. #
  358. RX_KEYS = [KEY_BATTERY, KEY_BATTERY_LOW, KEY_LINKQUALITY, KEY_OCCUPANCY, KEY_UNMOUNTED, KEY_VOLTAGE]
  359. def __init__(self, mqtt_client, topic):
  360. super().__init__(mqtt_client, topic)
  361. def warning_call_condition(self):
  362. return self.get(self.KEY_BATTERY_LOW)
  363. def warning_text(self, data):
  364. return "Battery low: level=%d" % self.get(self.KEY_BATTERY)
  365. #
  366. # RX
  367. #
  368. @property
  369. def linkquality(self):
  370. """rv: numeric value"""
  371. return self.get(self.KEY_LINKQUALITY)
  372. class my_powerplug(base):
  373. KEY_OUTPUT_0 = "output/1"
  374. KEY_OUTPUT_1 = "output/2"
  375. KEY_OUTPUT_2 = "output/3"
  376. KEY_OUTPUT_3 = "output/4"
  377. KEY_OUTPUT_ALL = "output/all"
  378. KEY_OUTPUT_LIST = [KEY_OUTPUT_0, KEY_OUTPUT_1, KEY_OUTPUT_2, KEY_OUTPUT_3]
  379. #
  380. TX_TYPE = base.TX_VALUE
  381. #
  382. RX_KEYS = [KEY_OUTPUT_0, KEY_OUTPUT_1, KEY_OUTPUT_2, KEY_OUTPUT_3]
  383. def __init__(self, mqtt_client, topic):
  384. super().__init__(mqtt_client, topic)
  385. #
  386. # RX
  387. #
  388. @property
  389. def output_0(self):
  390. """rv: [True, False]"""
  391. return self.get(self.KEY_OUTPUT_0)
  392. @property
  393. def output_1(self):
  394. """rv: [True, False]"""
  395. return self.get(self.KEY_OUTPUT_1)
  396. @property
  397. def output_2(self):
  398. """rv: [True, False]"""
  399. return self.get(self.KEY_OUTPUT_2)
  400. @property
  401. def output_3(self):
  402. """rv: [True, False]"""
  403. return self.get(self.KEY_OUTPUT_3)
  404. #
  405. # TX
  406. #
  407. def set_output(self, key, state):
  408. if key in self.KEY_OUTPUT_LIST:
  409. self.pack(key, state)
  410. else:
  411. logging.error("Unknown key to set the output!")
  412. def set_output_0(self, state):
  413. """state: [True, False, 'toggle']"""
  414. self.pack(self.KEY_OUTPUT_0, state)
  415. def set_output_0_mcb(self, device, key, data):
  416. self.logger.log(logging.INFO if data != self.output_0 else logging.DEBUG, "Changing output 0 to %s", str(data))
  417. self.set_output_0(data)
  418. def toggle_output_0_mcb(self, device, key, data):
  419. self.logger.info("Toggeling output 0")
  420. self.set_output_0('toggle')
  421. def set_output_1(self, state):
  422. """state: [True, False, 'toggle']"""
  423. self.pack(self.KEY_OUTPUT_1, state)
  424. def set_output_1_mcb(self, device, key, data):
  425. self.logger.log(logging.INFO if data != self.output_1 else logging.DEBUG, "Changing output 1 to %s", str(data))
  426. self.set_output_1(data)
  427. def toggle_output_1_mcb(self, device, key, data):
  428. self.logger.info("Toggeling output 1")
  429. self.set_output_1('toggle')
  430. def set_output_2(self, state):
  431. """state: [True, False, 'toggle']"""
  432. self.pack(self.KEY_OUTPUT_2, state)
  433. def set_output_2_mcb(self, device, key, data):
  434. self.logger.log(logging.INFO if data != self.output_2 else logging.DEBUG, "Changing output 2 to %s", str(data))
  435. self.set_output_2(data)
  436. def toggle_output_2_mcb(self, device, key, data):
  437. self.logger.info("Toggeling output 2")
  438. self.set_output_2('toggle')
  439. def set_output_3(self, state):
  440. """state: [True, False, 'toggle']"""
  441. self.pack(self.KEY_OUTPUT_3, state)
  442. def set_output_3_mcb(self, device, key, data):
  443. self.logger.log(logging.INFO if data != self.output_3 else logging.DEBUG, "Changing output 3 to %s", str(data))
  444. self.set_output_3(data)
  445. def toggle_output_3_mcb(self, device, key, data):
  446. self.logger.info("Toggeling output 3")
  447. self.set_output_3('toggle')
  448. def set_output_all(self, state):
  449. """state: [True, False, 'toggle']"""
  450. self.pack(self.KEY_OUTPUT_ALL, state)
  451. def set_output_all_mcb(self, device, key, data):
  452. self.logger.info("Changing all outputs to %s", str(data))
  453. self.set_output_all(data)
  454. def toggle_output_all_mcb(self, device, key, data):
  455. self.logger.info("Toggeling all outputs")
  456. self.set_output_0('toggle')
  457. def all_off(self):
  458. self.set_output_all(False)
  459. class tradfri_light(base):
  460. KEY_LINKQUALITY = "linkquality"
  461. KEY_OUTPUT_0 = "state"
  462. KEY_BRIGHTNESS = "brightness"
  463. KEY_COLOR_TEMP = "color_temp"
  464. KEY_BRIGHTNESS_FADE = "brightness_move"
  465. #
  466. TX_TYPE = base.TX_DICT
  467. TX_FILTER_DATA_KEYS = [KEY_OUTPUT_0, KEY_BRIGHTNESS, KEY_COLOR_TEMP, KEY_BRIGHTNESS_FADE]
  468. #
  469. RX_KEYS = [KEY_LINKQUALITY, KEY_OUTPUT_0, KEY_BRIGHTNESS, KEY_COLOR_TEMP]
  470. RX_IGNORE_KEYS = ['update', 'color_mode', 'color_temp_startup']
  471. RX_FILTER_DATA_KEYS = [KEY_OUTPUT_0, KEY_BRIGHTNESS, KEY_COLOR_TEMP]
  472. def __init__(self, mqtt_client, topic):
  473. super().__init__(mqtt_client, topic)
  474. def unpack_filter(self, key):
  475. if key == self.KEY_BRIGHTNESS:
  476. self[key] = round((self[key] - 1) * 100 / 253, 0)
  477. elif key == self.KEY_COLOR_TEMP:
  478. self[key] = round((self[key] - 250) * 10 / 204, 0)
  479. else:
  480. super().unpack_filter(key)
  481. def pack_filter(self, key, data):
  482. if key == self.KEY_BRIGHTNESS:
  483. return round(data * 253 / 100 + 1, 0)
  484. elif key == self.KEY_COLOR_TEMP:
  485. return round(data * 204 / 10 + 250, 0)
  486. else:
  487. return super().pack_filter(key, data)
  488. #
  489. # RX
  490. #
  491. @property
  492. def output_0(self):
  493. """rv: [True, False]"""
  494. return self.get(self.KEY_OUTPUT_0, False)
  495. @property
  496. def linkquality(self):
  497. """rv: numeric value"""
  498. return self.get(self.KEY_LINKQUALITY, 0)
  499. @property
  500. def brightness(self):
  501. """rv: numeric value [0%, ..., 100%]"""
  502. return self.get(self.KEY_BRIGHTNESS, 0)
  503. @property
  504. def color_temp(self):
  505. """rv: numeric value [0, ..., 10]"""
  506. return self.get(self.KEY_COLOR_TEMP, 0)
  507. #
  508. # TX
  509. #
  510. def request_data(self, device=None, key=None, data=None):
  511. self.mqtt_client.send(self.topic + "/get", '{"%s": ""}' % self.KEY_OUTPUT_0)
  512. def set_output_0(self, state):
  513. """state: [True, False, 'toggle']"""
  514. self.pack(self.KEY_OUTPUT_0, state)
  515. def set_output_0_mcb(self, device, key, data):
  516. self.logger.log(logging.INFO if data != self.output_0 else logging.DEBUG, "Changing output 0 to %s", str(data))
  517. self.set_output_0(data)
  518. def toggle_output_0_mcb(self, device, key, data):
  519. self.logger.info("Toggeling output 0")
  520. self.set_output_0('toggle')
  521. def set_brightness(self, brightness):
  522. """brightness: [0, ..., 100]"""
  523. self.pack(self.KEY_BRIGHTNESS, brightness)
  524. def set_brightness_mcb(self, device, key, data):
  525. self.logger.log(logging.INFO if data != self.brightness else logging.DEBUG, "Changing brightness to %s", str(data))
  526. self.set_brightness(data)
  527. def default_inc(self, speed=40):
  528. self.pack(self.KEY_BRIGHTNESS_FADE, speed)
  529. def default_dec(self, speed=-40):
  530. self.default_inc(speed)
  531. def default_stop(self):
  532. self.default_inc(0)
  533. def set_color_temp(self, color_temp):
  534. """color_temp: [0, ..., 10]"""
  535. self.pack(self.KEY_COLOR_TEMP, color_temp)
  536. def set_color_temp_mcb(self, device, key, data):
  537. self.logger.log(logging.INFO if data != self.color_temp else logging.DEBUG, "Changing color temperature to %s", str(data))
  538. self.set_color_temp(data)
  539. def all_off(self):
  540. self.set_output_0(False)
  541. class tradfri_button(base):
  542. ACTION_TOGGLE = "toggle"
  543. ACTION_BRIGHTNESS_UP = "brightness_up_click"
  544. ACTION_BRIGHTNESS_DOWN = "brightness_down_click"
  545. ACTION_RIGHT = "arrow_right_click"
  546. ACTION_LEFT = "arrow_left_click"
  547. ACTION_BRIGHTNESS_UP_LONG = "brightness_up_hold"
  548. ACTION_BRIGHTNESS_UP_RELEASE = "brightness_up_release"
  549. ACTION_BRIGHTNESS_DOWN_LONG = "brightness_down_hold"
  550. ACTION_BRIGHTNESS_DOWN_RELEASE = "brightness_down_release"
  551. ACTION_RIGHT_LONG = "arrow_right_hold"
  552. ACTION_RIGHT_RELEASE = "arrow_right_release"
  553. ACTION_LEFT_LONG = "arrow_left_hold"
  554. ACTION_LEFT_RELEASE = "arrow_left_release"
  555. #
  556. KEY_LINKQUALITY = "linkquality"
  557. KEY_BATTERY = "battery"
  558. KEY_ACTION = "action"
  559. KEY_ACTION_DURATION = "action_duration"
  560. #
  561. RX_KEYS = [KEY_LINKQUALITY, KEY_BATTERY, KEY_ACTION]
  562. RX_IGNORE_KEYS = ['update', KEY_ACTION_DURATION]
  563. def __init__(self, mqtt_client, topic):
  564. super().__init__(mqtt_client, topic)
  565. #
  566. # RX
  567. #
  568. @property
  569. def action(self):
  570. """rv: action_txt"""
  571. return self.get(self.KEY_ACTION)
  572. #
  573. # WARNING CALL
  574. #
  575. def warning_call_condition(self):
  576. return self.get(self.KEY_BATTERY) is not None and self.get(self.KEY_BATTERY) <= BATTERY_WARN_LEVEL
  577. def warning_text(self):
  578. return "Low battery level detected for %s. Battery level was %.0f%%." % (self.topic, self.get(self.KEY_BATTERY))
  579. class brennenstuhl_heatingvalve(base):
  580. KEY_LINKQUALITY = "linkquality"
  581. KEY_BATTERY = "battery"
  582. KEY_HEATING_SETPOINT = "current_heating_setpoint"
  583. KEY_TEMPERATURE = "local_temperature"
  584. #
  585. KEY_AWAY_MODE = "away_mode"
  586. KEY_CHILD_LOCK = "child_lock"
  587. KEY_PRESET = "preset"
  588. KEY_SYSTEM_MODE = "system_mode"
  589. KEY_VALVE_DETECTION = "valve_detection"
  590. KEY_WINDOW_DETECTION = "window_detection"
  591. #
  592. TX_TYPE = base.TX_DICT
  593. #
  594. RX_KEYS = [KEY_LINKQUALITY, KEY_BATTERY, KEY_HEATING_SETPOINT, KEY_TEMPERATURE]
  595. RX_IGNORE_KEYS = [KEY_AWAY_MODE, KEY_CHILD_LOCK, KEY_PRESET, KEY_SYSTEM_MODE, KEY_VALVE_DETECTION, KEY_WINDOW_DETECTION]
  596. def __init__(self, mqtt_client, topic):
  597. super().__init__(mqtt_client, topic)
  598. self.mqtt_client.send(self.topic + '/' + self.TX_TOPIC, json.dumps({self.KEY_WINDOW_DETECTION: "ON",
  599. self.KEY_CHILD_LOCK: "UNLOCK", self.KEY_VALVE_DETECTION: "ON", self.KEY_SYSTEM_MODE: "heat", self.KEY_PRESET: "manual"}))
  600. def warning_call_condition(self):
  601. return self.get(self.KEY_BATTERY, 100) <= BATTERY_WARN_LEVEL
  602. def warning_text(self):
  603. return "Low battery level detected for %s. Battery level was %.0f%%." % (self.topic, self.get(self.KEY_BATTERY))
  604. #
  605. # RX
  606. #
  607. @property
  608. def linkqulity(self):
  609. return self.get(self.KEY_LINKQUALITY)
  610. @property
  611. def heating_setpoint(self):
  612. return self.get(self.KEY_HEATING_SETPOINT)
  613. @property
  614. def temperature(self):
  615. return self.get(self.KEY_TEMPERATURE)
  616. #
  617. # TX
  618. #
  619. def set_heating_setpoint(self, setpoint):
  620. self.pack(self.KEY_HEATING_SETPOINT, setpoint)
  621. def set_heating_setpoint_mcb(self, device, key, data):
  622. self.logger.info("Changing heating setpoint to %s", str(data))
  623. self.set_heating_setpoint(data)
  624. class remote(base):
  625. KEY_CD = "CD"
  626. KEY_LINE1 = "LINE1"
  627. KEY_LINE3 = "LINE3"
  628. KEY_MUTE = "MUTE"
  629. KEY_POWER = "POWER"
  630. KEY_VOLDOWN = "VOLDOWN"
  631. KEY_VOLUP = "VOLUP"
  632. #
  633. TX_TOPIC = ''
  634. TX_TYPE = base.TX_VALUE
  635. #
  636. RX_IGNORE_TOPICS = [KEY_CD, KEY_LINE1, KEY_LINE3, KEY_MUTE, KEY_POWER, KEY_VOLUP, KEY_VOLDOWN]
  637. def set_cd(self, device=None, key=None, data=None):
  638. self.pack(self.KEY_CD, None)
  639. def set_line1(self, device=None, key=None, data=None):
  640. self.pack(self.KEY_LINE1, None)
  641. def set_line3(self, device=None, key=None, data=None):
  642. self.pack(self.KEY_LINE3, None)
  643. def set_mute(self, device=None, key=None, data=None):
  644. self.pack(self.KEY_MUTE, None)
  645. def set_power(self, device=None, key=None, data=None):
  646. self.pack(self.KEY_POWER, None)
  647. def set_volume_up(self, data=False):
  648. """data: [True, False]"""
  649. self.pack(self.KEY_VOLUP, data)
  650. def set_volume_down(self, data=False):
  651. """data: [True, False]"""
  652. self.pack(self.KEY_VOLDOWN, data)
  653. def default_inc(self, device=None, key=None, data=None):
  654. self.set_volume_up(True)
  655. def default_dec(self, device=None, key=None, data=None):
  656. self.set_volume_down(True)
  657. def default_stop(self, device=None, key=None, data=None):
  658. self.set_volume_up(False)
  659. class status(base):
  660. KEY_STATE = "state"
  661. #
  662. TX_TYPE = base.TX_VALUE
  663. #
  664. RX_KEYS = [KEY_STATE]
  665. def set_state(self, num, data):
  666. """data: [True, False]"""
  667. self.pack(self.KEY_STATE + "/" + str(num), data)
  668. def set_state_mcb(self, device, key, data):
  669. self.logger.info("Changing state to %s", str(data))
  670. self.set_state(data)
  671. class audio_status(status):
  672. KEY_TITLE = "title"
  673. #
  674. RX_KEYS = [status.KEY_STATE, KEY_TITLE]