wireless

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: 27 Imported by: 1 module, 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 wireless is Wireless M-Bus and OMS: the EN 13757-4 link layer (frame formats A and B with their CRCs, the 3-out-of-6 code, C fields, radio modes, FEC of mode F), the EN 13757-7:2025 transport and security layers (ELL, AFL with fragmentation, TPL short and long headers, security modes 5 and 7 to 10 and the deprecated DES modes 2 and 3, KDF-A, message counters with replay detection, mode 13 TLS records), security information transfer (SITP, annex A), compact frames (EN 13757-3:2025 annex G), the OMS Volume 2 profiles, the framings of receiver sticks (iM871A, Amber, raw, hexadecimal lines), and frames a gateway sends to bidirectional meters with a scheduler that sends one frame per receive window (Scheduler).

Decode (or a Decoder, which keeps fragments and counters) turns a frame into a Telegram with the meter's header, the security facts and the data records (package records). Mode 13 TLS endpoints use github.com/cB-Sigma/tlsx, a crypto/tls fork with the brainpool curves and TLS 1.2 features BSI TR-03116-3 needs.

Index

Examples

Constants

View Source
const (
	CICompactNone  byte = 0x79
	CICompactShort byte = 0x7B
	CICompactLong  byte = 0x73
	CIFormatNone   byte = 0x69
	CIFormatShort  byte = 0x6A
	CIFormatLong   byte = 0x6B
)

CI fields of the full, compact and format frames with no, short or long TPL header (G.2.1, Table G.2); the full-frame ones are CINoHeader, CIShortHeader and CILongHeader.

View Source
const (
	CIReqFullLong     byte = 0x80
	CIReqCompactLong  byte = 0x84
	CIReqFormatLong   byte = 0x85
	CIReqFullShort    byte = 0x93
	CIReqCompactShort byte = 0x94
	CIReqFormatShort  byte = 0x95
)

CI fields a partner uses to ask a meter for one frame kind (Table G.1), with a long or a short TPL header.

View Source
const (
	KindFull    = "full"
	KindCompact = "compact"
	KindFormat  = "format"
)

Frame kinds by CI field.

View Source
const (
	DCEncMeter byte = 0x00 // Kenc, meter to other
	DCMACMeter byte = 0x01 // Kmac, meter to other
	DCEncOther byte = 0x10 // Lenc, other to meter
	DCMACOther byte = 0x11 // Lmac, other to meter
)

Key derivation function A (EN 13757-7:2025 clause 9.6.2): the derivation constant says which key and which direction.

View Source
const (
	CSndNR = 0x44 // SND-NR: a meter's spontaneous telegram
	CSndIR = 0x46 // SND-IR: installation request
	CCnfIR = 0x06 // CNF-IR: confirmation of an installation request
	CSndUD = 0x53 // SND-UD with FCV set (73h with FCB)
	CACK   = 0x00 // ACK
	// CCGateway is the CC field of our frames: bidirectional, as in the
	// OMS annex N examples of a gateway's CNF-IR and SND-UD.
	CCGateway = 0x84
	// CIToMeterLong is the TPL long header of application data sent to a
	// meter (EN 13757-7); CIToMeterNoAPL carries no application data.
	CIToMeterLong  byte = 0x5B
	CIToMeterNoAPL byte = 0x80
)

Link-layer C fields of the frames a gateway sends and a meter answers with (link.go has the rest of tables 33 to 35).

View Source
const (
	ExpectNone     = ""           // SND-NKE, CNF-IR
	ExpectACK      = "ack"        // SND-UD
	ExpectRSP      = "rsp"        // SND-UD2, REQ-UD2
	ExpectACKOrRSP = "ack-or-rsp" // REQ-UD1
)

The answers a meter owes to a frame we send (EN 13757-4:2025 tables 34 and 35).

View Source
const (
	CPRM      = 0x40 // from the primary station
	CFCB      = 0x20 // ACD from a secondary station
	CFCV      = 0x10 // DFC from a secondary station
	CFunction = 0x0F // the function code bits

	CSndNKE  = 0x40 // link reset, to meter
	CSndUD2  = 0x43 // SND-UD with FCV cleared: answered with RSP-UD
	CSndUDF  = 0x73 // SND-UD, FCB and FCV set
	CSndUD3  = 0x45 // multicast/broadcast command, no reply
	CAccNR   = 0x47 // access opportunity, no application data
	CAccDMD  = 0x48 // access demand, answered with ACK
	CReqUD1  = 0x5A // alarm request (FCV set; 7Ah with FCB)
	CReqUD2  = 0x5B // data request (FCV set; 7Bh with FCB)
	CNACK    = 0x01 // NACK: the frame was not accepted
	CRspUD   = 0x08 // RSP-UD: answer with user data
	CReqUD1F = 0x7A // REQ-UD1 with FCB set
	CReqUD2F = 0x7B // REQ-UD2 with FCB set
)

C-field (EN 13757-4:2025, 12.5.4, Tables 33 to 35): bit 7 reserved (0), bit 6 PRM (1 = from the primary station), bit 5 FCB/ACD, bit 4 FCV/DFC, bits 3..0 the function code. downlink.go names SND-NR (44h), SND-IR (46h), CNF-IR (06h), SND-UD with FCV set (53h) and ACK (00h).

View Source
const (
	CCBidirectional = 0x80 // B
	CCFastDelay     = 0x40 // D: response delay
	CCSynchronized  = 0x20 // S
	CCHop           = 0x10 // H: relayed by a repeater
	CCPriority      = 0x08 // P
	CCAccessible    = 0x04 // A
	CCRepeated      = 0x02 // R: repeated access
	CCExtendedDelay = 0x01 // X (with D; mode N only)
)

Extended link layer CC field bits (13.2.7, Table 50).

View Source
const (
	ECLPayloadCRC = 0x80 // PLP
	ECLRXL        = 0x10 // RXLP
	ECLRTDMask    = 0x0C // RTDP: 01 = 1/256 s, 10 = 2 s, 11 reserved
	ECLSN         = 0x02 // SNP
	ECLAddress    = 0x01 // MAP: M2 and A2
)

ECL bits of the variable ELL, CI 86h (13.2.6, Table 49).

View Source
const (
	TLSCHAN byte = 0x00
	TLSPROT byte = 0x01
)

Mode 13 protocol types (CFE, table F.5).

View Source
const (
	CITLSToMeter byte = 0x5F // long header, from the gateway
	CITLSShort   byte = 0x9E // short header, from the meter
	CITLSLong    byte = 0x9F // long header, from a meter behind an adapter

)

Mode 13 CI fields (EN 13757-7:2025 table 16 "specific usage"; annex F table F.7).

View Source
const (
	TLSSessionLife  = 31 * 24 * time.Hour
	TLSSessionBytes = 5 << 20
)

Session limits of annex F F.3.1: 31 days and 5 Mbytes of TLS data.

View Source
const (
	CIToMeterShort byte = 0x5A // command to a device, short header (5Bh: long)
	CIClockLong    byte = 0x6C // clock synchronisation, long header
	CIClockShort   byte = 0x6D // clock synchronisation, short header
	CIAppErrShort  byte = 0x6E // application error from the device, short header
	CIAppErrLong   byte = 0x6F // application error from the device, long header
	CIAlarmShort   byte = 0x74 // alarm from the device, short header
	CIAlarmLong    byte = 0x75 // alarm from the device, long header
	CIPureShort    byte = 0x8A // TPL only, from the device, short header
	CIPureLong     byte = 0x8B // TPL only, from the device, long header

	// DLMS/COSEM APDUs carried by M-Bus (EN 13757-1:2021 9.2.1 Figure 11,
	// EN 13757-7 CI table, EN 62056-7-3): to the meter 60h (long header)
	// and 61h (short), from the meter 7Ch (long) and 7Dh (short). The APDU
	// is kept as bytes; it is not decoded here.
	CIDLMSToMeterLong  byte = 0x60
	CIDLMSToMeterShort byte = 0x61
	CIDLMSLong         byte = 0x7C
	CIDLMSShort        byte = 0x7D
)

TPL CI fields whose application data are not data records, or that carry no application data (OMS Volume 2 v5.0.1 Table 42; EN 13757-7 CI field table): the short and long header variants. Annex N shows 6Ch (N.8.2), 6Eh with a short header (N.9) and 8Bh (N.6.2, N.8.2, N.10).

View Source
const (
	OMSProfileNone = "none" // security mode 0, no AFL MAC
	OMSProfileA    = "A"    // mode 5 (AES-CBC, persistent key), no MAC
	OMSProfileB    = "B"    // mode 7 with KDF-A and an AFL AES-CMAC of 8 bytes
	OMSProfileC    = "C"    // mode 13 (TLS)
	OMSProfileD    = "D"    // mode 10 with KDF-A, the counter in the TPL and an 8-byte CCM tag
)

OMS security profiles (OMS Volume 2 v5.0.1 clause 9.1, Table 43).

View Source
const (
	FramerIM871A = "im871a" // IMST iM871A / WiMOD HCI
	FramerAmber  = "amber"  // Würth/Amber AMB8465 and relatives, command mode
	FramerRaw    = "raw"    // L-field framing (Amber transparent mode, bare radios)
	FramerHex    = "hex"    // one hexadecimal telegram per line (rtl-wmbus style, gateways)
)

Framer names.

View Source
const (
	IM871ASOF       = 0xA5 // start of frame
	IM871ARadioLink = 0x02 // the radio link endpoint
	IM871AMsgInd    = 0x03 // radio link: a received telegram
	IM871ADataReq   = 0x01 // radio link: send a telegram
	IM871ATimestamp = 0x20 // control bit: a timestamp follows
	IM871ARSSI      = 0x40 // control bit: an RSSI byte follows
	IM871ACRC       = 0x80 // control bit: a CRC-16 follows
)

iM871A HCI: start byte, control/endpoint, message ID, length, payload, then an optional 32-bit timestamp, RSSI byte and CRC-16 as the control nibble announces.

View Source
const (
	AmberStart   = 0xFF // start of a command
	AmberDataInd = 0x03 // a received telegram
	AmberDataReq = 0x00 // send a telegram
)

Amber command mode: 0xFF, command, length, payload, XOR checksum of every byte before it. Received radio telegrams are command 0x03.

View Source
const (
	StateQueued         = "queued"
	StateSent           = "sent"
	StateAcknowledged   = "acknowledged"
	StateAnswered       = "answered"
	StateRejected       = "rejected"
	StateUnacknowledged = "unacknowledged"
	StateExpired        = "expired"
	StateFailed         = "failed"
)

Downlink states reported through Scheduler.State.

View Source
const (
	CISITPCmdLong   byte = 0xC3
	CISITPRespShort byte = 0xC4
	CISITPRespLong  byte = 0xC5
	CISITPCmdShort  byte = 0xC6
)

SITP CI fields (table A.1).

View Source
const (
	SITPTransfer     byte = 0x00 // DSI 01h
	SITPActivate     byte = 0x01 // DSI 02h
	SITPDeactivate   byte = 0x02 // DSI 02h
	SITPDestroy      byte = 0x03 // DSI 02h
	SITPCombined     byte = 0x04 // DSI 03h
	SITPGenerate     byte = 0x05 // DSI 02h
	SITPGetInfo      byte = 0x06 // DSI 00h → 01h or 22h
	SITPListAll      byte = 0x07 // DSI 00h → 20h or 22h
	SITPListActive   byte = 0x08 // DSI 00h → 21h or 22h
	SITPListCounters byte = 0x09 // DSI 00h → 23h or 22h
	SITPSecuredData  byte = 0x20 // DSI 30h–37h → A0h
)

Block control field commands (table A.3); a response is the command with bit 7 set (A0h answers 20h).

View Source
const (
	DSIEmpty        byte = 0x00
	DSIKey          byte = 0x01 // KWP: key, target time, key ID, version
	DSIKeyAction    byte = 0x02 // KWP: target time, key ID, version
	DSIKeyPair      byte = 0x03 // KWP: target time, activate and deactivate IDs/versions, option
	DSIAllKeys      byte = 0x20 // KWP: all key IDs and versions
	DSIActiveKeys   byte = 0x21 // key ID, version pairs
	DSIStatus       byte = 0x22 // one status byte
	DSIActiveCounts byte = 0x23 // key ID, version, key counter
	DSICertificate  byte = 0x10 // X.509 certificates, DER (OMS annex F table F.A.5)
	DSIKeyPairDER   byte = 0x11 // key pair, DER (RFC 5958), OMS annex F
	DSIHMACSHA256   byte = 0x31
	DSICMAC8        byte = 0x32
	DSICMAC16       byte = 0x33
	DSIGCM          byte = 0x34
	DSIGMAC         byte = 0x35
	DSICCM8         byte = 0x36
	DSICCM16        byte = 0x37
)

Data structure identifiers (table A.5).

View Source
const (
	KeyIDMaster        byte = 0x00 // master key MK
	KeyIDGatewayCert1  byte = 0x81 // trust anchor: the gateway certificate
	KeyIDGatewayCert2  byte = 0x82
	KeyIDMeterCert     byte = 0x90 // the meter's TLS certificate (MTR_TLS_CRT)
	KeyIDMeterKeyPair  byte = 0xA0 // its key pair
	KeyVersionUnused   byte = 0xFF
	SITPStatusMismatch byte = 0x81
)

Key IDs of OMS Volume 2 annex F (F.4.3.1, F.4.4.1, table F.A.8).

View Source
const (
	SITPDown byte = 0x01 // partner to meter
	SITPUp   byte = 0x02 // meter to partner
)

SITP directions of the IV/nonce of structures 34h–37h.

View Source
const (
	FramerCUL      = "cul"      // CUL / nanoCUL running culfw: "b" + hex lines
	FramerRTLWMBUS = "rtlwmbus" // rtl-wmbus: "mode;crc;3of6;time;rssi;rssi;id;0xhex" lines
)

More framer names.

View Source
const (
	IM871ADevMgmt       = 0x01
	IM871APingReq       = 0x01
	IM871APingRsp       = 0x02
	IM871ASetConfigReq  = 0x03
	IM871ASetConfigRsp  = 0x04
	IM871AGetDevInfoReq = 0x0F
	IM871AGetDevInfoRsp = 0x10
)

iM871A device management endpoint and the messages used here.

View Source
const (
	IM871AModeS1  = 0x00
	IM871AModeS1m = 0x01
	IM871AModeS2  = 0x02
	IM871AModeT1  = 0x03
	IM871AModeT2  = 0x04
	IM871AModeR2  = 0x05
	IM871AModeC1A = 0x06
	IM871AModeC1B = 0x07
	IM871AModeC2A = 0x08
	IM871AModeC2B = 0x09
	// IM871AModeCT receives C1 and T1 together (or N1a on N-band
	// hardware), on firmware that has it.
	IM871AModeCT = 0x0A
)

iM871A link modes (the HCI's radio mode parameter).

View Source
const (
	AmberSetModeReq = 0x04
	AmberSetModeCnf = 0x84
	AmberModeS2     = 0x03 // collector, S1 and S1-m
	AmberModeT2     = 0x08 // collector, T1 and T2 (bidirectional)
	AmberModeC2T2   = 0x09 // collector, C and T together
	AmberModeR2     = 0x0B
	AmberModeC2     = 0x0E // collector, C (bidirectional)
)

Amber (AMB8465 and relatives) command mode: the set-mode request and its confirmation, and the mode codes of a collector.

View Source
const (
	CINoHeader    byte = 0x78 // APL follows, no TPL header
	CIShortHeader byte = 0x7A
	CILongHeader  byte = 0x72
	CIELL2        byte = 0x8C // ELL: CC, ACC
	CIELL8        byte = 0x8D // ELL: CC, ACC, SN, payload CRC
	CIELL10       byte = 0x8E // ELL: CC, ACC, M2, A2 (the destination)
	CIELL16       byte = 0x8F // ELL: CC, ACC, M2, A2, SN, payload CRC
	CIELLV        byte = 0x86 // variable ELL: CC, ACC, ECL, then what ECL selects
	CIAFL         byte = 0x90
	CIAppError    byte = 0x70
	CIAlarm       byte = 0x71
)

CI field values handled here.

View Source
const (
	AFLMF   = 1 << 14 // more fragments
	AFLMCLP = 1 << 13 // message control present
	AFLMLP  = 1 << 12 // message length present
	AFLMCRP = 1 << 11 // message counter present
	AFLMACP = 1 << 10 // MAC present
	AFLKIP  = 1 << 9  // key information present
)

AFL field control bits (EN 13757-7:2025 clause 6): which fields are present, and more fragments follow.

View Source
const DefaultFormatCacheSize = 1024

DefaultFormatCacheSize bounds the formats kept (and persisted).

View Source
const (
	FECIDReedSolomon = 0x01
)

FECIDReedSolomon is FEC ID 01h (header value 0421h).

View Source
const FragmentTimeout = 2 * time.Minute

FragmentTimeout is how long a partial message is kept.

View Source
const LMNMaxDays = 7 * 365

LMNMaxDays is the validity of a certificate the gateway makes for a meter: 7 years (BSI TR-03116-3 Table 17).

View Source
const OMSMaxMessage = 16 * 1024

OMSMaxMessage is the OMS limit of a fragmented message (OMS Volume 2 6.2.5: 16 kbytes), applied with the omsProfile setting.

View Source
const WarnFullFrameCRC = "full-frame-crc-ignored: the rebuilt records do not match the compact frame's Full-Frame-CRC; the format may be outdated"

WarnFullFrameCRC is the warning of a compact frame rebuilt although its Full-Frame-CRC did not match (FormatCache.IgnoreFullFrameCRC).

Variables

View Source
var (
	// ErrCompactFrame is what Decode returns for a compact or format frame:
	// its records need the format cache (FormatCache.Complete).
	ErrCompactFrame = errors.New("compact or format frame: the data records need the meter's format")
	// ErrFormatUnknown: no format with the compact frame's signature is
	// known for the meter yet.
	ErrFormatUnknown = errors.New("compact frame whose format (signature) is not known yet")
	// ErrFullFrameCRC: the rebuilt frame does not match the Full-Frame-CRC;
	// the cached format is outdated and is dropped.
	ErrFullFrameCRC = errors.New("the rebuilt full frame does not match its Full-Frame-CRC")
	// ErrFormatSignature: a format frame's bytes do not match its signature.
	ErrFormatSignature = errors.New("the format frame does not match its Format Signature")
)

Errors of the compact frame handling.

View Source
var (
	ErrFECUncorrectable = errors.New("wM-Bus FEC: too many symbol errors to correct")
	ErrFECAbsent        = errors.New("wM-Bus FEC: no Reed-Solomon FEC data after the frame")
)

Errors of the FEC decoder.

View Source
var (
	// ErrReplay: the message counter is not above the last verified one.
	ErrReplay = errors.New("the message counter is not newer than the last verified one (replay)")
	// ErrRepeat: the same message again (a repeat or a second receiver);
	// not an attack, but its counter is spent.
	ErrRepeat = errors.New("the same secured message was already accepted")
)

More error kinds (EN 13757-7:2025 clause 9.5: a message failing the counter check, the authentication check or the decryption verification is discarded; the caller may report it to monitoring).

View Source
var (
	ErrNoKey     = errors.New("the telegram is encrypted and no key is configured for this meter")
	ErrDecrypt   = errors.New("decryption failed: the key is wrong (no 2F2F after decrypting)")
	ErrMAC       = errors.New("the telegram's MAC does not verify")
	ErrUnsupport = errors.New("unsupported")
	// ErrManufacturerCI is returned (with ErrUnsupport) for a
	// manufacturer-specific CI field (A0h to B7h); Telegram.APL then holds
	// what follows the CI field, undecoded.
	ErrManufacturerCI = errors.New("manufacturer-specific CI field")
)

Error kinds a caller may count.

View Source
var ChannelRequestRecord = []byte{tlsChannelRequest, 0, 0, 0, 0}

ChannelRequestRecord is the TLSCHAN record (table F.10).

View Source
var ErrCRC = errors.New("wM-Bus frame CRC mismatch")

ErrCRC is returned for a frame whose CRCs do not match.

View Source
var ErrFragment = errors.New("fragment of a longer message: waiting for the rest")

ErrFragment is returned for a fragment that was kept until the rest of its message arrives.

View Source
var ErrFullFrameCRCIgnored = errors.New(WarnFullFrameCRC)

ErrFullFrameCRCIgnored comes with the rebuilt records from Expand and ExpandEncrypted when FormatCache.IgnoreFullFrameCRC let a frame through whose Full-Frame-CRC did not match: the records are returned, and the error is the warning. (Complete turns it into Warnings.)

View Source
var ErrSITPLength = errors.New("SITP block length below 6: the whole structure is ignored")

ErrSITPLength is a block length below 6: the whole structure is ignored (the meter answers application error 15h).

View Source
var ErrSecurityMode = errors.New("security mode not defined by EN 13757-7:2025")

ErrSecurityMode is returned for a security mode EN 13757-7:2025 does not define for this protocol (7.5.8 table 19).

View Source
var ErrStickRefused = errors.New("the receiver stick refused the command")

ErrStickRefused is returned when a stick answers a command with an error status.

Mode13Curves are the ECDHE curves the gateway accepts, in preference order: the curves of annex F Table F.2 (brainpoolP256r1 and P-256 are mandatory, the others recommended).

Mode13Suites are the cipher suites the gateway accepts, in preference order: ECDHE_ECDSA with AES-GCM, then with AES-CBC and encrypt-then-MAC. Annex F names no suite list of its own (it refers to BSI TR-03116-3); these are the four of its ClientHello example (F.D.3), and with encrypt-then-MAC offered the server uses GCM or encrypt-then-MAC (F.3.1) (F-555).

Functions

func AddCRCA

func AddCRCA(t []byte) []byte

AddCRCA builds a format A frame from a CRC-less one (for tests and simulators).

func AddCRCB

func AddCRCB(t []byte) []byte

AddCRCB builds a format B frame from a CRC-less one.

func AmberSetMode added in v0.2.0

func AmberSetMode(mode byte) []byte

AmberSetMode is the command-mode request that selects a mode.

func Answers

func Answers(e string, c byte) bool

Answers reports whether a meter frame with C field c answers a frame that expects e (ACD and DFC bits ignored). A legacy meter may ACK an SND-UD2 (table 34 note c); NACK answers SND-UD and SND-UD2.

func BCDID

func BCDID(b []byte) string

BCDID prints a 4-byte identification number sent least significant byte first (the A field's first four bytes) as its eight digits.

func BuildFormat

func BuildFormat(records []byte) ([]byte, error)

BuildFormat derives the format (the DIF … VIF bytes, idle fillers included) from a full frame's data records (G.2.2). Trailing idle fillers are left out.

func CFieldName

func CFieldName(c byte) string

CFieldName names a C-field (its symbolic name in 12.5.4), or "0xNN".

func CMAC

func CMAC(key, msg []byte) ([]byte, error)

CMAC computes AES-CMAC (NIST SP 800-38B, RFC 4493) of msg with a 16-byte key.

func CRC

func CRC(b []byte) uint16

CRC computes the link-layer CRC of EN 13757-4 (polynomial 0x3D65, initial value 0, no reflection, result complemented), as used in both frame formats.

func CRCX25

func CRCX25(b []byte) uint16

CRCX25 is the CRC-16 of the WiMOD HCI (polynomial 0x1021 reflected, initial 0xFFFF, complemented).

func CheckLMNCertificate

func CheckLMNCertificate(der []byte) error

CheckLMNCertificate checks a gateway or meter certificate against the LMN profile of BSI TR-03116-3 6.3: an ECDSA key on a Table 4 curve and at most 7 years of validity.

func ConfigureAmber added in v0.2.0

func ConfigureAmber(ctx context.Context, rw io.ReadWriter, mode byte) error

ConfigureAmber sets an Amber stick's mode (command mode) and waits for the confirmation.

func ConfigureCUL added in v0.2.0

func ConfigureCUL(ctx context.Context, rw io.ReadWriter, mode string) error

ConfigureCUL starts a culfw stick's Wireless M-Bus receiver in mode "T1", "S1" or "C1" (C1 also receives T1), then turns on the LQI and RSSI suffix the CUL framer expects (X21).

func ConfigureIM871A added in v0.2.0

func ConfigureIM871A(ctx context.Context, rw io.ReadWriter, mode byte, persist bool) error

ConfigureIM871A sets an iM871A's link mode and waits for its confirmation. Telegrams that arrive meanwhile are dropped. Not checked against a real stick (see the README).

func Decode3of6

func Decode3of6(chips []byte) ([]byte, error)

Decode3of6 decodes a mode T (meter to other) chip sequence: every 12 bits are two code words for the high and low nibble of one byte. A trailing partial byte is ignored.

func DecodeFEC

func DecodeFEC(b []byte, format FrameFormat) ([]byte, int, error)

DecodeFEC takes the bytes following the sync word (frame, FEC header, check data, maybe more) and returns the corrected frame and the number of corrected bytes. The frame length comes from the L field in the given format (A or B), so an error in the L field itself is not recoverable.

func DeriveKey

func DeriveKey(master []byte, dc byte, counter uint32, id [4]byte) ([]byte, error)

DeriveKey is KDF-A: CMAC under the master key of the derivation constant, the message counter and the meter ID (both as transmitted, least significant byte first), padded with 0x07 to one block.

func DuplicateKey

func DuplicateKey(t []byte) (string, error)

DuplicateKey identifies a frame for duplicate detection (12.7): the CRC-less frame with the fields a simple repeater changes neutralised (the H and R bits of the ELL CC field and of a mode 0 or 5 TPL configuration field, and the RTD and RXL fields of a variable ELL). A frame heard directly and again through a repeater, or twice, gives the same key.

func Encode3of6

func Encode3of6(b []byte) []byte

Encode3of6 is Decode3of6's inverse (for tests and simulators).

func EncodeAmber

func EncodeAmber(frame []byte, withL bool) []byte

EncodeAmber frames a CRC-less telegram (sent without its L field unless withL) as an Amber command-mode data request.

func EncodeDownlink(gw Gateway, meter Header, dl Downlink, ellACC, tplACC byte, key []byte) ([]byte, error)

EncodeDownlink builds a CRC-less frame from the gateway to a meter: link header, ELL (CI 8Ch: CC, ACC), TPL long header naming the meter, and the application data (security mode 5 when key is set). ellACC and tplACC are the ELL and TPL access numbers.

func EncodeDownlinkSealed

func EncodeDownlinkSealed(gw Gateway, meter Header, dl Downlink, ellACC, tplACC byte, sec DownlinkSeal) ([]byte, error)

EncodeDownlinkSealed is EncodeDownlink with the security chosen.

func EncodeFEC

func EncodeFEC(frame []byte) ([]byte, error)

EncodeFEC appends the FEC header and Reed-Solomon check data to a frame as sent (format A or B with CRCs), for tests and simulators.

func EncodeIM871A

func EncodeIM871A(frame []byte, withL bool) []byte

EncodeIM871A frames a CRC-less telegram (sent without its L field unless withL) as an iM871A radio-link data request with the HCI CRC.

func EncodeSITP

func EncodeSITP(blocks ...SITPBlock) []byte

EncodeSITP builds the APL of an SITP command.

func ExpectFor

func ExpectFor(c byte) string

ExpectFor is the answer a meter owes to a frame with C field c.

func FECHeader

func FECHeader(id byte) uint16

FECHeader builds the 16-bit FEC header for an ID.

func FECID

func FECID(h uint16) byte

FECID reads the FEC ID from a header by bitwise majority of its three copies.

func FormatSignature

func FormatSignature(format []byte) uint16

FormatSignature is the Format Signature of a format: the EN 13757 CRC (polynomial 3D65h, initial value 0, complemented) over the DIF/DIFE and VIF/VIFE bytes from the first DIF to the last VIF or DIF (G.4).

func FrameKind

func FrameKind(ci byte) (kind, header string)

FrameKind returns the Annex G frame kind of a CI field ("full", "compact" or "format") and its TPL header kind ("none", "short", "long"); both are "" for other CI fields.

func FrameLenA

func FrameLenA(l int) int

FrameLenA is the on-air length of a format A frame with this L field.

func FullFrameCRC

func FullFrameCRC(records []byte) uint16

FullFrameCRC is the Full-Frame-CRC of a full frame's application data: the same CRC over the data records from the first byte to the end of the last record (G.3). records excludes the TPL header and the AES check bytes; trailing idle fillers are not part of it and are ignored.

func HardAddress

func HardAddress(m uint16) bool

HardAddress reports whether an M field's most significant bit is clear: the A field is then a manufacturer-unique address, else an address that is only unique within radio range (12.5.5).

func IM871AFrame added in v0.2.0

func IM871AFrame(endpoint, msg byte, payload []byte) []byte

IM871AFrame encodes an HCI message with its CRC.

func IM871ASetLinkMode added in v0.2.0

func IM871ASetLinkMode(mode byte, persist bool) []byte

IM871ASetLinkMode is the SET_CONFIG request that sets only the link mode; persist stores it in the stick's non-volatile memory.

func IsDLMS

func IsDLMS(ci byte) bool

IsDLMS reports a CI whose application data is a DLMS/COSEM APDU.

func IsHexText

func IsHexText(b []byte) bool

IsHexText reports whether a datagram is hexadecimal text.

func KWPUnwrap

func KWPUnwrap(kek, wrapped []byte) ([]byte, error)

KWPUnwrap is KWPWrap's inverse; it checks the ICV, length and padding.

func KWPWrap

func KWPWrap(kek, plain []byte) ([]byte, error)

KWPWrap wraps plain with kek: AES key wrap with padding (RFC 5649, alternative initial value A65959A6), as SITP wraps keys.

func LinkHead

func LinkHead(c byte, m uint16, a [6]byte) []byte

LinkHead is the 10 bytes after L of a frame sent from address h.

func NormalizeLinkMode

func NormalizeLinkMode(s string) (string, bool)

NormalizeLinkMode returns the canonical name of a radio (sub-)mode, e.g. "t1" → "T1", "s1m" → "S1-m", "N2g" → "N2g"; ok is false for anything else.

func OMSProfile

func OMSProfile(tg *Telegram) string

OMSProfile classifies a decoded telegram's protection by the OMS security profiles, or returns "" when the combination of security mode, key derivation and authentication is none of them (for example mode 7 without the AFL MAC, a 4-byte CCM tag, modes 8 and 9, or a MAC on a mode 0 telegram).

func RSSIToRL

func RSSIToRL(dBm float64) byte

RSSIToRL is RXLValue's inverse for an RSSI in dBm (Figure 1: −60 dBm gives 42).

func RXLValue

func RXLValue(rxl byte) (kind string, value float64, ok bool)

RXL (13.2.14, Tables 55 and 56): bit 7 set is reserved; bit 6 selects RSSI (0) or link margin (1); bits 5..0 are RL. RL 0 means no information, 1 and 63 are the open ends of the range.

func RawAPL

func RawAPL(ci byte) bool

RawAPL reports a CI whose application data is kept as bytes (Telegram.APL) instead of being read as data records.

func Rebuild

func Rebuild(format, data []byte, ffc uint16, encEnd int) ([]byte, error)

Rebuild turns a compact frame's data into the full frame's data records with a format and checks the Full-Frame-CRC. encEnd is where the encrypted part of data ends in a partly encrypted frame, else -1.

func Relayed

func Relayed(t []byte) bool

Relayed reports whether a CRC-less frame was relayed by a repeater: the hop bit H is set in the ELL CC field (13.2.7.5) or in a short or long TPL header's configuration field (EN 13757-7:2025, 7.7, security modes 0 and 5).

func ResponseDelay added in v0.2.0

func ResponseDelay(linkMode string, tg *Telegram) (lo, hi time.Duration, ok bool)

ResponseDelay is the window, counted from the end of a meter's transmission, in which the meter listens for a gateway's frame (EN 13757-4:2025, the response delay tRO of tables 5, 8 and 15): modes S 3 to 15 ms, T 2 to 3 ms, C 99,5 to 100,5 ms, or 999,5 to 1 000,5 ms when the meter asks for the slow delay (the D bit of the extended link layer's CC field clear; without an extended link layer the fast delay is the default). ok is false for a mode not covered here (R, N, F).

func SITPPlainAction

func SITPPlainAction(at TargetTime, k KeyInfo) []byte

SITPPlainAction is DSI 02h content without wrapping (table F.30).

func SITPPlainKey

func SITPPlainKey(key []byte, at TargetTime, k KeyInfo) []byte

SITPPlainKey is DSI 01h content without wrapping (DSH FFh FFh, only inside a TLS channel, OMS annex F table F.22): key, target time, key ID and version.

func SITPPlainKeyPair

func SITPPlainKeyPair(at TargetTime, activate, deactivate KeyInfo, counterReset bool) []byte

SITPPlainKeyPair is DSI 03h content without wrapping (table F.25).

func SITPResponseBCF

func SITPResponseBCF(cmd byte) byte

SITPResponseBCF is the BCF that answers a command.

func SITPStatusText

func SITPStatusText(s byte) string

SITPStatusText names a status response byte (table A.14).

func SITPUnwrapAllKeys

func SITPUnwrapAllKeys(kek, content []byte) (map[byte][]byte, error)

SITPUnwrapAllKeys reads DSI 20h content: for each Key ID the versions the meter holds.

func SITPWrapAction

func SITPWrapAction(kek []byte, at TargetTime, k KeyInfo) ([]byte, error)

SITPWrapAction builds DSI 02h content for activate, deactivate, destroy and generate.

func SITPWrapKey

func SITPWrapKey(kek, key []byte, at TargetTime, k KeyInfo) ([]byte, error)

SITPWrapKey builds DSI 01h content: the new key wrapped with the wrapper key (KWP), for BCF 00h.

func SITPWrapKeyPair

func SITPWrapKeyPair(kek []byte, at TargetTime, activate, deactivate KeyInfo, counterReset bool) ([]byte, error)

SITPWrapKeyPair builds DSI 03h content: activate one key and deactivate another at the same time, optionally resetting the counter.

func SealAFL

func SealAFL(tpdu []byte, meter Header, key []byte, kdf int, counter uint32, at byte, ki *uint16, toMeter bool) ([]byte, error)

SealAFL puts an AFL (CI 90h) in front of a TPDU, unfragmented, with the message counter and a MAC: at 3–7 AES-CMAC of 2–16 bytes, 8 AES-GMAC. ki, when not nil, is the key information field. meter is the address of the GMAC IV.

func SealAFLFrames

func SealAFLFrames(head []byte, peer Header, c, cNext, cc, acc byte, tpdu, key []byte, counter uint32, sender Header, toMeter bool) ([][]byte, error)

SealAFLFrames authenticates a TPDU with an 8-byte AFL CMAC (KDF-A, key and counter) and frames it: one datagram behind ELL 8Ch when it fits, else fragments behind ELL 8Eh naming peer with message authentication (EN 13757-7:2025 6.3; OMS Volume 2 6.2.4: MCL, MCR and ML in the first fragment, the MAC over MCL, MCR, ML and the whole TPDU in the last).

func SealMode13

func SealMode13(ci byte, long bool, meter Header, acc, st byte, hi uint16, protocol byte, records []byte) []byte

SealMode13 builds a mode 13 TPL from its CI field: header (long when long is set, naming meter), configuration field (CC in hi's bits 15–14), CFE and the records.

func SealSITPApp

func SealSITPApp(key []byte, dsi byte, meter Header, dir byte, a SITPApp) ([]byte, error)

SealSITPApp builds the content of a secured application data structure (DSI 31h–37h) with the key the block's DSH names.

func SealTPL

func SealTPL(ci byte, long bool, meter Header, acc, st byte, hi uint16, s Seal, apl []byte) ([]byte, error)

SealTPL builds a TPL from its CI field: header, configuration field and secured application data. meter is the address used for the IV (the long header's address when long is true, else the link layer's), acc and st the access number and status; hi holds the configuration field bits a mode leaves to the caller (B, A, S, CC...).

func ServerConfig

func ServerConfig(cert tls.Certificate, meterCAs *x509.CertPool) *tls.Config

ServerConfig is the gateway's TLS configuration for mode 13: TLS 1.2 only, the suites and curves above, ECDSA signatures with SHA-256 or SHA-384, client certificates required and checked against the meter CAs, no renegotiation, resumption by session ID (in memory) or ticket.

func SessionKeys

func SessionKeys(master []byte, kdf int, c uint32, m Header, toMeter bool) (enc, mac []byte, err error)

SessionKeys are the encryption and MAC keys of a message: with KDF-A (kdf 1) derived from the persistent key, the counter c and the meter, for a message to the meter when toMeter; with kdf 0 the persistent key.

func SplitTLSFrames

func SplitTLSFrames(head []byte, peer Header, c, cNext, cc, acc byte, tpdu []byte) [][]byte

SplitTLSFrames builds CRC-less frames for a TPDU (a TPL, or an AFL with its TPL): one datagram behind ELL 8Ch when it fits, else AFL fragments behind ELL 8Eh naming peer (annex F F.D.4: FID from 1, MF, ML in the first fragment, no MAC). head is the 10-byte link header after L (C, M, A); c is the C field of the first frame and cNext of the others.

func SyncInterval

func SyncInterval(acc byte, tNom time.Duration) time.Duration

SyncInterval is the interval from a synchronous message with access number acc to the next one (12.6.2): tNom scaled by 1 + (|acc − 128| − 64) / 2048, i.e. within ±1/32 of tNom.

Types

type AFL

type AFL struct {
	FCL     uint16
	MCL     byte
	KI      uint16
	Counter uint32
	MAC     []byte
	ML      uint16
	// Fragments is the number of datagrams a reassembled message came in
	// (0 for an unfragmented one).
	Fragments int
	// contains filtered or unexported fields
}

AFL is the authentication and fragmentation layer.

func (*AFL) HasCounter

func (a *AFL) HasCounter() bool

HasCounter reports whether the AFL carried a message counter.

type AppRequest

type AppRequest interface {
	// AnsweredBy reports whether a telegram carries the answer.
	AnsweredBy(tg *Telegram) bool
}

AppRequest is a downlink the meter answers on the application layer after its link-layer ACK (a security information transfer, say).

type CompactInfo

type CompactInfo struct {
	Kind      string // "full", "compact" or "format"
	Signature uint16
	Known     bool // a compact frame's format was known
	// Warning is set when a frame was let through by a lenient option
	// (FormatCache.IgnoreFullFrameCRC).
	Warning string
}

CompactInfo describes how a telegram's records were obtained.

type CounterState

type CounterState struct {
	Meter   map[string]uint32 `json:"meter"`   // C”M by "MAN-ID/keyID"
	Partner map[string]uint32 `json:"partner"` // CCP by "MAN-ID/keyID"
}

CounterState is the counters to keep across restarts (C”M must be stored permanently, clause 9.2.5).

type Decoder

type Decoder struct {

	// Now returns the time (tests); nil means time.Now.
	Now func() time.Time
	// KeyByID returns the persistent key of a meter for a Key ID and key
	// version (-1: none given), or nil to use the KeyLookup's key.
	KeyByID func(meter Header, keyID, version int) []byte
	// MAC2Key returns security mode 8's Kmac_2 of a meter, or nil (MAC_2
	// is then reported as not verified).
	MAC2Key func(meter Header) []byte
	// DESKey returns the 8-byte DES key of the deprecated modes 2 and 3.
	DESKey func(meter Header) []byte
	// DESCheck2F2F also accepts a mode 2 telegram whose decrypted data
	// begins with two idle fillers (2F2Fh) when the meter's ID is not in
	// it, as wmbusmeters does. Off by default: the ID is the check
	// EN 13757-7 gives, and two fixed bytes are a weaker one. A telegram
	// accepted this way is marked "des-id" in Security.Unverified.
	DESCheck2F2F bool
	// TLS processes security mode 13 records for the meter's TLS channel
	// (mode13.go); nil refuses mode 13.
	TLS TLSHandler
	// TLSEstablished reports whether a meter has an established TLS
	// channel (alerts inside it need no AFL CMAC).
	TLSEstablished func(meter Header) bool
	// MaxMessage caps a reassembled message (0: 64 kbytes, the AFL.ML
	// range of EN 13757-7; OMSMaxMessage under the OMS profile).
	MaxMessage int
	// MeterSide decodes messages sent to a meter (KDF-A derives Lenc and
	// Lmac): for meter simulators and checks of our own downlinks.
	MeterSide bool
	// contains filtered or unexported fields
}

Decoder decodes telegrams, reassembles fragmented messages and keeps the message counters (security.go). The zero value is ready; it is safe for concurrent use.

func (*Decoder) Counters

func (d *Decoder) Counters() (CounterState, bool)

Counters returns the counters and whether they changed since the last call.

func (*Decoder) Decode

func (d *Decoder) Decode(frame []byte, format FrameFormat, keys KeyLookup) (*Telegram, error)

Decode is the package Decode with fragment reassembly (d may be nil).

func (*Decoder) MarkCountersChanged

func (d *Decoder) MarkCountersChanged()

MarkCountersChanged marks the counters changed, so the next Counters call reports them to be saved again (after a failed save, say).

func (*Decoder) NextPartnerCounter

func (d *Decoder) NextPartnerCounter(m Header, keyID int, step uint32) uint32

NextPartnerCounter returns the counter CCP for our next secured message to a meter (clause 9.2.3): the last one plus step (1–100), after it was raised to the meter's verified counter.

func (*Decoder) NextSITPCounter

func (d *Decoder) NextSITPCounter(m Header, keyID int) uint32

NextSITPCounter returns the next key counter of an SITP end-to-end key (annex A.9.1: kept by the command initiator, starting at 0, each command above the last).

func (*Decoder) ResetCounters

func (d *Decoder) ResetCounters(m Header, keyID int)

ResetCounters sets a meter's counters for a Key ID back to 0 (after a master key update with message counter reset, OMS annex F table F.25).

func (*Decoder) SetCounters

func (d *Decoder) SetCounters(s CounterState)

SetCounters restores saved counters (the higher of saved and current).

type Downlink struct {
	C      byte   // CCnfIR, CSndUD, CSndUD2, CSndNKE, CReqUD1 or CReqUD2
	CI     byte   // TPL CI
	APL    []byte // application data (before encryption)
	Status byte   // TPL status sent by the gateway
}

Downlink is one frame to send to a meter.

type DownlinkSeal

type DownlinkSeal struct {
	Mode    int
	Key     []byte
	KeyID   int
	Counter uint32 // CCP, for mode 7
	// KeyInfo sends AFL.KI with mode 7. OMS Volume 2 6.2.2 makes a meter
	// repeat KI in its answers once we send it, so by default (false) it
	// is left out when the key is Key ID 0 without a key version (as in
	// the annex N.12.2 example) and sent otherwise.
	KeyInfo bool
}

DownlinkSeal says how a downlink is secured: mode 0, mode 5 with the meter's key, or modes 7 to 10 with KDF-A (Lenc, Lmac from the persistent key and our counter CCP, EN 13757-7:2025 clause 9.6): mode 7 behind an AFL with the counter and an 8-byte AES-CMAC (clause 9.3.2), mode 8 with MAC_1, mode 9 with its 12-byte GCM tag, mode 10 with an 8-byte CCM tag and the counter in the TPL.

type ELL

type ELL struct {
	CI, CC, ACC byte
	SN          uint32
	HasSN       bool
	// Variable ELL (CI 86h) only: the ECL field and what it selects.
	ECL    byte
	RTD    uint16 // run time delay, see RunTimeDelay
	RTDRes byte   // ECL RTDP: 1 = 1/256 s units, 2 = 2 s units
	HasRTD bool
	RXL    byte // reception level of the partner, see RXLValue
	HasRXL bool
	// M2 and A2: the destination (CI 8Eh, 8Fh, or 86h with MAP).
	M2      uint16
	A2      [6]byte
	HasAddr bool
}

ELL is the extended link layer (EN 13757-4:2025, 13.2).

func (*ELL) ACCOr

func (e *ELL) ACCOr(def byte) byte

ACCOr is the ELL access number, or def without an ELL.

func (*ELL) RunTimeDelay

func (e *ELL) RunTimeDelay() time.Duration

RunTimeDelay is the accumulated repeater delay a variable ELL carries (13.2.13): RTD in units of 1/256 s or 2 s as ECL selects.

type FormatCache

type FormatCache struct {
	// IgnoreFullFrameCRC rebuilds a compact frame whose rebuilt records
	// fail the Full-Frame-CRC anyway (as wmbusmeters does, which does not
	// check it), and keeps the format. Off by default: the CRC is what
	// tells an outdated format from the right one. A frame let through
	// this way carries a warning (CompactInfo.Warning, Telegram.Warnings).
	IgnoreFullFrameCRC bool
	// contains filtered or unexported fields
}

FormatCache keeps the formats of meters by meter key and Format Signature, the least recently used dropped beyond its size. It is safe for concurrent use. The wireless driver persists it (SavedFormat); the wired M-Bus IPE may use one in memory.

func NewFormatCache

func NewFormatCache(max int) *FormatCache

NewFormatCache returns a cache of at most max formats (0: the default).

func (*FormatCache) Complete

func (c *FormatCache) Complete(tg *Telegram, decodeErr error) (CompactInfo, error)

Complete finishes a telegram that Decode left with ErrCompactFrame (or learns the format of a full frame when decodeErr is nil). It returns the telegram's error after that: nil when its records were rebuilt.

func (*FormatCache) Expand

func (c *FormatCache) Expand(meterKey string, ci byte, apl []byte) (full []byte, sig uint16, err error)

Expand handles the application data of an unencrypted frame (after the TPL header) by its CI field: a format frame's format is stored (full is nil); a compact frame is rebuilt into full data records and checked; a full frame's format is learnt and its data returned. sig is the Format Signature.

func (*FormatCache) ExpandEncrypted

func (c *FormatCache) ExpandEncrypted(meterKey string, ci byte, apl []byte, encLen int) (full []byte, sig uint16, err error)

ExpandEncrypted is Expand for decrypted data that starts with the two AES check bytes (2F2F); encLen is how many bytes of apl were encrypted (the rest was sent in the clear).

func (*FormatCache) Forget

func (c *FormatCache) Forget(meter string, sig uint16)

Forget drops a format (outdated: its Full-Frame-CRC failed).

func (*FormatCache) Get

func (c *FormatCache) Get(meter string, sig uint16) ([]byte, bool)

Get returns a meter's format with a signature.

func (*FormatCache) Len

func (c *FormatCache) Len() int

Len is the number of formats kept.

func (*FormatCache) Put

func (c *FormatCache) Put(meter string, format []byte) uint16

Put stores a format for a meter and returns its signature.

func (*FormatCache) Restore

func (c *FormatCache) Restore(saved []SavedFormat)

Restore adds persisted formats; entries whose bytes do not match their signature are skipped.

func (*FormatCache) Snapshot

func (c *FormatCache) Snapshot() (saved []SavedFormat, changed bool)

Snapshot returns the formats to persist and clears the changed flag; changed reports whether anything changed since the last snapshot (when nothing did, saved is nil).

type FrameFormat

type FrameFormat string

FrameFormat says how a received frame carries its CRCs.

const (
	// FormatAuto tries format A, then format B, then a frame whose CRCs a
	// receiver already removed.
	FormatAuto FrameFormat = "auto"
	// FormatA: L excludes CRCs; a 10-byte first block then 16-byte blocks,
	// each followed by its CRC (modes S, T and C).
	FormatA FrameFormat = "a"
	// FormatB: L includes CRCs; one CRC over the first 126 bytes and one
	// over the rest (mode C).
	FormatB FrameFormat = "b"
	// FormatNoCRC: a receiver checked and removed the CRCs.
	FormatNoCRC FrameFormat = "none"
)

func ModeFormats

func ModeFormats(mode string) []FrameFormat

ModeFormats lists the frame formats a radio mode can carry.

func StripCRC

func StripCRC(b []byte, f FrameFormat) ([]byte, FrameFormat, error)

StripCRC checks a frame's CRCs and returns it without them, with L set to the remaining length, and the format it was in.

type Gateway

type Gateway struct {
	Manufacturer string `json:"manufacturer"`
	ID           string `json:"id"`
	Version      byte   `json:"version,omitempty"`
	DeviceType   *byte  `json:"deviceType,omitempty"` // default 31h, communication controller
	// contains filtered or unexported fields
}

Gateway is our own link-layer address for frames we send.

func (Gateway) A

func (g Gateway) A() [6]byte

A is the gateway's A field: identification number, version and device type (after Validate).

func (Gateway) MField

func (g Gateway) MField() uint16

MField is the gateway's M field (after Validate).

func (*Gateway) Validate

func (g *Gateway) Validate() error

Validate checks the gateway's manufacturer and identification number and fills in its M and A fields (MField, A); call it before the gateway is used to send.

type HCIMessage added in v0.2.0

type HCIMessage struct {
	Endpoint, ID byte
	Payload      []byte
}

HCIMessage is one WiMOD HCI message.

func ReadHCI added in v0.2.0

func ReadHCI(r *bufio.Reader) (HCIMessage, error)

ReadHCI reads the next well-formed HCI message (a bad CRC is skipped).

type Header struct {
	L            int
	C            byte
	Manufacturer string // three letters from the M field
	MField       uint16
	ID           string // eight BCD digits of the A field's identification number
	Version      byte
	DeviceType   byte
	A            [6]byte // raw A field (ID, version, device type)
}

Header is the data link layer header of a CRC-less frame.

func ParseHeader

func ParseHeader(t []byte) (Header, error)

ParseHeader reads the link-layer header of a CRC-less frame.

func (Header) Key

func (h Header) Key() string

Key identifies a meter: manufacturer and ID, e.g. "KAM-12345678".

func (Header) Medium

func (h Header) Medium() string

Medium is the device type's name.

type KeyInfo

type KeyInfo struct{ ID, Version byte }

KeyInfo names a key: its Key ID and version (FFh: not used).

func SITPActiveKeys

func SITPActiveKeys(content []byte) ([]KeyInfo, error)

SITPActiveKeys reads DSI 21h content.

type KeyLookup

type KeyLookup func(meter Header) []byte

KeyLookup returns the AES-128 key of a meter ("MAN-ID" and the 8-digit ID are both offered), or nil.

type Pending

type Pending struct {
	ID     string   // the caller's name for it (a command's ID)
	Action string   // what it does, for the caller's records
	Frame  Downlink // the frame, before its link and transport headers
	Queued time.Time
	Sent   time.Time // zero until sent
	// Await is set while the meter owes an answer; Window once the frame
	// went out in a meter's receive window, with ELLACC our ELL access
	// number in it. Acked is set when the link-layer ACK of an App request
	// arrived.
	Await  bool
	Window bool
	ELLACC byte
	Acked  bool
	// Expect is the answer the meter owes (ExpectFor(Frame.C)).
	Expect string
	// App, when set, is answered on the application layer (Scheduler.App).
	App AppRequest
	// Meter is the meter's header from the telegram whose window the frame
	// went in.
	Meter Header
}

Pending is one frame queued for a meter.

type Reader

type Reader struct {
	Framer   string
	WithL    bool
	RSSIByte bool
	Format   FrameFormat
	// contains filtered or unexported fields
}

Reader cuts a receiver's byte stream into telegrams with one of the framings (Framer*): WithL says the receiver's telegrams start with their L field (iM871A and Amber; otherwise it is computed), RSSIByte that an Amber stick appends an RSSI byte, Format how many bytes follow L in the raw framing. The line framings (hex, CUL, rtl-wmbus) skip lines without a telegram.

func NewReader

func NewReader(r io.Reader, framer string) *Reader

NewReader reads telegrams from r with a framing.

func (*Reader) Read

func (rd *Reader) Read() (Received, error)

Read returns the next telegram, or the stream's error.

type Received

type Received struct {
	Frame    []byte // starts with the L field
	RSSI     *int   // receiver-reported RSSI (raw receiver units, or dBm when RSSIdBm)
	RSSIdBm  bool
	LinkMode string // "T1", "C1", "N2a" … (NormalizeLinkMode) when the source says
}

Received is one telegram as a receiver delivered it.

func ParseCULLine added in v0.2.0

func ParseCULLine(line string) (Received, error)

ParseCULLine reads a culfw telegram line: "b" and the frame in hex (frame format A, CRCs included) or "bY" and a format B frame, then the LQI and RSSI bytes (X21). RSSI is in dBm (the CC1101's raw value / 2 - 74). Other lines (command answers) give errNoHex.

func ParseHexLine

func ParseHexLine(line string) (Received, error)

ParseHexLine finds the telegram in a text line: the longest run of hex digits (an optional 0x prefix is dropped). A leading field naming a radio mode of EN 13757-4 ("T1;", "C1 ", "S1-m,", "R2:", "N2a;", "F2;" ...) gives the link mode.

func ParseRTLWMBUSLine added in v0.2.0

func ParseRTLWMBUSLine(line string) (Received, error)

ParseRTLWMBUSLine reads an rtl-wmbus line: link mode, CRC ok (1/0), 3-out-of-6 ok (1/0), time, packet RSSI, current RSSI, link-layer ID and the telegram as 0x and hex digits. Lines whose checks failed give an error.

func ReadAmber

func ReadAmber(r *bufio.Reader, withL, rssiByte bool) (Received, error)

ReadAmber reads one received radio telegram in Amber command mode, skipping other commands; rssiByte says an RSSI byte follows the telegram.

func ReadIM871A

func ReadIM871A(r *bufio.Reader, withL bool) (Received, error)

ReadIM871A reads one radio-link message indication, skipping other messages and garbage.

func ReadRaw

func ReadRaw(r *bufio.Reader, format FrameFormat) (Received, error)

ReadRaw reads an L-framed telegram; format says how many bytes follow L.

type SITPApp

type SITPApp struct {
	KeyCounter uint32
	At         TargetTime
	PID        byte // 01h M-Bus, 02h application error, ... (table A.16)
	APDU       []byte
}

SITPApp is the content of structures 31h–37h: end-to-end protected application data.

func OpenSITPApp

func OpenSITPApp(key []byte, dsi byte, meter Header, dir byte, content []byte) (SITPApp, error)

OpenSITPApp checks and opens a secured application data structure.

type SITPBlock

type SITPBlock struct {
	ID        byte
	BCF       byte
	Recipient byte
	DSI       byte
	DSH1      byte
	DSH2      byte
	Content   []byte
}

SITPBlock is one command or response block.

func ParseSITP

func ParseSITP(apl []byte) ([]SITPBlock, error)

ParseSITP splits an SITP APL into blocks. Idle fillers (2Fh) after the last block are skipped.

type SITPKey

type SITPKey struct {
	Key []byte
	At  TargetTime
	KeyInfo
}

SITPKey is the content of a DSI 01h structure after unwrapping.

func SITPUnwrapKey

func SITPUnwrapKey(kek, content []byte) (SITPKey, error)

SITPUnwrapKey reads DSI 01h content (the answer to "get security information" for a generated key).

type SITPKeyCounter

type SITPKeyCounter struct {
	KeyInfo
	Counter uint32
}

SITPKeyCounter is one entry of DSI 23h.

func SITPActiveCounters

func SITPActiveCounters(content []byte) ([]SITPKeyCounter, error)

SITPActiveCounters reads DSI 23h content.

type SITPResponse

type SITPResponse struct {
	Block  SITPBlock
	Status *byte // DSI 22h
	// Filled when the DSI carries it and the key to open it was known.
	Key      *SITPKey
	AllKeys  map[byte][]byte
	Active   []KeyInfo
	Counters []SITPKeyCounter
	App      *SITPApp
	// Certificate is a DSI 10h answer (OMS annex F F.4.4.2).
	Certificate *x509.Certificate
}

SITPResponse is a decoded response block.

func ReadSITPResponses

func ReadSITPResponses(apl []byte, meter Header, wrapper func(id, version byte) []byte) ([]SITPResponse, error)

ReadSITPResponses decodes the blocks of a response APL. wrapper returns the wrapper or end-to-end key a block's DSH1/DSH2 name (nil: unknown). A response whose BCF is not the command's with bit 7 set, or whose DSI is not allowed for it (table A.3), is refused.

type SavedFormat

type SavedFormat struct {
	Meter     string `json:"meter"`
	Signature uint16 `json:"signature"`
	Format    string `json:"format"` // hex
}

SavedFormat is a persisted format.

type Scheduler

type Scheduler struct {
	Gateway Gateway
	// Framer is FramerIM871A or FramerAmber; WithL sends the L field to the
	// receiver.
	Framer string
	WithL  bool
	// Timeout is how long a frame waits for a window, and a sent frame for
	// its answer.
	Timeout time.Duration
	// Seal chooses the security of a frame about to be sent in tg's
	// window; an error fails the frame with the error's text. Nil sends
	// without security.
	Seal func(dev string, tg *Telegram, p *Pending) (DownlinkSeal, error)
	// State is told each change of a frame's state (State*); detail says
	// more, or is empty. Nil records nothing.
	State func(dev string, p *Pending, state, detail string)
	// App reads the answer to an App request. keep says the request goes
	// on (it sent a following step), event is run with the other events.
	// Nil drops the request without an event.
	App func(dev string, p *Pending, tg *Telegram) (keep bool, event func())
	// LinkMode ("S2", "T2", "C2"), when set, times each frame into the
	// meter's response window (ResponseDelay): After waits until the
	// window's middle, counted from its call, less StickLatency (the
	// time the receiver took to deliver the telegram and will take to send
	// the frame). Empty sends at once, for sticks that time the answer
	// themselves.
	LinkMode     string
	StickLatency time.Duration
	// Wait sleeps (tests); nil is time.Sleep.
	Wait func(time.Duration)
	// contains filtered or unexported fields
}

Scheduler is the downlink queue of a gateway. Its zero value is not usable: set Gateway (validated), Framer and Timeout.

func (*Scheduler) After

func (s *Scheduler) After(dev string, tg *Telegram, direct bool) []func()

After runs after a meter's telegram: it settles the waiting frame a link-layer answer belongs to, passes application-layer answers to App, drops what timed out, and sends the meter's oldest queued frame when the telegram opens a receive window. direct is false for a telegram relayed by a repeater (hop bit H). It returns the state events in order, for the caller to run once it has recorded the queue.

func (*Scheduler) Enqueue

func (s *Scheduler) Enqueue(dev string, p *Pending)

Enqueue adds a frame to a meter's queue (dev names the meter).

func (*Scheduler) Queued

func (s *Scheduler) Queued() map[string][]*Pending

Queued lists every meter's queue (copies of the lists, the same entries).

func (*Scheduler) SetWriter

func (s *Scheduler) SetWriter(w io.Writer)

SetWriter sets the receiver frames are written to (nil while it is not connected).

func (*Scheduler) Transmit

func (s *Scheduler) Transmit(frame []byte) error

Transmit writes one CRC-less frame to the receiver with its framing.

type Seal

type Seal struct {
	Mode int
	// Key is the mode 5 key or the persistent (master) key of modes 7–10.
	Key []byte
	// MAC2Key is mode 8's Kmac_2; with Timestamp set MAC_2 is added.
	MAC2Key    []byte
	Timestamp  *uint32
	KDF        int // 0 persistent, 1 KDF-A
	KeyID      int
	KeyVersion int // -1 for none
	Counter    uint32
	// CounterInTPL sets the Z bit (modes 7 and 10); mode 8 and 9 always
	// carry it. Without it the counter goes in the AFL (see SealAFL).
	CounterInTPL bool
	CounterSize  int  // mode 8: 2, 3 or 4 (default 4)
	Padding      bool // mode 7 TPL padding
	TagLen       int  // mode 9: 0 or 12 (default 12); mode 10: 4/8/12/16 (default 8)
	// ToMeter derives Lenc/Lmac (the partner's direction) with KDF-A.
	ToMeter bool
	// Unencrypted follows the encrypted part.
	Unencrypted []byte
}

Seal says how to secure a TPL.

type Security

type Security struct {
	KeyID      int // 0–15 (Table 25)
	KeyVersion int // -1 when the message carries none
	KDF        int // 0 persistent key, 1 KDF-A
	// Counter is the message counter the mechanism used: the TPL's when
	// it has one, else the AFL's.
	Counter      uint32
	HasCounter   bool
	CounterFrom  string // "tpl" or "afl"
	Content      int    // CC subfield (Tables 21, 22)
	ContentIndex int    // IIII subfield (Table 23)
	// EncryptedLen and UnencryptedLen split the application data.
	EncryptedLen, UnencryptedLen int
	// TagLen is mode 10's CCM tag length (OMS profile D needs 8).
	TagLen int
	// Timestamp is mode 8's transmission time stamp: seconds since
	// 2013-01-01 00:00 (UTC is not stated; see findings).
	Timestamp *uint32
	// Verified lists the checks that passed: "decrypt-2f2f", "afl-cmac",
	// "afl-gmac", "mac1", "mac2", "gcm", "ccm".
	Verified []string
	// Unverified lists checks the telegram offers that could not be made
	// (e.g. "mac2" without a MAC_2 key).
	Unverified []string
	// contains filtered or unexported fields
}

Security is what a telegram's TPL says about its protection.

type TLSEndpoint

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

TLSEndpoint is one side of a mode 13 TLS channel: the server (us) or, in simulators and tests, the meter's client.

func NewTLSClient

func NewTLSClient(cfg *tls.Config) *TLSEndpoint

NewTLSClient starts a meter side (simulators, tests); its ClientHello is ready with Output once it settled.

func NewTLSServer

func NewTLSServer(cfg *tls.Config) *TLSEndpoint

NewTLSServer starts the gateway side of a channel.

func (*TLSEndpoint) Close

func (e *TLSEndpoint) Close() []byte

Close ends the channel (close_notify goes to Output).

func (*TLSEndpoint) Established

func (e *TLSEndpoint) Established() bool

Established reports whether the handshake completed.

func (*TLSEndpoint) Expired

func (e *TLSEndpoint) Expired(now time.Time) bool

Expired reports whether the session reached a limit of F.3.1.

func (*TLSEndpoint) Input

func (e *TLSEndpoint) Input(records []byte) (out, plain []byte, err error)

Input gives the endpoint received records and returns the records it answers with and the application data they carried.

func (*TLSEndpoint) Output

func (e *TLSEndpoint) Output() []byte

Output takes what the endpoint sent on its own (the client's hello).

func (*TLSEndpoint) Send

func (e *TLSEndpoint) Send(plain []byte) ([]byte, error)

Send encrypts application data into records.

func (*TLSEndpoint) State

func (e *TLSEndpoint) State() tls.ConnectionState

State is the connection state (after the handshake).

type TLSHandler

type TLSHandler func(tg *Telegram, info *TLSInfo) ([]byte, error)

TLSHandler processes a mode 13 telegram's records for the meter's TLS channel and returns the application data they carried (nil for handshake and alert records).

type TLSInfo

type TLSInfo struct {
	Protocol byte   // TLSCHAN or TLSPROT
	Types    []byte // content type of each record
	Records  []byte // the TLS records as received
	HSTypes  []byte // handshake message types seen in plaintext records
	Session  string // state reported by the channel ("handshake", "established")
}

TLSInfo is what a mode 13 telegram carried.

type TargetTime

type TargetTime [5]byte

TargetTime is a 5-byte type M date/time (EN 13757-3:2025 annex A), least significant byte first. All zero means "now".

func TargetTimeOf

func TargetTimeOf(v uint64) TargetTime

TargetTimeOf is a 5-byte target time from its value as annex F writes it (3000000000h now, 3080000000h invalid), least significant byte first.

type Telegram

type Telegram struct {
	Header
	Format FrameFormat
	// Meter is the meter the data is from: the TPL long header's address
	// when present (a repeater or converter sent the frame), else the link
	// layer's.
	Meter Header
	CI    byte
	// TPL fields, when the frame has a short or long header.
	HeaderKind string // "none", "short" or "long"
	Access     byte
	Status     byte
	Config     uint16
	ConfigExt  byte // mode 7's configuration field extension
	Mode       int  // security mode from the configuration field
	Encrypted  bool
	// Sec is the TPL security of modes 5–10 (security.go).
	Sec *Security
	// SITP holds the blocks of a security information transfer (CI C3h to
	// C6h) instead of Records.
	SITP []SITPBlock
	// TLS holds a security mode 13 telegram's records (mode13.go).
	TLS *TLSInfo
	ELL *ELL
	AFL *AFL
	// APL is the application layer after decryption, idle fillers kept.
	APL     []byte
	Records []records.Record
	// Warnings name what a lenient option let through (Warn*).
	Warnings []string
}

Telegram is a decoded wM-Bus telegram.

func Decode

func Decode(frame []byte, format FrameFormat, keys KeyLookup) (*Telegram, error)

Decode checks and removes CRCs, then decodes headers, decrypts with the meter's key and decodes the data records. It keeps no state, so a fragmented message (AFL with more fragments) is refused; a Decoder reassembles them.

Example

A meter's SND-NR with a short TPL header, encrypted in security mode 5, decoded with the meter's key.

package main

import (
	"encoding/binary"
	"fmt"

	"github.com/cB-Sigma/mbus/records"
	"github.com/cB-Sigma/mbus/wireless"
)

func main() {
	key := []byte{0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15}
	mf, _ := records.ManufacturerField("ABC")
	meter := wireless.Header{MField: mf, A: [6]byte{0x78, 0x56, 0x34, 0x12, 0x01, 0x07}}
	tpl, err := wireless.SealTPL(wireless.CIShortHeader, false, meter, 0x2A, 0, 0,
		wireless.Seal{Mode: 5, Key: key, KeyVersion: -1}, []byte{0x04, 0x13, 0x39, 0x30, 0x00, 0x00})
	if err != nil {
		panic(err)
	}
	frame := binary.LittleEndian.AppendUint16([]byte{0, wireless.CSndNR}, mf)
	frame = append(append(frame, meter.A[:]...), tpl...)
	frame[0] = byte(len(frame) - 1)

	tg, err := wireless.Decode(frame, wireless.FormatNoCRC, func(wireless.Header) []byte { return key })
	if err != nil {
		panic(err)
	}
	fmt.Println(tg.Meter.Key(), tg.Meter.Medium(), "mode", tg.Mode)
	for _, r := range tg.Records {
		fmt.Println(r.Name(), r.Value, r.Unit)
	}
	// With CRCs, as a radio receives it (frame format A).
	fmt.Println(len(wireless.AddCRCA(frame)) - len(frame))
}
Output:
ABC-12345678 water mode 5
volume 12.345 m3
6

func (*Telegram) Mode5IV

func (tg *Telegram) Mode5IV() []byte

Mode5IV is the initialisation vector of security mode 5: the meter's M and A fields, then the access number eight times.

Jump to

Keyboard shortcuts

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