Test Smart Brain implementation
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.

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