Documentation
¶
Overview ¶
Package schc is Static Context Header Compression and fragmentation (RFC 8724) with the LoRaWAN profile of RFC 9011.
Compression (compress.go): rules of field descriptors (FID, FL, FP, DI, TV, MO, CDA) matched as clause 7.2 says; the matching operators equal, ignore, MSB(x) and match-mapping; the actions not-sent, value-sent, mapping-sent, LSB, compute, DevIID and AppIID; variable-length residues with their 4/12/28-bit sizes. Fields are labelled by our parsers for IPv6 and UDP (clause 10, addresses and ports by Dev/App role) and the IEC 62056-4-7 wrapper header (fields.go); compute rebuilds the IPv6 and UDP lengths, the UDP checksum and the wrapper length, and a compute or DevIID field is elided only when the other end rebuilds the same value.
Fragmentation (frag.go, sender.go, receiver.go): the message formats of clause 8.3 with bitmap compression, the CRC32 RCS of 8.2.3, and the sender and receiver of No-ACK, ACK-Always and ACK-on-Error (8.4) as clock-driven state machines without I/O.
LoRaWAN (lorawan.go): RuleID in the FPort, the uplink ACK-on-Error and downlink ACK-Always rules with their parameters and class timers, the multicast No-ACK rule, and the AES-CMAC IID of RFC 9011 5.3.
Rules are our own JSON (rule.go). RFC 9363's YANG data model is not implemented and is not claimed.
Index ¶
- Constants
- Variables
- func LoRaWANIID(appSKey, devEUI []byte) ([]byte, error)
- type Bits
- func (x *Bits) Append(y Bits)
- func (x *Bits) AppendBit(v uint8)
- func (x *Bits) AppendBytes(b []byte)
- func (x *Bits) AppendUint(v uint64, n int)
- func (x Bits) Bit(i int) uint8
- func (x Bits) Bytes() []byte
- func (x Bits) Clone() Bits
- func (x Bits) Equal(y Bits) bool
- func (x Bits) Len() int
- func (x *Bits) Pad(word int) int
- func (x Bits) Slice(from, to int) Bits
- func (x Bits) String() string
- func (x Bits) UintAt(from, n int) uint64
- type Context
- type Direction
- type Duration
- type Field
- type FieldDescriptor
- type FragMsg
- type FragParams
- type LoRaWANFrame
- type MsgKind
- type Packet
- type Receiver
- type Rule
- type RuleSet
- func (rs *RuleSet) ByID(id uint32) *Rule
- func (rs *RuleSet) Compile() error
- func (rs *RuleSet) Compress(st Stack, raw []byte, dir Direction, ctx Context) (Bits, *Rule, error)
- func (rs *RuleSet) CompressPacket(p Packet, dir Direction, ctx Context) (Bits, *Rule, error)
- func (rs *RuleSet) Decompress(st Stack, msg Bits, dir Direction, ctx Context) ([]byte, *Rule, error)
- func (rs *RuleSet) DecompressPacket(msg Bits, dir Direction, ctx Context) (Packet, *Rule, error)
- func (rs *RuleSet) Fragmentation(dir Direction) []*Rule
- type Sender
- type Stack
Examples ¶
Constants ¶
const ( FIPv6Version = "ipv6.version" FIPv6TrafficClass = "ipv6.trafficClass" FIPv6FlowLabel = "ipv6.flowLabel" FIPv6PayloadLength = "ipv6.payloadLength" FIPv6NextHeader = "ipv6.nextHeader" FIPv6HopLimit = "ipv6.hopLimit" FIPv6DevPrefix = "ipv6.devPrefix" FIPv6DevIID = "ipv6.devIID" FIPv6AppPrefix = "ipv6.appPrefix" FIPv6AppIID = "ipv6.appIID" FUDPDevPort = "udp.devPort" FUDPAppPort = "udp.appPort" FUDPLength = "udp.length" FUDPChecksum = "udp.checksum" FWrapperVersion = "wrapper.version" FWrapperDevWPort = "wrapper.devWPort" FWrapperAppWPort = "wrapper.appWPort" FWrapperLength = "wrapper.length" )
Field IDs our parsers label. IPv6 and UDP follow RFC 8724 clause 10, naming addresses and ports by role (Dev, App) rather than position (10.7, 10.9). The wrapper fields are the IEC 62056-4-7 wrapper header, also named by role: the meter's wPort is devWPort.
const ( // FPortUp is the recommended uplink fragmentation RuleID (5.2). FPortUp = 20 // FPortDown is the recommended downlink fragmentation RuleID. FPortDown = 21 // FPortNoCompression is the recommended RuleID for a packet no rule // compresses. FPortNoCompression = 22 )
SCHC over LoRaWAN (RFC 9011). The RuleID is 8 bits carried in the LoRaWAN FPort; the SCHC Message is FPort then FRMPayload (5.1, 5.2). The L2 Word is a byte and padding is zeros (5.4, 5.6).
const ( ClassA = "A" ClassB = "B" ClassC = "C" )
LoRaWAN device classes (RFC 9011 4.1).
const ( MOEqual = "equal" MOIgnore = "ignore" MOMSB = "msb" MOMatchMapping = "match-mapping" )
Matching operators (RFC 8724 7.3).
const ( CDANotSent = "not-sent" CDAValueSent = "value-sent" CDAMappingSent = "mapping-sent" CDALSB = "lsb" CDACompute = "compute" CDADevIID = "deviid" CDAAppIID = "appiid" )
Compression/decompression actions (RFC 8724 7.4).
const ( KindCompression = "compression" KindNoCompression = "no-compression" KindFragmentation = "fragmentation" )
Rule kinds.
const ( NoAck = "no-ack" AckAlways = "ack-always" AckOnError = "ack-on-error" )
Fragmentation modes (RFC 8724 8.4).
const ( LastTileRegular = "regular" LastTileAll1 = "all1" LastTileEither = "either" )
Where an ACK-on-Error sender puts the last tile (RFC 8724 8.4.3).
Variables ¶
var ErrAborted = errors.New("schc: the receiver aborted the transfer")
ErrAborted is the error of a transfer the other end aborted.
var ErrInactive = errors.New("schc: the transfer was inactive for too long")
ErrInactive is the error of a transfer that timed out.
var ErrNoRule = errors.New("schc: no rule compresses this packet and there is no no-compression rule")
ErrNoRule is returned when no compression rule fits and the rule set has no no-compression rule.
var ErrSenderAborted = errors.New("schc: the sender aborted the transfer")
ErrSenderAborted is the error of a transfer the sender aborted.
Functions ¶
Types ¶
type Bits ¶
type Bits struct {
// contains filtered or unexported fields
}
Bits is a string of bits, most significant bit of the first byte first. SCHC works on bits, not bytes (RFC 8724 clause 9): residues, headers and tiles need not be whole bytes.
func FromLoRaWAN ¶
FromLoRaWAN joins FPort and FRMPayload into the SCHC Message (RFC 9011 5.1, 5.5).
func IPv6Value ¶
IPv6Value reads an IPv6 prefix ("fe80::/64") or interface identifier ("::1") as the 64 bits of a prefix or IID field.
func (*Bits) AppendUint ¶
AppendUint appends the n low bits of v, most significant first.
func (*Bits) Pad ¶
Pad appends zero bits up to a multiple of word bits and returns how many were added (RFC 8724 clause 9: fewer than one L2 Word; RFC 9011 5.4: always zero).
type Context ¶
Context is what the decompressor learns from the L2 (RFC 8724 7.4.7): the Dev's and the App's interface identifiers, 8 bytes each when known.
type Direction ¶
type Direction string
Direction is a field descriptor's Direction Indicator, or a packet's direction (RFC 8724 7.1): up (from the device), dw (to the device) or bi (both, descriptors only).
type Duration ¶
Duration is a JSON duration: "12h", "30s" or a number of seconds.
func (Duration) MarshalJSON ¶
MarshalJSON writes a duration string.
func (*Duration) UnmarshalJSON ¶
UnmarshalJSON reads "12h" or seconds.
type Field ¶
Field is one header field a parser labelled (RFC 8724 7.1: rules do not say how fields are found; a parser alongside SCHC labels them).
type FieldDescriptor ¶
type FieldDescriptor struct {
FID string `json:"fid"`
// FL is the field length in bits; 0 with Var set is a variable-length
// field measured in Var units ("bits" or "bytes", RFC 8724 7.4.2).
FL int `json:"fl,omitempty"`
Var string `json:"var,omitempty"`
// FP is the field position, default 1; 0 is "don't care" (RFC 8724
// 7.2).
FP *int `json:"fp,omitempty"`
DI Direction `json:"di,omitempty"` // default bi
// TV is a number, a hex string ("0x…" or bare hex), an IPv6 prefix or
// address (for 64-bit prefix and IID fields), or a list of these for
// match-mapping.
TV json.RawMessage `json:"tv,omitempty"`
MO string `json:"mo"`
MOArg int `json:"moArg,omitempty"` // x of MSB(x)
CDA string `json:"cda"`
// contains filtered or unexported fields
}
FieldDescriptor is one line of a compression rule (RFC 8724 7.1).
type FragMsg ¶
type FragMsg struct {
Kind MsgKind
Rule *Rule
DTag uint32
W uint32
FCN uint32 // fragments
RCS uint32 // All-1
// Payload is a fragment's payload bits (for an All-1 including its
// padding, which cannot be told from tile bits, RFC 8724 8.4.3.2).
Payload Bits
C bool // ACK
Bitmap []bool // ACK with C=0: the window's bitmap, leftmost tile (WINDOW_SIZE-1) first, uncompressed
}
FragMsg is one SCHC F/R message, decoded.
func DecodeAtReceiver ¶
DecodeAtReceiver reads a message a fragment receiver gets: a fragment, All-1, ACK REQ or Sender-Abort (RFC 8724 8.3.1, 8.3.3, 8.3.4; they are told apart by FCN and size).
func DecodeAtSender ¶
DecodeAtSender reads a message a fragment sender gets: an ACK or a Receiver-Abort (RFC 8724 8.3.2, 8.3.5).
type FragParams ¶
type FragParams struct {
Mode string `json:"mode"`
Direction Direction `json:"direction,omitempty"` // up or dw: which way the fragments go
DTagSize int `json:"dtagSize,omitempty"` // T
WSize int `json:"wSize,omitempty"` // M
FCNSize int `json:"fcnSize"` // N
WindowSize int `json:"windowSize,omitempty"`
// TileSize is the regular tile size in bits for ACK-on-Error; in
// JSON tileBytes (bytes) or tileBits.
TileSize int `json:"tileBits,omitempty"`
TileBytes int `json:"tileBytes,omitempty"`
RCSSize int `json:"rcsSize,omitempty"` // bits, default 32 (CRC32)
MaxAckRequests int `json:"maxAckRequests,omitempty"`
Retransmission Duration `json:"retransmissionTimer,omitempty"`
Inactivity Duration `json:"inactivityTimer,omitempty"`
LastTile string `json:"lastTile,omitempty"` // ACK-on-Error: regular, all1 or either (default either)
PenultimateShort bool `json:"penultimateShort,omitempty"` // ACK-on-Error: penultimate tile may be one L2 Word short
// AckEveryWindow: the ACK-on-Error receiver acknowledges every window
// and the sender waits for it before the next (RFC 9011 5.6.2).
AckEveryWindow bool `json:"ackEveryWindow,omitempty"`
}
FragParams are a fragmentation rule's parameters (RFC 8724 8.2.4, 8.4 and appendix D).
type LoRaWANFrame ¶
LoRaWANFrame is a SCHC Message as it travels on LoRaWAN: the FPort and the FRMPayload.
type MsgKind ¶
type MsgKind int
MsgKind is a SCHC F/R message type (RFC 8724 8.2.1, 8.3).
type Packet ¶
Packet is a parsed packet: its labelled header fields in header order and the payload that follows them.
type Receiver ¶
type Receiver struct {
// contains filtered or unexported fields
}
Receiver reassembles one fragmented SCHC Packet (one RuleID and DTag) and runs the receiver side of its mode (RFC 8724 8.4.1.2, 8.4.2.2, 8.4.3.2). Like Sender it does no I/O: it returns the messages to send back and, once the integrity check passes, the SCHC Packet.
func NewReceiver ¶
NewReceiver starts reassembly for a fragmentation rule and DTag. maxBytes bounds the reassembled packet (0: 4096).
func (*Receiver) Packet ¶
Packet is the reassembled SCHC Packet (with the padding bits of the fragment that carried the last tile, which decompression drops).
type Rule ¶
type Rule struct {
ID uint32 `json:"ruleId"`
IDLength int `json:"ruleIdLength,omitempty"` // bits, default 8
Kind string `json:"kind,omitempty"` // default compression, or fragmentation when fragmentation is set
// Name is a label for logs and the console.
Name string `json:"name,omitempty"`
Fields []FieldDescriptor `json:"fields,omitempty"`
Fragmentation *FragParams `json:"fragmentation,omitempty"`
}
Rule is one rule: compression, no-compression or fragmentation.
func LoRaWANDownlinkRule ¶
LoRaWANDownlinkRule is the unicast downlink fragmentation rule of RFC 9011 5.6.3: ACK-Always, T=0, M=1, N=1, WINDOW_SIZE 1, CRC32 RCS, MAX_ACK_REQUESTS 8, with the timers of the device class (5.6.3.5): class A inactivity 36 h and retransmission inactivity/(MAX+1); class B three ping slot periods; class C 30 s; B and C inactivity 12 h.
func LoRaWANMulticastRule ¶
LoRaWANMulticastRule is the multicast downlink rule of RFC 9011 5.6.3: No-ACK, T=0, N=1.
func LoRaWANUplinkRule ¶
LoRaWANUplinkRule is the uplink fragmentation rule of RFC 9011 5.6.2: ACK-on-Error, T=0, M=2, N=6, WINDOW_SIZE 63, 10-byte tiles, CRC32 RCS, MAX_ACK_REQUESTS 8, 12-hour timers, last tile in either fragment, regular penultimate tile. ackEveryWindow is the per-rule choice 5.6.2 adds (recommended for battery devices).
type RuleSet ¶
type RuleSet struct {
// L2Word is the L2 Word size in bits (default 8, the LoRaWAN value of
// RFC 9011 5.6).
L2Word int `json:"l2Word,omitempty"`
Rules []Rule `json:"rules"`
// MaxPacketSize bounds a decompressed or reassembled packet in bytes
// (RFC 8724 appendix D, clause 12; default 4096).
MaxPacketSize int `json:"maxPacketSize,omitempty"`
}
RuleSet is a SCHC context: the rules both ends hold (RFC 8724 7.1). It is our own JSON form; RFC 9363's YANG model is not implemented.
func ParseRuleSet ¶
ParseRuleSet reads and checks a rule set from JSON.
func (*RuleSet) Compress ¶
Compress parses raw with st and compresses it with the first rule that fits (RFC 8724 7.2), or sends it whole under the no-compression rule. The result is the SCHC Packet: RuleID, residue, payload (not padded).
Example ¶
Compress an IEC 62056-4-7 wrapper header (8 bytes) to a few bits with a rule that elides the constant fields and computes the length, then rebuild the frame on the other side from the same rules.
package main
import (
"bytes"
"fmt"
"github.com/cB-Sigma/schc"
)
func main() {
rules, err := schc.ParseRuleSet([]byte(`{"rules":[
{"ruleId":1,"fields":[
{"fid":"wrapper.version","fl":16,"tv":1,"mo":"equal","cda":"not-sent"},
{"fid":"wrapper.devWPort","fl":16,"tv":1,"mo":"equal","cda":"not-sent"},
{"fid":"wrapper.appWPort","fl":16,"tv":[16,32,48,64,80,96,102,1],"mo":"match-mapping","cda":"mapping-sent"},
{"fid":"wrapper.length","fl":16,"mo":"ignore","cda":"compute"}]},
{"ruleId":22,"kind":"no-compression"}]}`))
if err != nil {
panic(err)
}
stack, _ := schc.ParseStack("wrapper")
apdu := []byte{0xC0, 0x01, 0xC1, 0x00, 0x03}
frame := append([]byte{0x00, 0x01, 0x00, 0x01, 0x00, 0x10, 0x00, byte(len(apdu))}, apdu...)
msg, rule, err := rules.Compress(stack, frame, schc.Up, schc.Context{})
if err != nil {
panic(err)
}
fmt.Println("rule", rule.ID, "header and payload in", msg.Len(), "bits instead of", 8*len(frame))
msg.Pad(8)
back, _, err := rules.Decompress(stack, msg, schc.Up, schc.Context{})
fmt.Println(bytes.Equal(back, frame), err)
}
Output: rule 1 header and payload in 51 bits instead of 104 true <nil>
func (*RuleSet) CompressPacket ¶
CompressPacket compresses fields a caller labelled itself (no stack: compute CDAs are not checked) with the first rule that fits.
func (*RuleSet) Decompress ¶
func (rs *RuleSet) Decompress(st Stack, msg Bits, dir Direction, ctx Context) ([]byte, *Rule, error)
Decompress reads a SCHC Packet (possibly followed by padding of less than one L2 Word) and rebuilds the original packet with st (RFC 8724 7.2).
func (*RuleSet) DecompressPacket ¶
DecompressPacket reads a SCHC Packet into labelled fields and payload without a stack (compute fields come back empty).
func (*RuleSet) Fragmentation ¶
Fragmentation returns the fragmentation rules for a direction, in ID order.
type Sender ¶
type Sender struct {
// NextMTU, when set, gives the MTU of each new fragment in place of
// the mtu argument (an L2 whose MTU varies, RFC 8724 figure 32).
NextMTU func() int
// contains filtered or unexported fields
}
Sender fragments one SCHC Packet under a fragmentation rule and runs the sender side of its mode (RFC 8724 8.4.1.1, 8.4.2.1, 8.4.3.1). It does no I/O: its methods return the encoded messages to transmit, and the caller runs the clock (Tick) and says how many bits the next message may have (mtu, the whole SCHC message including the RuleID).
func NewSender ¶
NewSender starts fragmenting packet under rule r with DTag dtag.
Example ¶
Fragment a 300-byte packet for LoRaWAN with the RFC 9011 uplink rule (ACK-on-Error) and reassemble it. Sender and Receiver are state machines without I/O: the caller carries their messages and drives their timers.
package main
import (
"bytes"
"fmt"
"time"
"github.com/cB-Sigma/schc"
)
func main() {
rules := schc.RuleSet{Rules: []schc.Rule{schc.LoRaWANUplinkRule(schc.FPortUp, 10, false)}}
if err := rules.Compile(); err != nil {
panic(err)
}
rule := &rules.Rules[0]
packet := schc.BytesOf(bytes.Repeat([]byte("sensor data "), 25))
now := time.Now()
sender, err := schc.NewSender(rule, 8, 0, packet)
if err != nil {
panic(err)
}
receiver := schc.NewReceiver(rule, 8, 0, 0, now)
frags, err := sender.Start(now, 8+8*51) // FPort plus 51 bytes of LoRaWAN payload
if err != nil {
panic(err)
}
var acks []schc.Bits
for _, f := range frags {
lf, _ := schc.ToLoRaWAN(f) // what goes on the radio: FPort and payload
a, err := receiver.Receive(now, schc.FromLoRaWAN(lf.FPort, lf.Payload))
if err != nil {
panic(err)
}
acks = append(acks, a...)
}
for _, a := range acks {
if _, err := sender.Receive(now, a, 8+8*51); err != nil {
panic(err)
}
}
got, ok := receiver.Packet()
same := ok && bytes.Equal(got.Slice(0, packet.Len()).Bytes(), packet.Bytes())
fmt.Printf("%d fragments, reassembled %v, sender done %v\n", len(frags), same, sender.Done())
}
Output: 7 fragments, reassembled true, sender done true
func (*Sender) Done ¶
Done reports whether the transfer ended; Err is its error (nil when the receiver confirmed the packet, or for No-ACK once everything was sent).
type Stack ¶
type Stack []string
Stack is the protocol layers a packet's header is made of, outermost first: any of ipv6, udp and wrapper, in that order. An empty stack has no header: the whole packet is payload.
func ParseStack ¶
ParseStack reads "ipv6/udp/wrapper", "wrapper", "udp/wrapper", "none" or "".
func (Stack) Build ¶
Build writes a packet from its field values (by FID; fields missing from vals are computed) and payload. It is the inverse of Parse.
Source Files
¶
Directories
¶
| Path | Synopsis |
|---|---|
|
Package v44 is the ITU-T V.44 (11/2000, with Corrigendum 1 of 03/2002) data compression algorithm, packet method (annex B.1), in pure Go.
|
Package v44 is the ITU-T V.44 (11/2000, with Corrigendum 1 of 03/2002) data compression algorithm, packet method (annex B.1), in pure Go. |