-
Notifications
You must be signed in to change notification settings - Fork 3
/
sml_decoder.py
executable file
·146 lines (124 loc) · 4.18 KB
/
sml_decoder.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
#!/usr/bin/env python3
import binascii
from smllib.sml_frame import SmlFrame
from smllib.const import OBIS_NAMES, UNITS
from pprint import pprint
file = "test-data.txt"
class TasmotaSMLParser:
def __init__(self):
self.obis_decoded = []
self.obis_errors = []
self.parse_errors = []
def parse_input(self, input):
"""Parse a line into a frame"""
if " : 77 " in input.strip():
# Remove the spaces and return a bytestring
try:
frame = binascii.a2b_hex("".join((input.split(" : ", 1)[1]).split()))
except binascii.Error:
self.parse_errors.append(input)
return
elif input.startswith("77 "):
try:
frame = binascii.a2b_hex("".join(input.split()))
except binascii.Error:
self.parse_errors.append(input)
return
else:
self.parse_errors.append(input)
return
return frame
def decode_frame(self, frame):
f = SmlFrame(frame)
try:
msgs = f.get_obis()
if len(msgs) == 0:
return False
except Exception as e:
self.obis_errors.append(
{"frame": frame, "hex": binascii.b2a_hex(frame, b" "), "msg": e}
)
return None
return msgs
def decode_messages(self, input):
messages = []
for line in input:
frame = self.parse_input(line)
if frame is None:
continue
msgs = self.decode_frame(frame)
if msgs in [None, False]:
continue
for msg in msgs:
if msg.obis in self.obis_decoded:
continue
else:
self.obis_decoded.append(msg.obis)
messages.append(msg)
return messages
def get_message_details(self, msg):
name = OBIS_NAMES.get(msg.obis, "Unbekannter Datentyp")
unit = UNITS.get(msg.unit, "Unbekannte Einheit")
mqtt_topic = (
"_".join(OBIS_NAMES.get(msg.obis, "Unbekanntes MQTT Topic").split())
.replace("/", "-")
.lower()
)
try:
precision = msg.scaler * -1
except TypeError:
precision = 0
try:
human_readable = (
f"{round(msg.value * pow(10, msg.scaler), precision)}{unit} ({name})"
)
except TypeError:
try:
human_readable = f"{msg.value}{unit} ({name})"
except:
try:
human_readable = f"{msg.value}{unit}"
except:
try:
human_readable = f"{msg.value}"
except:
human_readable = ""
data = {
"obis": msg.obis,
"obis_code": msg.obis.obis_code,
"obis_short": msg.obis.obis_short,
"name": name,
"unit": unit,
"topic": mqtt_topic,
"precision": precision,
"value": msg.value,
"status": msg.status,
"val_time": msg.val_time,
"unit_raw": msg.unit,
"scaler": msg.scaler,
"value_signature": msg.value_signature,
"human_readable": human_readable,
}
return data
def build_meter_def(self, msg):
data = self.get_message_details(msg)
return f"1,7707{data['obis'].upper()}@1,{data['name']},{data['unit']},{data['topic']},{data['precision']}"
def pretty_print(self, msg):
print(msg.format_msg())
def main():
tas = TasmotaSMLParser()
msgs = []
with open(file, "r") as fp:
msgs = tas.decode_messages(fp.read().splitlines())
for msg in msgs:
tas.pretty_print(msg)
details = tas.get_message_details(msg)
print("Tasmota SML Script meter definition:")
print(tas.build_meter_def(msg))
print(80 * "#")
if len(tas.obis_errors) > 0:
pprint(tas.obis_errors)
if len(tas.parse_errors) > 0:
pprint(tas.parse_errors)
if __name__ == "__main__":
main()