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 30KB

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