bacnet

package module
v0.2.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: 21 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

bacnet

A BACnet client and device in pure Go for BACnet/IP, BACnet/IPv6 and BACnet Secure Connect (ANSI/ASHRAE Standard 135-2024).

Go Reference test Go

The module encodes and decodes BVLC, NPDU and APDU, runs confirmed and unconfirmed services with segmentation both ways, reaches devices behind BACnet routers, registers as a foreign device and can act as a BBMD. On BACnet/SC it is a hub connector with failover, a hub function and a node with direct connections, over TLS 1.3 WebSockets. Since v0.2.0 the device package serves objects to other BACnet clients (the device role), on its own BACnet/IP socket or on a client's data link. It has no cgo; TLS comes from tlsx (a fork of Go's crypto/tls with on-demand key updates). It was written for SigmaM2M, a oneM2M platform, where it serves the BACnet integrations; it does not depend on it.

Features

Feature Status
BACnet/IP (Annex J): unicast, local broadcast, foreign-device registration and re-registration, Distribute-Broadcast-To-Network yes (tested against bacnet-stack)
BBMD function (BDT, FDT, forwarding) yes
BACnet/IPv6 (Annex U): VMACs, address resolution, multicast or BBMD yes
BACnet/SC (Annex AB): hub connector with failover, heartbeat, hub function, direct connections, TLS 1.3 key updates, data options yes (hub connector tested against bacnet-stack's hub)
Routing: Who-Is-Router-To-Network, devices on remote networks yes
ReadProperty, ReadPropertyMultiple, WriteProperty, WritePropertyMultiple yes (RP, RPM, WP tested against bacnet-stack)
SubscribeCOV, SubscribeCOVProperty, COV notifications (confirmed and unconfirmed) yes (SubscribeCOV tested against bacnet-stack)
ReadRange on log buffers (by position, sequence, time) yes (by position and whole buffer tested against bacnet-stack)
Who-Is/I-Am, Who-Has/I-Have yes
AcknowledgeAlarm, GetEventInformation, GetAlarmSummary, event notifications yes
AtomicReadFile, AtomicWriteFile, AddListElement yes
DeviceCommunicationControl, ReinitializeDevice, TimeSynchronization, UTCTimeSynchronization yes
Segmentation, both directions, windowed Segment-ACKs (clause 5.4) yes (tested against BACpypes3 0.0.110 both ways, client and device role)
Errors, rejects and aborts as Go errors yes
Device role (device): the Device object and an object table; Who-Is, Who-Has; ReadProperty, ReadPropertyMultiple (array index, ALL, REQUIRED, OPTIONAL); WriteProperty, WritePropertyMultiple with priority arrays; SubscribeCOV with confirmed and unconfirmed notifications; segmented answers and requests; on its own B/IP socket or on a client's B/IP, B/IPv6 or BACnet/SC link yes (since v0.2.0; tested against BACpypes3's client)
Device role: ReadRange of trend logs, file access, alarms and events, DeviceCommunicationControl and ReinitializeDevice served, intrinsic reporting no (see Not yet)
MS/TP, Ethernet, ARCNET, LonTalk, PTP data links no (reach MS/TP devices through a BACnet router)

Security hooks: SCTLS takes the operational certificate and issuers, and optional hooks for a crypto policy (CheckCertificate), revocation (CheckRevocation) and TLS 1.3 cipher suites. Without them it makes the certificate checks of AB.7.4 only.

Choosing a BACnet library

Compared from each project's source at the version named, in October 2026. "Tested" means run against this module in the interop tests below. Check the projects themselves before relying on a row.

this module bacnet-stack 1.6.1 BACpypes3 0.0.110 alexbeltran/gobacnet (63505d3, 2024-03-16)
Language Go, no cgo C Python (asyncio) Go
Licence Apache-2.0 GPL-2.0 with the GCC linking exception (some files other licences) MIT GPL-2.0
Client yes yes (command-line tools and library) yes ReadProperty, ReadPropertyMultiple, Who-Is only
Device (server) side yes: properties, writes with priorities, COV, segmentation (no trend logs, files, alarms yet) yes yes no
Segmentation both ways (tested against BACpypes3) no state machine (the SEGMENT switch only changes what the device claims) yes no
Foreign device, BBMD both both (tested) both no
BACnet/IPv6 yes yes yes no
BACnet/SC hub connector, hub function, direct connections hub, node, direct connections (tested as hub) hub and direct connections over the websockets package no
Simulated device for tests yes (bacnet-sim) demo server sample applications no

Pick this module for a Go program that reads, writes and subscribes to BACnet devices, or serves points as a BACnet device, including over BACnet/SC, without cgo. Pick bacnet-stack or BACpypes3 when your device must serve trend logs, files, schedules or alarms, or needs MS/TP; bacnet-stack for C and embedded targets, BACpypes3 for Python. The Go packages found besides this one (gobacnet and its forks, for example NubeDev/bacnet) cover reading and discovery only and are GPL-2.0.

Install

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

Requires Go 1.27.1 or later (as tlsx does).

Quick start

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

c, err := bacnet.NewClient("0.0.0.0:0", slog.Default())
defer c.Close()
go c.Serve()
addr, _ := net.ResolveUDPAddr("udp", "192.0.2.10:47808")
t := bacnet.Target{Dest: bacnet.Dest{Addr: addr}, Peer: bacnet.Peer{MaxAPDU: 1476, RecvSeg: true}, Timeout: 3 * time.Second, Retries: 3}
v, err := c.ReadProperty(ctx, t, bacnet.ObjectID{Type: bacnet.AnalogInput, Instance: 1}, bacnet.PropPresentValue)
err = c.WriteProperty(ctx, t, bacnet.ObjectID{Type: bacnet.AnalogValue, Instance: 1}, bacnet.PropPresentValue, float32(21), 8)

Through a BBMD as a foreign device:

c.BBMD = bbmdAddr
err = c.RegisterForeign(ctx, 5*time.Minute, 3*time.Second, 2)

On BACnet/SC, a node connected to a hub:

n := &bacnet.SCNode{Creds: creds, Primary: "wss://hub.example:443", UUID: bacnet.NewUUID(), VMAC: bacnet.RandomVMAC(),
	MinReconnect: time.Second, MaxReconnect: 30 * time.Second, ConnectWait: 10 * time.Second, DisconnectWait: 5 * time.Second, Heartbeat: 5 * time.Minute}
c := bacnet.NewClientSC(n, slog.Default())
n.Start(ctx)

A device (v0.2.0):

d := device.New(device.Config{Instance: 4010, Name: "AHU-1", VendorID: 999})
d.AddObject(&device.Object{ID: bacnet.ObjectID{Type: bacnet.AnalogValue, Instance: 1}, Name: "Supply Setpoint",
	Commandable: true, Props: map[uint32]any{bacnet.PropPresentValue: float32(18), bacnet.PropUnits: bacnet.Enumerated(62)}})
d.Listen("0.0.0.0:47808")
d.Set(bacnet.ObjectID{Type: bacnet.AnalogValue, Instance: 1}, bacnet.PropPresentValue, float32(19)) // COV subscribers are told

The device tests (device/device_test.go) run it against this module's client. The runnable example in this module is ExampleEncodeReadProperty; bacnet-sim has a client example against the simulated device.

Documentation

API reference: https://pkg.go.dev/github.com/cB-Sigma/bacnet

Package What it does
bacnet (module root) the codec; Client over B/IP (NewClient), B/IPv6 (NewClient6) and BACnet/SC (NewClientSC); services, ReadRange, segmentation, BBMD state; BACnet/SC SCNode, SCHub, NodeSwitch, SCTLS
device the device role: New, Config, Device (AddObject, Set, Get, Listen, Attach, IAm, Handle, Close), Object, Error
interop (nested module, tests only) this module's client against bacnet-stack 1.6.1 in Docker; the client and the device role against BACpypes3 0.0.110 in Docker

The API is wide: SigmaM2M's adapter uses encoders, decoders and data link internals directly. Narrowing it is planned before v1.

Testing

go vet ./...
go test -race ./...

Tests carry // Covers: SIG-... comments: requirement IDs of the SigmaM2M project's compliance report, with no meaning outside it. Code comments that cite F- numbers refer to SigmaM2M's register of readings where the standard leaves a choice open; PROVENANCE.md explains them. The tests that drive the simulated device are in bacnet-sim, so this module does not depend on its simulator.

interop/ is a nested module with its own go.mod. It builds bacnet-stack 1.6.1 from its sources in a container (interop/peer; bacnet-stack is GPL and used only as a test peer, nothing of it is linked into this module) and runs this module against its demo server and BACnet/SC hub. The tests are skipped unless SIGMA_BACNET_INTEROP=1 is set and Docker is running:

cd interop && SIGMA_BACNET_INTEROP=1 go test -race -v ./...
Interop tested against

Run on 2026-10-11 on macOS with Docker Desktop; every item below passed.

bacnet-stack 1.6.1 (bacserv, BACnet/IP, its BBMD enabled), this module's client:

Area What was checked
ReadProperty device object-name and vendor-identifier, the 78-entry object-list, an analog input's present-value as REAL, an unknown object refused with object / unknown-object
ReadPropertyMultiple several properties of two objects in one request, an unknown property answered with its error in place
WriteProperty analog value at priority 8 and read back, relinquished with NULL, a wrong datatype refused
SubscribeCOV unconfirmed notifications: the initial one and the one after a write, with present-value and status-flags
ReadRange a trend log's log-buffer by position (5 records with their times) and whole (66 records, more-items set)
Foreign device Register-Foreign-Device accepted and renewed; Who-Is through Distribute-Broadcast-To-Network and a directed Who-Is, both answered by an I-Am that bacserv broadcasts and its BBMD forwards (device, max APDU 1476, no segmentation, vendor 260)
Segmentation only refusals: bacserv says it has none, and aborts a segmented request; the client reports the abort

bacnet-stack 1.6.1 (bacschub and a bacserv node, BACnet/SC), this module's hub connector and client: TLS 1.3 with certificates issued from bacnet-stack's test CA, Connect-Request and Accept, Who-Is broadcast through the hub and the I-Am from bacserv's VMAC, ReadProperty, WriteProperty and ReadPropertyMultiple through the hub.

Found on the way and fixed in this module (v0.1.0):

  • bacnet-stack 1.6.1's hub crashed (SIGSEGV) on the Hello header option this module puts in its Connect-Request. SCNode.NoHello leaves it out for such peers (test: TestSCNoHello); the default still sends it.
  • There was no constructor for a client over BACnet/SC; NewClientSC wires a node to a client.

Defects of the reference peer met on the way (not ours; recorded so nobody chases them): bacserv answers a 78-entry object-list unsegmented to a client that accepts only 50 octets; its BBMD distributes a broadcast from a device that has not registered instead of refusing it; with SEGMENT=true the device claims segmentation it does not have.

BACpypes3 0.0.110 (2026-10-12, python:3.12.10-slim in Docker Desktop; interop/bacpypes3_test.go, our scripts in interop/bacpypes3); every item passed:

Direction What was checked
BACpypes3's client, this module's device role the Device object's 405-entry object-list, sent in segments to a client taking 1024 octets; object-name; ReadPropertyMultiple of two objects; a write of 23.5 at priority 8 read back, and the 16-entry priority array; SubscribeCOV with unconfirmed notifications, the initial value and the change the device made
This module's client, a BACpypes3 device its 302-entry object-list and a ReadPropertyMultiple of 300 object names, both answered in segments; a ReadPropertyMultiple of 80 names and a WritePropertyMultiple of 40 values sent in segments (the peer stated to take 128 octets), the values read back

Not tested against an independent implementation:

  • The device role against bacnet-stack's client tools, and over BACnet/IPv6 and BACnet/SC (Attach) against another implementation (in process only).
  • This module's hub function with bacnet-stack's node: under Docker Desktop the node in its container never opened a connection to a hub on the host (the test is in interop/ and skipped by default). Direct connections, failover and key updates on BACnet/SC; BACnet/IPv6; the BBMD function; routing through a router; WritePropertyMultiple, SubscribeCOVProperty, alarm and event services, file access, device management services.
  • Real controllers and BMS head ends.
  • In process: the simulated device of bacnet-sim (same author, so not independent).

Not yet

What Why
The device role serving ReadRange of trend logs, AtomicRead/WriteFile, alarms and events (GetEventInformation, event notifications, intrinsic reporting), schedules, DeviceCommunicationControl and ReinitializeDevice SigmaM2M's BACnet adapter serves these from its own object store (same author); moving them into device is the next release
The device role as a router or BBMD the Client's BBMD function and routing exist; wiring them to a device port is planned
This module's BACnet/SC hub with bacnet-stack's node under Docker Desktop the node in its container never opened a connection to a hub on the host; hub and node are tested against each other in process (TestSCHubForwarding)
MS/TP, Ethernet, ARCNET, LonTalk, PTP MS/TP needs an RS-485 port; reach such devices through a BACnet router
Real controllers and BMS head ends needs hardware
  • bacnet-sim: a simulated BACnet/IP device, as a Go package and a command.
  • tlsx: the TLS 1.3 stack used for BACnet/SC.

Status

v0.x: the API may change before v1.

Contributing

See CONTRIBUTING.md.

Security

See SECURITY.md to report a vulnerability privately.

Licence

Apache-2.0 (see LICENSE and NOTICE). Copyright 2026 Abhinav Gautam. BACnet is a registered trademark of ASHRAE; this project is not affiliated with or endorsed by ASHRAE.

Documentation

Index

Examples

Constants

View Source
const (
	BVLCWriteBDT      = 0x01
	BVLCReadBDT       = 0x02
	BVLCReadBDTAck    = 0x03
	BVLCReadFDT       = 0x06
	BVLCReadFDTAck    = 0x07
	BVLCDeleteFDT     = 0x08
	ResultWriteBDTNAK = 0x0010
	ResultReadBDTNAK  = 0x0020
	ResultReadFDTNAK  = 0x0040
	ResultDeleteNAK   = 0x0050
)

BVLC functions of Annex J used only by BBMDs (J.2).

View Source
const (
	B6Result          = 0x00
	B6OriginalUnicast = 0x01
	B6OriginalBcast   = 0x02
	B6AddrRes         = 0x03
	B6FwdAddrRes      = 0x04
	B6AddrResACK      = 0x05
	B6VirtAddrRes     = 0x06
	B6VirtAddrResACK  = 0x07
	B6ForwardedNPDU   = 0x08
	B6RegisterFD      = 0x09
	B6DeleteFDTEntry  = 0x0a
	B6DistributeBcast = 0x0c
	R6OK              = 0x0000
	R6AddrResNAK      = 0x0030

	R6RegisterFDNAK = 0x0090
	R6DeleteFDTNAK  = 0x00a0
	R6DistributeNAK = 0x00c0

	B6AddrLen = 18 // IPv6 address and UDP port

)

BVLC functions and result codes of Annex U (Table U-1, U.2.1.1).

View Source
const (
	BVLCResult          = 0x00
	BVLCForwardedNPDU   = 0x04
	BVLCRegisterFD      = 0x05
	BVLCDistributeBcast = 0x09
	BVLCOriginalUnicast = 0x0a
	BVLCOriginalBcast   = 0x0b
)

BVLC functions (Annex J.2).

View Source
const (
	ResultOK            = 0x0000
	ResultRegisterFDNAK = 0x0030
	ResultDistributeNAK = 0x0060
)

BVLC-Result codes (Annex J.2.1) the IPE acts on.

View Source
const (
	NlWhoIsRouter = 0x00
	NlIAmRouter   = 0x01
)

Network layer message types (clause 6.2.4, 6.4).

View Source
const (
	PDUConfirmed   = 0x0
	PDUUnconfirmed = 0x1
	PDUSimpleACK   = 0x2
	PDUComplexACK  = 0x3
	PDUSegmentACK  = 0x4
	PDUError       = 0x5
	PDUReject      = 0x6
	PDUAbort       = 0x7
)

APDU types (clause 20.1), high nibble of the first octet.

View Source
const (
	SvcConfirmedCOV         = 1
	SvcSubscribeCOV         = 5
	SvcReadRange            = 26
	SvcReadProperty         = 12
	SvcReadPropertyMultiple = 14
	SvcWriteProperty        = 15
	SvcUnconfirmedCOV       = 2 // unconfirmed services
	SvcIAm                  = 0
	SvcWhoIs                = 8
)

Service choices (clause 21).

View Source
const (
	SegBoth     = 0
	SegTransmit = 1
	SegReceive  = 2
	SegNone     = 3
)

Segmentation support as I-Am states it (clause 21, BACnetSegmentation).

View Source
const (
	PropNumberOfStates   = 74
	PropOutOfService     = 81
	PropPresentValue     = 85
	PropStateText        = 110
	PropStatusFlags      = 111
	PropUnits            = 117
	PropLogBuffer        = 131
	PropRecordCount      = 141
	PropTotalRecordCount = 145
	PropPulseRate        = 186
	PropScale            = 187
)

Property identifiers used by the IPE.

View Source
const (
	AnalogInput  = 0
	AnalogOutput = 1
	AnalogValue  = 2
	BinaryInput  = 3
	BinaryOutput = 4
	BinaryValue  = 5
	// Multistate objects (clauses 12.18, 12.19, 12.20), the trend log
	// (12.25) and the accumulator (12.1).
	MultiStateInput  = 13
	MultiStateOutput = 14
	TrendLog         = 20
	MultiStateValue  = 19
	Accumulator      = 23
)

Object types the IPE maps.

View Source
const (
	TagSigned = 3

	TagCharString = 7

	TagDate     = 10
	TagTime     = 11
	TagObjectID = 12
)

Application tag numbers (clause 20.2.1.4).

View Source
const (
	MaxSegments = 64 // stated in requests as code 6
	MaxWindow   = 16 // the largest window the IPE accepts or proposes

)

Segmentation limits of the IPE as a requester.

View Source
const (
	AbortOther          = 0
	AbortBufferOverflow = 1

	AbortSegNotSupp = 4 // segmentation-not-supported
)

Abort reasons the IPE sends (clause 20.1.9, 21).

View Source
const (
	ErrClassServices           = 5
	ErrCodeUnknownSubscription = 79
)

Error class and code answered for a notification the IPE did not subscribe to: services (5), unknown-subscription (79).

View Source
const (
	RangeAll        = 0 // no range: every item
	RangeByPosition = 3
	RangeBySequence = 6
	RangeByTime     = 7
)

Range kinds of a ReadRange request: the context tag of the choice.

View Source
const (
	SCResult = 0x00

	SCAddrResolution = 0x02

	SCConnectRequest = 0x06
	SCConnectAccept  = 0x07
	SCDisconnectReq  = 0x08
	SCDisconnectACK  = 0x09
	SCHeartbeatReq   = 0x0a
	SCHeartbeatACK   = 0x0b
)

BVLC-SC functions (Table AB-1).

View Source
const (
	SCOptSecurePath = 1
	SCOptHello      = 2
	SCOptIdentity   = 3

	SCOptProprietary = 31
)

Header option types (Table AB-3, AB.2.3.1).

View Source
const (
	ErrClassCommunication       = 7
	ErrCodeOptionalNotSupported = 45

	ErrCodeBVLCFunctionUnknown = 143

	ErrCodeHeaderNotUnderstood = 146

	ErrCodeNodeDuplicateVMAC = 151

	ErrCodeWebsocketSchemeNotSupp = 166

	ErrCodeTLSError = 188
)

Error class and the error codes (clause 21, BACnetErrorCode) of BACnet/SC.

View Source
const (
	SCHubProtocol    = "hub.bsc.bacnet.org"
	SCDirectProtocol = "dc.bsc.bacnet.org"
)

WebSocket subprotocols (AB.7.1).

View Source
const (
	SCMaxNPDU = 1497
	SCMaxBVLC = 1497 + 4192 + 16
)

Sizes the IPE advertises: an NPDU of the largest APDU plus the longest NPDU header, and room for header options (AB.5.1 asks hubs for 1497 Octets of NPDU and 4192 of options).

View Source
const (
	SCNotConnected   = "not-connected"
	SCConnected      = "connected"
	SCDisconnectedEr = "disconnected-with-errors"
	SCFailed         = "failed-to-connect"
)

BACnetSCConnectionState names (clause 21).

View Source
const (
	SvcGetAlarmSummary      = 3
	SvcAtomicReadFile       = 6
	SvcAtomicWriteFile      = 7
	SvcAddListElement       = 8
	SvcWritePropertyMulti   = 16
	SvcDeviceCommControl    = 17
	SvcReinitializeDevice   = 20
	SvcSubscribeCOVProperty = 28
	SvcGetEventInformation  = 29

	SvcIHave          = 1 // unconfirmed
	SvcTimeSync       = 6 // unconfirmed
	SvcWhoHas         = 7 // unconfirmed
	SvcUTCTimeSync    = 9 // unconfirmed
	ObjNotificationCl = 15
	ObjFile           = 10
	ObjDevice         = 8
	PropRecipientList = 102
)

Service choices (clause 21).

View Source
const (
	DefaultPort = 47808
)
View Source
const RejectUnrecognizedService = 9

Reject reasons (clause 21, BACnetRejectReason) the IPE sends.

View Source
const SegTimeout = 2 * time.Second

SegTimeout is Tseg for received segments.

View Source
const SeqMax = 1<<32 - 1

Sequence numbers of log records count 1 to 2^32-1 and then start again at 1 (12.25.16).

View Source
const (
	SvcAcknowledgeAlarm = 0 // confirmed
)

Variables

View Source
var DCCStates = map[string]uint64{"enable": 0, "disable-initiation": 2}

DeviceCommunicationControl enable-disable values (16.1; disable (1) is deprecated).

View Source
var (
	EventStates = []string{"normal", "fault", "offnormal", "high-limit", "low-limit", "life-safety-alarm"}
)
View Source
var HubConnectorStates = [...]string{"no-hub-connection", "connected-to-primary", "connected-to-failover"}
View Source
var ReinitStates = map[string]uint64{"coldstart": 0, "warmstart": 1, "start-backup": 2, "end-backup": 3,
	"start-restore": 4, "end-restore": 5, "abort-restore": 6, "activate-changes": 7}

ReinitStates are the reinitialized-state-of-device values (16.4).

Functions

func AppValue

func AppValue(t Tag) (any, error)

AppValue decodes an application-tagged value (see enc.app for types). Types the IPE does not use come back as their raw octets.

func B6Addr

func B6Addr(a *net.UDPAddr) []byte

B6Addr is the 18-octet B/IPv6 address of a: IPv6 address then port.

func BDTBytes

func BDTBytes(bdt []BDTEntry) []byte

func BIPAddr

func BIPAddr(a *net.UDPAddr) []byte

BIPAddr is the six-octet B/IP address (Annex J.1.2) of an IPv4 address.

func BVLC

func BVLC(fn byte, payload []byte) []byte

BVLC builds a BVLL message without an NPDU (Register-Foreign-Device, BVLC-Result).

func Be16

func Be16(v uint16) []byte

func BeUnsigned

func BeUnsigned(d []byte) (uint64, error)

func BitContent

func BitContent(x BitString) []byte

BitContent is a bit string's content octets.

func ComplexACKSegment

func ComplexACKSegment(invokeID, service, seq, window byte, more bool, part []byte) []byte

ComplexACKSegment builds one segment of a segmented Complex-ACK.

func Confirmed

func Confirmed(invokeID, service byte, req []byte) []byte

Confirmed builds an unsegmented Confirmed-Request APDU. It accepts a segmented response of up to 64 segments of up to 1476 octets.

func ConfirmedSegment

func ConfirmedSegment(invokeID, service, seq, window byte, more bool, part []byte) []byte

ConfirmedSegment builds one segment of a segmented Confirmed-Request.

func DateTimeFrom

func DateTimeFrom(d, t []byte, loc *time.Location) (time.Time, error)

DateTimeFrom decodes an application Date and Time. Unspecified (0xff) fields are taken as zero; an unspecified year is an error.

func DecodeAtomicReadFileAck

func DecodeAtomicReadFileAck(b []byte) (fileRead, error)

func DecodeAtomicWriteFileAck

func DecodeAtomicWriteFileAck(b []byte) (int64, bool, error)

DecodeAtomicWriteFileAck is the start position or record the data was written at.

func DecodeIHave

func DecodeIHave(b []byte) (iHave, error)

func DecodeReadRangeAck

func DecodeReadRangeAck(b []byte, loc *time.Location) (rangeResult, error)

func DecodeResult

func DecodeResult(b []byte) scResultInfo

func DecodeWPMError

func DecodeWPMError(b []byte) error

func EncodeAbort

func EncodeAbort(invokeID, reason byte, srv bool) []byte

abortPDU builds an Abort; srv is set when a server sends it.

func EncodeAcknowledgeAlarm

func EncodeAcknowledgeAlarm(process uint32, o ObjectID, state uint32, stamp []byte, source string, at time.Time) []byte

EncodeAcknowledgeAlarm is the AcknowledgeAlarm request (13.5): stamp is the event's BACnetTimeStamp as the notification gave it; the time of acknowledgment is a date and time with an unspecified day of week.

func EncodeAddListElement

func EncodeAddListElement(o ObjectID, prop uint32, elements []byte) []byte

EncodeAddListElement adds elements (already encoded) to a list property.

func EncodeAtomicReadFile

func EncodeAtomicReadFile(file ObjectID, record bool, start int64, count uint64) []byte

EncodeAtomicReadFile reads count octets (stream) or records (record access) from start.

func EncodeAtomicWriteFile

func EncodeAtomicWriteFile(file ObjectID, start int64, data []byte, records [][]byte) []byte

EncodeAtomicWriteFile writes data at start (stream) or records at start (record access; -1 appends).

func EncodeBVLC6

func EncodeBVLC6(m BVLC6) []byte

func EncodeCOVNotification

func EncodeCOVNotification(n COVNotification, remaining uint32) ([]byte, error)

EncodeCOVNotification builds an UnconfirmedCOVNotification request.

func EncodeDCC

func EncodeDCC(minutes uint16, state uint64, password string) []byte

EncodeDCC is the DeviceCommunicationControl request; minutes 0 leaves the duration out (indefinite).

func EncodeDestination

func EncodeDestination(d Destination) []byte

EncodeDestination is the list element of AddListElement on Recipient_List.

func EncodeGetEventInformation

func EncodeGetEventInformation(last *ObjectID) []byte

EncodeGetEventInformation asks for the summaries after last (nil: from the start).

func EncodeIAm

func EncodeIAm(i IAm) []byte

func EncodeLogRecord

func EncodeLogRecord(r LogRecord, loc *time.Location) ([]byte, error)

EncodeLogRecord builds a BACnetLogRecord (for tests and the simulator).

func EncodeNPDU

func EncodeNPDU(fn byte, n NPDU) []byte

EncodeNPDU builds a BVLC frame of function fn around an NPDU. A Forwarded-NPDU carries n.origin; a destination gets n.hop as its hop Count.

func EncodeReadProperty

func EncodeReadProperty(o ObjectID, prop uint32) []byte

EncodeReadProperty is the ReadProperty request (clause 15.5).

Example

Build the BACnet/IP frame of a confirmed ReadProperty request for the present-value of analog input 1, and read it back. The client (bacnet.NewClient, Client.ReadProperty) sends such frames; bacnet-sim has a runnable client example against a simulated device.

package main

import (
	"fmt"

	"github.com/cB-Sigma/bacnet"
)

func main() {
	req := bacnet.EncodeReadProperty(bacnet.ObjectID{Type: bacnet.AnalogInput, Instance: 1}, bacnet.PropPresentValue)
	frame := bacnet.Frame(bacnet.Confirmed(1, bacnet.SvcReadProperty, req), true)
	fmt.Printf("% x\n", frame)

	apdu, err := bacnet.Unframe(frame)
	if err != nil {
		panic(err)
	}
	a, err := bacnet.ParseAPDU(apdu)
	fmt.Println(a.Service, err)
}
Output:
81 0a 00 11 01 04 02 65 01 0c 0c 00 00 00 01 19 55
12 <nil>

func EncodeReadPropertyMultiple

func EncodeReadPropertyMultiple(refs []PropRef) []byte

EncodeReadPropertyMultiple is the ReadPropertyMultiple request (clause 15.7), properties grouped by object in the order given.

func EncodeReadRange

func EncodeReadRange(o ObjectID, prop uint32, r ReadRange) []byte

EncodeReadRange is the ReadRange request.

func EncodeReinitialize

func EncodeReinitialize(state uint64, password string) []byte

func EncodeSubscribeCOVProperty

func EncodeSubscribeCOVProperty(process uint32, o ObjectID, confirmed bool, lifetime uint32, prop uint32, increment *float32) []byte

func EncodeTimeSync

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

EncodeTimeSync is the TimeSynchronization or UTCTimeSynchronization Request: a BACnetDateTime (the device's local time, or UTC).

func EncodeWhoHas

func EncodeWhoHas(low, high *uint32, name string, id *ObjectID) []byte

EncodeWhoHas asks for an object by name or identifier, optionally within a device instance range.

func EncodeWhoIs

func EncodeWhoIs(instance uint32) []byte

EncodeWhoIs is a Who-Is request (clause 16.10) for one device instance.

func EncodeWriteProperty

func EncodeWriteProperty(o ObjectID, prop uint32, value any, priority int) ([]byte, error)

EncodeWriteProperty is the WriteProperty request (clause 15.9); Priority 0 leaves the priority out.

func EncodeWritePropertyMultiple

func EncodeWritePropertyMultiple(ws []PropWrite) ([]byte, error)

EncodeWritePropertyMultiple groups consecutive writes to one object.

func EnumName

func EnumName(names []string, v uint32) string

func ErrorAPDU

func ErrorAPDU(id, svc byte, class, code uint32) []byte

ErrorAPDU builds an Error reply with an error class and code.

func ErrorFrom

func ErrorFrom(data []byte) error

ErrorFrom decodes the class and code of an Error APDU; for services whose error is constructed it takes the first two enumerations found.

func Frame

func Frame(apdu []byte, expectReply bool) []byte

Frame wraps an APDU in an NPDU without routing information and a BVLC Original-Unicast-NPDU header.

func FromResult6

func FromResult6(code uint16) uint16

FromResult6 maps an Annex U result code to the Annex J code the client expects for foreign-device registration and distribution; the others are kept apart.

func NPDUBytes

func NPDUBytes(n NPDU) []byte

NPDUBytes is the NPDU of clause 6.2 alone (version, control octet, DNET/DLEN/DADR, SNET/SLEN/SADR, hop count, message type and data), as every data link carries it.

func NewBBMD

func NewBBMD(bdt []BDTEntry, own int, accept bool, maxFD int) *bbmdState

func NewUUID

func NewUUID() [16]byte

NewUUID is a random (version 4) UUID.

func OwnEntry

func OwnEntry(bdt []BDTEntry, local *net.UDPAddr) (int, error)

OwnEntry finds this BBMD's entry in a BDT: the one with the socket's port whose address is the socket's or one of the host's.

func ParseUUID

func ParseUUID(s string) ([16]byte, error)

ParseUUID reads an RFC 4122 UUID in its text form.

func RawConstructed

func RawConstructed(b []byte, num byte) ([]byte, []byte, error)

RawConstructed returns the content between an opening tag and its closing tag, and what follows.

func RawPropertyValue

func RawPropertyValue(b []byte) ([]byte, error)

encodeReadPropertyRaw is ReadProperty; the ACK's value is taken raw (rawPropertyValue) for constructed types such as Recipient_List.

func ReplyLimit

func ReplyLimit(a APDU) int

ReplyLimit is the longest APDU the requester accepts.

func SegmentACK

func SegmentACK(invokeID, seq, window byte, nak, srv bool) []byte

SegmentACK builds a Segment-ACK; srv is set when a server sends it.

func SeqAdd

func SeqAdd(s, n uint64) uint64

SeqAdd is s advanced by n, wrapping after 2^32-1 to 1.

func SeqNext

func SeqNext(s uint64) uint64

func SequenceStamp

func SequenceStamp(seq uint64) []byte

SequenceStamp is a BACnetTimeStamp of the sequence-number choice.

func SignedBytes

func SignedBytes(v int64) []byte

func SkipConstructed

func SkipConstructed(b []byte, num byte) ([]byte, error)

func StampValue

func StampValue(raw []byte, loc *time.Location) any

StampValue turns a BACnetTimeStamp into a reading value.

func UUIDString

func UUIDString(u [16]byte) string

func Unframe

func Unframe(b []byte) ([]byte, error)

Unframe strips BVLC and NPDU, returning the APDU. Network-layer messages and BVLL messages without an APDU return nil, nil.

func ValuesUntilClose

func ValuesUntilClose(b []byte, num byte) ([]any, []byte, error)

ValuesUntilClose decodes application values up to the closing tag num, returning them and what follows the closing tag.

func WithPort

func WithPort(a string) string

Types

type APDU

type APDU struct {
	Typ      byte
	InvokeID byte
	Service  byte
	Data     []byte
	Reason   byte       // reject and abort reason
	Attrs    []SCOption // BACnet/SC data options (data attributes) of the request

	Seg, More bool // segmented, more follows
	Seq       byte // sequence number (segments, Segment-ACK)
	Window    byte // proposed (segments) or actual (Segment-ACK) window size
	NAK, Srv  bool // Segment-ACK and Abort flags
	Sa        bool // Confirmed-Request: segmented response accepted
	MaxResp   int  // Confirmed-Request: largest APDU the requester accepts
	MaxSegs   int  // Confirmed-Request: most segments the requester accepts (255: unspecified or more than 64)
}

APDU is a decoded APDU header with its service data.

func ParseAPDU

func ParseAPDU(b []byte) (APDU, error)

type AbortPDU

type AbortPDU struct{ Reason byte }

AbortPDU is a BACnet Abort reply.

func (*AbortPDU) Error

func (e *AbortPDU) Error() string

type AlarmSummary

type AlarmSummary struct {
	Object       ObjectID
	State        uint32
	Acked        BitString  // acknowledged-transitions
	Stamps       [][]byte   // GetEventInformation: the three time stamps as encoded
	Notify       *uint32    // GetEventInformation
	Enable       *BitString // GetEventInformation
	Priorities   []uint64   // GetEventInformation
	HasEventInfo bool
}

AlarmSummary is one entry of GetAlarmSummary-ACK or GetEventInformation-ACK.

func DecodeGetAlarmSummaryAck

func DecodeGetAlarmSummaryAck(b []byte) ([]AlarmSummary, error)

func DecodeGetEventInformationAck

func DecodeGetEventInformationAck(b []byte) ([]AlarmSummary, bool, error)

type BDTEntry

type BDTEntry struct {
	Addr *net.UDPAddr
	Mask [4]byte
}

BDTEntry is a BDT entry: a BBMD's B/IP address and its broadcast distribution mask (J.4.3.2).

func (BDTEntry) ForwardTo

func (e BDTEntry) ForwardTo() *net.UDPAddr

ForwardTo is where a Forwarded-NPDU for this entry goes: the inverted Mask ORed with the address (J.4.5), the BBMD itself for an all-ones Mask (two-hop) or the subnet's directed broadcast address (one-hop).

func (BDTEntry) TwoHop

func (e BDTEntry) TwoHop() bool

type BIP6

type BIP6 struct {
	Conn *net.UDPConn // unicast (and the group, when it shares the port)

	Group *net.UDPAddr // where broadcasts go (a multicast group)
	BBMD  *net.UDPAddr // foreign-device registration; nil for none

	Timeout time.Duration
	Log     *slog.Logger
	Deliver func(src net.Addr, n NPDU)
	Result  func(from *net.UDPAddr, code uint16)

	Mu      sync.Mutex
	Self    VMAC6
	Random  bool // self is a random instance VMAC
	ByVMAC  map[VMAC6]*net.UDPAddr
	ByAddr  map[string]VMAC6
	Learned chan struct{} // closed and replaced whenever the table changes
	Clash   chan struct{} // closed when another node answers for self
	// contains filtered or unexported fields
}

BIP6 is one B/IPv6 network port.

func (*BIP6) Broadcast

func (l *BIP6) Broadcast(np []byte) error

Broadcast sends an NPDU to every node: Original-Broadcast-NPDU to the Group, or Distribute-Broadcast-To-Network to the BBMD.

func (*BIP6) Claim

func (l *BIP6) Claim(ctx context.Context)

Claim checks that no other node answers for a random instance VMAC, choosing another when one does (H.7.2).

func (*BIP6) Close

func (l *BIP6) Close()

func (*BIP6) LocalAddr

func (l *BIP6) LocalAddr() *net.UDPAddr

func (*BIP6) LookupAddr

func (l *BIP6) LookupAddr(a *net.UDPAddr) (VMAC6, bool)

func (*BIP6) LookupVMAC

func (l *BIP6) LookupVMAC(v VMAC6) *net.UDPAddr

func (*BIP6) MyVMAC

func (l *BIP6) MyVMAC() VMAC6

func (*BIP6) Register

func (l *BIP6) Register(ttl uint16) error

Register sends Register-Foreign-Device to the BBMD.

func (*BIP6) Resolve

func (l *BIP6) Resolve(ctx context.Context, v VMAC6) (*net.UDPAddr, error)

Resolve is the B/IPv6 address of the node with VMAC v, found with Address-Resolution when it is not in the table.

func (*BIP6) Serve

func (l *BIP6) Serve()

Serve reads both sockets until they close.

func (*BIP6) Table

func (l *BIP6) Table() map[VMAC6]*net.UDPAddr

Table is the VMAC table, for Virtual_MAC_Address_Table.

func (*BIP6) Unicast

func (l *BIP6) Unicast(a *net.UDPAddr, np []byte) error

Unicast sends an NPDU to the node at a, learning its VMAC with Virtual-Address-Resolution first when it is not in the table; an NPDU whose destination cannot be translated is dropped (H.7.1).

type BVLC6

type BVLC6 struct {
	Fn     byte
	Src    VMAC6        // Source- or Original-Source-Virtual-Address
	Dst    VMAC6        // Destination- or Target-Virtual-Address
	Origin *net.UDPAddr // Original-Source-B/IPv6-Address (Forwarded-*), or the FDT entry
	Result uint16
	Ttl    uint16
	NPDU   []byte
}

BVLC6 is one decoded (or to be encoded) Annex U BVLL message.

func DecodeBVLC6

func DecodeBVLC6(b []byte) (BVLC6, error)

type BitString

type BitString struct {
	Len  int
	Bits []bool
}

BitString is an application-tagged bit string; bit 0 is the first bit.

func AllTransitions

func AllTransitions() BitString

func AllWeek

func AllWeek() BitString

type COVNotification

type COVNotification struct {
	Process uint32
	Device  ObjectID
	Object  ObjectID
	Values  map[uint32][]any
}

COVNotification is a decoded COV notification (clause 13.7 / 13.8).

func DecodeCOVNotification

func DecodeCOVNotification(b []byte) (COVNotification, error)

type Client

type Client struct {
	Conn          *net.UDPConn // BACnet/IP; nil over BACnet/SC
	SC            *SCNode      // BACnet/SC hub connector; nil over BACnet/IP
	IP6           *BIP6        // BACnet/IPv6 port; nil otherwise (bip6.go)
	Log           *slog.Logger
	OnUnconfirmed func(from Dest, a APDU)
	OnConfirmed   func(from Dest, a APDU) []byte // the reply to a device's confirmed request
	IAmLog        iAmLog                         // I-Ams while a discovery round runs
	Broadcast     *net.UDPAddr                   // local B/IP broadcast address; nil for none
	BBMD          *net.UDPAddr                   // BBMD to register with; nil for none
	BBMDRole      *bbmdState                     // this port's BBMD function (bbmd.go); nil for none
	// Fanout, when set, is the local subnet member by member: broadcasts
	// go to each instead of the broadcast address (hosts and tests
	// without IP broadcast).
	Fanout []*net.UDPAddr

	Mu sync.Mutex

	Pending    map[PendingKey]chan APDU
	Routers    map[uint16]net.Addr // discovered router per network
	RouterSeen chan struct{}       // closed and replaced on each I-Am-Router-To-Network
	Iams       map[uint32]chan IAm

	// MaxRespCode is the max-APDU-length-accepted code stated in our
	// requests (0: 5, 1476 octets).
	MaxRespCode byte
	Bindings    map[uint32]Dest // device instance to address, from the I-Ams heard
	Results     chan uint16     // BVLC-Result codes from the BBMD
	// contains filtered or unexported fields
}

Client is the driver's one UDP socket. Confirmed requests are matched to replies by invoke ID and the device's BACnet address (its B/IP address, or network number and MAC when routed); unconfirmed requests (COV notifications) go to onUnconfirmed. It finds routers with Who-Is-Router-To-Network and, with a BBMD configured, registers as a foreign device and broadcasts through the BBMD.

func NewClient

func NewClient(local string, log *slog.Logger) (*Client, error)

func NewClient6

func NewClient6(s *IPv6Settings, instance *uint32, timeout time.Duration, log *slog.Logger) (*Client, error)

NewClient6 is a client on a BACnet/IPv6 port whose VMAC is instance (random when nil).

func NewClientSC

func NewClientSC(n *SCNode, log *slog.Logger) *Client

NewClientSC is a client on the BACnet/SC network port n: the NPDUs n receives (with their data options) go to the client. Start n with n.Start after this call; Close closes n. Serve is not needed.

func (*Client) BroadcastNPDU

func (c *Client) BroadcastNPDU(n NPDU) error

BroadcastNPDU sends an NPDU to every device on the local network: through the BBMD when registered as a foreign device, else to the Broadcast address.

func (*Client) Close

func (c *Client) Close()

func (*Client) ForeignErr

func (c *Client) ForeignErr() error

ForeignErr is why the IPE is not (yet) a registered foreign device.

func (*Client) ReadMultiple

func (c *Client) ReadMultiple(ctx context.Context, t Target, refs []PropRef) ([]PropResult, error)

ReadMultiple reads several properties in one request.

func (*Client) ReadProperty

func (c *Client) ReadProperty(ctx context.Context, t Target, o ObjectID, prop uint32) ([]any, error)

ReadProperty reads one property.

func (*Client) ReadRange

func (c *Client) ReadRange(ctx context.Context, t Target, o ObjectID, prop uint32, r ReadRange) (rangeResult, error)

ReadRange reads items of a list property (a log buffer).

func (*Client) Receive

func (c *Client) Receive(src net.Addr, f NPDU)

Receive handles an NPDU from src, whichever data link it came over.

func (*Client) RegisterForeign

func (c *Client) RegisterForeign(ctx context.Context, ttl time.Duration, timeout time.Duration, retries int) error

RegisterForeign sends Register-Foreign-Device to the BBMD and waits for its BVLC-Result.

func (*Client) Request

func (c *Client) Request(ctx context.Context, t Target, service byte, data []byte) (APDU, error)

Request sends a confirmed request and waits for its reply, resending on Timeout up to retries more times. A request longer than the device's max APDU is segmented when the device accepts that; a segmented reply is acknowledged window by window and reassembled.

func (*Client) SendAPDU

func (c *Client) SendAPDU(to net.Addr, d Dest, expectReply bool, a []byte) error

SendAPDU sends an APDU to d through the data link address to (a B/IP address or a BACnet/SC VMAC).

func (*Client) Serve

func (c *Client) Serve()

Serve reads frames until the socket closes.

func (*Client) SubscribeCOV

func (c *Client) SubscribeCOV(ctx context.Context, t Target, process uint32, o ObjectID, confirmed bool, lifetime uint32) error

func (*Client) Unconfirmed

func (c *Client) Unconfirmed(ctx context.Context, t Target, svc byte, body []byte) error

Unconfirmed sends an unconfirmed request to the device.

func (*Client) WhoHas

func (c *Client) WhoHas(ctx context.Context, t Target, body []byte) ([]iHave, error)

WhoHas sends Who-Has to the device and collects the I-Haves that come back within the timeout.

func (*Client) WhoIs

func (c *Client) WhoIs(ctx context.Context, t Target, instance uint32) (IAm, error)

WhoIs asks one device for its I-Am (directed, not broadcast).

func (*Client) WriteMultiple

func (c *Client) WriteMultiple(ctx context.Context, t Target, ws []PropWrite) error

WriteMultiple sends the writes in one WritePropertyMultiple.

func (*Client) WriteProperty

func (c *Client) WriteProperty(ctx context.Context, t Target, o ObjectID, prop uint32, v any, prio int) error

type ContextValue

type ContextValue struct {
	Num  byte
	Data []byte
}

ContextValue is a primitive context-tagged value inside a property value (a CHOICE such as the accumulator's scale), left undecoded.

type Dest

type Dest struct {
	Addr net.Addr
	Net  uint16
	MAC  []byte
}

Dest is a device's BACnet address: a B/IP address (*net.UDPAddr) or a BACnet/SC VMAC on the local network, or a network number and MAC reached through the router at addr (nil until discovered).

func (Dest) Describe

func (d Dest) Describe() string

func (Dest) Key

func (d Dest) Key() string

Key identifies the device whatever path its replies take.

type Destination

type Destination struct {
	Days      BitString // valid-days, 7 bits from Monday
	From, To  [4]byte   // Time octets
	Device    *ObjectID // recipient: device, or
	Net       uint16    // address: network (0 local) and MAC
	MAC       []byte
	Process   uint32
	Confirmed bool
	Trans     BitString // to-offnormal, to-fault, to-normal
}

Destination is a BACnetDestination (clause 21) naming the IPE.

func DecodeDestinations

func DecodeDestinations(b []byte) ([]Destination, error)

DecodeDestinations reads the values of Recipient_List (as ValuesUntilClose left them flattened, re-read from raw octets).

type DirectConnect

type DirectConnect struct {
	Listen     string   `json:"listen,omitempty"`
	AcceptURIs []string `json:"acceptUris,omitempty"`
	Initiate   bool     `json:"initiate,omitempty"`
}

DirectConnect settings (12.56: SC_Direct_Connect_Initiate_Enable, SC_Direct_Connect_Accept_Enable, SC_Direct_Connect_Accept_URIs, SC_Direct_Connect_Binding).

type Enc

type Enc struct{ B []byte }

Enc builds tagged content.

func (*Enc) App

func (e *Enc) App(v any) error

App writes v as an application-tagged value. Go types map as: nil Null, bool Boolean, uint64/uint32/uint Unsigned, int64/int Signed, float32 Real, float64 Double, Enumerated, BitString, string CharacterString (UTF-8), ObjectID.

func (*Enc) Close

func (e *Enc) Close(num byte)

func (*Enc) CtxBool

func (e *Enc) CtxBool(num byte, v bool)

func (*Enc) CtxEnum

func (e *Enc) CtxEnum(num byte, v uint64)

func (*Enc) CtxObjectID

func (e *Enc) CtxObjectID(num byte, o ObjectID)

func (*Enc) CtxString

func (e *Enc) CtxString(num byte, s string)

func (*Enc) CtxUnsigned

func (e *Enc) CtxUnsigned(num byte, v uint64)

func (*Enc) Header

func (e *Enc) Header(num byte, context bool, n int)

Header writes a tag octet (clause 20.2.1) for content of length n.

func (*Enc) Octets

func (e *Enc) Octets(b []byte)

func (*Enc) Open

func (e *Enc) Open(num byte)

type Enumerated

type Enumerated uint32

Enumerated is an application-tagged enumerated value.

type ErrorPDU

type ErrorPDU struct{ Class, Code uint32 }

ErrorPDU is a BACnet Error reply (error class and code, clause 18).

func (*ErrorPDU) Error

func (e *ErrorPDU) Error() string

type EventNotification

type EventNotification struct {
	Process     uint32
	Device      ObjectID
	Object      ObjectID
	Stamp       []byte
	Class       uint64
	Priority    uint64
	EventType   uint32
	Text        string
	Notify      uint32
	ACKRequired *bool
	From        *uint32
	To          uint32
}

EventNotification is a decoded event notification (the request of 13.8 and 13.9, clause 21). stamp is the BACnetTimeStamp as encoded (inside its opening and closing tag 3), kept to echo in AcknowledgeAlarm.

func DecodeEventNotification

func DecodeEventNotification(b []byte) (EventNotification, error)

type IAm

type IAm struct {
	Device       ObjectID
	MaxAPDU      uint64
	Segmentation Enumerated
	Vendor       uint64
	// Irregular says what did not follow clause 16.10 (defaulted).
	Irregular string
}

IAm is a decoded I-Am request (clause 16.10).

func DecodeIAm

func DecodeIAm(b []byte) (IAm, error)

type IPv6Settings

type IPv6Settings struct {
	// Local is the unicast address to bind (default [::]:47808).
	Local string `json:"local,omitempty"`
	// Multicast is the B/IPv6 multicast address and port broadcasts go to
	// (default [FF02::BAC0]:47808, link-local scope).
	Multicast string `json:"multicast,omitempty"`
	// Interface is the network interface the group is joined on (needed
	// for link-local scope when the host has several).
	Interface string `json:"interface,omitempty"`
	// BBMD is a B/IPv6 BBMD to register with as a foreign device; its
	// time-to-live is bbmdTtl.
	BBMD string `json:"bbmd,omitempty"`
	// DeviceInstance is kind bacnet's VMAC (kind bacnet-server uses its
	// own); without it a random instance VMAC is used (H.7.2).
	DeviceInstance *uint32 `json:"deviceInstance,omitempty"`
	// contains filtered or unexported fields
}

IPv6Settings selects BACnet/IPv6 (Annex U) as the data link.

func (*IPv6Settings) BBMDAddr

func (s *IPv6Settings) BBMDAddr() *net.UDPAddr

BBMDAddr is the BBMD address resolved by Check; nil for none.

func (*IPv6Settings) Check

func (s *IPv6Settings) Check() error

func (*IPv6Settings) GroupAddr

func (s *IPv6Settings) GroupAddr() *net.UDPAddr

GroupAddr is the multicast group address resolved by Check.

func (*IPv6Settings) NetInterface

func (s *IPv6Settings) NetInterface() *net.Interface

NetInterface is the network interface resolved by Check; nil for none.

func (*IPv6Settings) SetFanout

func (s *IPv6Settings) SetFanout(addrs []*net.UDPAddr)

SetFanout makes broadcasts go to each of addrs instead of the multicast Group, which is then not joined (hosts and tests without multicast, such as Linux loopback).

type LogRecord

type LogRecord struct {
	At    time.Time
	Kind  string
	Value any
	Flags *BitString // status-flags, when the record has them
}

LogRecord is one record of a log buffer. kind names the log-datum choice: status, boolean, real, enumerated, unsigned, signed, bitstring, null, failure, time-change or any; value is its Go value (a BitString for status, bool, float32, Enumerated, uint64, int64, BitString, nil, an *ErrorPDU or float32 seconds for time-change; any is left out).

func DecodeLogRecord

func DecodeLogRecord(b []byte, loc *time.Location) (LogRecord, []byte, error)

DecodeLogRecord decodes a BACnetLogRecord after its timestamp's opening Tag.

type NPDU

type NPDU struct {
	Fn          byte         // BVLC function
	Origin      *net.UDPAddr // Forwarded-NPDU: the original B/IP source
	Result      uint16       // BVLC-Result code (fn == bvlcResult)
	ExpectReply bool
	Dnet        uint16 // 0: no destination specifier
	DADR        []byte
	Hop         byte
	Snet        uint16 // 0: no source specifier
	SADR        []byte
	NetMsg      bool
	MsgType     byte
	Data        []byte     // APDU, or the network message's content
	Opts        []SCOption // BACnet/SC data options that came with the NPDU
}

NPDU is a decoded BVLC frame and NPDU: the routing fields of clause 6.2, a network layer message (clause 6.4) or an APDU in data.

func DecodeFrame

func DecodeFrame(b []byte) (NPDU, error)

DecodeFrame decodes the BVLC header and the NPDU. BVLL functions that carry no NPDU (other than BVLC-Result) come back with their payload in data; hasNPDU tells them apart.

func DecodeNPDU

func DecodeNPDU(n NPDU, b []byte) (NPDU, error)

DecodeNPDU decodes the NPDU of clause 6.2 in b into n (whose BVLC fields are already set).

type NodeSwitch

type NodeSwitch struct {
	N        *SCNode
	Listen   string   // accept direct connections here ("" for no)
	URIs     []string // URIs advertised in Address-Resolution-ACK; default from the listener
	Initiate bool
	// Reconnect is the wait before trying a peer again after a failure
	// (the minimum reconnect time, AB.4).
	Reconnect time.Duration

	Mu sync.Mutex

	Conns map[VMAC]*dcConn
	// contains filtered or unexported fields
}

NodeSwitch keeps a node's direct connections.

func (*NodeSwitch) AcceptURIs

func (s *NodeSwitch) AcceptURIs() []string

AcceptURIs are the URIs sent in Address-Resolution-ACK.

func (*NodeSwitch) Connected

func (s *NodeSwitch) Connected(v VMAC) bool

Connected reports whether a direct connection to v is established.

type ObjectID

type ObjectID struct {
	Type     uint16
	Instance uint32
}

ObjectID names one object in a device.

func ObjectIDFrom

func ObjectIDFrom(v uint32) ObjectID

type Peer

type Peer struct {
	MaxAPDU int
	RecvSeg bool
}

Peer is what the device accepts: its largest APDU and whether it takes segmented requests.

type Peer6

type Peer6 struct {
	UDP  *net.UDPAddr
	VMAC VMAC6
}

Peer6 is a B/IPv6 node as the network layer sees it: its VMAC, and the B/IPv6 address it was heard from. It names the node by that address, as a configured device address does.

func (Peer6) Network

func (p Peer6) Network() string

func (Peer6) String

func (p Peer6) String() string

type PendingKey

type PendingKey struct {
	Addr string
	ID   byte
}

type PropRef

type PropRef struct {
	Object ObjectID
	Prop   uint32
}

PropRef names one property of one object.

type PropResult

type PropResult struct {
	PropRef
	Values []any
	Err    error
}

PropResult is one property's value or error.

func DecodeReadPropertyAck

func DecodeReadPropertyAck(b []byte) (PropResult, error)

func DecodeReadPropertyMultipleAck

func DecodeReadPropertyMultipleAck(b []byte) ([]PropResult, error)

type PropWrite

type PropWrite struct {
	Object   ObjectID
	Prop     uint32
	Value    any
	Priority int
}

PropWrite is one property value of a WriteAccessSpecification.

type ReadRange

type ReadRange struct {
	Kind  byte
	Ref   uint64
	At    time.Time
	Loc   *time.Location
	Count int32
}

ReadRange is the range of a ReadRange request. ref is the reference index (by position) or sequence number; at is the reference time (by time, in the device's time zone loc); a negative count reads backwards.

type RejectPDU

type RejectPDU struct{ Reason byte }

RejectPDU is a BACnet Reject reply.

func (*RejectPDU) Error

func (e *RejectPDU) Error() string

type SCConn

type SCConn struct {
	WS  *websocket.Conn
	TLS *tlsx.Conn // for key updates; nil when not known

	URI string

	KaHeartbeats atomic.Int64 // Heartbeat-Requests sent before key updates on an idle connection
	// contains filtered or unexported fields
}

SCConn is one BACnet/SC connection over a secure WebSocket.

func (*SCConn) Read

func (c *SCConn) Read(ctx context.Context) ([]byte, error)

Read returns the next BVLC message's octets. A non-binary frame closes the connection with 1003 (AB.7.5.3).

func (*SCConn) Send

func (c *SCConn) Send(ctx context.Context, m SCMsg) error

type SCConnStatus

type SCConnStatus struct {
	State        string    `json:"connectionState"`
	Connected    time.Time `json:"connectTimestamp,omitzero"`
	Disconnected time.Time `json:"disconnectTimestamp,omitzero"`
	ErrorCode    uint16    `json:"errorCode,omitempty"`
	Error        string    `json:"errorDetails,omitempty"`
}

SCConnStatus mirrors BACnetSCHubConnection (clause 21): the state of a hub connection, when it last connected and disconnected, and the last error.

type SCConnect

type SCConnect struct {
	VMAC    VMAC
	UUID    [16]byte
	MaxBVLC uint16
	MaxNPDU uint16
}

SCConnect is the payload of Connect-Request and Connect-Accept (AB.2.10, AB.2.11).

func DecodeConnect

func DecodeConnect(b []byte) (SCConnect, error)

func (SCConnect) Bytes

func (c SCConnect) Bytes() []byte

type SCFailedRequest

type SCFailedRequest struct {
	Time      time.Time `json:"timestamp"`
	Peer      string    `json:"peerAddress"`
	VMAC      string    `json:"peerVmac,omitempty"`
	UUID      string    `json:"peerUuid,omitempty"`
	ErrorCode uint16    `json:"errorCode"`
	Error     string    `json:"errorDetails,omitempty"`
}

SCFailedRequest mirrors BACnetSCFailedConnectionRequest (clause 21).

type SCHub

type SCHub struct {
	VMAC VMAC     // of the network port holding the hub (sent in Connect-Accept)
	UUID [16]byte // of the device holding the hub

	Mu sync.Mutex

	Failed []SCFailedRequest // SC_Failed_Connection_Requests (12.56.99), newest last

	Forwarded atomic.Int64 // messages forwarded
	// contains filtered or unexported fields
}

SCHub is a hub function.

func NewHub

func NewHub(log *slog.Logger, creds *SCTLS, vmac VMAC, uuid [16]byte, connectWait time.Duration) *SCHub

func (*SCHub) Close

func (h *SCHub) Close()

func (*SCHub) Connections

func (h *SCHub) Connections() []SCHubConn

Connections is SC_Hub_Function_Connection_Status (12.56).

func (*SCHub) Listen

func (h *SCHub) Listen(addr string) (net.Addr, error)

Listen serves the hub function on addr (TLS 1.3 with mutual authentication) until close.

func (*SCHub) ServeHTTP

func (h *SCHub) ServeHTTP(w http.ResponseWriter, r *http.Request)

ServeHTTP accepts one hub connection.

type SCHubConn

type SCHubConn struct {
	State     string    `json:"connectionState"`
	Connected time.Time `json:"connectTimestamp"`
	Peer      string    `json:"peerAddress"`
	VMAC      string    `json:"peerVmac"`
	UUID      string    `json:"peerUuid"`
}

SCHubConn mirrors BACnetSCHubFunctionConnection (clause 21).

type SCMsg

type SCMsg struct {
	Fn byte
	ID uint16

	DestOpts []SCOption

	Payload []byte
	// contains filtered or unexported fields
}

SCMsg is a BVLC-SC message (Table AB-2). orig and dest are nil when absent.

func DecodeSC

func DecodeSC(b []byte) (SCMsg, *scNAK)

DecodeSC decodes and checks a BVLC-SC message (AB.2, AB.3.1.5). On an error the partly decoded message (function, ID and addresses, when read) comes back with it so a NAK can be addressed.

func (SCMsg) Encode

func (m SCMsg) Encode() []byte

Encode is the message's octets (AB.2.1). Empty option lists are left Out.

type SCNode

type SCNode struct {
	Log            *slog.Logger
	Creds          *SCTLS
	Primary        string
	Failover       string
	UUID           [16]byte
	MinReconnect   time.Duration
	MaxReconnect   time.Duration
	ConnectWait    time.Duration
	DisconnectWait time.Duration
	Heartbeat      time.Duration
	KeyUpdate      time.Duration
	OnNPDU         func(from VMAC, npdu []byte, dataOpts []SCOption)
	OnChange       func()      // hub connector state changed
	Dc             *NodeSwitch // direct connections (scdirect.go); nil for none
	// DataOpts are the data options sent with every NPDU this node
	// originates (AB.2.3: Secure Path, Identity, proprietary).
	DataOpts []SCOption
	// NoHello leaves the Hello header option out of this node's
	// Connect-Request, for hubs and nodes written to an edition of the
	// standard before 2024 that do not skip it (bacnet-stack 1.6.1's hub
	// crashed on it).
	NoHello bool

	Mu   sync.Mutex
	VMAC VMAC
	Conn *SCConn

	RxResult []scResultInfo // BVLC-Results received, newest last (bounded)
	// contains filtered or unexported fields
}

SCNode is the IPE's BACnet/SC network port.

func (*SCNode) Broadcast

func (n *SCNode) Broadcast(npdu []byte) error

Broadcast sends an NPDU to every node of the network through the hub.

func (*SCNode) Close

func (n *SCNode) Close()

func (*SCNode) MyVMAC

func (n *SCNode) MyVMAC() VMAC

func (*SCNode) Start

func (n *SCNode) Start(ctx context.Context)

Start runs the hub connector until close.

func (*SCNode) State

func (n *SCNode) State() SCStatus

func (*SCNode) Unicast

func (n *SCNode) Unicast(to VMAC, npdu []byte) error

Unicast sends an NPDU to a node through the hub (AB.3.4).

type SCOption

type SCOption struct {
	Typ     byte
	Flag    bool
	HasData bool
	Data    []byte
}

SCOption is one header option (AB.2.3). flag is bit 6 of the marker: 'Must Understand' for a destination option, 'Every Segment' for a data option. hasData says whether 'Header Length' and 'Header Data' follow.

type SCStatus

type SCStatus struct {
	HubConnectorState string        `json:"hubConnectorState"`
	Primary           SCConnStatus  `json:"primaryHubConnectionStatus"`
	Failover          *SCConnStatus `json:"failoverHubConnectionStatus,omitempty"`
	VMAC              string        `json:"vmac"`
	UUID              string        `json:"deviceUuid"`
}

SCStatus is the hub connector's state as the Network Port object States it (12.56: SC_Hub_Connector_State, SC_Primary_Hub_Connection_Status, SC_Failover_Hub_Connection_Status) with the node's VMAC and UUID.

type SCTLS

type SCTLS struct {
	Certificate tlsx.Certificate    // the operational certificate and its key
	Issuers     []*x509.Certificate // the issuer certificates peers must be signed by
	// VerifyHostname additionally checks the hub's certificate against
	// the host of its URI (an installation option; off by default as
	// AB.7.4 requires).
	VerifyHostname bool
	// Now is the clock for validity checks; nil is time.Now.
	Now func() time.Time
	// CheckCertificate, when set, judges a peer certificate under the
	// application's crypto policy (use is "peer certificate"); an error
	// refuses it.
	CheckCertificate func(use string, c *x509.Certificate) error
	// CheckRevocation, when set, is called for a peer certificate that is
	// directly signed by issuer (AB.7.4 (c): revocation is a local
	// matter). An error refuses the certificate.
	CheckRevocation func(ctx context.Context, leaf, issuer *x509.Certificate) error
	// TLS13CipherSuites, when set and returning a non-empty list,
	// restricts the TLS 1.3 cipher suites; it is asked each time a
	// configuration is made.
	TLS13CipherSuites func() []uint16
}

SCTLS is a BACnet/SC node's operational credentials (AB.7.4.1.1) and the checks it makes of its peers. The hooks are optional: an application puts its crypto policy, revocation checks and cipher suite restrictions there; without them only the checks of AB.7.4 (a) to (d) are made and tlsx's TLS 1.3 suites are offered.

func (*SCTLS) Config

func (s *SCTLS) Config(server bool, serverName string) *tlsx.Config

Config is the TLS configuration for one side: client for the hub connector (serverName is the URI's host), server for the hub function.

func (*SCTLS) VerifyPeer

func (s *SCTLS) VerifyPeer(raw [][]byte) (*x509.Certificate, error)

VerifyPeer is the mutual authentication of AB.7.4 (a) to (d): well-formed, active now and not expired, and directly signed by one of the issuer certificates (the signature checks with its public key). Revocation (a local matter in AB.7.4) is checked with CheckRevocation.

type Tag

type Tag struct {
	Num     byte
	Context bool
	Open    bool
	Close   bool
	Lvt     uint32 // length, or the value of an application boolean
	Data    []byte
}

Tag is one decoded tag with its content.

func ReadTag

func ReadTag(b []byte) (Tag, []byte, error)

ReadTag decodes one tag and its content from b.

type Target

type Target struct {
	Dest
	Peer
	Timeout time.Duration
	Retries int
}

Target is everything a confirmed request needs to reach a device.

type VMAC

type VMAC [6]byte

VMAC is a BACnet/SC node's 6-octet virtual MAC address (AB.1.5.2, H.7.3). It is a net.Addr so it can stand where a B/IP address does.

func ParseVMAC

func ParseVMAC(s string) (VMAC, error)

ParseVMAC reads 12 hex digits (colons or dashes allowed between octets). The broadcast and all-zero VMACs are not node addresses.

func RandomVMAC

func RandomVMAC() VMAC

RandomVMAC is a Random-48 VMAC (H.7.3): the low four bits of the first octet are B'0010', the other 44 bits random.

func (VMAC) Network

func (v VMAC) Network() string

func (VMAC) String

func (v VMAC) String() string

type VMAC6

type VMAC6 [3]byte

VMAC6 is a B/IPv6 node's 3-octet VMAC (H.7.2).

func RandomInstanceVMAC

func RandomInstanceVMAC() VMAC6

RandomInstanceVMAC is a random instance VMAC: B'01' then 22 random bits.

func VMACOfInstance

func VMACOfInstance(i uint32) VMAC6

VMACOfInstance is the device instance as a VMAC: three octets, high order first, the top two bits zero.

func (VMAC6) Instance

func (v VMAC6) Instance() uint32

Instance is the device instance (or random instance) the VMAC carries.

func (VMAC6) Network

func (v VMAC6) Network() string

func (VMAC6) String

func (v VMAC6) String() string

type WPMError

type WPMError struct {
	ErrorPDU
	Object ObjectID
	Prop   uint32
}

WPMError is the first failed write of a WritePropertyMultiple-Error (clause 21): the error and the object and property it failed on.

func (*WPMError) Error

func (e *WPMError) Error() string

Directories

Path Synopsis
Package device is the BACnet device (server) role over BACnet/IP: a Device object and an object table served to other BACnet clients with Who-Is and Who-Has, ReadProperty and ReadPropertyMultiple (array indexes, ALL, REQUIRED and OPTIONAL), WriteProperty and WritePropertyMultiple (priority arrays of commandable objects), SubscribeCOV with confirmed and unconfirmed notifications and lifetimes, and segmentation of answers and of requests (clause 5.4).
Package device is the BACnet device (server) role over BACnet/IP: a Device object and an object table served to other BACnet clients with Who-Is and Who-Has, ReadProperty and ReadPropertyMultiple (array indexes, ALL, REQUIRED and OPTIONAL), WriteProperty and WritePropertyMultiple (priority arrays of commandable objects), SubscribeCOV with confirmed and unconfirmed notifications and lifetimes, and segmentation of answers and of requests (clause 5.4).

Jump to

Keyboard shortcuts

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