bacnet_plugin 0.4.0
bacnet_plugin: ^0.4.0 copied to clipboard
High-throughput BACnet/IP client and server for Dart and Flutter, built on bacnet-stack via FFI with an isolate based, non-blocking engine.
Changelog #
All notable changes to this project will be documented in this file.
The format is based on Keep a Changelog, and this project adheres to Semantic Versioning.
0.4.0 Unreleased #
Alarm subscriptions and server alarm events. See Migrating from 0.3.x in the README.
Added #
- Client — subscriptions:
client.subscribeAlarms(deviceId, notificationClass: n)adds the client to the Recipient_List (with WriteProperty for devices without AddListElement) and returns anAlarmSubscriptionwith itsnotifications,eventInformation(),refresh()andcancel().BacnetClient.localAddress()returns the BACnet/IP address of the client.BacnetEventSummarylists itsunacknowledgedTransitionswithtimeStampOfandstateOffor acknowledging them. - Server — events:
alarmAcknowledgements(AlarmAcknowledgedEvent) andlistElementEvents(ListElementEvent, e.g. to persist Recipient_List changes). - Testing:
FakeBacnetDevice.unsupportedServicesrejects services, to test the fallbacks of applications. - Example: an alarms screen per device (subscription, active alarms,
acknowledgement, notification log) with a widget test on
FakeBacnetClient.
Changed #
- Breaking:
AlarmAcknowledgedEventandListElementEventare new subclasses ofBacnetEvent; classes implementingBacnetClientneedlocalAddress(). - Breaking:
BacnetEventSummary.isUnacknowledgedis true when any transition waits for an acknowledgement (before: only the transition into the current event state, so an alarm that returned to normal unacknowledged counted as acknowledged).
Fixed #
- The package contains the bacnet-stack sources again: 0.1.0 to 0.3.0 were uploaded without them, so the build hook failed in applications.
0.3.0 - 2026-10-01 #
Alarms and events. See Migrating from 0.2.x in the README.
Added #
- Client — alarms and events:
eventNotificationsdeliversEventNotificationEvents (confirmed and unconfirmed) with the values of the event algorithm as the sealedBacnetEventValues(BacnetOutOfRangeValues,BacnetChangeOfStateValues,BacnetChangeOfValueValues,BacnetBufferReadyValues,BacnetChangeOfReliabilityValuesand the other algorithms;BacnetOtherEventValuesfor the rest).acknowledgeAlarmandacknowledgeEvent(AcknowledgeAlarm),getEventInformation(follows More_Events) withBacnetEventSummary,getAlarmSummarywithBacnetAlarmSummary. - Client — lists:
addListElement/removeListElementand the typedaddListElements/removeListElements, e.g. to add this client to the Recipient_List of a Notification Class. - Types:
BacnetDestination, the sealedBacnetRecipient(BacnetRecipient.device,BacnetRecipient.ip),BacnetDaysOfWeek,BacnetEventPriorities,BacnetEventTransition,BacnetPropertyState, and the enumerationsBacnetEventType,BacnetNotifyTypeandBacnetPropertyStateKind. Typed propertiesrecipientList,priority,ackRequired,notifyType,eventDetectionEnable,eventMessageTextsandbinaryAlarmValue. - Server — intrinsic reporting: Notification Class objects
(
addNotificationClass, instances 0..63) andenableEventReportingfor Analog and Binary Inputs and Values (OUT_OF_RANGE and CHANGE_OF_STATE, faults from Reliability). The server sends event and acknowledgement notifications to the recipients (unconfirmed and confirmed, device recipients resolved with Who-Is) and answers AcknowledgeAlarm, GetEventInformation, GetAlarmSummary and Add/RemoveListElement. - Testing: fake devices simulate event reporting
(
FakeBacnetDevice.addNotificationClass,FakeBacnetObject.enableEventReporting,reportEvent), acknowledgements, event information, alarm summaries and list services.
Changed #
- Breaking: event notifications are
EventNotificationEvents instead ofUnconfirmedServiceEvents;BacnetEventhas a new subclass.
Fixed #
writeandaddListElements(client, server and fake) accept anintfor adoubleproperty:client.write(id, output, BacnetProperties.analogPresentValue, 35)inferrednumand failed with aTypeError.BacnetWritableProperty.encodeValueconverts and checks values.- Invoke ids of confirmed notifications of the server that timed out are released.
0.2.0 - 2026-10-01 #
Typed identifiers and values, read coalescing, segmentation and request control. Breaking changes are marked; see Migrating from 0.1.x in the README.
Changed #
- Breaking — typed identifiers:
BacnetObjectType,BacnetPropertyId,BacnetEngineeringUnits, error classes/codes, reasons, services and the other enumerations are extension types overint. The client, server, models, events and exceptions use them, so a property id passed as an object type no longer compiles;.labelnames a value. - Breaking — typed values: property values are the sealed class
BacnetValuewith one subclass per BACnet datatype (BacnetReal,BacnetUnsigned,BacnetEnumerated,BacnetCharacterString,BacnetObject,BacnetList, ...); no public API returns or acceptsdynamicorObject?values any more:readProperty(client and server) returnsFuture<BacnetValue>; Unsigned and Enumerated are no longer both decoded toint, and NULL isBacnetNullinstead ofnull. AccessorsasDouble,asInt,asBool,asString,asStatusFlagsandasList.readMultipleandDeviceScanner.scanDevicereturnMap<BacnetObject, Map<BacnetPropertyId, BacnetPropertyResult>>(aBacnetValueor aBacnetErrorper property;valueOf/errorOf) instead of'type:instance'→int→dynamicmaps, and reject specifications that request a property twice.writeProperty,BacnetPropertyValue,BacnetServer.setPresentValue,setProperty,addObjectandBacnetPresentValueUpdatetake aBacnetValue; thetag:parameters are removed.BacnetValue.inferconverts untyped input explicitly.BacnetObjectis an identifier and the ObjectIdentifier value; itspropertiesmap and the getters based on it are removed.CovNotificationEvent.valuesisMap<BacnetPropertyId, BacnetValue>(presentValue,statusFlags);PropertyWriteEvent.valueis aBacnetValue?.PropertyUpdateis sealed:PropertyValueUpdateandPropertyErrorUpdate(with aBacnetException).TrendLogEntryhas a sealeddatum(TrendLogValue,TrendLogStatus,TrendLogFailure,TrendLogTimeChange) andBacnetStatusFlags? statusFlagsinstead ofvalueandstatus.readRangetakes a sealedBacnetRangeinstead oftype/reference/count;ReadRangeTypeis removed.BacnetErrormoved next to the values;BacnetBitString,BacnetDate,BacnetTimeareBacnetValues.
- Breaking:
scanDevicetakesbackground/cancelTokeninstead of the ignoredendDeviceId. DeviceScannersends background requests by default (background).- Breaking: I-Have, UnconfirmedTextMessage and
UnconfirmedPrivateTransfer arrive as typed events;
UnconfirmedServiceEventremains for event notifications and requests that cannot be decoded. - Dependencies: bacnet-stack 1.7.0-rc4 (security fixes for BVLC header encoding, enclosed data and constructed value decoding); the server object table gains Averaging, and Accumulator supports COV.
- Request methods use callbacks instead of
asyncfunctions (see Fixed); 50 000 concurrent reads run at 170–196k reads/s (AOT, loopback) instead of 123–138k.
Added #
- Read coalescing: concurrent
readPropertycalls to one device are merged into ReadPropertyMultiple requests (coalesceReads,maxCoalescedReads,coalescingWindow); identical reads share one result, devices without RPM support are detected. 50 000 concurrent reads need 24× fewer requests and run about 3× faster on loopback. - Segmentation: segmented ComplexACKs (large object lists, schedules,
RPM results) are acknowledged window by window, reassembled and decoded
like unsegmented answers; lost segments are requested again and stalled
transfers time out. Requests advertise
maxSegmentsAccepted(default 32, 0 disables).BacnetStats.segmentedRepliescounts them. - Background requests:
background: truequeues requests behind interactive ones and limits them to 3/4 of the transaction slots and one slot less per device. - Offline devices: after
offlineAfterTimeoutsconsecutive timeouts requests to a device fail immediately withBacnetDeviceOfflineException(aBacnetTimeoutException); one request probes it afterofflineRetryInterval(doubling while it stays silent), an I-Am brings it back.BacnetStats.offlineDevicescounts them. - Cancellation:
BacnetCancelTokencancels reads, writes, ReadRange and raw requests (BacnetCancelledException); queued requests are dropped from the worker queue. - Testing:
package:bacnet_plugin/testing.dartwithFakeBacnetClient,FakeBacnetDeviceandFakeBacnetObject: in-memory devices with discovery, real error codes, priority arrays, COV notifications, trend log records, latency and offline simulation, and a request log for assertions. - Typed properties:
BacnetProperty<T>/BacnetWritableProperty<T>and theBacnetPropertiescatalogue of standard properties;client.read/client.write(also onBacnetServerandFakeBacnetClient) return and accept the Dart type, read-only properties cannot be written, andgetreadsreadMultipleresults. - Constructed datatypes:
BacnetWeeklySchedule,BacnetTimeValue,BacnetSpecialEvent,BacnetCalendarEntry,BacnetDateRange,BacnetWeekNDay,BacnetDateTime,BacnetTimeStamp,BacnetDeviceObjectPropertyReference,BacnetAddressBinding,BacnetPriorityArray,BacnetEventTransitionBitsandBacnetLimitEnableconvert from and to the values of schedules, calendars, trend logs and event reporting. Checked against bacnet-stack'sbacserv. - Typed service events:
IHaveEvent,TextMessageEventandPrivateTransferEventinstead of rawUnconfirmedServiceEvents;sendWhoHas(answered byFakeBacnetDevices too). - JSON for values, write specifications and trend logs
(
{"datatype": "real", "value": 21.5}). - Constants
BacnetBinaryPVandBacnetPolarity.
Fixed #
- In JIT mode (debug builds,
dart run) bursts of tens of thousands of requests stalled for seconds: the client kept one suspendedasynccall per request, and the VM deoptimizes each of them separately when the function's optimized code is invalidated. Request methods now use callbacks; non-BACnet errors of merged reads fail the reads instead of escaping as uncaught errors. - Unsigned and Enumerated values of 64 bits wrapped to negative numbers;
they are now rejected with
BacnetDecodeException. - Datatype inference wrote REAL to Accumulator present values (Unsigned).
0.1.0 - 2026-10-01 #
Reworked for high-load client and server deployments. See the migration notes in the README.
Changed #
- Dependencies: bacnet-stack 1.6.1 pinned as git submodule (previously
an unpinned clone of
master); Dart SDK^3.11.0;ffi2.2,json_annotation4.12,meta1.16+,hooks2.2,code_assets2.1,native_toolchain_c0.19,ffigen22,build_runner2.16,json_serializable6.14,mocktail1.0.5,test1.30+,lints6.1; example:go_router18,provider6.1.5; CI actionscheckout@v7,setup-dart@v1,flutter-action@v2,setup-java@v6. - Build: the native library is compiled by
hook/build.dartfor all platforms (@Nativebindings). The package no longer depends on Flutter and runs in plain Dart programs. Removed the per-platform CMake, Gradle and CocoaPods files, which were broken (Android CMake path, iOS/macOS sources, Linux bundling, Windows-only native code). - Native engine rewritten (
native/src): portable C (nowindows.h, SEH orsetjmp), event buffer instead of FFI callbacks, wake-up socket, generic confirmed request sender, own BACnet/IP port for POSIX systems based ongetifaddrs(accepts interface names and IPv4 addresses). - Worker isolate: blocks on the sockets instead of a 10 ms timer that processed one packet per tick (~100 packets/s); processes up to 256 packets per iteration and batches messages to the main isolate.
- Client: request scheduler with
maxConcurrentRequests,maxConcurrentRequestsPerDevice,maxQueuedRequestsand deadlines; automatic address binding via targeted Who-Is; ReadPropertyMultiple is split automatically when the answer exceeds the APDU size; datatype inference for writes (BacnetValueto force a type). - Server: answers Who-Is, Read/WriteProperty(Multiple),
SubscribeCOV(Property), ReadRange, DCC, ReinitializeDevice and time
synchronization; COV notifications are detected and sent (full scan every
covScanInterval); objects with names, descriptions, units, COV increments and state texts;setPresentValue,updatePresentValues,setProperty,readProperty,removeObject,sendIAm. DeviceScannerandPropertyMonitorrun requests in parallel; COV subscriptions are renewed and cancelled, notifications carry values.BacnetClientandBacnetServershare one reference counted stack.- Events form the sealed
BacnetEventhierarchy (IAmEvent,CovNotificationEvent,PropertyWriteEvent,UnconfirmedServiceEvent,LogEvent,ErrorEvent); the*Responsenames of 0.0.x are deprecated aliases. Internal request/response classes are no longer exported. - Constants are generated from bacnet-stack (
tool/generate_constants.dart) and cover every standard object type, property, error code and service; existing names are unchanged. - Internals reorganized for maintainability: codec, worker isolate
(engine facade, event reader, unit tested request scheduler) and the C
engine are split into focused modules; tests mirror
lib/src; stricter lints.
Fixed #
- TSM timer was fed with wall clock timestamps instead of elapsed time, so requests timed out and were retransmitted almost immediately.
- Failed transactions never released their invoke id; after 255 failures no request could be sent anymore.
- Errors, rejects and aborts were not reported (requests waited for the 15 s timeout); requests to unknown devices never completed.
- I-Am did not add address bindings (
address_add_bindingonly updates existing entries) and routed devices lost their network address. - Confirmed COV notifications were never acknowledged; COV notifications
had no device id, so
PropertyMonitornever matched them. - WriteProperty sent the priority as array index; WPM forced REAL values.
- Server object names/vendor name pointed to freed memory; value objects rejected writes; demo objects of bacnet-stack were exposed.
- RPM/ReadRange decoders could read past the received data; ReadRange item data used the wrong context tag; malformed UCS-4 strings threw.
- JSON serialization of nested models.
Added #
- Typed exceptions:
BacnetRejectException,BacnetAbortException,BacnetDeviceNotFoundException,BacnetQueueFullException,BacnetDecodeException,BacnetEncodeException. BacnetStats,client.stats(),iAmEvents,covEvents,readRange,getTrendLog(decoded log records),timeSynchronization,sendConfirmedRaw,removeDeviceBinding,isDeviceBound,unsubscribeCOV,CallbackLogger.- Value types
BacnetBitString,BacnetStatusFlags,BacnetDate,BacnetTime,BacnetValue. - Constants
BacnetEngineeringUnits,BacnetEventState,BacnetReliability,BacnetDeviceStatus,BacnetSegmentation,BacnetAbortReason,BacnetRejectReason,BacnetConfirmedService,BacnetUnconfirmedService;valueslists the known values of each. - Unit tests (codec vectors from ASHRAE 135 Annex F, fuzzing), loopback client/server integration tests, load and server benchmarks, interop checks against the bacnet-stack demo tools.
0.0.1 - 2026-01-07 #
Added #
Core Features
- BACnet Client - Full client implementation with support for:
- Device discovery (Who-Is/I-Am)
- Read Property / Read Property Multiple
- Write Property / Write Property Multiple
- Change of Value (COV) subscriptions
- Foreign Device Registration
- Device scanning and object enumeration
- BACnet Server - Server implementation for hosting objects:
- Device initialization
- Object hosting (Analog, Binary, Multi-state)
- Write notification events
- Read/Write property handling
Developer Experience
-
Named Constants - Complete set of BACnet protocol constants:
BacnetObjectType- 25+ object types with human-readable namesBacnetPropertyId- 80+ property identifiersBacnetErrorClassandBacnetErrorCode- Comprehensive error constants
-
Modern Logging:
DeveloperBacnetLogger- Dart DevTools integrationConsoleBacnetLogger- Simple console output- Pluggable logger interface for custom implementations
-
Type Safety:
- Strict type checking throughout
- Named constants replace magic numbers
- Comprehensive parameter documentation
-
JSON Serialization:
- All models support
toJson()/fromJson() - Generated with
json_serializable - Easy API integration
- All models support
Data Models
-
Immutable Models:
BacnetObject- Object representation with propertiesBacnetPropertyReference- Property references for RPMBacnetReadAccessSpecification- RPM request specificationBacnetWriteAccessSpecification- WPM request specificationBacnetPropertyValue- Property values for WPM
-
Model Features:
@immutableannotationscopyWith()methods for updates- Equality operators (
==,hashCode) - Helper getters (name, presentValue, etc.)
- Full dartdoc documentation
Configuration
- BacnetConfig - Centralized configuration:
- Interface binding
- Port configuration
- Timeout settings
- Retry configuration
- Logger selection
Error Handling
- Exception Hierarchy:
BacnetException- Base exceptionBacnetTimeoutException- Request timeoutsBacnetNotInitializedException- Uninitialized operationsBacnetProtocolException- Protocol errors with error codes
Documentation
-
Complete API Documentation:
- Every public API has dartdoc comments
- Usage examples for all major features
- Parameter explanations with constant references
- Return value documentation
-
Project Documentation:
- Comprehensive README.md with examples
- CONTRIBUTING.md guide
- Architecture diagrams
- Quick start guides
Code Quality
-
Linting:
- 100+ lint rules configured
- Strict type checking enabled
- Code style enforcement (single quotes, const, etc.)
- Documentation requirements
-
Code Generation:
build_runnerintegration- JSON serialization generation
- FFI bindings generation
Architecture #
- Isolate-Based Design:
- Non-blocking network operations
- Smooth UI performance
- Background processing
- Worker isolate for native BACnet stack
Platforms #
- ✅ Windows
- ✅ Linux
- ✅ macOS
- ✅ Android
- ✅ iOS
Dependencies #
ffi: ^2.1.4- Foreign Function Interfacejson_annotation: ^4.9.0- JSON annotationsmeta: ^1.15.0- Metadata annotationsplugin_platform_interface: ^2.1.8- Platform interface
Dev Dependencies #
build_runner: ^2.4.0- Code generationjson_serializable: ^6.8.0- JSON serializationmocktail: ^1.0.0- Mocking for testsflutter_lints: ^6.0.0- Linting rules
Known Limitations #
- Trend log reading returns dummy data (planned for future release)
- Device scanning limited to first 10 objects
- Some native worker code lacks public documentation
- WritePropertyMultiple native binding pending implementation