Smarthome Functionen
選択できるのは25トピックまでです。 トピックは、先頭が英数字で、英数字とダッシュ('-')を使用した35文字以内のものにしてください。

base.py 4.5KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128
  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. BATTERY_WARN_LEVEL = 10
  9. def is_json(data):
  10. try:
  11. json.loads(data)
  12. except json.decoder.JSONDecodeError:
  13. return False
  14. else:
  15. return True
  16. class base(mqtt_base):
  17. TX_TOPIC = "set"
  18. TX_VALUE = 0
  19. TX_DICT = 1
  20. TX_TYPE = -1
  21. TX_FILTER_DATA_KEYS = []
  22. #
  23. RX_KEYS = []
  24. RX_IGNORE_TOPICS = []
  25. RX_IGNORE_KEYS = []
  26. RX_FILTER_DATA_KEYS = []
  27. #
  28. KEY_WARNING = '__WARNING__'
  29. def __init__(self, mqtt_client, topic):
  30. super().__init__(mqtt_client, topic, default_values=dict.fromkeys(self.RX_KEYS + [self.KEY_WARNING]))
  31. # data storage
  32. # initialisations
  33. mqtt_client.add_callback(topic=self.topic, callback=self.receive_callback)
  34. mqtt_client.add_callback(topic=self.topic+"/#", callback=self.receive_callback)
  35. #
  36. self.add_callback(None, None, self.__state_logging__, on_change_only=True)
  37. def set(self, key, data, block_callback=[]):
  38. if key in self.RX_IGNORE_KEYS:
  39. pass # ignore these keys
  40. elif key in self.RX_KEYS or key == self.KEY_WARNING:
  41. return super().set(key, data, block_callback)
  42. else:
  43. self.logger.warning("Unexpected key %s", key)
  44. def receive_callback(self, client, userdata, message):
  45. if message.topic != self.topic + '/' + videv_base.KEY_INFO:
  46. content_key = message.topic[len(self.topic) + 1:]
  47. if content_key not in self.RX_IGNORE_TOPICS and (not message.topic.endswith(self.TX_TOPIC) or len(self.TX_TOPIC) == 0):
  48. self.logger.debug("Unpacking content_key \"%s\" from message.", content_key)
  49. if is_json(message.payload):
  50. data = json.loads(message.payload)
  51. if type(data) is dict:
  52. for key in data:
  53. self.set(key, self.__device_to_instance_filter__(key, data[key]))
  54. else:
  55. self.set(content_key, self.__device_to_instance_filter__(content_key, data))
  56. # String
  57. else:
  58. self.set(content_key, self.__device_to_instance_filter__(content_key, message.payload.decode('utf-8')))
  59. else:
  60. self.logger.debug("Ignoring topic %s", content_key)
  61. def __device_to_instance_filter__(self, key, data):
  62. if key in self.RX_FILTER_DATA_KEYS:
  63. if data in [1, 'on', 'ON']:
  64. return True
  65. elif data in [0, 'off', 'OFF']:
  66. return False
  67. return data
  68. def __instance_to_device_filter__(self, key, data):
  69. if key in self.TX_FILTER_DATA_KEYS:
  70. if data is True:
  71. return "on"
  72. elif data is False:
  73. return "off"
  74. return data
  75. def send_command(self, key, data):
  76. data = self.__instance_to_device_filter__(key, data)
  77. if self.TX_TOPIC is not None:
  78. if self.TX_TYPE < 0:
  79. self.logger.error("Unknown tx type. Set TX_TYPE of class to a known value")
  80. else:
  81. self.logger.debug("Sending data for %s - %s", key, str(data))
  82. if self.TX_TYPE == self.TX_DICT:
  83. try:
  84. self.mqtt_client.send('/'.join([self.topic, self.TX_TOPIC]), json.dumps({key: data}))
  85. except TypeError:
  86. print(self.topic)
  87. print(key.__dict__)
  88. print(key)
  89. print(data)
  90. raise TypeError
  91. else:
  92. if type(data) not in [str, bytes]:
  93. data = json.dumps(data)
  94. self.mqtt_client.send('/'.join([self.topic, key, self.TX_TOPIC] if len(self.TX_TOPIC) > 0 else [self.topic, key]), data)
  95. else:
  96. self.logger.error("Unknown tx toptic. Set TX_TOPIC of class to a known value")
  97. class warning(dict):
  98. TYPE_BATTERY_LOW = 1
  99. TYPE_OVERTEMPERATURE = 2
  100. #
  101. KEY_ID = 'id'
  102. KEY_TYPE = 'type'
  103. KEY_TEXT = 'text'
  104. KEY_TM = 'tm'
  105. def __init__(self, identification, type, text, args):
  106. super().__init__({
  107. self.KEY_ID: identification,
  108. self.KEY_TYPE: type,
  109. self.KEY_TEXT: text % args,
  110. self.KEY_TM: time.localtime(),
  111. })
  112. def __str__(self):
  113. return time.asctime(self.get(self.KEY_TM)) + ": " + self[self.KEY_TEXT] + " - " + self[self.KEY_ID]