From ade87da9b1a003e2650b20a6b121f5c8b732a5be Mon Sep 17 00:00:00 2001 From: Steven Smethurst Date: Sat, 18 Jul 2026 13:51:13 -0700 Subject: [PATCH 01/15] feat: update to CAS BACnet Stack v6 (item-16 Network Port migration) Pin the stack submodule to 6.x-TestTool 92c91d74 (Sprint 261 P1-P5 public-interface review). v6 removed BACnetStack_AddNetworkPortObject; migrated to BACnetStack_AddNetworkPortObjectWithNetworkNumber, passing networkNumber 0 + NETWORK_NUMBER_QUALITY_UNKNOWN, which reproduce the old behaviour (a local port that has not been configured with, or learned, a network number). Added the BACnetNetworkNumberQuality constants (cl. 12.56.11) to the example constants header. Builds clean against the pinned stack. Co-Authored-By: Claude Fable 5 --- common/CASBACnetStackExampleConstants.h | 10 +++++++++- main.cpp | 7 ++++++- submodules/cas-bacnet-stack | 2 +- 3 files changed, 16 insertions(+), 3 deletions(-) diff --git a/common/CASBACnetStackExampleConstants.h b/common/CASBACnetStackExampleConstants.h index 36461d6..e8e23df 100644 --- a/common/CASBACnetStackExampleConstants.h +++ b/common/CASBACnetStackExampleConstants.h @@ -151,12 +151,20 @@ static const uint8_t NETWORK_TYPE_IP = 0; static const uint8_t NETWORK_PORT_NETWORK_TYPE_IPV4 = 5; // -- Network Port object protocol level (BACnetProtocolLevel enumeration, used -// by BACnetStack_AddNetworkPortObject). +// by BACnetStack_AddNetworkPortObjectWithNetworkNumber). // Full list: submodules/cas-bacnet-stack/source/BACnetProtocolLevel.h static const uint8_t NETWORK_PORT_PROTOCOL_LEVEL_BACNET_APPLICATION = 2; // The lowest protocol layer references this sentinel instead of another port. static const uint32_t NETWORK_PORT_REFERENCE_PORT_NONE = 4194303; +// -- Network_Number_Quality (BACnetNetworkNumberQuality, cl. 12.56.11). Says how +// the port learned its Network_Number. A port that has not been told and has +// not learned one reports "unknown" with Network_Number = 0. +static const uint8_t NETWORK_NUMBER_QUALITY_UNKNOWN = 0; +static const uint8_t NETWORK_NUMBER_QUALITY_LEARNED = 1; +static const uint8_t NETWORK_NUMBER_QUALITY_LEARNED_CONFIGURED = 2; +static const uint8_t NETWORK_NUMBER_QUALITY_CONFIGURED = 3; + // -- Character string encoding (the encoding byte returned by the character- // string Get callback). 0 = UTF-8. The BACnet character-set values are // defined by ANSI/ASHRAE 135 Clause 20.2.9; see the stack's handling in diff --git a/main.cpp b/main.cpp index 4c64901..ee37949 100644 --- a/main.cpp +++ b/main.cpp @@ -962,10 +962,15 @@ int main(int argc, char** argv) { // Every BACnet device (Protocol_Revision 17+) must have at least one Network // Port object describing the port it talks on. This one is the BACnet/IP // application port; it is the lowest layer, so its reference port is "none". - if (!BACnetStack_AddNetworkPortObject( + // v6: the old AddNetworkPortObject was removed - use the WithNetworkNumber + // form. networkNumber 0 + quality "unknown" reproduce the old behaviour (a + // local port that has not learned its network number). + if (!BACnetStack_AddNetworkPortObjectWithNetworkNumber( g_deviceInstance, NETWORK_PORT_INSTANCE, NETWORK_PORT_NETWORK_TYPE_IPV4, NETWORK_PORT_PROTOCOL_LEVEL_BACNET_APPLICATION, + 0, // networkNumber: not configured + NETWORK_NUMBER_QUALITY_UNKNOWN, NETWORK_PORT_REFERENCE_PORT_NONE)) { printf("Error: Failed to add Network Port 1 (Vermilion).\n"); return 1; diff --git a/submodules/cas-bacnet-stack b/submodules/cas-bacnet-stack index 863a090..92c91d7 160000 --- a/submodules/cas-bacnet-stack +++ b/submodules/cas-bacnet-stack @@ -1 +1 @@ -Subproject commit 863a090e0f6604816016af9a53a4aa477cff4c77 +Subproject commit 92c91d74e66056d0965b31e5256112d7323ca361 From ea09aac81d49e9433e1c838e81ef2bc668abb7df Mon Sep 17 00:00:00 2001 From: Steven Smethurst Date: Sat, 18 Jul 2026 14:09:31 -0700 Subject: [PATCH 02/15] chore(common): sync vendored helper to v1.4.0 (deferred restart + B-OD re-sync) Vendoring sweep. common/ must be identical in every example of the series, so this lands the v1.4.0 helper here even though this profile does not use it: - Adds RequestRestart()/RestartDue(), the deferred-restart pattern for ReinitializeDevice (DM-RD-B). Inert unless an example calls it; only B-AAC does, since it is the only profile in the series with DM-RD-B. - Re-syncs CASBACnetStackExampleConstants.h in B-OD, which had silently gone stale: it never received the NETWORK_NUMBER_QUALITY_* constants from the 2026-07-17 item-16 migration because B-OD was the one example that did not itself need the migrated AddNetworkPortObjectWithNetworkNumber call. Nothing failed to compile there, so the folder's byte-identical guarantee broke silently. (No-op in the other six repos, which were already current.) Verified: content-identical across all 8 repos; B-AAC and B-OD both build. Co-Authored-By: Claude Opus 4.8 --- common/CASExampleHelper.cpp | 59 +++++++++++++++++++++++++++++++++++++ common/CASExampleHelper.h | 58 +++++++++++++++++++++++++++++++++++- common/CHANGELOG.md | 42 ++++++++++++++++++++++++++ 3 files changed, 158 insertions(+), 1 deletion(-) diff --git a/common/CASExampleHelper.cpp b/common/CASExampleHelper.cpp index 2278f71..c7a06b8 100644 --- a/common/CASExampleHelper.cpp +++ b/common/CASExampleHelper.cpp @@ -237,10 +237,69 @@ void EnableRawInput() { } #endif +// --------------------------------------------------------------------------- +// Deferred-restart state (see the DM-RD-B block in CASExampleHelper.h). +// +// The clock here must be MONOTONIC, not wall-clock: a device that supports +// TimeSynchronization (DM-TS-B) can have its wall clock stepped - possibly +// backwards - by a management station at any moment, including during the +// restart delay. time() would then either fire the restart early or park it in +// the future indefinitely. A monotonic source cannot be stepped. +// --------------------------------------------------------------------------- +bool g_restartPending = false; +uint64_t g_restartDueAtMs = 0; +CASExampleHelper::RestartKind g_restartKind = CASExampleHelper::RestartKind::Warm; + +uint64_t MonotonicMilliseconds() { +#if defined(_WIN32) + // GetTickCount64 (not GetTickCount): the 32-bit version wraps to zero after + // ~49.7 days of uptime, which would make a pending deadline unreachable. + return (uint64_t)GetTickCount64(); +#else + struct timespec ts; + if (clock_gettime(CLOCK_MONOTONIC, &ts) != 0) { + return 0; + } + return (uint64_t)ts.tv_sec * 1000u + (uint64_t)(ts.tv_nsec / 1000000); +#endif +} + } // namespace namespace CASExampleHelper { +void RequestRestart(const RestartKind kind, const uint32_t delayMilliseconds) { + const uint64_t dueAt = MonotonicMilliseconds() + (uint64_t)delayMilliseconds; + + if (g_restartPending) { + // Never postpone a restart already promised to an earlier client: keep + // the earliest deadline, and let a Cold request upgrade a pending Warm. + if (dueAt < g_restartDueAtMs) { + g_restartDueAtMs = dueAt; + } + if (kind == RestartKind::Cold) { + g_restartKind = RestartKind::Cold; + } + return; + } + + g_restartPending = true; + g_restartDueAtMs = dueAt; + g_restartKind = kind; +} + +bool RestartDue(RestartKind* const outKind) { + if (!g_restartPending || MonotonicMilliseconds() < g_restartDueAtMs) { + return false; + } + // Clear BEFORE returning true so this fires exactly once. + g_restartPending = false; + if (outKind != NULL) { + *outKind = g_restartKind; + } + return true; +} + void PrintVersion(const char* appName, const char* appVersion) { printf("%s v%s\n", appName, appVersion); printf("CAS BACnet Stack version: %u.%u.%u.%u\n", diff --git a/common/CASExampleHelper.h b/common/CASExampleHelper.h index 1f1b928..c679e9b 100644 --- a/common/CASExampleHelper.h +++ b/common/CASExampleHelper.h @@ -38,7 +38,7 @@ namespace CASExampleHelper { // version). Bump it whenever anything in common/ changes, and record the // change in common/CHANGELOG.md - every example in the series must then be // re-synced to the same common/ version. -static const char* COMMON_VERSION = "1.3.0"; +static const char* COMMON_VERSION = "1.4.0"; // Print the example's name + version, the linked CAS BACnet Stack version, // and the common/ helper version. @@ -91,6 +91,62 @@ void SendIAm(uint32_t deviceInstance); // true on success; on failure the buffers are left untouched. bool GetLocalIPv4(uint8_t ipAddress[4], uint8_t subnetMask[4]); +// --- Deferred device restart (DM-RD-B) ------------------------------------- +// Only for examples whose profile includes DM-RD-B (i.e. that register a +// ReinitializeDevice callback). Most profiles in this series do not. +// +// WHY THIS EXISTS. A ReinitializeDevice callback must NOT restart the device +// inside the callback. Returning true only tells the stack the request was +// accepted - the SimpleACK is encoded now but does not reach the wire until a +// later BACnetStack_Tick(). Restart (or exit, or reset) before that tick and +// the ACK is never transmitted: the client sees a timeout and reports the +// device as unresponsive, even though it did exactly what it was told. That is +// the classic DM-RD-B interop bug, and it fails BTL. +// +// The fix is to defer: the callback records "a restart is due at time T" and +// returns immediately; the main loop performs the restart once T has passed, by +// which point the ACK has been sent. The delay also gives the client's own +// request timer a chance to complete cleanly. +// +// Usage - in the ReinitializeDevice callback, after it decides to accept: +// +// CASExampleHelper::RequestRestart(CASExampleHelper::RestartKind::Cold, +// CASExampleHelper::RESTART_DELAY_MS); +// return true; // let the stack ACK first +// +// ...and once per tick in the main loop, after BACnetStack_Tick(): +// +// CASExampleHelper::RestartKind kind; +// if (CASExampleHelper::RestartDue(&kind)) { +// // a real device reboots here; see main.cpp for what this example does +// } + +enum class RestartKind { + Cold, // REINITIALIZE_STATE_COLDSTART - full power-on restart + Warm // REINITIALIZE_STATE_WARMSTART - re-initialize, keep what survives +}; + +// A restart delay that is comfortably longer than one tick of the main loop, +// so the SimpleACK is on the wire before anything is torn down. One second is +// the conventional choice: long enough to be safe on a busy or slow link, +// short enough that the operator sees the device go down promptly. +static const uint32_t RESTART_DELAY_MS = 1000; + +// Record that a restart of the given kind is due delayMilliseconds from now. +// Safe to call more than once: the EARLIEST pending deadline wins, so a second +// ReinitializeDevice arriving during the delay window cannot postpone a restart +// that was already promised to the first client. A Cold request also upgrades a +// pending Warm one (cold is the stronger reset); the reverse does not downgrade. +void RequestRestart(RestartKind kind, uint32_t delayMilliseconds); + +// Call once per tick of the main loop. Returns true EXACTLY ONCE - on the first +// call after the deadline has passed - and writes the requested kind to +// *outKind. Returns false when no restart is pending or the delay has not yet +// elapsed. Clearing the request before returning true means a caller that +// handles the restart in-process (rather than actually rebooting) does not get +// a second one on the next tick. +bool RestartDue(RestartKind* outKind); + // --- Keyboard input (common to every example) ------------------------------ enum class KeyCommand { None, // nothing pressed diff --git a/common/CHANGELOG.md b/common/CHANGELOG.md index 30f7d6e..ebd10e5 100644 --- a/common/CHANGELOG.md +++ b/common/CHANGELOG.md @@ -12,6 +12,48 @@ entry here, and must then be re-copied into **every** example in the series. The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/), and the folder adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). +## [1.4.0] - 2026-07-18 + +### Added + +- **`RequestRestart()` / `RestartDue()` — the deferred-restart pattern for + `ReinitializeDevice` (DM-RD-B).** A `ReinitializeDevice` callback must not + restart the device inside the callback: returning `true` only *encodes* the + SimpleACK, which does not reach the wire until a later `BACnetStack_Tick()`. + Restarting (or exiting, or resetting) before that tick means the ACK is never + transmitted and the client reports a timeout against a device that did exactly + what it was asked — the classic DM-RD-B interop bug. The callback now records a + deadline and returns; the main loop restarts once the deadline passes. + Adopted by B-AAC (the only example in the series whose profile includes + DM-RD-B); the helper is inert in every example that never calls it. Adoption + checklist in `docs/deferred-restart-adoption.md` (B-AAC). + - The deadline uses a **monotonic** clock (`GetTickCount64` / `CLOCK_MONOTONIC`), + not `time()`: a device supporting DM-TS-B can have its wall clock stepped + backwards by a management station mid-delay, which would strand or prematurely + fire the pending restart. + - Repeat requests keep the **earliest** deadline (a second client cannot + postpone a restart already promised to the first) and let Cold upgrade a + pending Warm. + +### Fixed + +- **B-OD's `CASBACnetStackExampleConstants.h` was stale** — it never received the + `NETWORK_NUMBER_QUALITY_*` constants or the + `AddNetworkPortObjectWithNetworkNumber` comment update from the 2026-07-17 + item-16 migration, because B-OD was the one example that did not itself need the + migrated call. That silently broke the folder's byte-identical guarantee (the + rule this file states, and that parent-repo CI enforces) in a repo where nothing + failed to compile. Re-synced with this release's sweep. + +### Notes + +- The folder is verified **content-identical in all eight examples** as of this + release. A working-tree scan on Windows shows CRLF in six repos and LF in two, + which looks like drift but is not: every committed blob is LF in all eight, and + the difference is local `core.autocrlf` checkout behaviour. Compare with + `git show HEAD:common/`, or `diff --strip-trailing-cr`, when auditing this + — a naive working-tree `diff -r` reports eight files of phantom drift. + ## [1.3.0] - 2026-07-16 ### Changed From 36b8c48f646b22b9164eacdf76e27f9f87e56cec Mon Sep 17 00:00:00 2001 From: Steven Smethurst Date: Fri, 31 Jul 2026 12:01:54 -0700 Subject: [PATCH 03/15] build: bump CAS BACnet Stack pin to 6.x-TestTool b681f58d 38 commits ahead of the previous pin (92c91d74). Breaking API changes in range (RegisterHookProperty* removal, DecodeAs fold, SetCOVMultipleSettings rename, SetBackupAndRestoreEnabled signature, SetObjectTypeSupported removal) verified unused by this example. Rebuilt Release, smoke-tested: binds, broadcasts I-Am, device ready. One-time cosmetic BACnetSC 'UUID has not been set' debug-log line at startup is new stack behavior, noted in CHANGELOG. Co-Authored-By: Claude Fable 5 --- CHANGELOG.md | 10 ++++++++++ submodules/cas-bacnet-stack | 2 +- 2 files changed, 11 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index c5d3077..9a44387 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -35,6 +35,16 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Changed +- **Stack pin moved to `6.x-TestTool` @ `b681f58d` (2026-07-31).** 38 commits + ahead of the previous pin (`92c91d74`); includes the removal of the 13 + `RegisterHookProperty*` exports, the `DecodeAsXML`/`DecodeAsJSON` → + `DecodeAs` fold, the `SetCOVMultipleSettings` rename, the + `SetBackupAndRestoreEnabled` signature change (absorbs + `backupFailureTimeout`), and the removal of `SetObjectTypeSupported` — none + of which this example calls. Known cosmetic side effect: the newly merged + BACnet/SC datalink logs a one-time "UUID has not been set" error on the + debug callback at start-up in applications that never configure BACnet/SC; + it latches its error flag and goes quiet. Functionality is unaffected. - **Stack pin moved to the series `6.x` branch (CAS BACnet Stack 6.0.0.0).** Which stack version this example requires is a material licensing fact. - The commandable-setup loop carries `{type, instance}` pairs instead of a diff --git a/submodules/cas-bacnet-stack b/submodules/cas-bacnet-stack index 92c91d7..b681f58 160000 --- a/submodules/cas-bacnet-stack +++ b/submodules/cas-bacnet-stack @@ -1 +1 @@ -Subproject commit 92c91d74e66056d0965b31e5256112d7323ca361 +Subproject commit b681f58d549c3561d3c389152b796dcdbc636faa From c07fc6752b41611ab5f06cf7cab7bee47d3bc324 Mon Sep 17 00:00:00 2001 From: Steven Smethurst Date: Fri, 31 Jul 2026 14:00:01 -0700 Subject: [PATCH 04/15] build: consume CASBACnetStack::Adapter CMake target instead of hand-globbing stack source CMakeLists.txt now add_subdirectory()s submodules/cas-bacnet-stack/adapters/cpp and links CASBACnetStack::Adapter, instead of file(GLOB)-ing every source/*.cpp itself. CAS_BACNET_STACK_LINK (SOURCE default, or STATIC/DLL - set before configure) now switches link modes without touching this file. TEMPORARY submodule pin: submodules/cas-bacnet-stack now points at the tip of the adapter-cpp-package branch (stacked on adapter-cpp-generate), not yet merged into 6.x-TestTool - see cas-bacnet-stack PRs #267 and #268. Re-pin to 6.x-TestTool once both merge. main.cpp/common/ still include CASBACnetStackDLL.h directly and call BACnetStack_* unchanged (SOURCE mode exposes the same declarations via the adapter's transitive include dirs) - the include-swap + LoadBACnetFunctions() adoption is the next commit. Verified: fresh MSVC Release build, clean; smoke-run on --port 47899 identical to pre-migration (binds, broadcasts I-Am, "Device 389003 (Rainbow) ready"). Co-Authored-By: Claude Sonnet 5 --- CMakeLists.txt | 43 +++++++++++++++++++------------------ submodules/cas-bacnet-stack | 2 +- 2 files changed, 23 insertions(+), 22 deletions(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index b86594d..9a4d96a 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -1,18 +1,21 @@ # ============================================================================= # CMake build for the BACnet B-ASC (Application Specific Controller) C++ example. # -# This example links the CAS BACnet Stack by COMPILING IT FROM SOURCE: it builds -# every file in the stack's source/ folder straight into the executable and -# calls the stack's C API (CASBACnetStackDLL.h) directly. There is no DLL/.so to -# build, copy, or ship first - everything compiles into one self-contained -# executable. +# This example links the CAS BACnet Stack through the CASBACnetStack::Adapter CMake +# target (submodules/cas-bacnet-stack/adapters/cpp) and calls the stack's C API +# (BACnetStack_*, via CASBACnetStackAdapter.h) directly - no fp* indirection, the same +# call in every link mode. CAS_BACNET_STACK_LINK picks the mode (see below); it defaults +# to SOURCE, which compiles every file in the stack's source/ folder straight into the +# executable - there is no DLL/.so to build, copy, or ship first. # -# NOTE: the first build compiles the entire stack (~600 source files), so it +# NOTE: the first SOURCE-mode build compiles the entire stack (~600 source files), so it # takes a few minutes. Subsequent incremental builds are fast. # # Build: # cmake -B build -S . # cmake --build build --config Release +# Build against a prebuilt DLL/.so instead of compiling from source: +# cmake -B build -S . -DCAS_BACNET_STACK_LINK=DLL # Run (from the example folder): # ./build/BACnetExampleBASC (Linux/macOS) # .\build\Release\BACnetExampleBASC.exe (Windows) @@ -49,23 +52,20 @@ endif() if(NOT DEFINED CAS_STACK_DIR) set(CAS_STACK_DIR "${CMAKE_CURRENT_SOURCE_DIR}/submodules/cas-bacnet-stack") endif() -set(CAS_STACK_SOURCE_DIR "${CAS_STACK_DIR}/source") -if(NOT EXISTS "${CAS_STACK_SOURCE_DIR}/CASBACnetStackDLL.h") +if(NOT EXISTS "${CAS_STACK_DIR}/adapters/cpp/CMakeLists.txt") message(FATAL_ERROR - "CAS BACnet Stack source not found at: ${CAS_STACK_SOURCE_DIR}\n" + "CAS BACnet Stack adapter not found under: ${CAS_STACK_DIR}\n" "The stack is a git submodule. After cloning this repository, run:\n" " git submodule update --init --recursive\n" "Or pass -D CAS_STACK_DIR=/path/to/cas-bacnet-stack to use a stack elsewhere.") endif() -# --- Gather the CAS BACnet Stack source ------------------------------------- -# Compiling from source: grab every .cpp/.c in the stack's source/ folder. The -# example calls the stack's C API (CASBACnetStackDLL.h) directly, so no adapter -# layer is needed. -file(GLOB CAS_STACK_SOURCES - "${CAS_STACK_SOURCE_DIR}/*.cpp" - "${CAS_STACK_SOURCE_DIR}/*.c") +# --- The CAS BACnet Stack, via its CMake adapter target --------------------- +# CAS_BACNET_STACK_LINK is the adapter's own cache variable (SOURCE/STATIC/DLL, +# default SOURCE) - set it BEFORE add_subdirectory() so the adapter target picks it up. +# See submodules/cas-bacnet-stack/adapters/cpp/CMakeLists.txt for what each mode does. +add_subdirectory("${CAS_STACK_DIR}/adapters/cpp" cas-bacnet-stack-adapter) # --- The shared example helper ---------------------------------------------- set(COMMON_SOURCES @@ -75,16 +75,17 @@ set(COMMON_SOURCES # --- The executable --------------------------------------------------------- add_executable(BACnetExampleBASC main.cpp - ${COMMON_SOURCES} - ${CAS_STACK_SOURCES}) + ${COMMON_SOURCES}) target_include_directories(BACnetExampleBASC PRIVATE - "${EXAMPLES_COMMON_DIR}" - "${CAS_STACK_SOURCE_DIR}") + "${EXAMPLES_COMMON_DIR}") + +target_link_libraries(BACnetExampleBASC PRIVATE CASBACnetStack::Adapter) # --- Warnings on OUR sources only ------------------------------------------- # Apply strict warnings to the example + helper sources, but NOT to the bundled -# third-party stack (~600 files) which would be noisy and isn't ours to fix. +# third-party stack (~600 files, built inside the CASBACnetStack::Adapter target) +# which would be noisy and isn't ours to fix. if(MSVC) set(EXAMPLE_WARNINGS "/W4") else() diff --git a/submodules/cas-bacnet-stack b/submodules/cas-bacnet-stack index b681f58..8780d41 160000 --- a/submodules/cas-bacnet-stack +++ b/submodules/cas-bacnet-stack @@ -1 +1 @@ -Subproject commit b681f58d549c3561d3c389152b796dcdbc636faa +Subproject commit 8780d4128d50d6376e40188dd91bcd83cfdb2dc4 From 3809f00d1d9fffff1e9e351d06607527ccd8b975 Mon Sep 17 00:00:00 2001 From: Steven Smethurst Date: Fri, 31 Jul 2026 14:02:47 -0700 Subject: [PATCH 05/15] build: adopt LoadBACnetFunctions() contract, include CASBACnetStackAdapter.h main.cpp and common/CASExampleHelper.cpp now include CASBACnetStackAdapter.h instead of CASBACnetStackDLL.h directly. All BACnetStack_* call sites are UNCHANGED (34 in main.cpp, ~8 in common/) - the adapter exposes the exact same names in every link mode, so this is purely an include swap plus one new call: LoadBACnetFunctions() now runs as the very first thing in main(), before even --help/--version (PrintVersion calls BACnetStack_GetAPIMajorVersion() etc., so skipping the load step there would be a null-pointer call in DLL mode). common/ -> v1.5.0 (CHANGELOG entry): this is a contract change for every example in the series that vendors common/, not just B-ASC - each needs the same LoadBACnetFunctions() call added to its main() when it re-syncs (Stage D, out of scope here). Verified: clean incremental MSVC rebuild; smoke-run identical to before (binds, broadcasts I-Am, "Device 389003 (Rainbow) ready", RX 21 bytes from a real LAN device - proving the adapter-mediated send/receive path both directions); --version path also verified (exercises the pre-HandleHelpAndVersionArgs LoadBACnetFunctions() placement specifically). Co-Authored-By: Claude Sonnet 5 --- common/CASExampleHelper.cpp | 7 ++++--- common/CASExampleHelper.h | 8 +++++--- common/CHANGELOG.md | 17 +++++++++++++++++ main.cpp | 19 ++++++++++++++++--- 4 files changed, 42 insertions(+), 9 deletions(-) diff --git a/common/CASExampleHelper.cpp b/common/CASExampleHelper.cpp index c7a06b8..8befead 100644 --- a/common/CASExampleHelper.cpp +++ b/common/CASExampleHelper.cpp @@ -9,9 +9,10 @@ #include "SimpleUDP.h" #include "CASBACnetStackExampleConstants.h" -// The CAS BACnet Stack C API. The whole stack is compiled into this program -// from source, so we call BACnetStack_* functions directly. -#include "CASBACnetStackDLL.h" +// The CAS BACnet Stack C API, via the adapter: BACnetStack_* is called directly here, +// the same call in every link mode (source/static/DLL) - see CASBACnetStackAdapter.h. +// The caller's main() must have already called LoadBACnetFunctions() successfully. +#include "CASBACnetStackAdapter.h" #include #include diff --git a/common/CASExampleHelper.h b/common/CASExampleHelper.h index c679e9b..0dcd263 100644 --- a/common/CASExampleHelper.h +++ b/common/CASExampleHelper.h @@ -25,8 +25,10 @@ // To change it: edit it, bump COMMON_VERSION, record the change in // common/CHANGELOG.md, then re-copy common/ into EVERY example in the series. // -// The CAS BACnet Stack itself is compiled into the program from source, so its -// C API (CASBACnetStackDLL.h) is linked directly - there is no "load" step. +// The CAS BACnet Stack is linked via the C++ adapter (CASBACnetStackAdapter.h) - +// BACnetStack_* is called directly, the same call whether the stack is compiled from +// source, linked as a static lib, or loaded from a DLL/.so. The example's main() must +// call LoadBACnetFunctions() once, before any BACnetStack_* call, in every mode. // ============================================================================= #include @@ -38,7 +40,7 @@ namespace CASExampleHelper { // version). Bump it whenever anything in common/ changes, and record the // change in common/CHANGELOG.md - every example in the series must then be // re-synced to the same common/ version. -static const char* COMMON_VERSION = "1.4.0"; +static const char* COMMON_VERSION = "1.5.0"; // Print the example's name + version, the linked CAS BACnet Stack version, // and the common/ helper version. diff --git a/common/CHANGELOG.md b/common/CHANGELOG.md index ebd10e5..d60edf8 100644 --- a/common/CHANGELOG.md +++ b/common/CHANGELOG.md @@ -12,6 +12,23 @@ entry here, and must then be re-copied into **every** example in the series. The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/), and the folder adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). +## [1.5.0] - 2026-07-31 + +### Changed + +- **`CASExampleHelper.cpp` now includes `CASBACnetStackAdapter.h` instead of + `CASBACnetStackDLL.h`.** No functional change to `common/`'s own code — it still + calls `BACnetStack_*` directly, same as before. This is a **contract change for + every consuming example's `main()`**: it must call `LoadBACnetFunctions()` once, + before any `BACnetStack_*` call (including before `CASExampleHelper::PrintVersion` + / `HandleHelpAndVersionArgs`, which call `BACnetStack_GetAPIMajorVersion()` etc.), + in every link mode. In source/static-lib mode this was previously a no-op (the + functions are always callable — "linked directly, there is no load step," per the + old header comment); the adapter's DLL mode makes that no longer universally true, + so the load step is now mandatory everywhere for one call to work in all three + modes. B-ASC is the first example adopted onto this; the other 7 need the same + `LoadBACnetFunctions()` call added to their `main()` when they re-sync to 1.5.0. + ## [1.4.0] - 2026-07-18 ### Added diff --git a/main.cpp b/main.cpp index ee37949..b57c184 100644 --- a/main.cpp +++ b/main.cpp @@ -59,7 +59,9 @@ #include "CASExampleHelper.h" #include "CASBACnetStackExampleConstants.h" -#include "CASBACnetStackDLL.h" // the CAS BACnet Stack C API (BACnetStack_*) +#include "CASBACnetStackAdapter.h" // the CAS BACnet Stack C API (BACnetStack_*); call + // LoadBACnetFunctions() before any BACnetStack_* call - + // see the top of main() below. #include #include @@ -842,9 +844,20 @@ int main(int argc, char** argv) { // Show printf output immediately, even when stdout is piped to a file. setvbuf(stdout, NULL, _IONBF, 0); + // --- Load the CAS BACnet Stack ------------------------------------------- + // Required in every link mode (source/static/DLL) before any other + // BACnetStack_* call - see CASBACnetStackAdapter.h. In DLL mode this is the + // step that actually resolves the symbols; skipping it there is a null-pointer + // call, not a silent no-op, so it comes before even --version (which calls + // BACnetStack_GetAPIMajorVersion() to print the linked stack's version). + if (!LoadBACnetFunctions()) { + fprintf(stderr, "Error: failed to load the CAS BACnet Stack: %s\n", + CASBACnetStackAdapter_LastError()); + return 1; + } + // --- Command line + version -------------------------------------------- - // --help / --version print and exit, so handle them before we bind a socket - // or touch the stack. + // --help / --version print and exit, so handle them before we bind a socket. if (CASExampleHelper::HandleHelpAndVersionArgs(argc, argv, APP_NAME, APP_VERSION)) { return 0; } From 380ed308558f5558ca45e8b7cde0eda1da80263c Mon Sep 17 00:00:00 2001 From: Steven Smethurst Date: Fri, 31 Jul 2026 14:32:04 -0700 Subject: [PATCH 06/15] docs: DLL link-mode documentation + verification results README gets a new "Link modes" section under Build (SOURCE/STATIC/DLL, CAS_BACNET_STACK_LINK cache var). CHANGELOG entry summarizes the CMake-target migration across all 3 stages. DLL-mode verification results (built the stack DLL via submodules/cas-bacnet-stack/projects/msvs/BuildCASBACnetStack.sln, ReleaseDll|x64, /p:PlatformToolset=v143 override - v145 isn't installed): - FAILURE PATHS VERIFIED: DLL entirely absent -> clean "could not load the DLL" error, exit 1, no crash. DLL present but missing a required export -> clean "missing export: BACnetStack_X" error naming the exact symbol, exit 1, no crash. Both prove CASBACnetStackAdapter_LastError() and the all-or-nothing binding contract work correctly against a real DLL. - SUCCESS PATH NOT ACHIEVED: the built DLL is missing 3 of 213 declared exports (BACnetStack_RegisterCallbackWriteGroupInhibitDelay, SendWhoAmI, SendYouAre) for reasons not fully root-caused (ruled out incremental-build staleness via a from-scratch clean rebuild; ruled out a source-level #ifdef miss for 2 of the 3, which are unguarded in source). Root-cause + fix is a stack-repo follow-up (task chip spawned) - two leads documented: the STACK_OPTION_TARGET_FULL preset not cascading to STACK_OPTION_WRITE_GROUP, and a possible LTCG/OPT:ICF interaction with __declspec(dllexport) for the unguarded pair. SOURCE and STATIC mode are unaffected (real function linkage, not runtime symbol lookup) and are fully verified end-to-end (Stage C1/C2 commits). Co-Authored-By: Claude Sonnet 5 --- CHANGELOG.md | 17 +++++++++++++++++ README.md | 32 ++++++++++++++++++++++++++++++++ 2 files changed, 49 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 9a44387..1d94fa3 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -35,6 +35,23 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Changed +- **Links the CAS BACnet Stack through the `CASBACnetStack::Adapter` CMake + target instead of hand-globbing the stack's `source/*.cpp`.** `main.cpp` and + `common/CASExampleHelper.cpp` now include `CASBACnetStackAdapter.h` and call + `LoadBACnetFunctions()` once at the top of `main()`; every `BACnetStack_*` + call site is otherwise unchanged. `CAS_BACNET_STACK_LINK` (`SOURCE` default, + or `STATIC`/`DLL`) picks the link mode — see the README's new "Link modes" + section. `SOURCE` and `STATIC` mode are fully verified; `DLL` mode's failure + paths are verified (absent DLL, DLL missing a required export — both fail + cleanly via `CASBACnetStackAdapter_LastError()`, never a crash) but its + success path could not be demonstrated during verification because the + current `ReleaseDll|x64` MSVS build of the stack is missing a few exports for + reasons not yet root-caused — tracked upstream. **TEMPORARY:** the stack + submodule pin currently points at the `adapter-cpp-package` branch tip + (stacked on `adapter-cpp-generate`), not `6.x-TestTool` — see cas-bacnet-stack + PRs #267 and #268; re-pin once both merge. + common/ bumped to v1.5.0 (see `common/CHANGELOG.md`) — this is a contract + change every example in the series needs when it re-syncs. - **Stack pin moved to `6.x-TestTool` @ `b681f58d` (2026-07-31).** 38 commits ahead of the previous pin (`92c91d74`); includes the removal of the 13 `RegisterHookProperty*` exports, the `DecodeAsXML`/`DecodeAsJSON` → diff --git a/README.md b/README.md index 0fa83e8..588a55e 100644 --- a/README.md +++ b/README.md @@ -287,6 +287,38 @@ cmake --build build --config Release If your CAS BACnet Stack lives somewhere other than the bundled submodule, point CMake at it: `cmake -B build -S . -D CAS_STACK_DIR=/path/to/cas-bacnet-stack`. +### Link modes + +This example links the stack through the `CASBACnetStack::Adapter` CMake target +(`submodules/cas-bacnet-stack/adapters/cpp`). `CAS_BACNET_STACK_LINK` picks how: + +```bash +cmake -B build -S . # SOURCE (default) - compiles the stack in +cmake -B build -S . -D CAS_BACNET_STACK_LINK=STATIC # link a prebuilt .lib/.a +cmake -B build -S . -D CAS_BACNET_STACK_LINK=DLL # load a prebuilt .dll/.so at runtime +``` + +Application code (`main.cpp`, `common/`) is identical in every mode - it calls +`BACnetStack_AddDevice(...)` etc. by the exact export name, after one +`LoadBACnetFunctions()` call at the top of `main()`. In `DLL` mode, the built +executable needs `CASBACnetStack_x64_Release.dll` (Windows) or the equivalent +`.so` next to it at runtime (built separately via +`submodules/cas-bacnet-stack/projects/msvs/BuildCASBACnetStack.sln`, +`ReleaseDll|x64` configuration on Windows); `LoadBACnetFunctions()` fails +cleanly with a message from `CASBACnetStackAdapter_LastError()` if the DLL is +missing or absent a required export - see Troubleshooting. + +> **`DLL` mode status:** verified end-to-end for the *failure* paths (DLL +> absent; DLL present but missing a required export) — both fail cleanly with a +> clear message, never a crash. The *success* path (a DLL exporting all 213 +> declared functions) was **not** achieved during verification: the stock +> `ReleaseDll|x64` MSVS build is currently missing a few exports +> (`BACnetStack_RegisterCallbackWriteGroupInhibitDelay`, `BACnetStack_SendWhoAmI`, +> `BACnetStack_SendYouAre`) for reasons not yet root-caused — tracked as a +> follow-up in the stack repo. `SOURCE` and `STATIC` mode are unaffected (they +> link the real functions directly, not by runtime symbol lookup) and are fully +> verified. + ## Run ```bash From 32b5039d8d6009bf1f928888c24c88aa1cca3b03 Mon Sep 17 00:00:00 2001 From: Steven Smethurst Date: Fri, 31 Jul 2026 15:57:44 -0700 Subject: [PATCH 07/15] docs: review-panel corrections; DLL mode now verified working end-to-end Submodule pin -> c22ac0ab, which carries the stack-side fix for the three exports that were silently missing from every DLL build (option guards in CASBACnetStackDLL.h evaluated before any options header was in scope). With that fixed, DLL mode's SUCCESS path works for the first time: the example loads the library, binds all 213 exports, passes the version handshake, and runs - verified on port 47900. Both failure paths still degrade cleanly (library absent -> "could not load ..."; wrong build -> "missing export: ..."). README's Link modes section rewritten accordingly, including the CWD-relative library-lookup caveat and the BACNET_LIB_FILE override. Documentation corrections from the five-persona review: - Version banner and sample output said common/ v1.3.0 against a v1.5.0 tree - the exact drift the README teaches readers to detect. Now accurate, with a "trust the program" note. - Defined at first use: the BIBB -A/-B (client/server side) convention, Protocol_Revision, BACnet/SC, "BACnet internetwork", and a concrete what-is-a-B-ASC anchor (thermostat / VAV / fan-coil). - Verify section now names free clients (YABE, Wireshark) next to the commercial one, so evaluating costs nothing. - Reading order no longer implies you must start at another repository. - New: "What to copy, what to rewrite" - which parts of common/ are demo-only (per-packet printf, keyboard loop, first-adapter IP guess) versus worth keeping. - New: "Calling BACnetStack_Tick() in a real product" - cadence, and the single-threaded contract (the stack contains no locking of any kind; callbacks run synchronously on the calling thread). Verified: SOURCE mode rebuilt + smoke-run (binds, I-Am, RX from a live device); DLL mode built, run, and both failure paths exercised. Co-Authored-By: Claude Opus 5 --- CHANGELOG.md | 27 ++++--- README.md | 148 +++++++++++++++++++++++++++++------- submodules/cas-bacnet-stack | 2 +- 3 files changed, 138 insertions(+), 39 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 1d94fa3..0c7ece5 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -41,17 +41,26 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 `LoadBACnetFunctions()` once at the top of `main()`; every `BACnetStack_*` call site is otherwise unchanged. `CAS_BACNET_STACK_LINK` (`SOURCE` default, or `STATIC`/`DLL`) picks the link mode — see the README's new "Link modes" - section. `SOURCE` and `STATIC` mode are fully verified; `DLL` mode's failure - paths are verified (absent DLL, DLL missing a required export — both fail - cleanly via `CASBACnetStackAdapter_LastError()`, never a crash) but its - success path could not be demonstrated during verification because the - current `ReleaseDll|x64` MSVS build of the stack is missing a few exports for - reasons not yet root-caused — tracked upstream. **TEMPORARY:** the stack - submodule pin currently points at the `adapter-cpp-package` branch tip - (stacked on `adapter-cpp-generate`), not `6.x-TestTool` — see cas-bacnet-stack - PRs #267 and #268; re-pin once both merge. + section. **All three modes are verified**: `SOURCE` and `STATIC` build and run + against a live client, and `DLL` mode now loads the stack, binds all 213 + exports, passes the version handshake and runs — plus both of its failure + paths (library absent; library present but missing an export) report a + readable error and exit cleanly rather than crashing. + **TEMPORARY:** the stack submodule pin currently points at the + `adapter-cpp-package` branch tip (stacked on `adapter-cpp-generate`), not + `6.x-TestTool` — see cas-bacnet-stack PRs #267 and #268; re-pin once both merge. common/ bumped to v1.5.0 (see `common/CHANGELOG.md`) — this is a contract change every example in the series needs when it re-syncs. +- **Documentation corrections from a five-persona review** (lead developer, + educator, junior developer, BACnet newcomer, staff architect): the version + banner and sample output now match the shipped `common/` version (they claimed + v1.3.0 against a v1.5.0 tree — in a project whose own docs teach "the printed + versions are how you detect drift"); the BIBB `-A`/`-B` suffix convention, + `Protocol_Revision`, BACnet/SC and "BACnet internetwork" are now defined at + first use; the Verify section names free clients (YABE, Wireshark) alongside + the commercial one; and two new sections cover what in `common/` is demo-only + versus production-worthy, and the `BACnetStack_Tick()` cadence and + single-threading contract. - **Stack pin moved to `6.x-TestTool` @ `b681f58d` (2026-07-31).** 38 commits ahead of the previous pin (`92c91d74`); includes the removal of the 13 `RegisterHookProperty*` exports, the `DecodeAsXML`/`DecodeAsJSON` → diff --git a/README.md b/README.md index 588a55e..e713a58 100644 --- a/README.md +++ b/README.md @@ -10,12 +10,22 @@ It listens on **BACnet/IP (UDP 47808)**, answers **ReadProperty**, accepts Part of the CAS BACnet Stack **BACnet profile example series** - one repository per BACnet device profile. This example claims **only** B-ASC. -Reading order: [B-SS (Smart Sensor)](https://github.com/chipkin/BACnetProfileExample-B-SS-CPP) is the **first** example and the one to -start with, then [B-SA (Smart Actuator)](https://github.com/chipkin/BACnetProfileExample-B-SA-CPP); this is the **third**. +Reading order: this repository stands on its own — **you can start here.** If you also want the +gentler introductions to the shared sensor/actuator objects, [B-SS (Smart +Sensor)](https://github.com/chipkin/BACnetProfileExample-B-SS-CPP) is the first example in the +series and [B-SA (Smart Actuator)](https://github.com/chipkin/BACnetProfileExample-B-SA-CPP) the +second; this is the third and repeats everything it needs. > **Versions:** this document describes **example v1.1.0**, built and verified -> against **CAS BACnet Stack 6.0.0.0** at **Protocol_Revision 24**, with the -> vendored `common/` helper at **v1.3.0**. Running the example prints all three. +> against **CAS BACnet Stack 6.x** at **Protocol_Revision 24**, with the +> vendored `common/` helper at **v1.5.0**. Running the example prints all three — +> if what it prints disagrees with this line, trust the program and check +> `CHANGELOG.md`. +> +> **Protocol_Revision** is the revision of the ASHRAE 135 standard a device claims to conform +> to. It is a number every BACnet device advertises, and it changes real behaviour: at revision +> 20 and above, for example, the deprecated plain `disable` form of +> DeviceCommunicationControl must be rejected (see that section below). ## Quickstart @@ -56,9 +66,23 @@ certify devices against it. (New to BACnet in general? See Chipkin's [What is BACnet?](https://docs.chipkin.com/protocols/bacnet/) guide.) **B-ASC (BACnet Application Specific Controller)** is a controller with limited -resources, intended for a specific application. Compared to a Smart Actuator, it +resources, intended for a specific application - think a thermostat, a VAV box +controller, or a fan-coil controller: it does one job, and it does not have the +memory or CPU of a supervisory panel. Compared to a Smart Actuator, it adds the requirement to respond to communication-control messages. +**Reading the capability names.** Each capability below is a **BIBB** (BACnet +Interoperability Building Block) - the standard's unit of "this device can do this one +thing." Every BIBB name ends in **-A** or **-B**: + +- **-A** = the **A side**, the device that *initiates* the request (a client - an operator + workstation, a supervisory controller). +- **-B** = the **B side**, the device that *responds* to it (a server - this example). + +So `DS-RP-B` reads as "Data Sharing, ReadProperty, B side": *answers* ReadProperty requests. +A device profile is essentially a required list of BIBBs. This example implements only B-side +BIBBs, because a B-ASC is a device that gets asked, not one that asks. + **What the profile requires:** - **Data Sharing - ReadProperty - B side (DS-RP-B):** answer **ReadProperty**. @@ -197,6 +221,15 @@ as a Chipkin demo. None of it is cosmetic. > uniqueness problem the code comments warn about. In a real product, > `Object_Name` must be per-unit configurable too (serial number, DIP switches, > a config file, or a `--deviceName` argument). +> +> "Unique across the **BACnet internetwork**" means unique across *every* BACnet network +> reachable from this one — all the IP subnets and MS/TP segments joined by BACnet routers, +> which at a typical site means the whole building or campus, not just your local subnet. Two +> devices with the same name on opposite sides of a router still collide. +> +> Running several of these examples on one desk (or a classroom of students on one subnet) +> hits this immediately: pass a different `--deviceID` to each, and expect the duplicate +> `Object_Name` until you make it configurable. `main.cpp` marks this block with a `CHANGE ALL OF THIS BEFORE YOU SHIP` banner. @@ -298,26 +331,38 @@ cmake -B build -S . -D CAS_BACNET_STACK_LINK=STATIC # link a prebuilt .lib/.a cmake -B build -S . -D CAS_BACNET_STACK_LINK=DLL # load a prebuilt .dll/.so at runtime ``` -Application code (`main.cpp`, `common/`) is identical in every mode - it calls -`BACnetStack_AddDevice(...)` etc. by the exact export name, after one -`LoadBACnetFunctions()` call at the top of `main()`. In `DLL` mode, the built -executable needs `CASBACnetStack_x64_Release.dll` (Windows) or the equivalent -`.so` next to it at runtime (built separately via -`submodules/cas-bacnet-stack/projects/msvs/BuildCASBACnetStack.sln`, -`ReleaseDll|x64` configuration on Windows); `LoadBACnetFunctions()` fails -cleanly with a message from `CASBACnetStackAdapter_LastError()` if the DLL is -missing or absent a required export - see Troubleshooting. - -> **`DLL` mode status:** verified end-to-end for the *failure* paths (DLL -> absent; DLL present but missing a required export) — both fail cleanly with a -> clear message, never a crash. The *success* path (a DLL exporting all 213 -> declared functions) was **not** achieved during verification: the stock -> `ReleaseDll|x64` MSVS build is currently missing a few exports -> (`BACnetStack_RegisterCallbackWriteGroupInhibitDelay`, `BACnetStack_SendWhoAmI`, -> `BACnetStack_SendYouAre`) for reasons not yet root-caused — tracked as a -> follow-up in the stack repo. `SOURCE` and `STATIC` mode are unaffected (they -> link the real functions directly, not by runtime symbol lookup) and are fully -> verified. +**Application code is identical in every mode.** `main.cpp` and `common/` call +`BACnetStack_AddDevice(...)` and friends by the exact export name; switching modes changes +only the CMake flag, never a line of your code. The one requirement all three share is calling +`LoadBACnetFunctions()` once at the top of `main()` before any other `BACnetStack_*` call — in +`DLL` mode that is the step that binds the symbols, and it also runs a version handshake in +every mode. + +**Extra step for `DLL` mode:** build the library and put it where the executable can find it. + +```bash +# Windows: build CASBACnetStack_x64_Release.dll (ReleaseDll|x64) +msbuild submodules/cas-bacnet-stack/projects/msvs/CASBACnetStack/CASBACnetStack.vcxproj \ + /p:Configuration=ReleaseDll /p:Platform=x64 +# then copy submodules/cas-bacnet-stack/bin/CASBACnetStack_x64_Release.dll +# next to build-dll/Release/BACnetExampleBASC.exe +``` + +If it cannot be loaded, `LoadBACnetFunctions()` returns false and +`CASBACnetStackAdapter_LastError()` says why — `could not load +CASBACnetStack_x64_Release.dll` when the file is absent, or `missing export: +BACnetStack_` when the library is the wrong build. The program exits with a message +rather than crashing. + +> **Verified:** all three modes were built and run against a live BACnet client for this +> release. `DLL` mode was additionally checked for both failure paths (library absent; +> library present but missing an export) — each reports a readable error and exits cleanly. +> +> Note the default library name is looked up on the OS search path and **relative to the +> current working directory**, not to the executable's directory — so launching from a +> different working directory will not find a DLL that merely sits beside the .exe. Define +> `BACNET_LIB_FILE` to an absolute path if that matters to your deployment (see +> `adapters/cpp/CASBACnetStackAdapter.h`). ## Run @@ -334,7 +379,7 @@ Expected output: ``` BACnet B-ASC (Application Specific Controller) Example - C++ v1.1.0 CAS BACnet Stack version: 6.0.0.0 -Common helper (common/) version: 1.3.0 +Common helper (common/) version: 1.5.0 FYI: Listening for BACnet/IP on UDP port 47808. TX 21 bytes to 192.168.3.255:47808 (broadcast) ... (one or more red "Error:" lines here - expected and benign; see Troubleshooting) ... @@ -380,8 +425,17 @@ the series): ## Verify -Use a BACnet client such as the -[**CAS BACnet Explorer**](https://store.chipkin.com/products/tools/cas-bacnet-explorer): +You need a BACnet client to talk to the device. Any of these work: + +- [**CAS BACnet Explorer**](https://store.chipkin.com/products/tools/cas-bacnet-explorer) - + Chipkin's commercial client (free trial), used for the steps below. +- [**YABE**](https://sourceforge.net/projects/yetanotherbacnetexplorer/) ("Yet Another BACnet + Explorer") - free and open source; enough to discover, browse, read, and write. +- [**Wireshark**](https://www.wireshark.org/) with the `bvlc` display filter - free; shows you + the actual packets rather than an object tree, which is the better choice when you want to + understand the protocol or prove what went on the wire. + +Then: 1. **Discover** - send a **Who-Is**. The device replies with **I-Am** from instance **389003** (vendor **389**). It also broadcasts an I-Am at start-up. @@ -405,7 +459,7 @@ Use a BACnet client such as the | Symptom | Cause / fix | |---------|-------------| -| On start-up the app prints a wall of red `Error:` lines but the device works | **Expected — this is not your bug.** Two benign sources, both from the stack's own debug logging: (1) the device receives its **own** broadcast I-Am and logs a decode cascade (*"Services is not supported service=[0]"* … *"Failed to process the incoming NPDU"*) — any BACnet/IP device that listens for broadcasts hears itself; (2) a one-time *"UUID has not been set. A UUID must be set for the BACnetSC device to start."* — the stack starts a BACnet/SC datalink these IP-only examples never configure. It appears once and does not spam. How many red lines you see depends on subnet traffic: on a quiet network it can be a single line (just the UUID one); on a busy BACnet subnet the self-heard-broadcast decodes pile up into a wall. Either way the device is fine. | +| On start-up the app prints a wall of red `Error:` lines but the device works | **Expected — this is not your bug.** Two benign sources, both from the stack's own debug logging: (1) the device receives its **own** broadcast I-Am and logs a decode cascade (*"Services is not supported service=[0]"* … *"Failed to process the incoming NPDU"*) — any BACnet/IP device that listens for broadcasts hears itself; (2) a one-time *"UUID has not been set. A UUID must be set for the BACnetSC device to start."* — the stack starts a BACnet/SC (BACnet Secure Connect, the TLS/WebSocket-based transport added in ASHRAE 135-2020) datalink that these BACnet/IP-only examples never configure. It appears once and does not spam. How many red lines you see depends on subnet traffic: on a quiet network it can be a single line (just the UUID one); on a busy BACnet subnet the self-heard-broadcast decodes pile up into a wall. Either way the device is fine. | | CMake error: *"CAS BACnet Stack source not found"* | Submodules not initialized. Run `git submodule update --init --recursive` (or pass `-D CAS_STACK_DIR=...`). | | `CASBACnetStackDLL.h: No such file or directory` | Same - submodules not checked out. | | Windows: *"No CMAKE_CXX_COMPILER could be found"* | Install Visual Studio with the "Desktop development with C++" workload, then re-run from a fresh terminal. | @@ -546,4 +600,40 @@ public domain under [CC0-1.0](LICENSE) - use it for anything, no attribution required. The CAS BACnet Stack is a separate, commercially licensed product and is not covered by CC0. +### What to copy, what to rewrite + +`common/` is written for a **console demo**, not for a product. Copy it to get started, then +expect to replace these before you ship: + +| In `common/` | Why it is not production code | What a product does instead | +|---|---|---| +| `printf` on every RX/TX in the transport callbacks (`CASExampleHelper.cpp`) | Console I/O on the BACnet hot path - slow, and noise once the device is real | Log to your own logger at debug level, or drop it | +| The keyboard loop (`h`/`q`/arrows) | There is no console on an embedded device | Delete it; drive values from your real I/O | +| `GetLocalIPv4()` picking the first non-loopback adapter | A guess; wrong on multi-homed hardware | Bind the interface your product is configured for | +| `SimpleUDP` | Minimal blocking-socket demo | Your platform's networking stack | +| `PrintVersion` / `--help` / `--port` / `--deviceID` | Demo ergonomics | Your own configuration mechanism | + +What you *should* keep the shape of: the three transport/time callbacks +(`RegisterCommonCallbacks`), the deferred-restart pattern (`RequestRestart`/`RestartDue`), and +the `LoadBACnetFunctions()` call at the top of `main()`. + +### Calling `BACnetStack_Tick()` in a real product + +The example calls `Tick()` in a tight loop with a 1 ms sleep. What the stack actually requires: + +- **Call it regularly.** Every timer the stack owns - APDU retries/timeouts, COV lifetimes, + DCC durations, Schedule/Trend evaluation - advances only inside `Tick()`. A gap means late + or missed BACnet behaviour, not a crash. Every ~10 ms is comfortable; do not let it drift + into hundreds of milliseconds. +- **It is not free-running.** It does the work available and returns; it does not block. +- **Single-threaded contract.** The stack contains **no locking of any kind** (no mutexes, no + atomics - grep it), and `Tick()` invokes your property callbacks on the calling thread, + synchronously, before it returns. So: call `Tick()` from exactly one thread, never + concurrently from two, and do not call any other `BACnetStack_*` function from a different + thread. If your application is multi-threaded, own the stack from one task and marshal work + to it (a queue your callbacks read from is the usual shape). +- **Never block inside a callback.** A callback that waits on slow I/O stalls `Tick()`, and + with it every timer above. Serve cached values and do the slow work elsewhere (`main.cpp` + says the same at each `GetProperty*` callback). + See also [CHANGELOG.md](CHANGELOG.md). Contributors and AI agents: [AGENTS.md](AGENTS.md) documents the repo conventions. diff --git a/submodules/cas-bacnet-stack b/submodules/cas-bacnet-stack index 8780d41..c22ac0a 160000 --- a/submodules/cas-bacnet-stack +++ b/submodules/cas-bacnet-stack @@ -1 +1 @@ -Subproject commit 8780d4128d50d6376e40188dd91bcd83cfdb2dc4 +Subproject commit c22ac0ab82b2e1c4b0079d51dcf9246daa620d47 From b3530483a5c9a2f3f4a77a28e969c1e6879d226e Mon Sep 17 00:00:00 2001 From: Steven Smethurst Date: Fri, 31 Jul 2026 16:22:29 -0700 Subject: [PATCH 08/15] docs: round-2 review fixes (common/ v1.5.1) common/ 1.5.1: - --help printed the version banner twice (the handler printed it, then PrintHelp printed it again). Split the interactive key list into its own helper; --help now prints banner / usage / keys once each. - common/README.md was STALE in the way that matters most: it still said the stack "is compiled from source... there is no DLL to load at runtime", and its "How main.cpp uses it" skeleton - presented as a starting point to copy - omitted LoadBACnetFunctions(), which 1.5.0 had just made mandatory in every link mode. Copying it produced exactly the bug 1.5.0 exists to prevent (a null-pointer call in DLL mode). This was a regression from this arc's own work: CASExampleHelper.h/.cpp were updated and the folder's README was not. README corrections (all reported by the review panel, each verified first): - Troubleshooting named a CMake error string that no longer exists - CMake now says "CAS BACnet Stack adapter not found under:", so searching the README for the real message found nothing. Added the STATIC-mode configure error too. - A troubleshooting row blamed SO_REUSEADDR for duplicate-device symptoms; common/SimpleUDP.cpp deliberately asks for SO_EXCLUSIVEADDRUSE on Windows so that case fails loudly at bind instead. Rewritten per-platform. - New troubleshooting row for the most likely silent failure on a dev laptop: the example picks the first non-loopback adapter, which with Hyper-V/WSL/ VirtualBox/VPN is often not the real NIC, so the device looks healthy and no client ever sees it. Says to check the IP in the TX line. - Expected-output block listed the red Error line before "Device ready"; the real order is TX -> ready -> RX -> Error. Corrected, and noted that those lines are traffic-dependent. - Added --parallel to the build instructions (the ~600-file first build is the single largest time cost, and matters most when running a class through it). - Version banner in the sample output refreshed to common/ 1.5.1. Verified: rebuilt, --help prints one banner, smoke-run on --port 47899 shows the documented startup sequence with the banner matching the README. Co-Authored-By: Claude Opus 5 --- README.md | 22 ++++++++++++++++++---- common/CASExampleHelper.cpp | 12 +++++++++--- common/CASExampleHelper.h | 2 +- common/CHANGELOG.md | 15 +++++++++++++++ common/README.md | 21 ++++++++++++++++++--- submodules/cas-bacnet-stack | 2 +- 6 files changed, 62 insertions(+), 12 deletions(-) diff --git a/README.md b/README.md index e713a58..db61076 100644 --- a/README.md +++ b/README.md @@ -316,6 +316,13 @@ cmake --build build --config Release > **First build takes a few minutes** - it compiles the entire CAS BACnet Stack > (~600 source files) once. Incremental rebuilds after that are fast. +> +> Build in parallel to cut that down substantially - this is worth doing on the first +> build of the day, and essential if you are running a class through it: +> +> ```bash +> cmake --build build --config Release --parallel +> ``` If your CAS BACnet Stack lives somewhere other than the bundled submodule, point CMake at it: `cmake -B build -S . -D CAS_STACK_DIR=/path/to/cas-bacnet-stack`. @@ -379,13 +386,18 @@ Expected output: ``` BACnet B-ASC (Application Specific Controller) Example - C++ v1.1.0 CAS BACnet Stack version: 6.0.0.0 -Common helper (common/) version: 1.5.0 +Common helper (common/) version: 1.5.1 FYI: Listening for BACnet/IP on UDP port 47808. TX 21 bytes to 192.168.3.255:47808 (broadcast) -... (one or more red "Error:" lines here - expected and benign; see Troubleshooting) ... FYI: Device 389003 ("Rainbow") ready. Vendor ID 389. Press 'h' for help. +RX 21 bytes from 192.168.3.76:47808 +... (one or more red "Error:" lines - expected and benign; see Troubleshooting) ... ``` +The `RX`/`Error:` lines depend on what else is on your network, so they may appear +earlier, later, or (on a quiet subnet) only as a single line. The device is ready as +soon as the `Device ... ready` line prints. + Those first three lines are worth reading: they tell you the **example** version, the **stack** version you actually linked, and the version of the vendored `common/` helper — which is how you tell whether this repo's copy has drifted from @@ -460,7 +472,9 @@ Then: | Symptom | Cause / fix | |---------|-------------| | On start-up the app prints a wall of red `Error:` lines but the device works | **Expected — this is not your bug.** Two benign sources, both from the stack's own debug logging: (1) the device receives its **own** broadcast I-Am and logs a decode cascade (*"Services is not supported service=[0]"* … *"Failed to process the incoming NPDU"*) — any BACnet/IP device that listens for broadcasts hears itself; (2) a one-time *"UUID has not been set. A UUID must be set for the BACnetSC device to start."* — the stack starts a BACnet/SC (BACnet Secure Connect, the TLS/WebSocket-based transport added in ASHRAE 135-2020) datalink that these BACnet/IP-only examples never configure. It appears once and does not spam. How many red lines you see depends on subnet traffic: on a quiet network it can be a single line (just the UUID one); on a busy BACnet subnet the self-heard-broadcast decodes pile up into a wall. Either way the device is fine. | -| CMake error: *"CAS BACnet Stack source not found"* | Submodules not initialized. Run `git submodule update --init --recursive` (or pass `-D CAS_STACK_DIR=...`). | +| CMake error: *"CAS BACnet Stack adapter not found under: ..."* | Submodules not initialized. Run `git submodule update --init --recursive` (or pass `-D CAS_STACK_DIR=...`). | +| CMake error: *"CAS_BACNET_STACK_LINK=STATIC needs a prebuilt CAS BACnet Stack library"* | `STATIC` links a library you build separately; it does not compile the stack. Either build it (the message gives the exact `msbuild` line) and re-run CMake, or use the default `SOURCE` mode, which needs no prebuilt library. | +| The device starts and prints `TX ... (broadcast)`, but no client ever sees it | Check the IP in that `TX` line against the subnet your BACnet client is on. The example picks the **first non-loopback adapter** the OS reports, which on a laptop with Hyper-V, WSL, VirtualBox or a VPN is frequently not your Wi-Fi/Ethernet. There is no `--interface` option yet; disable the unwanted virtual adapters, or run on a machine without them. (Also check the firewall row above.) | | `CASBACnetStackDLL.h: No such file or directory` | Same - submodules not checked out. | | Windows: *"No CMAKE_CXX_COMPILER could be found"* | Install Visual Studio with the "Desktop development with C++" workload, then re-run from a fresh terminal. | | First build seems stuck for minutes | Normal - it's compiling ~600 stack files. Only the first build is slow. | @@ -469,7 +483,7 @@ Then: | DeviceCommunicationControl `disable` returns an error | Expected. The plain `disable` value is deprecated at Protocol_Revision >= 20; use `disable-initiation` instead. | | WriteProperty to an output is rejected | Write to the **output** objects, not the inputs (inputs are read-only sensors), and keep the value in range. | | Client sends Who-Is but sees no I-Am | Firewall is blocking UDP 47808, or the client and device are on different subnets. Allow the port; test on the same subnet first. | -| Replies show an unexpected device instance or vendor | Another BACnet device is already running on this host/port (the socket uses `SO_REUSEADDR`). Stop the other device, or run this example on its own machine/IP. | +| Replies show an unexpected device instance or vendor | Another BACnet device is already answering on this host/port. On Linux/macOS two processes can share the port and both reply; on Windows the example asks for `SO_EXCLUSIVEADDRUSE` (`common/SimpleUDP.cpp`) so this shows up as a bind failure instead. Stop the other device, or use `--port`. | ## Extending the example diff --git a/common/CASExampleHelper.cpp b/common/CASExampleHelper.cpp index 8befead..dd9f127 100644 --- a/common/CASExampleHelper.cpp +++ b/common/CASExampleHelper.cpp @@ -311,8 +311,9 @@ void PrintVersion(const char* appName, const char* appVersion) { printf("Common helper (common/) version: %s\n", COMMON_VERSION); } -void PrintHelp(const char* appName, const char* appVersion) { - PrintVersion(appName, appVersion); +// Just the interactive key list, with no version banner - so the two callers that already +// printed one (PrintHelp for the 'h' key, and the --help handler) do not print it twice. +static void PrintInteractiveCommands() { printf("Commands:\n"); printf(" h - show this help (version + commands)\n"); printf(" q - quit\n"); @@ -320,6 +321,11 @@ void PrintHelp(const char* appName, const char* appVersion) { printf(" down - decrease Analog Input 1 by 1.1\n"); } +void PrintHelp(const char* appName, const char* appVersion) { + PrintVersion(appName, appVersion); + PrintInteractiveCommands(); +} + bool HandleHelpAndVersionArgs(const int argc, char** argv, const char* appName, const char* appVersion) { for (int i = 1; i < argc; ++i) { if (strcmp(argv[i], "--help") == 0 || strcmp(argv[i], "-h") == 0 || @@ -338,7 +344,7 @@ bool HandleHelpAndVersionArgs(const int argc, char** argv, const char* appName, printf(" Use a non-default port to avoid clashing with another\n"); printf(" BACnet device already on 47808 on this host.\n"); printf("\n"); - PrintHelp(appName, appVersion); + PrintInteractiveCommands(); // version banner already printed above return true; } if (strcmp(argv[i], "--version") == 0) { diff --git a/common/CASExampleHelper.h b/common/CASExampleHelper.h index 0dcd263..40efc75 100644 --- a/common/CASExampleHelper.h +++ b/common/CASExampleHelper.h @@ -40,7 +40,7 @@ namespace CASExampleHelper { // version). Bump it whenever anything in common/ changes, and record the // change in common/CHANGELOG.md - every example in the series must then be // re-synced to the same common/ version. -static const char* COMMON_VERSION = "1.5.0"; +static const char* COMMON_VERSION = "1.5.1"; // Print the example's name + version, the linked CAS BACnet Stack version, // and the common/ helper version. diff --git a/common/CHANGELOG.md b/common/CHANGELOG.md index d60edf8..c9d9310 100644 --- a/common/CHANGELOG.md +++ b/common/CHANGELOG.md @@ -12,6 +12,21 @@ entry here, and must then be re-copied into **every** example in the series. The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/), and the folder adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). +## [1.5.1] - 2026-07-31 + +### Fixed + +- **`--help` printed the version banner twice.** The handler printed it, then called + `PrintHelp()` which printed it again. The interactive key list is now a separate + internal helper, so `--help` prints banner → usage → keys once each. `PrintHelp()` + (what the `h` key shows) is unchanged. +- **`common/README.md` was stale and taught a `main()` skeleton that no longer works.** + It still said the stack "is compiled from source… there is no DLL to load at runtime", + and its snippet omitted `LoadBACnetFunctions()` — which 1.5.0 made mandatory in every + link mode. Anyone using that snippet as their starting point wrote the exact bug 1.5.0 + was written to prevent (in DLL mode, a null-pointer call). The README now leads with the + load call and explains why it is not optional. + ## [1.5.0] - 2026-07-31 ### Changed diff --git a/common/README.md b/common/README.md index 3386b2d..caa1868 100644 --- a/common/README.md +++ b/common/README.md @@ -30,6 +30,14 @@ example repository. ## How `main.cpp` uses it ```cpp +// FIRST, before any other BACnetStack_* call - including anything in this helper, since +// PrintVersion() asks the stack for its version. Mandatory in every link mode. +if (!LoadBACnetFunctions()) { + fprintf(stderr, "Error: failed to load the CAS BACnet Stack: %s\n", + CASBACnetStackAdapter_LastError()); + return 1; +} + const uint16_t port = CASExampleHelper::ParsePortArg(argc, argv, 47808); g_deviceInstance = CASExampleHelper::ParseDeviceIdArg(argc, argv, g_deviceInstance); CASExampleHelper::PrintVersion(APP_NAME, APP_VERSION); // app + stack version @@ -45,6 +53,13 @@ while (running) { CASExampleHelper::RestoreInput(); ``` -The CAS BACnet Stack (a git submodule of this repository) is compiled from -source, so its C API (`CASBACnetStackDLL.h`) is called directly as -`BACnetStack_*` — there is no DLL to load at runtime. +The CAS BACnet Stack (a git submodule of this repository) is reached through the C++ +adapter (`adapters/cpp/CASBACnetStackAdapter.h`), so its C API is called directly as +`BACnetStack_*` — the same call whether the stack is compiled from source, linked as a +static library, or loaded from a DLL/.so at runtime. Which of those happens is a build-time +choice (`CAS_BACNET_STACK_LINK`); the code above does not change. + +**That is why `LoadBACnetFunctions()` is not optional.** In DLL mode it is the call that +binds the symbols, so skipping it leaves every `BACnetStack_*` name a null pointer; in the +other modes it still runs the stack-version handshake. Call it once, at the top of `main()`, +from a single thread. See `common/CHANGELOG.md` 1.5.0. diff --git a/submodules/cas-bacnet-stack b/submodules/cas-bacnet-stack index c22ac0a..00c7d14 160000 --- a/submodules/cas-bacnet-stack +++ b/submodules/cas-bacnet-stack @@ -1 +1 @@ -Subproject commit c22ac0ab82b2e1c4b0079d51dcf9246daa620d47 +Subproject commit 00c7d14f93dda4f0a28d8d30e6c52ad6c0430498 From 55f3098574b385dc8c59198e4705bec3d2c60d58 Mon Sep 17 00:00:00 2001 From: Steven Smethurst Date: Fri, 31 Jul 2026 16:27:44 -0700 Subject: [PATCH 09/15] docs: STATIC link mode now works and is documented Submodule -> 9f95ff2a (STATIC-mode MSVC runtime fix). STATIC previously configured but could not link - the prebuilt library is built /MT and consumers default to /MD, giving 562 LNK2038 errors that read like a corrupt library. README now documents the ReleaseLib build step, the automatic library lookup (and CAS_BACNET_STACK_LIB override), and the /MT forcing. The 'all three modes verified' claim is now actually earned: SOURCE, STATIC and DLL were each built AND run, with STATIC confirmed to need no DLL beside the executable. Co-Authored-By: Claude Opus 5 --- .gitignore | 2 ++ README.md | 23 ++++++++++++++++++++--- submodules/cas-bacnet-stack | 2 +- 3 files changed, 23 insertions(+), 4 deletions(-) diff --git a/.gitignore b/.gitignore index 68d6cf9..8723bc1 100644 --- a/.gitignore +++ b/.gitignore @@ -1,2 +1,4 @@ # CMake build output build/ + +build-static/ diff --git a/README.md b/README.md index db61076..aba88e1 100644 --- a/README.md +++ b/README.md @@ -345,6 +345,21 @@ only the CMake flag, never a line of your code. The one requirement all three sh `DLL` mode that is the step that binds the symbols, and it also runs a version handshake in every mode. +**Extra step for `STATIC` mode:** build the static library first — this mode links a prebuilt +`.lib`/`.a`, it does not compile the stack. + +```bash +# Windows: build CASBACnetStack_x64_Release.lib (ReleaseLib|x64) into /bin/ +msbuild submodules/cas-bacnet-stack/projects/msvs/CASBACnetStack/CASBACnetStack.vcxproj \ + /p:Configuration=ReleaseLib /p:Platform=x64 +``` + +CMake then finds it automatically in the stack's `bin/`; point elsewhere with +`-D CAS_BACNET_STACK_LIB=/path/to/lib`. If no library is there, configuration stops with +that `msbuild` line in the error rather than failing later at link. On MSVC the adapter also +forces the static CRT (`/MT`) to match how the library is built — mixing runtimes otherwise +produces hundreds of `LNK2038` errors that look like a corrupt library. + **Extra step for `DLL` mode:** build the library and put it where the executable can find it. ```bash @@ -361,9 +376,11 @@ CASBACnetStack_x64_Release.dll` when the file is absent, or `missing export: BACnetStack_` when the library is the wrong build. The program exits with a message rather than crashing. -> **Verified:** all three modes were built and run against a live BACnet client for this -> release. `DLL` mode was additionally checked for both failure paths (library absent; -> library present but missing an export) — each reports a readable error and exits cleanly. +> **Verified:** all three modes were built **and run** for this release — `SOURCE`, +> `STATIC` (confirmed with no DLL beside the executable, which is the point of static +> linking), and `DLL`. `DLL` mode was additionally checked for both failure paths (library +> absent; library present but missing an export) — each reports a readable error and exits +> cleanly. > > Note the default library name is looked up on the OS search path and **relative to the > current working directory**, not to the executable's directory — so launching from a diff --git a/submodules/cas-bacnet-stack b/submodules/cas-bacnet-stack index 00c7d14..9f95ff2 160000 --- a/submodules/cas-bacnet-stack +++ b/submodules/cas-bacnet-stack @@ -1 +1 @@ -Subproject commit 00c7d14f93dda4f0a28d8d30e6c52ad6c0430498 +Subproject commit 9f95ff2afed53fed7d8c3b467b6693ebd1e749eb From 90903ebcb2658f3ba9e2200966e23ea83c5e8a92 Mon Sep 17 00:00:00 2001 From: Steven Smethurst Date: Fri, 31 Jul 2026 16:29:27 -0700 Subject: [PATCH 10/15] build: bump stack pin to f30fa46d (adapters/README.md heading fix) Co-Authored-By: Claude Opus 5 --- submodules/cas-bacnet-stack | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/submodules/cas-bacnet-stack b/submodules/cas-bacnet-stack index 9f95ff2..f30fa46 160000 --- a/submodules/cas-bacnet-stack +++ b/submodules/cas-bacnet-stack @@ -1 +1 @@ -Subproject commit 9f95ff2afed53fed7d8c3b467b6693ebd1e749eb +Subproject commit f30fa46da68b7462cc2e55109eb0e8b3186e7728 From 7fb5574e8c952a1b787c83e22d4c516e5f95ded4 Mon Sep 17 00:00:00 2001 From: Steven Smethurst Date: Fri, 31 Jul 2026 16:39:33 -0700 Subject: [PATCH 11/15] docs: remove maintainer-log comments; the example should read as a snapshot A customer opening main.cpp for the first time has no interest in what a previous version of the file said. Several comments narrated this repo's own review history at the reader, which undermines confidence in the thing they are reading rather than building it. Removed the self-referential framing while keeping every technical claim: - 'the most important paragraph in the file, because an earlier version of this comment got it backwards' -> states the same warning directly. - 'HONEST NOTE, because an earlier version of this comment was wrong and a reader would have found out the hard way' -> 'WORTH KNOWING BEFORE YOU COPY THIS'. - 'This example shipped exactly that bug; it was caught by a reviewer tracing the stack source' -> explains the failure is invisible in code review, which is the part a reader can act on. - 'Trust the code, not the comment - including this one: go read it' -> cut; a comment telling you not to trust comments is not guidance. - 'this loop used to hardcode a literal 1' -> says what to do and why, without the archaeology. - 'v6: the old AddNetworkPortObject was removed' -> describes what the current arguments mean; migration notes belong in the stack's own changelog. Comment-only: shows no non-comment line changed. Rebuilt and smoke-tested to confirm identical behaviour. Co-Authored-By: Claude Opus 5 --- main.cpp | 46 +++++++++++++++++++++------------------------- 1 file changed, 21 insertions(+), 25 deletions(-) diff --git a/main.cpp b/main.cpp index b57c184..fb8df75 100644 --- a/main.cpp +++ b/main.cpp @@ -225,12 +225,12 @@ static bool ReadPrioritySlot(const Commandable* c, uint32_t propertyIdentifier, // stack uses a separate callback. We return true (and fill *value) when we // recognise the (object, property) pair, and false otherwise. // -// WHAT false ACTUALLY DOES - and this is the most important paragraph in the -// file, because an earlier version of this comment got it backwards. Returning -// false does NOT reliably produce a BACnet error. The stack only errors for the -// handful of properties it refuses to invent (BACnetBusinessLogic.cpp: the -// valueShouldBeInitialized switch) - Present_Value, Number_Of_States, -// Relinquish_Default, Local_Date, Local_Time, and a Network Port's APDU_Length. +// WHAT false ACTUALLY DOES - the most important paragraph in this file, and the +// opposite of what most people assume. Returning false does NOT reliably produce +// a BACnet error. The stack only errors for the handful of properties it refuses +// to invent (BACnetBusinessLogic.cpp: the valueShouldBeInitialized switch) - +// Present_Value, Number_Of_States, Relinquish_Default, Local_Date, Local_Time, +// and a Network Port's APDU_Length. // For EVERYTHING ELSE, a false return falls through to GetDefaultPropertyValue() // (BACnetDBDevice.cpp) and the stack SILENTLY SUBSTITUTES a default: // Object_Name -> the literal string "undefined" @@ -255,7 +255,8 @@ static bool ReadPrioritySlot(const Commandable* c, uint32_t propertyIdentifier, // // So: when you add an instance, walk EVERY callback below, then read back every // required property of the new object and DIFF IT against the existing one. Do -// not trust "it scanned OK" - that is exactly the failure mode. The README's "Extending the example" recipe lists the edits. +// not trust "it scanned OK" - that is exactly the failure mode. The README's +// "Extending the example" recipe lists the edits. // ----------------------------------------------------------------------------- // REAL (floating point) - the Analog Input's Present_Value. @@ -831,9 +832,6 @@ bool DeviceCommunicationControl(const uint32_t deviceInstance, const uint8_t ena // // This differs from the SetProperty* callbacks, which DO have a sensible // fallback (writeAccessDenied) - so do not carry the habit across. - // (The stack's own comment at that site says "otherwise assume - // passwordFailure"; the code does not do that. Trust the code, not the - // comment - including this one: go read it.) return true; } @@ -975,9 +973,9 @@ int main(int argc, char** argv) { // Every BACnet device (Protocol_Revision 17+) must have at least one Network // Port object describing the port it talks on. This one is the BACnet/IP // application port; it is the lowest layer, so its reference port is "none". - // v6: the old AddNetworkPortObject was removed - use the WithNetworkNumber - // form. networkNumber 0 + quality "unknown" reproduce the old behaviour (a - // local port that has not learned its network number). + // networkNumber 0 with quality "unknown" describes a local port that has not + // learned its network number - the right answer for a device that is not a + // router and has not been told one. if (!BACnetStack_AddNetworkPortObjectWithNetworkNumber( g_deviceInstance, NETWORK_PORT_INSTANCE, NETWORK_PORT_NETWORK_TYPE_IPV4, @@ -1003,9 +1001,9 @@ int main(int argc, char** argv) { // IsPropertyEnabled BEFORE it ever reaches the callbacks, and for an optional // property that check falls back to "is it required?" - which is false. So a // Description branch in the callback without this enable is DEAD CODE, and - // the client reads back Error: unknown-property. (This example shipped - // exactly that bug; it was caught by a reviewer tracing the stack source, not - // by running it - a plausible-looking callback branch that never executes.) + // the client reads back Error: unknown-property. Note that this fails + // invisibly: the callback branch looks correct and simply never runs, so you + // only find it by reading back the property, not by inspecting the code. if (!BACnetStack_SetPropertyEnabled(g_deviceInstance, OBJECT_TYPE_DEVICE, g_deviceInstance, PROPERTY_IDENTIFIER_DESCRIPTION, true)) { @@ -1024,10 +1022,9 @@ int main(int argc, char** argv) { // writing NULL relinquishes it, and the highest-priority non-null slot (or // Relinquish_Default) wins. // - // HONEST NOTE, because an earlier version of this comment was wrong and a - // reader would have found out the hard way: for ANALOG/BINARY/MULTI-STATE - // OUTPUT the three calls below are effectively NO-OPS. They reproduce the - // stack's own defaults. Verified in the stack source: + // WORTH KNOWING BEFORE YOU COPY THIS: for ANALOG/BINARY/MULTI-STATE OUTPUT + // the three calls below are effectively NO-OPS. They reproduce the stack's + // own defaults. In the stack source: // - Present_Value on an Analog Output already defaults to required AND // writable (BACnetDBPropertyProfile.cpp: presentValue -> SetProperty( // true, true, Real)), and Priority_Array / Relinquish_Default default to @@ -1046,11 +1043,10 @@ int main(int argc, char** argv) { // enabled before it will treat the object as commandable. Omit these calls on // an Analog Value and it silently is not commandable. // - // Carry the INSTANCE alongside the type: this loop used to hardcode a literal - // 1 while every other line in the file used the named constants. On these - // output types that mismatch is benign (see above) - but it is exactly the - // drift that IS fatal on a Value type, and a reader copying it would inherit - // the bug without the benignity. Say what you mean. + // Carry the INSTANCE alongside the type rather than assuming instance 1. On + // these output types the distinction is benign (see above) - but it is fatal + // on a Value type, where the enable must land on the exact object you mean. + // Say what you mean, so the pattern stays correct when it is copied. struct CommandableObject { uint16_t type; uint32_t instance; }; const CommandableObject outputs[] = { { OBJECT_TYPE_ANALOG_OUTPUT, ANALOG_OUTPUT_INSTANCE }, From 7c1fce95e0b03d49a465321fb045d378602f6822 Mon Sep 17 00:00:00 2001 From: Steven Smethurst Date: Fri, 31 Jul 2026 16:43:40 -0700 Subject: [PATCH 12/15] docs: drop citations into CAS BACnet Stack internals main.cpp cited stack source files by name (BACnetBusinessLogic.cpp, BACnetDBDevice.cpp, BACnetDBPropertyProfile.cpp) and internal symbols (valueShouldBeInitialized, IsPropertyCommandable, IsPropertyEnabled, GetDefaultPropertyValue) as evidence for its claims. Those are ~600 files of someone else's code that a first-time reader cannot usefully open, and citing them invites the reader to go verify rather than to trust and move on. Every claim is kept, stated as observable behaviour of the API instead: 'the stack substitutes a default for these properties', 'the stack treats Present_Value as commandable unconditionally on output types', 'the stack checks whether the property is enabled before reaching the callbacks'. What the reader can act on is unchanged; the archaeology is gone. Comment-only: shows no non-comment line changed. Rebuilt and smoke-tested. Co-Authored-By: Claude Opus 5 --- main.cpp | 52 ++++++++++++++++++++++------------------------------ 1 file changed, 22 insertions(+), 30 deletions(-) diff --git a/main.cpp b/main.cpp index fb8df75..0a732c5 100644 --- a/main.cpp +++ b/main.cpp @@ -228,11 +228,10 @@ static bool ReadPrioritySlot(const Commandable* c, uint32_t propertyIdentifier, // WHAT false ACTUALLY DOES - the most important paragraph in this file, and the // opposite of what most people assume. Returning false does NOT reliably produce // a BACnet error. The stack only errors for the handful of properties it refuses -// to invent (BACnetBusinessLogic.cpp: the valueShouldBeInitialized switch) - -// Present_Value, Number_Of_States, Relinquish_Default, Local_Date, Local_Time, -// and a Network Port's APDU_Length. -// For EVERYTHING ELSE, a false return falls through to GetDefaultPropertyValue() -// (BACnetDBDevice.cpp) and the stack SILENTLY SUBSTITUTES a default: +// to invent: Present_Value, Number_Of_States, Relinquish_Default, Local_Date, +// Local_Time, and a Network Port's APDU_Length. +// For EVERYTHING ELSE, a false return means the stack SILENTLY SUBSTITUTES a +// default: // Object_Name -> the literal string "undefined" // Units -> no-units (95) // otherwise -> a datatype zero-value @@ -353,11 +352,10 @@ bool GetPropertyEnumerated(const uint32_t deviceInstance, const uint16_t objectT } // Units is REQUIRED on an Analog Input AND on an Analog Output. Serve BOTH. // If you only serve the input's, the output does not error - it silently - // reports no-units(95), because Units is not in the stack's - // valueShouldBeInitialized list and so falls through to a substituted default - // (see the note at the top of this section). A setpoint that reads back "no - // units" next to a degC sensor is the kind of thing nobody notices until - // commissioning. + // reports no-units(95), because Units is one of the properties the stack + // substitutes a default for rather than erroring on (see the note at the top + // of this section). A setpoint that reads back "no units" next to a degC + // sensor is the kind of thing nobody notices until commissioning. if (propertyIdentifier == PROPERTY_IDENTIFIER_UNITS && ((objectType == OBJECT_TYPE_ANALOG_INPUT && objectInstance == ANALOG_INPUT_INSTANCE) || (objectType == OBJECT_TYPE_ANALOG_OUTPUT && objectInstance == ANALOG_OUTPUT_INSTANCE))) { @@ -924,9 +922,9 @@ int main(int argc, char** argv) { // Discovery: Who-Is/I-Am (DM-DDB-B) and Who-Has/I-Have (DM-DOB-B). // // These need enabling even though the device already ANSWERS them. The - // stack's service defaults are whoIs + whoHas + readProperty only - // (BACnetDBDevice.cpp) - iAm and iHave are left FALSE. Who-Is is answered and - // the start-up I-Am is sent regardless, because neither is gated on the bit; + // stack's service defaults are whoIs + whoHas + readProperty only - iAm and + // iHave are left FALSE. Who-Is is answered and the start-up I-Am is sent + // regardless, because neither is gated on the bit; // but Protocol_Services_Supported is emitted verbatim from that bitstring, so // without these calls the device DOES I-Am and I-Have while telling every // client it supports neither. The README claims DM-DDB-B and DM-DOB-B; this @@ -998,8 +996,8 @@ int main(int argc, char** argv) { // // The Device's Description is optional too, and it is an easy one to get // wrong: serving it from a Get callback is NOT enough. The stack checks - // IsPropertyEnabled BEFORE it ever reaches the callbacks, and for an optional - // property that check falls back to "is it required?" - which is false. So a + // whether the property is enabled BEFORE it ever reaches the callbacks, and + // for an optional property that check answers "no" unless you enable it. So a // Description branch in the callback without this enable is DEAD CODE, and // the client reads back Error: unknown-property. Note that this fails // invisibly: the callback branch looks correct and simply never runs, so you @@ -1023,25 +1021,19 @@ int main(int argc, char** argv) { // Relinquish_Default) wins. // // WORTH KNOWING BEFORE YOU COPY THIS: for ANALOG/BINARY/MULTI-STATE OUTPUT - // the three calls below are effectively NO-OPS. They reproduce the stack's - // own defaults. In the stack source: - // - Present_Value on an Analog Output already defaults to required AND - // writable (BACnetDBPropertyProfile.cpp: presentValue -> SetProperty( - // true, true, Real)), and Priority_Array / Relinquish_Default default to - // required - so AddObject already enabled all three; and - // - IsPropertyCommandable() (BACnetBusinessLogic.cpp) returns true for - // analogOutput / binaryOutput / multiStateOutput Present_Value - // UNCONDITIONALLY - it consults no enable at all. - // Delete this loop and these objects still accept WriteProperty. Nothing - // here "flips the object into commandable mode"; the stack already did. + // the three calls below are effectively NO-OPS - they re-state defaults the + // stack already applies. On those types Present_Value is required and + // writable, Priority_Array and Relinquish_Default are required, and the stack + // treats Present_Value as commandable unconditionally. Delete this loop and + // these objects still accept WriteProperty. // // So why keep it? Because it states the commandable contract in one visible // place, and because it becomes LOAD-BEARING the moment you copy this pattern // to an optionally-commandable type - Analog Value, Binary Value, Multi-State - // Value. There Priority_Array / Relinquish_Default default to OPTIONAL (not - // enabled), and IsPropertyCommandable() explicitly requires BOTH to be - // enabled before it will treat the object as commandable. Omit these calls on - // an Analog Value and it silently is not commandable. + // Value. There Priority_Array and Relinquish_Default are OPTIONAL, and the + // stack requires BOTH to be enabled before it will treat the object as + // commandable. Omit these calls on an Analog Value and it silently is not + // commandable - it accepts the write and ignores it. // // Carry the INSTANCE alongside the type rather than assuming instance 1. On // these output types the distinction is benign (see above) - but it is fatal From 701310ecf008d637b0ce0af1cb8297ebfac9d012 Mon Sep 17 00:00:00 2001 From: Steven Smethurst Date: Fri, 31 Jul 2026 17:14:13 -0700 Subject: [PATCH 13/15] ci: pin the published build to SOURCE link mode explicitly Release artifacts are built with CAS_BACNET_STACK_LINK=SOURCE, now stated explicitly rather than relying on it being the CMake default - what we publish must not change if that default ever moves. Added a step that reads the value back out of CMakeCache.txt and fails the build if it is not SOURCE. Why SOURCE for a published binary: the artifact is a single self-contained executable. STATIC would need a prebuilt library matched here first, and DLL would require shipping CASBACnetStack_x64_Release.dll alongside and would fail at start-up for anyone who downloaded only the exe. Those modes are for integrators choosing them deliberately in their own build. The cache assertion anchors its grep as '^CAS_BACNET_STACK_LINK:' - without the colon it also matches the CAS_BACNET_STACK_LINK-STRINGS:INTERNAL helper entry, and the comparison silently never matches. Verified against a real CMakeCache.txt both ways before committing. Also: README version banner said common/ v1.5.0 while the code ships v1.5.1 - the same doc/code drift the review panel flagged, reintroduced by my own 1.5.1 bump. Fixed. Submodule -> f9e65559 (licence verbiage + debug-limit comment). Rebuilt and smoke-tested: banner now matches the binary's output. Co-Authored-By: Claude Opus 5 --- .github/workflows/release.yml | 26 ++++++++++++++++++++++++-- README.md | 2 +- submodules/cas-bacnet-stack | 2 +- 3 files changed, 26 insertions(+), 4 deletions(-) diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index ff7663e..82106d3 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -52,8 +52,30 @@ jobs: # default token (which only works if the stack is made accessible). token: ${{ secrets.CAS_STACK_PAT || github.token }} - - name: Configure - run: cmake -B build -S . -DCMAKE_BUILD_TYPE=Release + # Published binaries are built with CAS_BACNET_STACK_LINK=SOURCE - the stack is + # compiled from source straight into the executable. Stated EXPLICITLY rather than + # relying on it being the CMake default, because what we publish must not change if + # that default ever moves. + # + # Why SOURCE for a release: the artifact is a single self-contained executable. STATIC + # would need a prebuilt library built and matched here first, and DLL would require + # shipping CASBACnetStack_x64_Release.dll alongside the exe and would fail at start-up + # for anyone who downloaded only the binary. Those two modes are for integrators + # choosing them deliberately in their own build, not for a downloadable demo. + - name: Configure (SOURCE link mode - self-contained binary) + run: cmake -B build -S . -DCMAKE_BUILD_TYPE=Release -DCAS_BACNET_STACK_LINK=SOURCE + + - name: Confirm the link mode CMake actually used + shell: bash + run: | + # Fail loudly if the cache does not say SOURCE - a published binary that silently + # needs a DLL beside it is the failure we are guarding against. + # Anchor on the colon: without it this also matches the + # CAS_BACNET_STACK_LINK-STRINGS:INTERNAL=SOURCE;STATIC;DLL helper entry and the + # comparison below never matches. + mode=$(grep -E '^CAS_BACNET_STACK_LINK:' build/CMakeCache.txt | cut -d= -f2) + echo "CAS_BACNET_STACK_LINK=$mode" + [ "$mode" = "SOURCE" ] || { echo "FAIL: expected SOURCE, got '$mode'"; exit 1; } - name: Build run: cmake --build build --config Release diff --git a/README.md b/README.md index aba88e1..9e1f648 100644 --- a/README.md +++ b/README.md @@ -18,7 +18,7 @@ second; this is the third and repeats everything it needs. > **Versions:** this document describes **example v1.1.0**, built and verified > against **CAS BACnet Stack 6.x** at **Protocol_Revision 24**, with the -> vendored `common/` helper at **v1.5.0**. Running the example prints all three — +> vendored `common/` helper at **v1.5.1**. Running the example prints all three — > if what it prints disagrees with this line, trust the program and check > `CHANGELOG.md`. > diff --git a/submodules/cas-bacnet-stack b/submodules/cas-bacnet-stack index f30fa46..f9e6555 160000 --- a/submodules/cas-bacnet-stack +++ b/submodules/cas-bacnet-stack @@ -1 +1 @@ -Subproject commit f30fa46da68b7462cc2e55109eb0e8b3186e7728 +Subproject commit f9e65559c18fc7d90b4cc6da7b051def02ca554b From 805e73c4d41810c5957ebb0b45a2d8919d9f2a2e Mon Sep 17 00:00:00 2001 From: Steven Smethurst Date: Fri, 31 Jul 2026 17:19:05 -0700 Subject: [PATCH 14/15] Updated to the latest 6.x-tool branch --- submodules/cas-bacnet-stack | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/submodules/cas-bacnet-stack b/submodules/cas-bacnet-stack index f9e6555..756371c 160000 --- a/submodules/cas-bacnet-stack +++ b/submodules/cas-bacnet-stack @@ -1 +1 @@ -Subproject commit f9e65559c18fc7d90b4cc6da7b051def02ca554b +Subproject commit 756371c1de656c30c85c6eeb875cdd49c93481ca From 0f945a3d425a5367455baebd9c38f7be27b80980 Mon Sep 17 00:00:00 2001 From: Steven Smethurst Date: Fri, 31 Jul 2026 17:21:16 -0700 Subject: [PATCH 15/15] build: re-pin the stack to merged 6.x-TestTool (756371c1) PRs #267 and #268 are merged, so the pin moves off the adapter-cpp-package branch tip and onto 6.x-TestTool, retiring the TEMPORARY note in the CHANGELOG. Verified the adapter content is byte-identical to the branch-tip pin it replaces (diff over adapters/cpp + CASBACnetStackDLL.{h,cpp} is empty), so this is a provenance change, not a code change. Also corrects the common/ version reference in that entry to 1.5.1. Rebuilt and smoke-tested on the merged pin. Co-Authored-By: Claude Opus 5 --- CHANGELOG.md | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 0c7ece5..6fc762a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -46,10 +46,9 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 exports, passes the version handshake and runs — plus both of its failure paths (library absent; library present but missing an export) report a readable error and exit cleanly rather than crashing. - **TEMPORARY:** the stack submodule pin currently points at the - `adapter-cpp-package` branch tip (stacked on `adapter-cpp-generate`), not - `6.x-TestTool` — see cas-bacnet-stack PRs #267 and #268; re-pin once both merge. - common/ bumped to v1.5.0 (see `common/CHANGELOG.md`) — this is a contract + The stack submodule is pinned to `6.x-TestTool` @ `756371c1`, which carries the + adapter work merged as cas-bacnet-stack PRs #267 and #268. + common/ bumped to v1.5.1 (see `common/CHANGELOG.md`) — this is a contract change every example in the series needs when it re-syncs. - **Documentation corrections from a five-persona review** (lead developer, educator, junior developer, BACnet newcomer, staff architect): the version