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

base.py 3.9KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103
  1. #!/usr/bin/env python
  2. # -*- coding: utf-8 -*-
  3. #
  4. from base import mqtt_base
  5. from base import videv_base
  6. import json
  7. import time
  8. def is_json(data):
  9. try:
  10. json.loads(data)
  11. except json.decoder.JSONDecodeError:
  12. return False
  13. else:
  14. return True
  15. class base(mqtt_base):
  16. TX_TOPIC = "set"
  17. TX_VALUE = 0
  18. TX_DICT = 1
  19. TX_TYPE = -1
  20. TX_FILTER_DATA_KEYS = []
  21. #
  22. RX_KEYS = []
  23. RX_IGNORE_TOPICS = []
  24. RX_IGNORE_KEYS = []
  25. RX_FILTER_DATA_KEYS = []
  26. def __init__(self, mqtt_client, topic):
  27. super().__init__(mqtt_client, topic, default_values=dict.fromkeys(self.RX_KEYS))
  28. # data storage
  29. # initialisations
  30. mqtt_client.add_callback(topic=self.topic, callback=self.receive_callback)
  31. mqtt_client.add_callback(topic=self.topic+"/#", callback=self.receive_callback)
  32. #
  33. self.add_callback(None, None, self.__state_logging__, on_change_only=True)
  34. def set(self, key, data, block_callback=[]):
  35. if key in self.RX_IGNORE_KEYS:
  36. pass # ignore these keys
  37. elif key in self.RX_KEYS:
  38. return super().set(key, data, block_callback)
  39. else:
  40. self.logger.warning("Unexpected key %s", key)
  41. def receive_callback(self, client, userdata, message):
  42. if message.topic != self.topic + '/' + videv_base.KEY_INFO:
  43. content_key = message.topic[len(self.topic) + 1:]
  44. if content_key not in self.RX_IGNORE_TOPICS and (not message.topic.endswith(self.TX_TOPIC) or len(self.TX_TOPIC) == 0):
  45. self.logger.debug("Unpacking content_key \"%s\" from message.", content_key)
  46. if is_json(message.payload):
  47. data = json.loads(message.payload)
  48. if type(data) is dict:
  49. for key in data:
  50. self.set(key, self.__device_to_instance_filter__(key, data[key]))
  51. else:
  52. self.set(content_key, self.__device_to_instance_filter__(content_key, data))
  53. # String
  54. else:
  55. self.set(content_key, self.__device_to_instance_filter__(content_key, message.payload.decode('utf-8')))
  56. else:
  57. self.logger.debug("Ignoring topic %s", content_key)
  58. def __device_to_instance_filter__(self, key, data):
  59. if key in self.RX_FILTER_DATA_KEYS:
  60. if data in [1, 'on', 'ON']:
  61. return True
  62. elif data in [0, 'off', 'OFF']:
  63. return False
  64. return data
  65. def __instance_to_device_filter__(self, key, data):
  66. if key in self.TX_FILTER_DATA_KEYS:
  67. if data is True:
  68. return "on"
  69. elif data is False:
  70. return "off"
  71. return data
  72. def send_command(self, key, data):
  73. data = self.__instance_to_device_filter__(key, data)
  74. if self.TX_TOPIC is not None:
  75. if self.TX_TYPE < 0:
  76. self.logger.error("Unknown tx type. Set TX_TYPE of class to a known value")
  77. else:
  78. self.logger.debug("Sending data for %s - %s", key, str(data))
  79. if self.TX_TYPE == self.TX_DICT:
  80. try:
  81. self.mqtt_client.send('/'.join([self.topic, self.TX_TOPIC]), json.dumps({key: data}))
  82. except TypeError:
  83. print(self.topic)
  84. print(key.__dict__)
  85. print(key)
  86. print(data)
  87. raise TypeError
  88. else:
  89. if type(data) not in [str, bytes]:
  90. data = json.dumps(data)
  91. self.mqtt_client.send('/'.join([self.topic, key, self.TX_TOPIC] if len(self.TX_TOPIC) > 0 else [self.topic, key]), data)
  92. else:
  93. self.logger.error("Unknown tx toptic. Set TX_TOPIC of class to a known value")