Feature/v1.0.0 release (#12)

v1.0.0 - 2025-03-13
EHS-Sentinel has been heavily modified to incorporate the control mechanism
The read-in behavior of the modbus registers has been revised from chunks to single byte
MessageProcessor now runs asynchronously
MessageProducer added which takes over the writing communication with the WP
Configuration of HASS entities has moved from hardcoded to NASA Repository
NASA Repository has been fundamentally changed
All FSV Values, NASA_POWER, VAR_IN_TEMP_WATER_LAW_TARGET_F, NASA_INDOOR_OPMODE are allowed for writing mode
NASA_OUTDOOR_DEFROST_STEP DEFROST STEP 10 (b'0xa') added
ENUM_IN_SG_READY_MODE_STATE ACTIVE (b'0x2') added
New configuration point allowControl to allow control of the Samsung EHS heat pump (deactivated by default).
[!CAUTION]
This functionality requires that EHS-Sentinel actively communicates with the Samsung EHS, so EHS-Sentinel intervenes here in the Modbus data traffic between the components (it sends its own messages). The activation of this functionality is exclusively at your own risk. I assume no liability for any damage caused.

new configuration points in logging
controlMessage (default False) to print out the controlled mesagges
invalidPacket (default False) prints out invalid messages (length not ok, x34 not at end...)
Dashboard template has been split, ressources/dashboard_readonly_template.yaml is for readonly mode and the ressources/dashboard_controlmode_template.yaml for control mode
This commit is contained in:
echoDaveD
2025-03-13 19:57:33 +01:00
committed by GitHub
parent 43de00aacc
commit f0222d750f
26 changed files with 7251 additions and 4316 deletions

View File

@@ -10,6 +10,7 @@ import gmqtt
from CustomLogger import logger
from EHSArguments import EHSArguments
from EHSConfig import EHSConfig
from MessageProducer import MessageProducer
class MQTTClient:
"""
@@ -23,18 +24,6 @@ class MQTTClient:
DEVICE_ID = "samsung_ehssentinel"
def __new__(cls, *args, **kwargs):
"""
Create a new instance of the class if one does not already exist.
This method ensures that only one instance of the class is created (singleton pattern).
If an instance already exists, it returns the existing instance.
Otherwise, it creates a new instance, marks it as uninitialized, and returns it.
Args:
cls: The class being instantiated.
*args: Variable length argument list.
**kwargs: Arbitrary keyword arguments.
Returns:
An instance of the class.
"""
if not cls._instance:
cls._instance = super(MQTTClient, cls).__new__(cls)
@@ -42,32 +31,12 @@ class MQTTClient:
return cls._instance
def __init__(self):
"""
Initializes the MQTTClient instance.
This constructor sets up the MQTT client with the necessary configuration
parameters, including broker URL, port, client ID, and authentication credentials.
It also assigns callback functions for various MQTT events such as connect,
disconnect, message, and subscribe. Additionally, it initializes topic-related
settings and a list to keep track of known topics.
Attributes:
config (EHSConfig): Configuration object for MQTT settings.
args (EHSArguments): Argument parser object.
broker (str): URL of the MQTT broker.
port (int): Port number of the MQTT broker.
client_id (str): Client ID for the MQTT connection.
client (gmqtt.Client): MQTT client instance.
topicPrefix (str): Prefix for MQTT topics.
homeAssistantAutoDiscoverTopic (str): Topic for Home Assistant auto-discovery.
useCamelCaseTopicNames (bool): Flag to use camel case for topic names.
initialized (bool): Flag indicating if the client has been initialized.
known_topics (list): List to keep track of known topics.
known_devices_topic (str): Topic for storing known devices.
"""
if self._initialized:
return
self.config = EHSConfig()
self.args = EHSArguments()
self.message_producer = None
self._initialized = True
self.broker = self.config.MQTT['broker-url']
self.port = self.config.MQTT['broker-port']
@@ -88,17 +57,6 @@ class MQTTClient:
self.known_devices_topic = "known/devices" # Dedicated topic for storing known topics
async def connect(self):
"""
Asynchronously connects to the MQTT broker and optionally clears the known devices topic.
This function logs the connection attempt, connects to the MQTT broker using the specified
broker address and port, and sets the keepalive interval. If the CLEAN_KNOWN_DEVICES argument
is set, it publishes an empty message to the known devices topic to clear it.
Args:
None
Returns:
None
"""
logger.info("[MQTT] Connecting to broker...")
await self.client.connect(self.broker, self.port, keepalive=60, version=gmqtt.constants.MQTTv311)
@@ -106,53 +64,21 @@ class MQTTClient:
self._publish(f"{self.topicPrefix.replace('/', '')}/{self.known_devices_topic}", " ", retain=True)
logger.info("Known Devices Topic have been cleared")
def subscribe_known_topics(self):
"""
Subscribe to predefined MQTT topics.
This method subscribes the MQTT client to a set of known topics, which include:
- A topic for known devices, constructed using the topic prefix and known devices topic.
- A status topic for Home Assistant auto-discovery.
The subscription is done with a QoS level of 1 for both topics.
Logging:
- Logs an info message indicating the subscription to known devices topic.
"""
def subscribe_known_topics(self):
logger.info("Subscribe to known devices topic")
self.client.subscribe(
[
sublist = [
gmqtt.Subscription(f"{self.topicPrefix.replace('/', '')}/{self.known_devices_topic}", 1),
gmqtt.Subscription(f"{self.homeAssistantAutoDiscoverTopic}/status", 1)
]
)
if self.config.GENERAL['allowControl']:
sublist.append(gmqtt.Subscription(f"{self.topicPrefix.replace('/', '')}/entity/+/set", 1))
self.client.subscribe(sublist)
def on_subscribe(self, client, mid, qos, properties):
"""
Callback function that is called when the client subscribes to a topic.
Args:
client (paho.mqtt.client.Client): The client instance for this callback.
mid (int): The message ID for the subscribe request.
qos (int): The Quality of Service level for the subscription.
properties (paho.mqtt.properties.Properties): The properties associated with the subscription.
Returns:
None
"""
logger.debug('SUBSCRIBED')
def on_message(self, client, topic, payload, qos, properties):
"""
Callback function that is triggered when a message is received on a subscribed topic.
Args:
client (paho.mqtt.client.Client): The MQTT client instance.
topic (str): The topic that the message was received on.
payload (bytes): The message payload.
qos (int): The quality of service level of the message.
properties (paho.mqtt.properties.Properties): The properties associated with the message.
This function performs the following actions:
- If the topic matches the known devices topic, it updates the known topics list with the retained message.
- If the topic matches the Home Assistant auto-discover status topic, it logs the status message and, if the payload indicates that Home Assistant is online, it clears the known devices topic.
"""
def on_message(self, client, topic, payload, qos, properties):
if self.known_devices_topic in topic:
# Update the known devices set with the retained message
self.known_topics = list(filter(None, [x.strip() for x in payload.decode().split(",")]))
@@ -174,19 +100,15 @@ class MQTTClient:
logger.info("Known Devices Topic have been cleared")
self.clear_hass()
logger.info("All configuration from HASS has been resetet")
if topic.startswith(f"{self.topicPrefix.replace('/', '')}/entity"):
logger.info(f"HASS Set Entity Messages {topic} received: {payload.decode()}")
parts = topic.split("/")
if self.message_producer is None:
self.message_producer = MessageProducer(None)
asyncio.create_task(self.message_producer.write_request(parts[2], payload.decode(), read_request_after=True))
def on_connect(self, client, flags, rc, properties):
"""
Callback function for when the client receives a CONNACK response from the server.
Parameters:
client (paho.mqtt.client.Client): The client instance for this callback.
flags (dict): Response flags sent by the broker.
rc (int): The connection result.
properties (paho.mqtt.properties.Properties): The properties associated with the connection.
If the connection is successful (rc == 0), logs a success message and subscribes to known topics if any.
Otherwise, logs an error message with the return code.
"""
if rc == 0:
logger.info(f"Connected to MQTT with result code {rc}")
if len(self.homeAssistantAutoDiscoverTopic) > 0:
@@ -194,18 +116,7 @@ class MQTTClient:
else:
logger.error(f"Failed to connect, return code {rc}")
def on_disconnect(self, client, packet, exc=None):
"""
Callback function that is called when the client disconnects from the MQTT broker.
This function logs the disconnection event and attempts to reconnect the client
in case of an unexpected disconnection. It will keep trying to reconnect every
5 seconds until successful.
Args:
client (paho.mqtt.client.Client): The MQTT client instance that disconnected.
packet (paho.mqtt.packet.Packet): The disconnect packet.
exc (Exception, optional): The exception that caused the disconnection, if any.
"""
def on_disconnect(self, client, packet, exc=None):
logger.info(f"Disconnected with result code ")
logger.warning("Unexpected disconnection. Reconnecting...")
while True:
@@ -216,31 +127,12 @@ class MQTTClient:
logger.error(f"Reconnection failed: {e}")
time.sleep(5)
def _publish(self, topic, payload, qos=0, retain=False):
"""
Publishes a message to a specified MQTT topic.
Args:
topic (str): The MQTT topic to publish to.
payload (str): The message payload to publish.
qos (int, optional): The Quality of Service level for the message. Defaults to 0.
retain (bool, optional): If True, the message will be retained by the broker. Defaults to False.
Returns:
None
"""
def _publish(self, topic, payload, qos=0, retain=False):
logger.debug(f"MQTT Publish Topic: {topic} payload: {payload}")
self.client.publish(f"{topic}", payload, qos, retain)
#time.sleep(0.1)
def refresh_known_devices(self, devname):
"""
Refreshes the list of known devices by publishing the current known topics to the MQTT broker.
Args:
devname (str): The name of the device to refresh.
This function constructs a topic string by replacing '/' with an empty string in the topicPrefix,
then concatenates it with the known_devices_topic. It publishes the known topics as a comma-separated
string to this constructed topic with the retain flag set to True.
"""
self.known_topics.append(devname)
if self.config.LOGGING['deviceAdded']:
logger.info(f"Device added no. {len(self.known_topics):<3}: {devname} ")
@@ -248,20 +140,7 @@ class MQTTClient:
logger.debug(f"Device added no. {len(self.known_topics):<3}: {devname} ")
self._publish(f"{self.topicPrefix.replace('/', '')}/{self.known_devices_topic}", ",".join(self.known_topics), retain=True)
def publish_message(self, name, value):
"""
Publishes a message to an MQTT topic.
This function normalizes the given name, determines the appropriate MQTT topic,
and publishes the provided value to that topic. It also handles Home Assistant
auto-discovery if configured.
Args:
name (str): The name of the sensor or device.
value (int, float, bool, str): The value to be published. If the value is a float,
it will be rounded to two decimal places.
Raises:
ValueError: If the value type is not supported for publishing.
"""
async def publish_message(self, name, value):
newname = f"{self._normalize_name(name)}"
if len(self.homeAssistantAutoDiscoverTopic) > 0:
@@ -270,13 +149,10 @@ class MQTTClient:
self.auto_discover_hass(name)
self.refresh_known_devices(name)
time.sleep(1)
sensor_type = "sensor"
if 'enum' in self.config.NASA_REPO[name]:
enum = [*self.config.NASA_REPO[name]['enum'].values()]
if all([en.lower() in ['on', 'off'] for en in enum]):
sensor_type = "binary_sensor"
if self.config.NASA_REPO[name]['hass_opts']['writable']:
sensor_type = self.config.NASA_REPO[name]['hass_opts']['platform']['type']
else:
sensor_type = self.config.NASA_REPO[name]['hass_opts']['default_platform']
topicname = f"{self.config.MQTT['homeAssistantAutoDiscoverTopic']}/{sensor_type}/{self.DEVICE_ID}_{newname.lower()}/state"
else:
topicname = f"{self.topicPrefix.replace('/', '')}/{newname}"
@@ -287,13 +163,13 @@ class MQTTClient:
self._publish(topicname, value, qos=2, retain=False)
def clear_hass(self):
"""
clears all entities/components fpr the HomeAssistant Device
"""
entities = {}
for nasa in self.config.NASA_REPO:
namenorm = self._normalize_name(nasa)
sensor_type = self._get_sensor_type(nasa)
if self.config.NASA_REPO[nasa]['hass_opts']['writable']:
sensor_type = self.config.NASA_REPO[nasa]['hass_opts']['platform']['type']
else:
sensor_type = self.config.NASA_REPO[nasa]['hass_opts']['default_platform']
entities[namenorm] = {"platform": sensor_type}
device = {
@@ -312,69 +188,47 @@ class MQTTClient:
retain=True)
def auto_discover_hass(self, name):
"""
Automatically discovers and configures Home Assistant entities based on the NASA_REPO configuration.
This function iterates through the NASA_REPO configuration to create and configure entities for Home Assistant.
It determines the type of sensor (binary_sensor or sensor) based on the configuration and sets various attributes
such as unit of measurement, device class, state class, and payloads for binary sensors. It then constructs a device
configuration payload and publishes it to the Home Assistant MQTT discovery topic.
The function performs the following steps:
1. Iterates through the NASA_REPO configuration.
2. Normalizes the name of each NASA_REPO entry.
3. Determines the sensor type (binary_sensor or sensor) based on the 'enum' values.
4. Configures the entity attributes such as unit of measurement, device class, state class, and payloads.
5. Constructs a device configuration payload.
6. Publishes the device configuration to the Home Assistant MQTT discovery topic.
Attributes:
entities (dict): A dictionary to store the configured entities.
device (dict): A dictionary to store the device configuration payload.
Logs:
Logs the constructed device configuration payload for debugging purposes.
Publishes:
Publishes the device configuration payload to the Home Assistant MQTT discovery topic with QoS 2 and retain flag set to True.
"""
entity = {}
namenorm = self._normalize_name(name)
sensor_type = self._get_sensor_type(name)
entity = {
"name": f"{namenorm}",""
"name": f"{namenorm}",
"object_id": f"{self.DEVICE_ID}_{namenorm.lower()}",
"unique_id": f"{self.DEVICE_ID}_{name.lower()}",
"platform": sensor_type,
"force_update": True,
#"expire_after": 86400, # 1 day (24h * 60m * 60s)
"value_template": "{{ value }}",
"value_template": "{{ value }}"
#"value_template": "{{ value if value | length > 0 else 'unavailable' }}",
"state_topic": f"{self.config.MQTT['homeAssistantAutoDiscoverTopic']}/{sensor_type}/{self.DEVICE_ID}_{namenorm.lower()}/state",
}
if sensor_type == "sensor":
if len(self.config.NASA_REPO[name]['unit']) > 0:
entity['unit_of_measurement'] = self.config.NASA_REPO[name]['unit']
if entity['unit_of_measurement'] == "\u00b0C":
entity['device_class'] = "temperature"
elif entity['unit_of_measurement'] == '%':
entity['state_class'] = "measurement"
elif entity['unit_of_measurement'] == 'kW':
entity['device_class'] = "power"
elif entity['unit_of_measurement'] == 'rpm':
entity['state_class'] = "measurement"
elif entity['unit_of_measurement'] == 'bar':
entity['device_class'] = "pressure"
elif entity['unit_of_measurement'] == 'HP':
entity['device_class'] = "power"
elif entity['unit_of_measurement'] == 'hz':
entity['device_class'] = "frequency"
else:
entity['device_class'] = None
if self.config.NASA_REPO[name]['hass_opts']['writable'] and self.config.GENERAL['allowControl']:
sensor_type = self.config.NASA_REPO[name]['hass_opts']['platform']['type']
if sensor_type == 'select':
entity['options'] = self.config.NASA_REPO[name]['hass_opts']['platform']['options']
if sensor_type == 'number':
entity['mode'] = self.config.NASA_REPO[name]['hass_opts']['platform']['mode']
entity['min'] = self.config.NASA_REPO[name]['hass_opts']['platform']['min']
entity['max'] = self.config.NASA_REPO[name]['hass_opts']['platform']['max']
if 'step' in self.config.NASA_REPO[name]['hass_opts']['platform']:
entity['step'] = self.config.NASA_REPO[name]['hass_opts']['platform']['step']
entity['command_topic'] = f"{self.topicPrefix.replace('/', '')}/entity/{name}/set"
entity['optimistic'] = False
else:
entity['payload_on'] = "ON"
entity['payload_off'] = "OFF"
sensor_type = self.config.NASA_REPO[name]['hass_opts']['default_platform']
if 'state_class' in self.config.NASA_REPO[name]:
entity['state_class'] = self.config.NASA_REPO[name]['state_class']
if 'device_class' in self.config.NASA_REPO[name]:
entity['device_class'] = self.config.NASA_REPO[name]['device_class']
if 'unit' in self.config.NASA_REPO[name]['hass_opts']:
entity['unit_of_measurement'] = self.config.NASA_REPO[name]['hass_opts']['unit']
entity['platform'] = sensor_type
entity['state_topic'] = f"{self.config.MQTT['homeAssistantAutoDiscoverTopic']}/{sensor_type}/{self.DEVICE_ID}_{namenorm.lower()}/state"
if 'payload_off' in self.config.NASA_REPO[name]['hass_opts']['platform']:
entity['payload_off'] = "OFF"
if 'payload_on' in self.config.NASA_REPO[name]['hass_opts']['platform']:
entity['payload_on'] = "ON"
if 'state_class' in self.config.NASA_REPO[name]['hass_opts']:
entity['state_class'] = self.config.NASA_REPO[name]['hass_opts']['state_class']
if 'device_class' in self.config.NASA_REPO[name]['hass_opts']:
entity['device_class'] = self.config.NASA_REPO[name]['hass_opts']['device_class']
device = {
"device": self._get_device(),
@@ -407,18 +261,6 @@ class MQTTClient:
}
def _normalize_name(self, name):
"""
Normalize the given name based on the specified naming convention.
If `useCamelCaseTopicNames` is True, the function will:
- Remove any of the following prefixes from the name: 'ENUM_', 'LVAR_', 'NASA_', 'VAR_'.
- Convert the name to CamelCase format.
If `useCamelCaseTopicNames` is False, the function will return the name as is.
Args:
name (str): The name to be normalized.
Returns:
str: The normalized name.
"""
if self.useCamelCaseTopicNames:
prefix_to_remove = ['ENUM_', 'LVAR_', 'NASA_', 'VAR_']
# remove unnecessary prefixes of name
@@ -436,19 +278,3 @@ class MQTTClient:
tmpname = name
return tmpname
def _get_sensor_type(self, name):
"""
return the sensor type of given measurement
Args:
name (str): The name of the measurement.
Returns:
str: The sensor type: sensor or binary_sensor.
"""
sensor_type = "sensor"
if 'enum' in self.config.NASA_REPO[name]:
enum = [*self.config.NASA_REPO[name]['enum'].values()]
if all([en.lower() in ['on', 'off'] for en in enum]):
sensor_type = "binary_sensor"
return sensor_type