Skip to content

Commit

Permalink
Adding support for dimmers and did some code clean up, (yes, there is…
Browse files Browse the repository at this point in the history
… a lot more cleaning to be done :D)
  • Loading branch information
mliljedahl committed Oct 10, 2021
1 parent 8ea48b8 commit 404a818
Show file tree
Hide file tree
Showing 4 changed files with 52 additions and 42 deletions.
2 changes: 1 addition & 1 deletion config_default.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -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}
Expand Down
6 changes: 3 additions & 3 deletions logging.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -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]
51 changes: 25 additions & 26 deletions main.py
Original file line number Diff line number Diff line change
Expand Up @@ -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))
Expand Down Expand Up @@ -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)

Expand All @@ -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:
Expand All @@ -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
Expand Down
35 changes: 23 additions & 12 deletions src/telldus.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand All @@ -60,14 +63,18 @@ 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'])
if hasattr(device, 'name'):
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'] = {}
Expand All @@ -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


Expand Down Expand Up @@ -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):
Expand All @@ -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))
Expand Down Expand Up @@ -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

0 comments on commit 404a818

Please sign in to comment.