Smarthome Functionen
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

base.py 4.3KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113
  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. #
  27. CFG_DATA = {}
  28. def __init__(self, mqtt_client, topic):
  29. super().__init__(mqtt_client, topic, default_values=dict.fromkeys(self.RX_KEYS))
  30. # data storage
  31. # initialisations
  32. mqtt_client.add_callback(topic=self.topic, callback=self.receive_callback)
  33. mqtt_client.add_callback(topic=self.topic+"/#", callback=self.receive_callback)
  34. #
  35. self.add_callback(None, None, self.__state_logging__, on_change_only=True)
  36. def __cfg_callback__(self, key, value):
  37. if self.CFG_DATA.get(key) != value:
  38. self.logger.warning("Differing configuration identified: %s=%s --> %s=%s",
  39. repr(key), repr(value), repr(key), repr(self.CFG_DATA.get(key)))
  40. self.send_command(key, self.CFG_DATA.get(key))
  41. def set(self, key, data, block_callback=[]):
  42. if key in self.CFG_DATA:
  43. self.__cfg_callback__(key, data)
  44. if key in self.RX_IGNORE_KEYS:
  45. pass # ignore these keys
  46. elif key in self.RX_KEYS:
  47. return super().set(key, data, block_callback)
  48. else:
  49. self.logger.warning("Unexpected key %s", key)
  50. def receive_callback(self, client, userdata, message):
  51. if message.topic != self.topic + '/' + videv_base.KEY_INFO:
  52. content_key = message.topic[len(self.topic) + 1:]
  53. if content_key not in self.RX_IGNORE_TOPICS and (not message.topic.endswith(self.TX_TOPIC) or len(self.TX_TOPIC) == 0):
  54. self.logger.debug("Unpacking content_key \"%s\" from message.", content_key)
  55. if is_json(message.payload):
  56. data = json.loads(message.payload)
  57. if type(data) is dict:
  58. for key in data:
  59. self.set(key, self.__device_to_instance_filter__(key, data[key]))
  60. else:
  61. self.set(content_key, self.__device_to_instance_filter__(content_key, data))
  62. # String
  63. else:
  64. self.set(content_key, self.__device_to_instance_filter__(content_key, message.payload.decode('utf-8')))
  65. else:
  66. self.logger.debug("Ignoring topic %s", content_key)
  67. def __device_to_instance_filter__(self, key, data):
  68. if key in self.RX_FILTER_DATA_KEYS:
  69. if data in [1, 'on', 'ON']:
  70. return True
  71. elif data in [0, 'off', 'OFF']:
  72. return False
  73. return data
  74. def __instance_to_device_filter__(self, key, data):
  75. if key in self.TX_FILTER_DATA_KEYS:
  76. if data is True:
  77. return "on"
  78. elif data is False:
  79. return "off"
  80. return data
  81. def send_command(self, key, data):
  82. data = self.__instance_to_device_filter__(key, data)
  83. if self.TX_TOPIC is not None:
  84. if self.TX_TYPE < 0:
  85. self.logger.error("Unknown tx type. Set TX_TYPE of class to a known value")
  86. else:
  87. self.logger.debug("Sending data for %s - %s", key, str(data))
  88. if self.TX_TYPE == self.TX_DICT:
  89. try:
  90. self.mqtt_client.send('/'.join([self.topic, self.TX_TOPIC]), json.dumps({key: data}))
  91. except TypeError:
  92. print(self.topic)
  93. print(key.__dict__)
  94. print(key)
  95. print(data)
  96. raise TypeError
  97. else:
  98. if type(data) not in [str, bytes]:
  99. data = json.dumps(data)
  100. self.mqtt_client.send('/'.join([self.topic, key, self.TX_TOPIC] if len(self.TX_TOPIC) > 0 else [self.topic, key]), data)
  101. else:
  102. self.logger.error("Unknown tx toptic. Set TX_TOPIC of class to a known value")