Smarthome Functionen
Ви не можете вибрати більше 25 тем Теми мають розпочинатися з літери або цифри, можуть містити дефіси (-) і не повинні перевищувати 35 символів.

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840
  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. KEY_TIMER = "timer"
  443. KEY_LED_X = "led%d"
  444. def __init__(self, mqtt_client, topic, enable_state=True, enable_brightness=False, enable_color_temp=False):
  445. super().__init__(mqtt_client, topic, enable_state, enable_brightness, enable_color_temp)
  446. self.add_callback(self.KEY_ENABLE, self.print_formatted, None)
  447. self.add_callback(self.KEY_TIMER, self.print_formatted, None)
  448. for i in range(0, 10):
  449. self.add_callback(self.KEY_LED_X % i, self.print_formatted, None)
  450. self.led_names = {}
  451. #
  452. self.maxvalue = None
  453. self.last_printed = None
  454. def __init_data__(self, enable_state, enable_brightness, enable_color_temp):
  455. data = {}
  456. data[self.KEY_ENABLE] = False
  457. if enable_state:
  458. data[self.KEY_STATE] = False
  459. if enable_brightness:
  460. data[self.KEY_BRIGHTNESS] = 50
  461. if enable_color_temp:
  462. data[self.KEY_COLOR_TEMP] = 5
  463. data[self.KEY_TIMER] = '-'
  464. for i in range(0, 10):
  465. data[self.KEY_LED_X % i] = False
  466. self.store_data(**data)
  467. def __rx__(self, client, userdata, message):
  468. value = payload_filter(message.payload)
  469. if message.topic.startswith(self.topic) and message.topic.endswith('/set'):
  470. targetkey = message.topic.split('/')[-2]
  471. if targetkey in self.data.keys():
  472. self.store_data(**{targetkey: value})
  473. else:
  474. print("Unknown key %s in %s::%s" % (targetkey, message.topic, self.__class__.__name__))
  475. elif message.topic == self.topic + '/get':
  476. self.__tx__(None)
  477. def send(self, key, data):
  478. if data is not None:
  479. topic = self.topic + '/' + key
  480. self.mqtt_client.send(topic, json.dumps(data))
  481. def command(self, command):
  482. try:
  483. command, value = command.split(' ')
  484. except ValueError:
  485. value = None
  486. if command in self.capabilities():
  487. if command == self.STATE_COMMANDS[0]:
  488. self.print_formatted(self, self.KEY_STATE, self.data.get(self.KEY_STATE))
  489. elif command == self.STATE_COMMANDS[1]:
  490. self.send(self.KEY_STATE, not self.data.get(self.KEY_STATE))
  491. elif command == self.BRIGHTNESS_COMMANDS[0]:
  492. self.print_formatted(self, self.KEY_BRIGHTNESS, self.data.get(self.KEY_BRIGHTNESS))
  493. elif command == self.BRIGHTNESS_COMMANDS[1]:
  494. self.send(self.KEY_BRIGHTNESS, command_int_value(value))
  495. elif command == self.COLOR_TEMP_COMMANDS[0]:
  496. self.print_formatted(self, self.KEY_COLOR_TEMP, self.data.get(self.KEY_COLOR_TEMP))
  497. elif command == self.COLOR_TEMP_COMMANDS[1]:
  498. self.send(self.KEY_COLOR_TEMP, command_int_value(value))
  499. else:
  500. print("%s: not yet implemented!" % command)
  501. else:
  502. print("Unknown command!")
  503. def add_led_name(self, key, name):
  504. self.led_names[key] = name
  505. def print_formatted(self, device, key, value):
  506. if value is not None:
  507. color = COLOR_GUI_ACTIVE
  508. device = " - ".join(self.topic.split('/')[1:])
  509. if key == self.KEY_STATE:
  510. if value == True:
  511. print(color + 10 * ' ' + u'\u25a0' + 9 * ' ' + device + colored.attr("reset"))
  512. else:
  513. print(color + 10 * ' ' + u'\u25a1' + 9 * ' ' + device + colored.attr("reset"))
  514. elif key == self.KEY_ENABLE:
  515. self.print_formatted(device, self.KEY_BRIGHTNESS, self.data.get(self.KEY_BRIGHTNESS))
  516. self.print_formatted(device, self.KEY_COLOR_TEMP, self.data.get(self.KEY_COLOR_TEMP))
  517. elif key in [self.KEY_BRIGHTNESS, self.KEY_COLOR_TEMP]:
  518. if not self.data.get(self.KEY_ENABLE, False):
  519. color = COLOR_GUI_PASSIVE
  520. value = round(value * 10 if key == self.KEY_COLOR_TEMP else value, 0)
  521. sys.stdout.write(color)
  522. sys.stdout.write('B' if key == self.KEY_BRIGHTNESS else 'C')
  523. sys.stdout.write(percent_bar(value))
  524. print("%3d%%" % value + 5 * " " + device + colored.attr("reset"))
  525. elif key == self.KEY_TIMER:
  526. if isinstance(value, (int, float, complex)) and not isinstance(value, bool):
  527. if self.maxvalue is None:
  528. self.maxvalue = value
  529. disp_value = value
  530. perc = disp_value / self.maxvalue * 100
  531. else:
  532. disp_value = 0
  533. perc = 0
  534. self.maxvalue = None
  535. self.last_printed = None
  536. if self.last_printed is None or abs(self.last_printed - perc) >= 4.95:
  537. print(color + 't' + percent_bar(perc) + '%3d%%' % perc + 5 * ' ' + device + ' (%.1f)' % disp_value + colored.attr('reset'))
  538. self.last_printed = perc
  539. elif key.startswith(self.KEY_LED_X[:-2]):
  540. led = green_led() if value else grey_led()
  541. ledname = '(%s)' % self.led_names.get(key, key)
  542. devicename = ' - '.join(self.topic.split('/')[1:])
  543. print(10 * ' ' + led + 9 * ' ' + COLOR_GUI_ACTIVE + devicename + ' ' + ledname + colored.attr("reset"))
  544. class tradfri_button(base):
  545. KEY_ACTION = "action"
  546. #
  547. ACTION_TOGGLE = "toggle"
  548. ACTION_BRIGHTNESS_UP = "brightness_up_click"
  549. ACTION_BRIGHTNESS_DOWN = "brightness_down_click"
  550. ACTION_RIGHT = "arrow_right_click"
  551. ACTION_LEFT = "arrow_left_click"
  552. ACTION_BRIGHTNESS_UP_LONG = "brightness_up_hold"
  553. ACTION_BRIGHTNESS_DOWN_LONG = "brightness_down_hold"
  554. ACTION_RIGHT_LONG = "arrow_right_hold"
  555. ACTION_LEFT_LONG = "arrow_left_hold"
  556. #
  557. COMMANDS = [ACTION_TOGGLE, ACTION_LEFT, ACTION_RIGHT, ACTION_BRIGHTNESS_UP, ACTION_BRIGHTNESS_DOWN,
  558. ACTION_LEFT_LONG, ACTION_RIGHT_LONG, ACTION_BRIGHTNESS_UP_LONG, ACTION_BRIGHTNESS_DOWN_LONG]
  559. def __init__(self, mqtt_client, topic):
  560. super().__init__(mqtt_client, topic)
  561. def __rx__(self, client, userdata, message):
  562. pass
  563. def command(self, command):
  564. try:
  565. command, value = command.split(' ')
  566. except ValueError:
  567. value = None
  568. else:
  569. value = json.loads(value)
  570. if command in self.capabilities():
  571. action = self.COMMANDS[self.COMMANDS.index(command)]
  572. if self.COMMANDS.index(command) <= 4:
  573. self.mqtt_client.send(self.topic, json.dumps({self.KEY_ACTION: action}))
  574. elif self.COMMANDS.index(command) <= 8:
  575. self.mqtt_client.send(self.topic, json.dumps({self.KEY_ACTION: action}))
  576. time.sleep(value or 0.5)
  577. action = '_'.join(action.split('_')[:-1] + ['release'])
  578. self.mqtt_client.send(self.topic, json.dumps({self.KEY_ACTION: action}))
  579. class gui_led_array(base):
  580. AUTOSEND = False
  581. #
  582. KEY_LED_0 = "led0"
  583. KEY_LED_1 = "led1"
  584. KEY_LED_2 = "led2"
  585. KEY_LED_3 = "led3"
  586. KEY_LED_4 = "led4"
  587. KEY_LED_5 = "led5"
  588. KEY_LED_6 = "led6"
  589. KEY_LED_7 = "led7"
  590. KEY_LED_8 = "led8"
  591. KEY_LED_9 = "led9"
  592. def __init__(self, mqtt_client, topic, ):
  593. super().__init__(mqtt_client, topic)
  594. for i in range(0, 10):
  595. key = getattr(self, "KEY_LED_%d" % i)
  596. self.data[key] = False
  597. self.add_callback(key, self.print_formatted, None)
  598. def __rx__(self, client, userdata, message):
  599. value = payload_filter(message.payload)
  600. if message.topic.startswith(self.topic) and message.topic.endswith('/set'):
  601. targetkey = message.topic.split('/')[-2]
  602. if targetkey in self.data.keys():
  603. self.store_data(**{targetkey: value})
  604. else:
  605. print("Unknown key %s in %s" % (targetkey, self.__class__.__name__))
  606. def print_formatted(self, device, key, value):
  607. led = green_led() if value else grey_led()
  608. channel = '(%s)' % self.names.get(key, key)
  609. devicename = ' - '.join(self.topic.split('/')[1:])
  610. print(10 * ' ' + led + 9 * ' ' + COLOR_GUI_ACTIVE + devicename + ' ' + channel + colored.attr("reset"))
  611. class remote(base):
  612. def __rx__(self, client, userdata, message):
  613. if message.topic == self.topic + "/VOLUP":
  614. if payload_filter(message.payload):
  615. icon = u'\u1403'
  616. else:
  617. icon = u'\u25a1'
  618. elif message.topic == self.topic + "/VOLDOWN":
  619. if payload_filter(message.payload):
  620. icon = u'\u1401'
  621. else:
  622. icon = u'\u25a1'
  623. else:
  624. return
  625. devicename = ' - '.join(self.topic.split('/')[1:-1])
  626. print(COLOR_REMOTE + 10 * ' ' + icon + 6 * ' ' + devicename + colored.attr("reset"))
  627. class brennenstuhl_radiator_valve(base):
  628. TEMP_RANGE = [10, 30]
  629. #
  630. KEY_TEMPERATURE_SETPOINT = "current_heating_setpoint"
  631. KEY_TEMPERATURE = "local_temperature"
  632. #
  633. COMMANDS = [
  634. "get_temperature_setpoint", "set_temperature_setpoint",
  635. ]
  636. def __init__(self, mqtt_client, topic):
  637. super().__init__(mqtt_client, topic)
  638. self.store_data(**{
  639. self.KEY_TEMPERATURE_SETPOINT: 20,
  640. self.KEY_TEMPERATURE: 20.7,
  641. })
  642. self.add_callback(self.KEY_TEMPERATURE_SETPOINT, self.print_formatted, None)
  643. def __rx__(self, client, userdata, message):
  644. if message.topic.startswith(self.topic) and message.topic.endswith("/set"):
  645. payload = payload_filter(message.payload)
  646. self.store_data(**payload)
  647. def command(self, command):
  648. try:
  649. command, value = command.split(' ')
  650. except ValueError:
  651. value = None
  652. if command in self.COMMANDS:
  653. if command == self.COMMANDS[0]:
  654. self.print_formatted(self, self.KEY_TEMPERATURE_SETPOINT, self.data.get(self.KEY_TEMPERATURE_SETPOINT))
  655. elif command == self.COMMANDS[1]:
  656. self.store_data(**{self.KEY_TEMPERATURE_SETPOINT: command_float_value(value)})
  657. def print_formatted(self, device, key, value):
  658. devicename = ' - '.join(self.topic.split('/')[1:])
  659. if key == self.KEY_TEMPERATURE_SETPOINT:
  660. perc = 100 * (value - self.TEMP_RANGE[0]) / (self.TEMP_RANGE[1] - self.TEMP_RANGE[0])
  661. perc = 100 if perc > 100 else perc
  662. perc = 0 if perc < 0 else perc
  663. sys.stdout.write(COLOR_RADIATOR_VALVE + '\u03d1' + percent_bar(perc))
  664. sys.stdout.write("%4.1f°C" % value + 3 * " ")
  665. print(devicename + colored.attr("reset"))
  666. class gui_radiator_valve(base):
  667. AUTOSEND = False
  668. #
  669. TEMP_RANGE = [10, 30]
  670. #
  671. KEY_TIMER = "timer"
  672. KEY_TEMPERATURE = "temperature"
  673. KEY_SETPOINT_TEMP = "setpoint_temp"
  674. KEY_SETPOINT_TO_DEFAULT = "setpoint_to_default"
  675. KEY_BOOST = 'boost'
  676. #
  677. COMMANDS = [
  678. "get_temperature",
  679. "get_temperature_setpoint", "set_temperature_setpoint",
  680. "trigger_boost", "trigger_setpoint_to_default"
  681. ]
  682. def __init__(self, mqtt_client, topic):
  683. super().__init__(mqtt_client, topic)
  684. self.add_callback(self.KEY_SETPOINT_TEMP, self.print_formatted, None)
  685. self.add_callback(self.KEY_TIMER, self.print_formatted, None)
  686. #
  687. self.store_data(**{
  688. self.KEY_TEMPERATURE: 20.7,
  689. self.KEY_SETPOINT_TEMP: 20,
  690. self.KEY_TIMER: 0,
  691. })
  692. def __rx__(self, client, userdata, message):
  693. value = payload_filter(message.payload)
  694. if message.topic.startswith(self.topic) and message.topic.endswith('/set'):
  695. targetkey = message.topic.split('/')[-2]
  696. if targetkey in self.data.keys():
  697. self.store_data(**{targetkey: value})
  698. else:
  699. print("Unknown key %s in %s::%s" % (targetkey, message.topic, self.__class__.__name__))
  700. elif message.topic == self.topic + '/get':
  701. self.__tx__(None)
  702. def send(self, key, data):
  703. if data is not None:
  704. topic = self.topic + '/' + key
  705. self.mqtt_client.send(topic, json.dumps(data))
  706. def command(self, command):
  707. try:
  708. command, value = command.split(' ')
  709. except ValueError:
  710. value = None
  711. if command in self.COMMANDS:
  712. if command == self.COMMANDS[0]:
  713. self.print_formatted(self, self.KEY_TEMPERATURE, self.data.get(self.KEY_TEMPERATURE))
  714. elif command == self.COMMANDS[1]:
  715. self.print_formatted(self, self.KEY_SETPOINT_TEMP, self.data.get(self.KEY_SETPOINT_TEMP))
  716. elif command == self.COMMANDS[2]:
  717. self.send(self.KEY_SETPOINT_TEMP, command_float_value(value))
  718. elif command == self.COMMANDS[3]:
  719. self.send(self.KEY_BOOST, True)
  720. elif command == self.COMMANDS[4]:
  721. self.send(self.KEY_SETPOINT_TO_DEFAULT, True)
  722. def print_formatted(self, device, key, value):
  723. devicename = ' - '.join(self.topic.split('/')[1:])
  724. if key in [self.KEY_TEMPERATURE, self.KEY_SETPOINT_TEMP, self.KEY_TIMER]:
  725. if key in [self.KEY_TEMPERATURE, self.KEY_SETPOINT_TEMP]:
  726. perc = 100 * (value - self.TEMP_RANGE[0]) / (self.TEMP_RANGE[1] - self.TEMP_RANGE[0])
  727. info = " (Temperature)" if key == self.KEY_TEMPERATURE else " (Setpoint)"
  728. else:
  729. try:
  730. perc = 100 * value / 60
  731. except TypeError:
  732. value = 0
  733. perc = 0
  734. info = " (Timer)"
  735. perc = 100 if perc > 100 else perc
  736. perc = 0 if perc < 0 else perc
  737. sys.stdout.write(COLOR_GUI_ACTIVE)
  738. if key == self.KEY_TIMER:
  739. sys.stdout.write('T' + percent_bar(perc) + "%4.1fmin" % value + 2 * " ")
  740. else:
  741. sys.stdout.write('\u03d1' + percent_bar(perc) + "%4.1f°C" % value + 3 * " ")
  742. print(devicename + info + colored.attr("reset"))