Skip to content

Python

With Python you can read the WattWächter TTL across platforms – most easily directly on a Raspberry Pi via its GPIO UART. For Mac, Linux and Windows without GPIO pins, the WattWächter USB is the better choice; for testing, a USB-to-TTL adapter works too.

Most modern meters send their data in the SML format (Smart Message Language) at 9600 baud, 8N1. We use pyserial to read the serial interface and smllib to decode the telegrams.

How the communication works

Most meters send their telegram on their own at regular intervals (push) – for those, the receive line (green / RXD) is sufficient for read-out. The TX line (white, yellow on the older TTL) is only needed for the remaining meters that have to be requested to send — marked with footnote ⁴ in the Supported meters table. Which wire goes where is shown in the wiring diagram under Connection → Wiring.

Which meters have to be requested to send?

The Supported meters table shows it: meters marked with footnote ⁴ only send after a request (IEC 62056-21, "D0") — example script 2 reads them. Most others send SML on their own; example script 1 is meant for them.

Some meters send D0 on their own, without a request (e.g. EasyMeter Q3D, Hager EHZ161/EHZ361). Neither script fits them exactly: script 1 expects SML, script 2 always sends a request first. The value lines are the same, though — with your meter's interface settings and without the request, script 2 is easy to adapt.

Meter prerequisites

For the meter to send the full instantaneous values (power, phases), the PIN usually has to be disabled and the extended info mode (Inf → On) enabled. You obtain the PIN from your grid operator. How to do that is described under Meter preparation.


Wiring

On a Raspberry Pi you plug the WattWächter TTL straight onto the pin header. Wiring, enabling the serial interface and a first test are described on the Raspberry Pi page. For testing on Mac, Linux or Windows, a standard USB-to-TTL adapter (e.g. CP2102, FT232, CH340) works too, powered with 3.3 V.


Installation

pip install pyserial smllib

Raspberry Pi OS Bookworm and later

There, pip refuses to install into the system Python ("externally-managed-environment"). Create a virtual environment once and run the scripts with its Python:

python3 -m venv ~/meter
~/meter/bin/pip install pyserial smllib
~/meter/bin/python script.py

Example script 1: SML meters

import serial
from smllib import SmlStreamReader
from smllib.errors import CrcError

# --- Serial interface -------------------------------------------------------
# Raspberry Pi (GPIO UART):  /dev/serial0
# USB-to-TTL adapter (Linux): /dev/ttyUSB0
# macOS:                     /dev/tty.usbserial-XXXX
# Windows:                   COM3
PORT = "/dev/serial0"

# OBIS codes we are interested in (short form -> label)
OBIS = {
    "1.8.0":  "Import",   # Wh, drawn from grid
    "2.8.0":  "Export",   # Wh, fed into grid
    "16.7.0": "Power",    # W, current active power (signed)
}

ser = serial.Serial(PORT, baudrate=9600, bytesize=8,
                    parity="N", stopbits=1, timeout=2)
stream = SmlStreamReader()

print(f"Reading WattWächter TTL on {PORT} ...")
while True:
    data = ser.read(ser.in_waiting or 1)
    if not data:
        continue

    stream.add(data)
    try:
        frame = stream.get_frame()
    except CrcError:
        continue   # skip a corrupted telegram
    if frame is None:
        continue   # telegram not complete yet

    for entry in frame.get_obis():
        name = OBIS.get(entry.obis.obis_short)
        if name is None:
            continue
        value = entry.get_value()          # already scaled (value × 10^scaler)
        if entry.obis.obis_short in ("1.8.0", "2.8.0"):
            print(f"{name:8s}: {value / 1000:.3f} kWh")
        else:
            print(f"{name:8s}: {value:.0f} W")
    print("-" * 30)

Example output:

Reading WattWächter TTL on /dev/serial0 ...
Import  : 12345.678 kWh
Export  : 4321.000 kWh
Power   : 437 W
------------------------------

Reading additional values

Extend the OBIS dictionary with more codes (e.g. 36.7.0, 56.7.0, 76.7.0 for per-phase power, or 32.7.0, 52.7.0, 72.7.0 for per-phase voltage). entry.get_value() returns the value already correctly scaled, entry.unit contains the unit code. An overview of common OBIS codes can be found under Additional OBIS codes.


Example script 2: meters that need a request (IEC 62056-21)

Older meters with the IEC 62056-21 mode C protocol ("D0", see the table above) only send when asked. For this, the TX wire must be connected as well (white, yellow on the older TTL). The script works the same way as the meter scripts of the WattWächter Tasmota:

  1. Send the request /?! at 300 baud, 7E1 (7 data bits, even parity, 1 stop bit).
  2. The meter answers with its identification, e.g. /LGZ5ZMD3104407.B32. The fifth character (5) names the baud rate at which it can send its data (5 = 9600 baud).
  3. Acknowledge with ACK 0 Z 0 and switch to that baud rate.
  4. The meter sends its values as text lines like 1.8.0(012345.678*kWh), followed by a line ! at the end.

This script only needs pyserial (pip install pyserial).

import re
import time
import serial

# --- Settings ---------------------------------------------------------------
PORT = "/dev/serial0"   # as in script 1: /dev/ttyUSB0, /dev/tty.usbserial-XXXX, COM3 ...
INTERVAL = 30           # seconds between two requests
KEEP_300 = False        # True: always read at 300 baud (if the switch fails)

# Baud rate character in the meter identification -> baud rate (IEC 62056-21, mode C)
BAUD = {"0": 300, "1": 600, "2": 1200, "3": 2400, "4": 4800, "5": 9600, "6": 19200}

# Known codes get a name, all others are printed with their code
NAMES = {
    "1.8.0":  "Import",
    "2.8.0":  "Export",
    "16.7.0": "Power",
    "C.1.0":  "Meter number",
}

# Data lines like  1.8.0(012345.678*kWh)  or  1-0:1.8.0*255(012345.678*kWh)
LINE = re.compile(r"^(?:\d+-\d+:)?([0-9A-Z]+(?:\.[0-9A-Z]+)+)(?:\*\d+)?\(([^)*]*)(?:\*([^)]*))?\)")


def read_meter(ser):
    """Polls the meter once and returns its identification and values."""
    # 1. Send the request at 300 baud
    ser.baudrate = 300
    ser.reset_input_buffer()
    ser.write(b"/?!\r\n")
    ser.flush()

    # 2. Read the identification, e.g. "/LGZ5ZMD3104407.B32" - the 5th character names the baud rate
    ident = ser.readline().decode("ascii", "replace").strip()
    if ident == "/?!":                      # skip the echo of our own request
        ident = ser.readline().decode("ascii", "replace").strip()
    if not ident.startswith("/") or len(ident) < 5 or ident[4] not in BAUD:
        raise RuntimeError(f"No valid answer from the meter: {ident!r}")
    z = "0" if KEEP_300 else ident[4]

    # 3. Acknowledge (ACK 0 Z 0) and switch to the new baud rate
    ack = b"\x06" + b"0" + z.encode() + b"0\r\n"
    start = time.monotonic()
    ser.write(ack)
    ser.flush()
    # Switch as soon as the ACK is out (6 characters x 10 bits at 300 baud = 200 ms).
    # The meter may start sending 200 ms later (20 ms if the 3rd ID letter is lowercase).
    time.sleep(max(0, start + len(ack) * 10 / 300 + 0.01 - time.monotonic()))
    ser.baudrate = BAUD[z]

    # 4. Read the data block until the end line "!" arrives
    values = {}
    block = None                            # bytes after STX, for the checksum (BCC)
    while True:
        line = ser.readline()
        if not line:
            raise RuntimeError("Timeout while reading the data block")
        if block is None:                   # ignore everything before STX (0x02)
            if b"\x02" not in line:
                continue
            line = line[line.index(b"\x02") + 1:]
            block = b""
        block += line
        text = line.decode("ascii", "replace").strip()
        if text.startswith("!"):
            tail = ser.read(2)              # ETX + BCC
            bcc = 0
            for b in block + tail[:1]:
                bcc ^= b
            if len(tail) < 2 or tail[0] != 0x03 or tail[1] != bcc:
                raise RuntimeError("Checksum (BCC) wrong - data block incomplete")
            return ident, values
        match = LINE.match(text)
        if match:
            code, value, unit = match.groups()
            values[code] = (value, unit or "")


# 7 data bits, even parity, 1 stop bit - this is how IEC 62056-21 meters talk
ser = serial.Serial(PORT, baudrate=300, bytesize=serial.SEVENBITS,
                    parity=serial.PARITY_EVEN, stopbits=serial.STOPBITS_ONE, timeout=2)

print(f"Polling meter on {PORT} (IEC 62056-21) ...")
while True:
    try:
        ident, values = read_meter(ser)
        print(f"Meter: {ident}")
        for code, (value, unit) in values.items():
            print(f"{NAMES.get(code, code):14s}: {value} {unit}")
    except RuntimeError as err:
        print(f"Error: {err}")
    print("-" * 30)
    time.sleep(INTERVAL)

Example output:

Polling meter on /dev/serial0 (IEC 62056-21) ...
Meter: /LGZ5ZMD3104407.B32
Meter number  : 12345678
Import        : 012345.678 kWh
Export        : 004321.000 kWh
Power         : 00.437 kW
------------------------------

Which codes arrive?

The script prints every value the meter sends — known ones with a name, all others with their code. The notation differs between manufacturers: some meters send 16.7.0, others 16.7. Add your meter's codes to NAMES. What each code means is listed under Readings.


Troubleshooting

Problem Possible cause / solution
Permission denied on /dev/... Add your user to the dialout group: sudo usermod -aG dialout $USER, then log in again
No data / frame stays None Reading head not positioned correctly over the IR diode; green wire (RXD) not on the RX of the Raspberry Pi or adapter; wrong port
Only energy counters, no power/phases Disable the PIN and set Inf → On on the meter
Nothing arrives on the Raspberry Pi Serial login shell still enabled? Use port /dev/serial0 instead of /dev/ttyAMA0
Values off by a factor of 10/100 In rare cases replace get_obis() with parse_frame() (see smllib docs)
Script 2: "No valid answer from the meter" TX wire (white, yellow on the older TTL) not connected or not on the TX of the Raspberry Pi or adapter; reading head not positioned correctly over the IR interface; the meter speaks SML — use script 1 instead
Script 2: timeout while reading the data block or "Checksum (BCC) wrong" Some meters do not handle the baud rate switch reliably — set KEEP_300 = True to stay at 300 baud