lunalink

package module
v0.1.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Dec 3, 2026 License: MIT Imports: 14 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.

README

A LunaLink node in Go: a library (github.com/lunasoft-llc/lunalink-go) and a small static gateway binary (cmd/lunalink-gateway) for Linux edge devices. It implements protocol revision 2.0 as a node (see docs/PROTOCOL.md in the LunaLink repository).

Pure Go, no cgo. The only dependency is bbolt for the durable state.

What is implemented

  • Frame codec and CRC-16/CCITT-FALSE, hand-written MessagePack arrays (no maps), .NET GUID byte order, value encoding for DataTypes 0 to 9.
  • Hello / HelloAck with capability negotiation: offers no-compression, max-payload=<n>, goodbye, window=<n>.
  • Durable outbox in one bbolt file with a persistent NodeSequence (spec 8.1). A batch is deleted only after TagDeltaAck with Accepted = true.
  • Ordered delivery: stop-and-wait, or a window when the master grants window=<n>, with go-back-N on a rejected ack. Resync baseline when the master expects a sequence the outbox no longer holds, and when the backlog reaches 1024 batches (spec 8.4).
  • Heartbeat with TimestampMs, Goodbye on shutdown when negotiated, Error logging.
  • Write commands (TagWriteCmd) with persisted idempotency by CommandId, expiry and QueryOnly (spec 9).
  • TLS 1.3 with an optional client certificate.
  • Reconnect loop with a fixed delay.

Not implemented: LZ4 (the node offers no-compression, so a conforming master never sends compressed frames), arrays and blobs (DataTypes 10 to 13), events, browse, historian backfill, no-crc, master-delta, snapshots and subscriptions. A frame with the Compressed flag is ignored.

Library

node, _ := lunalink.NewNode(lunalink.Config{
    Addr: "master:7788", NodeID: "gw-1", AuthToken: "secret",
    StorePath: "gw-1.db", Window: 16,
    OnWrite: func(tag lunalink.GUID, name string, dt int, v any) error { return nil },
})
defer node.Close()

go node.Run(ctx) // connects, replays the outbox, reconnects; sends Goodbye when ctx is cancelled

id, _ := lunalink.ParseGUID("00112233-4455-6677-8899-aabbccddeeff")
node.Publish([]lunalink.Item{{TagID: id, DataType: lunalink.TypeFloat64, Value: 21.5}})

Publish returns once the batch is durable on disk, so values survive a restart or power loss.

Gateway

lunalink-gateway -config gateway.json
lunalink-gateway -master host:7788 -node-id gw-1 [-token secret] [-data gw.db] [-window 16]

Values come from stdin, one per line: <tag> <value> or <tag>=<value>. <tag> is a name from the config or a GUID. Values that arrive within 20 ms form one batch.

{
  "master": "192.168.1.10:7788",
  "nodeId": "gw-1",
  "nodeName": "Boiler room gateway",
  "authToken": "secret",
  "dataFile": "/var/lib/lunalink/gw-1.db",
  "window": 16,
  "tls": { "enabled": true, "caFile": "ca.pem", "certFile": "node.pem", "keyFile": "node.key" },
  "tags": [
    { "name": "temp", "id": "00112233-4455-6677-8899-aabbccddeeff", "type": "float32" }
  ]
}

Types: bool int16 uint16 int32 uint32 float32 float64 string enum json. Without a declared type it is inferred. Remote writes are printed to stdout as WRITE <tag> <value> and acknowledged as succeeded.

Static binaries

CGO_ENABLED=0 GOOS=linux GOARCH=amd64 go build -trimpath -ldflags "-s -w" -o lunalink-gateway ./cmd/lunalink-gateway
CGO_ENABLED=0 GOOS=linux GOARCH=arm64 go build -trimpath -ldflags "-s -w" -o lunalink-gateway ./cmd/lunalink-gateway

Tests

go test ./...

Unit tests cover the Appendix A test vectors, integer encodings, values and an in-process fake master (stop-and-wait, window, go-back-N, reconnect, resync, restart, write idempotency, Goodbye). TestInteropDotNetMaster runs a real .NET master (LunaLink 1.2.0 NuGet package) through the harness in ../lunalink-python/interop/Harness and checks in-order delivery without loss across forced reconnects. It is skipped when dotnet or the built harness (dotnet build -c Release -o bin) is missing. Features that need a 2.0 master (window, goodbye) are only exercised against the fake master until it is released.

License

MIT

Documentation

Overview

Package lunalink implements a LunaLink node (protocol revision 2.0): frame codec, MessagePack array encoding, durable outbox, ordered delivery and remote writes.

Index

Constants

View Source
const (
	Magic          = 0x4C4C4E4B
	FrameVersion   = 1
	HeaderSize     = 15
	MaxPayloadSize = 4 * 1024 * 1024

	FlagCompressed  = 0x01
	FlagRequiresAck = 0x02
)

Frame constants (spec section 3).

View Source
const (
	MsgHello           = 0x01
	MsgHelloAck        = 0x02
	MsgTagDelta        = 0x03
	MsgTagWriteCmd     = 0x04
	MsgTagWriteAck     = 0x05
	MsgHeartbeat       = 0x06
	MsgHeartbeatAck    = 0x07
	MsgSnapshotReq     = 0x08
	MsgSnapshotResp    = 0x09
	MsgSubscribe       = 0x0A
	MsgError           = 0x0B
	MsgPing            = 0x0C
	MsgPong            = 0x0D
	MsgAck             = 0x0E
	MsgTagDeltaAck     = 0x0F
	MsgHistoryBatch    = 0x10
	MsgHistoryBatchAck = 0x11
	MsgGoodbye         = 0x12
	MsgBrowseReq       = 0x13
	MsgBrowseResp      = 0x14
	MsgEventAck        = 0x15
)

Message types (spec section 7).

View Source
const (
	StatusUnknown   = 0
	StatusSucceeded = 1
	StatusFailed    = 2
	StatusExpired   = 3
)

Write status values (spec 7.6).

View Source
const (
	TypeBool    = 0
	TypeInt16   = 1
	TypeUInt16  = 2
	TypeInt32   = 3
	TypeUInt32  = 4
	TypeFloat32 = 5
	TypeFloat64 = 6
	TypeString  = 7
	TypeEnum    = 8
	TypeJSON    = 9
)

DataType values (spec 5.3). Types 10 to 13 need arrays-v1 and are not implemented by this node.

View Source
const (
	QualityGood         = 1
	QualityBad          = 2
	QualityUncertain    = 3
	QualityNotConnected = 4
)

Quality values (spec 5.4).

Variables

View Source
var ErrBadCRC = errors.New("lunalink: crc mismatch")

ErrBadCRC is returned for a frame whose CRC does not match. The frame was fully consumed.

View Source
var ErrBadMagic = errors.New("lunalink: bad magic")

ErrBadMagic is returned when a frame does not start with the magic. The stream cannot be resynchronised.

View Source
var ErrFrameTooLarge = errors.New("lunalink: frame too large")

ErrFrameTooLarge is returned when PayloadLen exceeds the receiver's limit.

View Source
var ErrMsgpack = errors.New("lunalink: invalid msgpack")

ErrMsgpack is returned for truncated or unsupported MessagePack input.

View Source
var ErrWriteUnknown = errors.New("lunalink: write outcome unknown")

ErrWriteUnknown marks a write whose outcome is unknown.

Functions

func CRC16

func CRC16(data []byte) uint16

CRC16 computes CRC-16/CCITT-FALSE (poly 0x1021, init 0xFFFF) as in spec section 3.3.

func Decode

func Decode(b []byte) (any, error)

Decode decodes one MessagePack value. Result types: nil, bool, int64, uint64 (only above MaxInt64), float64, string, []byte, []any. Maps are rejected (spec 4.1).

func DecodeError

func DecodeError(p []byte) (code int64, msg string)

DecodeError decodes an Error payload.

func DecodeValue

func DecodeValue(dataType int, b []byte) any

DecodeValue decodes ValueBytes: bool, int64, uint64 (UInt32/UInt16 give int64), float64 or string. Empty bytes decode to nil. Unknown types decode as UTF-8 text (spec 5.3).

func EncodeAck

func EncodeAck(ackedSeq uint32) []byte

EncodeAck encodes an Ack payload.

func EncodeFrame

func EncodeFrame(f Frame, computeCRC bool) []byte

EncodeFrame serialises a frame. When computeCRC is false the CRC field is 0x0000 (no-crc).

func EncodeGoodbye

func EncodeGoodbye(reason string) []byte

EncodeGoodbye encodes a Goodbye payload.

func EncodeHeartbeat

func EncodeHeartbeat(tsMs, pendingBatches, pendingValues, pendingBytes int64, oldestAgeSec float64, connectedAtMs, reconnects int64) []byte

EncodeHeartbeat encodes a Heartbeat with keys 0 to 10 (the rest take defaults).

func EncodeHello

func EncodeHello(h Hello) []byte

EncodeHello encodes a Hello payload.

func EncodeItem

func EncodeItem(it Item) ([]byte, error)

EncodeItem encodes one TagDeltaItem.

func EncodeTagDelta

func EncodeTagDelta(items [][]byte, batchTsMs, nodeSeq int64, resync bool) []byte

EncodeTagDelta builds a TagDelta payload from already encoded items.

func EncodeTagWriteAck

func EncodeTagWriteAck(seqRef uint32, status int, commandID string, hasCommand bool) []byte

EncodeTagWriteAck encodes a TagWriteAck payload.

func EncodeValue

func EncodeValue(dataType int, v any) ([]byte, error)

EncodeValue encodes v as ValueBytes for dataType (spec 5.3). A nil value gives empty bytes (null).

func StatusName

func StatusName(s int) string

StatusName names a write status.

Types

type Config

type Config struct {
	Addr      string // master host:port
	NodeID    string // stable identity, required
	NodeName  string
	Version   string
	AuthToken string
	StorePath string      // bbolt file, required
	TLS       *tls.Config // nil for plain TCP; MinVersion is forced to TLS 1.3

	Window         int           // delivery window offered, 1 (default) to 256
	MaxPayload     int           // max-payload offered, default 65536 (min 512)
	AckTimeout     time.Duration // default 5 s
	ReconnectDelay time.Duration // default 5 s
	CollapseAt     int           // resync when the backlog reaches this many batches, default 1024 (0 keeps default, <0 disables)
	OnWrite        WriteHandler  // nil: every write fails
	Logf           func(format string, args ...any)
}

Config configures a Node.

type Encoder

type Encoder struct{ B []byte }

Encoder is a minimal MessagePack writer. LunaLink only uses arrays, never maps (spec 4.1).

func (*Encoder) Array

func (e *Encoder) Array(n int)

Array writes an array header.

func (*Encoder) Bin

func (e *Encoder) Bin(b []byte)

Bin writes a byte string.

func (*Encoder) Bool

func (e *Encoder) Bool(v bool)

Bool writes a boolean.

func (*Encoder) Float32

func (e *Encoder) Float32(v float32)

Float32 writes a float32.

func (*Encoder) Float64

func (e *Encoder) Float64(v float64)

Float64 writes a float64.

func (*Encoder) Int

func (e *Encoder) Int(v int64)

Int writes an integer in the smallest representation. Non-negative values use the unsigned forms, as the .NET reference encoder does (Appendix A shows 0xcf for 1767225600000).

func (*Encoder) Nil

func (e *Encoder) Nil()

Nil writes nil.

func (*Encoder) Raw

func (e *Encoder) Raw(b []byte)

Raw appends already encoded MessagePack.

func (*Encoder) Str

func (e *Encoder) Str(s string)

Str writes a UTF-8 string.

func (*Encoder) Uint

func (e *Encoder) Uint(v uint64)

Uint writes an unsigned integer in the smallest representation.

type Frame

type Frame struct {
	Version byte
	Type    byte
	Flags   byte
	Seq     uint32
	Payload []byte
}

Frame is one decoded frame.

func ReadFrame

func ReadFrame(r io.Reader, maxPayload int, checkCRC bool) (Frame, error)

ReadFrame reads one frame. maxPayload bounds PayloadLen. With checkCRC false the CRC is not validated. On ErrBadCRC the returned frame is still filled in and the stream stays aligned.

type GUID

type GUID [16]byte

GUID is a tag identifier held in text order (RFC 4122 byte order). On the wire it uses .NET Guid.ToByteArray() order (spec 5.2): see Wire and GUIDFromWire.

func GUIDFromWire

func GUIDFromWire(w []byte) (GUID, bool)

GUIDFromWire converts .NET order bytes to a GUID.

func ParseGUID

func ParseGUID(s string) (GUID, error)

ParseGUID parses 00112233-4455-6677-8899-aabbccddeeff.

func (GUID) String

func (g GUID) String() string

String returns the text form.

func (GUID) Wire

func (g GUID) Wire() []byte

Wire returns the 16 bytes in .NET order: groups 1 to 3 byte-swapped.

type Hello

type Hello struct {
	NodeID       string
	NodeName     string
	Version      string
	Capabilities []string
	TimestampMs  int64
	AuthToken    string // empty means nil
}

Hello is spec 7.1.

type HelloAck

type HelloAck struct {
	AssignedNodeID    string
	ServerTimeMs      int64
	HeartbeatInterval int64
	Accepted          bool
	RejectReason      string
	Capabilities      []string
	SupportedVersions []int64
}

HelloAck is spec 7.2.

func DecodeHelloAck

func DecodeHelloAck(p []byte) (HelloAck, error)

DecodeHelloAck decodes a HelloAck payload.

type Item

type Item struct {
	TagID       GUID
	Name        string // optional
	Value       any    // see EncodeValue
	DataType    int
	Quality     int
	TimestampMs int64
}

Item is one tag value (TagDeltaItem, spec 5.5).

type Node

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

Node is a LunaLink node. Publish values with Publish, run the connection loop with Run.

func NewNode

func NewNode(cfg Config) (*Node, error)

NewNode opens the durable store and returns a node.

func (*Node) Close

func (n *Node) Close() error

Close releases the store. Call after Run returned.

func (*Node) DropConnection

func (n *Node) DropConnection()

DropConnection closes the current TCP connection without Goodbye (used to test recovery).

func (*Node) Publish

func (n *Node) Publish(items []Item) error

Publish persists a batch in the outbox. It returns once the batch is durable. Large input is split into batches of at most 500 values.

func (*Node) Run

func (n *Node) Run(ctx context.Context) error

Run connects and serves until ctx is cancelled, reconnecting after failures. On cancellation it sends Goodbye (when negotiated) and returns.

func (*Node) Store

func (n *Node) Store() *Store

Store gives access to the durable state (for diagnostics and tests).

type OutboxEntry

type OutboxEntry struct {
	Seq     int64
	Payload []byte
}

OutboxEntry is one pending TagDelta payload.

type Store

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

Store is the node's durable state in one bbolt file (pure Go): the outbox with its NodeSequence counter (spec section 8.1), the latest value of every tag (for resync baselines, section 8.4) and the write command results (section 9).

func OpenStore

func OpenStore(path string) (*Store, error)

OpenStore opens or creates the state file.

func (*Store) After

func (s *Store) After(seq int64, n int) ([]OutboxEntry, error)

After returns up to n entries with sequence greater than seq, in ascending order.

func (*Store) Close

func (s *Store) Close() error

Close closes the file.

func (*Store) CommandStatus

func (s *Store) CommandStatus(id string) (status int, found bool)

CommandStatus returns the stored status of a write command.

func (*Store) DeleteUpTo

func (s *Store) DeleteUpTo(seq int64) error

DeleteUpTo removes every batch with sequence up to and including seq.

func (*Store) Enqueue

func (s *Store) Enqueue(items [][]byte, tagIDs []GUID, batchTsMs int64) (int64, error)

Enqueue assigns the next NodeSequence, persists the batch and updates the latest values in one transaction. bbolt syncs to disk before Update returns.

func (*Store) Has

func (s *Store) Has(seq int64) bool

Has reports whether the outbox holds the sequence.

func (*Store) LastSequence

func (s *Store) LastSequence() int64

LastSequence returns the highest NodeSequence ever assigned.

func (*Store) Latest

func (s *Store) Latest() [][]byte

Latest returns the encoded latest item of every tag.

func (*Store) SetCommandStatus

func (s *Store) SetCommandStatus(id string, status int) error

SetCommandStatus persists the status of a write command.

func (*Store) Stats

func (s *Store) Stats() (batches, bytes, highest int64)

Stats returns pending batch count, bytes and the highest sequence in the outbox (0 if empty).

type TagDeltaAck

type TagDeltaAck struct {
	NodeSequence     int64
	Accepted         bool
	ExpectedSequence int64
	Duplicate        bool
	Error            string
}

TagDeltaAck is spec 7.4.

func DecodeTagDeltaAck

func DecodeTagDeltaAck(p []byte) (TagDeltaAck, error)

DecodeTagDeltaAck decodes a TagDeltaAck payload.

type WriteCmd

type WriteCmd struct {
	SeqRef      uint32
	TagID       GUID
	ValueBytes  []byte
	DataType    int
	TagName     string
	CommandID   string
	HasCommand  bool
	ExpiresAtMs int64
	QueryOnly   bool
}

WriteCmd is spec 7.5.

func DecodeWriteCmd

func DecodeWriteCmd(p []byte) (WriteCmd, error)

DecodeWriteCmd decodes a TagWriteCmd payload.

type WriteHandler

type WriteHandler func(tag GUID, name string, dataType int, value any) error

WriteHandler executes a remote write. Return nil for success, an error for failure. Return ErrWriteUnknown when the outcome cannot be determined (status stays Unknown, spec 9.2).

Directories

Path Synopsis
cmd
lunalink-gateway command
Command lunalink-gateway reads values from stdin and publishes them to a LunaLink master.
Command lunalink-gateway reads values from stdin and publishes them to a LunaLink master.

Jump to

Keyboard shortcuts

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