From 8b086da5c9ec19f8a5ce687980837fd01c62fb80 Mon Sep 17 00:00:00 2001 From: SWS-Chipkin Date: Thu, 17 Sep 2026 14:52:13 -0700 Subject: [PATCH 1/5] feat(common): sync RX/TX object/property/DADR decode + --xml from B-SS-CPP Ports the common/ 2.7.0 change verbatim (B-SS-CPP's originating commit has the full rationale): RX/TX log lines now name the object/property being requested and any NPDU routing destination, and a new --xml option (off by default) prints every frame as a full indented XML block. main.cpp gains the same one line (ParseXmlLogArg) as every other example that adopts this - all decode/XML logic stays in common/. Verified against a live rebuilt binary: a crafted ReadProperty decodes correctly, and this example's own SCHED-E-B remote-discovery Who-Is correctly showed 'DNET=65535' in its own real traffic, not just a crafted test packet. Co-Authored-By: Claude Sonnet 5 --- CHANGELOG.md | 10 + common/CASExampleHelper.cpp | 1334 ++++++++++++++++++++++++++++++++++- common/CASExampleHelper.h | 43 +- common/CHANGELOG.md | 69 ++ main.cpp | 1 + 5 files changed, 1454 insertions(+), 3 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index b6f91ef..25d92cb 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,16 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ## [Unreleased] +### Added + +- Synced `common/` to 2.7.0 (from `BACnetProfileExample-B-SS-CPP`): RX/TX log + lines now name the service, the object/property being requested, and any + NPDU routing destination (DNET/DADR) - live-verified against this + example's own SCHED-E-B remote-discovery Who-Is, which correctly showed + `DNET=65535`. A new `--xml` option (off by default) prints every frame as + a full XML block instead. See `common/CHANGELOG.md` for the decode + details. + ### Changed - Restructured documentation to match the series' shared shape: `README.md` diff --git a/common/CASExampleHelper.cpp b/common/CASExampleHelper.cpp index f0baad3..7176b45 100644 --- a/common/CASExampleHelper.cpp +++ b/common/CASExampleHelper.cpp @@ -156,9 +156,10 @@ uint16_t HelperReceiveMessage(uint8_t* message, const uint16_t maxMessageLength, return 0; // no datagram waiting on any bound port } - printf("RX %u bytes from %u.%u.%u.%u:%u (Network Port %u)\n", (unsigned)bytesRead, + printf("RX %u bytes from %u.%u.%u.%u:%u (Network Port %u)", (unsigned)bytesRead, fromIp[0], fromIp[1], fromIp[2], fromIp[3], (unsigned)fromPort, (unsigned)servicedInstance); + CASExampleHelper::LogBacnetFrame(message, bytesRead); // Fill the 6-byte BACnet/IP connection string: IP[4] + port[2] (big-endian). sourceConnectionString[0] = fromIp[0]; @@ -207,9 +208,10 @@ uint16_t HelperSendMessage(const uint8_t* message, const uint16_t messageLength, const uint16_t port = (uint16_t)((connectionString[4] << 8) | connectionString[5]); const uint16_t sent = binding->udp.Send(ip, port, message, messageLength); - printf("TX %u bytes to %u.%u.%u.%u:%u%s (Network Port %u)\n", (unsigned)sent, + printf("TX %u bytes to %u.%u.%u.%u:%u%s (Network Port %u)", (unsigned)sent, ip[0], ip[1], ip[2], ip[3], (unsigned)port, broadcast ? " (broadcast)" : "", (unsigned)networkPortInstance); + CASExampleHelper::LogBacnetFrame(message, messageLength); return sent; } @@ -359,6 +361,1331 @@ uint64_t MonotonicMilliseconds() { } // namespace +namespace { + +// ANSI/ASHRAE 135 Clause 21 confirmed-service-choice names, index = the wire +// value. Includes the two removed-but-still-numbered choices (13, 24, 25) so +// an old/malformed frame using them still gets a name instead of falling +// through to the numeric fallback. +const char* ConfirmedServiceName(uint8_t choice) { + static const char* const names[] = { + "AcknowledgeAlarm", "ConfirmedCOVNotification", "ConfirmedEventNotification", + "GetAlarmSummary", "GetEnrollmentSummary", "SubscribeCOV", "AtomicReadFile", + "AtomicWriteFile", "AddListElement", "RemoveListElement", "CreateObject", + "DeleteObject", "ReadProperty", "ReadPropertyConditional", "ReadPropertyMultiple", + "WriteProperty", "WritePropertyMultiple", "DeviceCommunicationControl", + "ConfirmedPrivateTransfer", "ConfirmedTextMessage", "ReinitializeDevice", + "VTOpen", "VTClose", "VTData", "Authenticate", "RequestKey", "ReadRange", + "LifeSafetyOperation", "SubscribeCOVProperty", "GetEventInformation", + "SubscribeCOVPropertyMultiple", "ConfirmedCOVNotificationMultiple" + }; + if (choice < sizeof(names) / sizeof(names[0])) { + return names[choice]; + } + return NULL; +} + +// Clause 21 unconfirmed-service-choice names. +const char* UnconfirmedServiceName(uint8_t choice) { + static const char* const names[] = { + "I-Am", "I-Have", "UnconfirmedCOVNotification", "UnconfirmedEventNotification", + "UnconfirmedPrivateTransfer", "UnconfirmedTextMessage", "TimeSynchronization", + "Who-Has", "Who-Is", "UTCTimeSynchronization", "WriteGroup", + "UnconfirmedCOVNotificationMultiple" + }; + if (choice < sizeof(names) / sizeof(names[0])) { + return names[choice]; + } + return NULL; +} + +const char* RejectReasonName(uint8_t reason) { + static const char* const names[] = { + "other", "buffer-overflow", "inconsistent-parameters", + "invalid-parameter-data-type", "invalid-tag", "missing-required-parameter", + "parameter-out-of-range", "too-many-arguments", "undefined-enumeration", + "unrecognized-service" + }; + if (reason < sizeof(names) / sizeof(names[0])) { + return names[reason]; + } + return NULL; +} + +const char* AbortReasonName(uint8_t reason) { + static const char* const names[] = { + "other", "buffer-overflow", "invalid-apdu-in-this-state", + "preempted-by-higher-priority-task", "segmentation-not-supported", + "security-error", "insufficient-security", "window-size-out-of-range", + "application-exceeded-reply-time", "out-of-resources", "tsm-timeout", + "apdu-too-long" + }; + if (reason < sizeof(names) / sizeof(names[0])) { + return names[reason]; + } + return NULL; +} + +// Only the handful actually seen in this series' examples (routing discovery +// and network-number discovery); everything else falls back to "type=". +const char* NetworkMessageName(uint8_t type) { + switch (type) { + case 0: return "Who-Is-Router-To-Network"; + case 1: return "I-Am-Router-To-Network"; + case 2: return "I-Could-Be-Router-To-Network"; + case 3: return "Reject-Message-To-Network"; + case 4: return "Router-Busy-To-Network"; + case 5: return "Router-Available-To-Network"; + case 6: return "Initialize-Routing-Table"; + case 7: return "Initialize-Routing-Table-Ack"; + case 18: return "What-Is-Network-Number"; + case 19: return "Network-Number-Is"; + default: return NULL; + } +} + +// --- Object type / property identifier name tables -------------------------- +// Generated from the pinned stack's own BACnetObjectType.h / +// BACnetPropertyIdentifier.h (the authoritative source for names AND values - +// see common/CHANGELOG.md 2.7.0 for the exact generation script; do not +// hand-edit individual rows, regenerate both tables together if the stack +// pin changes). Sorted ascending by id - LookUpIdName binary-searches this, +// so a hand-edit that breaks the ordering breaks every lookup after it +// silently (no runtime check). +struct IdName { + uint32_t id; + const char* name; +}; + +const IdName OBJECT_TYPE_NAMES[] = { + { 0, "Analog_Input" }, + { 1, "Analog_Output" }, + { 2, "Analog_Value" }, + { 3, "Binary_Input" }, + { 4, "Binary_Output" }, + { 5, "Binary_Value" }, + { 6, "Calendar" }, + { 7, "Command" }, + { 8, "Device" }, + { 9, "Event_Enrollment" }, + { 10, "File" }, + { 11, "Group" }, + { 12, "Loop" }, + { 13, "Multi_State_Input" }, + { 14, "Multi_State_Output" }, + { 15, "Notification_Class" }, + { 16, "Program" }, + { 17, "Schedule" }, + { 18, "Averaging" }, + { 19, "Multi_State_Value" }, + { 20, "Trend_Log" }, + { 21, "Life_Safety_Point" }, + { 22, "Life_Safety_Zone" }, + { 23, "Accumulator" }, + { 24, "Pulse_Converter" }, + { 25, "Event_Log" }, + { 26, "Global_Group" }, + { 27, "Trend_Log_Multiple" }, + { 28, "Load_Control" }, + { 29, "Structured_View" }, + { 30, "Access_Door" }, + { 31, "Timer" }, + { 32, "Access_Credential" }, + { 33, "Access_Point" }, + { 34, "Access_Rights" }, + { 35, "Access_User" }, + { 36, "Access_Zone" }, + { 37, "Credential_Data_Input" }, + { 38, "Network_Security" }, + { 39, "Bitstring_Value" }, + { 40, "Characterstring_Value" }, + { 41, "Datepattern_Value" }, + { 42, "Date_Value" }, + { 43, "Datetimepattern_Value" }, + { 44, "Datetime_Value" }, + { 45, "Integer_Value" }, + { 46, "Large_Analog_Value" }, + { 47, "Octetstring_Value" }, + { 48, "Positive_Integer_Value" }, + { 49, "Timepattern_Value" }, + { 50, "Time_Value" }, + { 51, "Notification_Forwarder" }, + { 52, "Alert_Enrollment" }, + { 53, "Channel" }, + { 54, "Lighting_Output" }, + { 55, "Binary_Lighting_Output" }, + { 56, "Network_Port" }, + { 57, "Elevator_Group" }, + { 58, "Escalator" }, + { 59, "Lift" }, + { 60, "Staging" }, + { 61, "Audit_Log" }, + { 62, "Audit_Reporter" }, + { 63, "Color" }, + { 64, "Color_Temperature" }, +}; + +const IdName PROPERTY_NAMES[] = { + { 0, "Acked_Transitions" }, + { 1, "Ack_Required" }, + { 2, "Action" }, + { 3, "Action_Text" }, + { 4, "Active_Text" }, + { 5, "Active_Vt_Sessions" }, + { 6, "Alarm_Value" }, + { 7, "Alarm_Values" }, + { 8, "All" }, + { 9, "All_Writes_Successful" }, + { 10, "Apdu_Segment_Timeout" }, + { 11, "Apdu_Timeout" }, + { 12, "Application_Software_Version" }, + { 13, "Archive" }, + { 14, "Bias" }, + { 15, "Change_Of_State_Count" }, + { 16, "Change_Of_State_Time" }, + { 17, "Notification_Class" }, + { 19, "Controlled_Variable_Reference" }, + { 20, "Controlled_Variable_Units" }, + { 21, "Controlled_Variable_Value" }, + { 22, "Cov_Increment" }, + { 23, "Date_List" }, + { 24, "Daylight_Savings_Status" }, + { 25, "Deadband" }, + { 26, "Derivative_Constant" }, + { 27, "Derivative_Constant_Units" }, + { 28, "Description" }, + { 29, "Description_Of_Halt" }, + { 30, "Device_Address_Binding" }, + { 31, "Device_Type" }, + { 32, "Effective_Period" }, + { 33, "Elapsed_Active_Time" }, + { 34, "Error_Limit" }, + { 35, "Event_Enable" }, + { 36, "Event_State" }, + { 37, "Event_Type" }, + { 38, "Exception_Schedule" }, + { 39, "Fault_Values" }, + { 40, "Feedback_Value" }, + { 41, "File_Access_Method" }, + { 42, "File_Size" }, + { 43, "File_Type" }, + { 44, "Firmware_Revision" }, + { 45, "High_Limit" }, + { 46, "Inactive_Text" }, + { 47, "In_Process" }, + { 48, "Instance_Of" }, + { 49, "Integral_Constant" }, + { 50, "Integral_Constant_Units" }, + { 51, "Issue_Confirmed_Notifications" }, + { 52, "Limit_Enable" }, + { 53, "List_Of_Group_Members" }, + { 54, "List_Of_Object_Property_References" }, + { 56, "Local_Date" }, + { 57, "Local_Time" }, + { 58, "Location" }, + { 59, "Low_Limit" }, + { 60, "Manipulated_Variable_Reference" }, + { 61, "Maximum_Output" }, + { 62, "Max_Apdu_Length_Accepted" }, + { 63, "Max_Info_Frames" }, + { 64, "Max_Manager" }, + { 65, "Max_Pres_Value" }, + { 66, "Minimum_Off_Time" }, + { 67, "Minimum_On_Time" }, + { 68, "Minimum_Output" }, + { 69, "Min_Pres_Value" }, + { 70, "Model_Name" }, + { 71, "Modification_Date" }, + { 72, "Notify_Type" }, + { 73, "Number_Of_Apdu_Retries" }, + { 74, "Number_Of_States" }, + { 75, "Object_Identifier" }, + { 76, "Object_List" }, + { 77, "Object_Name" }, + { 78, "Object_Property_Reference" }, + { 79, "Object_Type" }, + { 80, "Optional" }, + { 81, "Out_Of_Service" }, + { 82, "Output_Units" }, + { 83, "Event_Parameters" }, + { 84, "Polarity" }, + { 85, "Present_Value" }, + { 86, "Priority" }, + { 87, "Priority_Array" }, + { 88, "Priority_For_Writing" }, + { 89, "Process_Identifier" }, + { 90, "Program_Change" }, + { 91, "Program_Location" }, + { 92, "Program_State" }, + { 93, "Proportional_Constant" }, + { 94, "Proportional_Constant_Units" }, + { 96, "Protocol_Object_Types_Supported" }, + { 97, "Protocol_Services_Supported" }, + { 98, "Protocol_Version" }, + { 99, "Read_Only" }, + { 100, "Reason_For_Halt" }, + { 102, "Recipient_List" }, + { 103, "Reliability" }, + { 104, "Relinquish_Default" }, + { 105, "Required" }, + { 106, "Resolution" }, + { 107, "Segmentation_Supported" }, + { 108, "Setpoint" }, + { 109, "Setpoint_Reference" }, + { 110, "State_Text" }, + { 111, "Status_Flags" }, + { 112, "System_Status" }, + { 113, "Time_Delay" }, + { 114, "Time_Of_Active_Time_Reset" }, + { 115, "Time_Of_State_Count_Reset" }, + { 116, "Time_Synchronization_Recipients" }, + { 117, "Units" }, + { 118, "Update_Interval" }, + { 119, "Utc_Offset" }, + { 120, "Vendor_Identifier" }, + { 121, "Vendor_Name" }, + { 122, "Vt_Classes_Supported" }, + { 123, "Weekly_Schedule" }, + { 124, "Attempted_Samples" }, + { 125, "Average_Value" }, + { 126, "Buffer_Size" }, + { 127, "Client_Cov_Increment" }, + { 128, "Cov_Resubscription_Interval" }, + { 130, "Event_Time_Stamps" }, + { 131, "Log_Buffer" }, + { 132, "Log_Device_Object_Property" }, + { 133, "Enable" }, + { 134, "Log_Interval" }, + { 135, "Maximum_Value" }, + { 136, "Minimum_Value" }, + { 137, "Notification_Threshold" }, + { 139, "Protocol_Revision" }, + { 140, "Records_Since_Notification" }, + { 141, "Record_Count" }, + { 142, "Start_Time" }, + { 143, "Stop_Time" }, + { 144, "Stop_When_Full" }, + { 145, "Total_Record_Count" }, + { 146, "Valid_Samples" }, + { 147, "Window_Interval" }, + { 148, "Window_Samples" }, + { 149, "Maximum_Value_Timestamp" }, + { 150, "Minimum_Value_Timestamp" }, + { 151, "Variance_Value" }, + { 152, "Active_Cov_Subscriptions" }, + { 153, "Backup_Failure_Timeout" }, + { 154, "Configuration_Files" }, + { 155, "Database_Revision" }, + { 156, "Direct_Reading" }, + { 157, "Last_Restore_Time" }, + { 158, "Maintenance_Required" }, + { 159, "Member_Of" }, + { 160, "Mode" }, + { 161, "Operation_Expected" }, + { 162, "Setting" }, + { 163, "Silenced" }, + { 164, "Tracking_Value" }, + { 165, "Zone_Members" }, + { 166, "Life_Safety_Alarm_Values" }, + { 167, "Max_Segments_Accepted" }, + { 168, "Profile_Name" }, + { 169, "Auto_Subordinate_Discovery" }, + { 170, "Manual_Subordinate_Address_Binding" }, + { 171, "Subordinate_Address_Binding" }, + { 172, "Subordinate_Proxy_Enable" }, + { 173, "Last_Notify_Record" }, + { 174, "Schedule_Default" }, + { 175, "Accepted_Modes" }, + { 176, "Adjust_Value" }, + { 177, "Count" }, + { 178, "Count_Before_Change" }, + { 179, "Count_Change_Time" }, + { 180, "Cov_Period" }, + { 181, "Input_Reference" }, + { 182, "Limit_Monitoring_Interval" }, + { 183, "Logging_Object" }, + { 184, "Logging_Record" }, + { 185, "Prescale" }, + { 186, "Pulse_Rate" }, + { 187, "Scale" }, + { 188, "Scale_Factor" }, + { 189, "Update_Time" }, + { 190, "Value_Before_Change" }, + { 191, "Value_Set" }, + { 192, "Value_Change_Time" }, + { 193, "Align_Intervals" }, + { 195, "Interval_Offset" }, + { 196, "Last_Restart_Reason" }, + { 197, "Logging_Type" }, + { 202, "Restart_Notification_Recipients" }, + { 203, "Time_Of_Device_Restart" }, + { 204, "Time_Synchronization_Interval" }, + { 205, "Trigger" }, + { 206, "Utc_Time_Synchronization_Recipients" }, + { 207, "Node_Subtype" }, + { 208, "Node_Type" }, + { 209, "Structured_Object_List" }, + { 210, "Subordinate_Annotations" }, + { 211, "Subordinate_List" }, + { 212, "Actual_Shed_Level" }, + { 213, "Duty_Window" }, + { 214, "Expected_Shed_Level" }, + { 215, "Full_Duty_Baseline" }, + { 218, "Requested_Shed_Level" }, + { 219, "Shed_Duration" }, + { 220, "Shed_Level_Descriptions" }, + { 221, "Shed_Levels" }, + { 222, "State_Description" }, + { 226, "Door_Alarm_State" }, + { 227, "Door_Extended_Pulse_Time" }, + { 228, "Door_Members" }, + { 229, "Door_Open_Too_Long_Time" }, + { 230, "Door_Pulse_Time" }, + { 231, "Door_Status" }, + { 232, "Door_Unlock_Delay_Time" }, + { 233, "Lock_Status" }, + { 234, "Masked_Alarm_Values" }, + { 235, "Secured_Status" }, + { 244, "Absentee_Limit" }, + { 245, "Access_Alarm_Events" }, + { 246, "Access_Doors" }, + { 247, "Access_Event" }, + { 248, "Access_Event_Authentication_Factor" }, + { 249, "Access_Event_Credential" }, + { 250, "Access_Event_Time" }, + { 251, "Access_Transaction_Events" }, + { 252, "Accompaniment" }, + { 253, "Accompaniment_Time" }, + { 254, "Activation_Time" }, + { 255, "Active_Authentication_Policy" }, + { 256, "Assigned_Access_Rights" }, + { 257, "Authentication_Factors" }, + { 258, "Authentication_Policy_List" }, + { 259, "Authentication_Policy_Names" }, + { 260, "Authentication_Status" }, + { 261, "Authorization_Mode" }, + { 262, "Belongs_To" }, + { 263, "Credential_Disable" }, + { 264, "Credential_Status" }, + { 265, "Credentials" }, + { 266, "Credentials_In_Zone" }, + { 267, "Days_Remaining" }, + { 268, "Entry_Points" }, + { 269, "Exit_Points" }, + { 270, "Expiration_Time" }, + { 271, "Extended_Time_Enable" }, + { 272, "Failed_Attempt_Events" }, + { 273, "Failed_Attempts" }, + { 274, "Failed_Attempts_Time" }, + { 275, "Last_Access_Event" }, + { 276, "Last_Access_Point" }, + { 277, "Last_Credential_Added" }, + { 278, "Last_Credential_Added_Time" }, + { 279, "Last_Credential_Removed" }, + { 280, "Last_Credential_Removed_Time" }, + { 281, "Last_Use_Time" }, + { 282, "Lockout" }, + { 283, "Lockout_Relinquish_Time" }, + { 285, "Max_Failed_Attempts" }, + { 286, "Members" }, + { 287, "Muster_Point" }, + { 288, "Negative_Access_Rules" }, + { 289, "Number_Of_Authentication_Policies" }, + { 290, "Occupancy_Count" }, + { 291, "Occupancy_Count_Adjust" }, + { 292, "Occupancy_Count_Enable" }, + { 294, "Occupancy_Lower_Limit" }, + { 295, "Occupancy_Lower_Limit_Enforced" }, + { 296, "Occupancy_State" }, + { 297, "Occupancy_Upper_Limit" }, + { 298, "Occupancy_Upper_Limit_Enforced" }, + { 300, "Passback_Mode" }, + { 301, "Passback_Timeout" }, + { 302, "Positive_Access_Rules" }, + { 303, "Reason_For_Disable" }, + { 304, "Supported_Formats" }, + { 305, "Supported_Format_Classes" }, + { 306, "Threat_Authority" }, + { 307, "Threat_Level" }, + { 308, "Trace_Flag" }, + { 309, "Transaction_Notification_Class" }, + { 310, "User_External_Identifier" }, + { 311, "User_Information_Reference" }, + { 317, "User_Name" }, + { 318, "User_Type" }, + { 319, "Uses_Remaining" }, + { 320, "Zone_From" }, + { 321, "Zone_To" }, + { 322, "Access_Event_Tag" }, + { 323, "Global_Identifier" }, + { 326, "Verification_Time" }, + { 327, "Base_Device_Security_Policy" }, + { 328, "Distribution_Key_Revision" }, + { 329, "Do_Not_Hide" }, + { 330, "Key_Sets" }, + { 331, "Last_Key_Server" }, + { 332, "Network_Access_Security_Policies" }, + { 333, "Packet_Reorder_Time" }, + { 334, "Security_Pdu_Timeout" }, + { 335, "Security_Time_Window" }, + { 336, "Supported_Security_Algorithms" }, + { 338, "Backup_And_Restore_State" }, + { 339, "Backup_Preparation_Time" }, + { 340, "Restore_Completion_Time" }, + { 341, "Restore_Preparation_Time" }, + { 342, "Bit_Mask" }, + { 343, "Bit_Text" }, + { 344, "Is_Utc" }, + { 345, "Group_Members" }, + { 346, "Group_Member_Names" }, + { 347, "Member_Status_Flags" }, + { 348, "Requested_Update_Interval" }, + { 349, "Covu_Period" }, + { 350, "Covu_Recipients" }, + { 351, "Event_Message_Texts" }, + { 352, "Event_Message_Texts_Config" }, + { 353, "Event_Detection_Enable" }, + { 354, "Event_Algorithm_Inhibit" }, + { 355, "Event_Algorithm_Inhibit_Ref" }, + { 356, "Time_Delay_Normal" }, + { 357, "Reliability_Evaluation_Inhibit" }, + { 358, "Fault_Parameters" }, + { 359, "Fault_Type" }, + { 360, "Local_Forwarding_Only" }, + { 361, "Process_Identifier_Filter" }, + { 362, "Subscribed_Recipients" }, + { 363, "Port_Filter" }, + { 364, "Authorization_Exemptions" }, + { 365, "Allow_Group_Delay_Inhibit" }, + { 366, "Channel_Number" }, + { 367, "Control_Groups" }, + { 368, "Execution_Delay" }, + { 369, "Last_Priority" }, + { 370, "Write_Status" }, + { 371, "Property_List" }, + { 372, "Serial_Number" }, + { 373, "Blink_Warn_Enable" }, + { 374, "Default_Fade_Time" }, + { 375, "Default_Ramp_Rate" }, + { 376, "Default_Step_Increment" }, + { 377, "Egress_Time" }, + { 378, "In_Progress" }, + { 379, "Instantaneous_Power" }, + { 380, "Lighting_Command" }, + { 381, "Lighting_Command_Default_Priority" }, + { 382, "Max_Actual_Value" }, + { 383, "Min_Actual_Value" }, + { 384, "Power" }, + { 385, "Transition" }, + { 386, "Egress_Active" }, + { 387, "Interface_Value" }, + { 388, "Fault_High_Limit" }, + { 389, "Fault_Low_Limit" }, + { 390, "Low_Diff_Limit" }, + { 391, "Strike_Count" }, + { 392, "Time_Of_Strike_Count_Reset" }, + { 393, "Default_Timeout" }, + { 394, "Initial_Timeout" }, + { 395, "Last_State_Change" }, + { 396, "State_Change_Values" }, + { 397, "Timer_Running" }, + { 398, "Timer_State" }, + { 399, "Apdu_Length" }, + { 400, "Ip_Address" }, + { 401, "Ip_Default_Gateway" }, + { 402, "Ip_Dhcp_Enable" }, + { 403, "Ip_Dhcp_Lease_Time" }, + { 404, "Ip_Dhcp_Lease_Time_Remaining" }, + { 405, "Ip_Dhcp_Server" }, + { 406, "Ip_Dns_Server" }, + { 407, "Bacnet_Ip_Global_Address" }, + { 408, "Bacnet_Ip_Mode" }, + { 409, "Bacnet_Ip_Multicast_Address" }, + { 410, "Bacnet_Ip_Nat_Traversal" }, + { 411, "Ip_Subnet_Mask" }, + { 412, "Bacnet_Ip_Udp_Port" }, + { 413, "Bbmd_Accept_Fd_Registrations" }, + { 414, "Bbmd_Broadcast_Distribution_Table" }, + { 415, "Bbmd_Foreign_Device_Table" }, + { 416, "Changes_Pending" }, + { 417, "Command" }, + { 418, "Fd_Bbmd_Address" }, + { 419, "Fd_Subscription_Lifetime" }, + { 420, "Link_Speed" }, + { 421, "Link_Speeds" }, + { 422, "Link_Speed_Autonegotiate" }, + { 423, "Mac_Address" }, + { 424, "Network_Interface_Name" }, + { 425, "Network_Number" }, + { 426, "Network_Number_Quality" }, + { 427, "Network_Type" }, + { 428, "Routing_Table" }, + { 429, "Virtual_Mac_Address_Table" }, + { 430, "Command_Time_Array" }, + { 431, "Current_Command_Priority" }, + { 432, "Last_Command_Time" }, + { 433, "Value_Source" }, + { 434, "Value_Source_Array" }, + { 435, "Bacnet_Ipv6_Mode" }, + { 436, "Ipv6_Address" }, + { 437, "Ipv6_Prefix_Length" }, + { 438, "Bacnet_Ipv6_Udp_Port" }, + { 439, "Ipv6_Default_Gateway" }, + { 440, "Bacnet_Ipv6_Multicast_Address" }, + { 441, "Ipv6_Dns_Server" }, + { 442, "Ipv6_Auto_Addressing_Enable" }, + { 443, "Ipv6_Dhcp_Lease_Time" }, + { 444, "Ipv6_Dhcp_Lease_Time_Remaining" }, + { 445, "Ipv6_Dhcp_Server" }, + { 446, "Ipv6_Zone_Index" }, + { 447, "Assigned_Landing_Calls" }, + { 448, "Car_Assigned_Direction" }, + { 449, "Car_Door_Command" }, + { 450, "Car_Door_Status" }, + { 451, "Car_Door_Text" }, + { 452, "Car_Door_Zone" }, + { 453, "Car_Drive_Status" }, + { 454, "Car_Load" }, + { 455, "Car_Load_Units" }, + { 456, "Car_Mode" }, + { 457, "Car_Moving_Direction" }, + { 458, "Car_Position" }, + { 459, "Elevator_Group" }, + { 460, "Energy_Meter" }, + { 461, "Energy_Meter_Ref" }, + { 462, "Escalator_Mode" }, + { 463, "Fault_Signals" }, + { 464, "Floor_Text" }, + { 465, "Group_Id" }, + { 467, "Group_Mode" }, + { 468, "Higher_Deck" }, + { 469, "Installation_Id" }, + { 470, "Landing_Calls" }, + { 471, "Landing_Call_Control" }, + { 472, "Landing_Door_Status" }, + { 473, "Lower_Deck" }, + { 474, "Machine_Room_Id" }, + { 475, "Making_Car_Call" }, + { 476, "Next_Stopping_Floor" }, + { 477, "Operation_Direction" }, + { 478, "Passenger_Alarm" }, + { 479, "Power_Mode" }, + { 480, "Registered_Car_Call" }, + { 481, "Active_Cov_Multiple_Subscriptions" }, + { 482, "Protocol_Level" }, + { 483, "Reference_Port" }, + { 484, "Deployed_Profile_Location" }, + { 485, "Profile_Location" }, + { 486, "Tags" }, + { 487, "Subordinate_Node_Types" }, + { 488, "Subordinate_Tags" }, + { 489, "Subordinate_Relationships" }, + { 490, "Default_Subordinate_Relationship" }, + { 491, "Represents" }, + { 492, "Default_Present_Value" }, + { 493, "Present_Stage" }, + { 494, "Stages" }, + { 495, "Stage_Names" }, + { 496, "Target_References" }, + { 497, "Audit_Source_Reporter" }, + { 498, "Audit_Level" }, + { 499, "Audit_Notification_Recipient" }, + { 500, "Audit_Priority_Filter" }, + { 501, "Auditable_Operations" }, + { 502, "Delete_On_Forward" }, + { 503, "Maximum_Send_Delay" }, + { 504, "Monitored_Objects" }, + { 505, "Send_Now" }, + { 506, "Floor_Number" }, + { 507, "Device_Uuid" }, + { 508, "Additional_Reference_Ports" }, + { 509, "Certificate_Signing_Request_File" }, + { 510, "Command_Validation_Result" }, + { 511, "Issuer_Certificate_Files" }, + { 4194304, "Max_Bvlc_Length_Accepted" }, + { 4194305, "Max_Npdu_Length_Accepted" }, + { 4194306, "Operational_Certificate_File" }, + { 4194307, "Current_Health" }, + { 4194308, "Sc_Connect_Wait_Timeout" }, + { 4194309, "Sc_Direct_Connect_Accept_Enable" }, + { 4194310, "Sc_Direct_Connect_Accept_Uris" }, + { 4194311, "Sc_Direct_Connect_Binding" }, + { 4194312, "Sc_Direct_Connect_Connection_Status" }, + { 4194313, "Sc_Direct_Connect_Initiate_Enable" }, + { 4194314, "Sc_Disconnect_Wait_Timeout" }, + { 4194315, "Sc_Failed_Connection_Requests" }, + { 4194316, "Sc_Failover_Hub_Connection_Status" }, + { 4194317, "Sc_Failover_Hub_Uri" }, + { 4194318, "Sc_Hub_Connector_State" }, + { 4194319, "Sc_Hub_Function_Accept_Uris" }, + { 4194320, "Sc_Hub_Function_Binding" }, + { 4194321, "Sc_Hub_Function_Connection_Status" }, + { 4194322, "Sc_Hub_Function_Enable" }, + { 4194323, "Sc_Heartbeat_Timeout" }, + { 4194324, "Sc_Primary_Hub_Connection_Status" }, + { 4194325, "Sc_Primary_Hub_Uri" }, + { 4194326, "Sc_Maximum_Reconnect_Time" }, + { 4194327, "Sc_Minimum_Reconnect_Time" }, + { 4194328, "Color_Override" }, + { 4194329, "Color_Reference" }, + { 4194330, "Default_Color" }, + { 4194331, "Default_Color_Temperature" }, + { 4194332, "Override_Color_Reference" }, + { 4194333, "Write_Every_Scheduled_Action" }, + { 4194334, "Color_Command" }, + { 4194335, "High_End_Trim" }, + { 4194336, "Low_End_Trim" }, + { 4194337, "Trim_Fade_Time" }, + { 4194338, "Device_Address_Proxy_Enable" }, + { 4194339, "Device_Address_Proxy_Table" }, + { 4194340, "Device_Address_Proxy_Timeout" }, + { 4194341, "Default_On_Value" }, + { 4194342, "Last_On_Value" }, + { 4194343, "Authorization_Cache" }, + { 4194344, "Authorization_Groups" }, + { 4194345, "Authorization_Policy" }, + { 4194346, "Authorization_Scope" }, + { 4194347, "Authorization_Server" }, + { 4194348, "Authorization_Status" }, + { 4194349, "Max_Proxied_I_Ams_Per_Second" }, +}; + +const char* LookUpIdName(const IdName* table, size_t count, uint32_t id) { + size_t lo = 0; + size_t hi = count; + while (lo < hi) { + const size_t mid = lo + (hi - lo) / 2; + if (table[mid].id == id) { + return table[mid].name; + } + if (table[mid].id < id) { + lo = mid + 1; + } else { + hi = mid; + } + } + return NULL; +} + +const char* ObjectTypeName(uint16_t objectType) { + return LookUpIdName(OBJECT_TYPE_NAMES, sizeof(OBJECT_TYPE_NAMES) / sizeof(OBJECT_TYPE_NAMES[0]), objectType); +} + +const char* PropertyName(uint32_t propertyId) { + return LookUpIdName(PROPERTY_NAMES, sizeof(PROPERTY_NAMES) / sizeof(PROPERTY_NAMES[0]), propertyId); +} + +// --- Generic BACnet tag-header decode (Clause 20.2.1) ------------------------ +struct TagHeader { + uint8_t tagNumber; + bool contextSpecific; + bool isOpeningTag; // constructed-tag opening ("(" - LVT==6) + bool isClosingTag; // constructed-tag closing (")" - LVT==7) + uint32_t length; // data length for a primitive tag; 0 for opening/closing + uint32_t headerLength; // bytes the tag header itself occupied +}; + +// Decodes the tag header starting at frame[offset]. Returns false (leaves +// *out untouched) on truncation or an encoding this decoder doesn't handle - +// every caller treats that as "stop decoding, fall back to what's already +// known" rather than guessing at the rest of the frame. +bool DecodeTagHeader(const uint8_t* frame, uint32_t frameLength, uint32_t offset, TagHeader* out) { + if (offset >= frameLength) { + return false; + } + uint32_t pos = offset; + const uint8_t b0 = frame[pos]; + uint8_t tagNumber = (b0 >> 4) & 0x0F; + const bool contextSpecific = (b0 & 0x08) != 0; + const uint8_t lvt = b0 & 0x07; + pos += 1; + if (tagNumber == 0x0F) { // extended tag number + if (pos >= frameLength) { + return false; + } + tagNumber = frame[pos]; + pos += 1; + } + bool isOpening = false; + bool isClosing = false; + uint32_t length = 0; + if (contextSpecific && lvt == 6) { + isOpening = true; + } else if (contextSpecific && lvt == 7) { + isClosing = true; + } else if (lvt <= 4) { + length = lvt; + } else if (lvt == 5) { // extended length + if (pos >= frameLength) { + return false; + } + const uint8_t lenByte = frame[pos]; + pos += 1; + if (lenByte < 254) { + length = lenByte; + } else if (lenByte == 254) { + if (pos + 2 > frameLength) { + return false; + } + length = ((uint32_t)frame[pos] << 8) | frame[pos + 1]; + pos += 2; + } else { + if (pos + 4 > frameLength) { + return false; + } + length = ((uint32_t)frame[pos] << 24) | ((uint32_t)frame[pos + 1] << 16) | + ((uint32_t)frame[pos + 2] << 8) | frame[pos + 3]; + pos += 4; + } + } else { + return false; // LVT 6/7 without the context-specific bit isn't valid here + } + out->tagNumber = tagNumber; + out->contextSpecific = contextSpecific; + out->isOpeningTag = isOpening; + out->isClosingTag = isClosing; + out->length = length; + out->headerLength = pos - offset; + return true; +} + +// --- One decode pass shared by the one-line summary and the XML dump -------- +// Everything SummarizeBacnetFrame() and the XML dump print comes out of one +// DecodedFrame, built by one walk of the bytes - the two views can never +// disagree with each other about what a frame contains. +struct DecodedFrame { + bool bacnetIp; // false: not even a recognizable BVLC header + uint8_t bvlcFunction; + bool hasNpdu; // false for a BVLC control message (no NPDU/APDU) + uint8_t npduVersion; + uint8_t npduControl; + bool hasDest; + uint16_t dnet; + const uint8_t* dadr; // points into the original frame; NULL/0-length = broadcast on dnet + uint8_t dadrLength; + bool hasSrc; + uint16_t snet; + const uint8_t* sadr; + uint8_t sadrLength; + bool isNetworkMessage; + uint8_t networkMessageType; + bool hasApdu; + uint8_t pduType; // 0-7 per Clause 20.1 + bool segmented; + bool hasInvokeId; + uint8_t invokeId; + bool hasServiceChoice; + uint8_t serviceChoice; // confirmed-service-choice for 0/2/3/5; unconfirmed for 1 + bool hasReason; + uint8_t reason; // reject reason (pduType 6) or abort reason (pduType 7) + bool hasObjectProperty; + uint16_t objectType; + uint32_t objectInstance; + uint32_t propertyId; + bool hasArrayIndex; + uint32_t arrayIndex; + + DecodedFrame() + : bacnetIp(false), bvlcFunction(0), hasNpdu(false), npduVersion(0), npduControl(0), + hasDest(false), dnet(0), dadr(NULL), dadrLength(0), hasSrc(false), snet(0), sadr(NULL), + sadrLength(0), isNetworkMessage(false), networkMessageType(0), hasApdu(false), pduType(0xFF), + segmented(false), hasInvokeId(false), invokeId(0), hasServiceChoice(false), serviceChoice(0), + hasReason(false), reason(0), hasObjectProperty(false), objectType(0), objectInstance(0), + propertyId(0), hasArrayIndex(false), arrayIndex(0) {} +}; + +// Shared layout of ReadProperty-Request, ReadProperty-ACK and +// WriteProperty-Request: context tag0 = ObjectIdentifier (4-byte primitive), +// context tag1 = PropertyIdentifier (1-4 byte unsigned), optional context +// tag2 = PropertyArrayIndex (1-4 byte unsigned). Populates the +// ObjectProperty* fields on success; leaves hasObjectProperty false if the +// layout doesn't match, so callers just omit that detail rather than +// printing something wrong. +void DecodeObjectAndProperty(const uint8_t* frame, uint32_t frameLength, uint32_t offset, + DecodedFrame* out) { + TagHeader objTag; + if (!DecodeTagHeader(frame, frameLength, offset, &objTag) || !objTag.contextSpecific || + objTag.tagNumber != 0 || objTag.length != 4 || + offset + objTag.headerLength + 4 > frameLength) { + return; + } + const uint32_t objValueOffset = offset + objTag.headerLength; + const uint32_t objValue = ((uint32_t)frame[objValueOffset] << 24) | + ((uint32_t)frame[objValueOffset + 1] << 16) | + ((uint32_t)frame[objValueOffset + 2] << 8) | + frame[objValueOffset + 3]; + uint32_t pos = objValueOffset + 4; + + TagHeader propTag; + if (!DecodeTagHeader(frame, frameLength, pos, &propTag) || !propTag.contextSpecific || + propTag.tagNumber != 1 || propTag.length == 0 || propTag.length > 4 || + pos + propTag.headerLength + propTag.length > frameLength) { + return; + } + pos += propTag.headerLength; + uint32_t propValue = 0; + for (uint32_t i = 0; i < propTag.length; ++i) { + propValue = (propValue << 8) | frame[pos + i]; + } + pos += propTag.length; + + out->hasObjectProperty = true; + out->objectType = (uint16_t)((objValue >> 22) & 0x3FF); + out->objectInstance = objValue & 0x3FFFFF; + out->propertyId = propValue; + + TagHeader idxTag; + if (DecodeTagHeader(frame, frameLength, pos, &idxTag) && idxTag.contextSpecific && + idxTag.tagNumber == 2 && idxTag.length > 0 && idxTag.length <= 4 && + pos + idxTag.headerLength + idxTag.length <= frameLength) { + uint32_t v = 0; + for (uint32_t i = 0; i < idxTag.length; ++i) { + v = (v << 8) | frame[pos + idxTag.headerLength + i]; + } + out->hasArrayIndex = true; + out->arrayIndex = v; + } +} + +// Walks BVLC -> NPDU -> APDU exactly as far as needed to fill in 'out'; +// never reads past frameLength. See DecodedFrame's comment. +void DecodeBacnetFrame(const uint8_t* frame, uint32_t frameLength, DecodedFrame* out) { + *out = DecodedFrame(); + if (frame == NULL || frameLength < 4 || frame[0] != 0x81) { + return; + } + out->bacnetIp = true; + out->bvlcFunction = frame[1]; + uint32_t offset; + switch (out->bvlcFunction) { + case 0x0A: // Original-Unicast-NPDU + case 0x0B: // Original-Broadcast-NPDU + offset = 4; + break; + case 0x04: // Forwarded-NPDU: BVLC header + 6-byte originating address + offset = 10; + break; + default: + return; // a BVLC control message carries no NPDU/APDU + } + if (offset + 2u > frameLength) { + return; + } + out->hasNpdu = true; + out->npduVersion = frame[offset]; + out->npduControl = frame[offset + 1]; + offset += 2; + + out->hasDest = (out->npduControl & 0x20) != 0; + out->hasSrc = (out->npduControl & 0x08) != 0; + out->isNetworkMessage = (out->npduControl & 0x80) != 0; + + if (out->hasDest) { + if (offset + 3u > frameLength) { + return; + } + out->dnet = (uint16_t)((frame[offset] << 8) | frame[offset + 1]); + const uint8_t dlen = frame[offset + 2]; + offset += 3; + if (offset + dlen > frameLength) { + return; + } + out->dadrLength = dlen; + out->dadr = (dlen > 0) ? &frame[offset] : NULL; + offset += dlen; + } + if (out->hasSrc) { + if (offset + 3u > frameLength) { + return; + } + out->snet = (uint16_t)((frame[offset] << 8) | frame[offset + 1]); + const uint8_t slen = frame[offset + 2]; + offset += 3; + if (offset + slen > frameLength) { + return; + } + out->sadrLength = slen; + out->sadr = (slen > 0) ? &frame[offset] : NULL; + offset += slen; + } + if (out->hasDest) { + if (offset >= frameLength) { + return; + } + offset += 1; // hop count, present whenever DNET is (Clause 6.2.2) + } + if (offset >= frameLength) { + return; + } + + if (out->isNetworkMessage) { + out->networkMessageType = frame[offset]; + return; + } + + out->hasApdu = true; + out->pduType = (frame[offset] >> 4) & 0x0F; + switch (out->pduType) { + case 0: { // Confirmed-Request + out->segmented = (frame[offset] & 0x08) != 0; + if (offset + 2u >= frameLength) { + return; + } + out->hasInvokeId = true; + out->invokeId = frame[offset + 2]; + const uint32_t serviceOffset = offset + (out->segmented ? 5u : 3u); + if (serviceOffset >= frameLength) { + return; + } + out->hasServiceChoice = true; + out->serviceChoice = frame[serviceOffset]; + if (out->serviceChoice == 12 || out->serviceChoice == 15) { // ReadProperty, WriteProperty + DecodeObjectAndProperty(frame, frameLength, serviceOffset + 1, out); + } + return; + } + case 1: { // Unconfirmed-Request + if (offset + 1u >= frameLength) { + return; + } + out->hasServiceChoice = true; + out->serviceChoice = frame[offset + 1]; + return; + } + case 2: { // SimpleACK + if (offset + 2u >= frameLength) { + return; + } + out->hasInvokeId = true; + out->invokeId = frame[offset + 1]; + out->hasServiceChoice = true; + out->serviceChoice = frame[offset + 2]; + return; + } + case 3: { // ComplexACK + out->segmented = (frame[offset] & 0x08) != 0; + if (offset + 1u >= frameLength) { + return; + } + out->hasInvokeId = true; + out->invokeId = frame[offset + 1]; + const uint32_t serviceOffset = offset + (out->segmented ? 4u : 2u); + if (serviceOffset >= frameLength) { + return; + } + out->hasServiceChoice = true; + out->serviceChoice = frame[serviceOffset]; + if (out->serviceChoice == 12) { // ReadProperty-ACK + DecodeObjectAndProperty(frame, frameLength, serviceOffset + 1, out); + } + return; + } + case 4: // SegmentACK - nothing further to decode + return; + case 5: { // Error + if (offset + 2u >= frameLength) { + return; + } + out->hasInvokeId = true; + out->invokeId = frame[offset + 1]; + out->hasServiceChoice = true; + out->serviceChoice = frame[offset + 2]; + return; + } + case 6: { // Reject + if (offset + 2u >= frameLength) { + return; + } + out->hasInvokeId = true; + out->invokeId = frame[offset + 1]; + out->hasReason = true; + out->reason = frame[offset + 2]; + return; + } + case 7: { // Abort + if (offset + 2u >= frameLength) { + return; + } + out->hasInvokeId = true; + out->invokeId = frame[offset + 1]; + out->hasReason = true; + out->reason = frame[offset + 2]; + return; + } + default: + return; + } +} + +void AppendHex(char* buf, size_t bufLen, const uint8_t* data, uint8_t length) { + size_t used = strlen(buf); + for (uint8_t i = 0; i < length && used + 2 < bufLen; ++i) { + used += (size_t)snprintf(buf + used, bufLen - used, "%02X", data[i]); + } +} + +// Appends " DNET=[ DADR=]" to 'buf' (nothing if the frame carries no +// destination specifier) - the shared tail for the one-line summary. +void AppendRouteSuffix(char* buf, size_t bufLen, const DecodedFrame& d) { + if (!d.hasDest) { + return; + } + size_t used = strlen(buf); + snprintf(buf + used, bufLen - used, " DNET=%u", (unsigned)d.dnet); + if (d.dadrLength > 0 && d.dadr != NULL) { + used = strlen(buf); + snprintf(buf + used, bufLen - used, " DADR="); + AppendHex(buf, bufLen, d.dadr, d.dadrLength); + } +} + +} // namespace + +void CASExampleHelper::SummarizeBacnetFrame(const uint8_t* frame, uint16_t frameLength, + char* outSummary, size_t outSummaryLength) { + if (outSummary == NULL || outSummaryLength == 0) { + return; + } + outSummary[0] = '\0'; + + DecodedFrame d; + DecodeBacnetFrame(frame, frameLength, &d); + if (!d.bacnetIp) { + snprintf(outSummary, outSummaryLength, "?"); + return; + } + if (!d.hasNpdu) { + snprintf(outSummary, outSummaryLength, "BVLC function=0x%02X", (unsigned)d.bvlcFunction); + return; + } + if (d.isNetworkMessage) { + const char* name = NetworkMessageName(d.networkMessageType); + if (name != NULL) snprintf(outSummary, outSummaryLength, "Network-Layer-Message: %s", name); + else snprintf(outSummary, outSummaryLength, "Network-Layer-Message: type=%u", (unsigned)d.networkMessageType); + AppendRouteSuffix(outSummary, outSummaryLength, d); + return; + } + if (!d.hasApdu) { + snprintf(outSummary, outSummaryLength, "?"); + return; + } + + char body[128]; + body[0] = '\0'; + switch (d.pduType) { + case 0: { + const char* name = d.hasServiceChoice ? ConfirmedServiceName(d.serviceChoice) : NULL; + if (!d.hasServiceChoice) snprintf(body, sizeof(body), "ConfirmedRequest"); + else if (name != NULL) snprintf(body, sizeof(body), "ConfirmedRequest: %s", name); + else snprintf(body, sizeof(body), "ConfirmedRequest: service=%u", (unsigned)d.serviceChoice); + break; + } + case 1: { + const char* name = d.hasServiceChoice ? UnconfirmedServiceName(d.serviceChoice) : NULL; + if (!d.hasServiceChoice) snprintf(body, sizeof(body), "Unconfirmed"); + else if (name != NULL) snprintf(body, sizeof(body), "Unconfirmed: %s", name); + else snprintf(body, sizeof(body), "Unconfirmed: service=%u", (unsigned)d.serviceChoice); + break; + } + case 2: { + const char* name = d.hasServiceChoice ? ConfirmedServiceName(d.serviceChoice) : NULL; + if (!d.hasServiceChoice) snprintf(body, sizeof(body), "SimpleACK"); + else if (name != NULL) snprintf(body, sizeof(body), "SimpleACK: %s", name); + else snprintf(body, sizeof(body), "SimpleACK: service=%u", (unsigned)d.serviceChoice); + break; + } + case 3: { + const char* name = d.hasServiceChoice ? ConfirmedServiceName(d.serviceChoice) : NULL; + if (!d.hasServiceChoice) snprintf(body, sizeof(body), "ComplexACK"); + else if (name != NULL) snprintf(body, sizeof(body), "ComplexACK: %s", name); + else snprintf(body, sizeof(body), "ComplexACK: service=%u", (unsigned)d.serviceChoice); + break; + } + case 4: + snprintf(body, sizeof(body), "SegmentACK"); + break; + case 5: { + const char* name = d.hasServiceChoice ? ConfirmedServiceName(d.serviceChoice) : NULL; + if (!d.hasServiceChoice) snprintf(body, sizeof(body), "Error"); + else if (name != NULL) snprintf(body, sizeof(body), "Error: %s", name); + else snprintf(body, sizeof(body), "Error: service=%u", (unsigned)d.serviceChoice); + break; + } + case 6: { + const char* name = d.hasReason ? RejectReasonName(d.reason) : NULL; + if (!d.hasReason) snprintf(body, sizeof(body), "Reject"); + else if (name != NULL) snprintf(body, sizeof(body), "Reject: %s", name); + else snprintf(body, sizeof(body), "Reject: reason=%u", (unsigned)d.reason); + break; + } + case 7: { + const char* name = d.hasReason ? AbortReasonName(d.reason) : NULL; + if (!d.hasReason) snprintf(body, sizeof(body), "Abort"); + else if (name != NULL) snprintf(body, sizeof(body), "Abort: %s", name); + else snprintf(body, sizeof(body), "Abort: reason=%u", (unsigned)d.reason); + break; + } + default: + snprintf(body, sizeof(body), "?"); + break; + } + + if (d.hasObjectProperty) { + const char* typeName = ObjectTypeName(d.objectType); + const char* propName = PropertyName(d.propertyId); + const size_t used = strlen(body); + if (d.hasArrayIndex) { + if (typeName != NULL && propName != NULL) { + snprintf(body + used, sizeof(body) - used, " %s %u.%s[%u]", + typeName, (unsigned)d.objectInstance, propName, (unsigned)d.arrayIndex); + } else { + snprintf(body + used, sizeof(body) - used, " object-type=%u %u.property=%u[%u]", + (unsigned)d.objectType, (unsigned)d.objectInstance, + (unsigned)d.propertyId, (unsigned)d.arrayIndex); + } + } else { + if (typeName != NULL && propName != NULL) { + snprintf(body + used, sizeof(body) - used, " %s %u.%s", + typeName, (unsigned)d.objectInstance, propName); + } else { + snprintf(body + used, sizeof(body) - used, " object-type=%u %u.property=%u", + (unsigned)d.objectType, (unsigned)d.objectInstance, (unsigned)d.propertyId); + } + } + } + + snprintf(outSummary, outSummaryLength, "%s", body); + AppendRouteSuffix(outSummary, outSummaryLength, d); +} + +// --- XML frame dump (off by default; ParseXmlLogArg turns it on) ----------- +namespace { +bool g_xmlFrameLoggingEnabled = false; +} + +void CASExampleHelper::ParseXmlLogArg(int argc, char** argv) { + for (int i = 1; i < argc; ++i) { + if (strcmp(argv[i], "--xmlLog") == 0 || strcmp(argv[i], "--xml") == 0) { + g_xmlFrameLoggingEnabled = true; + return; + } + } +} + +bool CASExampleHelper::IsXmlFrameLoggingEnabled() { + return g_xmlFrameLoggingEnabled; +} + +namespace { + +// Prints one indented XML block describing 'frame' to stdout (no leading/ +// trailing blank line management beyond what's shown - the caller has +// already printed the "RX/TX bytes ..." prefix with no newline). Very +// verbose by design - this is the deep-debug path, off by default. Always +// includes the full raw hex regardless of how much of the structured decode +// above succeeded, so nothing is ever silently lost (segmented PDUs, a +// service other than ReadProperty/WriteProperty, or the actual property +// VALUE bytes - none of which this decoder parses - are still fully present +// in RawHex for manual inspection). +void PrintFrameAsXml(const uint8_t* frame, uint32_t frameLength) { + DecodedFrame d; + DecodeBacnetFrame(frame, frameLength, &d); + + printf("\n \n", (unsigned)frameLength); + if (!d.bacnetIp) { + printf(" not a recognizable BACnet/IP (BVLC) frame\n \n"); + return; + } + printf(" \n", (unsigned)d.bvlcFunction); + if (d.hasNpdu) { + printf(" \n", (unsigned)d.npduVersion, (unsigned)d.npduControl); + if (d.hasDest) { + printf(" 0 && d.dadr != NULL) { + printf(" mac=\""); + for (uint8_t i = 0; i < d.dadrLength; ++i) { + printf("%02X", d.dadr[i]); + } + printf("\""); + } + printf("/>\n"); + } + if (d.hasSrc) { + printf(" 0 && d.sadr != NULL) { + printf(" mac=\""); + for (uint8_t i = 0; i < d.sadrLength; ++i) { + printf("%02X", d.sadr[i]); + } + printf("\""); + } + printf("/>\n"); + } + if (d.isNetworkMessage) { + const char* name = NetworkMessageName(d.networkMessageType); + if (name != NULL) printf(" \n", (unsigned)d.networkMessageType, name); + else printf(" \n", (unsigned)d.networkMessageType); + } else if (d.hasApdu) { + static const char* const PDU_TYPE_NAMES[] = { + "ConfirmedRequest", "UnconfirmedRequest", "SimpleACK", "ComplexACK", + "SegmentACK", "Error", "Reject", "Abort" + }; + const char* pduTypeName = (d.pduType < 8) ? PDU_TYPE_NAMES[d.pduType] : "Unknown"; + printf(" \n"); + } else { + printf(">\n"); + const char* typeName = ObjectTypeName(d.objectType); + if (typeName != NULL) printf(" \n", + (unsigned)d.objectType, typeName, (unsigned)d.objectInstance); + else printf(" \n", + (unsigned)d.objectType, (unsigned)d.objectInstance); + const char* propName = PropertyName(d.propertyId); + if (propName != NULL) printf(" \n", (unsigned)d.propertyId, propName); + else printf(" \n", (unsigned)d.propertyId); + if (d.hasArrayIndex) { + printf(" \n", (unsigned)d.arrayIndex); + } + printf(" \n"); + } + } + printf(" \n"); + } + printf(" "); + for (uint32_t i = 0; i < frameLength; ++i) { + printf("%02X", frame[i]); + } + printf("\n \n"); +} + +} // namespace + +void CASExampleHelper::LogBacnetFrame(const uint8_t* frame, uint16_t frameLength) { + if (g_xmlFrameLoggingEnabled) { + PrintFrameAsXml(frame, frameLength); + return; + } + char summary[192]; + SummarizeBacnetFrame(frame, frameLength, summary, sizeof(summary)); + printf(" - %s\n", summary); +} + + namespace CASExampleHelper { void RequestRestart(const RestartKind kind, const uint32_t delayMilliseconds) { @@ -435,6 +1762,9 @@ bool HandleHelpAndVersionArgs(const int argc, char** argv, const char* appName, printf(" --port BACnet/IP UDP port (1..65535). Default 47808 (0xBAC0).\n"); printf(" Use a non-default port to avoid clashing with another\n"); printf(" BACnet device already on 47808 on this host.\n"); + printf(" --xml Print every RX/TX BACnet message as an indented XML\n"); + printf(" block instead of a one-line summary. Off by default -\n"); + printf(" very verbose, meant for deep protocol debugging.\n"); printf("\n"); PrintInteractiveCommands(); // version banner already printed above return true; diff --git a/common/CASExampleHelper.h b/common/CASExampleHelper.h index 546f375..1b20e2a 100644 --- a/common/CASExampleHelper.h +++ b/common/CASExampleHelper.h @@ -32,6 +32,7 @@ // ============================================================================= #include +#include namespace CASExampleHelper { @@ -40,7 +41,7 @@ namespace CASExampleHelper { // version). Bump it whenever anything in common/ changes, and record the // change in common/CHANGELOG.md - every example in the series must then be // re-synced to the same common/ version. -static const char* COMMON_VERSION = "2.5.0"; +static const char* COMMON_VERSION = "2.7.0"; // Print the example's name + version, the linked CAS BACnet Stack version, // and the common/ helper version. @@ -197,6 +198,46 @@ void RequestRestart(RestartKind kind, uint32_t delayMilliseconds); // a second one on the next tick. bool RestartDue(RestartKind* outKind); +// --- Diagnostics ------------------------------------------------------------- +// Everything here is wired up automatically by the transport callbacks in +// CASExampleHelper.cpp - no example's main.cpp ever needs to call any of +// these directly. They exist in the header only so ParseXmlLogArg can be +// called once from main() at startup (the same pattern as ParsePortArg / +// ParseDeviceIdArg), and so SummarizeBacnetFrame is available if an example +// ever wants the one-line summary for something other than the RX/TX log. + +// Detects "--xml" / "--xmlLog" on the command line and turns on XML frame +// logging (see LogBacnetFrame) for the life of the process. Off by default - +// call this once in main(), alongside ParsePortArg/ParseDeviceIdArg: +// +// CASExampleHelper::ParseXmlLogArg(argc, argv); +void ParseXmlLogArg(int argc, char** argv); +bool IsXmlFrameLoggingEnabled(); + +// Decode just enough of a raw BACnet/IP datagram (the exact bytes handed to the +// transport callbacks - BVLC header + NPDU + APDU, as sent on the wire) to +// produce a short human-readable summary, e.g. "Unconfirmed: Who-Is", +// "ConfirmedRequest: ReadProperty Device 389001.Object_Name", "Reject: +// unrecognized-service". Falls back to "service=" / "property=" +// (matching the stack's own log wording) for anything not in the lookup +// tables, and to a short structural label ("Network-Layer-Message: ...", +// "BVLC function=0x..") for non-APDU frames. A trailing " DNET= +// [DADR=]" is appended whenever the NPDU carries a destination +// specifier (i.e. this is a routed frame). Never reads past frameLength or +// writes past outSummaryLength - a truncated or malformed frame degrades to +// "?" rather than being mis-parsed. +void SummarizeBacnetFrame(const uint8_t* frame, uint16_t frameLength, + char* outSummary, size_t outSummaryLength); + +// Prints the trailing part of an RX/TX log line for 'frame' (frameLength +// bytes), ending in a newline: either " - ", or, +// when XML frame logging is enabled, a full indented XML block instead (see +// ParseXmlLogArg). Called automatically by the transport callbacks after +// they print the leading "RX/TX bytes ... (Network Port N)" text (no +// trailing newline on that part) - this is what makes the XML option "off by +// default, and invisible to every example's main.cpp" at the same time. +void LogBacnetFrame(const uint8_t* frame, uint16_t frameLength); + // --- Keyboard input (common to every example) ------------------------------ enum class KeyCommand { None, // nothing pressed diff --git a/common/CHANGELOG.md b/common/CHANGELOG.md index bb76c17..95b595b 100644 --- a/common/CHANGELOG.md +++ b/common/CHANGELOG.md @@ -12,6 +12,75 @@ entry here, and must then be re-copied into **every** example in the series. The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/), and the folder adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). +## [2.7.0] - 2026-09-17 + +### Added + +- **RX/TX log lines now name the object/property being requested, and any + NPDU routing destination**, e.g.: + `RX 17 bytes from ... (Network Port 1) - ConfirmedRequest: ReadProperty Device 389001.Device_Address_Binding` + `RX 18 bytes from ... (Network Port 1) - ConfirmedRequest: ReadProperty Analog_Input 1.Present_Value DNET=1234 DADR=0A0B0C` + `SummarizeBacnetFrame()` decodes the shared ObjectIdentifier(tag0) + + PropertyIdentifier(tag1) + optional PropertyArrayIndex(tag2) layout common + to ReadProperty-Request, ReadProperty-ACK and WriteProperty-Request, using + two new lookup tables (`ObjectTypeName()`, `PropertyName()` - 65 object + types, 522 properties, generated from the pinned stack's own + `BACnetObjectType.h`/`BACnetPropertyIdentifier.h`, so the names are exactly + what this stack build uses, not hand-transcribed from the spec). Falls back + to `object-type= .property=` for anything outside the + tables. A trailing ` DNET=[ DADR=]` is appended whenever the NPDU + carries a destination specifier, regardless of PDU type. + Other confirmed services (ReadPropertyMultiple, WritePropertyMultiple, ...) + are intentionally NOT decoded this deeply - their nested + read-access-specification/property-reference structure reuses the same + tag numbers at a different nesting level, which this generic tag-walker + doesn't disambiguate. Those still print with just the service name, same + as before. +- **New `--xml` / `--xmlLog` command-line option (off by default).** When + set, every RX/TX frame prints as a full indented XML block (BVLC function, + NPDU version/control/routing, APDU type/invoke-id/service/object/property, + and always the complete raw hex of the frame as a fallback) instead of the + one-line summary - for deep protocol debugging sessions where the one-line + summary isn't enough. `CASExampleHelper::ParseXmlLogArg(argc, argv)` is the + only thing an example's `main()` needs to call (same pattern as + `ParsePortArg`/`ParseDeviceIdArg`); everything else - the flag itself, the + decode, the XML rendering - lives entirely in `common/`, invisible to + `main.cpp`. +- New shared internals backing both of the above: a generic BACnet tag-header + decoder (`DecodeTagHeader`, handles extended tag numbers and all four + length/value/type encodings including the 1/2/4-byte extended-length + escapes) and one `DecodeBacnetFrame()` parse pass that both + `SummarizeBacnetFrame()` and the new XML dump build their output from - the + two views can never disagree about what a frame contains, because they're + reading the same `DecodedFrame` struct. +- Both the object/property table generation and the on-disk lookup tables are + regenerable if the stack pin changes: `python3 -c "..."` extracts every + `name = value,` line from `BACnetObjectType.h`/`BACnetPropertyIdentifier.h`, + converts camelCase to `Title_Case`, sorts by value, and emits `{ id, "name" },` + rows - see this entry's originating commit for the exact script. + +## [2.6.0] - 2026-09-17 + +### Added + +- **RX/TX log lines now decode and print the BACnet service**, e.g. + `RX 21 bytes from ... (Network Port 1) - Unconfirmed: I-Am` or + `RX 17 bytes from ... (Network Port 1) - ConfirmedRequest: ReadProperty`, + instead of stopping at the byte count and Network Port. New + `CASExampleHelper::SummarizeBacnetFrame()` walks the raw BVLC + NPDU + APDU + bytes handed to the transport callbacks (the exact wire bytes - the stack + decodes them again itself; this is a read-only, best-effort peek purely for + the console log) far enough to name the PDU type (ConfirmedRequest / + Unconfirmed / SimpleACK / ComplexACK / SegmentACK / Error / Reject / Abort / + a network-layer message) and, where applicable, the Clause 21 + confirmed/unconfirmed service choice or reject/abort reason - falling back + to `service=` / `reason=` (matching the stack's own log wording) for + anything outside the lookup tables, and to `?` for a truncated/malformed + frame rather than misreading it. Handles the DNET/SNET/hop-count routing + fields in the NPDU so this doesn't mis-decode a routed frame. + First landed in `BACnetProfileExample-B-SS-CPP`; every sibling example + re-syncs to this `common/` version to pick it up. + ## [2.5.0] - 2026-09-15 ### Added diff --git a/main.cpp b/main.cpp index 8b4db40..dd4467c 100644 --- a/main.cpp +++ b/main.cpp @@ -1456,6 +1456,7 @@ int main(int argc, char** argv) { } const uint16_t port = CASExampleHelper::ParsePortArg(argc, argv, 47808); g_deviceInstance = CASExampleHelper::ParseDeviceIdArg(argc, argv, g_deviceInstance); + CASExampleHelper::ParseXmlLogArg(argc, argv); // --xml: dump every RX/TX frame as XML instead of one line (off by default) CASExampleHelper::PrintVersion(APP_NAME, APP_VERSION); // --- Bind the BACnet/IP socket ----------------------------------------- From 5d582618c960cbb44653596718e9c9be7ba5e68d Mon Sep 17 00:00:00 2001 From: SWS-Chipkin Date: Thu, 17 Sep 2026 15:17:12 -0700 Subject: [PATCH 2/5] chore: update CAS BACnet Stack submodule pin to latest 6.x (abd4cee1 -> 986c48a6) Public C API header (source/CASBACnetStackDLL.h) is unchanged between these two commits - no adapter/example code changes needed. Rebuilt from source (the documented default build path; removed a stale prebuilt STATIC .lib left over from earlier in this session so the build picked SOURCE mode again, matching README.md's documented two-command build). Verified: builds clean, 0 errors; smoke test confirms the device still starts and answers correctly (Device 389005 "Rainbow" ready). Co-Authored-By: Claude Sonnet 5 --- submodules/cas-bacnet-stack | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/submodules/cas-bacnet-stack b/submodules/cas-bacnet-stack index abd4cee..986c48a 160000 --- a/submodules/cas-bacnet-stack +++ b/submodules/cas-bacnet-stack @@ -1 +1 @@ -Subproject commit abd4cee1c7f28ca8e1af4720849c4081082bbe82 +Subproject commit 986c48a6d3bccb60f0524d9cbd13d9c3fb079bff From 5f61f9a4510d8cd6ca196a526751a33fa3e65b1d Mon Sep 17 00:00:00 2001 From: SWS-Chipkin Date: Thu, 17 Sep 2026 17:29:20 -0700 Subject: [PATCH 3/5] fix: Description abort, missing Local_Date/Local_Time, stale Protocol_Revision docs Three findings from chipkin/BACnetProfileExample-B-BC-CPP#7 (BACnet Explorer discovery against a live instance): - DEVICE_DESCRIPTION was 286 chars, over the stack's 256-char buffer on a full build - contrary to the truncation guard's own comment claiming it fit with room to spare, the over-length read Aborted outright instead of truncating. Shortened to 214 chars, fixed the comment, made the guard warn loudly instead of clipping silently if this ever happens again. This was also the actual trigger behind ReadPropertyMultiple(ALL) aborting the whole Device read (chipkin/cas-bacnet-stack#2175) - verified live: RPM(ALL) on the Device object now returns a full 619-byte ComplexACK instead of an Abort, even before that stack-side fix lands. - Device.Local_Date/Local_Time read back read-access-denied - undocumented as a defect (the stack deliberately never invents a default for either), but this example claims DM-TS-B/DM-UTC-B and never actually served them, which is exactly what a client reads to confirm a time sync took. GetPropertyDate/GetPropertyTime now answer both with real wall-clock local time. New PROPERTY_IDENTIFIER_LOCAL_DATE/_LOCAL_TIME constants in common/ (2.7.0 -> 2.8.0). - README.md/docs/PICS.md said Protocol_Revision 24; the running device reports 26 (the stack computes this itself) - docs-only correction, plus refreshed the stale stack-commit/common-version banner. Verified against a live rebuilt binary: Description, Local_Date and Local_Time all now return ComplexACK (not Abort/Error), and a full ReadPropertyMultiple(ALL) on the Device object succeeds end to end. Co-Authored-By: Claude Sonnet 5 --- CHANGELOG.md | 33 ++++++++++ README.md | 6 +- common/CASBACnetStackExampleConstants.h | 2 + common/CASExampleHelper.h | 2 +- common/CHANGELOG.md | 12 ++++ docs/PICS.md | 2 +- main.cpp | 83 +++++++++++++++++++++---- 7 files changed, 123 insertions(+), 17 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 25d92cb..8cbe49f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,39 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ## [Unreleased] +### Fixed + +- **Reading the Device's `Description` aborted the connection instead of + returning the string.** `DEVICE_DESCRIPTION` was 286 characters, over the + stack's 256-character buffer on a full build - and, contrary to the + truncation guard's own (wrong) comment claiming this string "fits with + room to spare," the over-length read Aborted outright rather than being + truncated. Shortened to 214 characters (well under the limit, with real + margin) and corrected the guard's comment; it now also warns loudly if a + served string is ever too long again, instead of silently clipping it. + This was also the actual trigger for `ReadPropertyMultiple(ALL)` aborting + the entire Device read (see chipkin/cas-bacnet-stack#2175) - fixing it + here makes RPM(ALL) on the Device object succeed even before that stack + issue lands. (chipkin/BACnetProfileExample-B-BC-CPP#7) +- **The Device's `Local_Date`/`Local_Time` read back `Error: + read-access-denied`**, even though this example claims DM-TS-B/DM-UTC-B - + these two properties are exactly what a client reads to confirm a time + sync took. The stack deliberately refuses to invent a default for either + (documented in `main.cpp`'s "WHAT false-WITHOUT-AN-ERROR-CODE ACTUALLY + DOES" comment) - the app has to actually serve them. `GetPropertyDate`/ + `GetPropertyTime` now answer the Device object with the real wall-clock + local date/time, the same clock `HelperGetSystemTime()` already uses. + New `PROPERTY_IDENTIFIER_LOCAL_DATE`/`_LOCAL_TIME` constants in `common/` + 2.8.0. (chipkin/BACnetProfileExample-B-BC-CPP#7) + +### Changed + +- `README.md`/`docs/PICS.md` said `Protocol_Revision 24`; the running device + (against the currently pinned stack) reports 26 - the stack computes this + value itself, so this was a docs-only correction, not a code change. + Updated the "Versions" banner to the current stack commit (`986c48a6`) and + `common/` version (2.8.0) too. (chipkin/BACnetProfileExample-B-BC-CPP#7) + ### Added - Synced `common/` to 2.7.0 (from `BACnetProfileExample-B-SS-CPP`): RX/TX log diff --git a/README.md b/README.md index 2cfe35a..133cbb3 100644 --- a/README.md +++ b/README.md @@ -19,8 +19,8 @@ and ReadRange). It listens on **BACnet/IP (UDP 47808)** and claims only B-BC. Statement: every object, every property, and who answers it. > **Versions:** this document describes **example v1.0.0**, built and verified -> against **CAS BACnet Stack 6.0.21** (`6.x` @ `abd4cee1`), at -> **Protocol_Revision 24**, with the vendored `common/` helper at **v2.5.0**. +> against **CAS BACnet Stack 6.0.21** (`6.x` @ `986c48a6`), at +> **Protocol_Revision 26**, with the vendored `common/` helper at **v2.8.0**. > Running the example prints all three - if what it prints disagrees with this > line, trust the program and check `CHANGELOG.md`. @@ -274,7 +274,7 @@ or any BACnet client: 2. **Object model** - fifteen objects incl. Analog Value "Diamond", Notification Class "Crimson", Schedule "Saffron", Calendar "Cream", File "Ivory", Trend Log "Lilac" and Trend Log Multiple "Magenta". `Object_List` lists them all; - `Protocol_Revision` = 24. *Verified live.* + `Protocol_Revision` = 26. *Verified live.* 3. **Command an output (F-OUTPUTS)** - WriteProperty Analog Output 1 (Chartreuse) `Present_Value` at a priority; read it back. *Verified live.* 4. **Fire an alarm** - WriteProperty Diamond `Present_Value` = `95`; read diff --git a/common/CASBACnetStackExampleConstants.h b/common/CASBACnetStackExampleConstants.h index cc22c9c..4a2ea55 100644 --- a/common/CASBACnetStackExampleConstants.h +++ b/common/CASBACnetStackExampleConstants.h @@ -38,6 +38,8 @@ static const uint32_t PROPERTY_IDENTIFIER_APPLICATION_SOFTWARE_VERSION = 12; static const uint32_t PROPERTY_IDENTIFIER_APDU_LENGTH = 399; static const uint32_t PROPERTY_IDENTIFIER_DESCRIPTION = 28; static const uint32_t PROPERTY_IDENTIFIER_FIRMWARE_REVISION = 44; +static const uint32_t PROPERTY_IDENTIFIER_LOCAL_DATE = 56; +static const uint32_t PROPERTY_IDENTIFIER_LOCAL_TIME = 57; static const uint32_t PROPERTY_IDENTIFIER_LOCATION = 58; static const uint32_t PROPERTY_IDENTIFIER_MODEL_NAME = 70; static const uint32_t PROPERTY_IDENTIFIER_IP_ADDRESS = 400; diff --git a/common/CASExampleHelper.h b/common/CASExampleHelper.h index 1b20e2a..7e68503 100644 --- a/common/CASExampleHelper.h +++ b/common/CASExampleHelper.h @@ -41,7 +41,7 @@ namespace CASExampleHelper { // version). Bump it whenever anything in common/ changes, and record the // change in common/CHANGELOG.md - every example in the series must then be // re-synced to the same common/ version. -static const char* COMMON_VERSION = "2.7.0"; +static const char* COMMON_VERSION = "2.8.0"; // Print the example's name + version, the linked CAS BACnet Stack version, // and the common/ helper version. diff --git a/common/CHANGELOG.md b/common/CHANGELOG.md index 95b595b..2ba3ec8 100644 --- a/common/CHANGELOG.md +++ b/common/CHANGELOG.md @@ -12,6 +12,18 @@ entry here, and must then be re-copied into **every** example in the series. The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/), and the folder adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). +## [2.8.0] - 2026-09-17 + +### Added + +- `PROPERTY_IDENTIFIER_LOCAL_DATE = 56` and `PROPERTY_IDENTIFIER_LOCAL_TIME = 57` + in `CASBACnetStackExampleConstants.h`. First consumer: + `BACnetProfileExample-B-BC-CPP` (chipkin/BACnetProfileExample-B-BC-CPP#7) - + a device claiming DM-TS-B/DM-UTC-B needs to actually serve the Device's + `Local_Date`/`Local_Time` (the properties a client reads back to confirm a + time sync took), not leave the stack's "callback declined, no default" + `read-access-denied` fallback in place. + ## [2.7.0] - 2026-09-17 ### Added diff --git a/docs/PICS.md b/docs/PICS.md index 54f9424..0617a9b 100644 --- a/docs/PICS.md +++ b/docs/PICS.md @@ -23,7 +23,7 @@ see [README.md](../README.md). | **Application Software Version** | 1.0.0 | | **Firmware Revision** | 1.0.0 | | **BACnet Protocol Version** | 1 | -| **BACnet Protocol Revision** | 24 | +| **BACnet Protocol Revision** | 26 | **Product Description:** a BACnet/IP Building Controller built on the CAS BACnet Stack. It presents fifteen objects spanning read-only sensors, diff --git a/main.cpp b/main.cpp index dd4467c..3940075 100644 --- a/main.cpp +++ b/main.cpp @@ -155,11 +155,18 @@ static const char* DEVICE_NAME = "Rainbow"; // The Device object's Description. Change it to what YOUR device actually is; // this string describes this tutorial. +// Kept well under 256 chars (STACK_OPTION_MAX_CHARACTER_STRING_SIZE on a full +// build) - see the ReturnCharacterString() comment below for why "truncate to +// fit" is NOT a safe fallback for this string: reading a Description longer +// than the stack's limit aborts the whole read rather than returning a +// shortened string (chipkin/BACnetProfileExample-B-BC-CPP#7). If you lengthen +// this, check the new length against that limit for real, on the target you +// actually build for. static const char* DEVICE_DESCRIPTION = - "Chipkin CAS BACnet Stack example - B-BC (Building Controller) profile, the " - "series capstone. Demonstrates DS-RP/RPM/WP/WPM-A/B, intrinsic alarming " - "(AE-N-I-B / AE-ACK-B / AE-INFO-B / AE-CRL-B), SCHED-E-B, trending " - "(T-VMT-I-B / T-ATR-B), DM-DCC-B, DM-TS-B / DM-UTC-B, DM-RD-B, and DM-BR-B."; + "Chipkin CAS BACnet Stack example - B-BC (Building Controller) profile, " + "the series capstone. Demonstrates DS-RP/RPM/WP/WPM-A/B, intrinsic " + "alarming, SCHED-E-B, trending, DM-DCC-B, DM-TS-B/UTC-B, DM-RD-B, and " + "DM-BR-B."; // Device identity strings (read by clients, and used to populate I-Am). // VENDOR_NAME - your company name; it must match VENDOR_IDENTIFIER above. @@ -780,14 +787,22 @@ static bool ReturnCharacterString(const char* text, char* value, uint8_t* encodingType) { uint32_t length = (uint32_t)strlen(text); if (length > maxElementCount) { - // Truncate SILENTLY to fit the stack's buffer. maxElementCount is - // MAX_CHARACTER_STRING_SIZE (256 in this build), and our longest string - // (DEVICE_DESCRIPTION) fits with room to spare - so this never trips - // here. But if you build 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. + // A previous version of this comment claimed a served string always + // fits under maxElementCount (MAX_CHARACTER_STRING_SIZE - 256 on a + // full build, 64 on STACK_OPTION_TARGET_EMBEDDED) "with room to + // spare." That was false: DEVICE_DESCRIPTION shipped at 286 chars, + // over the 256-char full-build limit, and the read didn't even get + // truncated - it Aborted outright before reaching this clamp + // (chipkin/BACnetProfileExample-B-BC-CPP#7). Whatever the actual + // on-the-wire behavior turns out to be for an over-length string, a + // silent truncation here is the wrong fallback for a tutorial + // example either way - it teaches "this is fine" when it isn't. Warn + // loudly instead, and keep every served string under the limit for + // real rather than relying on this clamp to save you. + printf("Warning: property value %u chars, longer than the stack's " + "%u-char buffer - truncating (and the actual read may fail " + "before this point; see issue #7).\n", + (unsigned)length, (unsigned)maxElementCount); length = maxElementCount; } memcpy(value, text, length); @@ -903,6 +918,24 @@ bool GetPropertyCharString(const uint32_t deviceInstance, const uint16_t objectT return false; } +// The Device's Local_Time / Local_Date (DM-TS-B, DM-UTC-B): the stack refuses +// to invent a default for either of these if the app declines (see "WHAT +// false-WITHOUT-AN-ERROR-CODE ACTUALLY DOES" above) - a device that never +// serves them reads back Error: read-access-denied, which is exactly how a +// client normally confirms a TimeSynchronization/UTCTimeSynchronization +// actually took (chipkin/BACnetProfileExample-B-BC-CPP#7). This example +// claims both BIBBs, so it has to actually answer these, not just leave the +// stack's "declined" fallback in place. Real wall-clock local time - the +// simplest honest answer, and consistent with HelperGetSystemTime(). +static bool GetCurrentLocalTm(struct tm* out) { + const time_t nowSeconds = time(NULL); +#if defined(_WIN32) + return localtime_s(out, &nowSeconds) == 0; +#else + return localtime_r(&nowSeconds, out) != NULL; +#endif +} + // Ivory (File 1) - Modification_Date's Time half. Fixed at a nominal start-up // value; a real device would stamp this on every WriteFile. bool GetPropertyTime(const uint32_t deviceInstance, const uint16_t objectType, @@ -920,6 +953,18 @@ bool GetPropertyTime(const uint32_t deviceInstance, const uint16_t objectType, *hour = 0; *minute = 0; *second = 0; *hundredthSecond = 0; return true; } + if (objectType == OBJECT_TYPE_DEVICE && objectInstance == g_deviceInstance && + propertyIdentifier == PROPERTY_IDENTIFIER_LOCAL_TIME) { + struct tm nowTm; + if (!GetCurrentLocalTm(&nowTm)) { + return false; + } + *hour = (uint8_t)nowTm.tm_hour; + *minute = (uint8_t)nowTm.tm_min; + *second = (uint8_t)nowTm.tm_sec; + *hundredthSecond = 0; + return true; + } return false; } @@ -940,6 +985,20 @@ bool GetPropertyDate(const uint32_t deviceInstance, const uint16_t objectType, *yearMinus1900 = 126; *month = 1; *day = 1; *weekday = 4; // nominal 2026-01-01 Thu return true; } + if (objectType == OBJECT_TYPE_DEVICE && objectInstance == g_deviceInstance && + propertyIdentifier == PROPERTY_IDENTIFIER_LOCAL_DATE) { + struct tm nowTm; + if (!GetCurrentLocalTm(&nowTm)) { + return false; + } + *yearMinus1900 = (uint8_t)nowTm.tm_year; + *month = (uint8_t)(nowTm.tm_mon + 1); + *day = (uint8_t)nowTm.tm_mday; + // struct tm's tm_wday is 0=Sunday..6=Saturday; BACnet's BACnetWeekday + // is 1=Monday..7=Sunday (ANSI/ASHRAE 135 Clause 21). + *weekday = (uint8_t)(((nowTm.tm_wday + 6) % 7) + 1); + return true; + } return false; } From 7581b50e9c4be0a0d2fc2f416a7f6842cf83cf73 Mon Sep 17 00:00:00 2001 From: SWS-Chipkin Date: Thu, 17 Sep 2026 17:34:03 -0700 Subject: [PATCH 4/5] chore: bump app version to 1.0.1 for the Description/Local_Date/Local_Time fixes Co-Authored-By: Claude Sonnet 5 --- CHANGELOG.md | 2 +- main.cpp | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 8cbe49f..70f3907 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,7 +5,7 @@ All notable changes to this project will be documented in this file. The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/), and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). -## [Unreleased] +## [1.0.1] - 2026-09-17 ### Fixed diff --git a/main.cpp b/main.cpp index 3940075..aef6d85 100644 --- a/main.cpp +++ b/main.cpp @@ -118,7 +118,7 @@ using namespace CASBACnetStackExampleConstants; // 1. Example + device configuration // ----------------------------------------------------------------------------- static const char* APP_NAME = "BACnet B-BC (Building Controller) Example - C++"; -static const char* APP_VERSION = "1.0.0"; +static const char* APP_VERSION = "1.0.1"; // The device instance. BACnet requires this to be configurable, so it defaults // to 389005 and can be overridden on the command line with --deviceID. Keep it From fdb899d443c9ae85657b364d67596525c6a62612 Mon Sep 17 00:00:00 2001 From: SWS-Chipkin Date: Thu, 17 Sep 2026 17:51:20 -0700 Subject: [PATCH 5/5] fix: Network Port Link_Speed reported a hardcoded 0.0 instead of the real speed Nothing served Link_Speed (property 420), so the stack's 'no callback answered' REAL-property fallback (a datatype zero-value) was silently standing in as if 0.0 meant 'indeterminable' - it didn't, it meant 'unimplemented'. New CASExampleHelper::GetLocalLinkSpeedBitsPerSecond() (common/ 2.8.0 -> 2.9.0): Windows reads it via GetIfEntry() keyed off the primary interface's adapter index (same interface GetLocalIPv4 already selects); POSIX reads /sys/class/net//speed. Read once at start-up into g_linkSpeedBitsPerSecond, same pattern as the IP addressing already cached there. New PROPERTY_IDENTIFIER_LINK_SPEED = 420 constant. Verified against a live rebuilt binary: Network Port 1's Link_Speed now returns a ComplexACK with 1000000000.0 (1 Gbps) - this machine's actual adapter speed - not 0.0. Co-Authored-By: Claude Sonnet 5 --- common/CASBACnetStackExampleConstants.h | 1 + common/CASExampleHelper.cpp | 81 +++++++++++++++++++++++++ common/CASExampleHelper.h | 10 ++- common/CHANGELOG.md | 13 ++++ docs/objects.json | 4 +- main.cpp | 26 ++++++++ 6 files changed, 132 insertions(+), 3 deletions(-) diff --git a/common/CASBACnetStackExampleConstants.h b/common/CASBACnetStackExampleConstants.h index 4a2ea55..6e72fb9 100644 --- a/common/CASBACnetStackExampleConstants.h +++ b/common/CASBACnetStackExampleConstants.h @@ -47,6 +47,7 @@ static const uint32_t PROPERTY_IDENTIFIER_IP_DEFAULT_GATEWAY = 401; static const uint32_t PROPERTY_IDENTIFIER_BACNET_IP_MODE = 408; static const uint32_t PROPERTY_IDENTIFIER_IP_SUBNET_MASK = 411; static const uint32_t PROPERTY_IDENTIFIER_BACNET_IP_UDP_PORT = 412; +static const uint32_t PROPERTY_IDENTIFIER_LINK_SPEED = 420; static const uint32_t PROPERTY_IDENTIFIER_MAC_ADDRESS = 423; static const uint32_t PROPERTY_IDENTIFIER_NUMBER_OF_STATES = 74; static const uint32_t PROPERTY_IDENTIFIER_OBJECT_IDENTIFIER = 75; diff --git a/common/CASExampleHelper.cpp b/common/CASExampleHelper.cpp index 7176b45..23043de 100644 --- a/common/CASExampleHelper.cpp +++ b/common/CASExampleHelper.cpp @@ -226,6 +226,83 @@ CASBACnetTime HelperGetSystemTime() { return (CASBACnetTime)time(0); } +// --------------------------------------------------------------------------- +// Find the primary network interface's negotiated link speed, in bits per +// second (what the Network Port object's Link_Speed property reports - a +// REAL, 0.0 meaning "indeterminable" per Clause 12.56.15). Same interface +// selection as GetPrimaryIPv4 (first non-loopback, "up" IPv4 interface) - +// deliberately not shared code with it: Windows needs a second API call +// (GetIfEntry) keyed off the adapter's index, and POSIX needs the interface +// NAME rather than its address, so the loop bodies diverge enough that +// factoring out "the one interface" isn't worth it for two ~30-line +// functions called once each, at start-up. Returns false (leaves +// *bitsPerSecond untouched) if no interface was found or its speed could not +// be read - the caller then reports 0.0 ("indeterminable"), which is honest, +// not this function silently inventing a number. +bool GetPrimaryLinkSpeedBitsPerSecond(double* bitsPerSecond) { +#if defined(_WIN32) + IP_ADAPTER_INFO adapters[32]; + ULONG len = sizeof(adapters); + if (GetAdaptersInfo(adapters, &len) != ERROR_SUCCESS) { + return false; + } + for (const IP_ADAPTER_INFO* a = adapters; a != NULL; a = a->Next) { + struct in_addr ipAddr; + if (inet_pton(AF_INET, a->IpAddressList.IpAddress.String, &ipAddr) != 1) { + continue; + } + const uint32_t ipN = ipAddr.s_addr; + if (ipN == 0 || (ipN & 0xFF) == 127) { + continue; // no address, or loopback - same exclusions as GetPrimaryIPv4 + } + MIB_IFROW ifRow; + memset(&ifRow, 0, sizeof(ifRow)); + ifRow.dwIndex = a->Index; + if (GetIfEntry(&ifRow) != NO_ERROR) { + return false; + } + *bitsPerSecond = (double)ifRow.dwSpeed; // already bits/sec on this API + return true; + } + return false; +#else + struct ifaddrs* ifap = NULL; + if (getifaddrs(&ifap) != 0) { + return false; + } + bool found = false; + for (const struct ifaddrs* ifa = ifap; ifa != NULL && !found; ifa = ifa->ifa_next) { + if (ifa->ifa_addr == NULL || ifa->ifa_addr->sa_family != AF_INET) { + continue; + } + if ((ifa->ifa_flags & IFF_LOOPBACK) || !(ifa->ifa_flags & IFF_UP)) { + continue; + } + // /sys/class/net//speed - the kernel's own view of the negotiated + // link speed in Mbit/s (an ethtool query would need root on some distros + // and a dependency this file doesn't otherwise have; + // the sysfs file is the same number, readable by anyone, no extra headers). + // Reads "-1" (or fails to open) for a link that's down or doesn't expose + // a speed (e.g. some virtual/tunnel interfaces) - either way, no value. + char path[64]; + snprintf(path, sizeof(path), "/sys/class/net/%s/speed", ifa->ifa_name); + FILE* f = fopen(path, "r"); + if (f == NULL) { + continue; + } + long mbps = -1; + const int scanned = fscanf(f, "%ld", &mbps); + fclose(f); + if (scanned == 1 && mbps > 0) { + *bitsPerSecond = (double)mbps * 1000000.0; + found = true; + } + } + freeifaddrs(ifap); + return found; +#endif +} + // --------------------------------------------------------------------------- // Find the primary IPv4 interface's address and subnet mask (each 4 octets in // network/big-endian order, i.e. ip[0] is the first dotted octet). These feed @@ -1882,6 +1959,10 @@ bool GetLocalIPv4(uint8_t ipAddress[4], uint8_t subnetMask[4]) { return GetPrimaryIPv4(ipAddress, subnetMask); } +bool GetLocalLinkSpeedBitsPerSecond(double* bitsPerSecond) { + return GetPrimaryLinkSpeedBitsPerSecond(bitsPerSecond); +} + void SendIAm(const uint32_t deviceInstance, const uint32_t networkPortInstance) { // Target the LOCAL subnet broadcast (the device's own network) rather than // the global 255.255.255.255 / network 0xFFFF. The broadcast is ip | ~mask diff --git a/common/CASExampleHelper.h b/common/CASExampleHelper.h index 7e68503..2d39d5e 100644 --- a/common/CASExampleHelper.h +++ b/common/CASExampleHelper.h @@ -41,7 +41,7 @@ namespace CASExampleHelper { // version). Bump it whenever anything in common/ changes, and record the // change in common/CHANGELOG.md - every example in the series must then be // re-synced to the same common/ version. -static const char* COMMON_VERSION = "2.8.0"; +static const char* COMMON_VERSION = "2.9.0"; // Print the example's name + version, the linked CAS BACnet Stack version, // and the common/ helper version. @@ -142,6 +142,14 @@ void SendIAm(uint32_t deviceInstance, uint32_t networkPortInstance); // true on success; on failure the buffers are left untouched. bool GetLocalIPv4(uint8_t ipAddress[4], uint8_t subnetMask[4]); +// Get the primary network interface's negotiated link speed in bits per +// second - the value a Network Port object's Link_Speed property reports +// (REAL; 0.0 means "indeterminable" per Clause 12.56.15, so a caller that +// gets false back should report 0.0, not fabricate a number). Windows reads +// it via GetIfEntry(); POSIX reads /sys/class/net//speed. Returns +// true on success; on failure *bitsPerSecond is left untouched. +bool GetLocalLinkSpeedBitsPerSecond(double* bitsPerSecond); + // --- Deferred device restart (DM-RD-B) ------------------------------------- // Only for examples whose profile includes DM-RD-B (i.e. that register a // ReinitializeDevice callback). Most profiles in this series do not. diff --git a/common/CHANGELOG.md b/common/CHANGELOG.md index 2ba3ec8..24fbcbd 100644 --- a/common/CHANGELOG.md +++ b/common/CHANGELOG.md @@ -12,6 +12,19 @@ entry here, and must then be re-copied into **every** example in the series. The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/), and the folder adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). +## [2.9.0] - 2026-09-17 + +### Added + +- `CASExampleHelper::GetLocalLinkSpeedBitsPerSecond()` - reads the primary + network interface's actual negotiated link speed (Windows: `GetIfEntry()`; + POSIX: `/sys/class/net//speed`), for a Network Port object's + `Link_Speed` property. First consumer: `BACnetProfileExample-B-BC-CPP`, + whose `Link_Speed` previously read back a hardcoded `0.0` because nothing + served it - the stack's "no callback answered" REAL-property fallback, + not a real "indeterminable" answer. `PROPERTY_IDENTIFIER_LINK_SPEED = 420` + added to `CASBACnetStackExampleConstants.h` alongside it. + ## [2.8.0] - 2026-09-17 ### Added diff --git a/docs/objects.json b/docs/objects.json index 8a4f4d7..253fb69 100644 --- a/docs/objects.json +++ b/docs/objects.json @@ -117,11 +117,11 @@ "type": "Network Port", "instance": 1, "name": "Vermilion", - "app": ["Object_Name", "Out_Of_Service", "Network_Type", "Protocol_Level", "Changes_Pending"], + "app": ["Object_Name", "Out_Of_Service", "Network_Type", "Protocol_Level", "Changes_Pending", "Link_Speed"], "enabled": [], "writable": [], "accepted": ["Reliability"], - "note": "BACnet/IP; Network_Type and Protocol_Level are set from BACnetStack_AddNetworkPortObject()'s arguments (IPv4, BACnet Application) at start-up, not a GetProperty callback like the object's other app-served rows; Changes_Pending is likewise computed and answered natively by the stack's Network Port object. Reliability has no fault condition this example detects, so it is accepted at the generic default (normal)" + "note": "BACnet/IP; Network_Type and Protocol_Level are set from BACnetStack_AddNetworkPortObject()'s arguments (IPv4, BACnet Application) at start-up, not a GetProperty callback like the object's other app-served rows; Changes_Pending is likewise computed and answered natively by the stack's Network Port object. Reliability has no fault condition this example detects, so it is accepted at the generic default (normal). Link_Speed is read once at start-up from the host's primary network interface (CASExampleHelper::GetLocalLinkSpeedBitsPerSecond) - 0.0 if the host OS can't report one, which is the spec-correct 'indeterminable' answer, not a bug" }, { "type": "Schedule", diff --git a/main.cpp b/main.cpp index aef6d85..e4a17da 100644 --- a/main.cpp +++ b/main.cpp @@ -208,6 +208,15 @@ static uint8_t g_ipSubnetMask[4] = { 0, 0, 0, 0 }; static uint8_t g_ipDefaultGateway[4] = { 0, 0, 0, 0 }; static uint16_t g_bacnetIpUdpPort = 47808; +// Network Port's Link_Speed (REAL, bits/sec; 0.0 means "indeterminable" per +// Clause 12.56.15). Read once at start-up, same as the IP addressing above - +// this example's link speed does not change at runtime, and re-querying it +// on every poll would be pointless work in the Tick loop for a value that +// never changes. Genuinely 0.0 (not just uninitialized) is a valid, honest +// answer if CASExampleHelper::GetLocalLinkSpeedBitsPerSecond() can't +// determine it - it is NOT this example fabricating a number either way. +static float g_linkSpeedBitsPerSecond = 0.0f; + // Analog Input 1's live present value (degrees Celsius). Starts at 21.5 and is // nudged by the up/down arrow keys. A real sensor would update this from // hardware instead. @@ -488,6 +497,16 @@ bool GetPropertyReal(const uint32_t deviceInstance, const uint16_t objectType, *value = g_analogInput1Value; return true; } + // Network Port "Vermilion" - Link_Speed, the negotiated speed of the + // physical interface this example's BACnet/IP traffic actually goes out + // over. Cached once at start-up into g_linkSpeedBitsPerSecond (see its + // declaration above for why). 0.0 ("indeterminable") is the correct, + // spec-honest answer when the host OS can't report a speed - not a bug. + if (objectType == OBJECT_TYPE_NETWORK_PORT && objectInstance == NETWORK_PORT_INSTANCE && + propertyIdentifier == PROPERTY_IDENTIFIER_LINK_SPEED) { + *value = g_linkSpeedBitsPerSecond; + return true; + } // Analog Value 1 "Diamond" - the alarm-capable process value. Its Present_Value // is what the intrinsic OutOfRange algorithm watches; a client writes its // Present_Value across a limit (>90 or <10) to fire an EventNotification. @@ -1529,6 +1548,13 @@ int main(int argc, char** argv) { printf("FYI: could not read a local IPv4 address; Network Port IP_Address " "will report 0.0.0.0.\n"); } + double linkSpeedBitsPerSecond = 0.0; + if (CASExampleHelper::GetLocalLinkSpeedBitsPerSecond(&linkSpeedBitsPerSecond)) { + g_linkSpeedBitsPerSecond = (float)linkSpeedBitsPerSecond; + } else { + printf("FYI: could not determine the local link speed; Network Port " + "Link_Speed will report 0.0 (indeterminable).\n"); + } // --- Register callbacks ------------------------------------------------- // Tell the helper which Network Port object owns the socket it just bound.