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/.gitignore b/.gitignore index 68d6cf9..8723bc1 100644 --- a/.gitignore +++ b/.gitignore @@ -1,2 +1,4 @@ # CMake build output build/ + +build-static/ diff --git a/CHANGELOG.md b/CHANGELOG.md index c5d3077..6fc762a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -35,6 +35,41 @@ 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. **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. + 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 + 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` → + `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/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/README.md b/README.md index 0fa83e8..9e1f648 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.1**. 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. @@ -283,10 +316,78 @@ 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`. +### 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 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 `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 +# 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** 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 +> 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 ```bash @@ -302,13 +403,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.3.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 @@ -348,8 +454,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. @@ -373,8 +488,10 @@ 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. | -| CMake error: *"CAS BACnet Stack source not found"* | Submodules not initialized. Run `git submodule update --init --recursive` (or pass `-D CAS_STACK_DIR=...`). | +| 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 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. | @@ -383,7 +500,7 @@ Use a BACnet client such as the | 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 @@ -514,4 +631,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/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/common/CASExampleHelper.cpp b/common/CASExampleHelper.cpp index 2278f71..dd9f127 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 @@ -237,10 +238,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", @@ -251,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"); @@ -260,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 || @@ -278,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 1f1b928..40efc75 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.3.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. @@ -91,6 +93,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..c9d9310 100644 --- a/common/CHANGELOG.md +++ b/common/CHANGELOG.md @@ -12,6 +12,80 @@ 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 + +- **`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 + +- **`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 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/main.cpp b/main.cpp index 4c64901..0a732c5 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 @@ -223,14 +225,13 @@ 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. -// For EVERYTHING ELSE, a false return falls through to GetDefaultPropertyValue() -// (BACnetDBDevice.cpp) and the stack SILENTLY SUBSTITUTES a default: +// 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: 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 @@ -253,7 +254,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. @@ -350,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))) { @@ -829,9 +830,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; } @@ -842,9 +840,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; } @@ -913,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 @@ -962,10 +971,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( + // 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, 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; @@ -982,12 +996,12 @@ 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. (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)) { @@ -1006,33 +1020,25 @@ 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: - // - 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. + // WORTH KNOWING BEFORE YOU COPY THIS: for ANALOG/BINARY/MULTI-STATE OUTPUT + // 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: 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 }, diff --git a/submodules/cas-bacnet-stack b/submodules/cas-bacnet-stack index 863a090..756371c 160000 --- a/submodules/cas-bacnet-stack +++ b/submodules/cas-bacnet-stack @@ -1 +1 @@ -Subproject commit 863a090e0f6604816016af9a53a4aa477cff4c77 +Subproject commit 756371c1de656c30c85c6eeb875cdd49c93481ca