Documentation
¶
Overview ¶
Package lpwan carries DLMS/COSEM over low-power wide-area networks: NB-IoT (and LTE-M) meters that call in over UDP from behind carrier NAT and sleep between calls (udp.go, queue.go, wake.go), and LoRaWAN meters reached through a network server with SCHC compression and fragmentation (RFC 8724, RFC 9011; bridge.go, ns.go, regional.go). The network server is reached through the NetworkServer interface: MemNS in memory for tests, or an application's MQTT integration.
Both present each meter as a net.Conn carrying IEC 62056-4-7 wrapper frames, so a client runs its inbound-meter logic (cosem.InboundConn: identity proof, pushes, associations told apart by wPort) over them unchanged.
Index ¶
- Constants
- Variables
- type Bridge
- type BridgeSettings
- type Device
- type DeviceConn
- func (c *DeviceConn) Close() error
- func (c *DeviceConn) DevEUI() string
- func (c *DeviceConn) LocalAddr() net.Addr
- func (c *DeviceConn) Read(p []byte) (int, error)
- func (c *DeviceConn) RemoteAddr() net.Addr
- func (c *DeviceConn) SetDeadline(t time.Time) error
- func (c *DeviceConn) SetReadDeadline(t time.Time) error
- func (c *DeviceConn) SetWriteDeadline(time.Time) error
- func (c *DeviceConn) Write(p []byte) (int, error)
- type DeviceOptions
- type Downlink
- type Duration
- type IPv6Settings
- type Item
- type LinkInfo
- type MemNS
- func (n *MemNS) Attach(devEUI, class string) <-chan Downlink
- func (n *MemNS) Queued(devEUI string) int
- func (n *MemNS) Ready() <-chan struct{}
- func (n *MemNS) Run(ctx context.Context, deliver func(Uplink)) error
- func (n *MemNS) Send(_ context.Context, dl Downlink) error
- func (n *MemNS) Uplink(devEUI string, fport int, data []byte)
- type MeterLoRaWAN
- type NetworkServer
- type PeerConn
- func (p *PeerConn) Close() error
- func (p *PeerConn) LocalAddr() net.Addr
- func (p *PeerConn) Read(b []byte) (int, error)
- func (p *PeerConn) RemoteAddr() net.Addr
- func (p *PeerConn) ReplyOpen() bool
- func (p *PeerConn) ReplyUntil() time.Time
- func (p *PeerConn) SetDeadline(t time.Time) error
- func (p *PeerConn) SetReadDeadline(t time.Time) error
- func (p *PeerConn) SetWriteDeadline(time.Time) error
- func (p *PeerConn) WokeAt() time.Time
- func (p *PeerConn) Write(b []byte) (int, error)
- type Queue
- func (q *Queue) Cancel(meter, id string) bool
- func (q *Queue) Due(meter string) []Item
- func (q *Queue) Enqueue(meter, id string, cmd json.RawMessage, ttl time.Duration) (Item, error)
- func (q *Queue) Expire() []Item
- func (q *Queue) Finish(meter, id string, err error, permanent bool) (Item, bool)
- func (q *Queue) List(meter string) []Item
- func (q *Queue) Restore(items []Item)
- func (q *Queue) Snapshot() []Item
- func (q *Queue) Waiting(meter string) int
- type QueueOptions
- type Region
- type Sleep
- type UDPListener
- type UDPOptions
- type Uplink
- type WakeState
- type Wakes
- type Warning
- type WarningKind
Examples ¶
Constants ¶
const ( Queued = "queued" // waiting for the meter to call Sent = "sent" // running on the meter's current call Done = "done" // the meter carried it out Failed = "failed" // the meter refused it, or every attempt failed Expired = "expired" // the meter did not call before it expired )
Command states in the queue of a meter that sleeps.
const PHYOverhead = 13
PHYOverhead is the LoRaWAN bytes around an FRMPayload without FOpts: MHDR, DevAddr, FCtrl, FCnt, FPort and MIC.
Variables ¶
var ErrQueueFull = errors.New("the meter's command queue is full")
ErrQueueFull is returned when a meter's queue holds its maximum of commands waiting.
var ErrReplyWindowClosed = errors.New("the meter's reply window has closed (it is asleep or its NAT binding expired); the command waits for its next call")
ErrReplyWindowClosed is returned by a write to an NB-IoT meter after its reply window: the carrier NAT binding (or the meter's receive window before it sleeps again) is taken to have closed.
Functions ¶
This section is empty.
Types ¶
type Bridge ¶
type Bridge struct {
// OnWarning reports something odd about a device (an application
// passes it on to its warnings).
OnWarning func(Warning)
// OnUplink, when set, is told of every uplink from a known device.
OnUplink func(devEUI string)
// contains filtered or unexported fields
}
Bridge runs SCHC between the network server and the meters, one Device (and DeviceConn) per DevEUI.
func NewBridge ¶
func NewBridge(s BridgeSettings, ns NetworkServer, log *slog.Logger, now func() time.Time) (*Bridge, error)
NewBridge builds a bridge; Check must have run on s.
func (*Bridge) Add ¶
func (b *Bridge) Add(o DeviceOptions) (*DeviceConn, error)
Add registers a meter and returns its conn.
func (*Bridge) HandleUplink ¶
HandleUplink takes one uplink from the network server.
func (*Bridge) Reopen ¶
func (b *Bridge) Reopen(devEUI string) *DeviceConn
Reopen gives a device a new conn when its old one was closed (the DLMS layer closes a conn after a failed write).
type BridgeSettings ¶
type BridgeSettings struct {
// Region names the regional parameters (default IN865): the largest
// payload per data rate and the duty cycle (regional.go).
Region string `json:"region,omitempty"`
// Class is the meters' LoRaWAN class: A (default), B or C.
Class string `json:"class,omitempty"`
PingSlot Duration `json:"pingSlot,omitempty"` // class B ping slot period (default 32 s)
// FPorts of the SCHC rules (RFC 9011 5.2: 20, 21 and 22 by default).
FPortUp int `json:"fPortUp,omitempty"`
FPortDown int `json:"fPortDown,omitempty"`
FPortNoCompression int `json:"fPortNoCompression,omitempty"`
// Header is what the SCHC Packet carries: "wrapper" (default: the IEC
// 62056-4-7 wrapper frame, its header compressed to a few bits),
// "none" (the bare APDU: the wrapper is dropped on the air and made up
// again here) or "ipv6/udp/wrapper" (the wrapper in UDP over IPv6,
// compressed as RFC 8724 clause 10 describes).
Header string `json:"header,omitempty"`
// IPv6 addresses and ports for header ipv6/udp/wrapper.
IPv6 *IPv6Settings `json:"ipv6,omitempty"`
// Rules replaces the built-in SCHC rules (package schc's JSON). The
// fragmentation rules on fPortUp and fPortDown and the no-compression
// rule are added when missing.
Rules json.RawMessage `json:"rules,omitempty"`
// DownlinkFragmentation is ack-always (default, RFC 9011 unicast) or
// no-ack.
DownlinkFragmentation string `json:"downlinkFragmentation,omitempty"`
// TileBytes is the uplink ACK-on-Error tile size (default 10, RFC 9011
// 5.6.2).
TileBytes int `json:"tileBytes,omitempty"`
// AckEveryWindow: acknowledge every uplink window (default true, RFC
// 9011's advice for battery meters).
AckEveryWindow *bool `json:"ackEveryWindow,omitempty"`
// InactivityTimer overrides the uplink reassembly inactivity timer
// (default 12 h, RFC 9011 5.6.2).
InactivityTimer Duration `json:"inactivityTimer,omitempty"`
// RetransmissionTimer overrides the downlink retransmission timer
// (default by class, RFC 9011 5.6.3.5: class A 4 h, B three ping
// slots, C 30 s).
RetransmissionTimer Duration `json:"retransmissionTimer,omitempty"`
// MaxPayload overrides the downlink payload limit in bytes (default:
// from the region and data rate); PayloadReserve keeps bytes free for
// MAC commands the network server adds (FOpts).
MaxPayload int `json:"maxPayload,omitempty"`
PayloadReserve int `json:"payloadReserve,omitempty"`
// DownlinkDataRate fixes the data rate assumed for downlinks (default:
// the lower of RX1 at the last uplink's rate and RX2).
DownlinkDataRate *int `json:"downlinkDataRate,omitempty"`
// DutyCycle paces our own downlinks per meter (0 to 1; default the
// region's: none in IN865, 1% in EU868). The network server still
// enforces the gateways' limits.
DutyCycle *float64 `json:"dutyCycle,omitempty"`
// Confirmed sends downlinks as LoRaWAN confirmed frames (SCHC does not
// need them, RFC 9011 4.3; default false).
Confirmed bool `json:"confirmed,omitempty"`
// RequestTimeout is each DLMS request's time-out over LoRaWAN
// (default 10 min for class A, whose downlinks wait for an uplink;
// 2 min for B and C).
RequestTimeout Duration `json:"requestTimeout,omitempty"`
}
BridgeSettings are a bridge's LoRaWAN settings. The DLMS UA's LoRaWAN communication profile is not available to us, so every choice it would fix (FPorts, SCHC rules, what header is compressed, the fragmentation modes and tile size) is a setting here; the defaults follow RFC 9011 and are reported as unverified (ProfileWarning).
func (*BridgeSettings) Check ¶
func (s *BridgeSettings) Check() error
Check fills in defaults and checks the settings.
func (*BridgeSettings) ProfileWarning ¶
func (s *BridgeSettings) ProfileWarning() (msg, detail string)
ProfileWarning names the settings that stand in for the DLMS UA LoRaWAN profile, which we could not read: they must match the meters'.
type Device ¶
type Device struct {
// contains filtered or unexported fields
}
Device is one meter's SCHC state.
type DeviceConn ¶
type DeviceConn struct {
// contains filtered or unexported fields
}
DeviceConn is a meter's LoRaWAN link as a stream of wrapper frames.
func (*DeviceConn) LocalAddr ¶
func (c *DeviceConn) LocalAddr() net.Addr
LocalAddr and RemoteAddr name the LoRaWAN ends.
func (*DeviceConn) Read ¶
func (c *DeviceConn) Read(p []byte) (int, error)
Read returns bytes of the wrapper frames received.
func (*DeviceConn) RemoteAddr ¶
func (c *DeviceConn) RemoteAddr() net.Addr
RemoteAddr names the device by its DevEUI.
func (*DeviceConn) SetDeadline ¶
func (c *DeviceConn) SetDeadline(t time.Time) error
SetDeadline sets the read deadline.
func (*DeviceConn) SetReadDeadline ¶
func (c *DeviceConn) SetReadDeadline(t time.Time) error
SetReadDeadline sets the read deadline.
func (*DeviceConn) SetWriteDeadline ¶
func (c *DeviceConn) SetWriteDeadline(time.Time) error
SetWriteDeadline does nothing: writes only queue.
type DeviceOptions ¶
type DeviceOptions struct {
Meter MeterLoRaWAN
// ServerWPort is the meter's wPort (default 1); PushWPort the wPort an
// unsolicited APDU is addressed to when the header is none (default
// 64).
ServerWPort uint16
PushWPort uint16
}
DeviceOptions describe one meter on the bridge.
type Duration ¶
Duration is a JSON duration ("20s" or seconds).
func (Duration) MarshalJSON ¶
MarshalJSON writes "20s".
func (*Duration) UnmarshalJSON ¶
UnmarshalJSON reads "20s" or a number of seconds.
type IPv6Settings ¶
type IPv6Settings struct {
DevPrefix string `json:"devPrefix,omitempty"` // default fe80::/64
AppPrefix string `json:"appPrefix,omitempty"` // default fe80::/64
AppIID string `json:"appIid,omitempty"` // default ::1
Port int `json:"port,omitempty"` // UDP port both ends (default 4059, IEC 62056-9-7)
HopLimit int `json:"hopLimit,omitempty"` // default 255
}
IPv6Settings are the addresses a header ipv6/udp/wrapper packet uses.
type Item ¶
type Item struct {
ID string `json:"id"`
Meter string `json:"meter"`
Command json.RawMessage `json:"command"`
Status string `json:"status"`
Queued time.Time `json:"queuedAt"`
Expires time.Time `json:"expiresAt"`
Updated time.Time `json:"updatedAt"`
Attempts int `json:"attempts"`
Error string `json:"error,omitempty"`
}
Item is one queued command.
type LinkInfo ¶
type LinkInfo struct {
DevEUI string `json:"devEui"`
LastUplink time.Time `json:"lastUplink,omitempty"`
FCnt *int64 `json:"fCnt,omitempty"`
DR *int `json:"dr,omitempty"`
RSSI *float64 `json:"rssi,omitempty"`
SNR *float64 `json:"snr,omitempty"`
Frequency int64 `json:"frequency,omitempty"`
Uplinks int `json:"uplinks"`
Downlinks int `json:"downlinks"`
Waiting int `json:"waitingFrames"` // downlink frames waiting for a receive window
MaxPayload int `json:"maxPayload"` // bytes now allowed per downlink
Reassembling bool `json:"reassembling"`
Fragmenting bool `json:"fragmenting"`
LastError string `json:"lastError,omitempty"`
}
LinkInfo is what the console shows of a meter's LoRaWAN link.
type MemNS ¶
type MemNS struct {
// DR, RSSI and SNR are reported with every uplink.
DR int
RSSI, SNR float64
DropDown func(n int, d Downlink) bool // lose a downlink (tests)
DropUp func(n int, u Uplink) bool // lose an uplink (tests)
// contains filtered or unexported fields
}
MemNS is an in-memory LoRaWAN network server for tests and the meter simulator: devices send uplinks with Uplink; downlinks queued with Send reach a class A device only in the receive window after its next uplink (one per uplink), a class C device at once. It does no radio, MAC commands, ADR or security.
func (*MemNS) Ready ¶
func (n *MemNS) Ready() <-chan struct{}
Ready is closed once the bridge is listening.
type MeterLoRaWAN ¶
type MeterLoRaWAN struct {
DevEUI string `json:"devEui"`
// AppSKey (hex, secret) lets the Dev IPv6 IID be computed as RFC 9011
// 5.3 says; DevIID (hex, 8 bytes) gives it directly. Only for header
// ipv6/udp/wrapper.
AppSKey string `json:"appSKey,omitempty"`
DevIID string `json:"devIid,omitempty"`
Class string `json:"class,omitempty"` // overrides the class of the bridge (lorawan.class)
}
MeterLoRaWAN is a meter's LoRaWAN identity.
func (*MeterLoRaWAN) Check ¶
func (m *MeterLoRaWAN) Check() error
Check checks a meter's LoRaWAN identity.
type NetworkServer ¶
type NetworkServer interface {
// Run delivers uplinks until ctx ends.
Run(ctx context.Context, deliver func(Uplink)) error
// Send queues a downlink; the network server sends it in the device's
// next receive window (class A) or ping slot (B), or at once (C).
Send(ctx context.Context, d Downlink) error
}
NetworkServer is a LoRaWAN network server's application integration.
type PeerConn ¶
type PeerConn struct {
// contains filtered or unexported fields
}
PeerConn is one meter's datagrams as a byte stream of whole wrapper frames; each Write goes out as one datagram.
func (*PeerConn) RemoteAddr ¶
RemoteAddr is the meter's address as the NAT shows it.
func (*PeerConn) ReplyUntil ¶
ReplyUntil is when the reply window closes, unless the meter sends again.
func (*PeerConn) SetDeadline ¶
SetDeadline sets the read deadline (writes do not block).
func (*PeerConn) SetReadDeadline ¶
SetReadDeadline sets the read deadline.
func (*PeerConn) SetWriteDeadline ¶
SetWriteDeadline does nothing: a datagram write does not block.
type Queue ¶
type Queue struct {
// contains filtered or unexported fields
}
Queue holds commands for meters that are asleep, to run when each next calls. It is safe for concurrent use; Snapshot and Restore let the caller keep it across restarts.
func (*Queue) Due ¶
Due returns the meter's commands to run now, oldest first, marking them sent (expired ones are marked expired first).
func (*Queue) Finish ¶
Finish records a sent command's outcome: done, or on error queued again for the next call until its attempts are used up (then failed). A permanent error (the meter refused it) fails at once.
type QueueOptions ¶
type QueueOptions struct {
Max int // commands waiting per meter (default 16)
TTL time.Duration // how long a command waits (default 72 h)
Attempts int // calls a command is tried on before it fails (default 3)
Keep time.Duration // how long finished commands stay listed (default 7 days)
Now func() time.Time
}
QueueOptions bound a queue.
type Region ¶
type Region struct {
Name string
MaxPayload []int // by DR; 0 is not a LoRa data rate here
SF []int
BW []int // kHz
RX2DR int
DutyCycle float64 // 0: none imposed
}
Regional LoRaWAN limits: the largest FRMPayload (N, without FOpts) per data rate, each data rate's spreading factor and bandwidth, the RX2 data rate and the duty cycle a head end should pace its own downlinks by. The figures are our reading of the LoRa Alliance Regional Parameters (RP002-1.0.x, dwell time off); they are not checked against a network server here, and the maxPayload and dutyCycle settings override them.
func LookupRegion ¶
LookupRegion finds a region by name ("IN865", "in865-867"…).
Example ¶
The largest LoRaWAN payload at a data rate in India's band.
package main
import (
"fmt"
"github.com/cB-Sigma/dlms/lpwan"
)
func main() {
r, err := lpwan.LookupRegion("IN865")
if err != nil {
panic(err)
}
fmt.Println(r.Name, r.Payload(0), r.Payload(5))
}
Output: IN865 51 242
type Sleep ¶
type Sleep struct {
// ActiveTime is how long the meter listens after it last sent
// (T3324; default 20 s). Requests are only sent within it.
ActiveTime Duration `json:"activeTime,omitempty"`
// Period is when the meter is expected to call again (its push
// interval or T3412; default 24 h). A meter silent for twice this is
// shown as overdue.
Period Duration `json:"period,omitempty"`
// EDRXCycle and PagingWindow: with eDRX the meter can be paged once
// per cycle for the window; requests are then held for the next
// window rather than failed. 0: no eDRX.
EDRXCycle Duration `json:"edrxCycle,omitempty"`
PagingWindow Duration `json:"pagingWindow,omitempty"`
// RequestTimeout is each DLMS request's time-out on this network
// (default 30 s: NB-IoT round trips run to seconds, longer in
// coverage extension).
RequestTimeout Duration `json:"requestTimeout,omitempty"`
// Retries is how many calls a queued command is tried on (default 3).
Retries int `json:"retries,omitempty"`
// QueueMax and QueueTTL bound the meter's command queue (default 16
// commands, 72 h).
QueueMax int `json:"queueMax,omitempty"`
QueueTTL Duration `json:"queueTtl,omitempty"`
}
Sleep describes how an NB-IoT (or LTE-M) meter sleeps: 3GPP power saving mode (PSM) and extended discontinuous reception (eDRX) as the network granted them. We cannot reach a meter in PSM; after each call it listens for about its active time (T3324), then sleeps until its next call or periodic update (T3412). With eDRX it listens once per cycle for its paging time window. These are per-meter settings; the values come from the meter or the operator, as the network grants them.
type UDPListener ¶
type UDPListener struct {
// contains filtered or unexported fields
}
UDPListener accepts one net.Conn per meter source address on a UDP socket: the first datagram from an address makes a new conn, which Accept returns; later datagrams from it go to that conn, and writes go back to that address while its reply window is open. It is a net.Listener, so meters that call over UDP are served like those that call over TCP.
func ListenUDP ¶
func ListenUDP(addr string, opt UDPOptions) (*UDPListener, error)
ListenUDP listens on addr ("0.0.0.0:4059").
func ServeUDP ¶
func ServeUDP(pc net.PacketConn, opt UDPOptions) *UDPListener
ServeUDP serves an existing packet socket.
func (*UDPListener) Accept ¶
func (l *UDPListener) Accept() (net.Conn, error)
Accept waits for a new meter.
func (*UDPListener) Close ¶
func (l *UDPListener) Close() error
Close stops the listener and every peer.
type UDPOptions ¶
type UDPOptions struct {
// ReplyWindow is how long after a meter's last datagram we may still
// send to its source address and port (default 30 s). Carrier NAT
// bindings for UDP commonly last 30 s to a few minutes; the meter's
// PSM active time may be shorter.
ReplyWindow time.Duration
// MaxPeers bounds the meters talking at once (default 10000); the
// oldest idle peer is dropped for a new one.
MaxPeers int
// OnDiscard is told about datagrams that are not whole wrapper frames
// (IEC 62056-4-7 5.2.1: one WPDU fills its datagram).
OnDiscard func(from net.Addr, err error)
// Now is the clock (tests).
Now func() time.Time
}
UDPOptions configure ListenUDP.
type Uplink ¶
type Uplink struct {
DevEUI string
Application string
FPort int // 0: a frame without FPort (MAC only, or empty)
Data []byte
FCnt *int64
DR *int
RSSI, SNR *float64 // the best gateway's
Frequency int64
Time time.Time
Confirmed bool
}
Uplink is a LoRaWAN uplink from the network server.
type WakeState ¶
type WakeState struct {
LastWake time.Time `json:"lastWake,omitempty"` // first datagram of its last call
LastSeen time.Time `json:"lastSeen,omitempty"` // its last datagram
ListenUntil time.Time `json:"listenUntil,omitempty"` // when it is expected to sleep again
NextCall time.Time `json:"nextCall,omitempty"` // when it is expected to call again
Calls int `json:"calls"`
Awake bool `json:"awake"`
Overdue bool `json:"overdue"`
}
WakeState is what we know of one meter's sleep.
type Wakes ¶
type Wakes struct {
// contains filtered or unexported fields
}
Wakes tracks meters' calls.
func (*Wakes) Heard ¶
Heard records a datagram from a meter; newCall is true for the first of a call.
func (*Wakes) NextWindow ¶
NextWindow is the start of the meter's next eDRX paging window after now, or zero without eDRX: reckoned from its last call, which the network aligns cycles to only approximately, so treat it as a hint.
type Warning ¶
type Warning struct {
Kind WarningKind
Subject, Setting, Msg, Detail string
}
Warning is something odd about a device, for an application's warnings.
type WarningKind ¶
type WarningKind int
WarningKind tells warnings apart; an application names them.
const ( WarnSCHC WarningKind = iota // a SCHC transfer failed WarnUnknownDevice // an uplink from a DevEUI no meter has WarnDownlinkFailed // the network server did not take a downlink WarnBacklog // packets arrived faster than read )
Warning kinds.