Test Smart Brain implementation
您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

devices.py 38KB

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