Test Smart Brain implementation
Du kan inte välja fler än 25 ämnen Ämnen måste starta med en bokstav eller siffra, kan innehålla bindestreck ('-') och vara max 35 tecken långa.

devices.py 34KB

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