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.

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