sml

package module
v0.0.0-...-b8bad78 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Apr 10, 2026 License: Apache-2.0 Imports: 7 Imported by: 1

README

go-sml

A pure-Go library for decoding Smart Message Language (SML) data from German smart electricity meters. Zero external dependencies.

go get github.com/databus23/go-sml

Quick Start

CLI tool

A small command-line tool is included that prints readings in the same format as the C sml_server:

go install github.com/databus23/go-sml/cmd/smlreader@latest
smlreader capture.bin
# or from stdin:
smlreader -

Output:

1-0:1.8.0*255#8391648.8#Wh
1-0:15.7.0*255#163.5#W
As a library

Decode a raw SML payload and print all meter readings:

file, err := sml.Decode(payload)
if err != nil {
    log.Fatal(err)
}
for _, entry := range file.Readings() {
    if v, ok := entry.ScaledValue(); ok {
        fmt.Printf("%s = %f %s\n", entry.OBISString(), v, entry.UnitString())
    }
}
// Output:
// 1-0:1.8.0*255 = 8391648.800000 Wh
// 1-0:16.7.0*255 = 163.500000 W

Streaming from a Serial Port

For continuous reading from a serial device (or any io.Reader), use Listen. It handles transport framing, escape sequences, and CRC validation automatically:

port, _ := os.Open("/dev/ttyUSB0")
defer port.Close()

err := sml.Listen(ctx, port, func(file *sml.File) error {
    for _, entry := range file.Readings() {
        if v, ok := entry.ScaledValue(); ok {
            fmt.Printf("%s = %.1f %s\n", entry.OBISString(), v, entry.UnitString())
        }
    }
    return nil
})

Use ListenMessages instead if you want per-message callbacks rather than per-file.

API Overview

Root package sml
Symbol Description
Decode(data) (*File, error) Decode a complete SML payload (strict mode)
DecodeWithOptions(data, opts) Decode with configurable strictness
Listen(ctx, r, handler) Stream-decode from an io.Reader
ListenMessages(ctx, r, handler) Like Listen, but calls handler per message
File.Readings() Collect all ListEntry values from GetListResponse messages
ListEntry.ScaledValue() Apply scaler, return float64
ListEntry.OBISString() Format OBIS code as "A-B:C.D.E*F"
ListEntry.UnitString() DLMS unit name (e.g. "Wh", "W", "V")
UnitName(code) Look up DLMS unit code directly
Sub-package transport
Symbol Description
NewReader(r) *Reader Wrap an io.Reader to extract SML transport frames
Reader.Next() ([]byte, error) Return next validated frame payload

The transport layer auto-detects CRC-16/X.25 (standard) and CRC-16/Kermit (Holley DTZ541 meters).

Value Types

SML values preserve their wire encoding width. Use a type switch on the Value interface:

switch v := entry.Value.(type) {
case sml.Uint32:
    fmt.Println("unsigned 32-bit:", uint32(v))
case sml.Int16:
    fmt.Println("signed 16-bit:", int16(v))
case sml.OctetString:
    fmt.Printf("bytes: %x\n", []byte(v))
}

Available types: OctetString, Bool, Int8, Int16, Int32, Int64, Uint8, Uint16, Uint32, Uint64.

Message Body Types

Message.Body implements MessageBody and is one of:

  • *OpenResponse
  • *CloseResponse
  • *GetListResponse (contains meter readings)
  • *AttentionResponse
  • *GetProcParameterResponse
  • *GetProfileListResponse
  • *GetProfilePackResponse

Testing

Run all tests
go test ./...
Integration tests only

The integration tests decode 37 real meter captures and compare the output against golden files generated by the C reference implementation (libsml):

go test -run TestGoldenFiles -v

Test data comes from devZer0/libsml-testing and covers 15+ meter models from manufacturers including EMH, DZG, Holley, ISKRA, EasyMeter, eBZ, ITRON, and DrNeuhaus.

Fuzz tests
go test -fuzz FuzzDecode -fuzztime 30s
go test -fuzz FuzzTransportReader -fuzztime 30s

Regenerating Golden Files

The golden files in testdata/golden/ are generated by piping each binary capture through the C sml_server example program from volkszaehler/libsml.

Build sml_server from source
git clone https://github.com/volkszaehler/libsml /tmp/libsml
cd /tmp/libsml
make

# On macOS the shared library target may fail — only the static library
# is needed. Link sml_server manually:
cc -o sml_server examples/sml_server.c -Isml/include sml/lib/libsml.a -lm
Generate golden files
for f in testdata/*.bin; do
  name=$(basename "$f" .bin)
  /tmp/libsml/sml_server - < "$f" > "testdata/golden/${name}.txt" 2>&1
done

The golden file format is one line per GetListResponse list entry:

OBIS#value#unit

where OBIS is A-B:C.D.E*F, value is the scaled numeric reading (or hex-formatted octet string), and unit is the DLMS unit name.

Using Docker (no local C toolchain)
docker run --rm -v "$(pwd)":/work -w /work gcc:latest bash -c '
  apt-get update -qq && apt-get install -y -qq uuid-dev > /dev/null 2>&1
  git clone --quiet https://github.com/volkszaehler/libsml /tmp/libsml
  cd /tmp/libsml && make > /dev/null 2>&1
  for f in /work/testdata/*.bin; do
    name=$(basename "$f" .bin)
    ./examples/sml_server - < "$f" > "/work/testdata/golden/${name}.txt" 2>&1
  done
'

License

Apache License 2.0 — see LICENSE.

Acknowledgements

Documentation

Overview

Package sml decodes Smart Message Language (SML) data from German smart electricity meters.

SML is a binary TLV-encoded protocol defined by the German BSI. It is used by virtually all modern German smart meters to transmit readings over an infrared optical interface. This package provides a pure-Go parser with zero external dependencies.

Decoding a single payload

If you already have a complete SML payload (transport layer stripped), use Decode or DecodeWithOptions:

file, err := sml.Decode(payload)
for _, entry := range file.Readings() {
    if v, ok := entry.ScaledValue(); ok {
        fmt.Printf("%s = %f %s\n", entry.OBISString(), v, entry.UnitString())
    }
}

Streaming from an io.Reader

For continuous reading from a serial port or other byte stream, use Listen or ListenMessages. These handle SML transport framing (start/end sequences, escape processing, CRC validation) automatically via the transport sub-package:

err := sml.Listen(ctx, serialPort, func(file *sml.File) error {
    for _, entry := range file.Readings() {
        // process readings
    }
    return nil
})

Value types

SML values preserve their wire encoding width. The Value interface is satisfied by named types (OctetString, Bool, Int8, Int16, Int32, Int64, Uint8, Uint16, Uint32, Uint64) which can be distinguished via a type switch. For meter readings, the ListEntry.ScaledValue convenience method applies the scaler and returns a float64.

Index

Constants

View Source
const (
	TimeSecIndex  uint8 = 0x01 // TimeSecIndex indicates the value is a seconds index (secIndex).
	TimeTimestamp uint8 = 0x02 // TimeTimestamp indicates the value is a UNIX timestamp.
)

Variables

This section is empty.

Functions

func FormatReadingValue

func FormatReadingValue(e *ListEntry) (string, bool)

FormatReadingValue formats a ListEntry as "OBIS#value#unit", matching the output format of the C sml_server reference tool. Returns ("", false) if the entry has a nil Value or an OBIS code that isn't exactly 6 bytes.

func Listen

func Listen(ctx context.Context, r io.Reader, handler Handler) error

Listen reads SML frames from r, decodes them, and calls handler for each file. Blocks until r is exhausted (io.EOF), ctx is cancelled, or handler returns a non-nil error. Frames that fail CRC validation or SML decoding are silently skipped.

func ListenMessages

func ListenMessages(ctx context.Context, r io.Reader, handler MessageHandler) error

ListenMessages calls handler once per message rather than once per file. Frames that fail CRC validation or SML decoding are silently skipped.

func ToInt64

func ToInt64(v Value) (int64, bool)

ToInt64 extracts the numeric value from a Value as int64. Returns (0, false) for nil, OctetString, and Bool values.

func UnitName

func UnitName(code uint8) string

UnitName returns the DLMS unit string for the given code. Returns "" for unknown codes.

Types

type AttentionResponse

type AttentionResponse struct {
	ServerID         []byte
	AttentionNo      []byte
	AttentionMsg     *string
	AttentionDetails []TreeEntry
}

AttentionResponse is the body of an SML attention response message.

type Bool

type Bool bool // Bool is an SML boolean value.

Concrete Value types. Named types preserve the wire encoding size so callers can distinguish between e.g. a 1-byte and a 4-byte unsigned integer via a type switch on Value.

type CloseResponse

type CloseResponse struct {
	Signature []byte
}

CloseResponse is the body of an SML close response message.

type DecodeOptions

type DecodeOptions struct {
	Strict bool // default: true — fail on first malformed message
}

DecodeOptions controls decoder behavior.

type File

type File struct {
	Messages []*Message
}

File is a decoded SML transmission containing one or more messages.

func Decode

func Decode(data []byte) (*File, error)

Decode parses SML binary data in strict mode, returning the first error encountered.

func DecodeWithOptions

func DecodeWithOptions(data []byte, opts DecodeOptions) (*File, error)

DecodeWithOptions parses SML binary data with configurable strictness. In strict mode (default), the first parse error aborts decoding. In non-strict mode, malformed messages are skipped and partial results are returned alongside a joined error.

func (*File) Readings

func (f *File) Readings() []ListEntry

Readings collects all ListEntry values from every GetListResponse in the file, returning them as a flat slice.

type GetListResponse

type GetListResponse struct {
	ClientID       []byte
	ServerID       []byte
	ListName       []byte
	ActSensorTime  *Time
	ValList        []ListEntry
	Signature      []byte
	ActGatewayTime *Time
}

GetListResponse is the body of an SML get-list response message.

type GetProcParameterResponse

type GetProcParameterResponse struct {
	ServerID      []byte
	TreePath      TreePath
	ParameterTree *TreeEntry
}

GetProcParameterResponse is the body of an SML get-proc-parameter response message.

type GetProfileListResponse

type GetProfileListResponse struct {
	ServerID          []byte
	ActTime           *Time
	RegPeriod         *uint32
	ParameterTreePath TreePath
	ValTime           *Time
	Status            *uint64
	ValList           []PeriodEntry
	RawData           []byte
	PeriodSignature   []byte
}

GetProfileListResponse is the body of an SML get-profile-list response message.

type GetProfilePackResponse

type GetProfilePackResponse struct {
	ServerID          []byte
	ActTime           *Time
	RegPeriod         *uint32
	ParameterTreePath TreePath
	HeaderList        []ProfileObjHeaderEntry
	PeriodList        []ProfileObjPeriodEntry
	RawData           []byte
	PeriodSignature   []byte
}

GetProfilePackResponse is the body of an SML get-profile-pack response message.

type Handler

type Handler func(*File) error

Handler is called for each decoded SML file. Return non-nil error to stop listening.

type Int8

type Int8 int8 // Int8 is a 1-byte signed integer.

Concrete Value types. Named types preserve the wire encoding size so callers can distinguish between e.g. a 1-byte and a 4-byte unsigned integer via a type switch on Value.

type Int16

type Int16 int16 // Int16 is a 2-byte signed integer.

Concrete Value types. Named types preserve the wire encoding size so callers can distinguish between e.g. a 1-byte and a 4-byte unsigned integer via a type switch on Value.

type Int32

type Int32 int32 // Int32 is a 4-byte signed integer.

Concrete Value types. Named types preserve the wire encoding size so callers can distinguish between e.g. a 1-byte and a 4-byte unsigned integer via a type switch on Value.

type Int64

type Int64 int64 // Int64 is an 8-byte signed integer.

Concrete Value types. Named types preserve the wire encoding size so callers can distinguish between e.g. a 1-byte and a 4-byte unsigned integer via a type switch on Value.

type ListEntry

type ListEntry struct {
	ObjName   []byte // OBIS code (typically 6 bytes)
	Status    *uint64
	ValTime   *Time
	Unit      *uint8 // DLMS unit code
	Scaler    *int8
	Value     Value
	Signature []byte
}

ListEntry represents a single meter reading.

func (*ListEntry) OBISString

func (e *ListEntry) OBISString() string

OBISString formats the 6-byte OBIS code as "A-B:C.D.E*F". Returns "" if ObjName is not exactly 6 bytes.

func (*ListEntry) ScaledValue

func (e *ListEntry) ScaledValue() (float64, bool)

ScaledValue returns the numeric value multiplied by 10^Scaler as a float64. Returns (0, false) if Value is nil, non-numeric, or Scaler is nil.

func (*ListEntry) UnitString

func (e *ListEntry) UnitString() string

UnitString returns the DLMS unit name for the entry's unit code. Returns "" if Unit is nil or the code is unknown.

type Message

type Message struct {
	TransactionID []byte
	GroupID       uint8
	AbortOnError  uint8
	Body          MessageBody
	CRC           uint16
}

Message is a single SML message within a file.

type MessageBody

type MessageBody interface {
	// contains filtered or unexported methods
}

MessageBody is implemented by each specific message type.

type MessageHandler

type MessageHandler func(*Message) error

MessageHandler is called for each message. Return non-nil error to stop listening.

type OctetString

type OctetString []byte // OctetString is a raw byte sequence.

Concrete Value types. Named types preserve the wire encoding size so callers can distinguish between e.g. a 1-byte and a 4-byte unsigned integer via a type switch on Value.

type OpenResponse

type OpenResponse struct {
	Codepage   *string
	ClientID   []byte
	ReqFileID  []byte
	ServerID   []byte
	RefTime    *Time
	SmlVersion *uint8
}

OpenResponse is the body of an SML open response message.

type PeriodEntry

type PeriodEntry struct {
	ObjName   []byte
	Unit      *uint8
	Scaler    *int8
	Value     Value
	Signature []byte
}

PeriodEntry is used in GetProfileListResponse.

type ProfileObjHeaderEntry

type ProfileObjHeaderEntry struct {
	ObjName []byte
	Unit    *uint8
	Scaler  *int8
}

ProfileObjHeaderEntry is used in GetProfilePackResponse.

type ProfileObjPeriodEntry

type ProfileObjPeriodEntry struct {
	ValTime   *Time
	Status    *uint64
	ValueList []PeriodEntry
}

ProfileObjPeriodEntry is used in GetProfilePackResponse.

type Time

type Time struct {
	Tag   uint8 // TimeSecIndex or TimeTimestamp
	Value uint32
}

Time represents a tagged SML time value.

type TreeEntry

type TreeEntry struct {
	ParameterName  []byte
	ParameterValue Value
	Children       []TreeEntry
}

TreeEntry is a recursive parameter tree node.

type TreePath

type TreePath [][]byte

TreePath is a flat path of OBIS code segments.

type Uint8

type Uint8 uint8 // Uint8 is a 1-byte unsigned integer.

Concrete Value types. Named types preserve the wire encoding size so callers can distinguish between e.g. a 1-byte and a 4-byte unsigned integer via a type switch on Value.

type Uint16

type Uint16 uint16 // Uint16 is a 2-byte unsigned integer.

Concrete Value types. Named types preserve the wire encoding size so callers can distinguish between e.g. a 1-byte and a 4-byte unsigned integer via a type switch on Value.

type Uint32

type Uint32 uint32 // Uint32 is a 4-byte unsigned integer.

Concrete Value types. Named types preserve the wire encoding size so callers can distinguish between e.g. a 1-byte and a 4-byte unsigned integer via a type switch on Value.

type Uint64

type Uint64 uint64 // Uint64 is an 8-byte unsigned integer.

Concrete Value types. Named types preserve the wire encoding size so callers can distinguish between e.g. a 1-byte and a 4-byte unsigned integer via a type switch on Value.

type Value

type Value interface {
	// contains filtered or unexported methods
}

Value is implemented by all SML value types.

Directories

Path Synopsis
cmd
smlreader command
Command smlreader reads SML binary data and prints meter readings in the same format as the C sml_server reference tool (OBIS#value#unit).
Command smlreader reads SML binary data and prints meter readings in the same format as the C sml_server reference tool (OBIS#value#unit).
Package transport handles SML transport layer framing.
Package transport handles SML transport layer framing.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL