cosem

package
v0.1.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: 45 Imported by: ? modules, 0 packages

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

Documentation

Overview

Package cosem is a DLMS/COSEM client (logical name referencing): the application association (AARQ, AARE, RLRQ, RLRE) with low-level and high-level security authentication (mechanisms 1 to 7), the security suites 0 to 2 with service-specific, general-glo, general-ded and general ciphering, general signing, third-party protection and V.44 compression (IEC 62056-5-3:2023, the DLMS UA Green Book), get, set and action with block transfer, the security setup object (class 64: key transfer and agreement, certificates), push reception (data-notification, general block transfer, HDLC pushes), the gateway protocol of IEC 62056-5-3 annex C for meters behind a data concentrator, profile reading by range, meter-initiated connections, local serial lines with the IEC 62056-21 mode E opening, and invocation counters kept across restarts.

The xDLMS services are those of gosem (gitlab.com/circutor-library/gosem, MIT), configured without ciphering: SecureTransport sits between gosem and the supporting layers (packages wrapper, hdlc, phy and gateway of this module) and applies the protection itself, so every combination of suite, policy, key and ciphering form works.

The main entry points:

  • SecurityConfig turns text settings into the HLS value an association uses; Associate opens one association over a transport the caller opened; Client keeps one meter's associations, its invocation counter and the system title it named.
  • ICReservation, Counter and PushCounter keep invocation counters through an iotsec.Store, so a restart never repeats one.
  • OpenProtectedPush, DecodeDataNotification, PushSetupOf and MapPush open and map pushes; ServeHDLCPushes reads pushes in HDLC frames; InboundConn carries a meter-initiated connection.
  • Gateway is the shared connection to a DCU (gateway or logical-device mode).
  • ReadCaptureObjects, ReadProfileRange and ProfileRow read profiles.
  • SecuritySetup runs the methods of the security setup object.
  • NewPortClient runs a client over a port another protocol opened (an optical head after an IEC 62056-21 mode E switch).
  • Seal, Open, Request and Exchange carry DLMS APDUs inside another protocol (wireless and wired M-Bus).

A crypto policy (iotsec.CryptoPolicy) may veto an authentication mechanism at association time (AssociationConfig.Policy, MechanismAlgorithm). Refusals of pushes for their protection are *PushSecurityError with a stable event name for a security log (iotsec.SecurityEvent).

Comments cite the clauses they implement; "F-nnnn" names a finding in SigmaM2M's register of specification defects (see PROVENANCE.md).

Index

Examples

Constants

View Source
const (
	ClassData             = is15959.ClassData
	ClassRegister         = is15959.ClassRegister
	ClassExtendedRegister = is15959.ClassExtendedRegister
	ClassDemandRegister   = is15959.ClassDemandRegister
	ClassProfileGeneric   = is15959.ClassProfileGeneric
	ClassClock            = is15959.ClassClock
	ClassDisconnect       = is15959.ClassDisconnect
)

Interface classes used here.

View Source
const (
	GroupNameplate     = is15959.GroupNameplate
	GroupInstantaneous = is15959.GroupInstantaneous
	GroupEnergy        = is15959.GroupEnergy
	GroupBlockLoad     = is15959.GroupBlockLoad
	GroupDailyLoad     = is15959.GroupDailyLoad
	GroupBilling       = is15959.GroupBilling
	GroupEvents        = is15959.GroupEvents
	GroupProgrammable  = is15959.GroupProgrammable
	GroupScalers       = is15959.GroupScalers
	GroupPush          = is15959.GroupPush
	GroupSecurity      = is15959.GroupSecurity
	GroupCommunication = is15959.GroupCommunication
)

Groups a meter can read (settings "groups").

View Source
const (
	// GatewayMalformed is a gateway prefix from the DCU that does not
	// parse.
	GatewayMalformed = "malformed"
	// GatewayAddressMismatch is an answer from another address than the
	// meter's, given to the only request waiting.
	GatewayAddressMismatch = "address-mismatch"
	// GatewayUnknownAddress is an answer or push from an address no meter
	// is known at.
	GatewayUnknownAddress = "unknown-address"
)

Kinds of GatewayEvent.

View Source
const (
	TagGeneralGlo       byte = 0xDB
	TagGeneralDed       byte = 0xDC
	TagGeneralCiphering byte = 0xDD
	TagGeneralSigning   byte = 0xDF
)

APDU tags.

View Source
const (
	KeyGlobalUnicast   byte = 0
	KeyGlobalBroadcast byte = 1
	KeyAuthentication  byte = 2
	KeyMaster          byte = 3
)

Key IDs of identified-key and of the security setup key methods.

View Source
const (
	OpGet    = "get"
	OpSet    = "set"
	OpAction = "action"
)

Operations.

View Source
const (
	MechNone   = 0
	MechLow    = 1
	MechHLS    = 2
	MechMD5    = 3
	MechSHA1   = 4
	MechGMAC   = 5
	MechSHA256 = 6
	MechECDSA  = 7
)

Authentication mechanism IDs (the last arc of the mechanism name).

View Source
const (
	SecAuthentication byte = 0x10
	SecEncryption     byte = 0x20
	SecBroadcastKey   byte = 0x40 // key set: the global broadcast key
	SecCompressed     byte = 0x80 // the protected APDU is V.44 compressed

)

Security policy bits of the security control byte.

View Source
const (
	ContextAuto        byte = 0
	ContextLN          byte = 1 // logical name referencing, no ciphering
	ContextLNCiphering byte = 3 // logical name referencing with ciphering
)

Application contexts the AARQ can propose (the last arc of the application context name, IEC 62056-5-3:2023 7.3.7.1).

View Source
const (
	CipherServiceSpecific byte = iota
	CipherGeneralGlo
	CipherGeneralDed
	CipherGeneral
)

Ciphering forms.

View Source
const (
	GenKeyIdentified byte = iota
	GenKeyWrapped
	GenKeyOnePass
	GenKeyStatic
)

General-ciphering key-info choices we send.

View Source
const (
	PolicyAuthRequest   byte = 0x04
	PolicyEncRequest    byte = 0x08
	PolicySignRequest   byte = 0x10
	PolicyAuthResponse  byte = 0x20
	PolicyEncResponse   byte = 0x40
	PolicySignResponse  byte = 0x80
	PolicyAuthenticated      = PolicyAuthRequest | PolicyAuthResponse
	PolicyEncrypted          = PolicyEncRequest | PolicyEncResponse
	PolicySigned             = PolicySignRequest | PolicySignResponse
)

Security policy bits (security setup version 1).

View Source
const ClassHDLCSetup = 23

ClassHDLCSetup is the IEC HDLC setup interface class (IEC 62056-6-2:2023 4.7.2).

View Source
const ClassLimiter = 71

ClassLimiter is the limiter interface class (IEC 62056-6-2:2023 4.5.9).

View Source
const ClassSecuritySetup = 64

ClassSecuritySetup is the security setup interface class.

View Source
const ClockOBIS = is15959.ClockOBIS

ClockOBIS is the meter clock (class 8).

View Source
const DefaultICWindow = 100000

DefaultICWindow is how far ICReservation reserves ahead.

View Source
const DefaultSystemTitle = "53474D0000000001"

DefaultSystemTitle is the system title SecurityConfig uses when none is given ("SGM" and a serial number).

View Source
const DisconnectControl = is15959.DisconnectControl

DisconnectControl is the disconnect control object (class 70).

View Source
const GeneralErrorOBIS = "0.0.97.97.0.255"

GeneralErrorOBIS is the general error object of annex A of EN 13757-1:2021 (Tables A.1 to A.4).

View Source
const HDLCSetupInactivity = 8

HDLCSetupInactivity is its inactivity_time_out attribute, in seconds, 0 when not operational (4.7.2.2.8).

View Source
const InvokeUnconfirmed byte = 0x01

InvokeUnconfirmed is invoke-id-and-priority for an unconfirmed request: invoke id 1, service class (bit 6) 0, normal priority.

View Source
const MaxGBT = maxGBT

MaxGBT bounds an APDU joined from blocks.

View Source
const MaxListItems = 64

MaxListItems bounds the items of one request with list (ours).

View Source
const RecentPushICs = 64

RecentPushICs bounds the counters of unauthenticated pushes a PushCounter keeps.

View Source
const SerialPrefix = "serial://"

SerialPrefix starts an address naming a local serial port.

View Source
const TagGBT byte = 0xE0

TagGBT is the general-block-transfer APDU tag.

Variables

View Source
var CertEntities = map[string]byte{"server": 0, "client": 1, "ca": 2, "other": 3}

CertEntities names the certificate entities.

View Source
var ErrCompressed = errors.New("the APDU is compressed (security control bit 7, ITU-T V.44) where IEC 62056-5-3:2023 has no compression: only general-glo, general-ded and general ciphering with security suite 1 or 2 carry compressed APDUs (5.3.6, Table 26, Table 9)")

ErrCompressed refuses APDUs whose security control has the compression bit set where no compression can be: IEC 62056-5-3:2023 applies V.44 in general-glo, general-ded and general ciphering (5.3.6, Figures 31 and 32) and only with suites 1 and 2 (Table 9).

View Source
var ErrCompressionOff = errors.New("the meter sent a V.44 compressed APDU (security control bit 7) and compression is not enabled for it (set compression.enabled, with the meter's V.44 codewords, maxStringLength and history)")

ErrCompressionOff refuses compressed APDUs from a meter whose settings do not enable compression.

View Source
var ErrInboundClosed = errors.New("the meter's inbound connection is closed")

ErrInboundClosed is the error of a request on a closed connection.

View Source
var ErrNoKeys = errors.New("the DLMS APDU is protected and no key is configured (dlmsKey)")

ErrNoKeys is returned for a protected APDU when no key is configured.

View Source
var GeneralErrorBits = []ErrorBit{
	{15, "alert_unacknowledged"}, {14, "warning_unacknowledged"}, {13, "indication_unacknowledged"},
	{7, "alert_pending"}, {6, "warning_pending"}, {5, "indication_pending"},
}

GeneralErrorBits are the named bits of the general error object.

View Source
var KeyNames = map[string]byte{"unicast": KeyGlobalUnicast, "broadcast": KeyGlobalBroadcast, "authentication": KeyAuthentication}

KeyNames name the keys key_transfer and key_agreement change.

View Source
var KeyPairs = map[string]byte{"signing": 0, "key-agreement": 1, "tls": 2}

KeyPairs names the key pairs of generate_key_pair and generate_certificate_request.

View Source
var MechanismNames = map[string]byte{
	"": MechNone, "none": MechNone, "low": MechLow,
	"hls": MechHLS, "hls-aes": MechHLS,
	"hls-md5": MechMD5, "hls-sha1": MechSHA1,
	"high": MechGMAC, "hls-gmac": MechGMAC, "gmac": MechGMAC,
	"hls-sha256": MechSHA256, "hls-ecdsa": MechECDSA, "ecdsa": MechECDSA,
}

MechanismNames maps the names of authentication mechanisms (as SecurityConfig.Authentication takes them) to their IDs.

Functions

func BitsSet

func BitsSet(d axdr.DlmsData) []int

BitsSet lists the bit numbers set in a bit string (bit 0 first, the most significant bit of the first byte), as IS 15959 numbers the event status word.

func CheckHDLCAddresses

func CheckHDLCAddresses(client, upper, lower, size int) error

CheckHDLCAddresses checks the addresses of a connection (IEC 62056-46 6.4.2.3, Tables 3 and 4): a client address of one octet that is neither no-station nor all-station; an upper address naming one logical device (the management logical device 1, or 16 up to below all-station); a lower address naming one physical device (16 up to below CALLING), or CALLING when the meter called us.

func ClockStatus

func ClockStatus(s string) (byte, bool)

ClockStatus is the clock_status octet of a 12-octet COSEM date-time in hex (its last octet), unless it is 0xFF, not specified.

func CommError

func CommError(err error) bool

CommError reports errors after which the association is dropped: all but the meter refusing a get, set or action, or a parameter.

func DateTime

func DateTime(hexs string, loc *time.Location) (time.Time, bool)

DateTime decodes a COSEM date-time (12-byte octet string, as hex). An unspecified deviation (0x8000) means the meter's local time in loc; a given deviation is minutes of UTC minus local time.

func DecodeLength

func DecodeLength(b []byte) (n, size int)

DecodeLength reads an A-XDR length.

func DefaultClientAddress

func DefaultClientAddress(mech byte) int

DefaultClientAddress is the client address of an association by its mechanism, as IS 15959 numbers them (table 3 of Part 1, table 2 of Part 2): 16 the public client without authentication, 32 the meter reader with low-level security, 48 the utility settings client with HLS.

func DefaultProfile

func DefaultProfile(phases int) string

DefaultProfile is the profile of a meter without a "profile" setting.

func DescribeEvent

func DescribeEvent(row map[string]any, code int)

DescribeEvent adds what IS 16444 readers need of an event code to its log row: the key applications label it by, its compartment, occurrence or restoration, the condition it belongs to and whether we class it as a tamper (is15959.EventInfo). Codes no part defines get none of these.

func DropOctets

func DropOctets(b []byte, at []int) []byte

DropOctets returns b without the octets at the given (ascending) positions.

func EncodeAXDR

func EncodeAXDR(d *axdr.DlmsData) (r, g []byte, strays []int)

EncodeAXDR returns the correct A-XDR encoding of d (r), gosem's encoding of it (g) and the positions in g of the octets gosem adds.

func EncodeDateTime

func EncodeDateTime(t time.Time, loc *time.Location) []byte

EncodeDateTime is the inverse of DateTime for loc: a COSEM date-time (IEC 62056-6-2:2023 4.1.6.1) in local time with the deviation not specified, hundredths 0, and clock_status bit 7 (daylight saving active) set when loc is on daylight saving time at t.

func EncodeResponse

func EncodeResponse(r Response) ([]byte, error)

EncodeResponse builds a response-normal (the meter's side): a GET with data, or a result code.

func EncodeUnconfirmedSet

func EncodeUnconfirmedSet(class uint16, obis string, attr int8, data *axdr.DlmsData) ([]byte, error)

EncodeUnconfirmedSet encodes a set-request-normal for one attribute that asks for no answer (invoke-id-and-priority with service class 0), as a broadcast set sends it.

func GeneralErrorFlags

func GeneralErrorFlags(v uint16) []string

GeneralErrorFlags names the set bits of a general error object value; reserved bits that are set are named "reserved_<bit>".

func IsGatewayDown

func IsGatewayDown(err error) bool

IsGatewayDown reports an error of an unreachable DCU (retrying the meter does not help).

func IsGeneralError

func IsGeneralError(code string, class uint16, attr int8) bool

IsGeneralError reports the general error object's value attribute.

func IsTimeColumn

func IsTimeColumn(c Capture) bool

IsTimeColumn reports a capture object holding a date-time that times a profile's entries: the clock's time (IEC 62056-6-2:2023 4.5.1), or the time stamp of the billing period (6.2.3: a Data object, or a register or extended register with scaler 0 and no unit).

func KeyTransferItem

func KeyTransferItem(id byte, wrapped []byte) *axdr.DlmsData

KeyTransferItem is one {key_id, wrapped key} of key_transfer.

func LimiterThreshold

func LimiterThreshold(class uint16, attr int8) bool

LimiterThreshold reports the limiter attributes holding thresholds (threshold_active, threshold_normal, threshold_emergency: 3, 4, 5), which are in the units of the value the limiter monitors.

func MechanismAlgorithm

func MechanismAlgorithm(mech byte) (alg iotsec.Algorithm, ok bool)

MechanismAlgorithm describes the cryptography of an authentication mechanism for a crypto policy (iotsec.CryptoPolicy): mechanism 2 is AES-128 in ECB mode, 3 MD5, 4 SHA-1, 5 AES-GMAC, 6 SHA-256 and 7 ECDSA. none and low use none (ok is false).

func MonitoredValue

func MonitoredValue(d axdr.DlmsData) (uint16, string, bool)

MonitoredValue reads a limiter's monitored_value: {class_id, logical_name, attribute_index}.

func NameOf

func NameOf(code string, class uint16, attr int8) string

NameOf returns the catalogue name of an attribute; for an object the catalogue does not list, the name the OBIS model derives (IEC 62056-6-1:2023, package obis) with the class's attribute suffix; and the OBIS code for a code without a standard meaning (manufacturer, utility, country specific or reserved). The class picks the row where one code names objects of several classes (IEC 62056-6-2:2023 clause 6).

func NeedsPassword

func NeedsPassword(mech byte) bool

NeedsPassword reports the mechanisms that need a password or secret: low-level security and HLS mechanisms 2, 3, 4 and 6.

func Number

func Number(d axdr.DlmsData) (float64, bool)

Number returns a numeric A-XDR value as float64.

func OBISFromHex

func OBISFromHex(h string) (string, error)

OBISFromHex writes a logical name given as 12 hex digits (as gosem gives octet strings) as a dotted OBIS code.

func Open

func Open(apdu []byte, keys *Keys) (plain, systemTitle []byte, ic uint32, err error)

Open removes general-glo-ciphering (an APDU in the clear comes back as it is, with a nil system title).

func OpenSerialLine

func OpenSerialLine(device string, s SerialSettings, timeout time.Duration) (net.Conn, error)

OpenSerialLine opens the line of a meter on device: with optical, the IEC 62056-21 mode E sign-on and switch to HDLC first.

func PEMBlock

func PEMBlock(v string) (*pem.Block, error)

PEMBlock reads the first PEM block of v (inline or a file path).

func PEMCertificates

func PEMCertificates(v string) []*x509.Certificate

PEMCertificates are the certificates in v (inline or a file path), in order; blocks of other types are skipped.

func ParseOBIS

func ParseOBIS(s string) ([6]byte, error)

ParseOBIS reads an OBIS code written as six numbers 0 to 255 separated by ".", "-" or ":".

func ParsePushObjectList

func ParsePushObjectList(d axdr.DlmsData) []is15959.Column

ParsePushObjectList reads a push setup's push_object_list (class 40 attribute 2) as columns named by the catalogue; nil when an entry is not in the expected form.

func PointName

func PointName(obis string, class uint16, attr int8) string

PointName names an attribute as the catalogue does (catalogue name, OBIS model name, else the code).

func PolicyBits

func PolicyBits(policy byte, signing bool) byte

PolicyBits is the version 1 security_policy for an APDU policy and signing.

func ProfileRow

func ProfileRow(r *axdr.DlmsData, cols []Capture, x RowScalers) (map[string]any, time.Time)

ProfileRow is a profile entry as written: each capture object's value by its name, register values scaled by the meter's scaler_unit with the units under "units", an event code named, and the entry's time from its first time column (zero when it has none).

func Protect

func Protect(suite Suite, policy byte, key, ak, systemTitle []byte, ic uint32, plain []byte) ([]byte, error)

Protect applies the security policy to plain, returning SC ‖ IC ‖ body.

Example

The security suite 0 example of the DLMS UA Green Book: a GET request authenticated and encrypted with AES-GCM-128 under system title 4D4D4D0000BC614E and invocation counter 01234567.

package main

import (
	"encoding/hex"
	"fmt"

	"github.com/cB-Sigma/dlms/cosem"
)

func main() {
	hexb := func(s string) []byte {
		b, err := hex.DecodeString(s)
		if err != nil {
			panic(err)
		}
		return b
	}
	p, err := cosem.Protect(0, cosem.SecAuthentication|cosem.SecEncryption,
		hexb("000102030405060708090A0B0C0D0E0F"), hexb("D0D1D2D3D4D5D6D7D8D9DADBDCDDDEDF"),
		hexb("4D4D4D0000BC614E"), 0x01234567, hexb("C0010000080000010000FF0200"))
	if err != nil {
		panic(err)
	}
	fmt.Printf("%X\n", p)
}
Output:
3001234567411312FF935A47566827C467BC7D825C3BE4A77C3FCC056B6B

func PushSetupOf

func PushSetupOf(sp *is15959.Spec, items []*axdr.DlmsData, read func(obis string) ([]is15959.Column, bool)) (*is15959.PushSetup, error)

PushSetupOf finds the push setup of a profile a notification came from: the element captured from a class 40 logical name names it; otherwise the one push setup whose capture list has as many elements. read, when not nil, gives the push_object_list read from the meter for a push setup, which then replaces the profile's capture list.

func PushTag

func PushTag(apdu []byte) bool

PushTag reports APDUs a meter sends unasked: data-notification, general-glo-ciphering (a protected push) and general block transfer.

func RangeDescriptor

func RangeDescriptor(c Capture, from, to time.Time, loc *time.Location) *axdr.DlmsData

RangeDescriptor is the selective access by range of a profile's buffer (IEC 62056-6-2:2023 4.3.6.2.9, access selector 1): restricted by the profile's own time column (a capture_object_definition with data index 0), from and to as date-time octet strings in the meter's local time, and every column (an empty selected_values).

func ReadCapturePeriod

func ReadCapturePeriod(c gdlms.Client, profile string) uint32

ReadCapturePeriod reads a profile's capture_period (IEC 62056-6-2:2023 profile generic, class 7 attribute 4, seconds): 0 when it is asynchronous or cannot be read.

func ReadInvocationCounter

func ReadInvocationCounter(tr gdlms.Transport, obis string, timeout time.Duration, name, where string) (uint32, error)

ReadInvocationCounter reads the frame counter a meter keeps for a client (class 1 value attribute at obis) through a public association on tr, which it closes. name and where name the meter in errors.

func ReadProfileRange

func ReadProfileRange(c gdlms.Client, profile string, tc Capture, from, to time.Time, loc *time.Location) ([]*axdr.DlmsData, error)

ReadProfileRange reads the entries of a profile's buffer from from to to, by its time column tc (selective access by range).

func ReadScaled

func ReadScaled(c gdlms.Client, o Object, loc *time.Location) (v any, unit string, err error)

ReadScaled reads one attribute. A register's value (class 3 or 4 attribute 2, class 5 attributes 2 and 3) is scaled by its scaler_unit (attribute 3, or 4 for class 5), whose unit is returned; clock values and 12-byte date-times are returned as RFC 3339 text.

func Readable

func Readable(d axdr.DlmsData, loc *time.Location, asDateTime bool) any

Readable is Value for an object's own reading: an octet string whose bytes are all printable ASCII is text (IS 15959 keeps the serial number, manufacturer name, device ID and firmware version in octet strings), a 12-byte one that is a valid COSEM date-time (the capture time of a maximum demand register) is a time, and any other stays hexadecimal (keys, system titles, bit fields). SigmaM2M finding F-2600 (PROVENANCE.md).

func Rejected

func Rejected(err error) bool

Rejected reports a DLMS error that concerns one object (the meter refused the request) rather than the link.

func Scaled

func Scaled(v float64, scaler int8) float64

Scaled applies 10^scaler to a numeric value, keeping it tidy.

func ScaledValue

func ScaledValue(class uint16, attr int8) bool

ScaledValue reports the attributes scaled by the scaler_unit: the value of a register or extended register, and the current and last average values of a demand register.

func ScalerAttr

func ScalerAttr(class uint16) int8

ScalerAttr is the scaler_unit attribute of a class: 3 for the register and extended register, 4 for the demand register (IEC 62056-6-2:2023 4.3.2 to 4.3.4); 0 for classes without one.

func ScalerProfile

func ScalerProfile(rows []*axdr.DlmsData, cols []Capture) map[string]Scaler

ScalerProfile reads the scalers a scaler profile's entry holds (IS 15959 Part 1 annexes C to G, Part 2 and 3 "scaler profile" clauses): the scaler_unit of each register of the profile it belongs to, by the register's logical name, from the last entry of rows.

func ScalerUnit

func ScalerUnit(d axdr.DlmsData) (int8, uint8, error)

ScalerUnit decodes a register's scaler_unit attribute.

func Seal

func Seal(keys *Keys, systemTitle []byte, ic uint32, apdu []byte) ([]byte, error)

Seal protects an APDU with general-glo-ciphering: authenticated and encrypted when the keys have an authentication key, encrypted only otherwise.

func SerialDevice

func SerialDevice(address string) (string, bool)

SerialDevice returns the port an address names (serial:///dev/ttyUSB0, serial://COM3), and whether it names one.

func ServeHDLCPushes

func ServeHDLCPushes(ctx context.Context, c net.Conn, set HDLCPushConfig, handle func(from net.Addr, apdu []byte))

ServeHDLCPushes reads pushes in HDLC frames from a connection a meter (or a converter in front of it) opened, until it closes or stays silent for the inactivity time, and hands each APDU, its LLC header removed, to handle. UI frames are taken as they come (segmented ones joined); I frames are acknowledged with RR. It closes c, also when ctx ends.

func SetSerialOpener

func SetSerialOpener(f func(SerialConfig) (io.ReadWriteCloser, error)) (restore func())

SetSerialOpener replaces the function that opens local serial ports (goburrow/serial by default): for tests with a simulated line, or a platform with its own serial driver. It returns a function restoring the previous one.

func TextOf

func TextOf(d axdr.DlmsData) string

TextOf returns a string or octet string's text (octet strings holding printable characters are read as text).

func TimeColumn

func TimeColumn(cols []Capture) (int, bool)

TimeColumn returns the first time column of a profile.

func TypedData

func TypedData(typ string, v any) (*axdr.DlmsData, error)

TypedData builds A-XDR data for a SET from a type name and a JSON value.

func UnitSymbol

func UnitSymbol(u uint8) string

UnitSymbol is the symbol of a COSEM unit code (IEC 62056-6-2 unit table), empty for codes without one.

func Unprotect

func Unprotect(suite Suite, key, ak, systemTitle, payload []byte) (plain []byte, ic uint32, err error)

Unprotect checks and removes the protection from SC ‖ IC ‖ body sent by the holder of systemTitle.

func UnprotectKeys

func UnprotectKeys(suite Suite, key, bkey, ak, systemTitle, payload, extra []byte) (plain []byte, ic uint32, err error)

UnprotectKeys is unprotectAAD that opens APDUs protected with the broadcast key (security control bit 6) with bkey. Compressed content is refused: callers where compression exists use unprotectGeneral.

func UnwrapKey

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

UnwrapKey reverses wrapKey and checks the integrity value.

func Value

func Value(d axdr.DlmsData, loc *time.Location, asDateTime bool) any

Value converts A-XDR data to a JSON-friendly Go value. Octet strings are hexadecimal text, except 12-byte ones when asDateTime is set.

func WrapKey

func WrapKey(kek, key []byte) ([]byte, error)

WrapKey is RFC 3394 AES key wrap of key (a multiple of 8 bytes, at least 16) with kek.

Types

type Access

type Access struct {
	Selector byte
	// Range: the restricting column (default the clock 0.0.1.0.0.255,
	// class 8, attribute 2) and the date-times from and to.
	RestrictClass uint16
	RestrictOBIS  string
	RestrictAttr  int8
	From, To      time.Time
	Loc           *time.Location
	// Entry: from and to entry (1-based; to 0 is the last).
	FromEntry, ToEntry uint32
}

Access is a selective access of a GET (IEC 62056-6-2:2023 profile generic buffer: selector 1 by range, 2 by entry).

type Association

type Association struct {
	Client gdlms.Client
	Secure *SecureTransport
	Raw    *RawSetTransport
	// Link is the supporting layers under the secure transport.
	Link gdlms.Transport
}

Association is an open application association: gosem's client over our secure transport.

func Associate

func Associate(cfg AssociationConfig) (*Association, error)

Associate opens an association. On failure the returned association, when not nil, still tells the invocation counters used (Secure.usedIC) so the next attempt never repeats one.

type AssociationConfig

type AssociationConfig struct {
	// Transport is the supporting layers for the client address (a
	// wrapper, HDLC or gateway transport); Associate owns it from now on.
	Transport gdlms.Transport
	// Mechanism is the authentication mechanism (MechNone to MechECDSA).
	// Password is the low-level password (MechLow).
	Mechanism byte
	Password  []byte
	// HLS holds the mechanism's secret and keys (mechanisms 2 to 7) and
	// the APDU protection (Security) of the association.
	HLS *HLS
	// FirstIC is the invocation counter the association starts at (see
	// ICReservation and ReadInvocationCounter).
	FirstIC uint32
	// ExpectSystemTitle, when set, is the meter's system title: an AARE
	// naming another is refused.
	ExpectSystemTitle []byte
	// Timeout bounds each request (default 10s).
	Timeout time.Duration
	// Writes, when set, counts the set and action requests sent.
	Writes *atomic.Int64
	// Alive, when set, says whether the link is still up when a request
	// is sent (a request sent on a link known closed never arrived).
	Alive func() bool
	// Check, when set, runs on the open association before it is
	// returned (an identity check, say); an error releases it.
	Check func(gdlms.Client) error
	// Policy, when set, is asked whether the mechanism's algorithm may be
	// used (Use names the use) before anything is sent.
	Policy iotsec.CryptoPolicy
	Use    string
	// Name names the meter and Where its address in errors.
	Name, Where string
}

AssociationConfig is what Associate needs.

type BlockTransfer

type BlockTransfer struct {
	Size int
	// contains filtered or unexported fields
}

BlockTransfer is one request's general block transfer on a request/answer link; a zero Size sends APDUs whole (answers in blocks are still joined).

func (*BlockTransfer) Blocks

func (b *BlockTransfer) Blocks() (sent, received int)

Blocks reports how many blocks we sent and how many of the meter's general-block-transfer APDUs carried data.

func (*BlockTransfer) Receive

func (b *BlockTransfer) Receive(w []byte) (next, answer []byte, err error)

Receive takes the meter's APDU: the next APDU to send (our next block or an acknowledgement), or the whole answer once it is complete.

func (*BlockTransfer) Send

func (b *BlockTransfer) Send(apdu []byte) []byte

Send starts sending a (protected) APDU: whole, or its first block.

type Broadcaster

type Broadcaster struct {
	Send     func(apdu []byte) error
	Security Security // suite, policy, systemTitle, ak, broadcastKey, ciphering
	Password []byte   // low-level security; nil: no authentication
	IC       uint32   // next invocation counter under the broadcast key
	// contains filtered or unexported fields
}

Broadcaster runs an unconfirmed application association with a group of meters or all meters (IEC 62056-5-3:2023 4.1.5, 7.2.4.3, 7.3.2.1): the AARQ proposes response-allowed FALSE and nothing is ever answered, so only the client can authenticate (none or low-level security), only the client's system title is sent (4.1.3.4), and only unconfirmed services are used. Everything is protected with the global broadcast key: the initiate request and service-specific or general-glo APDUs with the key-set bit, general-ciphering with identified-key 1 (the key- set bit 0) and an empty recipient-system-title (6.x, Recipient_System_ Title). Where the APDUs go (a group or the all-station address) is the supporting layer's business: send delivers one APDU there.

func (*Broadcaster) Associate

func (b *Broadcaster) Associate() error

Associate sends the AARQ of the unconfirmed AA; no AARE is awaited.

func (*Broadcaster) Release

func (b *Broadcaster) Release() error

Release sends the RLRQ, carrying the initiate request protected as in the AARQ; an unconfirmed AA's release is not answered.

func (*Broadcaster) Request

func (b *Broadcaster) Request(apdu []byte) error

Request sends an unconfirmed set or action request under the broadcast key in the configured ciphering form.

type Capture

type Capture struct {
	Class uint16
	OBIS  string
	Attr  int8
	Name  string
}

Capture is one column of a profile: the attribute it captures and its catalogue name.

func ParseCaptureObjects

func ParseCaptureObjects(d axdr.DlmsData, profile string) ([]Capture, error)

ParseCaptureObjects reads a profile's capture_objects (class 7 attribute 3): {class_id, logical_name, attribute_index, data_index} per column; columns are named by the catalogue.

func ReadCaptureObjects

func ReadCaptureObjects(c gdlms.Client, profile string) ([]Capture, error)

ReadCaptureObjects reads a profile's columns.

type CertID

type CertID struct {
	BySerial     bool
	Entity, Type byte
	SystemTitle  []byte
	Serial       *big.Int
	Issuer       []byte // DER issuer name
}

CertID identifies a certificate on the meter: by entity, type and system title, or by serial number and issuer.

type CertInfo

type CertInfo struct {
	Entity  byte   `json:"entity"`
	Type    byte   `json:"type"`
	Serial  string `json:"serial"`
	Issuer  string `json:"issuer"`
	Subject string `json:"subject"`
}

CertInfo is one entry of the certificates attribute.

type Client

type Client struct {
	Config ClientConfig
	// contains filtered or unexported fields
}

Client is a client of one meter. It is not safe for concurrent use: callers run one exchange at a time.

Example

A client with HLS-GMAC (mechanism 5) and authenticated and encrypted APDUs under a dedicated key reads a voltage register from a meter over the wrapper on TCP. The meter's frame counter for the client is read first through the public client, so the association starts past it. (It needs a meter, so it is compiled but not run; the dlms-sim module runs the same steps against its simulated meter.)

package main

import (
	"fmt"
	"time"

	gdlms "gitlab.com/circutor-library/gosem/pkg/dlms"

	"github.com/cB-Sigma/dlms/cosem"
	"github.com/cB-Sigma/dlms/wrapper"
)

func main() {
	key := []byte("0123456789ABCDEF")
	ak := []byte("FEDCBA9876543210")
	addr := "192.0.2.10:4059"

	sec := cosem.SecurityConfig{Name: "M1", Authentication: "hls-gmac", Security: "authenticated-encrypted",
		BlockCipherKey: fmt.Sprintf("%X", key), AuthenticationKey: fmt.Sprintf("%X", ak), DedicatedKey: true}
	hls, _, err := sec.Build()
	if err != nil {
		panic(err)
	}
	c := cosem.NewClient(cosem.ClientConfig{
		Transport: func(client int) (gdlms.Transport, error) {
			return wrapper.New("tcp", addr, client, 1, 5*time.Second)
		},
		ClientAddress:     cosem.DefaultClientAddress(cosem.MechGMAC), // 48
		HLS:               hls,
		InvocationCounter: &cosem.FrameCounterObject{OBIS: "0.0.43.1.3.255"},
		Name:              "M1", Where: addr,
	})
	if err := c.Connect(); err != nil {
		panic(err)
	}
	defer c.Close()
	v, err := c.Get(3, "1.0.32.7.0.255", 2)
	if err != nil {
		panic(err)
	}
	s, err := cosem.ReadScaler(c.Association().Client, 3, "1.0.32.7.0.255")
	if err != nil {
		panic(err)
	}
	n, _ := cosem.Number(v)
	fmt.Println(cosem.Scaled(n, s.Exponent), s.Unit)
}

func NewClient

func NewClient(cfg ClientConfig) *Client

NewClient returns a client; nothing is sent until Connect.

func (*Client) Association

func (c *Client) Association() *Association

Association is the open association, nil when there is none.

func (*Client) Close

func (c *Client) Close()

Close releases the open association, if any, and disconnects.

func (*Client) Connect

func (c *Client) Connect() error

Connect opens an association with the current settings, closing any open one first.

func (*Client) Get

func (c *Client) Get(class uint16, obis string, attr int8) (axdr.DlmsData, error)

Get reads one attribute on the open association.

func (*Client) LastIC

func (c *Client) LastIC() uint32

LastIC is the next invocation counter the client would use; SetLastIC sets it (a counter kept elsewhere).

func (*Client) MeterSystemTitle

func (c *Client) MeterSystemTitle() []byte

MeterSystemTitle is the system title the meter named in its first association (nil before).

func (*Client) Secure

func (c *Client) Secure() *SecureTransport

Secure is the secure transport of the last association attempted.

func (*Client) SetLastIC

func (c *Client) SetLastIC(ic uint32)

SetLastIC sets the next invocation counter the client would use.

type ClientConfig

type ClientConfig struct {
	// Transport opens the supporting layers for a client address.
	Transport func(client int) (gdlms.Transport, error)
	// ClientAddress is the association's client address.
	ClientAddress int
	// HLS is the authentication and APDU protection (SecurityConfig.Build);
	// it is read at every Connect, so a key change takes effect on the
	// next association. Password is the low-level password.
	HLS      *HLS
	Password []byte
	// InvocationCounter, when set, is read before each protected
	// association.
	InvocationCounter *FrameCounterObject
	// Reserve, when set, raises an association's first invocation counter
	// to a stored reservation and keeps the reservation ahead of it
	// (ICReservation.Reserve); first is true until the client has used a
	// counter.
	Reserve func(ic uint32, first bool) (uint32, error)
	// ExpectSystemTitle is the meter's system title; when nil, the one it
	// names in its first association is expected afterwards.
	ExpectSystemTitle []byte
	// Timeout bounds each request (default 10s).
	Timeout time.Duration
	// Writes, Alive, Check, Policy and Use are as in AssociationConfig.
	Writes *atomic.Int64
	Alive  func() bool
	Check  func(gdlms.Client) error
	Policy iotsec.CryptoPolicy
	Use    string
	// Name and Where name the meter and its address in errors.
	Name, Where string
}

ClientConfig configures a Client.

type CommandAccess

type CommandAccess struct {
	Selector  string `json:"selector"`
	From      string `json:"from"`
	To        string `json:"to"`
	FromEntry uint32 `json:"fromEntry"`
	ToEntry   uint32 `json:"toEntry"`
	Restrict  *struct {
		Class     int    `json:"class"`
		OBIS      string `json:"obis"`
		Attribute int    `json:"attribute"`
	} `json:"restrict"`
}

CommandAccess is the selective access of a dlms command.

type CommandRequest

type CommandRequest struct {
	Op        string `json:"op"` // get (default), set or action
	Class     int    `json:"class"`
	OBIS      string `json:"obis"`
	Attribute *int   `json:"attribute"` // get, set: 1 to 127, default 2
	Method    int    `json:"method"`    // action: the method id
	Value     string `json:"value"`     // set: the value; action: the parameters (optional); A-XDR in hex
	// Access is the selective access of a get: {"selector": "range",
	// "from", "to" (RFC 3339), "restrict": {"class", "obis",
	// "attribute"}} or {"selector": "entry", "fromEntry", "toEntry"}.
	Access *CommandAccess `json:"access"`
	// List adds further attributes (get, set) or methods (action) of the
	// same operation, each {"class", "obis", "attribute" or "method",
	// "value", "access"}; the request then goes "with list".
	List []CommandRequest `json:"list,omitempty"`
}

CommandRequest is a DLMS request as an M-Bus application takes it: a GET or SET of one attribute.

func (CommandRequest) Request

func (b CommandRequest) Request() (Request, error)

Request checks the command and builds its request (invoke-id 0).

type Compression

type Compression struct {
	Enabled          bool `json:"enabled"`
	CompressRequests bool `json:"compressRequests,omitempty"`
	Codewords        int  `json:"codewords,omitempty"`
	MaxStringLength  int  `json:"maxStringLength,omitempty"`
	History          int  `json:"history,omitempty"`
}

Compression is a meter's V.44 setting.

func (*Compression) Apply

func (c *Compression) Apply(meterID string, sec *Security) error

Apply checks the setting against the security settings and stores it in sec. A nil or disabled setting leaves compression off.

type CompressionParams

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

CompressionParams is the checked setting a secure transport uses.

type Counter

type Counter struct {
	Store iotsec.Store
	Name  string // the meter, in errors
	// contains filtered or unexported fields
}

Counter hands out the invocation counters of the APDUs a client protects for one meter (general-glo-ciphering never reuses a counter with a key): each counter is stored before it is used, so a restart continues above it. The stored value is {"ic": n}.

func (*Counter) Next

func (c *Counter) Next(ctx context.Context) (uint32, error)

Next returns the next counter, stored first.

type ErrorBit

type ErrorBit struct {
	Bit  uint
	Name string
}

ErrorBit is one named bit of the general error object of EN 13757-1:2021 10.3.2 (0.b.97.97.0.255, class 1, unsigned16; annex A lists it for every basic meter): per condition (alert, warning, indication) a non-acknowledged bit (15, 14, 13) and a pending bit (7, 6, 5); the other bits are reserved.

type Exchange

type Exchange struct {
	Req Request
	// contains filtered or unexported fields
}

Exchange runs one request.

func (*Exchange) Done

func (x *Exchange) Done() bool

Done reports a finished exchange.

func (*Exchange) Outcome

func (x *Exchange) Outcome(loc *time.Location) (point string, value any, result map[string]any)

Outcome is what a finished exchange writes: the attribute's point and value (a GET that brought data; empty otherwise) and the dlmsResult record.

func (*Exchange) Result

func (x *Exchange) Result() Result

Result is what a finished exchange brought.

func (*Exchange) Step

func (x *Exchange) Step(resp []byte) ([]byte, error)

Step takes the meter's answer (unprotected) and returns the next APDU to send, or nil when the exchange is done.

type FrameCounterObject

type FrameCounterObject struct {
	OBIS          string
	ClientAddress int
}

FrameCounterObject is the object holding a client's invocation counter in the meter (class 1, value attribute), read through an unauthenticated association of ClientAddress (default 16, the public client) before a protected association, so the client's counter never falls behind the meter's.

type GBTAssembler

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

GBTAssembler joins one sender's blocks.

func (*GBTAssembler) Add

func (g *GBTAssembler) Add(apdu []byte) ([]byte, error)

Add takes one block and returns the whole APDU after the last block, or nil while more are expected. Blocks must come in order from 1.

type Gateway

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

Gateway is the shared connection to a DCU and its health.

func NewGateway

func NewGateway(cfg GatewayConfig) *Gateway

NewGateway prepares a gateway; nothing is dialled until a transport connects or Ensure is called.

func (*Gateway) Close

func (l *Gateway) Close()

Close closes the DCU's connection and waits for its reader.

func (*Gateway) Dials

func (l *Gateway) Dials() int

Dials counts the connections opened to the DCU.

func (*Gateway) Ensure

func (l *Gateway) Ensure() error

Ensure opens the DCU's connection if it is not open. After a failed attempt, requests within the DCU's timeout fail at once with the same error instead of each dialling again.

func (*Gateway) Health

func (l *Gateway) Health() GatewayHealth

Health reports the DCU's connection state.

func (*Gateway) Online

func (l *Gateway) Online() int8

Online reports the DCU's last known state: -1 unknown, 0 unreachable, 1 connected.

func (*Gateway) Run

func (l *Gateway) Run(ctx context.Context, every time.Duration)

Run keeps trying an unreachable DCU every interval until ctx ends, so its meters' state is known without waiting for their reads.

func (*Gateway) Transport

func (l *Gateway) Transport(d GatewayDest) gdlms.Transport

Transport is a gosem transport to a meter behind the DCU. Connect joins the DCU's connection (dialling it when needed); Disconnect ends the association's use of it without closing it.

func (*Gateway) Unreachable

func (l *Gateway) Unreachable() bool

Unreachable reports whether the DCU's last connection attempt failed.

type GatewayConfig

type GatewayConfig struct {
	// ID names the DCU in messages.
	ID string
	// Address is the host:port of the DCU's wrapper port, Network tcp
	// (default) or udp.
	Address, Network string
	// MaxOutstanding is how many requests may wait for an answer at once,
	// across its meters (default 1: the meters in turn).
	MaxOutstanding int
	// Timeout bounds connecting (default 10s). After a failed attempt,
	// requests within it fail at once with the same error.
	Timeout time.Duration
	// Dial opens the connection (default net.DialTimeout).
	Dial func(network, address string, timeout time.Duration) (net.Conn, error)
	// Logger receives debug and warning lines (nil: none).
	Logger *slog.Logger
	// Event receives GatewayEvents (nil: logged only).
	Event func(GatewayEvent)
	// Push receives an APDU a meter sent unasked through the DCU: pre is
	// its gateway prefix (nil when it came without one), src its source
	// wPort (the logical device in logical-device mode).
	Push func(pre *gateway.Prefix, src uint16, apdu []byte)
	// HasMeter reports whether a gateway-mode meter is configured at a
	// network and physical address (pushes some DCUs forward as answers
	// are recognised by it).
	HasMeter func(network byte, address []byte) bool
	// Health is called after every connection attempt, outside the
	// gateway's locks, with the state before it (-1 unknown, 0
	// unreachable, 1 connected) and the attempt's error.
	Health func(was int8, err error)
}

GatewayConfig configures a Gateway.

type GatewayDest

type GatewayDest struct {
	Logical        bool
	Network        byte
	Address        []byte
	Client, Server uint16
	// Name names the meter in messages.
	Name string
	// Timeout bounds each request (default 20s).
	Timeout time.Duration
}

GatewayDest names one association's peer behind a DCU: a logical device of the DCU (Logical, at Server) or a meter at a network and physical address (gateway mode).

type GatewayDown

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

GatewayDown is the error of a DCU that cannot be reached.

func (*GatewayDown) Error

func (e *GatewayDown) Error() string

Error says which DCU is down and why.

type GatewayEvent

type GatewayEvent struct {
	Kind, Message, Detail string
}

GatewayEvent is something about a DCU's traffic an application may want to show: Kind is one of the Gateway constants, Message says what happened, and Detail is the address concerned.

type GatewayHealth

type GatewayHealth struct {
	Online  int8 // -1 unknown, 0 unreachable, 1 connected
	LastErr string
	Since   time.Time // when Online last changed
	LastOK  time.Time // the last successful connection
}

GatewayHealth is a DCU's connection state.

type HDLCPushConfig

type HDLCPushConfig struct {
	// Answer answers a Hayes modem's RING (ATA, then CONNECT; IEC 62056-42
	// A.2.3) before anything else; Identify runs the identification
	// service (6.3.3) and refuses another stack than COSEM; Trigger sends
	// the empty UI frame that gives the calling meter the right to talk,
	// with server addresses of AddressSize octets (1, 2 or 4).
	Answer, Identify, Trigger bool
	AddressSize               int
	// Inactivity closes a connection silent this long (default 10m).
	Inactivity time.Duration
	// Logger receives the refusals (nil: none).
	Logger *slog.Logger
}

HDLCPushConfig is how ServeHDLCPushes takes a call.

type HLS

type HLS struct {
	Mechanism byte
	Secret    []byte
	Security  Security
	SignKey   *ecdsa.PrivateKey // ours (mechanism 7)
	MeterKey  *ecdsa.PublicKey  // the meter's (mechanism 7)
}

HLS is everything passes 3 and 4 need.

type ICReservation

type ICReservation struct {
	Store  iotsec.Store
	Window uint32 // default DefaultICWindow
	// Name names the meter in errors.
	Name string
	// contains filtered or unexported fields
}

ICReservation keeps a reservation, "next", above every invocation counter the process may have used for an association's key. Each association starts at least there, and the reservation moves Window ahead whenever fewer than half of it remain, so one write covers many associations and a restart skips at most Window. The stored value is {"next": n}.

Example

Invocation counters across a restart: the reservation is stored ahead of the counters used, and the first association after a restart starts at the stored reservation.

package main

import (
	"context"
	"encoding/json"
	"fmt"

	"github.com/cB-Sigma/dlms/cosem"
	"github.com/cB-Sigma/iotsec"
)

// memStore is an iotsec.Store in memory (an application keeps it in a
// database, a file or the cloud).
type memStore struct{ b []byte }

func (m *memStore) Load(_ context.Context, v any) error {
	if m.b == nil {
		return iotsec.ErrNotStored
	}
	return json.Unmarshal(m.b, v)
}

func (m *memStore) Save(_ context.Context, v any) error {
	b, err := json.Marshal(v)
	m.b = b
	return err
}

func main() {
	store := &memStore{}
	ctx := context.Background()
	r := &cosem.ICReservation{Store: store, Window: 1000, Name: "M1"}
	ic, _ := r.Reserve(ctx, 1, true)
	fmt.Println("first association starts at", ic, "stored", string(store.b))
	// The process restarts: a new reservation reads the stored one.
	r = &cosem.ICReservation{Store: store, Window: 1000, Name: "M1"}
	ic, _ = r.Reserve(ctx, 1, true)
	fmt.Println("after the restart it starts at", ic)
}
Output:
first association starts at 1 stored {"next":1001}
after the restart it starts at 1001

func (*ICReservation) Reserve

func (r *ICReservation) Reserve(ctx context.Context, ic uint32, first bool) (uint32, error)

Reserve returns ic, raised to the stored reservation when first is set (the first association since a restart), and keeps the reservation ahead of it; the reservation is stored before Reserve returns.

type IdentityCheck

type IdentityCheck struct {
	Expect     string `json:"expect,omitempty"`
	OBIS       string `json:"obis,omitempty"`
	OnMismatch string `json:"onMismatch,omitempty"`
}

IdentityCheck is a meter's identity check: Expect is the value expected, OBIS the Data object read (default 0.0.96.1.0.255, the serial number; 0.0.42.0.0.255 is the logical device name), and OnMismatch refuse (default: the association is not used) or warn.

type InboundConn

type InboundConn struct {
	Conn net.Conn
	// contains filtered or unexported fields
}

InboundConn is a meter-initiated TCP connection. The push listener reads it; WPDUs for an open association go to that association's transport, everything else is handled as a push.

func NewInboundConn

func NewInboundConn(c net.Conn) *InboundConn

NewInboundConn wraps a connection a meter opened; the caller reads it (wrapper.ReadWPDU) and hands each WPDU to Deliver.

func (*InboundConn) Bound

func (ic *InboundConn) Bound() bool

Bound reports whether the caller's identity is proven.

func (*InboundConn) Deliver

func (ic *InboundConn) Deliver(h wrapper.Header, apdu []byte) bool

Deliver hands a WPDU to the association it answers, if one is open.

func (*InboundConn) DropHeld

func (ic *InboundConn) DropHeld()

DropHeld forgets the pushes held for the proof (an impostor's: never mapped, never counted).

func (*InboundConn) HoldUnlessBound

func (ic *InboundConn) HoldUnlessBound(n *Notification) bool

HoldUnlessBound keeps a push while the connection's identity is not proven yet (it is neither mapped nor counted); false when bound.

func (*InboundConn) IsClosed

func (ic *InboundConn) IsClosed() bool

IsClosed reports whether Shut closed the connection.

func (*InboundConn) SetState

func (ic *InboundConn) SetState(from, to int8) bool

SetState moves the connection from one binding state to another.

func (*InboundConn) Shut

func (ic *InboundConn) Shut()

Shut marks the connection closed and closes the socket.

func (*InboundConn) TakeHeldOrBind

func (ic *InboundConn) TakeHeldOrBind() []*Notification

TakeHeldOrBind returns the held pushes, or binds the connection when none are left, so pushes arriving meanwhile keep their order.

func (*InboundConn) Transport

func (ic *InboundConn) Transport(client, server int, timeout time.Duration) gdlms.Transport

Transport is a gosem transport for an association of client with server on the connection; timeout bounds each request (default 10s).

type ItemResult

type ItemResult struct {
	Result int
	Data   *axdr.DlmsData
}

ItemResult is one list item's outcome: a data-access-result (GET, SET) or action-result (ACTION), and the data a GET or ACTION returned.

type KeyWarning

type KeyWarning struct {
	Setting, Message string
}

KeyWarning is an optional key that could not be used: the meter runs without the feature it serves. Setting names the field.

type Keys

type Keys struct {
	Suite        Suite
	Key          []byte // global unicast encryption key
	AuthKey      []byte // authentication key (empty: none)
	BroadcastKey []byte // global broadcast key (optional)
	// SystemTitle is the sender's system title when the APDU does not
	// carry one (service-specific ciphering); general-glo carries its own.
	SystemTitle []byte
	// contains filtered or unexported fields
}

Keys are the global keys to open a protected APDU with.

func ParseKeys

func ParseKeys(suite int, key, authKey string) (*Keys, error)

ParseKeys reads a meter's DLMS keys of a security suite (IEC 62056-5-3:2023 Table 9: suites 0 and 1 AES-128, suite 2 AES-256; the authentication key has the same length, or none).

func (*Keys) SetCompression

func (k *Keys) SetCompression(c *Compression) error

SetCompression applies a meter's V.44 compression setting to general-glo ciphering with these keys (IEC 62056-5-3:2023 5.3.6; compression.go): Open decompresses APDUs with security control bit 7 and, with compressRequests, Seal compresses before ciphering when that makes the APDU smaller. Suites 1 and 2 only (Table 9). A nil or empty setting turns compression off.

type MBusTunnel

type MBusTunnel struct {
	Type byte   // rx_type
	Data []byte // rx_data
}

MBusTunnel is one tunnelled M-Bus frame.

func DecodeMBusTunnel

func DecodeMBusTunnel(d axdr.DlmsData) (MBusTunnel, error)

DecodeMBusTunnel reads the value of a tunnelling Data object.

func (MBusTunnel) IsMBusFrame

func (m MBusTunnel) IsMBusFrame() bool

IsMBusFrame reports rx_types whose data is an M-Bus frame from its CI field on (0 to 31).

func (MBusTunnel) TypeName

func (m MBusTunnel) TypeName() string

TypeName names rx_type.

type Notification

type Notification struct {
	InvokeID uint32
	Time     time.Time // zero when the meter sent none
	Body     axdr.DlmsData
	// SystemTitle is the sender's system title when the APDU was
	// protected, IC its invocation counter, and Authenticated whether its
	// authentication tag was verified with the meter's keys.
	SystemTitle   []byte
	IC            uint32
	Authenticated bool
}

Notification is a decoded data-notification.

func DecodeDataNotification

func DecodeDataNotification(apdu []byte, loc *time.Location) (*Notification, error)

DecodeDataNotification decodes a plain data-notification APDU: long-invoke-id-and-priority (4 bytes), date-time (an octet string, empty or 12 bytes; a leading octet-string tag 0x09 is tolerated), then the notification body as tagged A-XDR data.

func OpenNotification

func OpenNotification(apdu []byte, keys *Keys, loc *time.Location) (*Notification, error)

OpenNotification decodes a data-notification (tag 0Fh) or a general-glo-ciphering APDU (DBh) holding one; dates are read in loc.

func OpenProtectedPush

func OpenProtectedPush(apdu []byte, sources []PushSource, named func(*Notification) int) (int, *Notification, error)

OpenProtectedPush removes general-glo-ciphering from a pushed APDU with the keys of the first source it opens with, in the order given, and decodes the data-notification inside. named returns the index in sources of the meter a notification's device ID element names, or -1.

An encryption-only push (no authentication tag; the IS 15959 Part 2 push association) proves nothing about its sender, and global keys may be shared between meters: it is taken only from a source that accepts such pushes, only from that source's configured system title, and only when it names no other source. Refusals for the protection are *PushSecurityError. The notification's SystemTitle, IC and Authenticated are filled in.

func (*Notification) Values

func (n *Notification) Values(loc *time.Location) []NotificationValue

Values flattens a notification body into its leaf values in order: a structure or array element's path is its parent's path, a dot and its position.

type NotificationValue

type NotificationValue struct {
	Path  string // "1", "2.3": the element's position (1-based) in the body
	Value any    // as Value renders it
}

NotificationValue is one value of a notification body.

type Object

type Object struct {
	Name      string `json:"name"`
	OBIS      string `json:"obis"`
	Class     uint16 `json:"class"`
	Attribute int8   `json:"attribute,omitempty"` // default 2 (value or buffer)
	Unit      string `json:"unit,omitempty"`      // overrides the meter's scaler_unit
	Group     string `json:"-"`
}

Object is one COSEM attribute a client reads.

func Catalogue

func Catalogue(phases int, groups ...string) []Object

Catalogue returns the objects of the given groups of the Part 2 smart meter of the given phases (1 or 3).

func ProfileCatalogue

func ProfileCatalogue(profile string, groups ...string) []Object

ProfileCatalogue returns what a client reads of the given groups of an IS 15959 profile: the objects of each group, and for block load, daily load, billing, events and scalers their profile generic buffers.

type PortClient

type PortClient struct {
	gdlms.Client
	// contains filtered or unexported fields
}

PortClient is a DLMS client (logical name referencing) over HDLC on an already open port: gosem's client over our HDLC layer (package hdlc).

func NewPortClient

func NewPortClient(rwc io.ReadWriteCloser, o PortOptions) (*PortClient, error)

NewPortClient builds a DLMS client over HDLC on rwc, which it owns from now on. Nothing is sent until Connect (the SNRM) and Associate (the AARQ). Close ends the association and the link and closes rwc.

func (*PortClient) Close

func (p *PortClient) Close()

Close releases the association, disconnects the HDLC link and closes the port. It is safe to call more than once.

type PortOptions

type PortOptions struct {
	// ClientAddress is our HDLC client address (default 16, the public
	// client, without authentication; 32 with low-level security).
	ClientAddress int
	// ServerAddress is the logical device, the HDLC upper address
	// (default 1).
	ServerAddress int
	// HDLCAddress is the physical device, the HDLC lower address; it is
	// sent only with a 2 or 4 byte server address.
	HDLCAddress int
	// HDLCAddressSize is the server address length: 1 (default: logical
	// device only, usual on a point-to-point optical port), 2 or 4.
	HDLCAddressSize int
	// Authentication is "none" (default) or "low"; high-level security
	// over a handed-over port is not supported.
	Authentication string
	Password       string
	// Timeout bounds each reply (default 10s).
	Timeout time.Duration
}

PortOptions configures NewPortClient.

func (PortOptions) Check

func (o PortOptions) Check() error

Check reports options NewPortClient would refuse.

type PushCounter

type PushCounter struct {
	Store iotsec.Store
	Name  string // the meter, in errors
	// contains filtered or unexported fields
}

PushCounter keeps the invocation counter of the last protected push accepted from a meter. A push is accepted only after its counter is stored, so a replayed push is refused after a restart too.

An authenticated push (its tag verified with the meter's keys) moves the stored counter ("ic"), and every later push must be past it. An encryption-only push proves nothing about its sender: anyone holding shared global keys could send one with a counter far ahead and so block the meter's own pushes. It therefore never moves "ic"; it is refused if its counter is at or below "ic", or is one of the recent unauthenticated counters kept ("recent", ascending, the newest RecentPushICs), or, once that list is full, at or below its smallest. A counter far ahead only takes one place in the list, so the meter's next push is still taken. The stored value is {"last": n, "ic": n, "recent": [n...]}.

func (*PushCounter) Accept

func (p *PushCounter) Accept(ctx context.Context, ic uint32, authenticated bool) error

Accept checks a push's invocation counter against the stored ones and stores it.

type PushReport

type PushReport struct {
	Time        time.Time
	Row         map[string]any
	Values      []PushValue
	Events      []map[string]any
	LastGasp    bool
	FirstBreath bool
}

PushReport is a notification mapped by its push setup's capture objects. Time is the notification's time, the time of a captured clock, or the time it was mapped. Row holds the push setup's logical name ("pushSetup"), every value by name and the events ("events"); Values are the values in capture order (clock and push setup elements left out); LastGasp and FirstBreath say the event status word reported a power failure or its end.

func MapPush

func MapPush(n *Notification, setup *is15959.PushSetup, sp *is15959.Spec, loc *time.Location, scaler func(obis string) (Scaler, bool)) *PushReport

MapPush maps a notification by its push setup. Register values are scaled with scaler (from an earlier read of the register) and carry its unit; without one they are marked "unscaled". Event status word bits are named by the profile sp.

type PushSecurityError

type PushSecurityError struct {
	Event, Meter string
	SystemTitle  []byte
	Err          error
}

PushSecurityError is a push refused for its protection. Event is a stable name for a security log ("dlms_push_unauthenticated_refused", "dlms_push_system_title_refused"), Meter the source it was checked against (empty when none was) and SystemTitle the sender's, when known.

func (*PushSecurityError) Error

func (e *PushSecurityError) Error() string

Error is the refusal's reason.

func (*PushSecurityError) Unwrap

func (e *PushSecurityError) Unwrap() error

Unwrap returns the reason.

type PushSource

type PushSource struct {
	ID                    string
	Security              *Security
	SystemTitle           []byte
	AcceptUnauthenticated bool
	Location              *time.Location
}

PushSource is a meter a protected push may come from: its keys, the system title it is configured with (nil: not configured), whether it may push encryption-only APDUs, and the time zone of its clock.

type PushValue

type PushValue struct {
	Name    string
	Class   uint16
	OBIS    string
	Value   any
	Unit    string
	Quality string // "unscaled" when a register's scaler is not known yet
}

PushValue is one captured value of a push.

type RawSetTransport

type RawSetTransport struct {
	gdlms.Transport
	// contains filtered or unexported fields
}

RawSetTransport sits between gosem's client and the secure transport. When armed with a value, it rewrites gosem's encoding of that value (g) into ours (r) in the set-request that carries it.

func (*RawSetTransport) Arm

func (t *RawSetTransport) Arm(g, r []byte, strays []int)

Arm makes the transport replace g, gosem's encoding of a value, with r, ours, in the next set-request (strays: the octets gosem adds).

func (*RawSetTransport) Disarm

func (t *RawSetTransport) Disarm()

Disarm stops the replacement.

func (*RawSetTransport) Send

func (t *RawSetTransport) Send(src []byte) error

Send rewrites an armed value, then sends.

type Request

type Request struct {
	Op     string // OpGet (default), OpSet, OpAction
	Set    bool   // OpSet (kept for callers that set it alone)
	Class  uint16
	OBIS   string
	Attr   int8           // the attribute, or the method of an ACTION
	Value  *axdr.DlmsData // SET: the value; ACTION: the parameters (nil: none)
	Access *Access        // GET: selective access
	Invoke byte           // invoke-id-and-priority (low four bits the id)
	// List holds further items of the same operation, sent "with list"
	// after this one (mbuslist.go); their Invoke is not used.
	List []Request
}

Request is one GET, SET or ACTION.

func ParseRequest

func ParseRequest(apdu []byte) (Request, error)

ParseRequest reads a plain get- or set-request-normal without selective access (a test meter's side).

func (Request) Encode

func (r Request) Encode() ([]byte, error)

Encode is the request's first APDU, without request blocks.

func (Request) Start

func (r Request) Start(block int) (*Exchange, []byte, error)

Start begins an exchange; block is the largest raw data of one request block (0: no request blocks).

type Response

type Response struct {
	Set    bool
	Invoke byte
	Data   *axdr.DlmsData // GET: the value
	Result int            // data-access-result (0 success)
}

Response is a decoded get- or set-response-normal.

func ParseResponse

func ParseResponse(apdu []byte) (Response, error)

ParseResponse reads a plain get- or set-response-normal.

type Result

type Result struct {
	Data   *axdr.DlmsData // GET: the value; ACTION: the return parameters
	Result int            // data-access-result (GET, SET) or action-result (ACTION); 0 success
	// Blocks counts the blocks received (GET, ACTION answers) and Sent the
	// blocks sent (SET, ACTION requests).
	Blocks, Sent int
	// Items are the results of a request with list, in order; Result is
	// then the first item's non-zero result, or 0.
	Items []ItemResult
}

Result is what a finished exchange brought.

type RowScalers

type RowScalers struct {
	Location  *time.Location
	Scaler    func(class uint16, obis string) Scaler
	Limiter   func(obis string) Scaler
	EventName func(code int) string
}

RowScalers gives ProfileRow what it needs beyond the entry: the time zone of the meter's clock (deviation unspecified), a register's scaler (Scaler), the scaler of the value a limiter monitors (Limiter, for its thresholds; nil: unscaled) and an event code's name (EventName; nil: is15959.CodeName).

type Scaler

type Scaler struct {
	Exponent int8
	Unit     string
	OK       bool
}

Scaler is a register's scaler_unit: values are multiplied by 10^Exponent and carry Unit; OK is false when it is not known.

func ReadScaler

func ReadScaler(c gdlms.Client, class uint16, obis string) (Scaler, error)

ReadScaler reads the scaler_unit of a register, extended register or demand register; a class without one, or a value not in the expected form, gives a scaler that is not OK and no error.

type SecureTransport

type SecureTransport struct {
	gdlms.Transport
	// contains filtered or unexported fields
}

SecureTransport protects and unprotects APDUs between gosem and the meter, and records what passes 2 and 4 of HLS need.

func (*SecureTransport) BroadcastKey

func (t *SecureTransport) BroadcastKey() []byte

BroadcastKey is the global broadcast key the transport protects broadcasts with (nil: none).

func (*SecureTransport) Challenge

func (t *SecureTransport) Challenge() (meterST, stoc []byte)

Challenge is the system title and the challenge (StoC) of the meter's AARE.

func (*SecureTransport) LastFailure

func (t *SecureTransport) LastFailure() error

LastFailure is why the last incoming APDU was refused (nil: none was).

func (*SecureTransport) Release

func (t *SecureTransport) Release() (ciphered, verified bool)

Release says whether the last release was ciphered and whether the meter's RLRE proved it deciphered it.

func (*SecureTransport) Send

func (t *SecureTransport) Send(src []byte) error

Send protects an outgoing APDU.

func (*SecureTransport) SendBroadcastIC

func (t *SecureTransport) SendBroadcastIC(apdu []byte, ic uint32) error

SendBroadcastIC is sendBroadcast with the invocation counter to use under the broadcast key (0: the association's next counter).

func (*SecureTransport) SetLogger

func (t *SecureTransport) SetLogger(l *log.Logger)

SetLogger passes gosem's logger to the transport below.

func (*SecureTransport) SetReception

func (t *SecureTransport) SetReception(dc gdlms.DataChannel)

SetReception unprotects incoming APDUs before gosem sees them.

func (*SecureTransport) TakeAction

func (t *SecureTransport) TakeAction() []byte

TakeAction returns the last action-response seen, plain, and forgets it (gosem does not return an action's data).

func (*SecureTransport) UsedIC

func (t *SecureTransport) UsedIC() uint32

UsedIC is the next invocation counter this transport would have used, counting the one a ciphered RLRQ will still take: callers record it before the release is sent.

type Security

type Security struct {
	Suite       Suite
	Policy      byte   // 0: APDUs are not protected
	SystemTitle []byte // ours
	Key         []byte // global unicast (block cipher) key
	AuthKey     []byte // authentication key
	Dedicated   bool   // agree a dedicated key per association

	Ciphering  byte   // cipherServiceSpecific, cipherGeneralGlo, cipherGeneralDed or cipherGeneral
	GeneralKey byte   // general-ciphering key-info: genKeyIdentified, genKeyWrapped, genKeyOnePass, genKeyStatic
	MasterKey  []byte // the KEK the meter holds now
	// rootKey is the configured masterKey: it wraps a changed master key
	// in the key store and keys the store's base fingerprint.
	RootKey []byte
	// broadcastKey is the global broadcast key, known once rotated.
	BroadcastKey []byte
	Signing      bool // general-signing on every request and response
	// ECDSA keys: ours and the meter's for signing, ours and the meter's
	// for key agreement.
	SignKey      *ecdsa.PrivateKey
	MeterSignKey *ecdsa.PublicKey
	KAKey        *ecdsa.PrivateKey
	MeterKAKey   *ecdsa.PublicKey
	// tp, when set, signs every request for the meter as a third party
	// inside our own protection (thirdparty.go).
	ThirdParty *ThirdPartyLayer
	// compression, when set, is the meter's V.44 setting (compression.go).
	Compression *CompressionParams
	// Context is the application context the AARQ proposes: ContextAuto
	// (0, the default) names logical name referencing with ciphering
	// whenever our system title is sent (protected APDUs or mechanism 5
	// and above) and without it otherwise; ContextLN and
	// ContextLNCiphering name one or the other whatever is sent.
	Context byte
}

Security is one meter's application-layer security settings.

type SecurityConfig

type SecurityConfig struct {
	Name              string
	Authentication    string
	Password          string
	Security          string
	Suite             int
	SystemTitle       string
	BlockCipherKey    string
	AuthenticationKey string
	DedicatedKey      bool
	SigningKey        string
	MeterSigningKey   string
	Ciphering         string
	GeneralKey        string
	MasterKey         string
	BroadcastKey      string
	Signing           bool
	KeyAgreementKey   string
	MeterKAKey        string
	ThirdParty        *ThirdParty
	Compression       *Compression
	// ApplicationContext is "auto" (or empty: the ciphering context whenever
	// our system title is sent, as with mechanism 5 and protected APDUs),
	// "ln" (logical name referencing without ciphering: HLS-GMAC with
	// unprotected APDUs, as many meters and Gurux expect) or "ln-ciphering".
	ApplicationContext string
}

SecurityConfig is a meter's authentication and APDU protection as text.

Authentication     none, low, hls-aes (hls), hls-md5, hls-sha1, hls-gmac, hls-sha256, hls-ecdsa
Password           the low-level password, or the HLS secret (aes, md5, sha1, sha256)
Security           none, authenticated, encrypted or authenticated-encrypted
Suite              security suite 0, 1 or 2 (hls-ecdsa needs 1 or 2)
SystemTitle        ours, 8 bytes hex (default 53474D0000000001)
BlockCipherKey     the global unicast key, hex (16 bytes; 32 in suite 2)
AuthenticationKey  the authentication key, hex
DedicatedKey       agree a fresh dedicated key per association
SigningKey         our EC private key (PEM text or a file path): hls-ecdsa, signing, one-pass agreement
MeterSigningKey    the meter's signing public key or certificate
Ciphering          service-specific (default), general-glo, general-ded or general
GeneralKey         general: identified (default), wrapped, agreed-one-pass or agreed-static
MasterKey          the KEK, hex: wrapped keys and key_transfer
BroadcastKey       the global broadcast key, hex
Signing            general-signing on every request and response (suite 1 or 2)
KeyAgreementKey    our static key agreement key (PEM or path)
MeterKAKey         the meter's key agreement public key or certificate
ThirdParty         requests protected for a third party inside our layer
Compression        V.44 (suite 1 or 2, general ciphering)
ApplicationContext auto (default), ln or ln-ciphering: the context the AARQ proposes

Name names the meter in errors.

func (*SecurityConfig) Build

func (c *SecurityConfig) Build() (*HLS, []KeyWarning, error)

Build checks and decodes the settings, filling in their defaults (Security "none", SystemTitle). A key a configured feature needs (hls-ecdsa, signing, an agreed general key) must be usable; any other key that cannot be read or parsed is left out with a KeyWarning.

type SecuritySetup

type SecuritySetup struct {
	Client gdlms.Client
	Secure *SecureTransport
	OBIS   string
}

SecuritySetup is the security setup object (class 64, version 1) of an open association: Client and Secure are the association's, OBIS the object's logical name (0.0.43.0.e.255).

func (SecuritySetup) Action

func (s SecuritySetup) Action(method int8, param *axdr.DlmsData) (*axdr.DlmsData, error)

Action invokes a security setup method and returns its return data (nil when it has none).

func (SecuritySetup) Activate

func (s SecuritySetup) Activate(bits byte) error

Activate raises the meter's security policy.

func (SecuritySetup) AgreeKeys

func (s SecuritySetup) AgreeKeys(sec *Security, ids []byte) (map[byte][]byte, error)

AgreeKeys runs key_agreement for the given key IDs with the signing keys and system title of sec and returns the agreed keys.

func (SecuritySetup) CertificateRequest

func (s SecuritySetup) CertificateRequest(kind byte) (*x509.CertificateRequest, error)

CertificateRequest asks the meter for a PKCS #10 request for one of its key pairs and checks its signature.

func (SecuritySetup) Certificates

func (s SecuritySetup) Certificates() ([]CertInfo, error)

Certificates reads the certificates attribute (6).

func (SecuritySetup) ExportCertificate

func (s SecuritySetup) ExportCertificate(id CertID) (*x509.Certificate, error)

ExportCertificate reads a certificate the meter holds.

func (SecuritySetup) GenerateKeyPair

func (s SecuritySetup) GenerateKeyPair(kind byte) error

GenerateKeyPair asks the meter to generate a key pair (0 signing, 1 key agreement, 2 TLS).

func (SecuritySetup) ImportCertificate

func (s SecuritySetup) ImportCertificate(c *x509.Certificate) error

ImportCertificate gives the meter a certificate.

func (SecuritySetup) RemoveCertificate

func (s SecuritySetup) RemoveCertificate(id CertID) error

RemoveCertificate removes a certificate from the meter.

func (SecuritySetup) TransferKeys

func (s SecuritySetup) TransferKeys(masterKey []byte, keys map[byte][]byte) error

TransferKeys sends new keys (by key_id) wrapped with the master key.

type SerialConfig

type SerialConfig struct {
	Device   string
	Baud     int
	DataBits int
	Parity   string
	StopBits int
}

SerialConfig is one opening of a port.

type SerialSettings

type SerialSettings struct {
	Baud          int    `json:"baud,omitempty"`
	DataBits      int    `json:"dataBits,omitempty"`
	Parity        string `json:"parity,omitempty"`
	StopBits      int    `json:"stopBits,omitempty"`
	Optical       bool   `json:"optical,omitempty"`
	SignOnAddress string `json:"signOnAddress,omitempty"`
}

SerialSettings are the line settings of a meter on a local serial port.

func (*SerialSettings) Defaults

func (s *SerialSettings) Defaults() error

Defaults fills in the defaults (9600 baud, 8N1) and checks the settings.

type Suite

type Suite byte

Suite is a DLMS security suite.

func (Suite) Curve

func (s Suite) Curve() (elliptic.Curve, error)

Curve is the suite's elliptic curve (suites 1 and 2 only).

func (Suite) KeyLen

func (s Suite) KeyLen() int

KeyLen is the suite's AES key length.

type ThirdParty

type ThirdParty struct {
	// SystemTitle is the TP's system title, 16 hex digits.
	SystemTitle string `json:"systemTitle"`
	// SigningKey is the TP's ECDSA private key (PEM text or a file path)
	// on the suite's curve; the meter holds its certificate. It signs the
	// requests (unless Sign is false) and the ephemeral key of one-pass
	// agreement.
	SigningKey string `json:"signingKey,omitempty"`
	// Sign applies the TP's general-signing layer (default true).
	Sign *bool `json:"sign,omitempty"`
	// Security is the TP's general-ciphering layer: none (default),
	// authenticated, encrypted or authenticated-encrypted.
	Security string `json:"security,omitempty"`
	// GeneralKey is the key agreement of that layer: agreed-one-pass
	// (default) or agreed-static.
	GeneralKey string `json:"generalKey,omitempty"`
	// KeyAgreementKey is the TP's static key agreement private key (PEM
	// or a file path): needed for agreed-static, and to open the meter's
	// one-pass ciphered answers.
	KeyAgreementKey string `json:"keyAgreementKey,omitempty"`
	// AuthenticationKey is the global authentication key the TP uses
	// (hex), when its layer is authenticated.
	AuthenticationKey string `json:"authenticationKey,omitempty"`
	// SignedResponses asks for the meter's answers to be signed for the
	// TP (default: when the TP signs); CipheredResponses asks for them to
	// be ciphered for the TP (default: when the TP ciphers). With neither,
	// an unprotected layer for the TP is accepted (annex J.3).
	SignedResponses   *bool `json:"signedResponses,omitempty"`
	CipheredResponses *bool `json:"cipheredResponses,omitempty"`
}

ThirdParty is the "thirdParty" setting of a meter: the identity on whose behalf requests are protected.

func (*ThirdParty) Build

func (tp *ThirdParty) Build(sec *Security) (*ThirdPartyLayer, error)

Build checks the setting against the rest of the security settings and returns the TP layers.

type ThirdPartyLayer

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

ThirdPartyLayer is a validated ThirdParty.

type TunnelRecord

type TunnelRecord struct {
	Name    string
	Unit    string
	Value   any
	Quality string
	Labels  []string
}

TunnelRecord is one data record of a tunnelled M-Bus frame, as the M-Bus decoder names it.

Jump to

Keyboard shortcuts

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