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

devices.py 23KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560
  1. import colored
  2. import json
  3. import sys
  4. import time
  5. # TODO: implement my powerplug
  6. COLOR_GUI_ACTIVE = colored.fg("light_blue")
  7. COLOR_GUI_PASSIVE = COLOR_GUI_ACTIVE + colored.attr("dim")
  8. COLOR_SHELLY_1 = colored.fg("light_magenta")
  9. COLOR_SHELLY_2 = colored.fg("light_cyan")
  10. COLOR_LIGHT_ACTIVE = colored.fg("yellow")
  11. COLOR_LIGHT_PASSIVE = COLOR_LIGHT_ACTIVE + colored.attr("dim")
  12. COLOR_MOTION_SENSOR = colored.fg("red")
  13. def payload_filter(payload):
  14. try:
  15. return json.loads(payload)
  16. except json.decoder.JSONDecodeError:
  17. return payload.decode("utf-8")
  18. def percent_print(value):
  19. for i in range(0, 10):
  20. if (value - 5) > 10*i:
  21. sys.stdout.write(u"\u25ac")
  22. else:
  23. sys.stdout.write(u"\u25ad")
  24. def command_int_value(value):
  25. try:
  26. return int(value)
  27. except TypeError:
  28. print("You need to give a integer parameter not '%s'" % str(value))
  29. class base(object):
  30. AUTOSEND = True
  31. COMMANDS = []
  32. def __init__(self, mqtt_client, topic):
  33. self.mqtt_client = mqtt_client
  34. self.topic = topic
  35. #
  36. self.data = {}
  37. self.callbacks = {}
  38. self.commands = self.COMMANDS[:]
  39. #
  40. self.mqtt_client.add_callback(self.topic, self.__rx__)
  41. self.mqtt_client.add_callback(self.topic + '/#', self.__rx__)
  42. def add_callback(self, key, callback, value):
  43. if self.callbacks.get(key) is None:
  44. self.callbacks[key] = []
  45. self.callbacks[key].append((callback, value))
  46. def capabilities(self):
  47. return self.commands
  48. def store_data(self, *args, **kwargs):
  49. keys_changed = []
  50. for key in kwargs:
  51. if kwargs[key] is not None and kwargs[key] != self.data.get(key):
  52. keys_changed.append(key)
  53. self.data[key] = kwargs[key]
  54. for callback, value in self.callbacks.get(key, [(None, None)]):
  55. if callback is not None and (value is None or value == kwargs[key]):
  56. callback(self, key, kwargs[key])
  57. if self.AUTOSEND and len(keys_changed) > 0:
  58. self.__tx__(keys_changed)
  59. def __tx__(self, keys_changed):
  60. self.mqtt_client.send(self.topic, json.dumps(self.data))
  61. def __rx__(self, client, userdata, message):
  62. print("%s: __rx__ not handled!" % self.__class__.__name__)
  63. class shelly(base):
  64. KEY_OUTPUT_0 = "relay/0"
  65. KEY_OUTPUT_1 = "relay/1"
  66. #
  67. COMMANDS = [
  68. "get_relay_0", "set_relay_0", "unset_relay_0",
  69. "get_relay_1", "set_relay_1", "unset_relay_1",
  70. ]
  71. def __init__(self, mqtt_client, topic):
  72. super().__init__(mqtt_client, topic)
  73. #
  74. self.store_data(**{self.KEY_OUTPUT_0: "off", self.KEY_OUTPUT_1: "off"})
  75. self.add_callback(self.KEY_OUTPUT_0, self.print_formatted, None)
  76. def __rx__(self, client, userdata, message):
  77. value = payload_filter(message.payload)
  78. if message.topic == self.topic + "/relay/0/command":
  79. if value in ['on', 'off']:
  80. self.store_data(**{self.KEY_OUTPUT_0: value})
  81. elif value == 'toggle':
  82. self.store_data(**{self.KEY_OUTPUT_0: 'on' if self.data.get(self.KEY_OUTPUT_0) == 'off' else 'off'})
  83. elif message.topic == self.topic + "/relay/1/command":
  84. if value in ['on', 'off']:
  85. self.store_data(**{self.KEY_OUTPUT_1: value})
  86. elif value == 'toggle':
  87. self.store_data(**{self.KEY_OUTPUT_1: 'on' if self.data.get(self.KEY_OUTPUT_1) == 'off' else 'off'})
  88. def __tx__(self, keys_changed):
  89. for key in keys_changed:
  90. self.mqtt_client.send(self.topic + '/' + key, self.data.get(key))
  91. def command(self, command):
  92. if command in self.COMMANDS:
  93. if command == self.COMMANDS[0]:
  94. self.print_formatted(self, self.KEY_OUTPUT_0, self.data.get(self.KEY_OUTPUT_0))
  95. elif command == self.COMMANDS[1]:
  96. self.store_data(**{self.KEY_OUTPUT_0: "on"})
  97. elif command == self.COMMANDS[2]:
  98. self.store_data(**{self.KEY_OUTPUT_0: "off"})
  99. elif command == self.COMMANDS[3]:
  100. self.print_formatted(self, self.KEY_OUTPUT_1, self.data.get(self.KEY_OUTPUT_1))
  101. elif command == self.COMMANDS[4]:
  102. self.store_data(**{self.KEY_OUTPUT_1: "on"})
  103. elif command == self.COMMANDS[5]:
  104. self.store_data(**{self.KEY_OUTPUT_1: "off"})
  105. else:
  106. print("%s: not yet implemented!" % command)
  107. else:
  108. print("Unknown command!")
  109. def print_formatted(self, device, key, value):
  110. if value is not None:
  111. if key == shelly.KEY_OUTPUT_0:
  112. color = COLOR_SHELLY_1
  113. else:
  114. color = COLOR_SHELLY_2
  115. if value == "on":
  116. print(color + 10 * ' ' + u'\u2b24' + 6 * ' ' + " - ".join(self.topic.split('/')[1:]) + colored.attr("reset"))
  117. else:
  118. print(color + 10 * ' ' + u'\u25ef' + 6 * ' ' + " - ".join(self.topic.split('/')[1:]) + colored.attr("reset"))
  119. class my_powerplug(base):
  120. COMMANDS = [
  121. "get_state", "set_state", "unset_state",
  122. ]
  123. def __init__(self, mqtt_client, topic, names=[]):
  124. super().__init__(mqtt_client, topic)
  125. #
  126. self.names = []
  127. #
  128. for i in range(0, 4):
  129. self.data[str(i)] = False
  130. try:
  131. self.names.append(names[i])
  132. except IndexError:
  133. self.names.append("Channel %d" % (i + 1))
  134. self.add_callback(str(i), self.print_formatted, None)
  135. def __rx__(self, client, userdata, message):
  136. if message.topic.startswith(self.topic + '/output/') and message.topic.endswith('/set'):
  137. channel = int(message.topic.split('/')[-2]) - 1
  138. payload = payload_filter(message.payload)
  139. if payload == "toggle":
  140. payload = not self.data.get(str(channel))
  141. self.store_data(**{str(channel): payload})
  142. def __tx__(self, keys_changed):
  143. for key in keys_changed:
  144. self.mqtt_client.send(self.topic + "/output/" + str(int(key) + 1), json.dumps(self.data.get(key)))
  145. def command(self, command):
  146. if command in self.COMMANDS:
  147. if command == self.COMMANDS[0]:
  148. self.print_formatted(self, self.KEY_OUTPUT_0, self.data.get(self.KEY_OUTPUT_0))
  149. elif command == self.COMMANDS[1]:
  150. self.store_data(**{self.KEY_OUTPUT_0: 'on'})
  151. elif command == self.COMMANDS[2]:
  152. self.store_data(**{self.KEY_OUTPUT_0: 'off'})
  153. else:
  154. print("%s: not yet implemented!" % command)
  155. else:
  156. print("Unknown command!")
  157. def print_formatted(self, device, key, value):
  158. if value is not None:
  159. if value:
  160. print(COLOR_SHELLY_1 + 10 * ' ' + u'\u2b24' + 6 * ' ' + " - ".join(self.topic.split('/')
  161. [1:]) + " (%s)" % self.names[int(key)] + colored.attr("reset"))
  162. else:
  163. print(COLOR_SHELLY_1 + 10 * ' ' + u'\u25ef' + 6 * ' ' + " - ".join(self.topic.split('/')
  164. [1:]) + " (%s)" % self.names[int(key)] + colored.attr("reset"))
  165. class silvercrest_powerplug(base):
  166. KEY_OUTPUT_0 = "state"
  167. #
  168. COMMANDS = [
  169. "get_state", "set_state", "unset_state",
  170. ]
  171. def __init__(self, mqtt_client, topic):
  172. super().__init__(mqtt_client, topic)
  173. self.add_callback(self.KEY_OUTPUT_0, self.print_formatted, None)
  174. #
  175. self.store_data(**{self.KEY_OUTPUT_0: "off"})
  176. def __rx__(self, client, userdata, message):
  177. if message.topic == self.topic + '/set':
  178. STATES = ["on", "off", "toggle"]
  179. #
  180. state = json.loads(message.payload).get('state').lower()
  181. if state in STATES:
  182. if state == STATES[0]:
  183. self.store_data(**{self.KEY_OUTPUT_0: 'on'})
  184. elif state == STATES[1]:
  185. self.store_data(**{self.KEY_OUTPUT_0: 'off'})
  186. else:
  187. self.store_data(**{self.KEY_OUTPUT_0: "off" if self.data.get(self.KEY_OUTPUT_0) == "on" else "on"})
  188. def command(self, command):
  189. if command in self.COMMANDS:
  190. if command == self.COMMANDS[0]:
  191. self.print_formatted(self, self.KEY_OUTPUT_0, self.data.get(self.KEY_OUTPUT_0))
  192. elif command == self.COMMANDS[1]:
  193. self.store_data(**{self.KEY_OUTPUT_0: 'on'})
  194. elif command == self.COMMANDS[2]:
  195. self.store_data(**{self.KEY_OUTPUT_0: 'off'})
  196. else:
  197. print("%s: not yet implemented!" % command)
  198. else:
  199. print("Unknown command!")
  200. def print_formatted(self, device, key, value):
  201. if value is not None:
  202. if value == "on":
  203. print(COLOR_SHELLY_1 + 10 * ' ' + u'\u2b24' + 6 * ' ' + " - ".join(self.topic.split('/')[1:]) + colored.attr("reset"))
  204. else:
  205. print(COLOR_SHELLY_1 + 10 * ' ' + u'\u25ef' + 6 * ' ' + " - ".join(self.topic.split('/')[1:]) + colored.attr("reset"))
  206. class silvercrest_motion_sensor(base):
  207. KEY_OCCUPANCY = "occupancy"
  208. COMMANDS = ['motion']
  209. def __init__(self, mqtt_client, topic):
  210. super().__init__(mqtt_client, topic)
  211. self.data[self.KEY_OCCUPANCY] = False
  212. self.add_callback(self.KEY_OCCUPANCY, self.print_formatted, None)
  213. def __rx__(self, client, userdata, message):
  214. pass
  215. def command(self, command):
  216. try:
  217. command, value = command.split(' ')
  218. except ValueError:
  219. value = None
  220. else:
  221. value = json.loads(value)
  222. if command == self.COMMANDS[0]:
  223. self.store_data(**{self.KEY_OCCUPANCY: True})
  224. time.sleep(value or 10)
  225. self.store_data(**{self.KEY_OCCUPANCY: False})
  226. def print_formatted(self, device, key, value):
  227. if value is not None:
  228. if value:
  229. print(COLOR_MOTION_SENSOR + 10 * ' ' + u'\u2b24' + 6 * ' ' + " - ".join(self.topic.split('/')[1:]) + colored.attr("reset"))
  230. else:
  231. print(COLOR_MOTION_SENSOR + 10 * ' ' + u'\u25ef' + 6 * ' ' + " - ".join(self.topic.split('/')[1:]) + colored.attr("reset"))
  232. class tradfri_light(base):
  233. KEY_STATE = "state"
  234. KEY_BRIGHTNESS = "brightness"
  235. KEY_COLOR_TEMP = "color_temp"
  236. KEY_BRIGHTNESS_MOVE = "brightness_move"
  237. #
  238. STATE_COMMANDS = ("get_state", "change_state", )
  239. BRIGHTNESS_COMMANDS = ("get_brightness", "set_brightness",)
  240. COLOR_TEMP_COMMANDS = ("get_color_temp", "set_color_temp",)
  241. def __init__(self, mqtt_client, topic, enable_state=True, enable_brightness=False, enable_color_temp=False, send_on_power_on=True):
  242. super().__init__(mqtt_client, topic)
  243. self.send_on_power_on = send_on_power_on
  244. self.add_callback(self.KEY_STATE, self.print_formatted, None)
  245. self.add_callback(self.KEY_BRIGHTNESS, self.print_formatted, None)
  246. self.add_callback(self.KEY_COLOR_TEMP, self.print_formatted, None)
  247. #
  248. self.commands = []
  249. if enable_state:
  250. self.commands.extend(self.STATE_COMMANDS)
  251. if enable_brightness:
  252. self.commands.extend(self.BRIGHTNESS_COMMANDS)
  253. if enable_color_temp:
  254. self.commands.extend(self.COLOR_TEMP_COMMANDS)
  255. self.__init_data__(enable_state, enable_brightness, enable_color_temp)
  256. def __init_data__(self, enable_state, enable_brightness, enable_color_temp):
  257. data = {}
  258. if enable_state:
  259. data[self.KEY_STATE] = 'off'
  260. self.commands.extend(self.STATE_COMMANDS)
  261. if enable_brightness:
  262. data[self.KEY_BRIGHTNESS] = 128
  263. self.brightnes_move = (0, time.time())
  264. self.commands.extend(self.BRIGHTNESS_COMMANDS)
  265. if enable_color_temp:
  266. data[self.KEY_COLOR_TEMP] = 352
  267. self.commands.extend(self.COLOR_TEMP_COMMANDS)
  268. self.store_data(**data)
  269. def __rx__(self, client, userdata, message):
  270. data = json.loads(message.payload)
  271. if self.data.get(self.KEY_STATE) == 'on' or data.get(self.KEY_STATE) in ['on', 'toggle']:
  272. if message.topic.startswith(self.topic) and message.topic.endswith('/set'):
  273. for targetkey in data:
  274. value = data[targetkey]
  275. if targetkey in self.data.keys():
  276. if targetkey == self.KEY_STATE and value == "toggle":
  277. value = "on" if self.data.get(self.KEY_STATE) == "off" else "off"
  278. self.store_data(**{targetkey: value})
  279. else:
  280. if targetkey == self.KEY_BRIGHTNESS_MOVE:
  281. new_value = self.data.get(self.KEY_BRIGHTNESS) + (time.time() - self.brightnes_move[1]) * self.brightnes_move[0]
  282. if new_value < 0:
  283. new_value = 0
  284. if new_value > 255:
  285. new_value = 255
  286. self.store_data(**{self.KEY_BRIGHTNESS: int(new_value)})
  287. self.brightnes_move = (value, time.time())
  288. else:
  289. print("%s: UNKNOWN KEY %s" % (message.topic, targetkey))
  290. elif message.topic == self.topic + '/get':
  291. self.__tx__(None)
  292. def command(self, command):
  293. try:
  294. command, value = command.split(' ')
  295. except ValueError:
  296. value = None
  297. if command in self.capabilities():
  298. if command == self.STATE_COMMANDS[0]:
  299. self.print_formatted(self, self.KEY_STATE, self.data.get(self.KEY_STATE))
  300. elif command == self.STATE_COMMANDS[1]:
  301. self.store_data(**{self.KEY_STATE: 'off' if self.data.get(self.KEY_STATE) == 'on' else 'on'})
  302. elif command == self.BRIGHTNESS_COMMANDS[0]:
  303. self.print_formatted(self, self.KEY_BRIGHTNESS, self.data.get(self.KEY_BRIGHTNESS))
  304. elif command == self.BRIGHTNESS_COMMANDS[1]:
  305. self.store_data(**{self.KEY_BRIGHTNESS: command_int_value(value)})
  306. elif command == self.COLOR_TEMP_COMMANDS[0]:
  307. self.print_formatted(self, self.KEY_COLOR_TEMP, self.data.get(self.KEY_COLOR_TEMP))
  308. elif command == self.COLOR_TEMP_COMMANDS[1]:
  309. self.store_data(**{self.KEY_COLOR_TEMP: command_int_value(value)})
  310. else:
  311. print("%s: not yet implemented!" % command)
  312. else:
  313. print("Unknown command!")
  314. def power_off(self, device, key, value):
  315. self.data[self.KEY_STATE] = 'off'
  316. self.print_formatted(self, self.KEY_STATE, 'off')
  317. def power_on(self, device, key, value):
  318. if self.send_on_power_on:
  319. self.store_data(**{self.KEY_STATE: 'on'})
  320. else:
  321. self.data[self.KEY_STATE] = 'on'
  322. self.print_formatted(self, self.KEY_STATE, 'on')
  323. def print_formatted(self, device, key, value):
  324. if value is not None:
  325. color = COLOR_LIGHT_ACTIVE
  326. if key == self.KEY_STATE:
  327. if value == "on":
  328. print(color + 10 * ' ' + u'\u2b24' + 6 * ' ' + " - ".join(self.topic.split('/')[1:]) + colored.attr("reset"))
  329. else:
  330. print(color + 10 * ' ' + u'\u25ef' + 6 * ' ' + " - ".join(self.topic.split('/')[1:]) + colored.attr("reset"))
  331. self.print_formatted(device, self.KEY_BRIGHTNESS, self.data.get(self.KEY_BRIGHTNESS))
  332. self.print_formatted(device, self.KEY_COLOR_TEMP, self.data.get(self.KEY_COLOR_TEMP))
  333. elif key in [self.KEY_BRIGHTNESS, self.KEY_COLOR_TEMP]:
  334. if self.data.get(self.KEY_STATE) != "on":
  335. color = COLOR_LIGHT_PASSIVE
  336. if key == self.KEY_BRIGHTNESS:
  337. value = round(value * 100 / 256, 0)
  338. else:
  339. value = round((value - 250) * 100 / 204, 0)
  340. sys.stdout.write(color)
  341. sys.stdout.write('B' if key == gui_light.KEY_BRIGHTNESS else 'C')
  342. percent_print(value)
  343. sys.stdout.write("%3d%% " % value)
  344. print(" - ".join(self.topic.split('/')[1:]) + colored.attr("reset"))
  345. class gui_light(tradfri_light):
  346. AUTOSEND = False
  347. #
  348. KEY_ENABLE = "enable"
  349. def __init__(self, mqtt_client, topic, enable_state=True, enable_brightness=False, enable_color_temp=False):
  350. super().__init__(mqtt_client, topic, enable_state, enable_brightness, enable_color_temp)
  351. self.add_callback(self.KEY_ENABLE, self.print_formatted, None)
  352. def __init_data__(self, enable_state, enable_brightness, enable_color_temp):
  353. data = {}
  354. data[self.KEY_ENABLE] = False
  355. if enable_state:
  356. data[self.KEY_STATE] = False
  357. if enable_brightness:
  358. data[self.KEY_BRIGHTNESS] = 50
  359. if enable_color_temp:
  360. data[self.KEY_COLOR_TEMP] = 5
  361. self.store_data(**data)
  362. def __rx__(self, client, userdata, message):
  363. value = payload_filter(message.payload)
  364. if message.topic.startswith(self.topic) and message.topic.endswith('/set'):
  365. targetkey = message.topic.split('/')[-2]
  366. if targetkey in self.data.keys():
  367. self.store_data(**{targetkey: value})
  368. else:
  369. print("Unknown key %s in %s" % (targetkey, self.__class__.__name__))
  370. elif message.topic == self.topic + '/get':
  371. self.__tx__(None)
  372. def send(self, key, data):
  373. if data is not None:
  374. topic = self.topic + '/' + key
  375. self.mqtt_client.send(topic, json.dumps(data))
  376. def command(self, command):
  377. try:
  378. command, value = command.split(' ')
  379. except ValueError:
  380. value = None
  381. if command in self.capabilities():
  382. if command == self.STATE_COMMANDS[0]:
  383. self.print_formatted(self, self.KEY_STATE, self.data.get(self.KEY_STATE))
  384. elif command == self.STATE_COMMANDS[1]:
  385. self.send(self.KEY_STATE, not self.data.get(self.KEY_STATE))
  386. elif command == self.BRIGHTNESS_COMMANDS[0]:
  387. self.print_formatted(self, self.KEY_BRIGHTNESS, self.data.get(self.KEY_BRIGHTNESS))
  388. elif command == self.BRIGHTNESS_COMMANDS[1]:
  389. self.send(self.KEY_BRIGHTNESS, command_int_value(value))
  390. elif command == self.COLOR_TEMP_COMMANDS[0]:
  391. self.print_formatted(self, self.KEY_COLOR_TEMP, self.data.get(self.KEY_COLOR_TEMP))
  392. elif command == self.COLOR_TEMP_COMMANDS[1]:
  393. self.send(self.KEY_COLOR_TEMP, command_int_value(value))
  394. else:
  395. print("%s: not yet implemented!" % command)
  396. else:
  397. print("Unknown command!")
  398. def print_formatted(self, device, key, value):
  399. if value is not None:
  400. color = COLOR_GUI_ACTIVE
  401. if key == self.KEY_STATE:
  402. if value == True:
  403. print(color + 10 * ' ' + u'\u25a0' + 6 * ' ' + " - ".join(self.topic.split('/')[1:-1]) + colored.attr("reset"))
  404. else:
  405. print(color + 10 * ' ' + u'\u25a1' + 6*' ' + " - ".join(self.topic.split('/')[1:-1]) + colored.attr("reset"))
  406. elif key == self.KEY_ENABLE:
  407. self.print_formatted(device, self.KEY_BRIGHTNESS, self.data.get(self.KEY_BRIGHTNESS))
  408. self.print_formatted(device, self.KEY_COLOR_TEMP, self.data.get(self.KEY_COLOR_TEMP))
  409. elif key in [self.KEY_BRIGHTNESS, self.KEY_COLOR_TEMP]:
  410. if not self.data.get(self.KEY_ENABLE, False):
  411. color = COLOR_GUI_PASSIVE
  412. value = round(value * 10 if key == self.KEY_COLOR_TEMP else value, 0)
  413. sys.stdout.write(color)
  414. sys.stdout.write('B' if key == self.KEY_BRIGHTNESS else 'C')
  415. percent_print(value)
  416. sys.stdout.write("%3d%% " % value)
  417. print(" - ".join(self.topic.split('/')[1:-1]) + colored.attr("reset"))
  418. class tradfri_button(base):
  419. KEY_ACTION = "action"
  420. #
  421. ACTION_TOGGLE = "toggle"
  422. ACTION_BRIGHTNESS_UP = "brightness_up_click"
  423. ACTION_BRIGHTNESS_DOWN = "brightness_down_click"
  424. ACTION_RIGHT = "arrow_right_click"
  425. ACTION_LEFT = "arrow_left_click"
  426. ACTION_BRIGHTNESS_UP_LONG = "brightness_up_hold"
  427. ACTION_BRIGHTNESS_DOWN_LONG = "brightness_down_hold"
  428. ACTION_RIGHT_LONG = "arrow_right_hold"
  429. ACTION_LEFT_LONG = "arrow_left_hold"
  430. #
  431. COMMANDS = [ACTION_TOGGLE, ACTION_LEFT, ACTION_RIGHT, ACTION_BRIGHTNESS_UP, ACTION_BRIGHTNESS_DOWN,
  432. ACTION_LEFT_LONG, ACTION_RIGHT_LONG, ACTION_BRIGHTNESS_UP_LONG, ACTION_BRIGHTNESS_DOWN_LONG]
  433. def __init__(self, mqtt_client, topic):
  434. super().__init__(mqtt_client, topic)
  435. def __rx__(self, client, userdata, message):
  436. pass
  437. def command(self, command):
  438. try:
  439. command, value = command.split(' ')
  440. except ValueError:
  441. value = None
  442. else:
  443. value = json.loads(value)
  444. if command in self.capabilities():
  445. action = self.COMMANDS[self.COMMANDS.index(command)]
  446. if self.COMMANDS.index(command) <= 4:
  447. self.mqtt_client.send(self.topic, json.dumps({self.KEY_ACTION: action}))
  448. elif self.COMMANDS.index(command) <= 8:
  449. self.mqtt_client.send(self.topic, json.dumps({self.KEY_ACTION: action}))
  450. time.sleep(value or 0.5)
  451. action = '_'.join(action.split('_')[:-1] + ['release'])
  452. self.mqtt_client.send(self.topic, json.dumps({self.KEY_ACTION: action}))
  453. class gui_led_array(base):
  454. AUTOSEND = False
  455. #
  456. KEY_LED_0 = "led0"
  457. KEY_LED_1 = "led1"
  458. KEY_LED_2 = "led2"
  459. KEY_LED_3 = "led3"
  460. KEY_LED_4 = "led4"
  461. KEY_LED_5 = "led5"
  462. KEY_LED_6 = "led6"
  463. KEY_LED_7 = "led7"
  464. KEY_LED_8 = "led8"
  465. KEY_LED_9 = "led9"
  466. def __init__(self, mqtt_client, topic, names=[]):
  467. super().__init__(mqtt_client, topic)
  468. self.names = {}
  469. for i in range(0, 10):
  470. key = getattr(self, "KEY_LED_%d" % i)
  471. self.data[key] = False
  472. try:
  473. self.names[key] = names[i]
  474. except IndexError:
  475. self.names[key] = key
  476. self.add_callback(key, self.print_formatted, None)
  477. def __rx__(self, client, userdata, message):
  478. value = payload_filter(message.payload)
  479. if message.topic.startswith(self.topic) and message.topic.endswith('/set'):
  480. targetkey = message.topic.split('/')[-2]
  481. if targetkey in self.data.keys():
  482. self.store_data(**{targetkey: value})
  483. else:
  484. print("Unknown key %s in %s" % (targetkey, self.__class__.__name__))
  485. def print_formatted(self, device, key, value):
  486. if value:
  487. color = colored.fg('green')
  488. else:
  489. color = ""
  490. print(color + 10 * ' ' + u"\u2b24" + 6 * ' ' + COLOR_GUI_ACTIVE +
  491. ' - '.join(self.topic.split('/')[:-1]) + ' (%s)' % self.names[key] + colored.attr("reset"))