Skip to content

Commit

Permalink
last_seen as sensor not attribute
Browse files Browse the repository at this point in the history
  • Loading branch information
mdegat01 committed Apr 27, 2022
1 parent 78453f9 commit 153db7b
Showing 1 changed file with 20 additions and 11 deletions.
31 changes: 20 additions & 11 deletions amr2mqtt/rootfs/amr2mqtt/amr2mqtt.py
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand Down Expand Up @@ -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,
Expand All @@ -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 }}"
),
Expand Down Expand Up @@ -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


Expand Down Expand Up @@ -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(
Expand Down Expand Up @@ -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(
Expand Down

0 comments on commit 153db7b

Please sign in to comment.