schc

package module
v0.1.1 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: 15 Imported by: 0 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.

README

schc

Static Context Header Compression and fragmentation (SCHC, RFC 8724) with the LoRaWAN profile (RFC 9011), and V.44 data compression (packet method), in pure Go.

Go Reference test Go

No cgo and no dependencies outside the Go standard library. Written for SigmaM2M, a oneM2M platform, where it carries DLMS/COSEM meter traffic over LoRaWAN.

Features

Feature Status
Compression: matching operators equal, ignore, MSB(x), match-mapping; actions not-sent, value-sent, mapping-sent, LSB, compute, DevIID, AppIID; variable-length residues Implemented
Fields: IPv6, UDP, IEC 62056-4-7 wrapper header Implemented
Fields: CoAP (RFC 8824) Not implemented
Fragmentation: No-ACK, ACK-Always, ACK-on-Error, bitmap compression, CRC32 RCS Implemented, as clock-driven sender and receiver state machines without I/O
Other RCS algorithms Not implemented
LoRaWAN profile (RFC 9011): uplink ACK-on-Error, downlink ACK-Always, multicast No-ACK, class timers, FPort mapping, AES-CMAC interface identifier Implemented
Rule management (RFC 9363 YANG, RFC 9441 CORECONF) Not implemented; rules are JSON in this module's own format
V.44 packet method (ITU-T V.44 annex B.1) Implemented
V.44 stream and multi-packet methods, V.42 negotiation Not implemented

Standards and clause references are listed in PROVENANCE.md.

Choosing a SCHC implementation

No other Go implementation of SCHC was found (GitHub and the Go module proxy, October 2026). The other open implementations are in Python and C; compared from their repositories at the versions named. Check the projects themselves before relying on a row.

this module openschc (Python) microSCHC 0.22.0 (Python) libschc (C)
Version looked at v0.x master, last commit 2025-12-16 (PyPI 0.0.3 is from 2022) PyPI, 2026-03-02 master, last commit 2023-04-28
Licence Apache-2.0 MIT MIT GPL-3.0, or a commercial licence
Compression of IPv6 and UDP yes yes yes, and IPv4, SCTP yes
CoAP fields (RFC 8824) no yes yes yes
IEC 62056-4-7 wrapper (DLMS/COSEM) fields yes no no no
Fragmentation: No-ACK, ACK-Always, ACK-on-Error yes yes no yes
LoRaWAN the RFC 9011 profile: FPort mapping, timers, AES-CMAC interface identifier examples carry the rule ID in FPort; no AES-CMAC identifier found no a LoRaWAN profile in its rule headers; no AES-CMAC identifier found
Rules as YANG / CORECONF no (own JSON) yes no (own data model) no (C headers)
V.44 compression yes no no no
Runs in a Go program without cgo yes no no no

Pick this module for a Go server that receives DLMS/COSEM or other UDP/IPv6 traffic over LoRaWAN. Pick openschc when you need CoAP rules, YANG/CORECONF rule management or its network simulator, and Python is fine; microSCHC for compression alone on MicroPython; libschc on a microcontroller, if GPL-3.0 or its commercial licence suits you.

Install

go get github.com/cB-Sigma/schc@latest

Requires Go 1.24 or later.

Quick start

Compress an IEC 62056-4-7 wrapper header with a rule that elides the constant fields and computes the length, then rebuild the frame from the same rules (from ExampleRuleSet_Compress):

import "github.com/cB-Sigma/schc"

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 {
	return 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{})
// rule 1: header and payload in 51 bits instead of 104
msg.Pad(8) // whole bytes for the link
back, _, err := rules.Decompress(stack, msg, schc.Up, schc.Context{})
// bytes.Equal(back, frame) == true

Fragmentation: NewSender and NewReceiver take a fragmentation rule. The caller carries the sender's fragments to the receiver (Start, Receive) and the receiver's acknowledgements back, and calls Tick at each Deadline. ExampleNewSender fragments a 300-byte packet with the RFC 9011 uplink rule and reassembles it; v44.ExampleCompress compresses and decompresses one V.44 packet.

Documentation

Reference: pkg.go.dev/github.com/cB-Sigma/schc.

Package Contents
schc (module root) Rules as JSON; compression and decompression of IPv6, UDP and IEC 62056-4-7 wrapper headers; fragmentation sender and receiver; the RFC 9011 LoRaWAN rules, FPort mapping and interface identifier
schc/v44 ITU-T V.44 compression, packet method (dictionary reset per packet, FLUSH at the end), with the annex B indicator for packets sent uncompressed

Testing

go test -race ./...

The tests re-enact the RFC 8724 appendix B and RFC 9011 appendix A example exchanges message by message, and the V.44 appendix II examples; sources are listed in PROVENANCE.md. There are fuzz tests for SCHC message decoding, decompression and V.44. // Covers: SIG-... comments in tests are requirement IDs of the SigmaM2M project's compliance report and have no meaning outside it.

Interop tested against

Nothing yet. No other SCHC implementation (openschc, libschc), no LoRaWAN network server and no meter that uses V.44 has been tested against this module.

This module has no simulator. Its LoRaWAN fragmentation is exercised by SigmaM2M's DLMS/COSEM tests.

Status

v0.x. The API may change before v1.

Contributing

See CONTRIBUTING.md.

Security

See SECURITY.md for how to report a vulnerability.

Licence

Apache-2.0 (see LICENSE and NOTICE). Copyright 2026 Abhinav Gautam.

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

Examples

Constants

View Source
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.

View Source
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).

View Source
const (
	ClassA = "A"
	ClassB = "B"
	ClassC = "C"
)

LoRaWAN device classes (RFC 9011 4.1).

View Source
const (
	MOEqual        = "equal"
	MOIgnore       = "ignore"
	MOMSB          = "msb"
	MOMatchMapping = "match-mapping"
)

Matching operators (RFC 8724 7.3).

View Source
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).

View Source
const (
	KindCompression   = "compression"
	KindNoCompression = "no-compression"
	KindFragmentation = "fragmentation"
)

Rule kinds.

View Source
const (
	NoAck      = "no-ack"
	AckAlways  = "ack-always"
	AckOnError = "ack-on-error"
)

Fragmentation modes (RFC 8724 8.4).

View Source
const (
	LastTileRegular = "regular"
	LastTileAll1    = "all1"
	LastTileEither  = "either"
)

Where an ACK-on-Error sender puts the last tile (RFC 8724 8.4.3).

Variables

View Source
var ErrAborted = errors.New("schc: the receiver aborted the transfer")

ErrAborted is the error of a transfer the other end aborted.

View Source
var ErrInactive = errors.New("schc: the transfer was inactive for too long")

ErrInactive is the error of a transfer that timed out.

View Source
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.

View Source
var ErrSenderAborted = errors.New("schc: the sender aborted the transfer")

ErrSenderAborted is the error of a transfer the sender aborted.

Functions

func LoRaWANIID

func LoRaWANIID(appSKey, devEUI []byte) ([]byte, error)

LoRaWANIID is the Dev IPv6 interface identifier of RFC 9011 5.3: the first 8 bytes of AES128-CMAC(AppSKey, DevEUI).

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 BitsOf

func BitsOf(b []byte, n int) Bits

BitsOf is the first n bits of b (b is not copied).

func BytesOf

func BytesOf(b []byte) Bits

BytesOf is every bit of b.

func FromLoRaWAN

func FromLoRaWAN(fport uint8, payload []byte) Bits

FromLoRaWAN joins FPort and FRMPayload into the SCHC Message (RFC 9011 5.1, 5.5).

func IPv6Value

func IPv6Value(s string) (Bits, error)

IPv6Value reads an IPv6 prefix ("fe80::/64") or interface identifier ("::1") as the 64 bits of a prefix or IID field.

func ParseBits

func ParseBits(s string) (Bits, error)

ParseBits reads a string of 0 and 1 (spaces ignored), for tests.

func Uint

func Uint(v uint64, n int) Bits

Uint is v in n bits (n up to 64).

func (*Bits) Append

func (x *Bits) Append(y Bits)

Append appends y.

func (*Bits) AppendBit

func (x *Bits) AppendBit(v uint8)

AppendBit appends one bit.

func (*Bits) AppendBytes

func (x *Bits) AppendBytes(b []byte)

AppendBytes appends every bit of b.

func (*Bits) AppendUint

func (x *Bits) AppendUint(v uint64, n int)

AppendUint appends the n low bits of v, most significant first.

func (Bits) Bit

func (x Bits) Bit(i int) uint8

Bit is bit i (0 or 1).

func (Bits) Bytes

func (x Bits) Bytes() []byte

Bytes returns the bits zero-extended to whole bytes (a copy).

func (Bits) Clone

func (x Bits) Clone() Bits

Clone copies x.

func (Bits) Equal

func (x Bits) Equal(y Bits) bool

Equal reports whether x and y hold the same bits.

func (Bits) Len

func (x Bits) Len() int

Len is the number of bits.

func (*Bits) Pad

func (x *Bits) Pad(word int) int

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).

func (Bits) Slice

func (x Bits) Slice(from, to int) Bits

Slice is bits [from, to) (a copy).

func (Bits) String

func (x Bits) String() string

String shows the bits as 0 and 1, for tests and logs.

func (Bits) UintAt

func (x Bits) UintAt(from, n int) uint64

UintAt reads n bits (up to 64) at bit offset from.

type Context

type Context struct {
	DevIID []byte
	AppIID []byte
}

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).

const (
	Up   Direction = "up"
	Down Direction = "dw"
	Bi   Direction = "bi"
)

Directions.

type Duration

type Duration time.Duration

Duration is a JSON duration: "12h", "30s" or a number of seconds.

func (Duration) D

func (d Duration) D() time.Duration

D is the duration.

func (Duration) MarshalJSON

func (d Duration) MarshalJSON() ([]byte, error)

MarshalJSON writes a duration string.

func (*Duration) UnmarshalJSON

func (d *Duration) UnmarshalJSON(b []byte) error

UnmarshalJSON reads "12h" or seconds.

type Field

type Field struct {
	FID   string
	Pos   int // occurrence, from 1
	Value Bits
}

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

func DecodeAtReceiver(r *Rule, msg Bits, word int) (*FragMsg, error)

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

func DecodeAtSender(r *Rule, msg Bits, word int) (*FragMsg, error)

DecodeAtSender reads a message a fragment sender gets: an ACK or a Receiver-Abort (RFC 8724 8.3.2, 8.3.5).

func (*FragMsg) Encode

func (m *FragMsg) Encode(word int) Bits

Encode writes the message with padding to the L2 Word (RFC 8724 8.3, clause 9).

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

type LoRaWANFrame struct {
	FPort   uint8
	Payload []byte
}

LoRaWANFrame is a SCHC Message as it travels on LoRaWAN: the FPort and the FRMPayload.

func ToLoRaWAN

func ToLoRaWAN(msg Bits) (LoRaWANFrame, error)

ToLoRaWAN splits a SCHC Message (8-bit RuleID first) into FPort and payload, padding with zeros to whole bytes (RFC 9011 5.1, 5.4).

type MsgKind

type MsgKind int

MsgKind is a SCHC F/R message type (RFC 8724 8.2.1, 8.3).

const (
	MsgFragment      MsgKind = iota // Regular SCHC Fragment (including All-0)
	MsgAll1                         // All-1 SCHC Fragment
	MsgAckReq                       // SCHC ACK REQ
	MsgSenderAbort                  // SCHC Sender-Abort
	MsgAck                          // SCHC ACK
	MsgReceiverAbort                // SCHC Receiver-Abort
)

Message types.

func (MsgKind) String

func (k MsgKind) String() string

String is the message type's short name, such as "ack-req".

type Packet

type Packet struct {
	Fields  []Field
	Payload []byte
}

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

func NewReceiver(r *Rule, word int, dtag uint32, maxBytes int, now time.Time) *Receiver

NewReceiver starts reassembly for a fragmentation rule and DTag. maxBytes bounds the reassembled packet (0: 4096).

func (*Receiver) Deadline

func (rv *Receiver) Deadline() time.Time

Deadline is when the inactivity timer expires.

func (*Receiver) Done

func (rv *Receiver) Done() bool

Done reports whether the packet was reassembled or the transfer ended.

func (*Receiver) Err

func (rv *Receiver) Err() error

Err is why reassembly failed.

func (*Receiver) Packet

func (rv *Receiver) Packet() (Bits, bool)

Packet is the reassembled SCHC Packet (with the padding bits of the fragment that carried the last tile, which decompression drops).

func (*Receiver) Receive

func (rv *Receiver) Receive(now time.Time, msg Bits) ([]Bits, error)

Receive handles a message; it returns the messages to send back.

func (*Receiver) Tick

func (rv *Receiver) Tick(now time.Time) []Bits

Tick runs the inactivity timer: on expiry reassembly ends (with a Receiver-Abort outside No-ACK). After success it just ends the clean-up.

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

func LoRaWANDownlinkRule(fport uint8, class string, pingSlot time.Duration) Rule

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

func LoRaWANMulticastRule(fport uint8) Rule

LoRaWANMulticastRule is the multicast downlink rule of RFC 9011 5.6.3: No-ACK, T=0, N=1.

func LoRaWANUplinkRule

func LoRaWANUplinkRule(fport uint8, tileBytes int, ackEveryWindow bool) Rule

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

func ParseRuleSet(b []byte) (*RuleSet, error)

ParseRuleSet reads and checks a rule set from JSON.

func (*RuleSet) ByID

func (rs *RuleSet) ByID(id uint32) *Rule

ByID returns the rule with an ID (of any length), or nil.

func (*RuleSet) Compile

func (rs *RuleSet) Compile() error

Compile fills in defaults and checks the rules; it must run before use.

func (*RuleSet) Compress

func (rs *RuleSet) Compress(st Stack, raw []byte, dir Direction, ctx Context) (Bits, *Rule, error)

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

func (rs *RuleSet) CompressPacket(p Packet, dir Direction, ctx Context) (Bits, *Rule, error)

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

func (rs *RuleSet) DecompressPacket(msg Bits, dir Direction, ctx Context) (Packet, *Rule, error)

DecompressPacket reads a SCHC Packet into labelled fields and payload without a stack (compute fields come back empty).

func (*RuleSet) Fragmentation

func (rs *RuleSet) Fragmentation(dir Direction) []*Rule

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

func NewSender(r *Rule, word int, dtag uint32, packet Bits) (*Sender, error)

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) Deadline

func (s *Sender) Deadline() time.Time

Deadline is when Tick next has work (the retransmission timer), or zero.

func (*Sender) Done

func (s *Sender) Done() bool

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).

func (*Sender) Err

func (s *Sender) Err() error

Err is why the transfer failed.

func (*Sender) Receive

func (s *Sender) Receive(now time.Time, msg Bits, mtu int) ([]Bits, error)

Receive handles an ACK or Receiver-Abort.

func (*Sender) Start

func (s *Sender) Start(now time.Time, mtu int) ([]Bits, error)

Start sends the first messages: every fragment in No-ACK, the first window otherwise.

func (*Sender) Tick

func (s *Sender) Tick(now time.Time) ([]Bits, error)

Tick runs the retransmission timer: an ACK REQ (ACK-Always) or the All-1 again (ACK-on-Error), up to MAX_ACK_REQUESTS, then a Sender-Abort.

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

func ParseStack(s string) (Stack, error)

ParseStack reads "ipv6/udp/wrapper", "wrapper", "udp/wrapper", "none" or "".

func (Stack) Build

func (st Stack) Build(vals map[string]Bits, payload []byte, dir Direction) ([]byte, error)

Build writes a packet from its field values (by FID; fields missing from vals are computed) and payload. It is the inverse of Parse.

func (Stack) Parse

func (st Stack) Parse(raw []byte, dir Direction) (Packet, error)

Parse labels a packet's header fields. dir tells the Dev end from the App end (source is the Dev going up).

func (Stack) String

func (st Stack) String() string

String is the stack as ParseStack reads it.

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.

Jump to

Keyboard shortcuts

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