Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add option for last_seen #54

Merged
merged 1 commit into from
Jan 18, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions amr2mqtt/DOCS.md
Original file line number Diff line number Diff line change
Expand Up @@ -212,6 +212,12 @@ Client ID to use when connecting to the MQTT broker.
By default, the topics of all MQTT messages begins with `amr2mqtt/{meter_ID}`.
If you set this option then the topics will begin with `{mqtt.base_topic}/{meter_id}`.

### Option: `last_seen`

Add `last_seen` field to each message with the current time in the specified format.
Options are: `ISO_8601`, `ISO_8601_local`, and `epoch`. Disabled if omitted. Useful
for detecting issues when meter normally reports in on a consistent interval.

### Option: `home_assistant_discovery_enabled`

Set to `false` to disable the add-on from sending discovery messages for the
Expand Down
1 change: 1 addition & 0 deletions amr2mqtt/config.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -43,3 +43,4 @@ schema:
log_level: list(trace|debug|info|notice|warning|error|fatal)?
home_assistant_discovery_enabled: bool?
home_assistant_discovery_prefix: match(^[^+#]{1,65535}$)?
last_seen: list(ISO_8601|ISO_8601_local|epoch)?
29 changes: 28 additions & 1 deletion amr2mqtt/rootfs/amr2mqtt/amr2mqtt.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,14 +5,15 @@
is a watched one, processes its reading using settings first.

"""
from datetime import timedelta
from datetime import timedelta, datetime, timezone
import logging
import subprocess
import signal
import sys
import time
import json
import re
import math
import paho.mqtt.client as mqtt
import settings
from dateutil import parser
Expand All @@ -29,6 +30,7 @@
IDM_CONSUMPTION_FIELD = "LastConsumptionCount"
NETIDM_CONSUMPTION_FIELD = "LastConsumptionNet"
SCMPLUS_ID_FIELD = "EndpointID"
LAST_SEEN_ATTR = "'last_seen': value_json.last_seen"
ALL_IDM = [
"Preamble",
"PacketLength",
Expand Down Expand Up @@ -185,6 +187,8 @@ 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 @@ -196,6 +200,7 @@ 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 @@ -236,6 +241,11 @@ 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 @@ -440,6 +450,23 @@ def main_loop():
else:
continue

# Add last seen if in use
if settings.LAST_SEEN_ENABLED:
if settings.LAST_SEEN_FORMAT == "ISO_8601":
last_seen = (
datetime.now().replace(microsecond=0).astimezone().isoformat()
)
elif settings.LAST_SEEN_FORMAT == "ISO_8601_local":
last_seen = (
datetime.utcnow()
.replace(microsecond=0, tzinfo=timezone.utc)
.isoformat()
)
else:
last_seen = math.floor(time.time())

amr_message["last_seen"] = last_seen

# If in debugging mode, add the protocol to the message
if settings.WATCHED_PROTOCOLS == "all":
amr_message["Protocol"] = msg_type
Expand Down
4 changes: 4 additions & 0 deletions amr2mqtt/rootfs/amr2mqtt/settings.py
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,10 @@ def make_meters_map(meters, meter):
MQTT_BASE_TOPIC = base_topic if bool(base_topic) else "amr2mqtt"
MQTT_AVAILABILTY_TOPIC = f"{MQTT_BASE_TOPIC}/bridge/state"

# Using last seen
LAST_SEEN_FORMAT = os.environ.get("LAST_SEEN")
LAST_SEEN_ENABLED = LAST_SEEN_FORMAT != "disable"

# Set up logging
EV_TO_LOG_LEVEL = {
"DEBUG": logging.DEBUG,
Expand Down
3 changes: 3 additions & 0 deletions amr2mqtt/rootfs/etc/services.d/amr2mqtt/run
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,9 @@ elif bashio::config.exists 'home_assistant_discovery_prefix'; then
export "HA_DISCOVERY_TOPIC=$(bashio::config 'home_assistant_discovery_prefix')"
fi

# --- OTHER SETTINGS ---
export "LAST_SEEN=$(bashio::config 'last_seen' 'disable')"

# --- SET LOG LEVEL ---
case "$(bashio::config 'log_level')" in \
trace) ;& \
Expand Down