Repository navigation
Expand file tree
/
Copy pathmain.rs
More file actions
1050 lines (991 loc) · 49.7 KB
/
Copy pathmain.rs
File metadata and controls
1050 lines (991 loc) · 49.7 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-SS (BACnet Smart Sensor) - Rust
//
// The Rust translation of BACnetProfileExample-B-SS-CPP's main.cpp (v1.3.0):
// same device, same objects, same sensor Simulation, same test-only hook, same
// command line - its Wire Tests (tests/) run unchanged against this program.
//
// "A B-SS is a simple sensing device with very limited resources." (ANSI/ASHRAE
// 135-2024, Annex L.4.5). Its Profile Function is the one Data Sharing line of
// that clause: "Ability to provide values for any of its BACnet objects upon
// request" - a client reads the sensor and gets what it is measuring NOW. Its
// only mandatory service is:
//
// DS-RP-B - respond to ReadProperty requests
//
// plus the ability to be discovered: it answers Who-Is with I-Am (handled
// automatically by the stack) and announces itself with an unsolicited I-Am on
// start-up.
//
// SIMULATION. This example has no real sensor, so section 2 below is a sensor
// Simulation that stands in for the physical world: the temperature ramps up and
// down, the binary input toggles and the multi-state input steps through its
// states, all on a timer. It is NOT part of the BACnet Surface - on a real device
// you replace sensor_simulation_tick() with your hardware sampling. The
// Simulation also has one Failure Mode: a broken sensor wire, which this device
// reports the BACnet way, as Reliability OPEN_LOOP and the FAULT bit of
// Status_Flags (cl. 12.2.7, 12.2.9). A Wire Test breaks the "wire" through a
// test-only hook (SENSOR_FAULT_FILE_VARIABLE below); nothing on the network can.
//
// A B-SS does NOT require WriteProperty, COV, alarms/events, scheduling, or
// trending - so this example deliberately does NOT enable any of those. That is
// the whole point of a profile example: implement exactly what the profile
// asks for, nothing more.
//
// The device exposes three read-only sensor objects plus the Network Port
// object that every BACnet device must have. Each object is given a colour name
// (a convention shared across this example series):
//
// Device 389001 "Chipkin Example B-SS" (instance configurable with --deviceID,
// Object_Name with --deviceName)
// Analog Input 1 "Bronze" (REAL, degrees Celsius; ramps 18.0 .. 26.0)
// Binary Input 1 "Emerald" (active / inactive; toggles every 3 s)
// Multi-State Input 1 "Hot Pink" (an enumerated state, 1..3; steps every 4 s)
// Network Port 1 "Vermilion" (the BACnet/IP port - required)
//
// To be a conformant BACnet device (Protocol_Revision 30) 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_*).
// Event_State is NOT generated - with no alarming configured it simply reads its
// datatype default of normal(0), correct by coincidence, not because the stack
// computes it. The handful that the application must supply are served by the
// Get*Property callbacks below, and a few are turned on with SetPropertyEnabled.
//
// Interactive keys (handled by the shared helper): h = help, q = quit,
// u / d = nudge the simulated Analog Input 1 reading by +/-1.1 (on a terminal,
// press Enter after the key - see common/cas_example_helper.rs poll_key()).
// Command line: --port <n>, --deviceID <n>, --deviceName <text>, --help,
// --version.
//
// WHAT IS DIFFERENT FROM THE C++ EDITION, AND WHY:
// - The stack is loaded at run time through the stack's own Rust adapter,
// compiled IN PLACE from the submodule (the `mod cas_bacnet_stack_adapters`
// below): `libloading`, every symbol looked up at its first call - the
// Rust equivalent of the C++ edition's LoadBACnetFunctions() in DLL mode.
// - BACnetStack_RegisterCallback*() takes a plain `extern "C" fn`, not a
// closure, so every callback is a free-standing function that reads the
// device's state from one static (common/device_state.rs) instead of the
// C++ edition's g_* globals.
// - A Rust panic must never unwind into the C stack, so every callback body
// runs inside std::panic::catch_unwind and declines (returns false,
// errorCode untouched) if it panics.
//
// All the UDP/stack plumbing lives in common/cas_example_helper.rs so this file
// can stay focused on the BACnet logic.
// =============================================================================
// The CAS BACnet Stack's Rust adapter, generated by the stack's
// _ci_scripts/generate-rust-adapter.js and compiled IN PLACE from the
// submodule - never copied into this repository (its licence covers it as part
// of the stack). It binds every export of the stack; this example calls a
// handful, so the unused ones are allowed here rather than warned about.
#[allow(dead_code)]
#[path = "../submodules/cas-bacnet-stack/adapters/rust/cas_bacnet_stack_adapters.rs"]
mod cas_bacnet_stack_adapters;
mod common;
use std::os::raw::c_char;
use std::panic::catch_unwind;
use std::path::PathBuf;
use std::process::ExitCode;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::Arc;
use std::time::{Duration, Instant};
use cas_bacnet_stack_adapters as bacnet;
use common::cas_example_helper::{self as helper, KeyCommand};
use common::constants::*;
use common::device_state::state;
// -----------------------------------------------------------------------------
// 1. Example + device configuration
// -----------------------------------------------------------------------------
const APP_NAME: &str = "BACnet B-SS (Smart Sensor) Example - Rust";
const APP_VERSION: &str = "1.2.1";
// The device instance. BACnet requires this to be configurable, so it defaults
// to 389001 and can be overridden on the command line with --deviceID. Keep it
// configurable in your product: it must be unique across the internetwork.
const DEFAULT_DEVICE_INSTANCE: u32 = 389001;
// ---- Device identity: CHANGE ALL OF THIS BEFORE YOU SHIP --------------------
// Everything in this block is read by clients and shown to the operator in every
// discovery tool on the network. Left as-is, your product will appear on a real
// site announcing itself as a Chipkin demo. None of it is cosmetic:
// Object_Name must be unique across the BACnet internetwork, and Model_Name /
// Vendor_Identifier are what a building operator uses to identify your device.
//
// This block is the ship checklist. Every constant below has a note saying what
// to change it to; nothing here is safe to leave at its example value.
// -----------------------------------------------------------------------------
// Your BACnet Vendor Identifier. 389 = Chipkin Automation Systems; change this
// to YOUR company's vendor ID before shipping a product. Vendor IDs are assigned
// by ASHRAE - request one (free) at https://bacnet.org/assigned-vendor-ids/.
// Update VENDOR_NAME below to match.
const VENDOR_IDENTIFIER: u32 = 389;
// The Device object's Object_Name - the DEFAULT one.
//
// THIS IS THE ONE THAT WILL BITE YOU. Object_Name must be unique across the
// whole BACnet internetwork (cl. 12.1.1.4), so it must be per-unit
// configurable, exactly like the instance. This example takes it at start-up
// with --deviceName <text> (common/ parse_device_name_arg(), read into the
// device state's device_name in main()); DEVICE_NAME is only what a unit
// announces when nobody configured it. Ship two units without --deviceName and
// BOTH announce the same Object_Name - a spec violation, and a hard BTL
// failure. In your product, configure the name per unit (a serial number, DIP
// switches, a config file, or this argument) and change the default below to
// something that says "not configured yet".
const DEVICE_NAME: &str = "Chipkin Example B-SS";
// The Device object's Description. Change it to what YOUR device actually is;
// this string describes this tutorial.
const DEVICE_DESCRIPTION: &str = "Chipkin CAS BACnet Stack example - B-SS (Smart Sensor) profile. \
Demonstrates DS-RP-B: ReadProperty plus Who-Is/I-Am with read-only sensor objects.";
// Device identity strings (read by clients, and used to populate I-Am).
// VENDOR_NAME - your company name; it must match VENDOR_IDENTIFIER above.
// MODEL_NAME - your model designation. This is what a building operator reads
// to identify your device in a discovery tool.
// Application_Software_Version (12) is just APP_VERSION - one source of truth,
// so it can never drift from what --version / the start-up banner prints.
// Firmware_Revision (44) names the underlying platform/stack, not this
// example's own version: it is built at start-up from the stack's own
// BACnetStack_GetAPI*Version() calls (the same ones the banner's
// "CAS BACnet Stack version" line uses) into the device state's
// firmware_revision, right after the stack loads.
const VENDOR_NAME: &str = "Chipkin Automation Systems";
const MODEL_NAME: &str = "CAS BACnet Stack Example - B-SS";
// The sensor objects (all instance 1) and their colour names.
const ANALOG_INPUT_INSTANCE: u32 = 1; // "Bronze"
const BINARY_INPUT_INSTANCE: u32 = 1; // "Emerald"
const MULTI_STATE_INPUT_INSTANCE: u32 = 1; // "Hot Pink"
const MULTI_STATE_INPUT_NUMBER_OF_STATES: u32 = 3;
// The Network Port object - every BACnet device must have one. It represents
// the BACnet/IP port this device communicates on.
const NETWORK_PORT_INSTANCE: u32 = 1; // "Vermilion"
const MAX_APDU_LENGTH: u32 = 1476; // BACnet/IP APDU length
// The sensor objects' live values, the Network Port's BACnet/IP addressing and
// Analog Input 1's Reliability live in common/device_state.rs (STATE): the
// callbacks in section 3 only ever hand them back; section 2 (the Simulation)
// is the only thing that changes the sensor values. On a real device your
// hardware sampling updates them instead.
//
// Analog Input 1's Reliability (cl. 12.2.9). NO_FAULT_DETECTED while the sensor
// is healthy; OPEN_LOOP while its (simulated) wire is broken. The stack builds
// the FAULT bit of Status_Flags from this property by itself (cl. 12.2.7: FAULT
// is "Logical TRUE (1) if the Reliability property is present and does not have
// a value of NO_FAULT_DETECTED") - the example only has to serve it.
const PROPERTY_IDENTIFIER_RELIABILITY: u32 = 103;
const RELIABILITY_NO_FAULT_DETECTED: u32 = 0;
const RELIABILITY_OPEN_LOOP: u32 = 4;
// -----------------------------------------------------------------------------
// 2. The sensor Simulation (NOT part of the BACnet Surface)
//
// Stands in for the physical world. Once a second:
// - Analog Input 1 moves 0.5 C, ramping up to 26.0 and back down to 18.0
// - Binary Input 1 toggles every 3 s
// - Multi-State Input 1 steps 1 -> 2 -> 3 -> 1 every 4 s
// and the sensor wire is checked.
//
// The broken wire is a TEST-ONLY hook, not a feature: when the environment
// variable named by SENSOR_FAULT_FILE_VARIABLE names a file, the wire counts as
// broken for as long as that file exists. A Wire Test creates and deletes the
// file to break and repair the sensor. While the wire is broken the reading
// freezes at its last good value (a dead wire measures nothing new) and
// Reliability reads OPEN_LOOP; once the file is gone the reading resumes and
// Reliability returns to NO_FAULT_DETECTED. On a real device, set Reliability
// from your hardware's own diagnostics (an ADC reading on the rails, a sensor
// that stopped answering, ...).
// -----------------------------------------------------------------------------
const SENSOR_FAULT_FILE_VARIABLE: &str = "CAS_EXAMPLE_TEST_SENSOR_FAULT_FILE";
const ANALOG_INPUT_LOWEST: f32 = 18.0;
const ANALOG_INPUT_HIGHEST: f32 = 26.0;
const ANALOG_INPUT_STEP: f32 = 0.5;
const BINARY_INPUT_TOGGLE_SECONDS: u64 = 3;
const MULTI_STATE_INPUT_STEP_SECONDS: u64 = 4;
/// The Simulation's own bookkeeping (the C++ edition's function-local
/// statics). Created when the main loop starts.
struct SensorSimulation {
sensor_fault_file: Option<PathBuf>, // read once at start-up; None = no hook
started: Instant,
last_second: u64,
analog_input_direction: f32,
}
impl SensorSimulation {
fn new(sensor_fault_file: Option<PathBuf>) -> Self {
SensorSimulation { sensor_fault_file, started: Instant::now(), last_second: 0, analog_input_direction: 1.0 }
}
fn sensor_wire_broken(&self) -> bool {
match &self.sensor_fault_file {
Some(path) => std::fs::File::open(path).is_ok(),
None => false,
}
}
}
fn sensor_simulation_tick(simulation: &mut SensorSimulation) {
let seconds_running = simulation.started.elapsed().as_secs();
if seconds_running == simulation.last_second {
return;
}
simulation.last_second = seconds_running;
let reliability =
if simulation.sensor_wire_broken() { RELIABILITY_OPEN_LOOP } else { RELIABILITY_NO_FAULT_DETECTED };
let mut device = state();
if reliability != device.analog_input_1_reliability {
device.analog_input_1_reliability = reliability;
let broken = reliability == RELIABILITY_OPEN_LOOP;
println!(
"Simulation: Analog Input 1 (Bronze) sensor wire {} - Reliability {}",
if broken { "broken" } else { "repaired" },
if broken { "OPEN_LOOP" } else { "NO_FAULT_DETECTED" }
);
}
if device.analog_input_1_reliability == RELIABILITY_NO_FAULT_DETECTED {
if device.analog_input_1_value >= ANALOG_INPUT_HIGHEST {
simulation.analog_input_direction = -1.0;
} else if device.analog_input_1_value <= ANALOG_INPUT_LOWEST {
simulation.analog_input_direction = 1.0;
}
device.analog_input_1_value += simulation.analog_input_direction * ANALOG_INPUT_STEP;
}
if seconds_running % BINARY_INPUT_TOGGLE_SECONDS == 0 {
device.binary_input_1_value = if device.binary_input_1_value != 0 { 0 } else { 1 };
}
if seconds_running % MULTI_STATE_INPUT_STEP_SECONDS == 0 {
device.multi_state_input_1_value =
device.multi_state_input_1_value % MULTI_STATE_INPUT_NUMBER_OF_STATES + 1;
}
}
// -----------------------------------------------------------------------------
// 3. Property "get" callbacks
//
// The stack calls these when a client reads a property. For each data type the
// stack uses a separate callback. We return true (and fill *value) when we
// recognise the (object, property) pair, and false otherwise.
//
// THE errorCode OUT-PARAMETER. Every Get callback ends with an error_code
// pointer. The stack PRESETS it to success (84) before the call, and reads it
// only if you return false. That gives a declining callback two distinct
// meanings:
//
// 1. return false and LEAVE *error_code ALONE -> "I have no opinion on this
// property." The stack falls back to its own handling (see below).
// 2. return false and SET *error_code -> "This read fails, with THIS
// BACnet error." The client gets exactly that Error-PDU.
//
// Option 2 is new (CAS BACnet Stack issue #974); before it, a Get callback had
// no way to name an error at all. Do not reach for it reflexively - option 1 is
// still the right answer most of the time, for the reason in the next paragraph.
//
// WHAT false-WITHOUT-AN-ERROR-CODE ACTUALLY DOES - the most important paragraph
// in this file, and the opposite of what most people assume. It does NOT
// reliably produce a BACnet error. The stack errors only 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
// (declining one of those reads back as Error: read-access-denied).
// 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
//
// AND THAT FALLBACK IS LORE-BEARING, WHICH IS WHY WE DO NOT "FIX" IT HERE.
// It is tempting to end every callback with *error_code = unknown-property so
// nothing is ever silently invented. That breaks the device. The stack relies on
// the decline-and-fabricate path to answer required properties the application
// is not expected to serve - the Device's Max_APDU_Length_Accepted, APDU_Timeout
// and Number_Of_APDU_Retries among them. Name an error on the catch-all return
// and those required properties start failing instead of answering.
// So: set *error_code ONLY where THIS device knows the read is wrong. There is
// exactly one such case below (State_Text with an out-of-range array index); the
// catch-all `false` at the end of each callback deliberately leaves error_code
// alone.
//
// ADDING AN OBJECT? READ THIS FIRST.
// These callbacks are not uniformly strict:
// - get_property_real / get_property_enumerated / get_property_unsigned_integer
// match on object type AND INSTANCE (e.g. object_instance ==
// ANALOG_INPUT_INSTANCE). A new instance falls through every one of them.
// - get_property_bool matches on TYPE ONLY, so a new instance gets
// Out_Of_Service for free.
// So a half-added object does NOT fail loudly. Its Present_Value errors (that one
// is in the list above) - but its Object_Name reads back as "undefined" and its
// Units as no-units, with no error at all. Add two objects that way and BOTH
// report Object_Name "undefined": duplicate object names within one device, a
// spec violation and a hard BTL failure, which every scan tool shows you as a
// healthy object.
//
// 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. The
// TUTORIAL's "Add a second analog input" recipe lists the edits.
//
// SAFETY of the `unsafe` writes below: every pointer the stack passes (value,
// error_code, value_element_count, encoding_type) is valid and writable for the
// duration of the call, per the stack's documented callback contract.
// -----------------------------------------------------------------------------
/// REAL (floating point) - the Analog Input's Present_Value.
extern "C" fn get_property_real(
device_instance: u32,
object_type: u16,
object_instance: u32,
property_identifier: u32,
value: *mut f32,
_use_array_index: bool,
_property_array_index: u32,
_error_code: *mut u32, // see "THE errorCode OUT-PARAMETER" above: we decline without naming an error
) -> bool {
catch_unwind(|| {
let device = state();
if device_instance == device.device_instance
&& object_type == OBJECT_TYPE_ANALOG_INPUT
&& object_instance == ANALOG_INPUT_INSTANCE
&& property_identifier == PROPERTY_IDENTIFIER_PRESENT_VALUE
{
// ON REAL HARDWARE: return the live sensor reading here. Read it from
// a cached variable that your hardware updates (as
// analog_input_1_value is), NOT directly from a slow/blocking device
// (I2C, SPI, ADC conversion): this callback runs inside
// BACnetStack_Tick(), so blocking it delays all BACnet processing.
// Sample the sensor on a timer/another thread and just hand back the
// latest value from here.
unsafe { *value = device.analog_input_1_value };
return true;
}
false
})
.unwrap_or(false)
}
/// ENUMERATED - the Binary Input's Present_Value (0 = inactive, 1 = active) and
/// Polarity, the Analog Input's Units and Reliability, and the Network Port's
/// BACnet_IP_Mode.
extern "C" fn get_property_enumerated(
device_instance: u32,
object_type: u16,
object_instance: u32,
property_identifier: u32,
value: *mut u32,
_use_array_index: bool,
_property_array_index: u32,
_error_code: *mut u32,
) -> bool {
catch_unwind(|| {
let device = state();
if device_instance != device.device_instance {
return false;
}
if object_type == OBJECT_TYPE_BINARY_INPUT && object_instance == BINARY_INPUT_INSTANCE {
if property_identifier == PROPERTY_IDENTIFIER_PRESENT_VALUE {
// ON REAL HARDWARE: return your cached input state here - the same
// rule as get_property_real above applies (never block this
// callback on slow I/O).
unsafe { *value = device.binary_input_1_value };
return true;
}
if property_identifier == PROPERTY_IDENTIFIER_POLARITY {
unsafe { *value = POLARITY_NORMAL }; // required property of a Binary Input
return true;
}
}
if object_type == OBJECT_TYPE_ANALOG_INPUT && object_instance == ANALOG_INPUT_INSTANCE {
if property_identifier == PROPERTY_IDENTIFIER_UNITS {
unsafe { *value = ENGINEERING_UNITS_DEGREES_CELSIUS };
return true;
}
// Reliability (enabled in main()). The stack also reads it through this
// callback to build Status_Flags, so once enabled it must always answer:
// if it declines, the stack silently substitutes 0 (no-fault-detected),
// and the sensor reports itself healthy forever.
if property_identifier == PROPERTY_IDENTIFIER_RELIABILITY {
unsafe { *value = device.analog_input_1_reliability };
return true;
}
}
if object_type == OBJECT_TYPE_NETWORK_PORT
&& object_instance == NETWORK_PORT_INSTANCE
&& property_identifier == PROPERTY_IDENTIFIER_BACNET_IP_MODE
{
unsafe { *value = BACNET_IP_MODE_NORMAL }; // not foreign-device, not BBMD
return true;
}
false
})
.unwrap_or(false)
}
/// UNSIGNED INTEGER - the Multi-State Input's Present_Value, and the Device's
/// Vendor_Identifier (the stack also uses Vendor_Identifier to build I-Am).
extern "C" fn get_property_unsigned_integer(
device_instance: u32,
object_type: u16,
object_instance: u32,
property_identifier: u32,
value: *mut u32,
use_array_index: bool,
property_array_index: u32,
_error_code: *mut u32,
) -> bool {
catch_unwind(|| {
let device = state();
if device_instance != device.device_instance {
return false;
}
if object_type == OBJECT_TYPE_MULTI_STATE_INPUT && object_instance == MULTI_STATE_INPUT_INSTANCE {
if property_identifier == PROPERTY_IDENTIFIER_PRESENT_VALUE {
unsafe { *value = device.multi_state_input_1_value }; // valid range is 1..Number_Of_States
return true;
}
if property_identifier == PROPERTY_IDENTIFIER_NUMBER_OF_STATES {
unsafe { *value = MULTI_STATE_INPUT_NUMBER_OF_STATES }; // required property
return true;
}
// State_Text is an array. The stack asks for its LENGTH here (array
// index 0) before reading each element via
// get_property_character_string.
if property_identifier == PROPERTY_IDENTIFIER_STATE_TEXT && use_array_index && property_array_index == 0 {
unsafe { *value = MULTI_STATE_INPUT_NUMBER_OF_STATES };
return true;
}
}
if object_type == OBJECT_TYPE_DEVICE
&& object_instance == device.device_instance
&& property_identifier == PROPERTY_IDENTIFIER_VENDOR_IDENTIFIER
{
unsafe { *value = VENDOR_IDENTIFIER };
return true;
}
if object_type == OBJECT_TYPE_NETWORK_PORT && object_instance == NETWORK_PORT_INSTANCE {
if property_identifier == PROPERTY_IDENTIFIER_APDU_LENGTH {
unsafe { *value = MAX_APDU_LENGTH };
return true;
}
if property_identifier == PROPERTY_IDENTIFIER_REFERENCE_PORT {
unsafe { *value = NETWORK_PORT_REFERENCE_PORT_NONE };
return true;
}
if property_identifier == PROPERTY_IDENTIFIER_BACNET_IP_UDP_PORT {
unsafe { *value = device.bacnet_ip_udp_port as u32 };
return true;
}
}
false
})
.unwrap_or(false)
}
/// BOOLEAN - Out_Of_Service is a required property of every input object and of
/// the Network Port. This is a read-only sensor, so nothing is ever out of
/// service: always false.
extern "C" fn get_property_bool(
device_instance: u32,
object_type: u16,
_object_instance: u32,
property_identifier: u32,
value: *mut bool,
_use_array_index: bool,
_property_array_index: u32,
_error_code: *mut u32,
) -> bool {
catch_unwind(|| {
if device_instance != state().device_instance {
return false;
}
if property_identifier == PROPERTY_IDENTIFIER_OUT_OF_SERVICE
&& (object_type == OBJECT_TYPE_ANALOG_INPUT
|| object_type == OBJECT_TYPE_BINARY_INPUT
|| object_type == OBJECT_TYPE_MULTI_STATE_INPUT
|| object_type == OBJECT_TYPE_NETWORK_PORT)
{
unsafe { *value = false };
return true;
}
false
})
.unwrap_or(false)
}
/// OCTET STRING - the Network Port's BACnet/IP addressing. The stack cannot know
/// the host's IP, so the application must supply IP_Address and IP_Subnet_Mask
/// (and IP_Default_Gateway). Each is four octets. The stack also reads
/// IP_Address (with BACnet_IP_UDP_Port) to build the port's six-octet
/// MAC_Address.
extern "C" fn get_property_octet_string(
device_instance: u32,
object_type: u16,
object_instance: u32,
property_identifier: u32,
value: *mut u8,
value_element_count: *mut u32,
max_element_count: u32,
_use_array_index: bool,
_property_array_index: u32,
_error_code: *mut u32,
) -> bool {
catch_unwind(|| {
let device = state();
if device_instance != device.device_instance
|| object_type != OBJECT_TYPE_NETWORK_PORT
|| object_instance != NETWORK_PORT_INSTANCE
|| max_element_count < 4
{
return false;
}
let source = match property_identifier {
PROPERTY_IDENTIFIER_IP_ADDRESS => device.ip_address,
PROPERTY_IDENTIFIER_IP_SUBNET_MASK => device.ip_subnet_mask,
PROPERTY_IDENTIFIER_IP_DEFAULT_GATEWAY => device.ip_default_gateway,
_ => return false,
};
unsafe {
std::ptr::copy_nonoverlapping(source.as_ptr(), value, 4);
*value_element_count = 4;
}
true
})
.unwrap_or(false)
}
/// Small helper: copy a string into the stack's character-string buffer and set
/// the element count + encoding. Returns true (so callers can `return` it).
///
/// SAFETY: `value` has room for `max_element_count` bytes and the other two
/// pointers are writable (the stack's callback contract).
unsafe fn return_character_string(
text: &str,
value: *mut c_char,
value_element_count: *mut u32,
max_element_count: u32,
encoding_type: *mut u8,
) -> bool {
let mut length = text.len();
if length > max_element_count as usize {
// Truncate SILENTLY to fit the stack's buffer. max_element_count is
// MAX_CHARACTER_STRING_SIZE (256 in this build), and our longest
// strings fit: DEVICE_DESCRIPTION with room to spare, and a
// --deviceName, which parse_device_name_arg() caps at 255 bytes - so
// this never trips here. But if the stack is built with
// STACK_OPTION_TARGET_EMBEDDED, that limit drops to 64, and a long
// Object_Name or Description would be clipped mid-word with nothing on
// the wire or console to tell you. If
// you lengthen any served string, check it against
// MAX_CHARACTER_STRING_SIZE for your target, or make this truncation
// loud.
length = max_element_count as usize;
}
std::ptr::copy_nonoverlapping(text.as_ptr(), value as *mut u8, length);
*value_element_count = length as u32;
*encoding_type = CHARACTER_STRING_ENCODING_UTF8;
true
}
/// CHARACTER STRING - Object_Name for each object, State_Text, and the Device's
/// identity strings.
extern "C" fn get_property_character_string(
device_instance: u32,
object_type: u16,
object_instance: u32,
property_identifier: u32,
value: *mut c_char,
value_element_count: *mut u32,
max_element_count: u32,
encoding_type: *mut u8,
use_array_index: bool,
property_array_index: u32,
error_code: *mut u32,
) -> bool {
catch_unwind(|| {
let device = state();
if device_instance != device.device_instance {
return false;
}
let answer = |text: &str| unsafe {
return_character_string(text, value, value_element_count, max_element_count, encoding_type)
};
// State_Text (optional) - one label per state of the Multi-State Input. It
// is a BACnet array, so the stack asks for one element at a time by index
// (1..Number_Of_States). Present_Value 1 -> "On", 2 -> "Off", 3 -> "Auto".
if object_type == OBJECT_TYPE_MULTI_STATE_INPUT
&& object_instance == MULTI_STATE_INPUT_INSTANCE
&& property_identifier == PROPERTY_IDENTIFIER_STATE_TEXT
&& use_array_index
{
const STATE_TEXT: [&str; 3] = ["On", "Off", "Auto"];
if (1..=MULTI_STATE_INPUT_NUMBER_OF_STATES).contains(&property_array_index) {
return answer(STATE_TEXT[(property_array_index - 1) as usize]);
}
// The one place in this file where naming an error is clearly right:
// the client asked for State_Text[n] and this object has no element n.
// That is not "no opinion" - it is a wrong read, and the spec has a
// code for it. (At this Stack Pin the stack also checks n against the
// length get_property_unsigned_integer serves for index 0 and answers
// invalid-array-index before it gets here; this line is what still
// answers correctly if that length and this table ever disagree -
// without it the client would silently receive an empty string.)
unsafe { *error_code = ERROR_CODE_INVALID_ARRAY_INDEX };
return false;
}
// Object_Name - the colour name for each object.
if property_identifier == PROPERTY_IDENTIFIER_OBJECT_NAME {
if object_type == OBJECT_TYPE_DEVICE && object_instance == device.device_instance {
return answer(&device.device_name);
}
if object_type == OBJECT_TYPE_ANALOG_INPUT && object_instance == ANALOG_INPUT_INSTANCE {
return answer("Bronze");
}
if object_type == OBJECT_TYPE_BINARY_INPUT && object_instance == BINARY_INPUT_INSTANCE {
return answer("Emerald");
}
if object_type == OBJECT_TYPE_MULTI_STATE_INPUT && object_instance == MULTI_STATE_INPUT_INSTANCE {
return answer("Hot Pink");
}
if object_type == OBJECT_TYPE_NETWORK_PORT && object_instance == NETWORK_PORT_INSTANCE {
return answer("Vermilion");
}
}
// The remaining strings are all on the Device object - its identity, read
// by clients and used to populate the device's I-Am / object list.
if object_type == OBJECT_TYPE_DEVICE && object_instance == device.device_instance {
match property_identifier {
PROPERTY_IDENTIFIER_DESCRIPTION => return answer(DEVICE_DESCRIPTION),
PROPERTY_IDENTIFIER_VENDOR_NAME => return answer(VENDOR_NAME),
PROPERTY_IDENTIFIER_MODEL_NAME => return answer(MODEL_NAME),
PROPERTY_IDENTIFIER_FIRMWARE_REVISION => return answer(&device.firmware_revision),
PROPERTY_IDENTIFIER_APPLICATION_SOFTWARE_VERSION => return answer(APP_VERSION),
_ => {}
}
}
false
})
.unwrap_or(false)
}
// -----------------------------------------------------------------------------
// 4. main()
// -----------------------------------------------------------------------------
/// The stack library's file name on this OS (the stack's CMake shared-library build).
fn stack_library_file_name() -> &'static str {
if cfg!(windows) {
"CASBACnetStack_x64_Release.dll"
} else if cfg!(target_os = "macos") {
"libCASBACnetStack_x64_Release.dylib"
} else {
"libCASBACnetStack_x64_Release.so"
}
}
/// Where the CAS BACnet Stack library is looked for, in order. Each entry is the
/// full path of the file to open.
/// 1. CAS_BACNET_STACK_LIBRARY_PATH, the adapter's own override, if it is set.
/// 2. The run directory: the folder that holds this executable. A release
/// ships the executable WITHOUT the library (it is a licensed product), so
/// this is where a licensed customer puts it.
/// 3. A development checkout only: submodules/cas-bacnet-stack/bin/, where the
/// submodule's build puts the library, found by walking up from the
/// executable's folder (target/release/ -> the repository root). Searched
/// only if that folder exists.
fn stack_library_candidates() -> Vec<PathBuf> {
let file_name = stack_library_file_name();
let mut candidates = Vec::new();
if let Some(path) = std::env::var_os("CAS_BACNET_STACK_LIBRARY_PATH").filter(|path| !path.is_empty()) {
candidates.push(PathBuf::from(path));
}
if let Some(run_directory) = std::env::current_exe().ok().and_then(|exe| exe.parent().map(PathBuf::from)) {
candidates.push(run_directory.join(file_name));
let checkout_bin = run_directory
.ancestors()
.map(|folder| folder.join("submodules").join("cas-bacnet-stack").join("bin"))
.find(|folder| folder.is_dir());
if let Some(folder) = checkout_bin {
candidates.push(folder.join(file_name));
}
}
candidates
}
/// Why the stack could not be loaded.
enum StackLoadError {
/// No candidate folder has the library file.
Missing { searched: Vec<PathBuf> },
/// The file is there but the operating system or the adapter refused it.
Failed { path: PathBuf, error: String },
}
/// Load the CAS BACnet Stack - the Rust edition's LoadBACnetFunctions().
///
/// The adapter opens the library at its first BACnetStack_* call, from the path
/// in CAS_BACNET_STACK_LIBRARY_PATH. So this finds the library first (above),
/// opens it here, and only then points that variable at the exact file found
/// and makes the first call. Single-threaded at this point (nothing else has
/// started), so setting a process environment variable is safe.
///
/// WORKAROUND - ADAPTER DEFECT (cas-bacnet-stack#3970, TODO.md): the adapter's
/// load_library() calls `.unwrap()` on the load, so a missing or broken library
/// PANICS inside its Lazy static on the first BACnetStack_* call, instead of
/// returning the Err that every binding's BACnetResult promises. No binding is
/// touched until the library has been found and opened here, so a missing
/// library is reported as a message, never a panic.
fn load_bacnet_functions() -> Result<(), StackLoadError> {
let candidates = stack_library_candidates();
let Some(path) = candidates.iter().find(|path| path.is_file()).cloned() else {
return Err(StackLoadError::Missing { searched: candidates });
};
let probe = unsafe { libloading::Library::new(&path) }
.map_err(|error| StackLoadError::Failed { path: path.clone(), error: error.to_string() })?;
std::env::set_var("CAS_BACNET_STACK_LIBRARY_PATH", &path);
let loaded = bacnet::BACnetStack_GetAPIMajorVersion()
.map(|_| ())
.map_err(|error| StackLoadError::Failed { path: path.clone(), error: error.to_string() });
drop(probe); // the adapter holds its own handle now
loaded
}
/// Print why the stack could not be loaded, to stderr - the series' message.
fn print_stack_load_error(error: &StackLoadError) {
match error {
StackLoadError::Missing { searched } => {
let file_name = stack_library_file_name();
let mut folders: Vec<String> = Vec::new();
for path in searched {
let folder = path.parent().map(|folder| folder.display().to_string()).unwrap_or_default();
if !folders.contains(&folder) {
folders.push(folder);
}
}
eprintln!("ERROR: This example cannot run without the CAS BACnet Stack library.");
eprintln!();
eprintln!(" Missing file: {file_name}");
eprintln!(" Looked in: {}", folders.join("\n "));
eprintln!();
eprintln!("The CAS BACnet Stack is a commercially licensed (paid) library from Chipkin.");
eprintln!("It is not included in this release, so the example cannot start without it.");
eprintln!();
eprintln!(" - To license the CAS BACnet Stack: https://store.chipkin.com/contact-us");
eprintln!(" - Licensed customers: build the library from the cas-bacnet-stack submodule");
eprintln!(" (see README.md) and place {file_name} next to this executable.");
}
StackLoadError::Failed { path, error } => {
eprintln!("ERROR: The CAS BACnet Stack library could not be loaded.");
eprintln!();
eprintln!(" File: {}", path.display());
eprintln!(" Error: {error}");
eprintln!();
eprintln!("Build it from the cas-bacnet-stack submodule (see README.md) for this");
eprintln!("operating system and architecture, and place it next to this executable.");
}
}
}
fn main() -> ExitCode {
// --- Load the CAS BACnet Stack -------------------------------------------
// Before any other BACnetStack_* call. --help and --version still work
// without it (the stack line of the banner then says it is not loaded).
let stack = load_bacnet_functions();
if stack.is_ok() {
helper::set_stack_loaded();
// Firmware_Revision (Device object property 44) - the STACK's version,
// not this example's own (that is Application_Software_Version /
// APP_VERSION). Set before the Device object is ever readable.
state().firmware_revision = helper::stack_version();
}
// --- Command line + version ----------------------------------------------
// --help / --version print and exit, so handle them before we bind a socket.
let arguments: Vec<String> = std::env::args().collect();
// The last argument lists --deviceName in --help: this example reads it.
if helper::handle_help_and_version_args_with_options(&arguments, APP_NAME, APP_VERSION, true) {
return ExitCode::SUCCESS;
}
if let Err(error) = &stack {
print_stack_load_error(error);
return ExitCode::FAILURE;
}
let port = helper::parse_port_arg(&arguments, 47808);
let device_instance = helper::parse_device_id_arg(&arguments, DEFAULT_DEVICE_INSTANCE);
let device_name = helper::parse_device_name_arg(&arguments, DEVICE_NAME);
{
let mut device = state();
device.device_instance = device_instance;
device.device_name = device_name.clone();
}
helper::print_version(APP_NAME, APP_VERSION);
// --- Bind the BACnet/IP socket -------------------------------------------
// Tell the helper which Network Port object owns the socket it binds. The
// stack identifies a link by its Network Port INSTANCE, so the transport
// callbacks (and the start-up I-Am) have to name the one added below.
helper::set_network_port_instance(NETWORK_PORT_INSTANCE);
if !helper::setup_udp(port) {
return ExitCode::FAILURE;
}
// Capture the BACnet/IP addressing the Network Port object will report.
{
let mut device = state();
device.bacnet_ip_udp_port = port;
let (mut ip_address, mut ip_subnet_mask) = ([0u8; 4], [0u8; 4]);
if !helper::get_local_ipv4(&mut ip_address, &mut ip_subnet_mask) {
println!("FYI: could not read a local IPv4 address; Network Port IP_Address will report 0.0.0.0.");
}
device.ip_address = ip_address;
device.ip_subnet_mask = ip_subnet_mask;
}
// --- Register callbacks --------------------------------------------------
// The transport + time callbacks are shared boilerplate; the property
// callbacks are specific to this example.
let registered = helper::register_common_callbacks()
&& bacnet::BACnetStack_RegisterCallbackGetPropertyReal(Some(get_property_real)).is_ok()
&& bacnet::BACnetStack_RegisterCallbackGetPropertyEnumerated(Some(get_property_enumerated)).is_ok()
&& bacnet::BACnetStack_RegisterCallbackGetPropertyUnsignedInteger(Some(get_property_unsigned_integer)).is_ok()
&& bacnet::BACnetStack_RegisterCallbackGetPropertyCharacterString(Some(get_property_character_string)).is_ok()
&& bacnet::BACnetStack_RegisterCallbackGetPropertyBool(Some(get_property_bool)).is_ok()
&& bacnet::BACnetStack_RegisterCallbackGetPropertyOctetString(Some(get_property_octet_string)).is_ok();
if !registered {
println!("Error: Failed to register the CAS BACnet Stack callbacks.");
return ExitCode::FAILURE;
}
// Every stack setup call returns a bool (here wrapped in the adapter's
// Result: Err = the symbol was not found); a real device should always check
// it, so this example does too.
let ok = |result: cas_bacnet_stack_adapters::BACnetResult<bool>| result.unwrap_or(false);
// --- Create the device ---------------------------------------------------
if !ok(bacnet::BACnetStack_AddDevice(device_instance)) {
println!("Error: Failed to add the Device {device_instance}.");
return ExitCode::FAILURE;
}
// Enable ReadProperty (DS-RP-B) - the one mandatory service for B-SS.
// We set it explicitly to make the profile requirement obvious.
//
// We deliberately do NOT enable WriteProperty, ReadPropertyMultiple,
// SubscribeCOV, or any alarm/event service: a Smart Sensor does not require
// them, so a faithful B-SS example leaves them off.
if !ok(bacnet::BACnetStack_SetServiceEnabled(device_instance, SERVICE_READ_PROPERTY, true)) {
println!("Error: Failed to enable the ReadProperty service.");
return ExitCode::FAILURE;
}
// 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;
// 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
// is what makes the claim true on the wire.
if !ok(bacnet::BACnetStack_SetServiceEnabled(device_instance, SERVICE_WHO_IS, true))
|| !ok(bacnet::BACnetStack_SetServiceEnabled(device_instance, SERVICE_I_AM, true))
|| !ok(bacnet::BACnetStack_SetServiceEnabled(device_instance, SERVICE_WHO_HAS, true))
|| !ok(bacnet::BACnetStack_SetServiceEnabled(device_instance, SERVICE_I_HAVE, true))
{
println!("Error: Failed to enable the discovery services (Who-Is/I-Am, Who-Has/I-Have).");
return ExitCode::FAILURE;
}
// --- Add the read-only sensor objects ------------------------------------
if !ok(bacnet::BACnetStack_AddObject(device_instance, OBJECT_TYPE_ANALOG_INPUT, ANALOG_INPUT_INSTANCE)) {
println!("Error: Failed to add Analog Input {ANALOG_INPUT_INSTANCE} (Bronze).");
return ExitCode::FAILURE;
}
if !ok(bacnet::BACnetStack_AddObject(device_instance, OBJECT_TYPE_BINARY_INPUT, BINARY_INPUT_INSTANCE)) {
println!("Error: Failed to add Binary Input {BINARY_INPUT_INSTANCE} (Emerald).");
return ExitCode::FAILURE;
}
if !ok(bacnet::BACnetStack_AddObject(device_instance, OBJECT_TYPE_MULTI_STATE_INPUT, MULTI_STATE_INPUT_INSTANCE)) {
println!("Error: Failed to add Multi-State Input {MULTI_STATE_INPUT_INSTANCE} (Hot Pink).");
return ExitCode::FAILURE;
}
// --- Add the Network Port object -----------------------------------------
// 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".
// 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 !ok(bacnet::BACnetStack_AddNetworkPortObject(
device_instance,
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,
)) {
println!("Error: Failed to add Network Port 1 (Vermilion).");
return ExitCode::FAILURE;
}
// --- Enable the OPTIONAL properties we choose to expose ------------------
// The stack automatically enables an object's REQUIRED properties when the
// object is added (AddObject / AddNetworkPortObject) - so Units, Polarity,
// Number_Of_States, Out_Of_Service, and the Network Port's BACnet/IP
// addressing are already enabled; our Get* callbacks just supply their
// values. Only OPTIONAL properties need SetPropertyEnabled.
//
// 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
// Description branch in the callback without this enable is DEAD CODE, and
// the client reads back Error: unknown-property.
if !ok(bacnet::BACnetStack_SetPropertyEnabled(
device_instance,
OBJECT_TYPE_DEVICE,
device_instance,
PROPERTY_IDENTIFIER_DESCRIPTION,
true,
)) {
println!("Error: Failed to enable Description on the Device object.");
return ExitCode::FAILURE;
}
// State_Text is optional on a Multi-State Input (served in
// get_property_character_string).
if !ok(bacnet::BACnetStack_SetPropertyEnabled(
device_instance,
OBJECT_TYPE_MULTI_STATE_INPUT,
MULTI_STATE_INPUT_INSTANCE,
PROPERTY_IDENTIFIER_STATE_TEXT,
true,
)) {
println!("Error: Failed to enable State_Text on Multi-State Input 1 (Hot Pink).");
return ExitCode::FAILURE;
}
// Reliability is optional on an Analog Input; it is how a sensor says its
// reading cannot be trusted. Enabling it also gives the FAULT bit of
// Status_Flags its meaning - the stack derives that bit from it.
if !ok(bacnet::BACnetStack_SetPropertyEnabled(
device_instance,
OBJECT_TYPE_ANALOG_INPUT,
ANALOG_INPUT_INSTANCE,
PROPERTY_IDENTIFIER_RELIABILITY,
true,
)) {
println!("Error: Failed to enable Reliability on Analog Input 1 (Bronze).");
return ExitCode::FAILURE;
}
// The Simulation's test-only broken-wire hook (section 2).
let sensor_fault_file =
std::env::var_os(SENSOR_FAULT_FILE_VARIABLE).filter(|value| !value.is_empty()).map(PathBuf::from);
// Who-Is is answered automatically. The spec also requires a device to
// announce itself on start-up, so broadcast an unsolicited I-Am now (to the