Skip to content

Instantly share code, notes, and snippets.

@wizardofzos
Created May 23, 2020 19:39
Show Gist options
  • Save wizardofzos/9531ef20c565804bba9cf3b98e633e2f to your computer and use it in GitHub Desktop.
Save wizardofzos/9531ef20c565804bba9cf3b98e633e2f to your computer and use it in GitHub Desktop.
Get metrics from smart meter
# metrics.py - getting smart meter data via python
# based on http://gejanssen.com/howto/Slimme-meter-uitlezen
# and http://domoticx.com/p1-poort-slimme-meter-hardware/
import sys
import serial
import json
def parseLine(l):
if len(l) > 0:
parts = l.split('(')
key = parts[0]
try:
value = parts[1][:-1]
except:
value = "0"
# see if value has unit
vparts = value.split('*')
v = vparts[0]
keys = {}
keys["0-0:96.1.1"] = "equipmentIdentifier"
keys["0-0:96.7.9"] = "longPowerFailures"
keys["0-0:96.7.21"] = "powerFailures"
keys["1-0:1.8.1"] = "kWhConsumedLowTariff" # lowRateElectrical
keys["1-0:1.8.2"] = "kWhConsumedHighTariff" # highRateElectrical
keys["1-0:2.8.1"] = "kWhDeliveredLowTariff"
keys["1-0:2.8.2"] = "kWhDeliveredLowTariff"
keys["0-0:96.14.0"] = "currentTariffIndicator"
keys["1-0:1.7.0"] = "wattsConsumed"
keys["1-0:2.7.0"] = "wattsDelivered"
keys["0-0:1.0.0"] = "dateTime"
keys["1-0:21.7.0"] = "wattsConsumedL1+P"
keys["1-0:22.7.0"] = "wattsConsumedL1-P"
keys["1-0:41.7.0"] = "wattsConsumedL2+P"
keys["1-0:42.7.0"] = "wattsConsumedL2-P"
keys["1-0:61.7.0"] = "wattsConsumedL3+P"
keys["1-0:62.7.0"] = "wattsConsumedL3-P"
keys["0-1:24.2.1"] = "gasM3Consumed"
try:
key = keys[key]
if key == "dateTime":
v = "20%s-%s-%s %s:%s:%s" % (v[0:2],v[2:4], v[4:6], v[6:8], v[8:10], v[10:12])
else:
if key != "equipmentIdentifier" and key != "gasM3Consumed":
v = float(v)
if key == "gasM3Consumed":
# This field has it's own value for dateTimeOfLastMeasurement, but we don't care, we take the current values time
gp = l.split(')(')
v = float(gp[1].split('*')[0][:-1])
return (key, v)
except:
return (0,0)
#Set COM port config
ser = serial.Serial()
ser.baudrate = 112500
ser.bytesize=serial.SEVENBITS
ser.parity=serial.PARITY_EVEN
ser.stopbits=serial.STOPBITS_ONE
ser.xonxoff=0
ser.rtscts=0
ser.timeout=20
ser.port="/dev/ttyUSB0"
#Open COM port
try:
ser.open()
except:
sys.exit ("Cannot open %s. Abort! Abort!" % ser.name)
resdict = {}
goon = True
while goon:
p1_line=''
try:
p1_raw = ser.readline()
except:
sys.exit ("Can't read from serial port")
p1_str=str(p1_raw)
p1_line=p1_str.strip()
if len(p1_line) > 0:
if p1_line[0] == "!":
goon = False
else:
k,v = parseLine(p1_line)
if k != 0:
resdict[k] = v
print json.dumps(resdict,sort_keys=True)
try:
ser.close()
except:
sys.exit ("Error closing port %s" % ser.name )
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment