Repository navigation
Expand file tree
/
Copy pathpymultical.py
More file actions
executable file
·441 lines (381 loc) · 15.3 KB
/
Copy pathpymultical.py
File metadata and controls
executable file
·441 lines (381 loc) · 15.3 KB
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
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
#!/usr/bin/env python3
# ----------------------------------------------------------------------------
# "THE BEER-WARE LICENSE" (Revision 42):
# <phk@FreeBSD.ORG> wrote this file. As long as you retain this notice you
# can do whatever you want with this stuff. If we meet some day, and you think
# this stuff is worth it, you can buy me a beer in return. Poul-Henning Kamp
# ----------------------------------------------------------------------------
#
# Modified for Domotics and single request.
#
# Modified by Ronald van der Meer, Frank Reijn and Paul Bonnemaijers for the
# Kamstrup Multical 402
#
# Modified by Tim van Werkhoven 20201112 for generic use (e.g. mqtt/influxdb).
# Also pruned superfluous meter reading from script to save meter battery
# life (previous version read all 30 vars and discarded unused data)
#
# Usage: __file__ <ComPort>
#
# Home assistant integration over MQTT:
#
# sensor:
# - platform: mqtt
# name: 'multical_energy'
# unique_id: 'multical_energy'
# state_topic: 'pymultical/heat/value'
# state_class: "total_increasing"
# unit_of_measurement: 'GJ'
# value_template: '{{ value/1000/1000/1000 | round(1) }}'
# device_class: energy
# force_update: true
# expire_after: 3600
from __future__ import print_function
# You need pySerial
import serial
import math
import sys
import datetime
import requests
import paho.mqtt.client as paho
import codecs
import os
import yaml
# Variables
reader = codecs.getreader("utf-8")
debug = 1
multical_var = { # Decimal Number in Command for Kamstrup Multical
0x003C: "Heat Energy (E1)", #60
0x0050: "Power", #80
0x0056: "Temp1", #86
0x0057: "Temp2", #87
0x0059: "Tempdiff", #89
0x004A: "Flow", #74
0x0044: "Volume", #68
0x008D: "MinFlow_M", #141
0x008B: "MaxFlow_M", #139
0x008C: "MinFlowDate_M", #140
0x008A: "MaxFlowDate_M", #138
0x0091: "MinPower_M", #145
0x008F: "MaxPower_M", #143
0x0095: "AvgTemp1_M", #149
0x0096: "AvgTemp2_M", #150
0x0090: "MinPowerDate_M", #144
0x008E: "MaxPowerDate_M", #142
0x007E: "MinFlow_Y", #126
0x007C: "MaxFlow_Y", #124
0x007D: "MinFlowDate_Y", #125
0x007B: "MaxFlowDate_Y", #123
0x0082: "MinPower_Y", #130
0x0080: "MaxPower_Y", #128
0x0092: "AvgTemp1_Y", #146
0x0093: "AvgTemp2_Y", #147
0x0081: "MinPowerDate_Y", #129
0x007F: "MaxPowerDate_Y", #127
0x0061: "Temp1xm3", #97
0x006E: "Temp2xm3", #110
0x0071: "Infoevent", #113
0x03EC: "HourCounter", #1004
}
multical_var_si = { # Decimal Number in Command for Kamstrup Multical
0x003C: 1E+9, # source data in GJ --> J - "Heat Energy (E1)", #60
0x0050: 1E+3, # source data in kW --> W - "Power", #80
0x0056: 1E+0, # source data in Celcius OK - "Temp1", #86
0x0057: 1E+0, # source data in Celcius OK - "Temp2", #87
0x0059: 1E+0, # source data in Celcius OK - "Tempdiff", #89
0x004A: 1E-3/3600, # source data l/hour --> m^3/second- "Flow", #74
0x0044: 1E+0, # source data TBD - "Volume", #68
0x008D: 1E+0, # source data TBD - "MinFlow_M", #141
0x008B: 1E+0, # source data TBD - "MaxFlow_M", #139
0x008C: 1E+0, # source data TBD - "MinFlowDate_M", #140
0x008A: 1E+0, # source data TBD - "MaxFlowDate_M", #138
0x0091: 1E+0, # source data TBD - "MinPower_M", #145
0x008F: 1E+0, # source data TBD - "MaxPower_M", #143
0x0095: 1E+0, # source data TBD - "AvgTemp1_M", #149
0x0096: 1E+0, # source data TBD - "AvgTemp2_M", #150
0x0090: 1E+0, # source data TBD - "MinPowerDate_M", #144
0x008E: 1E+0, # source data TBD - "MaxPowerDate_M", #142
0x007E: 1E+0, # source data TBD - "MinFlow_Y", #126
0x007C: 1E+0, # source data TBD - "MaxFlow_Y", #124
0x007D: 1E+0, # source data TBD - "MinFlowDate_Y", #125
0x007B: 1E+0, # source data TBD - "MaxFlowDate_Y", #123
0x0082: 1E+0, # source data TBD - "MinPower_Y", #130
0x0080: 1E+0, # source data TBD - "MaxPower_Y", #128
0x0092: 1E+0, # source data TBD - "AvgTemp1_Y", #146
0x0093: 1E+0, # source data TBD - "AvgTemp2_Y", #147
0x0081: 1E+0, # source data TBD - "MinPowerDate_Y", #129
0x007F: 1E+0, # source data TBD - "MaxPowerDate_Y", #127
0x0061: 1E+0, # source data TBD - "Temp1xm3", #97
0x006E: 1E+0, # source data TBD - "Temp2xm3", #110
0x0071: 1E+0, # source data TBD - "Infoevent", #113
0x03EC: 1E+0, # source data TBD - "HourCounter", #1004
}
#######################################################################
# Units, provided by Erik Jensen
units = {
0: '', 1: 'Wh', 2: 'kWh', 3: 'MWh', 4: 'GWh', 5: 'j', 6: 'kj', 7: 'Mj',
8: 'Gj', 9: 'Cal', 10: 'kCal', 11: 'Mcal', 12: 'Gcal', 13: 'varh',
14: 'kvarh', 15: 'Mvarh', 16: 'Gvarh', 17: 'VAh', 18: 'kVAh',
19: 'MVAh', 20: 'GVAh', 21: 'kW', 22: 'kW', 23: 'MW', 24: 'GW',
25: 'kvar', 26: 'kvar', 27: 'Mvar', 28: 'Gvar', 29: 'VA', 30: 'kVA',
31: 'MVA', 32: 'GVA', 33: 'V', 34: 'A', 35: 'kV',36: 'kA', 37: 'C',
38: 'K', 39: 'l', 40: 'm3', 41: 'l/h', 42: 'm3/h', 43: 'm3xC',
44: 'ton', 45: 'ton/h', 46: 'h', 47: 'hh:mm:ss', 48: 'yy:mm:dd',
49: 'yyyy:mm:dd', 50: 'mm:dd', 51: '', 52: 'bar', 53: 'RTC',
54: 'ASCII', 55: 'm3 x 10', 56: 'ton x 10', 57: 'GJ x 10',
58: 'minutes', 59: 'Bitfield', 60: 's', 61: 'ms', 62: 'days',
63: 'RTC-Q', 64: 'Datetime'
}
#######################################################################
# Kamstrup uses the "true" CCITT CRC-16
#
def crc_1021(message):
poly = 0x1021
reg = 0x0000
for byte in message:
mask = 0x80
while(mask > 0):
reg<<=1
if byte & mask:
reg |= 1
mask>>=1
if reg & 0x10000:
reg &= 0xffff
reg ^= poly
return reg
#######################################################################
# Byte values which must be escaped before transmission
#
escapes = {
0x06: True,
0x0d: True,
0x1b: True,
0x40: True,
0x80: True,
}
#######################################################################
# And here we go....
#
class kamstrup(object):
def __init__(self, serial_port):
self.debug_fd = open("/tmp/_kamstrup", "a")
self.debug_fd.write("\n\nStart\n")
self.debug_id = None
self.ser = serial.Serial(
port = serial_port,
baudrate = 1200,
timeout = 5.0,
bytesize = serial.EIGHTBITS,
parity = serial.PARITY_NONE,
stopbits = serial.STOPBITS_TWO)
# xonxoff = 0,
# rtscts = 0)
# timeout = 20
def debug(self, dir, b):
for i in b:
if dir != self.debug_id:
if self.debug_id != None:
self.debug_fd.write("\n")
self.debug_fd.write(dir + "\t")
self.debug_id = dir
self.debug_fd.write(" %02x " % i)
self.debug_fd.flush()
def debug_msg(self, msg):
if self.debug_id != None:
self.debug_fd.write("\n")
self.debug_id = "Msg"
self.debug_fd.write("Msg\t" + msg)
self.debug_fd.flush()
def wr(self, b):
b = bytearray(b)
self.debug("Wr", b);
self.ser.write(b)
def rd(self):
a = self.ser.read(1)
if len(a) == 0:
self.debug_msg("Rx Timeout")
return None
b = bytearray(a)[0]
self.debug("Rd", bytearray((b,)));
return b
def send(self, pfx, msg):
b = bytearray(msg)
b.append(0)
b.append(0)
c = crc_1021(b)
b[-2] = c >> 8
b[-1] = c & 0xff
c = bytearray()
c.append(pfx)
for i in b:
if i in escapes:
c.append(0x1b)
c.append(i ^ 0xff)
else:
c.append(i)
c.append(0x0d)
self.wr(c)
def recv(self):
b = bytearray()
while True:
d = self.rd()
if d == None:
return None
if d == 0x40:
b = bytearray()
b.append(d)
if d == 0x0d:
break
c = bytearray()
i = 1;
while i < len(b) - 1:
if b[i] == 0x1b:
v = b[i + 1] ^ 0xff
if v not in escapes:
self.debug_msg(
"Missing Escape %02x" % v)
c.append(v)
i += 2
else:
c.append(b[i])
i += 1
if crc_1021(c):
self.debug_msg("CRC error")
return c[:-2]
def readvar(self, nbr):
# I wouldn't be surprised if you can ask for more than
# one variable at the time, given that the length is
# encoded in the response. Havn't tried.
self.send(0x80, (0x3f, 0x10, 0x01, nbr >> 8, nbr & 0xff))
b = self.recv()
if b == None:
return (None, None)
if b[0] != 0x3f or b[1] != 0x10:
return (None, None)
if b[2] != nbr >> 8 or b[3] != nbr & 0xff:
return (None, None)
if b[4] in units:
u = units[b[4]]
else:
u = None
# Decode the mantissa
x = 0
for i in range(0,b[5]):
x <<= 8
x |= b[i + 7]
# Decode the exponent
i = b[6] & 0x3f
if b[6] & 0x40:
i = -i
i = math.pow(10,i)
if b[6] & 0x80:
i = -i
x *= i
if False:
# Debug print
s = ""
for i in b[:4]:
s += " %02x" % i
s += " |"
for i in b[4:7]:
s += " %02x" % i
s += " |"
for i in b[7:]:
s += " %02x" % i
print(s, "=", x, units[b[4]])
return (x, u)
def influxdb_update(value, auth, req_url='http://localhost:8086/write?db=mydb&precision=s', querybase="energy,quantity=heat,source=multical,type=consumption value="):
"""
Push update to influxdb with second precision
"""
# Something like post_data = "energy,type=heat,device=landisgyr value=10"
# Alternatively, like post_data = "energy landisgyr=10"
post_data = "{}{:d}".format(querybase, int(value))
if debug > 0:
print("Pushing data '{}' to influxdb".format(post_data))
try:
httpresponse = requests.post(req_url, data=post_data, verify=False, timeout=5, auth=(INFLUX_USER, INFLUX_PASSWD))
except Exception as inst:
print("Could not update meter reading: {}".format(inst))
pass
def mqtt_update(client, topic, payload):
"""
Publish to mqtt
http://www.steves-internet-guide.com/publishing-messages-mqtt-client/
https://pypi.org/project/paho-mqtt/#publishing
"""
# broker="192.168.1.184"
# port=1883
try:
ret = client.publish(topic, payload)
if debug > 0:
print('Pushed {} to topic {}'.format(payload,topic))
except:
print('Could not publish mqtt value')
if __name__ == "__main__":
# Load config from YAML, should look something like:
# pymultical:
# comport: "/dev/serial/by-id/usb-FTDI_FT232R_USB_UART_FF00F0F0-if00-port0"
# index: "60,80,86,87,74"
# mqqt_server_host: "localhost"
# mqqt_client_username: "pymultical"
# mqqt_client_passwd: "password"
# influx_write_uri: "http://localhost:8086/write?db=mydb&precision=s"
with open(os.path.join(sys.path[0], "secrets.yaml"), 'r') as stream:
try:
data = yaml.safe_load(stream)
comport = data['pymultical']['comport']
index = data['pymultical']['index']
MQTT_SERVER_HOST = data['pymultical']['mqqt_server_host']
MQTT_CLIENT_USERNAME = data['pymultical']['mqqt_client_username']
MQTT_CLIENT_PASSWD = data['pymultical']['mqqt_client_passwd']
INFLUX_WRITE_URI = data['pymultical']['influx_write_uri']
# Influxdb settings URI
INFLUX_USER = data['influx_username']
INFLUX_PASSWD = data['influx_password']
except yaml.YAMLError as exc:
raise yaml.YAMLError('Could not load config from yaml file: {}'.format(exc))
index = index.split(',')
if debug > 0:
print("Parameter specified: ")
for i in index:
print("+ " + i)
multical = kamstrup( comport )
# heat_timestamp = datetime.datetime.strftime(datetime.datetime.today(), "%Y-%m-%d %H:%M:%S" )
# Setup mqtt client
mqtt_client = paho.Client(client_id=MQTT_CLIENT_USERNAME)
mqtt_client.username_pw_set(MQTT_CLIENT_USERNAME, MQTT_CLIENT_PASSWD)
try:
mqtt_client.connect(MQTT_SERVER_HOST,int(1883))
if debug > 0:
print('Connected to mqtt broker')
except:
print('Could not connect to mqtt broker')
for i in index:
print('Loop over requested measurements, read each, then push: {}'.format(i))
ii = int(i)
x,u = multical.readvar(ii)
# Convert to SI units
xsi = x * multical_var_si[ii]
print("Metric: {}, Raw value: {}, Unit: {}, SI: {}".format(multical_var[ii], x, xsi, u))
# Push syntax depends on sensor.
# Heat energy
if ii == 60:
influxdb_update(xsi, auth=(INFLUX_USER,INFLUX_PASSWD), req_url=INFLUX_WRITE_URI, querybase="energyv3,quantity=heat,source=multical,type=consumption value=")
mqtt_update(mqtt_client, "pymultical/heat/value", xsi)
# Power
elif ii == 80:
influxdb_update(xsi, auth=(INFLUX_USER,INFLUX_PASSWD), req_url=INFLUX_WRITE_URI, querybase="powerv3,quantity=heat,source=multical,type=consumption value=")
mqtt_update(mqtt_client, "pymultical/power/value", xsi)
# Temp1
elif ii == 86:
influxdb_update(xsi, auth=(INFLUX_USER,INFLUX_PASSWD), req_url=INFLUX_WRITE_URI, querybase="systemv3,quantity=temp1,source=multical value=")
mqtt_update(mqtt_client, "pymultical/temp1/value", xsi)
# Temp2
elif ii == 87:
influxdb_update(xsi, auth=(INFLUX_USER,INFLUX_PASSWD), req_url=INFLUX_WRITE_URI, querybase="systemv3,quantity=temp2,source=multical value=")
mqtt_update(mqtt_client, "pymultical/temp2/value", xsi)
# Flow
elif ii == 74:
influxdb_update(xsi, auth=(INFLUX_USER,INFLUX_PASSWD), req_url=INFLUX_WRITE_URI, querybase="systemv3,quantity=flow,source=multical value=")
mqtt_update(mqtt_client, "pymultical/flow/value", xsi)