Skip to content

Commit 38af094

Browse files
committed
Add a function to support set timestamp in the payload
1 parent ae286a1 commit 38af094

File tree

2 files changed

+18
-2
lines changed

2 files changed

+18
-2
lines changed

config/devices.toml

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -35,6 +35,8 @@ decimalshiftright=0
3535
input=false
3636
datatype="float"
3737
measurementmapping.templatestring="{\"Test\":{\"Float32\":%% }}"
38+
#timestamp and time are also supported in the template
39+
#measurementmapping.templatestring="{\"Test\":{\"Float32\":%% }, \"timestamp\":\"\"}"
3840

3941

4042
[[device.coils]]

tedge_modbus/reader/mapper.py

Lines changed: 16 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -53,6 +53,20 @@ def __init__(self, device):
5353
self.device = device
5454
self.data = {"hr": {}, "ir": {}, "co": {}, "di": {}}
5555

56+
def _process_template(self, template_string, value):
57+
"""Process template string with value and timestamp replacements"""
58+
# Replace the main value placeholder
59+
data = template_string.replace("%%", str(value))
60+
61+
# Generate current timestamp in ISO format
62+
current_timestamp = datetime.now(timezone.utc).isoformat()
63+
64+
# Replace timestamp placeholders
65+
data = data.replace('"timestamp":""', f'"timestamp":"{current_timestamp}"')
66+
data = data.replace('"time":""', f'"time":"{current_timestamp}"')
67+
68+
return data
69+
5670
def validate(self, register_def):
5771
"""Validate definition"""
5872
start_bit = register_def["startbit"]
@@ -141,8 +155,8 @@ def map_register(
141155
has_changed = last_value != scaled_value
142156

143157
if not on_change or last_value is None or has_changed:
144-
data = register_def["measurementmapping"]["templatestring"].replace(
145-
"%%", str(scaled_value)
158+
data = self._process_template(
159+
register_def["measurementmapping"]["templatestring"], scaled_value
146160
)
147161
if register_def["measurementmapping"].get(
148162
"combinemeasurements", device_combine_measurements

0 commit comments

Comments
 (0)