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.

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