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 ¶
- Constants
- Variables
- func AddCRCA(t []byte) []byte
- func AddCRCB(t []byte) []byte
- func Answers(e string, c byte) bool
- func BCDID(b []byte) string
- func BuildFormat(records []byte) ([]byte, error)
- func CFieldName(c byte) string
- func CMAC(key, msg []byte) ([]byte, error)
- func CRC(b []byte) uint16
- func CRCX25(b []byte) uint16
- func CheckLMNCertificate(der []byte) error
- func Decode3of6(chips []byte) ([]byte, error)
- func DecodeFEC(b []byte, format FrameFormat) ([]byte, int, error)
- func DeriveKey(master []byte, dc byte, counter uint32, id [4]byte) ([]byte, error)
- func DuplicateKey(t []byte) (string, error)
- func Encode3of6(b []byte) []byte
- func EncodeAmber(frame []byte, withL bool) []byte
- func EncodeDownlink(gw Gateway, meter Header, dl Downlink, ellACC, tplACC byte, key []byte) ([]byte, error)
- func EncodeDownlinkSealed(gw Gateway, meter Header, dl Downlink, ellACC, tplACC byte, sec DownlinkSeal) ([]byte, error)
- func EncodeFEC(frame []byte) ([]byte, error)
- func EncodeIM871A(frame []byte, withL bool) []byte
- func EncodeSITP(blocks ...SITPBlock) []byte
- func ExpectFor(c byte) string
- func FECHeader(id byte) uint16
- func FECID(h uint16) byte
- func FormatSignature(format []byte) uint16
- func FrameKind(ci byte) (kind, header string)
- func FrameLenA(l int) int
- func FullFrameCRC(records []byte) uint16
- func HardAddress(m uint16) bool
- func IsDLMS(ci byte) bool
- func IsHexText(b []byte) bool
- func KWPUnwrap(kek, wrapped []byte) ([]byte, error)
- func KWPWrap(kek, plain []byte) ([]byte, error)
- func LinkHead(c byte, m uint16, a [6]byte) []byte
- func NormalizeLinkMode(s string) (string, bool)
- func OMSProfile(tg *Telegram) string
- func RSSIToRL(dBm float64) byte
- func RXLValue(rxl byte) (kind string, value float64, ok bool)
- func RawAPL(ci byte) bool
- func Rebuild(format, data []byte, ffc uint16, encEnd int) ([]byte, error)
- func Relayed(t []byte) bool
- func SITPPlainAction(at TargetTime, k KeyInfo) []byte
- func SITPPlainKey(key []byte, at TargetTime, k KeyInfo) []byte
- func SITPPlainKeyPair(at TargetTime, activate, deactivate KeyInfo, counterReset bool) []byte
- func SITPResponseBCF(cmd byte) byte
- func SITPStatusText(s byte) string
- func SITPUnwrapAllKeys(kek, content []byte) (map[byte][]byte, error)
- func SITPWrapAction(kek []byte, at TargetTime, k KeyInfo) ([]byte, error)
- func SITPWrapKey(kek, key []byte, at TargetTime, k KeyInfo) ([]byte, error)
- func SITPWrapKeyPair(kek []byte, at TargetTime, activate, deactivate KeyInfo, counterReset bool) ([]byte, error)
- func SealAFL(tpdu []byte, meter Header, key []byte, kdf int, counter uint32, at byte, ...) ([]byte, error)
- func SealAFLFrames(head []byte, peer Header, c, cNext, cc, acc byte, tpdu, key []byte, ...) ([][]byte, error)
- func SealMode13(ci byte, long bool, meter Header, acc, st byte, hi uint16, protocol byte, ...) []byte
- func SealSITPApp(key []byte, dsi byte, meter Header, dir byte, a SITPApp) ([]byte, error)
- func SealTPL(ci byte, long bool, meter Header, acc, st byte, hi uint16, s Seal, apl []byte) ([]byte, error)
- func ServerConfig(cert tls.Certificate, meterCAs *x509.CertPool) *tls.Config
- func SessionKeys(master []byte, kdf int, c uint32, m Header, toMeter bool) (enc, mac []byte, err error)
- func SplitTLSFrames(head []byte, peer Header, c, cNext, cc, acc byte, tpdu []byte) [][]byte
- func SyncInterval(acc byte, tNom time.Duration) time.Duration
- type AFL
- type AppRequest
- type CompactInfo
- type CounterState
- type Decoder
- func (d *Decoder) Counters() (CounterState, bool)
- func (d *Decoder) Decode(frame []byte, format FrameFormat, keys KeyLookup) (*Telegram, error)
- func (d *Decoder) MarkCountersChanged()
- func (d *Decoder) NextPartnerCounter(m Header, keyID int, step uint32) uint32
- func (d *Decoder) NextSITPCounter(m Header, keyID int) uint32
- func (d *Decoder) ResetCounters(m Header, keyID int)
- func (d *Decoder) SetCounters(s CounterState)
- type Downlink
- type DownlinkSeal
- type ELL
- type FormatCache
- func (c *FormatCache) Complete(tg *Telegram, decodeErr error) (CompactInfo, error)
- func (c *FormatCache) Expand(meterKey string, ci byte, apl []byte) (full []byte, sig uint16, err error)
- func (c *FormatCache) ExpandEncrypted(meterKey string, ci byte, apl []byte, encLen int) (full []byte, sig uint16, err error)
- func (c *FormatCache) Forget(meter string, sig uint16)
- func (c *FormatCache) Get(meter string, sig uint16) ([]byte, bool)
- func (c *FormatCache) Len() int
- func (c *FormatCache) Put(meter string, format []byte) uint16
- func (c *FormatCache) Restore(saved []SavedFormat)
- func (c *FormatCache) Snapshot() (saved []SavedFormat, changed bool)
- type FrameFormat
- type Gateway
- type Header
- type KeyInfo
- type KeyLookup
- type Pending
- type Reader
- type Received
- type SITPApp
- type SITPBlock
- type SITPKey
- type SITPKeyCounter
- type SITPResponse
- type SavedFormat
- type Scheduler
- type Seal
- type Security
- type TLSEndpoint
- func (e *TLSEndpoint) Close() []byte
- func (e *TLSEndpoint) Established() bool
- func (e *TLSEndpoint) Expired(now time.Time) bool
- func (e *TLSEndpoint) Input(records []byte) (out, plain []byte, err error)
- func (e *TLSEndpoint) Output() []byte
- func (e *TLSEndpoint) Send(plain []byte) ([]byte, error)
- func (e *TLSEndpoint) State() tls.ConnectionState
- type TLSHandler
- type TLSInfo
- type TargetTime
- type Telegram
Examples ¶
Constants ¶
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.
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.
const ( KindFull = "full" KindCompact = "compact" KindFormat = "format" )
Frame kinds by CI field.
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.
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).
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).
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).
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).
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).
const ( TLSCHAN byte = 0x00 TLSPROT byte = 0x01 )
Mode 13 protocol types (CFE, table F.5).
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).
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.
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).
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).
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.
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.
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.
const ( StateQueued = "queued" StateSent = "sent" StateAcknowledged = "acknowledged" StateAnswered = "answered" StateRejected = "rejected" StateUnacknowledged = "unacknowledged" StateExpired = "expired" StateFailed = "failed" )
Downlink states reported through Scheduler.State.
const ( CISITPCmdLong byte = 0xC3 CISITPRespShort byte = 0xC4 CISITPRespLong byte = 0xC5 CISITPCmdShort byte = 0xC6 )
SITP CI fields (table A.1).
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).
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).
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).
const ( SITPDown byte = 0x01 // partner to meter SITPUp byte = 0x02 // meter to partner )
SITP directions of the IV/nonce of structures 34h–37h.
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.
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.
const DefaultFormatCacheSize = 1024
DefaultFormatCacheSize bounds the formats kept (and persisted).
const (
FECIDReedSolomon = 0x01
)
FECIDReedSolomon is FEC ID 01h (header value 0421h).
const FragmentTimeout = 2 * time.Minute
FragmentTimeout is how long a partial message is kept.
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).
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.
Variables ¶
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.
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.
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).
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") )
Error kinds a caller may count.
var ChannelRequestRecord = []byte{tlsChannelRequest, 0, 0, 0, 0}
ChannelRequestRecord is the TLSCHAN record (table F.10).
var ErrCRC = errors.New("wM-Bus frame CRC mismatch")
ErrCRC is returned for a frame whose CRCs do not match.
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.
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).
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).
var Mode13Curves = []tls.CurveID{tls.BrainpoolP256r1, tls.CurveP256, tls.BrainpoolP384r1, tls.CurveP384, tls.BrainpoolP512r1}
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).
var Mode13Suites = []uint16{ tls.TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256, tls.TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384, tls.TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256, tls.TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384, }
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 Answers ¶
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 ¶
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 ¶
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 ¶
CFieldName names a C-field (its symbolic name in 12.5.4), or "0xNN".
func CRC ¶
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 ¶
CRCX25 is the CRC-16 of the WiMOD HCI (polynomial 0x1021 reflected, initial 0xFFFF, complemented).
func CheckLMNCertificate ¶
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 Decode3of6 ¶
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 ¶
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 ¶
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 ¶
Encode3of6 is Decode3of6's inverse (for tests and simulators).
func EncodeAmber ¶
EncodeAmber frames a CRC-less telegram (sent without its L field unless withL) as an Amber command-mode data request.
func EncodeDownlink ¶
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 ¶
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 ¶
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 ¶
EncodeSITP builds the APL of an SITP command.
func FormatSignature ¶
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 ¶
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 FullFrameCRC ¶
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 ¶
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 KWPWrap ¶
KWPWrap wraps plain with kek: AES key wrap with padding (RFC 5649, alternative initial value A65959A6), as SITP wraps keys.
func NormalizeLinkMode ¶
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 ¶
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 RXLValue ¶
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 ¶
RawAPL reports a CI whose application data is kept as bytes (Telegram.APL) instead of being read as data records.
func Rebuild ¶
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 ¶
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 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 ¶
SITPResponseBCF is the BCF that answers a command.
func SITPStatusText ¶
SITPStatusText names a status response byte (table A.14).
func SITPUnwrapAllKeys ¶
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 ¶
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 ¶
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 ¶
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.
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 ¶
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
}
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
// 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) 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 ¶
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 ¶
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 ¶
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 ¶
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) RunTimeDelay ¶
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 {
// 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) 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 ¶
A is the gateway's A field: identification number, version and device type (after Validate).
type Header ¶
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 ¶
ParseHeader reads the link-layer header of a CRC-less frame.
type KeyInfo ¶
type KeyInfo struct{ ID, Version byte }
KeyInfo names a key: its Key ID and version (FFh: not used).
func SITPActiveKeys ¶
SITPActiveKeys reads DSI 21h content.
type KeyLookup ¶
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. A hex stream skips lines without a telegram.
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 ParseHexLine ¶
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 ReadAmber ¶
ReadAmber reads one received radio telegram in Amber command mode, skipping other commands; rssiByte says an RSSI byte follows the telegram.
func ReadIM871A ¶
ReadIM871A reads one radio-link message indication, skipping other messages and garbage.
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.
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.
type SITPKey ¶
type SITPKey struct {
Key []byte
At TargetTime
KeyInfo
}
SITPKey is the content of a DSI 01h structure after unwrapping.
func SITPUnwrapKey ¶
SITPUnwrapKey reads DSI 01h content (the answer to "get security information" for a generated key).
type SITPKeyCounter ¶
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())
// 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 ¶
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) Queued ¶
Queued lists every meter's queue (copies of the lists, the same entries).
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 ¶
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
}
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