Documentation
¶
Index ¶
- Constants
- Variables
- func AppValue(t Tag) (any, error)
- func B6Addr(a *net.UDPAddr) []byte
- func BDTBytes(bdt []BDTEntry) []byte
- func BIPAddr(a *net.UDPAddr) []byte
- func BVLC(fn byte, payload []byte) []byte
- func Be16(v uint16) []byte
- func BeUnsigned(d []byte) (uint64, error)
- func BitContent(x BitString) []byte
- func ComplexACKSegment(invokeID, service, seq, window byte, more bool, part []byte) []byte
- func Confirmed(invokeID, service byte, req []byte) []byte
- func ConfirmedSegment(invokeID, service, seq, window byte, more bool, part []byte) []byte
- func DateTimeFrom(d, t []byte, loc *time.Location) (time.Time, error)
- func DecodeAtomicReadFileAck(b []byte) (fileRead, error)
- func DecodeAtomicWriteFileAck(b []byte) (int64, bool, error)
- func DecodeIHave(b []byte) (iHave, error)
- func DecodeReadRangeAck(b []byte, loc *time.Location) (rangeResult, error)
- func DecodeResult(b []byte) scResultInfo
- func DecodeWPMError(b []byte) error
- func EncodeAbort(invokeID, reason byte, srv bool) []byte
- func EncodeAcknowledgeAlarm(process uint32, o ObjectID, state uint32, stamp []byte, source string, ...) []byte
- func EncodeAddListElement(o ObjectID, prop uint32, elements []byte) []byte
- func EncodeAtomicReadFile(file ObjectID, record bool, start int64, count uint64) []byte
- func EncodeAtomicWriteFile(file ObjectID, start int64, data []byte, records [][]byte) []byte
- func EncodeBVLC6(m BVLC6) []byte
- func EncodeCOVNotification(n COVNotification, remaining uint32) ([]byte, error)
- func EncodeDCC(minutes uint16, state uint64, password string) []byte
- func EncodeDestination(d Destination) []byte
- func EncodeGetEventInformation(last *ObjectID) []byte
- func EncodeIAm(i IAm) []byte
- func EncodeLogRecord(r LogRecord, loc *time.Location) ([]byte, error)
- func EncodeNPDU(fn byte, n NPDU) []byte
- func EncodeReadProperty(o ObjectID, prop uint32) []byte
- func EncodeReadPropertyMultiple(refs []PropRef) []byte
- func EncodeReadRange(o ObjectID, prop uint32, r ReadRange) []byte
- func EncodeReinitialize(state uint64, password string) []byte
- func EncodeSubscribeCOVProperty(process uint32, o ObjectID, confirmed bool, lifetime uint32, prop uint32, ...) []byte
- func EncodeTimeSync(t time.Time, loc *time.Location) []byte
- func EncodeWhoHas(low, high *uint32, name string, id *ObjectID) []byte
- func EncodeWhoIs(instance uint32) []byte
- func EncodeWriteProperty(o ObjectID, prop uint32, value any, priority int) ([]byte, error)
- func EncodeWritePropertyMultiple(ws []PropWrite) ([]byte, error)
- func EnumName(names []string, v uint32) string
- func ErrorAPDU(id, svc byte, class, code uint32) []byte
- func ErrorFrom(data []byte) error
- func Frame(apdu []byte, expectReply bool) []byte
- func FromResult6(code uint16) uint16
- func NPDUBytes(n NPDU) []byte
- func NewBBMD(bdt []BDTEntry, own int, accept bool, maxFD int) *bbmdState
- func NewUUID() [16]byte
- func OwnEntry(bdt []BDTEntry, local *net.UDPAddr) (int, error)
- func ParseUUID(s string) ([16]byte, error)
- func RawConstructed(b []byte, num byte) ([]byte, []byte, error)
- func RawPropertyValue(b []byte) ([]byte, error)
- func ReplyLimit(a APDU) int
- func SegmentACK(invokeID, seq, window byte, nak, srv bool) []byte
- func SeqAdd(s, n uint64) uint64
- func SeqNext(s uint64) uint64
- func SequenceStamp(seq uint64) []byte
- func SignedBytes(v int64) []byte
- func SkipConstructed(b []byte, num byte) ([]byte, error)
- func StampValue(raw []byte, loc *time.Location) any
- func UUIDString(u [16]byte) string
- func Unframe(b []byte) ([]byte, error)
- func ValuesUntilClose(b []byte, num byte) ([]any, []byte, error)
- func WithPort(a string) string
- type APDU
- type AbortPDU
- type AlarmSummary
- type BDTEntry
- type BIP6
- func (l *BIP6) Broadcast(np []byte) error
- func (l *BIP6) Claim(ctx context.Context)
- func (l *BIP6) Close()
- func (l *BIP6) LocalAddr() *net.UDPAddr
- func (l *BIP6) LookupAddr(a *net.UDPAddr) (VMAC6, bool)
- func (l *BIP6) LookupVMAC(v VMAC6) *net.UDPAddr
- func (l *BIP6) MyVMAC() VMAC6
- func (l *BIP6) Register(ttl uint16) error
- func (l *BIP6) Resolve(ctx context.Context, v VMAC6) (*net.UDPAddr, error)
- func (l *BIP6) Serve()
- func (l *BIP6) Table() map[VMAC6]*net.UDPAddr
- func (l *BIP6) Unicast(a *net.UDPAddr, np []byte) error
- type BVLC6
- type BitString
- type COVNotification
- type Client
- func (c *Client) BroadcastNPDU(n NPDU) error
- func (c *Client) Close()
- func (c *Client) ForeignErr() error
- func (c *Client) ReadMultiple(ctx context.Context, t Target, refs []PropRef) ([]PropResult, error)
- func (c *Client) ReadProperty(ctx context.Context, t Target, o ObjectID, prop uint32) ([]any, error)
- func (c *Client) ReadRange(ctx context.Context, t Target, o ObjectID, prop uint32, r ReadRange) (rangeResult, error)
- func (c *Client) Receive(src net.Addr, f NPDU)
- func (c *Client) RegisterForeign(ctx context.Context, ttl time.Duration, timeout time.Duration, retries int) error
- func (c *Client) Request(ctx context.Context, t Target, service byte, data []byte) (APDU, error)
- func (c *Client) SendAPDU(to net.Addr, d Dest, expectReply bool, a []byte) error
- func (c *Client) Serve()
- func (c *Client) SubscribeCOV(ctx context.Context, t Target, process uint32, o ObjectID, confirmed bool, ...) error
- func (c *Client) Unconfirmed(ctx context.Context, t Target, svc byte, body []byte) error
- func (c *Client) WhoHas(ctx context.Context, t Target, body []byte) ([]iHave, error)
- func (c *Client) WhoIs(ctx context.Context, t Target, instance uint32) (IAm, error)
- func (c *Client) WriteMultiple(ctx context.Context, t Target, ws []PropWrite) error
- func (c *Client) WriteProperty(ctx context.Context, t Target, o ObjectID, prop uint32, v any, prio int) error
- type ContextValue
- type Dest
- type Destination
- type DirectConnect
- type Enc
- func (e *Enc) App(v any) error
- func (e *Enc) Close(num byte)
- func (e *Enc) CtxBool(num byte, v bool)
- func (e *Enc) CtxEnum(num byte, v uint64)
- func (e *Enc) CtxObjectID(num byte, o ObjectID)
- func (e *Enc) CtxString(num byte, s string)
- func (e *Enc) CtxUnsigned(num byte, v uint64)
- func (e *Enc) Header(num byte, context bool, n int)
- func (e *Enc) Octets(b []byte)
- func (e *Enc) Open(num byte)
- type Enumerated
- type ErrorPDU
- type EventNotification
- type IAm
- type IPv6Settings
- type LogRecord
- type NPDU
- type NodeSwitch
- type ObjectID
- type Peer
- type Peer6
- type PendingKey
- type PropRef
- type PropResult
- type PropWrite
- type ReadRange
- type RejectPDU
- type SCConn
- type SCConnStatus
- type SCConnect
- type SCFailedRequest
- type SCHub
- type SCHubConn
- type SCMsg
- type SCNode
- type SCOption
- type SCStatus
- type SCTLS
- type Tag
- type Target
- type VMAC
- type VMAC6
- type WPMError
Examples ¶
Constants ¶
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).
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).
const ( BVLCResult = 0x00 BVLCForwardedNPDU = 0x04 BVLCRegisterFD = 0x05 BVLCDistributeBcast = 0x09 BVLCOriginalUnicast = 0x0a BVLCOriginalBcast = 0x0b )
BVLC functions (Annex J.2).
const ( ResultOK = 0x0000 ResultRegisterFDNAK = 0x0030 ResultDistributeNAK = 0x0060 )
BVLC-Result codes (Annex J.2.1) the IPE acts on.
const ( NlWhoIsRouter = 0x00 NlIAmRouter = 0x01 )
Network layer message types (clause 6.2.4, 6.4).
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.
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).
const ( SegBoth = 0 SegTransmit = 1 SegReceive = 2 SegNone = 3 )
Segmentation support as I-Am states it (clause 21, BACnetSegmentation).
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.
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.
const ( TagSigned = 3 TagCharString = 7 TagDate = 10 TagTime = 11 TagObjectID = 12 )
Application tag numbers (clause 20.2.1.4).
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.
const ( AbortOther = 0 AbortBufferOverflow = 1 AbortSegNotSupp = 4 // segmentation-not-supported )
Abort reasons the IPE sends (clause 20.1.9, 21).
const ( ErrClassServices = 5 ErrCodeUnknownSubscription = 79 )
Error class and code answered for a notification the IPE did not subscribe to: services (5), unknown-subscription (79).
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.
const ( SCResult = 0x00 SCAddrResolution = 0x02 SCConnectRequest = 0x06 SCConnectAccept = 0x07 SCDisconnectReq = 0x08 SCDisconnectACK = 0x09 SCHeartbeatReq = 0x0a SCHeartbeatACK = 0x0b )
BVLC-SC functions (Table AB-1).
const ( SCOptSecurePath = 1 SCOptHello = 2 SCOptIdentity = 3 SCOptProprietary = 31 )
Header option types (Table AB-3, AB.2.3.1).
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.
const ( SCHubProtocol = "hub.bsc.bacnet.org" SCDirectProtocol = "dc.bsc.bacnet.org" )
WebSocket subprotocols (AB.7.1).
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).
const ( SCNotConnected = "not-connected" SCConnected = "connected" SCDisconnectedEr = "disconnected-with-errors" SCFailed = "failed-to-connect" )
BACnetSCConnectionState names (clause 21).
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).
const (
DefaultPort = 47808
)
const RejectUnrecognizedService = 9
Reject reasons (clause 21, BACnetRejectReason) the IPE sends.
const SegTimeout = 2 * time.Second
SegTimeout is Tseg for received segments.
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).
const (
SvcAcknowledgeAlarm = 0 // confirmed
)
Variables ¶
var DCCStates = map[string]uint64{"enable": 0, "disable-initiation": 2}
DeviceCommunicationControl enable-disable values (16.1; disable (1) is deprecated).
var (
EventStates = []string{"normal", "fault", "offnormal", "high-limit", "low-limit", "life-safety-alarm"}
)
var HubConnectorStates = [...]string{"no-hub-connection", "connected-to-primary", "connected-to-failover"}
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 ¶
AppValue decodes an application-tagged value (see enc.app for types). Types the IPE does not use come back as their raw octets.
func BeUnsigned ¶
func ComplexACKSegment ¶
ComplexACKSegment builds one segment of a segmented Complex-ACK.
func Confirmed ¶
Confirmed builds an unsegmented Confirmed-Request APDU. It accepts a segmented response of up to 64 segments of up to 1476 octets.
func ConfirmedSegment ¶
ConfirmedSegment builds one segment of a segmented Confirmed-Request.
func DateTimeFrom ¶
DateTimeFrom decodes an application Date and Time. Unspecified (0xff) fields are taken as zero; an unspecified year is an error.
func DecodeAtomicReadFileAck ¶
func DecodeAtomicWriteFileAck ¶
DecodeAtomicWriteFileAck is the start position or record the data was written at.
func DecodeIHave ¶
func DecodeReadRangeAck ¶
func DecodeResult ¶
func DecodeResult(b []byte) scResultInfo
func DecodeWPMError ¶
func EncodeAbort ¶
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 ¶
EncodeAddListElement adds elements (already encoded) to a list property.
func EncodeAtomicReadFile ¶
EncodeAtomicReadFile reads count octets (stream) or records (record access) from start.
func EncodeAtomicWriteFile ¶
EncodeAtomicWriteFile writes data at start (stream) or records at start (record access; -1 appends).
func EncodeBVLC6 ¶
func EncodeCOVNotification ¶
func EncodeCOVNotification(n COVNotification, remaining uint32) ([]byte, error)
EncodeCOVNotification builds an UnconfirmedCOVNotification request.
func EncodeDCC ¶
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 ¶
EncodeGetEventInformation asks for the summaries after last (nil: from the start).
func EncodeLogRecord ¶
EncodeLogRecord builds a BACnetLogRecord (for tests and the simulator).
func EncodeNPDU ¶
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 ¶
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 ¶
EncodeReadPropertyMultiple is the ReadPropertyMultiple request (clause 15.7), properties grouped by object in the order given.
func EncodeReadRange ¶
EncodeReadRange is the ReadRange request.
func EncodeReinitialize ¶
func EncodeTimeSync ¶
EncodeTimeSync is the TimeSynchronization or UTCTimeSynchronization Request: a BACnetDateTime (the device's local time, or UTC).
func EncodeWhoHas ¶
EncodeWhoHas asks for an object by name or identifier, optionally within a device instance range.
func EncodeWhoIs ¶
EncodeWhoIs is a Who-Is request (clause 16.10) for one device instance.
func EncodeWriteProperty ¶
EncodeWriteProperty is the WriteProperty request (clause 15.9); Priority 0 leaves the priority out.
func EncodeWritePropertyMultiple ¶
EncodeWritePropertyMultiple groups consecutive writes to one object.
func ErrorFrom ¶
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 ¶
Frame wraps an APDU in an NPDU without routing information and a BVLC Original-Unicast-NPDU header.
func FromResult6 ¶
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 ¶
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 OwnEntry ¶
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 RawConstructed ¶
RawConstructed returns the content between an opening tag and its closing tag, and what follows.
func RawPropertyValue ¶
encodeReadPropertyRaw is ReadProperty; the ACK's value is taken raw (rawPropertyValue) for constructed types such as Recipient_List.
func SegmentACK ¶
SegmentACK builds a Segment-ACK; srv is set when a server sends it.
func SequenceStamp ¶
SequenceStamp is a BACnetTimeStamp of the sequence-number choice.
func SignedBytes ¶
func StampValue ¶
StampValue turns a BACnetTimeStamp into a reading value.
func UUIDString ¶
func Unframe ¶
Unframe strips BVLC and NPDU, returning the APDU. Network-layer messages and BVLL messages without an APDU return nil, nil.
func ValuesUntilClose ¶
ValuesUntilClose decodes application values up to the closing tag num, returning them and what follows the closing tag.
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.
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 ¶
BDTEntry is a BDT entry: a BBMD's B/IP address and its broadcast distribution mask (J.4.3.2).
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 ¶
Broadcast sends an NPDU to every node: Original-Broadcast-NPDU to the Group, or Distribute-Broadcast-To-Network to the BBMD.
func (*BIP6) Claim ¶
Claim checks that no other node answers for a random instance VMAC, choosing another when one does (H.7.2).
func (*BIP6) Resolve ¶
Resolve is the B/IPv6 address of the node with VMAC v, found with Address-Resolution when it is not in the table.
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 ¶
type BitString ¶
BitString is an application-tagged bit string; bit 0 is the first bit.
func AllTransitions ¶
func AllTransitions() 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 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 ¶
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 ¶
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) ForeignErr ¶
ForeignErr is why the IPE is not (yet) a registered foreign device.
func (*Client) ReadMultiple ¶
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) 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 ¶
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 ¶
SendAPDU sends an APDU to d through the data link address to (a B/IP address or a BACnet/SC VMAC).
func (*Client) SubscribeCOV ¶
func (*Client) Unconfirmed ¶
Unconfirmed sends an unconfirmed request to the device.
func (*Client) WhoHas ¶
WhoHas sends Who-Has to the device and collects the I-Haves that come back within the timeout.
func (*Client) WriteMultiple ¶
WriteMultiple sends the writes in one WritePropertyMultiple.
type ContextValue ¶
ContextValue is a primitive context-tagged value inside a property value (a CHOICE such as the accumulator's scale), left undecoded.
type Dest ¶
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).
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 ¶
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) CtxObjectID ¶
func (*Enc) CtxUnsigned ¶
type ErrorPDU ¶
type ErrorPDU struct{ Class, Code uint32 }
ErrorPDU is a BACnet Error reply (error class and code, clause 18).
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).
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).
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 ¶
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.
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 Peer ¶
Peer is what the device accepts: its largest APDU and whether it takes segmented requests.
type Peer6 ¶
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.
type PendingKey ¶
type PropResult ¶
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 ReadRange ¶
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 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.
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 ¶
SCConnect is the payload of Connect-Request and Connect-Accept (AB.2.10, AB.2.11).
func DecodeConnect ¶
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 (*SCHub) Connections ¶
Connections is SC_Hub_Function_Connection_Status (12.56).
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.
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.
type SCOption ¶
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 ¶
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.
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 ¶
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.
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 ¶
VMACOfInstance is the device instance as a VMAC: three octets, high order first, the top two bits zero.
Source Files
¶
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). |