From 38af094126ae331ca68b7c41a73df3232017e872 Mon Sep 17 00:00:00 2001 From: zhongys-c8y Date: Fri, 24 Oct 2025 10:48:00 +0200 Subject: [PATCH] Add a function to support set timestamp in the payload --- config/devices.toml | 2 ++ tedge_modbus/reader/mapper.py | 18 ++++++++++++++++-- 2 files changed, 18 insertions(+), 2 deletions(-) diff --git a/config/devices.toml b/config/devices.toml index 8328558..f598044 100644 --- a/config/devices.toml +++ b/config/devices.toml @@ -35,6 +35,8 @@ decimalshiftright=0 input=false datatype="float" measurementmapping.templatestring="{\"Test\":{\"Float32\":%% }}" +#timestamp and time are also supported in the template +#measurementmapping.templatestring="{\"Test\":{\"Float32\":%% }, \"timestamp\":\"\"}" [[device.coils]] diff --git a/tedge_modbus/reader/mapper.py b/tedge_modbus/reader/mapper.py index 06b09fd..4d1f356 100644 --- a/tedge_modbus/reader/mapper.py +++ b/tedge_modbus/reader/mapper.py @@ -53,6 +53,20 @@ def __init__(self, device): self.device = device self.data = {"hr": {}, "ir": {}, "co": {}, "di": {}} + def _process_template(self, template_string, value): + """Process template string with value and timestamp replacements""" + # Replace the main value placeholder + data = template_string.replace("%%", str(value)) + + # Generate current timestamp in ISO format + current_timestamp = datetime.now(timezone.utc).isoformat() + + # Replace timestamp placeholders + data = data.replace('"timestamp":""', f'"timestamp":"{current_timestamp}"') + data = data.replace('"time":""', f'"time":"{current_timestamp}"') + + return data + def validate(self, register_def): """Validate definition""" start_bit = register_def["startbit"] @@ -141,8 +155,8 @@ def map_register( has_changed = last_value != scaled_value if not on_change or last_value is None or has_changed: - data = register_def["measurementmapping"]["templatestring"].replace( - "%%", str(scaled_value) + data = self._process_template( + register_def["measurementmapping"]["templatestring"], scaled_value ) if register_def["measurementmapping"].get( "combinemeasurements", device_combine_measurements