From 404a818347bed0ff9c2247d1bc54b8e40c7ce2d1 Mon Sep 17 00:00:00 2001 From: mliljedahl Date: Sun, 10 Oct 2021 22:19:07 +0200 Subject: [PATCH] Adding support for dimmers and did some code clean up, (yes, there is a lot more cleaning to be done :D) --- config_default.yaml | 2 +- logging.yaml | 6 +++--- main.py | 51 ++++++++++++++++++++++----------------------- src/telldus.py | 35 ++++++++++++++++++++----------- 4 files changed, 52 insertions(+), 42 deletions(-) diff --git a/config_default.yaml b/config_default.yaml index f438bcd..d28fd94 100644 --- a/config_default.yaml +++ b/config_default.yaml @@ -3,7 +3,7 @@ home_assistant: state_topic: !ENV ${TDM_STATE_TOPIC:telldus} telldus: - repeat_cmd: !ENV ${TDM_REPEAT_CMD:5} + repeat_cmd: !ENV ${TDM_REPEAT_CMD:3} mqtt: broker: !ENV ${TDM_MQTT_SERVER:127.0.0.1} diff --git a/logging.yaml b/logging.yaml index 58ff9c2..8816c69 100644 --- a/logging.yaml +++ b/logging.yaml @@ -5,14 +5,14 @@ formatters: handlers: console: class: logging.StreamHandler - level: DEBUG + level: INFO formatter: simple stream: ext://sys.stdout loggers: simpleExample: - level: DEBUG + level: INFO handlers: [console] propagate: no root: - level: DEBUG + level: INFO handlers: [console] diff --git a/main.py b/main.py index 7ffa9ed..a84804a 100755 --- a/main.py +++ b/main.py @@ -63,23 +63,23 @@ def subscribe_device(client: mqtt_client): def on_message(client, userdata, msg): logging.info(f"Received `{msg.payload.decode()}` from `{msg.topic}` topic") id = msg.topic.split('/')[1] + module = msg.topic.split('/')[2] + action = msg.topic.split('/')[3] cmd_status = False - if int(msg.payload.decode()) == int(const.TELLSTICK_TURNON): - logging.debug('[DEVICE] Sending command ON to device id {}'.format(id)) - cmd_status = d.turn_on(id) + if module == 'light': + if action == 'dim': + logging.debug('[DEVICE] Sending command DIM "{}" to device id {}'.format(int(msg.payload.decode()), id)) + cmd_status = d.dim(id, int(msg.payload.decode())) - if int(msg.payload.decode()) == int(const.TELLSTICK_TURNOFF): - logging.debug('[DEVICE] Sending command OFF to device id {}'.format(id)) - cmd_status = d.turn_off(id) + if action != 'dim': + if int(msg.payload.decode()) == int(const.TELLSTICK_TURNON): + logging.debug('[DEVICE] Sending command ON to device id {}'.format(id)) + cmd_status = d.turn_on(id) - # TODO: Need to find out what Home Assistant sends to dim... - # https://www.home-assistant.io/integrations/light.mqtt/ - value = int(0) - if int(msg.payload.decode()) == int(const.TELLSTICK_DIM): - logging.debug('[DEVICE] Sending command DIM "{}" to device id {}'.format(id, value)) - logging.info('[DEVICE] MSG = {}'.format(msg)) - cmd_status = d.dim(id, value) + if int(msg.payload.decode()) == int(const.TELLSTICK_TURNOFF): + logging.debug('[DEVICE] Sending command OFF to device id {}'.format(id)) + cmd_status = d.turn_off(id) if int(msg.payload.decode()) == int(const.TELLSTICK_BELL): logging.debug('[DEVICE] Sending command BELL to device id {}'.format(id)) @@ -113,20 +113,23 @@ def device_event(id_, method, data, cid): string = '[DEVICE] {0} -> {1} ({2})'.format(id_, method_string, method) if method == const.TELLSTICK_DIM: string += ' [{0}]'.format(data) - logging.debug('[DEVICE] {}'.format(string)) + logging.debug(string) - # TODO: Need method to lookup id and get model, now assuming "switch" - topic = d.create_topic(id_, 'switch') - data = d.create_topic_data('switch', method) - publish_mqtt(mqtt_client, topic, data) + if method == const.TELLSTICK_DIM: + topic = d.create_topic(id_, 'light') + topic_data = d.create_topic_data('light', data) + else: + topic = d.create_topic(id_, 'switch') + topic_data = d.create_topic_data('switch', method) + publish_mqtt(mqtt_client, topic, topic_data) def sensor_event(protocol, model, id_, dataType, value, timestamp, cid): type_string = TYPES.get(dataType, 'UNKNOWN METHOD {0}'.format(dataType)) string = '[SENSOR] {0} {1} ({2}) = {3}'.format(id_, model, type_string, value) - logging.debug('[SENSOR] {}'.format(string)) + logging.debug(string) - # Sensors can be added to telldus-core without a restart, ensure config topic for hass + # Sensors can be added or discovered in telldus-core without a restart, ensure config topic for HASS sensor_topics = s.create_topics(s.get(id_)) initial_publish(mqtt_client, sensor_topics) @@ -141,10 +144,6 @@ def initial_publish(mqtt_client, topics): publish_mqtt(mqtt_client, topic['config']['topic'], topic['config']['data']) if 'state' in topic: publish_mqtt(mqtt_client, topic['state']['topic'], topic['state']['data']) - if 'command' in topic: - if 'data' in topic['command']: - publish_mqtt(mqtt_client, topic['command']['topic'], topic['command']['data']) - with open('./logging.yaml', 'r') as stream: @@ -153,9 +152,9 @@ def initial_publish(mqtt_client, topics): logging.config.dictConfig(logging_config) logger = logging.getLogger('telldus-core-mqtt-main') -# Wait 30s for telldus-core to start and start collecting data +# Wait 5s for telldus-core to start and start collecting data logging.info('Waiting for telldus-core to start...') -time.sleep(30) +time.sleep(5) logging.info('telldus-core have started.') # Setup connection MQTT server diff --git a/src/telldus.py b/src/telldus.py index 041ef7e..b6d5e69 100755 --- a/src/telldus.py +++ b/src/telldus.py @@ -51,7 +51,10 @@ def create_topics(self, data): topics['state']['topic'] = '{}/{}/{}/state'.format(self.config['home_assistant']['state_topic'], d['device'].id, d['type']) topics['command'] = {} topics['command']['topic'] = '{}/{}/{}/set'.format(self.config['home_assistant']['state_topic'], d['device'].id, d['type']) - config_data = self._create_config_data(d['device'], topics['state']['topic'], d, topics['command']['topic']) + topics['brightness'] = {} + topics['brightness']['command'] = '{}/{}/{}/set'.format(self.config['home_assistant']['state_topic'], d['device'].id, 'brightness') + topics['brightness']['state'] = '{}/{}/{}/dim'.format(self.config['home_assistant']['state_topic'], d['device'].id, 'brightness') + config_data = self._create_config_data(d['device'], topics['state']['topic'], d, topics['command']['topic'], topics['brightness']) topics['config']['data'] = json.dumps(config_data, ensure_ascii=False) topics['state']['data'] = json.dumps(d['state_data'], ensure_ascii=False) @@ -60,7 +63,7 @@ def create_topics(self, data): return topics_to_create - def _create_config_data(self, device, state_topic, extra, command_topic=None): + def _create_config_data(self, device, state_topic, extra, command_topic=None, brightness_command=None): # common config_data = {} config_data['unique_id'] = '{}_telldus_{}'.format(device.id, extra['type']) @@ -68,6 +71,10 @@ def _create_config_data(self, device, state_topic, extra, command_topic=None): config_data['name'] = device.name else: config_data['name'] = 'telldus_{}_{}'.format(device.id, extra['type']) + if extra['type'] == 'light': + config_data['brightness_state_topic'] = brightness_command['state'] + config_data['brightness_value_template'] = '{{ value_json.%s }}' % 'brightness' + config_data['brightness_command_topic'] = brightness_command['command'] config_data['state_topic'] = state_topic config_data['value_template'] = '{{ value_json.%s }}' % extra['type'] config_data['device'] = {} @@ -90,14 +97,18 @@ def _create_config_data(self, device, state_topic, extra, command_topic=None): config_data['command_topic'] = command_topic config_data['payload_on'] = const.TELLSTICK_TURNON config_data['payload_off'] = const.TELLSTICK_TURNOFF - config_data['state_on'] = const.TELLSTICK_TURNON - config_data['state_off'] = const.TELLSTICK_TURNOFF + if extra['type'] != 'light': + config_data['state_on'] = const.TELLSTICK_TURNON + config_data['state_off'] = const.TELLSTICK_TURNOFF return config_data def create_topic(self, id, model): - topic = '{}/{}/{}/state'.format(self.config['home_assistant']['state_topic'], id, model) + if model == 'light': + topic = '{}/{}/brightness/dim'.format(self.config['home_assistant']['state_topic'], id) + else: + topic = '{}/{}/{}/state'.format(self.config['home_assistant']['state_topic'], id, model) return topic @@ -193,11 +204,11 @@ def get(self, id=None): return sensors_data - def _find_sensor(self, sensor): + def _find_sensor(self, id): for s in self.core.sensors(): - if int(s.id) == int(sensor): + if int(s.id) == int(id): return s - logging.warning("Sensor '{}' not found".format(sensor)) + logging.warning('Sensor id "{}" not found'.format(int(id))) return None class Device(Telldus): @@ -217,7 +228,7 @@ def get(self, id=None): device_model = 'switch' if 'dimmer' in device.model: - device_model = 'dimmer' + device_model = 'light' if device_model == '': logging.INFO('Device "{}" not yet supported, please raise an github issue.'.format(device.model)) @@ -322,9 +333,9 @@ def stop(self, id): return False - def _find_device(self, device): + def _find_device(self, id): for d in self.core.devices(): - if str(d.id) == device or d.name == device: + if int(d.id) == int(id): return d - logging.warning("Device '{}' not found".format(device)) + logging.warning('Device id "{}" not found'.format(int(id))) return None \ No newline at end of file