diff --git a/amr2mqtt/rootfs/amr2mqtt/amr2mqtt.py b/amr2mqtt/rootfs/amr2mqtt/amr2mqtt.py index b9d69fd..68ab38b 100644 --- a/amr2mqtt/rootfs/amr2mqtt/amr2mqtt.py +++ b/amr2mqtt/rootfs/amr2mqtt/amr2mqtt.py @@ -30,7 +30,8 @@ IDM_CONSUMPTION_FIELD = "LastConsumptionCount" NETIDM_CONSUMPTION_FIELD = "LastConsumptionNet" SCMPLUS_ID_FIELD = "EndpointID" -LAST_SEEN_ATTR = "'last_seen': value_json.last_seen" +LAST_SEEN_ATTR = "last_seen" +PROTOCOL_ATTR = "Protocol" ALL_IDM = [ "Preamble", "PacketLength", @@ -188,8 +189,6 @@ def create_mqtt_client(): def create_interval_sensor(meter_id, meter, device_name, device_id): """Create discovery message for interval consumption sensor.""" - last_seen_attr = f"{LAST_SEEN_ATTR}," if settings.LAST_SEEN_ENABLED else "" - return set_consumption_details( payload={ "enabled_by_default": True, @@ -201,7 +200,6 @@ def create_interval_sensor(meter_id, meter, device_name, device_id): "{{ {" f"'{INTERVAL_FIELD}': value_json.{INTERVAL_FIELD}," f"'{INTERVAL_START_FIELD}': value_json.{INTERVAL_START_FIELD}," - f"{last_seen_attr}" f"'last_reset': value_json.{INTERVAL_START_FIELD}" "} | tojson }}" ), @@ -242,11 +240,6 @@ def create_sensor(attribute, device_name, device_id, enabled=True, category=None if category: sensor["entity_category"] = category - if settings.LAST_SEEN_ENABLED: - sensor[ - "json_attributes_template" - ] = f"{{{{ {{ {LAST_SEEN_ATTR} }} | tojson }}}}" - return sensor @@ -305,6 +298,22 @@ def send_discovery_messages(): payload=consumption, ) + if settings.LAST_SEEN_ENABLED: + last_seen = create_sensor( + attribute=LAST_SEEN_ATTR, + device_name=device_name, + device_id=device_id, + enabled=False, + category=CATEGORY_DIAGNOSTIC, + ) + last_seen["device_class"] = "timestamp" + publish_sensor_discovery( + meter_id=meter_id, + device=device, + attribute=LAST_SEEN_ATTR, + payload=last_seen, + ) + # IDM meters have interval consumption if protocol in ["idm", "netidm"]: publish_sensor_discovery( @@ -467,11 +476,11 @@ def main_loop(): else: last_seen = math.floor(time.time()) - amr_message["last_seen"] = last_seen + amr_message[LAST_SEEN_ATTR] = last_seen # If in debugging mode, add the protocol to the message if settings.WATCHED_PROTOCOLS == "all": - amr_message["Protocol"] = msg_type + amr_message[PROTOCOL_ATTR] = msg_type json_message = json.dumps(amr_message) logging.debug(