Repository navigation
Expand file tree
/
Copy pathmain.cpp
More file actions
1065 lines (994 loc) · 52.2 KB
/
Copy pathmain.cpp
File metadata and controls
1065 lines (994 loc) · 52.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// SPDX-License-Identifier: CC0-1.0
// Public-domain example code (CC0) - see LICENSE. The CAS BACnet Stack itself is
// a separate, commercially licensed product and is not covered by CC0.
// =============================================================================
// BACnet Profile Example - B-RTR (BACnet Router) - C++
//
// This example implements the BACnet "B-RTR" (Router) device profile with the
// CAS BACnet Stack. It is the B-ASC (Application Specific Controller) example
// minus DeviceCommunicationControl, plus TWO Network Port objects and physical
// inter-datalink routing between them (ANSI/ASHRAE 135 cl. 6.6, Annex L NM-RC-B).
//
// A B-RTR is a stand-alone BACnet router: a device that forwards NPDUs between
// two (or more) directly-connected BACnet networks and answers the network-layer
// messages that let other devices discover and use it as a router:
//
// DS-RP-B - respond to ReadProperty requests,
// DS-WP-B - allow other devices to WriteProperty its objects,
// DM-DDB-A - INITIATE Who-Is (SendWhoIs) as well as answer it - a router is
// expected to actively discover devices on the networks it joins,
// not just wait to be asked,
// DM-DOB-B - answer Who-Has,
// NM-RC-B - Network Management - Router Configuration: configure router
// ports/routes, answer Who-Is-Router-To-Network with
// I-Am-Router-To-Network, and announce Network-Number-Is.
//
// plus discovery (Who-Is/I-Am, Who-Has/I-Have). This example does NOT implement
// DM-LM-B (AddListElement/RemoveListElement, services 8/9): see TODO.md - the
// customer-facing STATIC build of the pinned stack does not compile that support
// in, so it is a documented gap rather than a faked claim.
//
// The device keeps the same base objects as B-ASC/B-SA - three read-only sensor
// inputs and three commandable outputs a client drives with WriteProperty - PLUS
// a SECOND Network Port object, one per side of the router:
//
// Device 389018 "Chipkin Example B-RTR" (instance configurable with --deviceID)
// Analog Input 1 "Bronze" (REAL, degrees Celsius; read-only)
// Binary Input 1 "Emerald" (active / inactive; read-only)
// Multi-State Input 1 "Hot Pink" (state 1..3; read-only)
// Analog Output 1 "Chartreuse" (REAL setpoint; WRITABLE, commandable)
// Binary Output 1 "Fuchsia" (active / inactive; WRITABLE, commandable)
// Multi-State Output 1 "Indigo" (state 1..3; WRITABLE, commandable)
// Network Port 1 "Vermilion" (BACnet/IP port A - network 1)
// Network Port 2 "Vermilion 2" (BACnet/IP port B - network 2)
//
// F-MULTIPORT: the two Network Ports each own their own UDP socket, via the
// common/ 2.3.0+ multi-port SetupUDP(port, networkPortInstance) /
// SendIAm(deviceInstance, networkPortInstance) overloads - see
// common/CASExampleHelper.h/.cpp for how the shared transport callbacks
// dispatch on networkPortInstance. This is the FIRST example in the series to
// use more than one Network Port; everything below is written to be a clear
// pattern for a later multi-port example (e.g. B-GW) to copy.
//
// F-ROUTER: BACnetStack_AddRouterPort registers each Network Port's directly
// connected network with the stack's router logic; BACnetStack_SetRouterEnabled
// turns forwarding on. A third, ONE-HOP-AWAY network is configured with
// BACnetStack_AddRouterRoute purely to demonstrate that API - see the
// DEMO_REMOTE_NETWORK comment below for what is and is not verified about it.
//
// Output objects are COMMANDABLE: their Present_Value is driven by a 16-slot
// BACnet Priority_Array, exactly as in B-SA/B-ASC. See GetCommandable() etc.
// below - this part is unchanged from B-ASC.
//
// To be a conformant BACnet device (Protocol_Revision 24) each object must
// expose its full set of REQUIRED properties. Most are generated by the stack
// (Object_Identifier, Object_Type, Status_Flags, Object_List, Protocol_*). A
// Network Port additionally gets Network_Number, Network_Number_Quality,
// BACnet_IP_Mode and MAC_Address from the stack once AddNetworkPortObject is
// called with the right arguments - see the callbacks below for the handful
// this application still has to supply (IP_Address, IP_Subnet_Mask, ...).
//
// Interactive keys (handled by the shared helper): h = help, q = quit,
// up/down = nudge Analog Input 1 by +/-1.1, r = re-send I-Am-Router-To-Network
// on both ports now (common/ 2.4.0+). Command line: --port <n> (Network Port 1 /
// Vermilion), --port2 <n> (Network Port 2 / Vermilion 2, default --port + 1),
// --deviceID <n>.
//
// All the UDP/stack plumbing lives in common/CASExampleHelper so this file can
// stay focused on the BACnet logic.
// =============================================================================
#include "CASExampleHelper.h"
#include "CASBACnetStackExampleConstants.h"
#include "CASBACnetStackAdapter.h" // the CAS BACnet Stack C API (BACnetStack_*); call
// LoadBACnetFunctions() before any BACnetStack_* call -
// see the top of main() below.
#include <stdio.h>
#include <string.h>
#include <string>
#include <errno.h>
#include <stdlib.h>
#if defined(_WIN32)
#include <windows.h> // Sleep()
#else
#include <unistd.h> // usleep()
#endif
using namespace CASBACnetStackExampleConstants;
// -----------------------------------------------------------------------------
// 1. Example + device configuration
// -----------------------------------------------------------------------------
static const char* APP_NAME = "BACnet B-RTR (Router) Example - C++";
static const char* APP_VERSION = "1.0.2";
// The device instance. BACnet requires this to be configurable, so it defaults
// to 389018 (docs/colour-table.md) and can be overridden with --deviceID.
// CHANGE ALL OF THIS BEFORE YOU SHIP: like DEVICE_NAME above, this instance
// number MUST BE UNIQUE ACROSS THE WHOLE BACNET INTERNETWORK. --deviceID
// already makes it runtime-configurable; a real product still needs a process
// (serial number, commissioning step, ...) for assigning a non-colliding value
// per unit, since the default here is only a placeholder for this example.
static uint32_t g_deviceInstance = 389018;
// ---- Device identity: CHANGE ALL OF THIS BEFORE YOU SHIP --------------------
// Every constant in this block is read by clients and shown to the operator in
// EVERY discovery tool on the network. Left as-is, your product appears on a
// real site announcing itself as a Chipkin demo. None of it is cosmetic.
// Change to YOUR company's vendor ID, assigned free by ASHRAE:
// https://bacnet.org/assigned-vendor-ids/ . Must match VENDOR_NAME below.
static const uint32_t VENDOR_IDENTIFIER = 389;
// This is the device's Object_Name. It MUST BE UNIQUE ACROSS THE WHOLE BACNET
// INTERNETWORK - two devices with the same Object_Name is a spec violation
// that every scan tool renders as two perfectly good objects (see TUTORIAL.md's
// "silent failure" warning for the same failure shape on a per-object level).
// Here it is a COMPILE-TIME CONSTANT, which is fine for a tutorial but not for
// a real product: a real device needs a name that is unique PER UNIT, not per
// firmware build - derive it from a serial number, DIP switches, a config
// file, or a --deviceName command-line argument, not a hardcoded string.
static const char* DEVICE_NAME = "Chipkin Example B-RTR";
// Change to a description of what YOUR device actually is.
static const char* DEVICE_DESCRIPTION =
"Chipkin CAS BACnet Stack example - B-RTR (Router) profile. Demonstrates "
"DS-RP-B + DS-WP-B + DM-DDB-A + DM-DOB-B + NM-RC-B: a stand-alone BACnet "
"router forwarding between two BACnet/IP networks, each with its own "
"Network Port object.";
// Change to YOUR company name - must match VENDOR_IDENTIFIER above.
static const char* VENDOR_NAME = "Chipkin Automation Systems";
// Change to your product's own model designation.
static const char* MODEL_NAME = "CAS BACnet Stack Example - B-RTR";
// Firmware_Revision reflects the underlying CAS BACnet Stack's REAL version,
// built at runtime (once LoadBACnetFunctions() has loaded the stack DLL) from
// BACnetStack_GetAPI{Major,Minor,Patch,Build}Version() - see main() below.
// Application_Software_Version is this example's own version: APP_VERSION above.
static std::string g_firmwareRevision;
// The sensor objects (all instance 1) and their colour names - unchanged from
// B-SA/B-ASC.
static const uint32_t ANALOG_INPUT_INSTANCE = 1; // "Bronze"
static const uint32_t BINARY_INPUT_INSTANCE = 1; // "Emerald"
static const uint32_t MULTI_STATE_INPUT_INSTANCE = 1; // "Hot Pink"
static const uint32_t MULTI_STATE_INPUT_NUMBER_OF_STATES = 3;
// -----------------------------------------------------------------------------
// F-MULTIPORT: TWO Network Port objects, one per routed network.
//
// Both ports share the SAME host network interface (this is one process on one
// box); they are distinguished by UDP PORT NUMBER, not IP address - exactly
// like running two independent BACnet/IP devices on one machine, except the
// stack now treats them as two sides of one router instead of two devices.
// common/CASExampleHelper's SendIAm(deviceInstance, networkPortInstance)
// documents this same assumption (see its "NOTE for multi-port examples").
// -----------------------------------------------------------------------------
static const uint32_t NETWORK_PORT_1_INSTANCE = 1; // "Vermilion" - network A
static const uint32_t NETWORK_PORT_2_INSTANCE = 2; // "Vermilion 2" - network B
static const uint32_t MAX_APDU_LENGTH = 1476; // BACnet/IP APDU length
// The BACnet network NUMBERS the two ports directly connect (ASHRAE 135 cl.
// 6.2.2 numbers a network, distinct from the Network Port OBJECT instance).
// Configured (not learned), so Network_Number_Quality reports CONFIGURED.
// CHANGE ALL OF THIS BEFORE YOU SHIP: these two placeholder numbers (1, 2)
// must become YOUR site's actual network numbers - they must be unique across
// the whole BACnet internetwork, exactly like the device instance above. A
// wrong or colliding network number breaks routing for every device on it,
// not just this one.
static const uint16_t NETWORK_NUMBER_PORT_1 = 1;
static const uint16_t NETWORK_NUMBER_PORT_2 = 2;
// F-ROUTER: the router-layer "port identifier" BACnetStack_AddRouterPort and
// BACnetStack_AddRouterRoute use, as reported in the Network Port's
// Routing_Table property. This is a DELIBERATELY SEPARATE id space from the
// Network Port OBJECT instance above (see AddRouterPort's own doc comment in
// CASBACnetStackDLL.h) - they happen to share the same small integers here
// (1 <-> Network Port 1, 2 <-> Network Port 2) purely for readability; do not
// assume the stack ties them together.
static const uint8_t ROUTER_PORT_ID_1 = 1;
static const uint8_t ROUTER_PORT_ID_2 = 2;
// BACnetStack_AddRouterPort's networkType is the STACK'S OWN internal
// datalink enum (source/BACnetPacket.h, BACnetPacket::NetworkType: IP=0,
// MSTP=1, SC=2) - NOT the Network Port object's Network_Type property
// (NETWORK_PORT_NETWORK_TYPE_IPV4 = 5, ASHRAE 135's BACnetNetworkType, used
// above with AddNetworkPortObject). Passing the object-level value here fails
// with "unknown network type" - confirmed against the pinned stack while
// building this example. Not (yet) mirrored in
// common/CASBACnetStackExampleConstants.h because it is stack-internal rather
// than a 135 standard enumeration; a later routing example (e.g. B-GW) that
// also needs it should consider promoting it there.
static const uint8_t ROUTER_NETWORK_TYPE_IP = 0;
// DEMONSTRATION ONLY: a network reachable one hop beyond port 2, configured
// with BACnetStack_AddRouterRoute (as opposed to BACnetStack_AddRouterPort,
// which is for a DIRECTLY connected network). Nothing in this example series
// actually sits on network 3 - no device answers there - so this entry exists
// to exercise the AddRouterRoute API, NOT to be a wire-verified route. See
// README "Verification" and TODO.md for exactly what IS and is not confirmed
// on the wire (including why Routing_Table itself cannot be read back - a
// separate stack gap, not specific to this demo entry).
static const uint16_t DEMO_REMOTE_NETWORK = 3;
// BACnet/IP addressing the Network Port reports. Both ports report the SAME
// host IP/subnet (see the comment above NETWORK_PORT_1_INSTANCE) - only the
// UDP port differs, captured per-port below.
static uint8_t g_ipAddress[4] = { 0, 0, 0, 0 };
static uint8_t g_ipSubnetMask[4] = { 0, 0, 0, 0 };
static uint8_t g_ipDefaultGateway[4] = { 0, 0, 0, 0 };
static uint16_t g_bacnetIpUdpPort1 = 47808; // Network Port 1 / Vermilion
static uint16_t g_bacnetIpUdpPort2 = 47809; // Network Port 2 / Vermilion 2 (default +1)
// Analog Input 1's live present value (degrees Celsius). Starts at 21.5 and is
// nudged by the up/down arrow keys.
static float g_analogInput1Value = 21.5f;
// The commandable OUTPUT objects (all instance 1) and their colour names -
// unchanged from B-SA/B-ASC.
static const uint32_t ANALOG_OUTPUT_INSTANCE = 1; // "Chartreuse"
static const uint32_t BINARY_OUTPUT_INSTANCE = 1; // "Fuchsia"
static const uint32_t MULTI_STATE_OUTPUT_INSTANCE = 1; // "Indigo"
static const uint32_t MULTI_STATE_OUTPUT_NUMBER_OF_STATES = 3;
static const uint32_t BACNET_PRIORITY_ARRAY_SIZE = 16;
struct Commandable {
bool isSet[16];
double value[16];
double relinquishDefault;
};
static Commandable g_analogOutput = { { false }, { 0 }, 20.0 };
static Commandable g_binaryOutput = { { false }, { 0 }, 0.0 };
static Commandable g_multiStateOutput = { { false }, { 0 }, 1.0 };
static uint8_t EffectivePriority(uint8_t priority) {
return (priority >= 1 && priority <= BACNET_PRIORITY_ARRAY_SIZE) ? priority : 16;
}
static void CommandWrite(Commandable* c, uint8_t priority, double value) {
const uint8_t p = EffectivePriority(priority);
c->isSet[p - 1] = true;
c->value[p - 1] = value;
}
static void CommandRelinquish(Commandable* c, uint8_t priority) {
const uint8_t p = EffectivePriority(priority);
c->isSet[p - 1] = false;
}
static Commandable* GetCommandable(uint16_t objectType, uint32_t objectInstance) {
if (objectType == OBJECT_TYPE_ANALOG_OUTPUT && objectInstance == ANALOG_OUTPUT_INSTANCE) {
return &g_analogOutput;
}
if (objectType == OBJECT_TYPE_BINARY_OUTPUT && objectInstance == BINARY_OUTPUT_INSTANCE) {
return &g_binaryOutput;
}
if (objectType == OBJECT_TYPE_MULTI_STATE_OUTPUT && objectInstance == MULTI_STATE_OUTPUT_INSTANCE) {
return &g_multiStateOutput;
}
return NULL;
}
static bool ReadPrioritySlot(const Commandable* c, uint32_t propertyIdentifier,
bool useArrayIndex, uint32_t propertyArrayIndex,
bool* slotIsSet, double* slotValue) {
if (propertyIdentifier != PROPERTY_IDENTIFIER_PRIORITY_ARRAY || !useArrayIndex ||
propertyArrayIndex < 1 || propertyArrayIndex > BACNET_PRIORITY_ARRAY_SIZE) {
return false;
}
*slotIsSet = c->isSet[propertyArrayIndex - 1];
*slotValue = c->value[propertyArrayIndex - 1];
return true;
}
// -----------------------------------------------------------------------------
// 2. Property "get" callbacks - see B-ASC's main.cpp for the full essay on the
// errorCode out-parameter and the decline-and-fabricate fallback; the same
// rules apply here unchanged. The only NEW material below is serving TWO
// Network Port objects instead of one.
// -----------------------------------------------------------------------------
bool GetPropertyReal(const uint32_t deviceInstance, const uint16_t objectType,
const uint32_t objectInstance, const uint32_t propertyIdentifier,
float* value, const bool useArrayIndex,
const uint32_t propertyArrayIndex, uint32_t* errorCode) {
(void)errorCode;
if (deviceInstance != g_deviceInstance) {
return false;
}
if (objectType == OBJECT_TYPE_ANALOG_INPUT &&
objectInstance == ANALOG_INPUT_INSTANCE &&
propertyIdentifier == PROPERTY_IDENTIFIER_PRESENT_VALUE) {
*value = g_analogInput1Value;
return true;
}
const Commandable* c = GetCommandable(objectType, objectInstance);
if (c != NULL && objectType == OBJECT_TYPE_ANALOG_OUTPUT) {
bool slotIsSet = false;
double slotValue = 0.0;
if (ReadPrioritySlot(c, propertyIdentifier, useArrayIndex, propertyArrayIndex,
&slotIsSet, &slotValue)) {
if (!slotIsSet) {
return false;
}
*value = (float)slotValue;
return true;
}
if (propertyIdentifier == PROPERTY_IDENTIFIER_RELINQUISH_DEFAULT) {
*value = (float)c->relinquishDefault;
return true;
}
}
return false;
}
bool GetPropertyEnumerated(const uint32_t deviceInstance, const uint16_t objectType,
const uint32_t objectInstance, const uint32_t propertyIdentifier,
uint32_t* value, const bool useArrayIndex,
const uint32_t propertyArrayIndex, uint32_t* errorCode) {
(void)errorCode;
if (deviceInstance != g_deviceInstance) {
return false;
}
if (objectType == OBJECT_TYPE_BINARY_INPUT &&
objectInstance == BINARY_INPUT_INSTANCE) {
if (propertyIdentifier == PROPERTY_IDENTIFIER_PRESENT_VALUE) {
*value = 0; // inactive - the series-wide starting value
return true;
}
if (propertyIdentifier == PROPERTY_IDENTIFIER_POLARITY) {
*value = POLARITY_NORMAL;
return true;
}
}
const Commandable* c = GetCommandable(objectType, objectInstance);
if (c != NULL && objectType == OBJECT_TYPE_BINARY_OUTPUT) {
bool slotIsSet = false;
double slotValue = 0.0;
if (ReadPrioritySlot(c, propertyIdentifier, useArrayIndex, propertyArrayIndex,
&slotIsSet, &slotValue)) {
if (!slotIsSet) {
return false;
}
*value = (uint32_t)slotValue;
return true;
}
if (propertyIdentifier == PROPERTY_IDENTIFIER_RELINQUISH_DEFAULT) {
*value = (uint32_t)c->relinquishDefault;
return true;
}
if (propertyIdentifier == PROPERTY_IDENTIFIER_POLARITY) {
*value = POLARITY_NORMAL;
return true;
}
}
if (propertyIdentifier == PROPERTY_IDENTIFIER_UNITS &&
((objectType == OBJECT_TYPE_ANALOG_INPUT && objectInstance == ANALOG_INPUT_INSTANCE) ||
(objectType == OBJECT_TYPE_ANALOG_OUTPUT && objectInstance == ANALOG_OUTPUT_INSTANCE))) {
*value = ENGINEERING_UNITS_DEGREES_CELSIUS;
return true;
}
// BACnet_IP_Mode: NORMAL on BOTH Network Ports - neither is a foreign
// device or a BBMD. Checking objectType only (not instance) serves every
// Network Port this device has, present or future.
if (objectType == OBJECT_TYPE_NETWORK_PORT &&
propertyIdentifier == PROPERTY_IDENTIFIER_BACNET_IP_MODE) {
*value = BACNET_IP_MODE_NORMAL;
return true;
}
return false;
}
bool GetPropertyUnsignedInteger(const uint32_t deviceInstance, const uint16_t objectType,
const uint32_t objectInstance, const uint32_t propertyIdentifier,
uint32_t* value, const bool useArrayIndex,
const uint32_t propertyArrayIndex, uint32_t* errorCode) {
(void)errorCode;
if (deviceInstance != g_deviceInstance) {
return false;
}
if (objectType == OBJECT_TYPE_MULTI_STATE_INPUT &&
objectInstance == MULTI_STATE_INPUT_INSTANCE) {
if (propertyIdentifier == PROPERTY_IDENTIFIER_PRESENT_VALUE) {
*value = 1;
return true;
}
if (propertyIdentifier == PROPERTY_IDENTIFIER_NUMBER_OF_STATES) {
*value = MULTI_STATE_INPUT_NUMBER_OF_STATES;
return true;
}
if (propertyIdentifier == PROPERTY_IDENTIFIER_STATE_TEXT &&
useArrayIndex && propertyArrayIndex == 0) {
*value = MULTI_STATE_INPUT_NUMBER_OF_STATES;
return true;
}
}
if (objectType == OBJECT_TYPE_DEVICE && objectInstance == g_deviceInstance &&
propertyIdentifier == PROPERTY_IDENTIFIER_VENDOR_IDENTIFIER) {
*value = VENDOR_IDENTIFIER;
return true;
}
// Network Port properties that are the SAME for both ports (APDU_Length,
// Reference_Port) vs the ONE that differs (BACnet_IP_UDP_Port).
if (objectType == OBJECT_TYPE_NETWORK_PORT &&
(objectInstance == NETWORK_PORT_1_INSTANCE || objectInstance == NETWORK_PORT_2_INSTANCE)) {
if (propertyIdentifier == PROPERTY_IDENTIFIER_APDU_LENGTH) {
*value = MAX_APDU_LENGTH;
return true;
}
if (propertyIdentifier == PROPERTY_IDENTIFIER_REFERENCE_PORT) {
*value = NETWORK_PORT_REFERENCE_PORT_NONE;
return true;
}
if (propertyIdentifier == PROPERTY_IDENTIFIER_BACNET_IP_UDP_PORT) {
*value = (objectInstance == NETWORK_PORT_1_INSTANCE) ? g_bacnetIpUdpPort1 : g_bacnetIpUdpPort2;
return true;
}
}
const Commandable* c = GetCommandable(objectType, objectInstance);
if (c != NULL && objectType == OBJECT_TYPE_MULTI_STATE_OUTPUT) {
bool slotIsSet = false;
double slotValue = 0.0;
if (ReadPrioritySlot(c, propertyIdentifier, useArrayIndex, propertyArrayIndex,
&slotIsSet, &slotValue)) {
if (!slotIsSet) {
return false;
}
*value = (uint32_t)slotValue;
return true;
}
if (propertyIdentifier == PROPERTY_IDENTIFIER_RELINQUISH_DEFAULT) {
*value = (uint32_t)c->relinquishDefault;
return true;
}
if (propertyIdentifier == PROPERTY_IDENTIFIER_NUMBER_OF_STATES) {
*value = MULTI_STATE_OUTPUT_NUMBER_OF_STATES;
return true;
}
}
return false;
}
bool GetPropertyBool(const uint32_t deviceInstance, const uint16_t objectType,
const uint32_t objectInstance, const uint32_t propertyIdentifier,
bool* value, const bool useArrayIndex,
const uint32_t propertyArrayIndex, uint32_t* errorCode) {
(void)errorCode;
if (deviceInstance != g_deviceInstance) {
return false;
}
const Commandable* c = GetCommandable(objectType, objectInstance);
if (c != NULL && propertyIdentifier == PROPERTY_IDENTIFIER_PRIORITY_ARRAY &&
useArrayIndex && propertyArrayIndex >= 1 &&
propertyArrayIndex <= BACNET_PRIORITY_ARRAY_SIZE) {
*value = !c->isSet[propertyArrayIndex - 1];
return true;
}
// Out_Of_Service: false for every input/output object AND for BOTH Network
// Ports (objectType-only check, so it covers every Network Port instance).
if (propertyIdentifier == PROPERTY_IDENTIFIER_OUT_OF_SERVICE &&
(objectType == OBJECT_TYPE_ANALOG_INPUT ||
objectType == OBJECT_TYPE_BINARY_INPUT ||
objectType == OBJECT_TYPE_MULTI_STATE_INPUT ||
objectType == OBJECT_TYPE_ANALOG_OUTPUT ||
objectType == OBJECT_TYPE_BINARY_OUTPUT ||
objectType == OBJECT_TYPE_MULTI_STATE_OUTPUT ||
objectType == OBJECT_TYPE_NETWORK_PORT)) {
*value = false;
return true;
}
return false;
}
// OCTET STRING - BOTH Network Ports report the SAME host IP/subnet/gateway
// (see the comment above NETWORK_PORT_1_INSTANCE): one host interface, two
// UDP ports simulating two BACnet/IP networks.
bool GetPropertyOctetString(const uint32_t deviceInstance, const uint16_t objectType,
const uint32_t objectInstance, const uint32_t propertyIdentifier,
uint8_t* value, uint32_t* valueElementCount,
const uint32_t maxElementCount, const bool useArrayIndex,
const uint32_t propertyArrayIndex, uint32_t* errorCode) {
(void)useArrayIndex;
(void)propertyArrayIndex;
(void)errorCode;
if (deviceInstance != g_deviceInstance ||
objectType != OBJECT_TYPE_NETWORK_PORT ||
(objectInstance != NETWORK_PORT_1_INSTANCE && objectInstance != NETWORK_PORT_2_INSTANCE) ||
maxElementCount < 4) {
return false;
}
const uint8_t* source = NULL;
switch (propertyIdentifier) {
case PROPERTY_IDENTIFIER_IP_ADDRESS: source = g_ipAddress; break;
case PROPERTY_IDENTIFIER_IP_SUBNET_MASK: source = g_ipSubnetMask; break;
case PROPERTY_IDENTIFIER_IP_DEFAULT_GATEWAY: source = g_ipDefaultGateway; break;
default: return false;
}
memcpy(value, source, 4);
*valueElementCount = 4;
return true;
}
static bool ReturnCharacterString(const char* text, char* value,
uint32_t* valueElementCount,
const uint32_t maxElementCount,
uint8_t* encodingType) {
uint32_t length = (uint32_t)strlen(text);
if (length > maxElementCount) {
length = maxElementCount;
}
memcpy(value, text, length);
*valueElementCount = length;
*encodingType = CHARACTER_STRING_ENCODING_UTF8;
return true;
}
bool GetPropertyCharString(const uint32_t deviceInstance, const uint16_t objectType,
const uint32_t objectInstance, const uint32_t propertyIdentifier,
char* value, uint32_t* valueElementCount,
const uint32_t maxElementCount, uint8_t* encodingType,
const bool useArrayIndex, const uint32_t propertyArrayIndex,
uint32_t* errorCode) {
if (deviceInstance != g_deviceInstance) {
return false;
}
if (objectType == OBJECT_TYPE_MULTI_STATE_INPUT &&
objectInstance == MULTI_STATE_INPUT_INSTANCE &&
propertyIdentifier == PROPERTY_IDENTIFIER_STATE_TEXT && useArrayIndex) {
static const char* const stateText[] = { "On", "Off", "Auto" };
if (propertyArrayIndex >= 1 && propertyArrayIndex <= MULTI_STATE_INPUT_NUMBER_OF_STATES) {
return ReturnCharacterString(stateText[propertyArrayIndex - 1], value,
valueElementCount, maxElementCount, encodingType);
}
*errorCode = ERROR_CODE_INVALID_ARRAY_INDEX;
return false;
}
if (propertyIdentifier == PROPERTY_IDENTIFIER_OBJECT_NAME) {
if (objectType == OBJECT_TYPE_DEVICE && objectInstance == g_deviceInstance) {
return ReturnCharacterString(DEVICE_NAME, value, valueElementCount, maxElementCount, encodingType);
}
if (objectType == OBJECT_TYPE_ANALOG_INPUT && objectInstance == ANALOG_INPUT_INSTANCE) {
return ReturnCharacterString("Bronze", value, valueElementCount, maxElementCount, encodingType);
}
if (objectType == OBJECT_TYPE_BINARY_INPUT && objectInstance == BINARY_INPUT_INSTANCE) {
return ReturnCharacterString("Emerald", value, valueElementCount, maxElementCount, encodingType);
}
if (objectType == OBJECT_TYPE_MULTI_STATE_INPUT && objectInstance == MULTI_STATE_INPUT_INSTANCE) {
return ReturnCharacterString("Hot Pink", value, valueElementCount, maxElementCount, encodingType);
}
if (objectType == OBJECT_TYPE_ANALOG_OUTPUT && objectInstance == ANALOG_OUTPUT_INSTANCE) {
return ReturnCharacterString("Chartreuse", value, valueElementCount, maxElementCount, encodingType);
}
if (objectType == OBJECT_TYPE_BINARY_OUTPUT && objectInstance == BINARY_OUTPUT_INSTANCE) {
return ReturnCharacterString("Fuchsia", value, valueElementCount, maxElementCount, encodingType);
}
if (objectType == OBJECT_TYPE_MULTI_STATE_OUTPUT && objectInstance == MULTI_STATE_OUTPUT_INSTANCE) {
return ReturnCharacterString("Indigo", value, valueElementCount, maxElementCount, encodingType);
}
if (objectType == OBJECT_TYPE_NETWORK_PORT && objectInstance == NETWORK_PORT_1_INSTANCE) {
return ReturnCharacterString("Vermilion", value, valueElementCount, maxElementCount, encodingType);
}
if (objectType == OBJECT_TYPE_NETWORK_PORT && objectInstance == NETWORK_PORT_2_INSTANCE) {
return ReturnCharacterString("Vermilion 2", value, valueElementCount, maxElementCount, encodingType);
}
}
if (objectType == OBJECT_TYPE_DEVICE && objectInstance == g_deviceInstance) {
switch (propertyIdentifier) {
case PROPERTY_IDENTIFIER_DESCRIPTION:
return ReturnCharacterString(DEVICE_DESCRIPTION, value, valueElementCount, maxElementCount, encodingType);
case PROPERTY_IDENTIFIER_VENDOR_NAME:
return ReturnCharacterString(VENDOR_NAME, value, valueElementCount, maxElementCount, encodingType);
case PROPERTY_IDENTIFIER_MODEL_NAME:
return ReturnCharacterString(MODEL_NAME, value, valueElementCount, maxElementCount, encodingType);
case PROPERTY_IDENTIFIER_FIRMWARE_REVISION:
return ReturnCharacterString(g_firmwareRevision.c_str(), value, valueElementCount, maxElementCount, encodingType);
case PROPERTY_IDENTIFIER_APPLICATION_SOFTWARE_VERSION:
return ReturnCharacterString(APP_VERSION, value, valueElementCount, maxElementCount, encodingType);
default:
break;
}
}
return false;
}
// -----------------------------------------------------------------------------
// 2b. Property "set" callbacks - DS-WP-B (identical to B-SA/B-ASC).
// -----------------------------------------------------------------------------
bool SetPropertyReal(const uint32_t deviceInstance, const uint16_t objectType,
const uint32_t objectInstance, const uint32_t propertyIdentifier,
const float value, const bool useArrayIndex,
const uint32_t propertyArrayIndex, const uint8_t priority,
uint32_t* errorCode) {
(void)useArrayIndex;
(void)propertyArrayIndex;
(void)errorCode;
if (deviceInstance != g_deviceInstance) {
return false;
}
Commandable* c = GetCommandable(objectType, objectInstance);
if (c != NULL && objectType == OBJECT_TYPE_ANALOG_OUTPUT &&
propertyIdentifier == PROPERTY_IDENTIFIER_PRESENT_VALUE) {
CommandWrite(c, priority, (double)value);
printf("WriteProperty: Analog Output %u (Chartreuse) <- %.2f @ priority %u\n",
objectInstance, value, EffectivePriority(priority));
return true;
}
return false;
}
bool SetPropertyEnumerated(const uint32_t deviceInstance, const uint16_t objectType,
const uint32_t objectInstance, const uint32_t propertyIdentifier,
const uint32_t value, const bool useArrayIndex,
const uint32_t propertyArrayIndex, const uint8_t priority,
uint32_t* errorCode) {
(void)useArrayIndex;
(void)propertyArrayIndex;
if (deviceInstance != g_deviceInstance) {
return false;
}
Commandable* c = GetCommandable(objectType, objectInstance);
if (c != NULL && objectType == OBJECT_TYPE_BINARY_OUTPUT &&
propertyIdentifier == PROPERTY_IDENTIFIER_PRESENT_VALUE) {
if (value > 1) {
*errorCode = ERROR_CODE_VALUE_OUT_OF_RANGE;
return false;
}
CommandWrite(c, priority, (double)value);
printf("WriteProperty: Binary Output %u (Fuchsia) <- %s @ priority %u\n",
objectInstance, value ? "active" : "inactive", EffectivePriority(priority));
return true;
}
return false;
}
bool SetPropertyUnsignedInteger(const uint32_t deviceInstance, const uint16_t objectType,
const uint32_t objectInstance, const uint32_t propertyIdentifier,
const uint32_t value, const bool useArrayIndex,
const uint32_t propertyArrayIndex, const uint8_t priority,
uint32_t* errorCode) {
(void)useArrayIndex;
(void)propertyArrayIndex;
if (deviceInstance != g_deviceInstance) {
return false;
}
Commandable* c = GetCommandable(objectType, objectInstance);
if (c != NULL && objectType == OBJECT_TYPE_MULTI_STATE_OUTPUT &&
propertyIdentifier == PROPERTY_IDENTIFIER_PRESENT_VALUE) {
if (value < 1 || value > MULTI_STATE_OUTPUT_NUMBER_OF_STATES) {
*errorCode = ERROR_CODE_VALUE_OUT_OF_RANGE;
return false;
}
CommandWrite(c, priority, (double)value);
printf("WriteProperty: Multi-State Output %u (Indigo) <- state %u @ priority %u\n",
objectInstance, value, EffectivePriority(priority));
return true;
}
return false;
}
bool SetPropertyNull(const uint32_t deviceInstance, const uint16_t objectType,
const uint32_t objectInstance, const uint32_t propertyIdentifier,
const bool useArrayIndex, const uint32_t propertyArrayIndex,
const uint8_t priority, uint32_t* errorCode) {
(void)useArrayIndex;
(void)propertyArrayIndex;
(void)errorCode;
if (deviceInstance != g_deviceInstance) {
return false;
}
Commandable* c = GetCommandable(objectType, objectInstance);
if (c != NULL && propertyIdentifier == PROPERTY_IDENTIFIER_PRESENT_VALUE) {
CommandRelinquish(c, priority);
printf("WriteProperty: relinquished %s %u @ priority %u\n",
objectType == OBJECT_TYPE_ANALOG_OUTPUT ? "Analog Output" :
objectType == OBJECT_TYPE_BINARY_OUTPUT ? "Binary Output" :
"Multi-State Output",
objectInstance, EffectivePriority(priority));
return true;
}
return false;
}
// -----------------------------------------------------------------------------
// 2c. Router helpers (F-ROUTER)
//
// SendIAmRouterToNetwork/SendWhoIsRouterToNetwork/SendNetworkNumberIs all take
// a DESTINATION connection string (who to send TO), not a source. Broadcasting
// on one of our own ports means "the local subnet broadcast of THAT port's
// network" - the same address CASExampleHelper::SendIAm computes internally,
// rebuilt here because main.cpp does not have access to that private helper.
// -----------------------------------------------------------------------------
static void BuildLocalBroadcastConnectionString(uint16_t port, uint8_t connectionString[6]) {
uint8_t bcast[4] = { 255, 255, 255, 255 };
uint8_t ip[4], mask[4];
if (CASExampleHelper::GetLocalIPv4(ip, mask)) {
bcast[0] = (uint8_t)(ip[0] | ~mask[0]);
bcast[1] = (uint8_t)(ip[1] | ~mask[1]);
bcast[2] = (uint8_t)(ip[2] | ~mask[2]);
bcast[3] = (uint8_t)(ip[3] | ~mask[3]);
}
connectionString[0] = bcast[0];
connectionString[1] = bcast[1];
connectionString[2] = bcast[2];
connectionString[3] = bcast[3];
connectionString[4] = (uint8_t)((port >> 8) & 0xFF);
connectionString[5] = (uint8_t)(port & 0xFF);
}
// Broadcast I-Am-Router-To-Network on BOTH ports, each announcing this
// router's FULL configured routing table (networkNumbers = NULL, count = 0 -
// see BACnetStack_SendIAmRouterToNetwork's doc comment: since CAS BACnet Stack
// #1014 this works for a physical router too, and reports every enabled
// port's directly-connected network plus every BACnetStack_AddRouterRoute
// entry). Called once at start-up and again whenever the 'r' key is pressed.
static void AnnounceRouterToBothNetworks() {
uint8_t cs1[6];
BuildLocalBroadcastConnectionString(g_bacnetIpUdpPort1, cs1);
const bool ok1 = BACnetStack_SendIAmRouterToNetwork(
NULL, 0, cs1, 6, NETWORK_PORT_1_INSTANCE, true, 0, NULL, 0);
uint8_t cs2[6];
BuildLocalBroadcastConnectionString(g_bacnetIpUdpPort2, cs2);
const bool ok2 = BACnetStack_SendIAmRouterToNetwork(
NULL, 0, cs2, 6, NETWORK_PORT_2_INSTANCE, true, 0, NULL, 0);
printf("FYI: I-Am-Router-To-Network broadcast on Network Port 1 (Vermilion): %s; "
"on Network Port 2 (Vermilion 2): %s\n",
ok1 ? "sent" : "FAILED", ok2 ? "sent" : "FAILED");
}
// -----------------------------------------------------------------------------
// 3. main()
// -----------------------------------------------------------------------------
int main(int argc, char** argv) {
setvbuf(stdout, NULL, _IONBF, 0);
if (!LoadBACnetFunctions()) {
fprintf(stderr, "Error: failed to load the CAS BACnet Stack: %s\n",
CASBACnetStackAdapter_LastError());
return 1;
}
{
char buf[32];
snprintf(buf, sizeof(buf), "%u.%u.%u.%u",
BACnetStack_GetAPIMajorVersion(), BACnetStack_GetAPIMinorVersion(),
BACnetStack_GetAPIPatchVersion(), BACnetStack_GetAPIBuildVersion());
g_firmwareRevision = buf;
}
if (CASExampleHelper::HandleHelpAndVersionArgs(argc, argv, APP_NAME, APP_VERSION)) {
return 0;
}
// --port sets Network Port 1 (Vermilion); --port2 sets Network Port 2
// (Vermilion 2), defaulting to --port + 1 so the example runs out of the
// box with two DIFFERENT UDP ports and no extra flags. ParsePortArg (the
// shared helper) only knows the one "--port" flag, so --port2 is parsed
// locally with the same validation rule.
const uint16_t port1 = CASExampleHelper::ParsePortArg(argc, argv, 47808);
uint16_t port2 = (uint16_t)(port1 + 1);
for (int i = 1; i + 1 < argc; ++i) {
if (strcmp(argv[i], "--port2") == 0) {
char* end = NULL;
errno = 0;
const long p = strtol(argv[i + 1], &end, 10);
if (errno == 0 && end != argv[i + 1] && *end == '\0' && p > 0 && p <= 65535) {
port2 = (uint16_t)p;
} else {
printf("Warning: ignoring invalid --port2 \"%s\" (want 1..65535); using %u.\n",
argv[i + 1], (unsigned)port2);
}
}
}
if (port2 == port1) {
fprintf(stderr, "Error: --port2 (%u) must differ from --port (%u) - they are two "
"separate BACnet/IP networks on this router.\n",
(unsigned)port2, (unsigned)port1);
return 1;
}
g_deviceInstance = CASExampleHelper::ParseDeviceIdArg(argc, argv, g_deviceInstance);
CASExampleHelper::PrintVersion(APP_NAME, APP_VERSION);
// --- Bind BOTH BACnet/IP sockets (F-MULTIPORT) --------------------------
// SetNetworkPortInstance first, so the single-argument SetupUDP(port1) and
// (later) SendIAm(deviceInstance) act on Network Port 1 by default; port 2
// is bound with the explicit two-argument overload.
CASExampleHelper::SetNetworkPortInstance(NETWORK_PORT_1_INSTANCE);
if (!CASExampleHelper::SetupUDP(port1)) {
return 1;
}
if (!CASExampleHelper::SetupUDP(port2, NETWORK_PORT_2_INSTANCE)) {
return 1;
}
g_bacnetIpUdpPort1 = port1;
g_bacnetIpUdpPort2 = port2;
if (!CASExampleHelper::GetLocalIPv4(g_ipAddress, g_ipSubnetMask)) {
printf("FYI: could not read a local IPv4 address; both Network Ports will report "
"IP_Address 0.0.0.0.\n");
}
// --- Register callbacks -------------------------------------------------
// One set of transport/time callbacks serves BOTH ports - common/ 2.3.0+
// dispatches on networkPortInstance internally (see CASExampleHelper.cpp).
CASExampleHelper::RegisterCommonCallbacks();
BACnetStack_RegisterCallbackGetPropertyReal(GetPropertyReal);
BACnetStack_RegisterCallbackGetPropertyEnumerated(GetPropertyEnumerated);
BACnetStack_RegisterCallbackGetPropertyUnsignedInteger(GetPropertyUnsignedInteger);
BACnetStack_RegisterCallbackGetPropertyCharacterString(GetPropertyCharString);
BACnetStack_RegisterCallbackGetPropertyBool(GetPropertyBool);
BACnetStack_RegisterCallbackGetPropertyOctetString(GetPropertyOctetString);
BACnetStack_RegisterCallbackSetPropertyReal(SetPropertyReal);
BACnetStack_RegisterCallbackSetPropertyEnumerated(SetPropertyEnumerated);
BACnetStack_RegisterCallbackSetPropertyUnsignedInteger(SetPropertyUnsignedInteger);
BACnetStack_RegisterCallbackSetPropertyNull(SetPropertyNull);
// NOTE: no DeviceCommunicationControl callback - this profile (unlike
// B-ASC, its seed) does not include DM-DCC-B.
// --- Create the device --------------------------------------------------
if (!BACnetStack_AddDevice(g_deviceInstance)) {
printf("Error: Failed to add the Device %u.\n", g_deviceInstance);
return 1;
}
// DS-RP-B, DS-WP-B: ReadProperty, WriteProperty.
if (!BACnetStack_SetServiceEnabled(g_deviceInstance, SERVICE_READ_PROPERTY, true)) {
printf("Error: Failed to enable the ReadProperty service.\n");
return 1;
}
if (!BACnetStack_SetServiceEnabled(g_deviceInstance, SERVICE_WRITE_PROPERTY, true)) {
printf("Error: Failed to enable the WriteProperty service.\n");
return 1;
}
// DM-DDB-A/B, DM-DOB-B: Who-Is/I-Am (both directions - DM-DDB-A means this
// device also INITIATES Who-Is, not just answers it) and Who-Has/I-Have.
// NM-RC-B's network-layer messages (Who-Is-Router-To-Network,
// I-Am-Router-To-Network, Network-Number-Is) are NOT gated by
// SetServiceEnabled - they are enabled purely by BACnetStack_AddRouterPort
// + BACnetStack_SetRouterEnabled below.
if (!BACnetStack_SetServiceEnabled(g_deviceInstance, SERVICE_WHO_IS, true) ||
!BACnetStack_SetServiceEnabled(g_deviceInstance, SERVICE_I_AM, true) ||
!BACnetStack_SetServiceEnabled(g_deviceInstance, SERVICE_WHO_HAS, true) ||
!BACnetStack_SetServiceEnabled(g_deviceInstance, SERVICE_I_HAVE, true)) {
printf("Error: Failed to enable the discovery services (Who-Is/I-Am, Who-Has/I-Have).\n");
return 1;
}
// --- Add the read-only sensor objects -----------------------------------
if (!BACnetStack_AddObject(g_deviceInstance, OBJECT_TYPE_ANALOG_INPUT, ANALOG_INPUT_INSTANCE)) {
printf("Error: Failed to add Analog Input %u (Bronze).\n", ANALOG_INPUT_INSTANCE);
return 1;
}
if (!BACnetStack_AddObject(g_deviceInstance, OBJECT_TYPE_BINARY_INPUT, BINARY_INPUT_INSTANCE)) {
printf("Error: Failed to add Binary Input %u (Emerald).\n", BINARY_INPUT_INSTANCE);
return 1;
}
if (!BACnetStack_AddObject(g_deviceInstance, OBJECT_TYPE_MULTI_STATE_INPUT, MULTI_STATE_INPUT_INSTANCE)) {
printf("Error: Failed to add Multi-State Input %u (Hot Pink).\n", MULTI_STATE_INPUT_INSTANCE);
return 1;
}
// --- Add the commandable OUTPUT objects ----------------------------------
if (!BACnetStack_AddObject(g_deviceInstance, OBJECT_TYPE_ANALOG_OUTPUT, ANALOG_OUTPUT_INSTANCE)) {
printf("Error: Failed to add Analog Output %u (Chartreuse).\n", ANALOG_OUTPUT_INSTANCE);
return 1;
}
if (!BACnetStack_AddObject(g_deviceInstance, OBJECT_TYPE_BINARY_OUTPUT, BINARY_OUTPUT_INSTANCE)) {
printf("Error: Failed to add Binary Output %u (Fuchsia).\n", BINARY_OUTPUT_INSTANCE);
return 1;
}
if (!BACnetStack_AddObject(g_deviceInstance, OBJECT_TYPE_MULTI_STATE_OUTPUT, MULTI_STATE_OUTPUT_INSTANCE)) {
printf("Error: Failed to add Multi-State Output %u (Indigo).\n", MULTI_STATE_OUTPUT_INSTANCE);
return 1;
}
// --- Add BOTH Network Port objects (F-MULTIPORT) -------------------------
// Each one is BACNET_APPLICATION level, so it gets a Network_Number and
// Network_Number_Quality; we pass CONFIGURED, since a router locally
// configures the number of each network it joins rather than learning it.
if (!BACnetStack_AddNetworkPortObject(
g_deviceInstance, NETWORK_PORT_1_INSTANCE,
NETWORK_PORT_NETWORK_TYPE_IPV4,
NETWORK_PORT_PROTOCOL_LEVEL_BACNET_APPLICATION,
NETWORK_NUMBER_PORT_1,
NETWORK_NUMBER_QUALITY_CONFIGURED,
NETWORK_PORT_REFERENCE_PORT_NONE)) {
printf("Error: Failed to add Network Port 1 (Vermilion).\n");
return 1;
}
if (!BACnetStack_AddNetworkPortObject(
g_deviceInstance, NETWORK_PORT_2_INSTANCE,
NETWORK_PORT_NETWORK_TYPE_IPV4,
NETWORK_PORT_PROTOCOL_LEVEL_BACNET_APPLICATION,
NETWORK_NUMBER_PORT_2,
NETWORK_NUMBER_QUALITY_CONFIGURED,
NETWORK_PORT_REFERENCE_PORT_NONE)) {
printf("Error: Failed to add Network Port 2 (Vermilion 2).\n");
return 1;
}
// --- Enable the OPTIONAL properties we choose to expose ------------------
if (!BACnetStack_SetPropertyEnabled(g_deviceInstance, OBJECT_TYPE_DEVICE,
g_deviceInstance, PROPERTY_IDENTIFIER_DESCRIPTION, true)) {
printf("Error: Failed to enable Description on the Device object.\n");
return 1;
}
if (!BACnetStack_SetPropertyEnabled(g_deviceInstance, OBJECT_TYPE_MULTI_STATE_INPUT,
MULTI_STATE_INPUT_INSTANCE, PROPERTY_IDENTIFIER_STATE_TEXT, true)) {
printf("Error: Failed to enable State_Text on Multi-State Input 1 (Hot Pink).\n");
return 1;
}
// Routing_Table (cl. 12.56.62) is INTENTIONALLY NOT enabled here.
//
// BACnetStack_AddNetworkPortObject's doc comment says it is served by the
// stack "if you enable them" - but verified against the pinned stack
// (abd4cee1) with a live client, enabling it and then reading it aborts
// the request: BACnetBusinessLogic::UseCallbackGetList has no case for
// Network Port/Routing_Table outside the forbidden A-side test-tool surface, so the
// read always fails to encode. Enabling a property that is guaranteed to
// abort on every read is worse than not claiming it at all - see TODO.md
// and https://github.com/chipkin/cas-bacnet-stack/issues/2038.
// --- Make the output objects commandable --------------------------------
struct CommandableObject { uint16_t type; uint32_t instance; };
const CommandableObject outputs[] = {
{ OBJECT_TYPE_ANALOG_OUTPUT, ANALOG_OUTPUT_INSTANCE },
{ OBJECT_TYPE_BINARY_OUTPUT, BINARY_OUTPUT_INSTANCE },
{ OBJECT_TYPE_MULTI_STATE_OUTPUT, MULTI_STATE_OUTPUT_INSTANCE },
};
for (size_t i = 0; i < sizeof(outputs) / sizeof(outputs[0]); ++i) {
if (!BACnetStack_SetPropertyEnabled(g_deviceInstance, outputs[i].type, outputs[i].instance,
PROPERTY_IDENTIFIER_PRIORITY_ARRAY, true) ||
!BACnetStack_SetPropertyEnabled(g_deviceInstance, outputs[i].type, outputs[i].instance,
PROPERTY_IDENTIFIER_RELINQUISH_DEFAULT, true) ||
!BACnetStack_SetPropertyWritable(g_deviceInstance, outputs[i].type, outputs[i].instance,
PROPERTY_IDENTIFIER_PRESENT_VALUE, true)) {
printf("Error: Failed to make object type %u instance %u commandable.\n",
outputs[i].type, outputs[i].instance);
return 1;
}
}
// --- F-ROUTER: configure and enable physical routing ---------------------
// AddRouterPort registers each DIRECTLY connected network (one call per
// Network Port that participates - see its doc comment: "two or more
// ports make the device a router").
if (!BACnetStack_AddRouterPort(g_deviceInstance, ROUTER_PORT_ID_1,
NETWORK_NUMBER_PORT_1, ROUTER_NETWORK_TYPE_IP)) {
printf("Error: Failed to register router port 1 (network %u, Vermilion).\n",
(unsigned)NETWORK_NUMBER_PORT_1);
return 1;
}
if (!BACnetStack_AddRouterPort(g_deviceInstance, ROUTER_PORT_ID_2,
NETWORK_NUMBER_PORT_2, ROUTER_NETWORK_TYPE_IP)) {
printf("Error: Failed to register router port 2 (network %u, Vermilion 2).\n",
(unsigned)NETWORK_NUMBER_PORT_2);
return 1;
}
// AddRouterRoute: a static route to DEMO_REMOTE_NETWORK, one hop beyond
// port 2, with no next-hop MAC configured (NULL/0 - "the relay falls back
// to the egress link broadcast" per the doc comment). DEMONSTRATION ONLY:
// see the DEMO_REMOTE_NETWORK comment above - nothing actually answers on
// this network in this example series, and Routing_Table cannot be read
// back at this pin (TODO.md), so this call demonstrates the AddRouterRoute
// API accepting the configuration, not an end-to-end verified route.
if (!BACnetStack_AddRouterRoute(g_deviceInstance, DEMO_REMOTE_NETWORK,
ROUTER_PORT_ID_2, NULL, 0)) {
printf("Error: Failed to configure the demonstration route to network %u.\n",
(unsigned)DEMO_REMOTE_NETWORK);
return 1;
}
// Routing is opt-in even with ports configured (SetRouterEnabled's doc
// comment: "configuring ports alone does not start forwarding").
if (!BACnetStack_SetRouterEnabled(g_deviceInstance, true)) {
printf("Error: Failed to enable routing. (Built without STACK_OPTION_ROUTER_PHYSICAL?)\n");
return 1;
}
// Who-Is is answered automatically on both ports (DM-DDB-B). Broadcast an
// unsolicited I-Am on EACH network this device is on (DM-DDB-A/cl. 16.1 -
// one I-Am per network the device is directly reachable from).
CASExampleHelper::SendIAm(g_deviceInstance, NETWORK_PORT_1_INSTANCE);