Skip to content

Commit bd1ceba

Browse files
Merge pull request #64 from bhelm/main
Restored missing SensorInfo parameters, fixed mqtt global variable shadowing and some linting
2 parents d36971d + 41dee29 commit bd1ceba

4 files changed

Lines changed: 29 additions & 25 deletions

File tree

plugins/sinks/ha_mqtt/ha_mqtt.py

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,6 @@
11
import os
22
import time
33
import logging
4-
from collections import defaultdict
54
import ha_mqtt_discoverable
65
from ha_mqtt_discoverable import Settings
76
from ha_mqtt_discoverable.sensors import SensorInfo, Sensor, DeviceInfo
@@ -136,7 +135,10 @@ def get_sensor(name: str, device_info: DeviceInfo) -> Optional[Sensor]:
136135
'unit_of_measurement'),
137136
device_class=result.get('device_class'),
138137
state_class=result.get('state_class'),
139-
entity_category=result.get('entity_category'))
138+
entity_category=result.get('entity_category'),
139+
suggested_display_precision=result.get('suggested_display_precision'),
140+
icon=result.get('icon'),
141+
device=device_info)
140142
# mqtt_settings is guarded above, so cast is safe for the type checker
141143
sensor = Sensor(Settings(mqtt=mqtt_settings, entity=sensor_info))
142144
sensors[name] = sensor

plugins/sinks/mqtt/mqtt.py

Lines changed: 15 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -3,13 +3,11 @@
33
import logging
44
import ssl
55
import paho.mqtt.client as mqtt
6-
from typing import Dict, Optional
76

87
# Get client ID with optional postfix for multiple instances
98
client_id_postfix = os.environ.get('IDENT_POSTFIX', '')
109
client = mqtt.Client(
1110
client_id=f"smahub{client_id_postfix}", transport='tcp', protocol=mqtt.MQTTv311, clean_session=False)
12-
pubunits = False
1311

1412

1513
def env_vars(config):
@@ -50,6 +48,19 @@ def execute(config, get_items, register_callback, do_stop):
5048

5149
logging.info("Starting MQTT sink")
5250

51+
# Define publish and callback functions here to capture pubunits in closure
52+
def publish(topic, value):
53+
# only publish units if they are there and we really want to
54+
publish_value = value
55+
if isinstance(value, tuple):
56+
if not pubunits:
57+
publish_value = value[0]
58+
client.publish(topic, str(publish_value))
59+
60+
def my_callback(key, value):
61+
topic = str(key).replace(".", "/")
62+
publish(topic, value)
63+
5364
# No need for global - we're only using the module-level client, not rebinding it
5465
if config['server']['username']:
5566
client.username_pw_set(
@@ -103,7 +114,7 @@ def execute(config, get_items, register_callback, do_stop):
103114
logging.fatal(
104115
f"MQTT broker configuration error: {str(exc)}, rethrowing exception")
105116
raise
106-
except ConnectionError as exc:
117+
except ConnectionError:
107118
logging.fatal(
108119
f"MQTT broker not reachable at address: {config.get('server', 'address')}: {str(config.get('server', 'port'))}")
109120
raise
@@ -112,7 +123,7 @@ def execute(config, get_items, register_callback, do_stop):
112123
f"MQTT broker unknown error: {str(exc)}, rethrowing exception")
113124
raise
114125

115-
# We only publish data on change
126+
# We only publish data on change (use closure-captured my_callback)
116127
register_callback(my_callback)
117128

118129
i = 0
@@ -132,21 +143,6 @@ def execute(config, get_items, register_callback, do_stop):
132143
logging.info("Stopping MQTT sink")
133144

134145

135-
def publish(topic, value):
136-
# read module-level client and pubunits (no rebinding), no global statement required
137-
# only publish units if they are there and we really want to
138-
publish_value = value
139-
if isinstance(value, tuple):
140-
if not pubunits:
141-
publish_value = value[0]
142-
client.publish(topic, str(publish_value))
143-
144-
145-
def my_callback(key, value):
146-
topic = str(key).replace(".", "/")
147-
publish(topic, value)
148-
149-
150146
def on_connect(client, userdata, flags, rc):
151147
if rc == 0:
152148
logging.info("Connected to MQTT Broker")

plugins/sources/TripowerX/tripowerx.py

Lines changed: 9 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -136,7 +136,10 @@ def execute(config, add_data, dostop):
136136
try:
137137
v = round(float(v), 2)
138138
except Exception as e:
139-
logging.error(f"Error rounding value for parameter '{name}': value='{v}', type={type(v).__name__}, error: {e}")
139+
logging.error(
140+
f"Error rounding value for parameter "
141+
f"'{name}': value='{v}', "
142+
f"type={type(v).__name__}, error: {e}")
140143
raise
141144

142145
unit = get_parameter_unit('SENSORS_TRIPOWERX', name)
@@ -152,9 +155,12 @@ def execute(config, add_data, dostop):
152155
try:
153156
v = round(float(v), 2)
154157
except Exception as e:
155-
logging.error(f"Error rounding value for parameter '{name}[{idx}]': value='{v}', type={type(v).__name__}, error: {e}")
158+
logging.error(
159+
f"Error rounding value for parameter "
160+
f"'{name}[{idx}]': value='{v}', "
161+
f"type={type(v).__name__}, error: {e}")
156162
raise
157-
163+
158164
idxname = dname + "." + str(idx + 1)
159165
unit = get_parameter_unit('SENSORS_TRIPOWERX', name)
160166
if unit:

pyproject.toml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@ requires = ["flit_core >=3.8.0,<4"]
44

55
[project]
66
name = "smahub"
7-
version = "1.6.3"
7+
version = "1.7.1"
88
authors = [{ name = "Daniel Krippner", email = "dk.mailbox@gmx.net" }]
99
description = "Little daemon that runs plugins for collecting data from SMA PV products, and publishes to eg MQTT via other plugins."
1010
readme = "README.md"

0 commit comments

Comments
 (0)