README.md says what this example is. This document is the how: how to extend it into your own router, what each object type needs the application to serve, how the two Network Ports and the router configuration fit together, how to review the result for conformance, and what goes wrong when you get it subtly right.
Read this once before you start changing main.cpp. The most expensive
mistake in this example is silent, and the section it lives in is
Add a second analog input.
- Extending the example
- F-MULTIPORT: two Network Ports, two UDP sockets
- F-ROUTER: router configuration
- What each object type needs you to serve
- Who serves what: the application or the stack?
- Reviewing your device
- Troubleshooting
The example is intentionally small so it's easy to change.
Change an object's value or name - edit the constants / callbacks in
main.cpp (e.g. the initial value of g_analogInput1Value, or the
"Bronze" string in GetPropertyCharString).
Change the device identity before you ship - vendor ID, vendor name,
model name, description, firmware revision, device name and the two network
numbers are all in the CHANGE ALL OF THIS BEFORE YOU SHIP block at the top
of main.cpp, with a per-field comment on each saying what to change it to.
That block is the authoritative checklist; it is in the source rather than
here so it cannot be skipped by someone who only reads the code.
Read this whole recipe before starting — the last step is the one that is easy to miss and the one BTL will fail you for.
Why there are four edits, not three — and why skipping one is SILENT. Most of the
GetProperty*callbacks match on both object type and instance (objectInstance == ANALOG_INPUT_INSTANCE), so a new instance falls through every one of them.GetPropertyBoolis the exception forOut_Of_Service: it matches on type only, so it works for a new instance for free.Here is the part that matters, and it is the opposite of what most people assume: falling through a callback does not reliably produce an error. The stack errors only for the few properties it refuses to invent -
Present_Value,Number_Of_States,Relinquish_Default, and a Network Port'sAPDU_Length. For everything else it silently substitutes a default:
Property If you forget to serve it Loud? Present_ValueError ( read-access-denied)yes Object_Namereads back as the string "undefined"no Unitsreads back as no-units(95)no Out_Of_Serviceserved on type alone — works by accident n/a Doesn't the
errorCodeout-parameter fix this? Only if you use it, and only where it is right to. EachGetProperty*callback ends with auint32_t* errorCodethat the stack presets tosuccessand reads only when you returnfalse, so you can turn any decline into a chosen BACnet error. But ending every callback with*errorCode = unknown-propertybreaks the device: the stack's decline-and-fabricate path is what answers required properties an application is not expected to serve — the Device'sMax_APDU_Length_Accepted,APDU_TimeoutandNumber_Of_APDU_Retriesamong them. Name an error on the catch-all and those start failing instead of answering. SeterrorCodeonly where this device knows the read is wrong;main.cppdoes it in exactly one place,State_Textwith an out-of-range array index.It is worse than "wrong value": the object's
Property_Liststill advertisesUnits(117). So the object actively claims to have the property, and then answers with a default. Nothing on the wire says you forgot anything.So a half-added object does not look broken; it looks healthy. Add two of them and both report
Object_Name "undefined"— duplicate object names inside one device, which is a spec violation and a hard BTL failure that every scan tool will render as a perfectly good object. "It scanned OK" is exactly the failure mode, not evidence against it.
// 1) a new instance number (in section 1).
// Naming: a second object of a type is "<Colour> 2" - so Analog Input 2 is
// "Bronze 2", NOT a new colour. Each object TYPE owns one colour series-wide.
static const uint32_t ANALOG_INPUT_2_INSTANCE = 2; // "Bronze 2"
static float g_analogInput2Value = 23.1f; // its live value
// 2) add the object (in main, next to the other BACnetStack_AddObject calls).
// Check the return, like every other stack call in this file.
if (!BACnetStack_AddObject(g_deviceInstance, OBJECT_TYPE_ANALOG_INPUT, ANALOG_INPUT_2_INSTANCE)) {
printf("Error: Failed to add Analog Input 2 (Bronze 2).\n");
return 1;
}
// 3) serve its Present_Value + Object_Name:
// GetPropertyReal: AI/2 + Present_Value -> *value = g_analogInput2Value;
// GetPropertyCharString: AI/2 + Object_Name -> "Bronze 2"
// 4) DO NOT SKIP: serve its Units, in GetPropertyEnumerated.
// Units is a REQUIRED property of an Analog Input. The existing check reads
// `objectInstance == ANALOG_INPUT_INSTANCE`, which is instance 1 - so without
// this, reading Analog Input 2's Units returns an ERROR and the object is
// NON-CONFORMANT. It will still appear in the Object_List and its
// Present_Value will read back perfectly, so the device looks healthy right
// up until BTL certification.
// GetPropertyEnumerated: AI/2 + Units -> *value = ENGINEERING_UNITS_DEGREES_CELSIUS;Then re-run the README's Verify steps against Analog Input 2, not just
Analog Input 1 — read every required property, on both networks, and diff
it against Analog Input 1. Any property that comes back "undefined",
no-units, or 0 where object 1 returns something real is a step you
missed. Because the failure is silent (see the table above), this diff is
the only thing that catches it.
Most examples in this series own exactly one Network Port and one UDP socket.
This example is the series' canonical example of owning two:
CASExampleHelper::SetupUDP(port, networkPortInstance) binds an additional
socket keyed to a specific Network Port instance, and the shared
receive/send callbacks (common/CASExampleHelper.cpp) dispatch on that
instance internally - main.cpp just calls SetupUDP twice and
SendIAm(deviceInstance, networkPortInstance) once per port. See
common/CHANGELOG.md's 2.3.0 entry and the "WHY THIS IS SAFE FOR
SINGLE-PORT EXAMPLES" comment in CASExampleHelper.cpp for why this did not
change any single-port example's behaviour.
Both ports run on one host and are distinguished purely by UDP port
number (--port / --port2, default --port + 1) - they report the same
IP_Address/IP_Subnet_Mask and different BACnet_IP_UDP_Port /
Network_Number.
Adding a third port to a device you build from this example follows the same
pattern: a third NETWORK_PORT_x_INSTANCE, a third SetupUDP(port, instance) call, a third SendIAm(deviceInstance, instance) call, and (if it
should also route) a third BACnetStack_AddRouterPort.
The router forwards between its two BACnet/IP networks because each Network
Port object carries its own Network_Number (1 on Vermilion, 2 on Vermilion
2, both configured, passed to BACnetStack_AddNetworkPortObject). The stack
gives each BACnet/IP Network Port object its own datalink instance and binds a
router port to the instance whose Network Port has that port's network
number - so a frame arriving on Vermilion 2's socket is attributed to router
port 2, and a frame leaving through router port 2 goes out of Vermilion 2's
socket. Give the two ports the same number and nothing is forwarded.
At start-up, main.cpp:
BACnetStack_AddRouterPortonce per Network Port, registering the network it directly connects (network 1 on Vermilion, network 2 on Vermilion 2).BACnetStack_AddRouterRoutefor one DEMONSTRATION-ONLY network (3), one hop beyond port 2, with no next-hop MAC configured - this exercises the API; no device in this example series actually sits on network 3 (seemain.cpp'sDEMO_REMOTE_NETWORKcomment).BACnetStack_SetRouterEnabled(deviceInstance, true)- routing is opt-in even with ports configured.- Broadcasts I-Am-Router-To-Network on both ports when the
rkey is pressed. (At start-up the stack sends this announcement itself, on the firstBACnetStack_Tick(), with the same per-port lists - somain.cppdoes not. It reaches the wire becausecommon/(3.2.0 and later) sends a frame the stack hands it with no connection string to the port's local broadcast address.) Each port gets its own list - "each accessible network except the networks reachable via the network on which the broadcast is being made" (cl. 6.6.2): networks 2 and 3 on Vermilion, network 1 on Vermilion 2. PassingnetworkNumbers = NULLinstead would announce every port's own network on every port, telling network 1 that network 1 is reachable through this router. - Broadcasts Network-Number-Is on both ports, announcing each network's own (configured) number.
- Broadcasts Who-Is-Router-To-Network (unrestricted) on both ports, the polite router start-up probe for any other router already present (none is expected to answer in this example).
BACnetStack_AddRouterPort's networkType parameter is the stack's own
internal datalink enum (BACnetPacket::NetworkType_IP = 0), which is a
different enumeration from the Network Port object's Network_Type
property (NETWORK_PORT_NETWORK_TYPE_IPV4 = 5, used with
AddNetworkPortObject) - passing the wrong one fails with "unknown network
type"; see the ROUTER_NETWORK_TYPE_IP comment in main.cpp.
What the router then does on its own (the stack, not main.cpp), all checked
on the wire by tests/:
- Forwards a message whose DNET is the other network: a ReadProperty from network 1 for a device on network 2 reaches it, and the answer comes back with SNET = 2 / SADR = that device (cl. 6.5.4).
- Rejects a message for a network it cannot reach with Reject-Message-To-Network, reason 1, after searching for a router to it with a Who-Is-Router-To-Network broadcast on its other port (cl. 6.6.3.1).
- Re-broadcasts a remote broadcast (DNET = 2, DLEN = 0) on network 2 and a global broadcast (DNET = 0xFFFF) on every port but the one it came in on (cl. 6.3.2, 6.5.4), adding SNET / SADR - so a Who-Is from network 1 finds a device on network 2, and its I-Am comes back to network 1 with SNET = 2.
- Answers Who-Is-Router-To-Network with the networks reachable through it except those behind the port the query came in on (cl. 6.6.3.2).
Every broadcast in that list - the start-up announcement, the search, the
re-broadcast Who-Is - is a frame the stack originates with no destination
address. It hands it to the send callback with a NULL / length-0 connection
string, which BACnetStack_RegisterCallbackSendMessageForPort documents as
"broadcast on this data link"; common/'s HelperSendMessage sends it to the
local subnet broadcast on that Network Port's UDP port. A transport callback of
your own has to do the same, or none of them reaches the wire.
- Keeps each Network Port's
Routing_Table(cl. 12.56.62: "the table of first hop routers to remote networks reachable through this port"). The stack enables the property on every Network Port while routing is enabled and builds each port's table from the routes configured above, somain.cppdoes nothing for it. Network Port 1 reads an empty list - no router lies beyond it. Network Port 2 reads one entry: network 3, MAC address empty (the demonstration route names no next-hop router - giveAddRouterRoutethe next router's address and it appears here), status available. Directly connected networks 1 and 2 are never listed. (tests/routing_table_test.py) - Attributes Network-Number-Is to the port it arrived on (cl. 6.4.20), so a
port whose number is learned learns its own network's number.
(
tests/routing_table_test.py)
What it does not do yet - a broadcast answer to Who-Is-Router-To-Network
(stack #3931) - is in
TODO.md. It is not in main.cpp.
AddListElement and RemoveListElement (cl. 15.1 / 15.2) edit one element of a
BACnetLIST property. This example gives them a list to edit: Group 1
"Olive", whose List_Of_Group_Members the stack holds. Four calls in
main.cpp:
BACnetStack_AddObject(device, OBJECT_TYPE_GROUP, 1)thenBACnetStack_AddGroupObject(device, 1)- the second hands the list to the stack, which stores it and builds the Group'sPresent_Valuefrom it (one ReadAccessResult per member).BACnetStack_AddGroupMember(...)- one starting member, Analog Input 1'sPresent_Value, so a client sees a non-empty list.BACnetStack_SetPropertyWritable(..., List_Of_Group_Members, true)- without this every AddListElement/RemoveListElement is refused with PROPERTY / WRITE_ACCESS_DENIED: a stack-held list is read-only to clients until you make it writable.BACnetStack_SetServiceEnabledfor services 8 and 9 - without it the requests are Rejected as an unrecognized service.
The application serves only the Group's Object_Name. A client's
AddListElement of a ReadAccessSpecification adds a member; RemoveListElement
of the same element removes it; removing one that is not there answers
SERVICES / LIST_ELEMENT_NOT_FOUND (tests/list_element_test.py).
The application must serve every REQUIRED property the stack does not generate. It differs per type — this is the checklist, so you do not have to infer it:
| Object type | You must serve | Plus |
|---|---|---|
| Analog Input | Present_Value (Real), Object_Name, Units |
— |
| Binary Input | Present_Value (Enumerated), Object_Name |
Polarity |
| Multi-State Input | Present_Value (Unsigned), Object_Name |
Number_Of_States |
| Analog Output (commandable) | Object_Name, Units, Relinquish_Default |
16-slot Priority_Array via GetPropertyReal/GetPropertyBool; Present_Value resolved by the stack |
| Binary Output (commandable) | Object_Name, Polarity, Relinquish_Default |
16-slot Priority_Array via GetPropertyEnumerated/GetPropertyBool; Present_Value resolved by the stack |
| Multi-State Output (commandable) | Object_Name, Number_Of_States, Relinquish_Default |
16-slot Priority_Array via GetPropertyUnsignedInteger/GetPropertyBool; Present_Value resolved by the stack |
Group (stack-held, BACnetStack_AddGroupObject) |
Object_Name |
List_Of_Group_Members and Present_Value are the stack's |
| Network Port | Object_Name, Network_Type, Protocol_Level, Changes_Pending, IP_Address/IP_Subnet_Mask/IP_Default_Gateway, BACnet_IP_UDP_Port |
one instance per network the device joins |
The single most common question when reading this file is "who answers this property?" For Analog Output 1 (the representative commandable object), the whole picture:
| Property | Served by | How |
|---|---|---|
Object_Identifier |
stack | generated from the object you added |
Object_Type |
stack | generated |
Object_List |
stack | generated (Device object) |
Property_List |
stack | generated |
Status_Flags |
stack | generated |
Event_State |
stack, sort of | no intrinsic alarming here, so nothing serves it — it reads normal only because normal is the enumeration's zero value and the stack substitutes a datatype default. Correct by coincidence, not design. |
Out_Of_Service |
you | GetPropertyBool — matched on object type only |
Present_Value |
stack | resolved from the Priority_Array slots you serve; writable — SetPropertyReal stores the slot |
Priority_Array |
stack, backed by you | GetPropertyBool returns whether each slot is set; SetPropertyReal/SetPropertyNull write/relinquish a slot |
Current_Command_Priority |
stack | computed from the Priority_Array slots |
Relinquish_Default |
you | GetPropertyReal |
Object_Name |
you | GetPropertyCharString |
Units |
you | GetPropertyEnumerated |
Every object, not just this one, is in docs/PICS.md.
Going beyond this (alarming/events, COV, scheduling, trending) means implementing a richer profile — see the series table in README.md.
After you have changed anything, review it against the conformance statement rather than against "it looked fine in the explorer":
- Regenerate docs/PICS.md after editing
docs/objects.json(see Keeping the PICS honest below). A ⚠ row is a required property nothing serves. - Read every property listed for every object with a BACnet client,
on both ports independently, and compare the value against the PICS.
"undefined",no-unitsand0are the three shapes a missed callback takes. - Diff a new object of a type against the existing one of that type. Anything that differs and shouldn't is a callback that matched on instance.
- WriteProperty each commandable output at a priority, re-read it, then
write NULL to relinquish and confirm it falls back to
Relinquish_Default. - Run the wire-level tests in
tests/: forwarding across the router, the reject for an unreachable network (and the search before it), Who-Is discovery across the router, Who-Is-Router-To-Network on both ports, the start-up announcements, and AddListElement/RemoveListElement on the Group. A new check you add there must fail with the feature removed before you trust it. - Confirm services this device does not implement are still rejected - ReadPropertyMultiple, DeviceCommunicationControl, and any alarm/event, COV, or scheduling service.
docs/PICS.md is partly generated. docs/objects.json describes each
object and who serves which property; the series tool regenerates the
object tables from it plus the stack's own
docs/property-profile-reference.md at the pinned commit:
python tools/gen-objects-properties.py BACnetProfileExample-B-RTR-CPP # rewrite
python tools/gen-objects-properties.py BACnetProfileExample-B-RTR-CPP --check # fail if stale(That tool lives in the example-series repository, not in this one. If you
only have this repository, edit the generated block by hand and keep it
matching the callbacks in main.cpp.)
When you add an object or a property to main.cpp, update
docs/objects.json in the same change and regenerate. The app list is
what the callbacks serve; accepted is for a required property you
deliberately leave to the stack's default, and each one needs a
justification. Anything required, not in app and not in accepted, comes
out as a ⚠ row - that is a defect, not a feature.
| Symptom | Cause / fix |
|---|---|
Start-up prints Failed to send the start-up IAmRouterToNetwork out portId=[1] (and [2]), with The datalink refused a routed packet above it |
Your common/ is older than 3.2.0, or your own send callback returns 0 for a NULL / length-0 connection string. That is the stack asking for a broadcast on that port ("broadcast on this data link"); send it to the port's local broadcast address. Until you do, the router also drops every Who-Is it should re-broadcast and the search before a Reject-Message-To-Network. |
| Nothing on network 2 answers a Who-Is sent from network 1 | The device on network 2 must hear network 2's broadcasts: on its own host, on Network Port 2's UDP port (47809 by default) and the same subnet. If it does and still nothing comes back, check the row above. A ReadProperty addressed to the device (DNET = 2, DADR = its address) crosses the router without any broadcast. |
| Two ports and routing enabled, but nothing is forwarded | The two Network Port objects have the same Network_Number. Each port needs its own (see F-ROUTER). |
ReadProperty of Routing_Table fails with unknown-property |
Routing is not enabled (BACnetStack_SetRouterEnabled), or your stack is older than 6.x @ 5472c6e1 (stack #2511) - the stack enables the property only while the router is on. |
On start-up the app prints a wall of red Error: lines but the device works |
Expected — this is not your bug. Several benign sources, all from the stack's own debug logging: (1) each port receives its own broadcast I-Am and logs a decode cascade — 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 this IP-only example never configures. |
| CMake error: "CAS BACnet Stack adapter not found under: ..." | 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. |
| First build seems stuck for minutes | Normal - it's compiling ~600 stack files. Only the first build is slow. |
Failed to bind UDP port ... |
Another program is using that port. Stop it, or pass a different --port/--port2. |
--port2 equals --port |
Rejected on purpose - they must be two different UDP ports (two different simulated networks). |
| Client sends Who-Is but sees no I-Am | Firewall is blocking the UDP port, or the client and device are on different subnets (Who-Is is a broadcast). Allow both ports; test on the same subnet first. |
| Replies show an unexpected device instance or vendor | Another BACnet device is already answering on this host/port. Stop the other device, or use --port/--port2. |