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.

devices.py 34KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846
  1. import colored
  2. import json
  3. import task
  4. import time
  5. COLOR_GUI_ACTIVE = colored.fg("light_blue")
  6. COLOR_GUI_PASSIVE = COLOR_GUI_ACTIVE + colored.attr("dim")
  7. COLOR_SHELLY = colored.fg("light_magenta")
  8. COLOR_POWERPLUG = colored.fg("light_cyan")
  9. COLOR_LIGHT_ACTIVE = colored.fg("yellow")
  10. COLOR_LIGHT_PASSIVE = COLOR_LIGHT_ACTIVE + colored.attr("dim")
  11. COLOR_MOTION_SENSOR = colored.fg("dark_orange_3b")
  12. COLOR_HEATING_VALVE = colored.fg("red")
  13. COLOR_REMOTE = colored.fg("green")
  14. def payload_filter(payload):
  15. try:
  16. return json.loads(payload)
  17. except json.decoder.JSONDecodeError:
  18. return payload.decode("utf-8")
  19. def command_int_value(value):
  20. try:
  21. return int(value)
  22. except TypeError:
  23. print("You need to give a integer parameter not '%s'" % str(value))
  24. def command_float_value(value):
  25. try:
  26. return float(value)
  27. except TypeError:
  28. print("You need to give a integer parameter not '%s'" % str(value))
  29. def devicename(topic):
  30. return " - ".join(topic.split('/')[1:])
  31. def percent_bar(value):
  32. rv = ""
  33. for i in range(0, 10):
  34. rv += u"\u25ac" if (value - 5) > 10*i else u"\u25ad"
  35. return rv
  36. def print_light(color, state, topic, description, led=False):
  37. if led is True:
  38. if state is True:
  39. icon = colored.fg('green') + "\u2b24" + color
  40. else:
  41. icon = colored.fg('light_gray') + "\u2b24" + color
  42. else:
  43. icon = u'\u2b24' if state is True else u'\u25ef'
  44. print(color + 10 * ' ' + icon + 9 * ' ' + devicename(topic), description + colored.attr("reset"))
  45. def print_switch(color, state, topic, description):
  46. icon = u'\u25a0' if state is True else u'\u25a1'
  47. print(color + 10 * ' ' + icon + 9 * ' ' + devicename(topic), description + colored.attr("reset"))
  48. def print_percent(color, prefix, perc_value, value_str, topic, description):
  49. if len(prefix) > 1 or len(value_str) > 7:
  50. raise ValueError("Length of prefix (%d) > 1 or length of value_str (%d) > 7" % (len(prefix), len(value_str)))
  51. print(color + prefix + percent_bar(perc_value), value_str + (8 - len(value_str)) * ' ' + devicename(topic), description + colored.attr("reset"))
  52. class base(object):
  53. AUTOSEND = True
  54. COMMANDS = []
  55. def __init__(self, mqtt_client, topic):
  56. self.mqtt_client = mqtt_client
  57. self.topic = topic
  58. #
  59. self.data = {}
  60. self.callbacks = {}
  61. self.names = {}
  62. self.commands = self.COMMANDS[:]
  63. #
  64. self.mqtt_client.add_callback(self.topic, self.__rx__)
  65. self.mqtt_client.add_callback(self.topic + '/#', self.__rx__)
  66. def add_callback(self, key, callback, value):
  67. if self.callbacks.get(key) is None:
  68. self.callbacks[key] = []
  69. self.callbacks[key].append((callback, value))
  70. def add_channel_name(self, key, name):
  71. self.names[key] = name
  72. def capabilities(self):
  73. return self.commands
  74. def store_data(self, *args, **kwargs):
  75. keys_changed = []
  76. for key in kwargs:
  77. if kwargs[key] is not None and kwargs[key] != self.data.get(key):
  78. keys_changed.append(key)
  79. self.data[key] = kwargs[key]
  80. for callback, value in self.callbacks.get(key, [(None, None)]):
  81. if callback is not None and (value is None or value == kwargs[key]):
  82. callback(self, key, kwargs[key])
  83. if self.AUTOSEND and len(keys_changed) > 0:
  84. self.__tx__(keys_changed)
  85. def __tx__(self, keys_changed):
  86. self.mqtt_client.send(self.topic, json.dumps(self.data))
  87. def __rx__(self, client, userdata, message):
  88. print("%s: __rx__ not handled!" % self.__class__.__name__)
  89. class shelly(base):
  90. KEY_OUTPUT_0 = "relay/0"
  91. KEY_OUTPUT_1 = "relay/1"
  92. KEY_INPUT_0 = "input/0"
  93. KEY_INPUT_1 = "input/1"
  94. KEY_LONGPUSH_0 = "longpush/0"
  95. KEY_LONGPUSH_1 = "longpush/1"
  96. #
  97. INPUT_FUNC_OUT1_FOLLOW = "out1_follow"
  98. INPUT_FUNC_OUT1_TRIGGER = "out1_trigger"
  99. INPUT_FUNC_OUT2_FOLLOW = "out2_follow"
  100. INPUT_FUNC_OUT2_TRIGGER = "out2_trigger"
  101. #
  102. COMMANDS = [
  103. "get_relay_0", "toggle_relay_0",
  104. "get_relay_1", "toggle_relay_1",
  105. "get_input_0", "toggle_input_0",
  106. "get_input_1", "toggle_input_1",
  107. "trigger_long_input_0", "trigger_long_input_1",
  108. ]
  109. def __init__(self, mqtt_client, topic, input_0_func=None, input_1_func=None, output_0_auto_off=None):
  110. super().__init__(mqtt_client, topic)
  111. #
  112. self.store_data(**{self.KEY_OUTPUT_0: "off", self.KEY_OUTPUT_1: "off", self.KEY_INPUT_0: "off", self.KEY_INPUT_1: "off"})
  113. self.__input_0_func = input_0_func
  114. self.__input_1_func = input_1_func
  115. self.__output_0_auto_off__ = output_0_auto_off
  116. if self.__output_0_auto_off__ is not None:
  117. self.__delayed_off__ = task.delayed(float(self.__output_0_auto_off__), self.__auto_off__, self.KEY_OUTPUT_0)
  118. #
  119. self.add_callback(self.KEY_OUTPUT_0, self.print_formatted, None)
  120. self.add_callback(self.KEY_OUTPUT_0, self.__start_auto_off__, "on")
  121. self.add_callback(self.KEY_OUTPUT_0, self.__stop_auto_off__, "off")
  122. self.add_callback(self.KEY_OUTPUT_1, self.print_formatted, None)
  123. #
  124. self.add_callback(self.KEY_INPUT_0, self.__input_function__, None)
  125. self.add_callback(self.KEY_INPUT_1, self.__input_function__, None)
  126. def __rx__(self, client, userdata, message):
  127. value = payload_filter(message.payload)
  128. if message.topic.startswith(self.topic) and message.topic.endswith("/command"):
  129. key = '/'.join(message.topic.split('/')[-3:-1])
  130. if value == 'toggle':
  131. self.__toggle_data__(key)
  132. else:
  133. self.__set_data__(key, value)
  134. def __tx__(self, keys_changed):
  135. for key in keys_changed:
  136. self.mqtt_client.send(self.topic + '/' + key, self.data.get(key))
  137. def __input_function__(self, device, key, data):
  138. if key == self.KEY_INPUT_0:
  139. func = self.__input_0_func
  140. elif key == self.KEY_INPUT_1:
  141. func = self.__input_1_func
  142. else:
  143. func = None
  144. if func == self.INPUT_FUNC_OUT1_FOLLOW:
  145. self.__set_data__(self.KEY_OUTPUT_0, data)
  146. elif func == self.INPUT_FUNC_OUT1_TRIGGER:
  147. self.__toggle_data__(self.KEY_OUTPUT_0)
  148. elif func == self.INPUT_FUNC_OUT2_FOLLOW:
  149. self.__set_data__(self.KEY_OUTPUT_1, data)
  150. elif func == self.INPUT_FUNC_OUT2_TRIGGER:
  151. self.__toggle_data__(self.KEY_OUTPUT_1)
  152. def __start_auto_off__(self, device, key, data):
  153. self.__stop_auto_off__(device, key, data)
  154. if self.__output_0_auto_off__ is not None:
  155. self.__delayed_off__.run()
  156. def __stop_auto_off__(self, device, key, data):
  157. if self.__output_0_auto_off__ is not None:
  158. if not self.__delayed_off__._stopped:
  159. self.__delayed_off__.stop()
  160. def __auto_off__(self, key):
  161. if key == self.KEY_OUTPUT_0:
  162. self.__set_data__(key, 'off')
  163. def __set_data__(self, key, value):
  164. if value in ["on", "off"]:
  165. self.store_data(**{key: value})
  166. else:
  167. print("Wrong value (%s)!" % repr(value))
  168. def __toggle_data__(self, key):
  169. if key in self.data:
  170. self.__set_data__(key, 'on' if self.data.get(key) == 'off' else 'off')
  171. def command(self, command):
  172. if command in self.COMMANDS:
  173. if command == self.COMMANDS[0]:
  174. self.print_formatted(self, self.KEY_OUTPUT_0, self.data.get(self.KEY_OUTPUT_0))
  175. elif command == self.COMMANDS[1]:
  176. self.__toggle_data__(self.KEY_OUTPUT_0)
  177. elif command == self.COMMANDS[2]:
  178. self.print_formatted(self, self.KEY_OUTPUT_1, self.data.get(self.KEY_OUTPUT_1))
  179. elif command == self.COMMANDS[3]:
  180. self.__toggle_data__(self.KEY_OUTPUT_1)
  181. elif command == self.COMMANDS[4]:
  182. self.print_formatted(self, self.KEY_INPUT_0, self.data.get(self.KEY_INPUT_0))
  183. elif command == self.COMMANDS[5]:
  184. self.__toggle_data__(self.KEY_INPUT_0)
  185. elif command == self.COMMANDS[6]:
  186. self.print_formatted(self, self.KEY_INPUT_1, self.data.get(self.KEY_INPUT_1))
  187. elif command == self.COMMANDS[7]:
  188. self.__toggle_data__(self.KEY_INPUT_1)
  189. elif command == self.COMMANDS[8]:
  190. self.__toggle_data__(self.KEY_INPUT_0)
  191. time.sleep(0.4)
  192. self.__set_data__(self.KEY_LONGPUSH_0, 'on')
  193. time.sleep(0.1)
  194. self.__set_data__(self.KEY_LONGPUSH_0, 'off')
  195. elif command == self.COMMANDS[9]:
  196. self.__toggle_data__(self.KEY_INPUT_1)
  197. time.sleep(0.4)
  198. self.__set_data__(self.KEY_LONGPUSH_1, 'on')
  199. time.sleep(0.1)
  200. self.__set_data__(self.KEY_LONGPUSH_1, 'off')
  201. else:
  202. print("%s: not yet implemented!" % command)
  203. else:
  204. print("Unknown command!")
  205. def print_formatted(self, device, key, value):
  206. if value is not None:
  207. info = (" - %ds" % self.__output_0_auto_off__) if self.__output_0_auto_off__ is not None and value == "on" else ""
  208. channel = "(%s%s)" % (self.names.get(key, key), info)
  209. print_light(COLOR_SHELLY, value == "on", self.topic, channel)
  210. class my_powerplug(base):
  211. KEY_OUTPUT_0 = "0"
  212. KEY_OUTPUT_1 = "1"
  213. KEY_OUTPUT_2 = "2"
  214. KEY_OUTPUT_3 = "3"
  215. COMMANDS = [
  216. "get_output_0", "toggle_output_0",
  217. "get_output_1", "toggle_output_1",
  218. "get_output_2", "toggle_output_2",
  219. "get_output_3", "toggle_output_3",
  220. ]
  221. def __init__(self, mqtt_client, topic):
  222. super().__init__(mqtt_client, topic)
  223. #
  224. for i in range(0, 4):
  225. self.data[str(i)] = False
  226. self.add_callback(str(i), self.print_formatted, None)
  227. def __rx__(self, client, userdata, message):
  228. if message.topic.startswith(self.topic + '/output/') and message.topic.endswith('/set'):
  229. try:
  230. channels = [int(message.topic.split('/')[-2]) - 1]
  231. except ValueError:
  232. channels = range(0, 4)
  233. for channel in channels:
  234. payload = payload_filter(message.payload)
  235. if payload == "toggle":
  236. payload = not self.data.get(str(channel))
  237. self.store_data(**{str(channel): payload})
  238. def __tx__(self, keys_changed):
  239. for key in keys_changed:
  240. self.mqtt_client.send(self.topic + "/output/" + str(int(key) + 1), json.dumps(self.data.get(key)))
  241. def command(self, command):
  242. if command in self.COMMANDS:
  243. if command == self.COMMANDS[0]:
  244. self.print_formatted(self, self.KEY_OUTPUT_0, self.data.get(self.KEY_OUTPUT_0))
  245. elif command == self.COMMANDS[1]:
  246. self.store_data(**{self.KEY_OUTPUT_0: not self.data.get(self.KEY_OUTPUT_0)})
  247. elif command == self.COMMANDS[2]:
  248. self.print_formatted(self, self.KEY_OUTPUT_1, self.data.get(self.KEY_OUTPUT_1))
  249. elif command == self.COMMANDS[3]:
  250. self.store_data(**{self.KEY_OUTPUT_1: not self.data.get(self.KEY_OUTPUT_1)})
  251. elif command == self.COMMANDS[4]:
  252. self.print_formatted(self, self.KEY_OUTPUT_2, self.data.get(self.KEY_OUTPUT_2))
  253. elif command == self.COMMANDS[5]:
  254. self.store_data(**{self.KEY_OUTPUT_2: not self.data.get(self.KEY_OUTPUT_2)})
  255. elif command == self.COMMANDS[6]:
  256. self.print_formatted(self, self.KEY_OUTPUT_3, self.data.get(self.KEY_OUTPUT_3))
  257. elif command == self.COMMANDS[7]:
  258. self.store_data(**{self.KEY_OUTPUT_3: not self.data.get(self.KEY_OUTPUT_3)})
  259. else:
  260. print("%s: not yet implemented!" % command)
  261. else:
  262. print("Unknown command!")
  263. def print_formatted(self, device, key, value):
  264. if value is not None:
  265. print_light(COLOR_POWERPLUG, value, self.topic, "(%s)" % self.names.get(key, "Channel %d" % (int(key) + 1)))
  266. class silvercrest_powerplug(base):
  267. KEY_OUTPUT_0 = "state"
  268. #
  269. COMMANDS = [
  270. "get_state", "set_state", "unset_state",
  271. ]
  272. def __init__(self, mqtt_client, topic):
  273. super().__init__(mqtt_client, topic)
  274. self.add_callback(self.KEY_OUTPUT_0, self.print_formatted, None)
  275. #
  276. self.store_data(**{self.KEY_OUTPUT_0: "off"})
  277. def __rx__(self, client, userdata, message):
  278. if message.topic == self.topic + '/set':
  279. STATES = ["on", "off", "toggle"]
  280. #
  281. state = json.loads(message.payload).get('state').lower()
  282. if state in STATES:
  283. if state == STATES[0]:
  284. self.store_data(**{self.KEY_OUTPUT_0: 'on'})
  285. elif state == STATES[1]:
  286. self.store_data(**{self.KEY_OUTPUT_0: 'off'})
  287. else:
  288. self.store_data(**{self.KEY_OUTPUT_0: "off" if self.data.get(self.KEY_OUTPUT_0) == "on" else "on"})
  289. def command(self, command):
  290. if command in self.COMMANDS:
  291. if command == self.COMMANDS[0]:
  292. self.print_formatted(self, self.KEY_OUTPUT_0, self.data.get(self.KEY_OUTPUT_0))
  293. elif command == self.COMMANDS[1]:
  294. self.store_data(**{self.KEY_OUTPUT_0: 'on'})
  295. elif command == self.COMMANDS[2]:
  296. self.store_data(**{self.KEY_OUTPUT_0: 'off'})
  297. else:
  298. print("%s: not yet implemented!" % command)
  299. else:
  300. print("Unknown command!")
  301. def print_formatted(self, device, key, value):
  302. if value is not None:
  303. print_light(COLOR_POWERPLUG, value == "on", self.topic, "(%s)" % self.names.get(key, key))
  304. class silvercrest_motion_sensor(base):
  305. KEY_OCCUPANCY = "occupancy"
  306. COMMANDS = ['motion']
  307. def __init__(self, mqtt_client, topic):
  308. super().__init__(mqtt_client, topic)
  309. self.data[self.KEY_OCCUPANCY] = False
  310. self.add_callback(self.KEY_OCCUPANCY, self.print_formatted, None)
  311. def __rx__(self, client, userdata, message):
  312. pass
  313. def command(self, command):
  314. try:
  315. command, value = command.split(' ')
  316. except ValueError:
  317. value = None
  318. else:
  319. value = json.loads(value)
  320. if command == self.COMMANDS[0]:
  321. self.store_data(**{self.KEY_OCCUPANCY: True})
  322. time.sleep(value or 10)
  323. self.store_data(**{self.KEY_OCCUPANCY: False})
  324. def print_formatted(self, device, key, value):
  325. if value is not None:
  326. print_light(COLOR_MOTION_SENSOR, value, self.topic, "")
  327. class tradfri_light(base):
  328. KEY_STATE = "state"
  329. KEY_BRIGHTNESS = "brightness"
  330. KEY_COLOR_TEMP = "color_temp"
  331. KEY_BRIGHTNESS_MOVE = "brightness_move"
  332. #
  333. STATE_COMMANDS = ("get_state", "toggle_state", )
  334. BRIGHTNESS_COMMANDS = ("get_brightness", "set_brightness",)
  335. COLOR_TEMP_COMMANDS = ("get_color_temp", "set_color_temp",)
  336. def __init__(self, mqtt_client, topic, enable_state=True, enable_brightness=False, enable_color_temp=False, send_on_power_on=True):
  337. super().__init__(mqtt_client, topic)
  338. self.send_on_power_on = send_on_power_on
  339. self.add_callback(self.KEY_STATE, self.print_formatted, None)
  340. self.add_callback(self.KEY_BRIGHTNESS, self.print_formatted, None)
  341. self.add_callback(self.KEY_COLOR_TEMP, self.print_formatted, None)
  342. #
  343. self.commands = []
  344. if enable_state:
  345. self.commands.extend(self.STATE_COMMANDS)
  346. if enable_brightness:
  347. self.commands.extend(self.BRIGHTNESS_COMMANDS)
  348. if enable_color_temp:
  349. self.commands.extend(self.COLOR_TEMP_COMMANDS)
  350. self.__init_data__(enable_state, enable_brightness, enable_color_temp)
  351. def __init_data__(self, enable_state, enable_brightness, enable_color_temp):
  352. data = {}
  353. if enable_state:
  354. data[self.KEY_STATE] = 'off'
  355. self.commands.extend(self.STATE_COMMANDS)
  356. if enable_brightness:
  357. data[self.KEY_BRIGHTNESS] = 128
  358. self.brightnes_move = (0, time.time())
  359. self.commands.extend(self.BRIGHTNESS_COMMANDS)
  360. if enable_color_temp:
  361. data[self.KEY_COLOR_TEMP] = 352
  362. self.commands.extend(self.COLOR_TEMP_COMMANDS)
  363. self.store_data(**data)
  364. def __rx__(self, client, userdata, message):
  365. data = json.loads(message.payload)
  366. if self.data.get(self.KEY_STATE) == 'on' or data.get(self.KEY_STATE) in ['on', 'toggle']:
  367. if message.topic.startswith(self.topic) and message.topic.endswith('/set'):
  368. for targetkey in data:
  369. value = data[targetkey]
  370. if targetkey in self.data.keys():
  371. if targetkey == self.KEY_STATE and value == "toggle":
  372. value = "on" if self.data.get(self.KEY_STATE) == "off" else "off"
  373. self.store_data(**{targetkey: value})
  374. else:
  375. if targetkey == self.KEY_BRIGHTNESS_MOVE:
  376. new_value = self.data.get(self.KEY_BRIGHTNESS) + (time.time() - self.brightnes_move[1]) * self.brightnes_move[0]
  377. if new_value < 0:
  378. new_value = 0
  379. if new_value > 255:
  380. new_value = 255
  381. self.store_data(**{self.KEY_BRIGHTNESS: int(new_value)})
  382. self.brightnes_move = (value, time.time())
  383. else:
  384. print("%s: UNKNOWN KEY %s" % (message.topic, targetkey))
  385. elif message.topic == self.topic + '/get':
  386. self.__tx__(None)
  387. def command(self, command):
  388. try:
  389. command, value = command.split(' ')
  390. except ValueError:
  391. value = None
  392. if command in self.capabilities():
  393. if command == self.STATE_COMMANDS[0]:
  394. self.print_formatted(self, self.KEY_STATE, self.data.get(self.KEY_STATE))
  395. elif command == self.STATE_COMMANDS[1]:
  396. self.store_data(**{self.KEY_STATE: 'off' if self.data.get(self.KEY_STATE) == 'on' else 'on'})
  397. elif command == self.BRIGHTNESS_COMMANDS[0]:
  398. self.print_formatted(self, self.KEY_BRIGHTNESS, self.data.get(self.KEY_BRIGHTNESS))
  399. elif command == self.BRIGHTNESS_COMMANDS[1]:
  400. self.store_data(**{self.KEY_BRIGHTNESS: command_int_value(value)})
  401. elif command == self.COLOR_TEMP_COMMANDS[0]:
  402. self.print_formatted(self, self.KEY_COLOR_TEMP, self.data.get(self.KEY_COLOR_TEMP))
  403. elif command == self.COLOR_TEMP_COMMANDS[1]:
  404. self.store_data(**{self.KEY_COLOR_TEMP: command_int_value(value)})
  405. else:
  406. print("%s: not yet implemented!" % command)
  407. else:
  408. print("Unknown command!")
  409. def power_off(self, device, key, value):
  410. self.data[self.KEY_STATE] = 'off'
  411. self.print_formatted(self, self.KEY_STATE, 'off')
  412. def power_on(self, device, key, value):
  413. if self.send_on_power_on:
  414. self.store_data(**{self.KEY_STATE: 'on'})
  415. else:
  416. self.data[self.KEY_STATE] = 'on'
  417. self.print_formatted(self, self.KEY_STATE, 'on')
  418. def print_formatted(self, device, key, value):
  419. if value is not None:
  420. color = COLOR_LIGHT_ACTIVE
  421. if key == self.KEY_STATE:
  422. print_light(COLOR_LIGHT_ACTIVE, value == "on", self.topic, "")
  423. self.print_formatted(device, self.KEY_BRIGHTNESS, self.data.get(self.KEY_BRIGHTNESS))
  424. self.print_formatted(device, self.KEY_COLOR_TEMP, self.data.get(self.KEY_COLOR_TEMP))
  425. elif key in [self.KEY_BRIGHTNESS, self.KEY_COLOR_TEMP]:
  426. perc_value = round(value * 100 / 256, 0) if key == self.KEY_BRIGHTNESS else round((value - 250) * 100 / 204, 0)
  427. print_percent(
  428. COLOR_LIGHT_PASSIVE if self.data.get(self.KEY_STATE) != "on" else COLOR_LIGHT_ACTIVE,
  429. 'B' if key == gui_light.KEY_BRIGHTNESS else 'C',
  430. perc_value,
  431. "%3d%%" % perc_value,
  432. self.topic,
  433. ""
  434. )
  435. class gui_light(tradfri_light):
  436. AUTOSEND = False
  437. #
  438. KEY_ENABLE = "enable"
  439. KEY_TIMER = "timer"
  440. KEY_LED_X = "led%d"
  441. def __init__(self, mqtt_client, topic, enable_state=True, enable_brightness=False, enable_color_temp=False):
  442. super().__init__(mqtt_client, topic, enable_state, enable_brightness, enable_color_temp)
  443. self.add_callback(self.KEY_ENABLE, self.print_formatted, None)
  444. self.add_callback(self.KEY_TIMER, self.print_formatted, None)
  445. for i in range(0, 10):
  446. self.add_callback(self.KEY_LED_X % i, self.print_formatted, None)
  447. self.led_names = {}
  448. #
  449. self.maxvalue = None
  450. def __init_data__(self, enable_state, enable_brightness, enable_color_temp):
  451. data = {}
  452. data[self.KEY_ENABLE] = False
  453. if enable_state:
  454. data[self.KEY_STATE] = False
  455. if enable_brightness:
  456. data[self.KEY_BRIGHTNESS] = 50
  457. if enable_color_temp:
  458. data[self.KEY_COLOR_TEMP] = 5
  459. data[self.KEY_TIMER] = '-'
  460. for i in range(0, 10):
  461. data[self.KEY_LED_X % i] = False
  462. self.store_data(**data)
  463. def __rx__(self, client, userdata, message):
  464. value = payload_filter(message.payload)
  465. if message.topic.startswith(self.topic) and message.topic.endswith('/set'):
  466. targetkey = message.topic.split('/')[-2]
  467. if targetkey in self.data.keys():
  468. self.store_data(**{targetkey: value})
  469. else:
  470. print("Unknown key %s in %s::%s" % (targetkey, message.topic, self.__class__.__name__))
  471. elif message.topic == self.topic + '/get':
  472. self.__tx__(None)
  473. def send(self, key, data):
  474. if data is not None:
  475. topic = self.topic + '/' + key
  476. self.mqtt_client.send(topic, json.dumps(data))
  477. def command(self, command):
  478. try:
  479. command, value = command.split(' ')
  480. except ValueError:
  481. value = None
  482. if command in self.capabilities():
  483. if command == self.STATE_COMMANDS[0]:
  484. self.print_formatted(self, self.KEY_STATE, self.data.get(self.KEY_STATE))
  485. elif command == self.STATE_COMMANDS[1]:
  486. self.send(self.KEY_STATE, not self.data.get(self.KEY_STATE))
  487. elif command == self.BRIGHTNESS_COMMANDS[0]:
  488. self.print_formatted(self, self.KEY_BRIGHTNESS, self.data.get(self.KEY_BRIGHTNESS))
  489. elif command == self.BRIGHTNESS_COMMANDS[1]:
  490. self.send(self.KEY_BRIGHTNESS, command_int_value(value))
  491. elif command == self.COLOR_TEMP_COMMANDS[0]:
  492. self.print_formatted(self, self.KEY_COLOR_TEMP, self.data.get(self.KEY_COLOR_TEMP))
  493. elif command == self.COLOR_TEMP_COMMANDS[1]:
  494. self.send(self.KEY_COLOR_TEMP, command_int_value(value))
  495. else:
  496. print("%s: not yet implemented!" % command)
  497. else:
  498. print("Unknown command!")
  499. def add_led_name(self, key, name):
  500. self.led_names[key] = name
  501. def print_formatted(self, device, key, value):
  502. if value is not None:
  503. device = " - ".join(self.topic.split('/')[1:])
  504. if key == self.KEY_STATE:
  505. print_switch(COLOR_GUI_ACTIVE, value, self.topic, "")
  506. elif key == self.KEY_ENABLE:
  507. self.print_formatted(device, self.KEY_BRIGHTNESS, self.data.get(self.KEY_BRIGHTNESS))
  508. self.print_formatted(device, self.KEY_COLOR_TEMP, self.data.get(self.KEY_COLOR_TEMP))
  509. elif key in [self.KEY_BRIGHTNESS, self.KEY_COLOR_TEMP]:
  510. perc_value = round(value * 10 if key == self.KEY_COLOR_TEMP else value, 0)
  511. print_percent(
  512. COLOR_GUI_PASSIVE if not self.data.get(self.KEY_ENABLE, False) else COLOR_GUI_ACTIVE,
  513. 'B' if key == self.KEY_BRIGHTNESS else 'C',
  514. perc_value,
  515. "%3d%%" % perc_value,
  516. self.topic,
  517. ""
  518. )
  519. elif key == self.KEY_TIMER:
  520. if value > 0:
  521. if self.maxvalue is None and value != 0:
  522. self.maxvalue = value
  523. disp_value = value
  524. try:
  525. perc = disp_value / self.maxvalue * 100
  526. except ZeroDivisionError:
  527. perc = 0
  528. else:
  529. disp_value = 0
  530. perc = 0
  531. self.maxvalue = None
  532. print_percent(COLOR_GUI_ACTIVE, 't', perc, '%3d%%' % perc, self.topic, '(%.1f)' % disp_value)
  533. elif key.startswith(self.KEY_LED_X[:-2]):
  534. print_light(COLOR_GUI_ACTIVE, value, self.topic, '(%s)' % self.led_names.get(key, key), True)
  535. class tradfri_button(base):
  536. KEY_ACTION = "action"
  537. #
  538. ACTION_TOGGLE = "toggle"
  539. ACTION_BRIGHTNESS_UP = "brightness_up_click"
  540. ACTION_BRIGHTNESS_DOWN = "brightness_down_click"
  541. ACTION_RIGHT = "arrow_right_click"
  542. ACTION_LEFT = "arrow_left_click"
  543. ACTION_BRIGHTNESS_UP_LONG = "brightness_up_hold"
  544. ACTION_BRIGHTNESS_DOWN_LONG = "brightness_down_hold"
  545. ACTION_RIGHT_LONG = "arrow_right_hold"
  546. ACTION_LEFT_LONG = "arrow_left_hold"
  547. #
  548. COMMANDS = [ACTION_TOGGLE, ACTION_LEFT, ACTION_RIGHT, ACTION_BRIGHTNESS_UP, ACTION_BRIGHTNESS_DOWN,
  549. ACTION_LEFT_LONG, ACTION_RIGHT_LONG, ACTION_BRIGHTNESS_UP_LONG, ACTION_BRIGHTNESS_DOWN_LONG]
  550. def __init__(self, mqtt_client, topic):
  551. super().__init__(mqtt_client, topic)
  552. def __rx__(self, client, userdata, message):
  553. pass
  554. def command(self, command):
  555. try:
  556. command, value = command.split(' ')
  557. except ValueError:
  558. value = None
  559. else:
  560. value = json.loads(value)
  561. if command in self.capabilities():
  562. action = self.COMMANDS[self.COMMANDS.index(command)]
  563. if self.COMMANDS.index(command) <= 4:
  564. self.mqtt_client.send(self.topic, json.dumps({self.KEY_ACTION: action}))
  565. elif self.COMMANDS.index(command) <= 8:
  566. self.mqtt_client.send(self.topic, json.dumps({self.KEY_ACTION: action}))
  567. time.sleep(value or 0.5)
  568. action = '_'.join(action.split('_')[:-1] + ['release'])
  569. self.mqtt_client.send(self.topic, json.dumps({self.KEY_ACTION: action}))
  570. class gui_led_array(base):
  571. AUTOSEND = False
  572. #
  573. KEY_LED_0 = "led0"
  574. KEY_LED_1 = "led1"
  575. KEY_LED_2 = "led2"
  576. KEY_LED_3 = "led3"
  577. KEY_LED_4 = "led4"
  578. KEY_LED_5 = "led5"
  579. KEY_LED_6 = "led6"
  580. KEY_LED_7 = "led7"
  581. KEY_LED_8 = "led8"
  582. KEY_LED_9 = "led9"
  583. def __init__(self, mqtt_client, topic, ):
  584. super().__init__(mqtt_client, topic)
  585. for i in range(0, 10):
  586. key = getattr(self, "KEY_LED_%d" % i)
  587. self.data[key] = False
  588. self.add_callback(key, self.print_formatted, None)
  589. def __rx__(self, client, userdata, message):
  590. value = payload_filter(message.payload)
  591. if message.topic.startswith(self.topic) and message.topic.endswith('/set'):
  592. targetkey = message.topic.split('/')[-2]
  593. if targetkey in self.data.keys():
  594. self.store_data(**{targetkey: value})
  595. else:
  596. print("Unknown key %s in %s" % (targetkey, self.__class__.__name__))
  597. def print_formatted(self, device, key, value):
  598. print_light(COLOR_GUI_ACTIVE, value, self.topic, '(%s)' % self.names.get(key, key), True)
  599. class remote(base):
  600. def __rx__(self, client, userdata, message):
  601. if message.topic == self.topic + "/VOLUP":
  602. if payload_filter(message.payload):
  603. icon = u'\u1403'
  604. else:
  605. icon = u'\u25a1'
  606. elif message.topic == self.topic + "/VOLDOWN":
  607. if payload_filter(message.payload):
  608. icon = u'\u1401'
  609. else:
  610. icon = u'\u25a1'
  611. else:
  612. return
  613. devicename = ' - '.join(self.topic.split('/')[1:-1])
  614. print(COLOR_REMOTE + 10 * ' ' + icon + 6 * ' ' + devicename + colored.attr("reset"))
  615. class brennenstuhl_heating_valve(base):
  616. TEMP_RANGE = [10, 30]
  617. #
  618. KEY_TEMPERATURE_SETPOINT = "current_heating_setpoint"
  619. KEY_TEMPERATURE = "local_temperature"
  620. #
  621. COMMANDS = [
  622. "get_temperature_setpoint", "set_temperature_setpoint",
  623. ]
  624. def __init__(self, mqtt_client, topic):
  625. super().__init__(mqtt_client, topic)
  626. self.store_data(**{
  627. self.KEY_TEMPERATURE_SETPOINT: 20,
  628. self.KEY_TEMPERATURE: 20.7,
  629. })
  630. self.add_callback(self.KEY_TEMPERATURE_SETPOINT, self.print_formatted, None)
  631. def __rx__(self, client, userdata, message):
  632. if message.topic.startswith(self.topic) and message.topic.endswith("/set"):
  633. payload = payload_filter(message.payload)
  634. self.store_data(**payload)
  635. def command(self, command):
  636. try:
  637. command, value = command.split(' ')
  638. except ValueError:
  639. value = None
  640. if command in self.COMMANDS:
  641. if command == self.COMMANDS[0]:
  642. self.print_formatted(self, self.KEY_TEMPERATURE_SETPOINT, self.data.get(self.KEY_TEMPERATURE_SETPOINT))
  643. elif command == self.COMMANDS[1]:
  644. self.store_data(**{self.KEY_TEMPERATURE_SETPOINT: command_float_value(value)})
  645. def print_formatted(self, device, key, value):
  646. devicename = ' - '.join(self.topic.split('/')[1:])
  647. if key == self.KEY_TEMPERATURE_SETPOINT:
  648. perc = 100 * (value - self.TEMP_RANGE[0]) / (self.TEMP_RANGE[1] - self.TEMP_RANGE[0])
  649. perc = 100 if perc > 100 else perc
  650. perc = 0 if perc < 0 else perc
  651. print_percent(COLOR_HEATING_VALVE, '\u03d1', perc, "%4.1f°C" % value, self.topic, "")
  652. class gui_heating_valve(base):
  653. AUTOSEND = False
  654. #
  655. TEMP_RANGE = [10, 30]
  656. #
  657. KEY_TIMER = "timer"
  658. KEY_TEMPERATURE = "temperature"
  659. KEY_SETPOINT_TEMP = "setpoint_temp"
  660. KEY_SETPOINT_TO_DEFAULT = "setpoint_to_default"
  661. KEY_BOOST = 'boost'
  662. KEY_AWAY = "away"
  663. KEY_SUMMER = "summer"
  664. KEY_ENABLE = "enable"
  665. #
  666. COMMANDS = [
  667. "get_temperature",
  668. "get_temperature_setpoint", "set_temperature_setpoint",
  669. "trigger_boost", "trigger_setpoint_to_default",
  670. "toggle_away", "toggle_summer",
  671. ]
  672. def __init__(self, mqtt_client, topic):
  673. super().__init__(mqtt_client, topic)
  674. self.add_callback(self.KEY_SETPOINT_TEMP, self.print_formatted, None)
  675. self.add_callback(self.KEY_TIMER, self.print_formatted, None)
  676. self.add_callback(self.KEY_AWAY, self.print_formatted, None)
  677. self.add_callback(self.KEY_SUMMER, self.print_formatted, None)
  678. #
  679. self.store_data(**{
  680. self.KEY_TEMPERATURE: 20.7,
  681. self.KEY_SETPOINT_TEMP: 20,
  682. self.KEY_TIMER: 0,
  683. self.KEY_AWAY: False,
  684. self.KEY_SUMMER: False,
  685. self.KEY_ENABLE: True
  686. })
  687. def __rx__(self, client, userdata, message):
  688. value = payload_filter(message.payload)
  689. if message.topic.startswith(self.topic) and message.topic.endswith('/set'):
  690. targetkey = message.topic.split('/')[-2]
  691. if targetkey in self.data.keys():
  692. self.store_data(**{targetkey: value})
  693. else:
  694. print("Unknown key %s in %s::%s" % (targetkey, message.topic, self.__class__.__name__))
  695. elif message.topic == self.topic + '/get':
  696. self.__tx__(None)
  697. def send(self, key, data):
  698. if data is not None:
  699. topic = self.topic + '/' + key
  700. self.mqtt_client.send(topic, json.dumps(data))
  701. def command(self, command):
  702. try:
  703. command, value = command.split(' ')
  704. except ValueError:
  705. value = None
  706. if command in self.COMMANDS:
  707. if command == self.COMMANDS[0]:
  708. self.print_formatted(self, self.KEY_TEMPERATURE, self.data.get(self.KEY_TEMPERATURE))
  709. elif command == self.COMMANDS[1]:
  710. self.print_formatted(self, self.KEY_SETPOINT_TEMP, self.data.get(self.KEY_SETPOINT_TEMP))
  711. elif command == self.COMMANDS[2]:
  712. self.send(self.KEY_SETPOINT_TEMP, command_float_value(value))
  713. elif command == self.COMMANDS[3]:
  714. self.send(self.KEY_BOOST, True)
  715. elif command == self.COMMANDS[4]:
  716. self.send(self.KEY_SETPOINT_TO_DEFAULT, True)
  717. elif command == self.COMMANDS[5]:
  718. self.send(self.KEY_AWAY, not self.data.get(self.KEY_AWAY))
  719. elif command == self.COMMANDS[6]:
  720. self.send(self.KEY_SUMMER, not self.data.get(self.KEY_SUMMER))
  721. def print_formatted(self, device, key, value):
  722. devicename = ' - '.join(self.topic.split('/')[1:])
  723. if key == self.KEY_TIMER:
  724. value /= 60
  725. try:
  726. perc = 100 * value / 60
  727. except TypeError:
  728. value = 0
  729. perc = 0
  730. print_percent(COLOR_GUI_ACTIVE, 't', perc, "%4.1fmin" % value, self.topic, "(Timer)")
  731. elif key == self.KEY_TEMPERATURE:
  732. perc = 100 * (value - self.TEMP_RANGE[0]) / (self.TEMP_RANGE[1] - self.TEMP_RANGE[0])
  733. perc = 100 if perc > 100 else perc
  734. perc = 0 if perc < 0 else perc
  735. print_percent(COLOR_GUI_ACTIVE, '\u03d1', perc, "%4.1f°C" % value, self.topic, "(Temperature)")
  736. elif key == self.KEY_SETPOINT_TEMP:
  737. perc = 100 * (value - self.TEMP_RANGE[0]) / (self.TEMP_RANGE[1] - self.TEMP_RANGE[0])
  738. perc = 100 if perc > 100 else perc
  739. perc = 0 if perc < 0 else perc
  740. print_percent(COLOR_GUI_ACTIVE if self.data.get(self.KEY_ENABLE) else COLOR_GUI_PASSIVE,
  741. '\u03d1', perc, "%4.1f°C" % value, self.topic, "(Setpoint)")
  742. elif key == self.KEY_AWAY:
  743. print_switch(COLOR_GUI_ACTIVE, value, self.topic, "(Away Mode)")
  744. elif key == self.KEY_SUMMER:
  745. print_switch(COLOR_GUI_ACTIVE, value, self.topic, "(Summer Mode)")