Smarthome Functionen
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

devices.py 34KB

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