wired

package
v0.2.0 Latest Latest
Warning

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

Go to latest
Published: Oct 11, 2026 License: Apache-2.0 Imports: 16 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package wired is wired M-Bus: the EN 13757-2:2018+A1:2023 link layer (FT1.2 frames, ACK and NACK, the frame count bit per address, repeats, answer timing, collisions) and the EN 13757-3:2025 application procedures of a master: primary and secondary addressing (a command to a meter named with wildcards goes only to one selected meter), the secondary address search, multi-telegram reads, class 1 data and alarms, application select and reset, set primary address, baud rate switch, clock synchronisation and image transfer (annex I); plus the fixed data structure, application errors and DLMS/COSEM responses.

Master talks over a Port: a local serial port behind a level converter (OpenSerial, 8E1) or a transparent serial-to-IP converter (DialTCP). Data records are decoded by package records.

Index

Examples

Constants

View Source
const (
	CIAppSelect      = 0x50 // application reset or select (no header); CIAppReset
	CIAppSelectLong  = 0x53 // the same with a long header
	CIAppSelectShort = 0x57 // the same with a short header (wM-Bus)
	CIReqSelected    = 0x54 // request of the selected application (no header)
	CIReqSelLong     = 0x55
	CIReqSelShort    = 0x56
	CIRspSelected    = 0x66 // response of the selected application (no header)
	CIRspSelShort    = 0x67 // wM-Bus only
	CIRspSelLong     = 0x68
	CISynchronize    = 0x5C // synchronize action, no data (clause 12)
	CIClockSync      = 0x6C // clock synchronisation (annex E.3), long header
	CIAppErrShort    = 0x6E // application error from the device (clause 10.3), short header
	CIAppErrLong     = 0x6F // long header
	CIAppErrNone     = 0x70
	CIAlarmShort     = 0x74 // alarm status with a short header (clause 9)
	CIAlarmLong      = 0x75
)

CI fields of the application procedures (EN 13757-3:2025 tables 27 and 29, clauses 8 to 12; the TPL header variant in brackets).

View Source
const (
	TCSetI      = 0x0
	TCAddJ      = 0x1
	TCSubtractJ = 0x2
	TCCorrectJ  = 0x3
	TCSetM      = 0x4
	TCAddM      = 0x5
	TCSubtractM = 0x6
	TCCorrectM  = 0x7
)

Clock synchronisation functions (TC field bits 0-3, table E.13); the data type is I (set) or J (differences, correction) for 0 to 3 and M for 4 to 7.

View Source
const (
	FixedBinary    = 0x01 // counters are signed binary, else BCD
	FixedStored    = 0x02 // counters were stored at a fixed date, else actual
	FixedPowerLow  = 0x04
	FixedPermanent = 0x08 // permanent error
	FixedTemporary = 0x10 // temporary error

)

Status bits of the fixed structure.

View Source
const (
	CSndNke = 0x40 // normalisation; FCV and FCB clear
	CSndUD  = 0x53 // send user data, answer ACK (0x73 with FCB)
	CSndUD2 = 0x43 // send user data, answer RSP_UD (A1:2023 5.7.3.4); FCV clear
	CReqUD2 = 0x5B // request class 2 data (0x7B with FCB)
	CReqUD1 = 0x5A // request class 1 data (0x7A with FCB)
	CRspUD  = 0x08 // respond user data (ACD 0x20, DFC 0x10 may be set)
	FCB     = 0x20
	FCV     = 0x10
	ACK     = 0xE5 // A1:2023 3.1.3
	NACK    = 0xA2 // A1:2023 3.1.4: the answer of a meter without SND_UD2

	// MaxLongData is the most bytes after the CI field: the L field
	// counts C, A, CI and the data and is one byte.
	MaxLongData = 255 - 3
)

Control field values (5.7.3, 5.7.7, annex F). FCV (bit 4) is set in SND_UD, REQ_UD1 and REQ_UD2 and clear in SND_NKE and SND_UD2.

View Source
const (
	AddrUnconfigured = 0    // every unconfigured slave answers
	AddrRepeater     = 0xFB // 251: management of the primary master repeater
	AddrReserved     = 0xFC // 252: reserved
	AddrSecondary    = 0xFD // 253: the slave(s) selected by secondary addressing
	AddrTest         = 0xFE // 254: test and diagnosis; every slave answers
	AddrBroadcast    = 0xFF // 255: broadcast; every slave executes, none answers
	// AddrBroadcastAns is the older name of AddrTest.
	AddrBroadcastAns = AddrTest
)

Addresses (5.7.5).

View Source
const (
	CIAppReset     = 0x50
	CISetData      = 0x51
	CISelect       = 0x52
	CIRspVariable  = 0x72 // variable data, long header, LSB first
	CIRspVariableM = 0x76 // variable data, long header, MSB first
	CIRspFixed     = 0x73
	CIRspFixedM    = 0x77 // fixed data, multi-byte fields MSB first
	CIRspAlarm     = 0x71 // alarm status (answer to REQ_UD1)
	CIRspNoHeader  = 0x78
	CIRspShort     = 0x7A
	// A DLMS/COSEM APDU from the meter (EN 13757-1:2021 9.2.1, EN
	// 13757-7 CI table): long header 7Ch, short header 7Dh.
	CIRspDLMSLong  = 0x7C
	CIRspDLMSShort = 0x7D
)

CI fields.

View Source
const (
	CIImageCmdLong  = 0xC0 // command to the device, long header
	CIImageRspShort = 0xC1 // response from the device, short header
	CIImageRspLong  = 0xC2 // response from the device, long header
	CIImageCmdShort = 0xC7 // command to the device, short header
)

Image transfer CI fields (table I.1).

View Source
const (
	ImgPrepare      = 0x00
	ImgSynchronize  = 0x01
	ImgTransfer     = 0x02
	ImgCompletion   = 0x03
	ImgState        = 0x04
	ImgValidate     = 0x05
	ImgActivate     = 0x06
	ImgTerminate    = 0x07
	ImgActiveImages = 0x08
	ImgResponse     = 0x80
)

Image transfer functions (table I.4); a response has bit 7 set.

View Source
const (
	// Prepare command (table I.6).
	PrepMAC  = 0x01
	PrepADT  = 0x02
	PrepSZIN = 0x04
	PrepIDEN = 0x08
	PrepMCAS = 0x10
	PrepINFO = 0x20
	// Prepare response (table I.13).
	PrepRspAINF = 0x01
	PrepRspSZIN = 0x02
	PrepRspRDY  = 0x04 // set: not ready
	PrepRspIDEN = 0x08
	PrepRspMCAS = 0x10
	PrepRspINFO = 0x20
	// Synchronize command (table I.16).
	SyncCTDN = 0x01
	SyncIDEN = 0x02
	// Transfer command (table I.18): SEQ in bits 1-2.
	XferAINF      = 0x01
	XferSeqFirst  = 0x02
	XferSeqMiddle = 0x04
	XferSeqLast   = 0x06
	XferIDEN      = 0x08
	XferREM       = 0x10

	CmplIDEN        = 0x02 // completion, state, validate commands (tables I.22, I.26, I.31)
	CmplAINF        = 0x01
	CmplRspNBR      = 0x01 // completion response (table I.24)
	CmplRspLIB      = 0x02
	CmplRspTNLB     = 0x04
	CmplRspIDEN     = 0x08
	ActADT          = 0x01 // activate command (table I.35)
	ActIDEN         = 0x02
	TermTIT         = 0x01 // terminate command (table I.39)
	TermTTR         = 0x02
	TermIDEN        = 0x04
	ActiveImagesLAI = 0x01 // active images response (table I.45)

)

Sub-function bits.

View Source
const (
	StateTransferSuccessful   = 5
	StateTransferFailed       = 6
	StateValidationInitiated  = 7
	StateValidationActive     = 8
	StateValidationSuccessful = 9
	StateValidationFailed     = 10
	StateActivationInitiated  = 11
	StateActivationSuccessful = 12
	StateActivationFailed     = 13
	StateIdle                 = 15
)

Image transfer states used by the head end.

View Source
const MaxApplication = 45

MaxApplication is the highest message application the three-byte subcode can carry (a + b + c with a = b = 15).

Variables

View Source
var ErrFrame = errors.New("invalid M-Bus frame")

ErrFrame is wrapped by framing errors (checksum, length, stop byte, or bytes that start no frame, as after a collision).

View Source
var ErrImageNoResponse = errors.New("no image transfer response")

ErrImageNoResponse is ImageCommand's error when the device sends no image transfer response (a device may not answer while it activates).

View Source
var ErrNoAnswer = errors.New("no answer")

ErrNoAnswer is the error of an exchange nobody answered.

View Source
var ErrSegmentLength = errors.New("invalid image transfer segment length")

ErrSegmentLength is a segment length below 3 or past the data: the whole structure is ignored (annex I.2.2).

View Source
var ErrTimeout = errors.New("no answer within the timeout")

ErrTimeout is what ReadByte returns after the deadline.

View Source
var ImageStates = [16]string{"sync_activated", "sync_terminated", "transfer_initiated", "transfer_active",
	"transfer_terminated", "transfer_successful", "transfer_failed", "validation_initiated", "validation_active",
	"validation_successful", "validation_failed", "activation_initiated", "activation_successful",
	"activation_failed", "image_transfer_terminated", "idle"}

Transfer states (table I.29).

View Source
var PrepareResults = []string{"accepted", "version_not_accepted", "minimum_sw_version", "minimum_hw_version",
	"update_disabled", "image_type_not_supported", "image_too_big", "other_error"}

PrepareResults names the preparation results (table I.14).

View Source
var Wildcard = SecondaryAddress{ID: "FFFFFFFF", Manufacturer: 0xFFFF, Version: 0xFF, Medium: 0xFF}

Wildcard matches every slave.

Functions

func AppErrorName

func AppErrorName(c byte) string

AppErrorName names a first error code byte.

func Application

func Application(code int) string

Applications names the message applications of EN 13757-3:2025 table 26 (codes 30 to 45 are manufacturer specific, 46 to 61 additional data for fixed network readout).

func BaudCI

func BaudCI(baud int) (byte, error)

BaudCI is the CI field that switches a slave to baud (table 29).

func BitTime

func BitTime(baud int) time.Duration

BitTime is one bit at the baud rate.

func CIBaud

func CIBaud(ci byte) int

CIBaud is the baud rate a CI field B8h to BFh selects, 0 for others.

func DialTCP

func DialTCP(ctx context.Context, address string) (io.ReadWriteCloser, error)

DialTCP connects to a transparent serial-to-IP converter (which does the 8E1 UART framing itself), giving up after 10 s.

func EncodeSegments

func EncodeSegments(segs ...Segment) []byte

EncodeSegments concatenates segments: a 2-byte length (LSB first) counting the segment ID, function, sub-function and parameters.

func Epoch2013

func Epoch2013(t time.Time) []byte

Epoch2013 encodes t as the 4-byte EPOCH 2013 seconds used by the image transfer date and time fields (annex I.2.4.3).

func FrameTime

func FrameTime(n, baud int) time.Duration

FrameTime is how long n bytes take on the line.

func Full

func Full(a *SecondaryAddress) bool

Full reports whether a secondary address names one meter: no part is a wildcard.

func LongHeader

func LongHeader(id SecondaryAddress, acc byte) ([]byte, error)

LongHeader is the 12-byte TPL long header of a command to a slave: its address, our access number acc, status 0 and configuration 0 (no security).

func MaxAnswerDelay

func MaxAnswerDelay(baud int) time.Duration

MaxAnswerDelay is the latest a slave may begin its answer after the master's datagram ends: 330 bit times + 50 ms (5.7.6).

func OpenSerial

func OpenSerial(dev string, baud int) (io.ReadWriteCloser, error)

OpenSerial opens a local serial port for an M-Bus level converter: 8 data bits, even parity, 1 stop bit (EN 13757-2 5.4).

func ParseSubcode

func ParseSubcode(b []byte) (app, block int, err error)

ParseSubcode decodes an application select subcode (up to 10 bytes; bytes after the third carry nothing defined and are ignored).

func QuietAfter

func QuietAfter(n, baud int) time.Duration

QuietAfter is the pause after an unanswered datagram of n bytes.

func SelectSubcode

func SelectSubcode(app, block int) ([]byte, error)

SelectSubcode encodes an application select subcode: the upper nibbles carry the message application (a, or 15 + b when a is 15, or 30 + c when a and b are 15) and the lower nibbles the block number (x in bits 0-3, y in 4-7, z in 8-11). Block 0 asks for every block. Only as many bytes as the application or block need are sent.

func StatusInfo

func StatusInfo(s byte) map[string]any

StatusInfo decodes the status byte of a short or long TPL header (EN 13757-7:2025 7.5.6, referenced by EN 13757-3:2025 10.2): bits 0-1 the application state, bit 2 power low, bit 3 permanent error, bit 4 temporary error, bits 5-7 manufacturer specific.

func TypeI

func TypeI(t time.Time) []byte

TypeI encodes a date and time as data type I (annex A, 6 bytes, local time of t; day of week, week and daylight saving fields not given).

func TypeJ

func TypeJ(h, m, s int) []byte

TypeJ encodes a time of day as data type J (3 bytes, local time).

func TypeM

func TypeM(t time.Time, n int) []byte

TypeM encodes an absolute UTC time as data type M (annex A table A.12) in n bytes (2 to 10): seconds since 2013-01-01 UTC, resolution 1 s, no time offset given (01111b), so the meter keeps its configured zone. The LVAR byte (E0h + n) is not included.

func TypeMDuration

func TypeMDuration(d time.Duration, n int) ([]byte, error)

TypeMDuration encodes a relative time (time offset 10000b) of d in whole seconds, n bytes.

Types

type AppError

type AppError struct {
	Code byte // first error code byte; 0 when the data field is empty
	Name string
	Data []byte // every byte after the CI (and header)
}

AppError is a general application error reported by a slave (CI 6Eh, 6Fh or 70h, EN 13757-3:2025 table 28).

func ParseAppError

func ParseAppError(b []byte) AppError

ParseAppError decodes the application error bytes. An empty data field is an unspecified error.

func (AppError) Error

func (e AppError) Error() string

Error names the code.

type ClockSync

type ClockSync struct {
	Function byte          // TCSetI … TCCorrectM
	Time     time.Time     // set, correction
	Diff     time.Duration // add, subtract (positive)
	// Legacy keeps the reserved (00h) and command verification (2Fh)
	// fields, for meters of the earlier editions (functions 0 to 2 only).
	Legacy bool
}

ClockSync is one clock synchronisation command.

func (ClockSync) Encode

func (c ClockSync) Encode() ([]byte, error)

Encode is the application data after the TPL header: the TC field, the date/time value and, for Legacy, the reserved and verification fields. Type I and J values are the local time of t's location.

type CompletionRsp

type CompletionRsp struct {
	NoneReceived bool
	Lost         []uint16 // missing blocks
	LostFrom     int      // -1, or the first block of a missing tail (FFFFh marker)
	Total        int      // total number of lost blocks, -1 when not given
	ID           *ImageID
}

CompletionRsp is the completion response (tables I.23 and I.24).

func ParseCompletionRsp

func ParseCompletionRsp(s Segment) (CompletionRsp, error)

ParseCompletionRsp decodes a completion response.

func (CompletionRsp) Missing

func (r CompletionRsp) Missing(n int) []uint16

Missing lists the blocks to send again, of n in the image.

type FixedCounter

type FixedCounter struct {
	Quantity string  // "energy", "volume", … or "" when the unit code has none
	Unit     string  // SenML / UCUM symbol like the variable-data records
	Value    float64 // scaled; raw when the unit code is not a physical unit
	UnitCode byte    // the 6-bit unit code as sent
	Historic bool    // stored at a fixed date (status bit, or unit code 3Eh)
	Valid    bool    // false when a BCD counter holds non-decimal digits
}

FixedCounter is one counter of a fixed data structure, scaled to its base unit.

type FixedData

type FixedData struct {
	ID       string
	Access   byte
	Status   byte
	Medium   string
	Counters [2]FixedCounter
}

FixedData is a decoded fixed data structure.

func ParseFixed

func ParseFixed(p []byte, msbFirst bool) (*FixedData, error)

ParseFixed decodes the 16 data bytes of a CI 73h (msbFirst false) or 77h (msbFirst true) response.

type Frame

type Frame struct {
	Single bool // E5 (ACK)
	Nack   bool // A2 (NACK)
	C, A   byte
	Long   bool // control or long frame (with CI)
	CI     byte
	Data   []byte
}

Frame is one M-Bus frame.

func ReadFrame

func ReadFrame(r io.ByteReader) (Frame, error)

ReadFrame reads one frame. Unlike FT1.2 readers on a quiet line, a byte that starts no frame is an error: on M-Bus it means two slaves answered at once.

func (Frame) Check

func (f Frame) Check() error

Check reports a long frame whose data does not fit the one-byte L field; Encode would write a wrong length for it.

func (Frame) Encode

func (f Frame) Encode() []byte

Encode serialises the frame.

Example

A REQ_UD2 to primary address 5 with the frame count bit set.

package main

import (
	"fmt"

	"github.com/cB-Sigma/mbus/wired"
)

func main() {
	fmt.Printf("% X\n", wired.Frame{C: wired.CReqUD2 | wired.FCB, A: 5}.Encode())
}
Output:
10 7B 05 80 16

type ImageID

type ImageID struct {
	Manufacturer uint16
	Version      byte
	DeviceType   byte
	Image        uint32 // manufacturer image identifier
}

ImageID is the 8-byte image identifier field (table I.7).

func (ImageID) Bytes

func (id ImageID) Bytes() []byte

Bytes is the field as sent (manufacturer and image number LSB first).

type MAC

type MAC struct {
	Algorithm  byte
	KeyID      byte
	KeyVersion byte
	Value      []byte
}

MAC is the MAC field of a prepare command (table I.9): algorithm (01h HMAC-SHA256/8, 02h HMAC-SHA256/16, 03h CMAC/8, 04h CMAC, 05h GMAC/12), key ID and version, and the value MSB first, padded with zeros to 16 bytes.

type MTime

type MTime struct {
	Relative bool          // time offset 10000b: a duration
	Invalid  bool          // the most negative duration
	Offset   int           // hours to UTC, -12 to 14; 15 not given
	Duration time.Duration // since the starting time, or the relative time
	Time     time.Time     // absolute: UTC
}

MTime is a decoded data type M value.

func ParseTypeM

func ParseTypeM(b []byte) (MTime, error)

ParseTypeM decodes n bytes of data type M (without the LVAR byte).

type Master

type Master struct {
	// Timeout is the time to the first byte of an answer; zero is 2 s.
	// MaxAnswerDelay is the least a slave may take.
	Timeout time.Duration
	// Retries is how often an unanswered request, or one answered with a
	// damaged frame, is repeated (the standard's two: three attempts).
	Retries int
	// Log receives the search's notes; nil is slog.Default().
	Log *slog.Logger
	// contains filtered or unexported fields
}

Master is the primary station of a wired M-Bus segment (EN 13757-2:2018+A1:2023 clause 5, EN 13757-3:2025): it keeps the frame count bit of every address, repeats unanswered requests, selects slaves by primary or secondary address, searches the bus and runs the application procedures. Its line is a Port (SetPort), which can be replaced when the line is reopened; the frame count bits stay.

A Master runs one transaction at a time: the caller serialises the methods that talk on the bus (a selection followed by a read is one transaction, so it holds its own lock around both).

Example

A master on a bus behind a serial-to-IP converter: find the meters by the secondary address search, select the first and read its data records. (It needs a bus, so it is compiled but not run; the mbus-sim module runs the same steps against its simulated bus.)

package main

import (
	"context"
	"fmt"
	"net"
	"time"

	"github.com/cB-Sigma/mbus/wired"
)

func main() {
	conn, err := net.Dial("tcp", "192.0.2.20:10001") // wired.OpenSerial for a local port
	if err != nil {
		panic(err)
	}
	p := wired.NewPort(conn)
	defer p.Close()
	m := wired.NewMaster(2400)
	m.Timeout, m.Retries = 300*time.Millisecond, 2
	m.SetPort(p, 2400)

	ctx := context.Background()
	found, err := m.Search(ctx)
	if err != nil || len(found) == 0 {
		panic(fmt.Sprint("no meter found: ", err))
	}
	fmt.Println(found[0].Key()) // ABC-12345678
	a, err := m.Select(ctx, wired.Target{Secondary: &found[0]})
	if err != nil {
		panic(err)
	}
	_, err = m.ReadTelegrams(ctx, a, 8, func(t wired.Telegram) error {
		for _, r := range t.Records {
			fmt.Println(r.Name(), r.Value, r.Unit) // volume 12.345 m3
		}
		return nil
	})
	if err != nil {
		panic(err)
	}
}

func NewMaster

func NewMaster(baud int) *Master

NewMaster is a master with the standard's timing for the baud rate: answer timeout 10 s at 300 Bd, 2 s up to 2400 Bd, 1 s above, and two retries.

func (*Master) Baud

func (m *Master) Baud() int

Baud is the line's rate.

func (*Master) CheckAppError

func (m *Master) CheckAppError(ctx context.Context, a byte) (*AppError, error)

CheckAppError reads the selected address a once: an application error answer (CI 6Eh-70h, clause 10.1) is returned as the AppError; err is a failed read.

func (*Master) ConfirmAlarm

func (m *Master) ConfirmAlarm(ctx context.Context, a byte) error

ConfirmAlarm confirms an alarm status (EN 13757-3:2025 annex D.1): a slave repeats its alarm frame until a REQ_UD1 with the frame count bit toggled confirms it; a one-time alarm is then answered with E5.

func (*Master) Exchange

func (m *Master) Exchange(ctx context.Context, f Frame, answer bool) (Frame, error)

Exchange sends a frame and reads one answer: the frame count bit is set by the link sequence, and an unanswered frame or a damaged answer is repeated up to Retries times. Without answer the frame is sent once and followed by the pause a datagram nobody answers needs.

func (*Master) ExpectACK

func (m *Master) ExpectACK(ctx context.Context, f Frame, what string) error

ExpectACK sends a frame that is answered with E5; what names it in errors.

func (*Master) ImageCommand

func (m *Master) ImageCommand(ctx context.Context, a byte, hdr []byte, seg Segment, want bool) (Segment, error)

ImageCommand sends one image transfer command segment (EN 13757-3:2025 annex I, CI C0h behind our long header hdr) to the selected address a and, when want is set, reads the response segment with the same segment ID.

func (*Master) Port

func (m *Master) Port() (*Port, error)

Port is the open line.

func (*Master) Probe

func (m *Master) Probe(ctx context.Context, pattern SecondaryAddress) (int, SecondaryAddress, error)

Probe selects a pattern and reports how many slaves match: 0, 1 (with its address) or 2 meaning "more than one" (a collision).

func (*Master) ReadAddress

func (m *Master) ReadAddress(ctx context.Context, a byte) (SecondaryAddress, error)

ReadAddress reads the selected address a once for its long header: the slave's full secondary address.

func (*Master) ReadTelegrams

func (m *Master) ReadTelegrams(ctx context.Context, a byte, max int, fn func(Telegram) error) (int, error)

ReadTelegrams sends REQ_UD2 to the selected address a until the slave has no more telegrams (the last record is not DIF 1Fh), up to max telegrams, and passes each answer to fn. It stops at an application error (returned after fn saw it), a fixed data structure and a DLMS APDU, and returns how many telegrams were read. The frame count bit starts at 1 after SND_NKE or selection and toggles with each REQ_UD2.

func (*Master) Repeater added in v0.2.0

func (m *Master) Repeater(ctx context.Context, c, ci byte, data []byte, answer bool) (Frame, error)

Repeater sends a management frame to the primary master repeater at address 251 (EN 13757-2:2018+A1:2023, 5.7.5) and returns its answer (none when answer is false). The standard reserves the address but leaves the commands to the repeater's maker, so c, ci and data are the caller's: a short frame when ci is 0 and data empty, else a long one.

func (*Master) RequestClass1

func (m *Master) RequestClass1(ctx context.Context, a byte) (*Response, error)

RequestClass1 requests class 1 data (REQ_UD1, EN 13757-2 clause 5) of the selected address a. A slave with nothing to report acknowledges with E5 (a nil response); otherwise it answers RSP_UD, usually with an alarm status (CI 71h).

func (*Master) Reset

func (m *Master) Reset(ctx context.Context, a byte) error

Reset sends an application reset (SND_UD CI 50h) to the selected address a.

func (*Master) Search

func (m *Master) Search(ctx context.Context) ([]SecondaryAddress, error)

Search runs the wildcard search over the identification digits, most significant first, going one digit deeper wherever slaves collide, and returns the slaves found (also when it fails part way).

func (*Master) Select

func (m *Master) Select(ctx context.Context, t Target) (byte, error)

Select prepares a slave for REQ_UD2: SND_NKE to its primary address, or selection of its secondary address. It returns the address to poll.

func (*Master) SelectApplication

func (m *Master) SelectApplication(ctx context.Context, a byte, app, block int) error

SelectApplication selects a message application and block (EN 13757-3:2025 clause 7.2) at the selected address a.

func (*Master) SelectOne

func (m *Master) SelectOne(ctx context.Context, t Target) (a byte, full *SecondaryAddress, err error)

SelectOne prepares a slave for a command that changes it. A slave named by a secondary address with wildcards (ID or ID.MAN, version and medium left open) can select several slaves sharing its identification number, which would all carry the command out and acknowledge as one (EN 13757-2: simultaneous single characters cannot be told apart). So the selected slaves are read once: a collision, or an answer from another address than the target's, refuses the command; otherwise the slave's full address is selected for the command. full is that address when it was read (nil otherwise).

func (*Master) SetPort

func (m *Master) SetPort(p *Port, baud int)

SetPort gives the master its line at a baud rate (nil when the line is closed).

func (*Master) SetPrimary

func (m *Master) SetPrimary(ctx context.Context, t Target, to byte) (lostACK bool, err error)

SetPrimary gives the slave t the primary address to (1 to 250): the address must be free (no slave acknowledges SND_NKE there), then the slave is selected alone (SelectOne) and sent the data record DIF 01h, VIF 7Ah. When its acknowledgement is lost, the repeats to the old address go unanswered; a slave answering at the new address (free before) then has it, and lostACK reports that case.

func (*Master) SwitchBaud

func (m *Master) SwitchBaud(ctx context.Context, a byte, baud int) error

SwitchBaud sends the baud rate switch of clause 11 (a control frame with the baud rate's CI) to address a, acknowledged at the old rate. The caller then reopens the line at the new rate; the slave must answer there within 2 minutes.

type Port

type Port struct {
	// contains filtered or unexported fields
}

Port turns a byte stream into ReadByte calls with a deadline. A reader goroutine feeds a channel, so serial read timeouts and TCP reads look the same.

func NewPort

func NewPort(rw io.ReadWriteCloser) *Port

NewPort reads rw in the background.

func (*Port) Close

func (p *Port) Close() error

Close ends the port.

func (*Port) Done

func (p *Port) Done() <-chan struct{}

Done is closed when the port stops (Err says why).

func (*Port) Drain

func (p *Port) Drain()

Drain discards whatever arrived so far (echoes, late answers).

func (*Port) Err

func (p *Port) Err() error

Err is why the port stopped.

func (*Port) ReadByte

func (p *Port) ReadByte() (byte, error)

ReadByte returns the next byte, ErrTimeout after the deadline.

func (*Port) SetDeadline

func (p *Port) SetDeadline(t time.Time)

SetDeadline bounds the following ReadByte calls; zero waits forever.

func (*Port) Write

func (p *Port) Write(b []byte) (int, error)

Write writes to the line; a failed write ends the port.

type PrepareCmd

type PrepareCmd struct {
	Multicast  bool
	Absolute   bool   // ADT: Start is EPOCH 2013 seconds, else seconds from now
	Start      uint32 // with Multicast
	Pace       byte   // seconds between blocks, with Multicast
	Size       *SizeInfo
	ID         *ImageID
	MAC        *MAC
	Additional *[2]byte
}

PrepareCmd is the prepare command (tables I.5 and I.6). The optional fields are present when set.

func (PrepareCmd) Segment

func (c PrepareCmd) Segment(id byte) (Segment, error)

Segment encodes the command; fields follow the sub-function in the order of table I.5.

type PrepareRsp

type PrepareRsp struct {
	Ready      bool
	Multicast  bool
	Result     byte
	ID         *ImageID
	Size       *SizeInfo
	Additional []byte
}

PrepareRsp is the prepare response (tables I.12 to I.14).

func ParsePrepareRsp

func ParsePrepareRsp(s Segment) (PrepareRsp, error)

ParsePrepareRsp decodes a prepare response segment.

func (PrepareRsp) ResultName

func (r PrepareRsp) ResultName() string

ResultName names a preparation result.

type Response

type Response struct {
	Address  SecondaryAddress // from the long header (CI 72/76)
	Access   byte
	Status   byte
	Records  []records.Record
	More     bool // the last record was DIF 1F: another telegram follows
	CI       byte
	Fixed    *FixedData // CI 73/77
	Alarm    []byte     // CI 71: the alarm status bytes
	ACD      bool       // the slave has class 1 (alarm) data waiting
	Primary  byte
	Header   bool
	DecodeOK bool
	// AppError is set for an application error response (CI 6Eh, 6Fh,
	// 70h, EN 13757-3:2025 clause 10.3).
	AppError *AppError
	// Selected marks a response of a selected application (CI 66h, 67h,
	// 68h, clause 7.3).
	Selected bool
	// DLMS is the DLMS/COSEM APDU of a CI 7Ch/7Dh response.
	DLMS []byte
	// TPDU is a transport PDU of a DLMS/COSEM APDU (CI 00h to 1Fh, EN
	// 13757-1:2021 8.2.4).
	TPDU *tpdu.TPDU
	// UnknownCI marks an answer with a CI this decoder does not know; its
	// data is the one manufacturer_data record.
	UnknownCI bool
}

Response is a decoded RSP_UD.

func ParseResponse

func ParseResponse(f Frame) (*Response, error)

ParseResponse decodes an RSP_UD with a variable data structure.

func (*Response) HasStatus

func (r *Response) HasStatus() bool

header reads the TPL header a CI implies (none, short: access number, status, 2 bytes configuration; long: the 8-byte address first) and returns the rest. HasStatus reports whether the response carried a short or long header, so its Status is a TPL status byte (EN 13757-3:2025 10.2). Fixed data structures (CI 73h/77h) have a status byte with other bit meanings and are not included.

type SecondaryAddress

type SecondaryAddress struct {
	ID           string // eight digits (F: any)
	Manufacturer uint16 // 0xFFFF: any
	Version      byte   // 0xFF: any
	Medium       byte   // 0xFF: any
}

SecondaryAddress identifies a slave: the 8-digit identification number, manufacturer, version and medium. In a selection pattern any ID digit may be F and the other fields their wildcard values.

func ParsePattern

func ParsePattern(s string) (SecondaryAddress, error)

ParsePattern reads a secondary address pattern from configuration: "12345678", "1234FFFF", optionally with manufacturer, version and medium as "12345678.KAM.01.07" (use "*" or "FF" for any).

func ParseSecondary

func ParseSecondary(b []byte) SecondaryAddress

ParseSecondary reads the 8-byte form.

func (SecondaryAddress) Bytes

func (s SecondaryAddress) Bytes() ([]byte, error)

Bytes is the 8-byte form used in selection and in the long header (ID in BCD, least significant byte first; manufacturer LSB first).

func (SecondaryAddress) Key

func (s SecondaryAddress) Key() string

Key is "MAN-ID", the device identifier used for discovered meters.

func (SecondaryAddress) Matches

func (s SecondaryAddress) Matches(pattern SecondaryAddress) bool

Matches reports whether a concrete address matches a selection pattern.

type Segment

type Segment struct {
	ID       byte
	Function byte
	Sub      byte
	Params   []byte
}

Segment is one command or response segment (tables I.2 and I.3).

func EncodeCompletionRsp

func EncodeCompletionRsp(id byte, lost []uint16, none bool) Segment

EncodeCompletionRsp builds a completion response (for simulators).

func ParseSegments

func ParseSegments(b []byte) ([]Segment, error)

ParseSegments splits image transfer data into segments. Any invalid length rejects the whole structure.

func SimpleCmd

func SimpleCmd(id byte, function byte, img *ImageID, flags byte, extra []byte) Segment

SimpleCmd is a command whose parameters are an optional image identifier and optional fields in order: completion, state and validate (IDEN bit 1), terminate (IDEN bit 2 with T_TR/T_IT flags) and activate (IDEN bit 1 and a 4-byte date and time).

type SizeInfo

type SizeInfo struct {
	Blocks     uint16
	BlockSize  uint16
	Repetition byte
}

SizeInfo is the size information field (table I.8).

type StateRsp

type StateRsp struct {
	Function byte
	State    int
	ID       *ImageID
}

StateRsp is a response carrying the transfer state in the sub-function (transfer, state, validate, activate and terminate responses).

func ParseStateRsp

func ParseStateRsp(s Segment) (StateRsp, error)

ParseStateRsp decodes such a response.

type Target

type Target struct {
	Primary   byte
	Secondary *SecondaryAddress
	Name      string
}

Target names one slave: by its primary address, or (when Secondary is set) by its secondary address, which may have wildcards. Name is how errors call it.

type Telegram

type Telegram struct {
	*Response
	ParseErr error
	APDU     []byte
}

Telegram is one answer to REQ_UD2 in ReadTelegrams. ParseErr says what of it was not decoded; APDU is a whole DLMS/COSEM APDU (CI 7Ch/7Dh, or the transport PDUs up to the last one joined).

type TransferCmd

type TransferCmd struct {
	ID        *ImageID
	Block     uint16
	Blocks    uint16 // total, for the sequence state and remaining field
	Remaining bool   // include the remaining field
	Data      []byte
}

TransferCmd is one image block (tables I.17 and I.18).

func ParseTransferCmd

func ParseTransferCmd(s Segment) (TransferCmd, error)

ParseTransferCmd decodes a transfer command segment (used by simulators).

func (TransferCmd) Segment

func (c TransferCmd) Segment(id byte) Segment

Segment encodes the command.

Jump to

Keyboard shortcuts

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