From ac8a292dad3ed0ab89c89f34c62d07174ef1e820 Mon Sep 17 00:00:00 2001 From: Muhammed rafi Date: Thu, 15 Jan 2026 09:46:52 +0000 Subject: [PATCH 01/23] step1 and step2 --- DBUS_MIGRATION_STEP1_2_PLAN.md | 336 +++++++ DBUS_MIGRATION_STEP3_BULKDATA_PLAN.md | 594 ++++++++++++ source/ccspinterface/dbusInterface.c | 916 ++++++++++++++++++ source/ccspinterface/dbusInterface.h | 258 +++++ source/commonlib/Makefile.am | 22 +- .../commonlib/telemetry_busmessage_sender.c | 442 ++------- 6 files changed, 2214 insertions(+), 354 deletions(-) create mode 100755 DBUS_MIGRATION_STEP1_2_PLAN.md create mode 100755 DBUS_MIGRATION_STEP3_BULKDATA_PLAN.md create mode 100755 source/ccspinterface/dbusInterface.c create mode 100755 source/ccspinterface/dbusInterface.h diff --git a/DBUS_MIGRATION_STEP1_2_PLAN.md b/DBUS_MIGRATION_STEP1_2_PLAN.md new file mode 100755 index 00000000..089f9f29 --- /dev/null +++ b/DBUS_MIGRATION_STEP1_2_PLAN.md @@ -0,0 +1,336 @@ +# DBUS Migration Plan: Step 1 & 2 - CommonLib Event Sending + +## Current Status + +**COMPLETED:** +✅ Updated dbusInterface.h with new service name "telemetry.t2" +✅ Added new APIs: `dbusGetMarkerList()`, `dbusGetOperationalStatus()`, `dbusSubscribeProfileUpdate()` +✅ Updated dbusInterface.c with implementations +✅ Includes in telemetry_busmessage_sender.c already changed to use DBUS + +**PENDING:** +❌ Remove all RBUS/CCSP specific code from telemetry_busmessage_sender.c +❌ Replace RBUS operations with DBUS equivalents +❌ Update Makefile.am to link with DBUS libraries + +--- + +## Changes Required in telemetry_busmessage_sender.c + +### 1. Remove These Functions (CCSP/RBUS specific): + +```c +// Lines 138-178: Remove entire CCSP block +#if defined(CCSP_SUPPORT_ENABLED) +T2ERROR getParamValues(...) {...} +static void freeParamValue(...) {...} +static T2ERROR getCCSPParamVal(...) {...} +#endif + +// Lines 183-184: Remove RBUS uninit +static void rBusInterface_Uninit() {...} + +// Lines 186-235: Remove initMessageBus - Replace with DBUS init +static T2ERROR initMessageBus() {...} + +// Lines 237-268: Remove getRbusParameterVal - not needed for commonlib +static T2ERROR getRbusParameterVal(...) {...} +``` + +### 2. Replace filtered_event_send() Function (Lines 407-500) + +**Current RBUS Implementation:** +```c +int filtered_event_send(const char* data, const char *markerName) { + // Uses rbus_set() with rbusProperty, rbusValue + // Complex object creation for RBUS + ... +} +``` + +**New DBUS Implementation:** +```c +int filtered_event_send(const char* data, const char *markerName) { + T2ERROR ret = T2ERROR_SUCCESS; + + // Check DBUS initialized + if(!isDbusInitialized()) { + EVENT_ERROR("DBUS not initialized\n"); + return -1; + } + + // Keep event filtering logic (lines 420-445) AS-IS + // ... marker list filtering code ... + + // Replace RBUS rbus_set() with DBUS signal + ret = dbusPublishEvent(markerName, data); + if(ret != T2ERROR_SUCCESS) { + EVENT_ERROR("dbusPublishEvent Failed\n"); + return -1; + } + return 0; +} +``` + +### 3. Replace doPopulateEventMarkerList() Function (Lines 505-598) + +**Current RBUS Implementation:** +```c +static T2ERROR doPopulateEventMarkerList(void) { + // Uses rbus_get() to fetch marker list as RBUS_OBJECT + // Iterates through rbusProperty list + ... +} +``` + +**New DBUS Implementation:** +```c +static T2ERROR doPopulateEventMarkerList(void) { + EVENT_DEBUG("%s ++in\n", __FUNCTION__); + T2ERROR status = T2ERROR_SUCCESS; + + if(!isDbusInitialized()) { + EVENT_ERROR("DBUS not initialized\n"); + return T2ERROR_FAILURE; + } + + pthread_mutex_lock(&markerListMutex); + + if(eventMarkerMap) { + hash_map_destroy(eventMarkerMap); + eventMarkerMap = NULL; + } + + // Get marker list via DBUS method call + char* markerListStr = NULL; + status = dbusGetMarkerList(componentName, &markerListStr); + + if(status != T2ERROR_SUCCESS || !markerListStr) { + EVENT_ERROR("dbusGetMarkerList failed\n"); + pthread_mutex_unlock(&markerListMutex); + return T2ERROR_FAILURE; + } + + // Parse marker list string (format: "marker1,marker2,marker3") + eventMarkerMap = hash_map_create(); + char* token = strtok(markerListStr, ","); + while(token != NULL) { + // Trim whitespace + while(*token == ' ') token++; + if(strlen(token) > 0) { + EVENT_DEBUG("\t %s\n", token); + hash_map_put(eventMarkerMap, strdup(token), strdup(token), free); + } + token = strtok(NULL, ","); + } + + free(markerListStr); + pthread_mutex_unlock(&markerListMutex); + + EVENT_DEBUG("%s --out\n", __FUNCTION__); + return status; +} +``` + +### 4. Replace rbusEventReceiveHandler() with DBUS Callback (Lines 600-615) + +**Current RBUS Implementation:** +```c +static void rbusEventReceiveHandler(rbusHandle_t handle, rbusEvent_t const* event, ...) { + // RBUS event subscription callback + if(strcmp(eventName, T2_PROFILE_UPDATED_NOTIFY) == 0) { + doPopulateEventMarkerList(); + } +} +``` + +**New DBUS Implementation:** +```c +static void dbusProfileUpdateHandler(void) { + EVENT_DEBUG("Profile update notification received\n"); + doPopulateEventMarkerList(); +} +``` + +### 5. Replace isCachingRequired() Function (Lines 617-690) + +**Current RBUS Implementation:** +```c +static bool isCachingRequired() { + // Uses rbus_getUint() to check T2_OPERATIONAL_STATUS + retVal = rbus_getUint(bus_handle, T2_OPERATIONAL_STATUS, &t2ReadyStatus); + + // Uses rbusEvent_Subscribe() for profile updates + ret = rbusEvent_Subscribe(bus_handle, T2_PROFILE_UPDATED_NOTIFY, rbusEventReceiveHandler, ...); + ... +} +``` + +**New DBUS Implementation:** +```c +static bool isCachingRequired() { + // Keep RFC and PAM initialization checks AS-IS (lines 624-633) + + if(!initRFC()) { + EVENT_ERROR("initRFC failed - cache the events\n"); + return true; + } + + if(!isRFCT2Enable) { + return false; + } + + // Replace rbus_getUint() with DBUS method call + uint32_t t2ReadyStatus; + T2ERROR retVal = dbusGetOperationalStatus(&t2ReadyStatus); + + if(retVal != T2ERROR_SUCCESS) { + return true; + } + + EVENT_DEBUG("Operational status: %d\n", t2ReadyStatus); + if((t2ReadyStatus & T2_STATE_COMPONENT_READY) == 0) { + return true; + } + + if(!isT2Ready) { + if(componentName && (strcmp(componentName, "telemetry_client") != 0)) { + if((t2ReadyStatus & T2_STATE_COMPONENT_READY) == 0) { + return true; + } else { + // Fetch marker list and subscribe to profile updates + doPopulateEventMarkerList(); + + // Subscribe to profile update signal + T2ERROR ret = dbusSubscribeProfileUpdate(dbusProfileUpdateHandler); + if(ret != T2ERROR_SUCCESS) { + EVENT_ERROR("Failed to subscribe to profile updates\n"); + } + isT2Ready = true; + } + } else { + isT2Ready = true; + } + } + + return false; +} +``` + +### 6. Update t2_init() and t2_uninit() Functions (Lines 734-752) + +**Current Implementation:** +```c +void t2_init(char *component) { + componentName = strdup(component); +} + +void t2_uninit(void) { + if(componentName) { + free(componentName); + componentName = NULL; + } + if(isRbusEnabled) { + rBusInterface_Uninit(); + } + uninitMutex(); +} +``` + +**New DBUS Implementation:** +```c +void t2_init(char *component) { + componentName = strdup(component); + + // Initialize DBUS connection + T2ERROR ret = dBusInterface_Init(componentName); + if(ret != T2ERROR_SUCCESS) { + EVENT_ERROR("DBUS initialization failed for %s\n", componentName); + } +} + +void t2_uninit(void) { + if(componentName) { + free(componentName); + componentName = NULL; + } + + // Uninitialize DBUS + dBusInterface_Uninit(); + + uninitMutex(); +} +``` + +--- + +## Changes Required in Makefile.am + +### File: telemetry/source/commonlib/Makefile.am + +**Add DBUS dependencies:** + +```makefile +# Add DBUS CFLAGS and LIBS +AM_CFLAGS = -I$(top_srcdir)/include \ + -I$(top_srcdir)/source/ccspinterface \ + $(DBUS_CFLAGS) \ + ... (existing flags) + +libt2commonlib_la_LIBADD = $(DBUS_LIBS) ... (existing libs) +``` + +--- + +## Testing Plan + +After making these changes, you should: + +1. **Compile:** + ```bash + cd telemetry + ./configure --enable-dbus + make clean + make + ``` + +2. **Check for DBUS symbols:** + ```bash + nm -D .libs/libt2commonlib.so | grep dbus + ``` + +3. **Test with simple client:** + ```bash + # Terminal 1: Monitor DBUS + dbus-monitor --session "interface='telemetry.t2.interface'" + + # Terminal 2: Run test client + ./test_client + ``` + +4. **Expected DBUS traffic:** + - Signal: `TelemetryEvent` with (marker_name, event_value) + - Method call: `GetMarkerList` with component_name + - Method call: `GetOperationalStatus` + - Signal: `ProfileUpdate` + +--- + +## Summary of API Mappings + +| RBUS API | DBUS API | Type | Purpose | +|----------|----------|------|---------| +| `rbus_set(T2_EVENT_PARAM, ...)` | `dbusPublishEvent(marker, value)` | Signal | Send telemetry event | +| `rbusEvent_Subscribe(T2_PROFILE_UPDATED_NOTIFY)` | `dbusSubscribeProfileUpdate(callback)` | Signal | Listen for profile updates | +| `rbus_get("...EventMarkerList", ...)` | `dbusGetMarkerList(component, &list)` | Method | Get marker list | +| `rbus_getUint(T2_OPERATIONAL_STATUS)` | `dbusGetOperationalStatus(&status)` | Method | Check T2 daemon status | + +--- + +## Questions? + +1. Should I proceed with creating the complete modified telemetry_busmessage_sender.c file? +2. Do you want me to create a patch file instead for easier review? +3. Should we test incrementally or make all changes at once? + +Please confirm and I'll proceed with the implementation. diff --git a/DBUS_MIGRATION_STEP3_BULKDATA_PLAN.md b/DBUS_MIGRATION_STEP3_BULKDATA_PLAN.md new file mode 100755 index 00000000..4f3e3b73 --- /dev/null +++ b/DBUS_MIGRATION_STEP3_BULKDATA_PLAN.md @@ -0,0 +1,594 @@ +# DBUS Migration Plan: STEP 3 - BulkData Side (T2 Daemon) + +## Overview + +This step implements the **server side** of the DBUS communication in the T2 daemon (BulkData). The daemon will: +1. **Receive telemetry events** via DBUS signals from commonlib clients +2. **Provide marker lists** via DBUS method responses +3. **Provide operational status** via DBUS method responses +4. **Send profile update notifications** via DBUS signals to commonlib clients + +--- + +## Current Status + +**STEP 1 & 2 COMPLETED:** +✅ CommonLib modified to use DBUS (telemetry_busmessage_sender.c) +✅ DBUS interface APIs implemented (dbusInterface.h/c) +✅ Makefile.am updated with DBUS dependencies + +**STEP 3 PENDING:** +❌ Implement DBUS signal receiver for telemetry events in BulkData +❌ Implement DBUS method providers (GetMarkerList, GetOperationalStatus) +❌ Implement DBUS signal sender for profile updates +❌ Update BulkData initialization to register DBUS handlers + +--- + +## Architecture Overview + +``` +┌──────────────────┐ ┌───────────────────────┐ +│ CommonLib │ │ BulkData (T2 Daemon) │ +│ (Client Apps) │ │ │ +├──────────────────┤ ├───────────────────────┤ +│ │ DBUS Signal │ │ +│ dbusPublishEvent├───────────────────────>│ dbusEventHandler() │ +│ (marker, value) │ "TelemetryEvent" │ ↓ │ +│ │ │ T2ER_Push() │ +│ │ │ ↓ │ +│ │ │ Event Queue │ +└──────────────────┘ └───────────────────────┘ + │ │ + │ DBUS Method Call │ + │ "GetMarkerList" │ + └───────────────────────────────────────────>│ + │ │ dbusGetMarkerListHandler() + │<───────────────────────────────────────────┤ getComponentMarkerList() + │ DBUS Method Reply │ + │ (marker1,marker2,...) │ + │ │ + │ DBUS Method Call │ + │ "GetOperationalStatus" │ + └───────────────────────────────────────────>│ + │ │ dbusGetOperationalStatusHandler() + │<───────────────────────────────────────────┤ t2ReadyStatus + │ DBUS Method Reply (uint32) │ + │ │ + │ │ + │ DBUS Signal │ + │ "ProfileUpdate" │ + │<───────────────────────────────────────────┤ publishEventsProfileUpdates() + │ │ (when profiles change) +``` + +--- + +## Files to Modify + +### Primary Files: +1. **`telemetry/source/bulkdata/t2eventreceiver.c`** - Add DBUS event reception +2. **`telemetry/source/bulkdata/t2markers.c`** - Add DBUS method provider for marker list +3. **`telemetry/source/ccspinterface/rbusInterface.c`** - Add DBUS method providers and signal sender +4. **`telemetry/source/telemetry2_0.c`** - Update daemon initialization + +### Supporting Files: +5. **`telemetry/source/ccspinterface/Makefile.am`** - Already has DBUS (verify) +6. **`telemetry/source/bulkdata/Makefile.am`** - May need DBUS includes + +--- + +## Detailed Implementation Plan + +### **STEP 3.1: Implement DBUS Event Reception in BulkData** + +**File:** [`t2eventreceiver.c`](telemetry/source/bulkdata/t2eventreceiver.c) + +**Current RBUS Implementation:** +- Function: `registerRbusT2EventListener()` registers callback for RBUS events +- Callback: `t2rbusEventCallback()` receives RBUS property set events +- Processing: Extracts event name/value and calls `T2ER_Push()` + +**New DBUS Implementation:** + +```c +/** + * @brief DBUS signal handler for telemetry events + * Called when TelemetryEvent signal is received + */ +static DBusHandlerResult dbusEventSignalHandler(DBusConnection *connection, + DBusMessage *message, + void *user_data) +{ + (void)connection; + (void)user_data; + + T2Debug("%s ++in\n", __FUNCTION__); + + if (!dbus_message_is_signal(message, T2_DBUS_INTERFACE_NAME, T2_DBUS_SIGNAL_EVENT)) { + return DBUS_HANDLER_RESULT_NOT_YET_HANDLED; + } + + const char* eventName = NULL; + const char* eventValue = NULL; + DBusError error; + dbus_error_init(&error); + + // Extract event name and value from signal + if (!dbus_message_get_args(message, &error, + DBUS_TYPE_STRING, &eventName, + DBUS_TYPE_STRING, &eventValue, + DBUS_TYPE_INVALID)) { + T2Error("Failed to parse TelemetryEvent signal: %s\n", error.message); + dbus_error_free(&error); + return DBUS_HANDLER_RESULT_HANDLED; + } + + T2Info("Received DBUS event: %s = %s\n", eventName, eventValue); + + // Create rbusProperty for backward compatibility with existing code + rbusProperty_t properties = NULL; + rbusValue_t value; + rbusValue_Init(&value); + rbusValue_SetString(value, eventValue); + rbusProperty_Init(&properties, eventName, value); + + // Push to event queue (reuse existing T2ER_Push logic) + T2ER_Push(properties); + + // Cleanup + rbusValue_Release(value); + rbusProperty_Release(properties); + + T2Debug("%s --out\n", __FUNCTION__); + return DBUS_HANDLER_RESULT_HANDLED; +} + +/** + * @brief Register DBUS telemetry event listener + */ +T2ERROR registerDbusT2EventListener(void) +{ + T2Debug("%s ++in\n", __FUNCTION__); + + if (!isDbusInitialized()) { + T2Error("DBUS not initialized\n"); + return T2ERROR_FAILURE; + } + + // Subscribe to TelemetryEvent signal + T2ERROR ret = registerDbusT2EventListener(dbusEventSignalHandler); + if (ret != T2ERROR_SUCCESS) { + T2Error("Failed to register DBUS event listener\n"); + return T2ERROR_FAILURE; + } + + T2Info("DBUS telemetry event listener registered\n"); + T2Debug("%s --out\n", __FUNCTION__); + return T2ERROR_SUCCESS; +} +``` + +**Changes Required:** +- Add `dbusEventSignalHandler()` function +- Add `registerDbusT2EventListener()` function +- Update `T2ER_Init()` to call `registerDbusT2EventListener()` instead of/alongside RBUS + +--- + +### **STEP 3.2: Implement DBUS Method Provider for Marker List** + +**File:** [`rbusInterface.c`](telemetry/source/ccspinterface/rbusInterface.c) + +**Current RBUS Implementation:** +- Data element: `"Telemetry.ReportProfiles.{component}.EventMarkerList"` +- Handler: `t2PropertyDataGetHandler()` calls `getMarkerListCallBack()` +- Returns: RBUS_OBJECT containing marker names as properties + +**New DBUS Implementation:** + +```c +/** + * @brief DBUS method handler for GetMarkerList + */ +static DBusMessage* dbusGetMarkerListHandler(DBusMessage *msg) +{ + T2Debug("%s ++in\n", __FUNCTION__); + + const char* componentName = NULL; + DBusError error; + dbus_error_init(&error); + + // Extract component name from method call + if (!dbus_message_get_args(msg, &error, + DBUS_TYPE_STRING, &componentName, + DBUS_TYPE_INVALID)) { + T2Error("Failed to parse GetMarkerList arguments: %s\n", error.message); + dbus_error_free(&error); + return dbus_message_new_error(msg, DBUS_ERROR_INVALID_ARGS, "Missing component name"); + } + + T2Debug("GetMarkerList request for component: %s\n", componentName); + + // Get marker list from callback (reuse existing getComponentMarkerList) + Vector* markerList = NULL; + if (getMarkerListCallBack) { + getMarkerListCallBack(componentName, (void**)&markerList); + } + + // Build comma-separated string + char markerListStr[4096] = {0}; + if (markerList && Vector_Size(markerList) > 0) { + for (size_t i = 0; i < Vector_Size(markerList); i++) { + char* marker = (char*)Vector_At(markerList, i); + if (marker) { + if (i > 0) strcat(markerListStr, ","); + strcat(markerListStr, marker); + } + } + } + + T2Debug("Marker list: %s\n", markerListStr); + + // Create reply + DBusMessage* reply = dbus_message_new_method_return(msg); + const char* markerListPtr = markerListStr; + dbus_message_append_args(reply, + DBUS_TYPE_STRING, &markerListPtr, + DBUS_TYPE_INVALID); + + T2Debug("%s --out\n", __FUNCTION__); + return reply; +} +``` + +--- + +### **STEP 3.3: Implement DBUS Method Provider for Operational Status** + +**File:** [`rbusInterface.c`](telemetry/source/ccspinterface/rbusInterface.c) + +**Current RBUS Implementation:** +- Data element: `"Telemetry.OperationalStatus"` +- Handler: `t2PropertyDataGetHandler()` returns `t2ReadyStatus` (uint32) + +**New DBUS Implementation:** + +```c +/** + * @brief DBUS method handler for GetOperationalStatus + */ +static DBusMessage* dbusGetOperationalStatusHandler(DBusMessage *msg) +{ + T2Debug("%s ++in\n", __FUNCTION__); + + // Get current operational status (global variable) + uint32_t status = t2ReadyStatus; + + T2Debug("Operational status: %u\n", status); + + // Create reply + DBusMessage* reply = dbus_message_new_method_return(msg); + dbus_message_append_args(reply, + DBUS_TYPE_UINT32, &status, + DBUS_TYPE_INVALID); + + T2Debug("%s --out\n", __FUNCTION__); + return reply; +} +``` + +--- + +### **STEP 3.4: Implement DBUS Signal Sender for Profile Updates** + +**File:** [`rbusInterface.c`](telemetry/source/ccspinterface/rbusInterface.c) + +**Current RBUS Implementation:** +- Function: `publishEventsProfileUpdates()` +- Uses: `rbusEvent_Publish()` on `"Telemetry.ReportProfiles.ProfilesUpdated"` + +**New DBUS Implementation:** + +```c +/** + * @brief Publish profile update notification via DBUS signal + */ +void dbusPublishProfileUpdate(void) +{ + T2Debug("%s ++in\n", __FUNCTION__); + + if (!isDbusInitialized()) { + T2Error("DBUS not initialized\n"); + return; + } + + DBusMessage *signal = dbus_message_new_signal(T2_DBUS_OBJECT_PATH, + T2_DBUS_INTERFACE_NAME, + T2_DBUS_SIGNAL_PROFILE_UPDATE); + if (!signal) { + T2Error("Failed to create ProfileUpdate signal\n"); + return; + } + + // Send signal (no arguments needed) + if (!dbus_connection_send(getDbuConnection(), signal, NULL)) { + T2Error("Failed to send ProfileUpdate signal\n"); + } else { + dbus_connection_flush(getDbusConnection()); + T2Info("ProfileUpdate signal sent\n"); + } + + dbus_message_unref(signal); + T2Debug("%s --out\n", __FUNCTION__); +} +``` + +**Update existing function:** +```c +void publishEventsProfileUpdates(void) +{ + // Keep RBUS for internal components (if needed) + // Add DBUS for commonlib clients + dbusPublishProfileUpdate(); +} +``` + +--- + +### **STEP 3.5: Register DBUS Method Handlers** + +**File:** [`rbusInterface.c`](telemetry/source/ccspinterface/rbusInterface.c) or new `dbusMethodProvider.c` + +**Create DBUS method object registration:** + +```c +/** + * @brief DBUS method dispatch function + */ +static DBusHandlerResult dbusMethodDispatcher(DBusConnection *connection, + DBusMessage *message, + void *user_data) +{ + (void)connection; + (void)user_data; + + T2Debug("%s ++in\n", __FUNCTION__); + + if (dbus_message_is_method_call(message, T2_DBUS_INTERFACE_NAME, "GetMarkerList")) { + DBusMessage* reply = dbusGetMarkerListHandler(message); + dbus_connection_send(connection, reply, NULL); + dbus_message_unref(reply); + return DBUS_HANDLER_RESULT_HANDLED; + } + else if (dbus_message_is_method_call(message, T2_DBUS_INTERFACE_NAME, "GetOperationalStatus")) { + DBusMessage* reply = dbusGetOperationalStatusHandler(message); + dbus_connection_send(connection, reply, NULL); + dbus_message_unref(reply); + return DBUS_HANDLER_RESULT_HANDLED; + } + + T2Debug("%s --out\n", __FUNCTION__); + return DBUS_HANDLER_RESULT_NOT_YET_HANDLED; +} + +/** + * @brief Register DBUS method providers + */ +T2ERROR registerDbusMethodProviders(void) +{ + T2Debug("%s ++in\n", __FUNCTION__); + + if (!isDbusInitialized()) { + T2Error("DBUS not initialized\n"); + return T2ERROR_FAILURE; + } + + // Register object path with method handler + DBusObjectPathVTable vtable = { + .message_function = dbusMethodDispatcher, + .unregister_function = NULL + }; + + if (!dbus_connection_register_object_path(getDbusConnection(), + T2_DBUS_OBJECT_PATH, + &vtable, + NULL)) { + T2Error("Failed to register DBUS object path\n"); + return T2ERROR_FAILURE; + } + + T2Info("DBUS method providers registered\n"); + T2Debug("%s --out\n", __FUNCTION__); + return T2ERROR_SUCCESS; +} +``` + +--- + +### **STEP 3.6: Update T2 Daemon Initialization** + +**File:** [`telemetry2_0.c`](telemetry/source/telemetry2_0.c) + +**Current Initialization:** +```c +int main(int argc, char *argv[]) +{ + ... + // Initialize RBUS + initRbusInterface(); + ... + // Initialize event receiver + T2ER_Init(); + ... +} +``` + +**Updated Initialization:** +```c +int main(int argc, char *argv[]) +{ + ... + // Initialize DBUS (alongside or instead of RBUS) + T2ERROR ret = dBusInterface_Init("telemetry2_0"); + if (ret != T2ERROR_SUCCESS) { + T2Error("DBUS initialization failed\n"); + // Handle error + } + + // Register DBUS method providers + registerDbusMethodProviders(); + + // Initialize event receiver (will register DBUS event listener) + T2ER_Init(); + ... +} +``` + +--- + +## Summary of Changes + +| Component | Current RBUS | New DBUS | File | +|-----------|-------------|----------|------| +| **Event Reception** | `t2rbusEventCallback()` | `dbusEventSignalHandler()` | t2eventreceiver.c | +| **Marker List Provider** | `t2PropertyDataGetHandler()` | `dbusGetMarkerListHandler()` | rbusInterface.c | +| **Status Provider** | `t2PropertyDataGetHandler()` | `dbusGetOperationalStatusHandler()` | rbusInterface.c | +| **Profile Update Notification** | `rbusEvent_Publish()` | `dbusPublishProfileUpdate()` | rbusInterface.c | +| **Method Registration** | `rbus_regDataElements()` | `registerDbusMethodProviders()` | rbusInterface.c | +| **Daemon Init** | `initRbusInterface()` | `dBusInterface_Init()` | telemetry2_0.c | + +--- + +## API Flow Summary + +### 1. **Telemetry Event Flow** (CommonLib → BulkData) +``` +Client App + ↓ t2_event_s("marker", "value") +CommonLib + ↓ dbusPublishEvent() + ↓ DBUS Signal "TelemetryEvent" +BulkData + ↓ dbusEventSignalHandler() + ↓ T2ER_Push() + ↓ Event Queue Processing +``` + +### 2. **Marker List Request Flow** (CommonLib → BulkData) +``` +Client App + ↓ isCachingRequired() / doPopulateEventMarkerList() +CommonLib + ↓ dbusGetMarkerList("component") + ↓ DBUS Method Call "GetMarkerList" +BulkData + ↓ dbusGetMarkerListHandler() + ↓ getComponentMarkerList() + ↓ DBUS Method Reply("marker1,marker2,...") +CommonLib + ↓ Parse and store in eventMarkerMap +``` + +### 3. **Operational Status Check Flow** (CommonLib → BulkData) +``` +Client App + ↓ isCachingRequired() +CommonLib + ↓ dbusGetOperationalStatus() + ↓ DBUS Method Call "GetOperationalStatus" +BulkData + ↓ dbusGetOperationalStatusHandler() + ↓ Return t2ReadyStatus + ↓ DBUS Method Reply(uint32) +CommonLib + ↓ Check status and decide caching +``` + +### 4. **Profile Update Notification Flow** (BulkData → CommonLib) +``` +BulkData + ↓ Profile configuration changed + ↓ publishEventsProfileUpdates() + ↓ dbusPublishProfileUpdate() + ↓ DBUS Signal "ProfileUpdate" +CommonLib + ↓ dbusProfileUpdateHandler() + ↓ doPopulateEventMarkerList() + ↓ Refresh marker list from daemon +``` + +--- + +## Testing Strategy + +### Unit Tests: +1. **Event Reception:** Send DBUS signal, verify T2ER_Push() called +2. **Marker List:** Call GetMarkerList method, verify correct response +3. **Status Check:** Call GetOperationalStatus, verify status value +4. **Profile Update:** Emit ProfileUpdate signal, verify clients notified + +### Integration Tests: +1. **End-to-End Event:** Client sends event → Daemon receives → Stored in queue +2. **Marker List Sync:** Client requests list → Daemon provides → Client filters events +3. **Status Check:** Client checks status → Decides caching → Sends when ready +4. **Profile Update:** Daemon updates profile → Sends signal → Client refreshes list + +### System Tests: +1. **Full Profile Cycle:** Load profile → Send events → Update profile → Events filtered +2. **Multi-Client:** Multiple clients sending events simultaneously +3. **Stress Test:** 10,000 events from 10 clients concurrently +4. **Failover:** Daemon restart → Clients reconnect → Events cached/restored + +--- + +## Compilation and Testing Commands + +```bash +# Compile +cd telemetry +./configure +make clean +make + +# Check DBUS symbols in daemon +nm -D .libs/telemetry2_0 | grep dbus + +# Run daemon with DBUS monitoring +# Terminal 1: Monitor DBUS +dbus-monitor --session "interface='telemetry.t2.interface'" + +# Terminal 2: Run T2 daemon +./telemetry2_0 + +# Terminal 3: Run test client +./telemetry2_0_client + +# Expected DBUS traffic: +# - Signal: TelemetryEvent(marker, value) +# - Method call: GetMarkerList(component) → Reply(markers) +# - Method call: GetOperationalStatus() → Reply(status) +# - Signal: ProfileUpdate() +``` + +--- + +## Questions for Review + +1. **Backward Compatibility:** Do we need to keep RBUS alongside DBUS for internal components? +2. **Error Handling:** Should DBUS failures fall back to RBUS or cache events? +3. **Threading:** Should DBUS method handlers run in separate thread or main loop? +4. **Data Format:** Is comma-separated marker list format acceptable, or prefer JSON? +5. **Registration:** Should we register DBUS object path in dbusInterface.c or rbusInterface.c? + +--- + +## Next Steps After Review + +Once you review and approve this plan: +1. I'll implement all BulkData changes +2. Update necessary build files (Makefile.am) +3. You test the end-to-end flow +4. We move to Step 4: Complete testing and deployment + +**Ready for your review and feedback!** diff --git a/source/ccspinterface/dbusInterface.c b/source/ccspinterface/dbusInterface.c new file mode 100755 index 00000000..f704fd33 --- /dev/null +++ b/source/ccspinterface/dbusInterface.c @@ -0,0 +1,916 @@ +/* + * If not stated otherwise in this file or this component's LICENSE file the + * following copyright and licenses apply: + * + * Copyright 2026 RDK Management + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. +*/ + +/** + * @file dbusInterface.c + * @brief D-Bus Interface Implementation for Telemetry 2.0 + * + * This file implements D-Bus based inter-process communication + * as an alternative to RBUS for telemetry operations. + */ + +#include +#include +#include +#include +#include +#include + +#include "dbusInterface.h" +#include "t2collection.h" +#include "t2common.h" +#include "busInterface.h" +#include "telemetry2_0.h" +#include "t2log_wrapper.h" +#include "profile.h" + +#define BUFF_LEN 1024 +#define MAX_PARAM_LEN 128 + +/* D-Bus Service Configuration */ +#define T2_DBUS_SERVICE_NAME "telemetry.t2" +#define T2_DBUS_OBJECT_PATH "/telemetry/t2" +#define T2_DBUS_INTERFACE_NAME "telemetry.t2.interface" +#define T2_DBUS_SIGNAL_EVENT "TelemetryEvent" +#define T2_DBUS_SIGNAL_PROFILE_UPDATE "ProfileUpdate" + +/* Global D-Bus handle */ +static T2DbusHandle_t t2dbus_handle = {NULL, NULL, false}; +static void (*profileUpdateCallback)(void) = NULL; + +/* Callback handlers */ +static TelemetryEventCallback eventCallBack = NULL; +static T2EventMarkerListCallback getMarkerListCallBack = NULL; +static dataModelCallBack dmProcessingCallBack = NULL; +static dataModelMsgPckCallBack dmMsgPckProcessingCallBack = NULL; +static dataModelSavedJsonCallBack dmSavedJsonProcessingCallBack = NULL; +static dataModelSavedMsgPackCallBack dmSavedMsgPackProcessingCallBack = NULL; +static profilememCallBack profilememUsedCallBack = NULL; +static dataModelReportOnDemandCallBack reportOnDemandCallBack = NULL; +static triggerReportOnCondtionCallBack reportOnConditionCallBack = NULL; +static xconfPrivacyModesDoNotShareCallBack privacyModesDoNotShareCallBack = NULL; +static ReportProfilesDeleteDNDCallBack mprofilesDeleteCallBack = NULL; + +/* State variables */ +static uint32_t t2ReadyStatus = T2_STATE_NOT_READY; +static char* reportProfileVal = NULL; +static char* tmpReportProfileVal = NULL; +static char* reportProfilemsgPckVal = NULL; + +/* Threading */ +static pthread_mutex_t dbusMutex = PTHREAD_MUTEX_INITIALIZER; +static pthread_t dbusListenerThread; +static bool stopListenerThread = false; + +/* Component to parameter map */ +static hash_map_t *compTr181ParamMap = NULL; +static pthread_mutex_t compParamMap = PTHREAD_MUTEX_INITIALIZER; + +/** + * @brief Check if D-Bus is initialized + */ +bool isDbusInitialized(void) { + return t2dbus_handle.is_initialized; +} + +/** + * @brief D-Bus filter function for incoming messages + */ +static DBusHandlerResult dbusMessageFilter(DBusConnection *connection, + DBusMessage *message, + void *user_data) { + (void)connection; + (void)user_data; + + T2Debug("%s ++in\n", __FUNCTION__); + + if (dbus_message_is_signal(message, T2_DBUS_INTERFACE_NAME, T2_DBUS_SIGNAL_EVENT)) { + DBusMessageIter args; + char *eventName = NULL; + char *eventValue = NULL; + + if (!dbus_message_iter_init(message, &args)) { + T2Error("Event signal has no arguments\n"); + } else { + /* Get event name */ + if (dbus_message_iter_get_arg_type(&args) == DBUS_TYPE_STRING) { + dbus_message_iter_get_basic(&args, &eventName); + dbus_message_iter_next(&args); + } + + /* Get event value */ + if (dbus_message_iter_get_arg_type(&args) == DBUS_TYPE_STRING) { + dbus_message_iter_get_basic(&args, &eventValue); + } + + if (eventName && eventValue && eventCallBack) { + T2Debug("Received event: name=%s, value=%s\n", eventName, eventValue); + eventCallBack(strdup(eventName), strdup(eventValue)); + } + } + + return DBUS_HANDLER_RESULT_HANDLED; + } + else if (dbus_message_is_signal(message, T2_DBUS_INTERFACE_NAME, T2_DBUS_SIGNAL_PROFILE_UPDATE)) { + T2Info("Received ProfileUpdate signal\n"); + /* Invoke profile update callback */ + if (profileUpdateCallback) { + profileUpdateCallback(); + } + return DBUS_HANDLER_RESULT_HANDLED; + } + + T2Debug("%s --out\n", __FUNCTION__); + return DBUS_HANDLER_RESULT_NOT_YET_HANDLED; +} + +/** + * @brief D-Bus listener thread function + */ +static void* dbusListenerThreadFunc(void *arg) { + (void)arg; + + T2Debug("%s ++in\n", __FUNCTION__); + + while (!stopListenerThread && t2dbus_handle.connection) { + /* Process messages with timeout */ + dbus_connection_read_write_dispatch(t2dbus_handle.connection, 100); + } + + T2Debug("%s --out\n", __FUNCTION__); + return NULL; +} + +/** + * @brief Initialize D-Bus interface + */ +T2ERROR dBusInterface_Init(const char *component_name) { + T2Debug("%s ++in\n", __FUNCTION__); + + pthread_mutex_lock(&dbusMutex); + + if (t2dbus_handle.is_initialized) { + T2Warning("D-Bus interface already initialized\n"); + pthread_mutex_unlock(&dbusMutex); + return T2ERROR_SUCCESS; + } + + DBusError error; + dbus_error_init(&error); + + /* Connect to system bus */ + t2dbus_handle.connection = dbus_bus_get(DBUS_BUS_SYSTEM, &error); + if (dbus_error_is_set(&error)) { + T2Error("D-Bus connection error: %s\n", error.message); + dbus_error_free(&error); + pthread_mutex_unlock(&dbusMutex); + return T2ERROR_FAILURE; + } + + if (!t2dbus_handle.connection) { + T2Error("Failed to get D-Bus connection\n"); + pthread_mutex_unlock(&dbusMutex); + return T2ERROR_FAILURE; + } + + /* Request well-known name */ + char service_name[256]; + if (component_name) { + snprintf(service_name, sizeof(service_name), "%s.%s", + T2_DBUS_SERVICE_NAME, component_name); + } else { + snprintf(service_name, sizeof(service_name), "%s", T2_DBUS_SERVICE_NAME); + } + + int ret = dbus_bus_request_name(t2dbus_handle.connection, service_name, + DBUS_NAME_FLAG_REPLACE_EXISTING, &error); + if (dbus_error_is_set(&error)) { + T2Error("D-Bus name request error: %s\n", error.message); + dbus_error_free(&error); + dbus_connection_unref(t2dbus_handle.connection); + t2dbus_handle.connection = NULL; + pthread_mutex_unlock(&dbusMutex); + return T2ERROR_FAILURE; + } + + if (ret != DBUS_REQUEST_NAME_REPLY_PRIMARY_OWNER) { + T2Warning("Not primary owner of D-Bus name\n"); + } + + /* Store unique name */ + t2dbus_handle.unique_name = strdup(dbus_bus_get_unique_name(t2dbus_handle.connection)); + + /* Add message filter */ + dbus_connection_add_filter(t2dbus_handle.connection, dbusMessageFilter, NULL, NULL); + + t2dbus_handle.is_initialized = true; + + /* Start listener thread */ + stopListenerThread = false; + if (pthread_create(&dbusListenerThread, NULL, dbusListenerThreadFunc, NULL) != 0) { + T2Error("Failed to create D-Bus listener thread\n"); + dBusInterface_Uninit(); + pthread_mutex_unlock(&dbusMutex); + return T2ERROR_FAILURE; + } + + pthread_mutex_unlock(&dbusMutex); + + T2Info("D-Bus interface initialized successfully with name: %s\n", service_name); + T2Debug("%s --out\n", __FUNCTION__); + + return T2ERROR_SUCCESS; +} + +/** + * @brief Uninitialize D-Bus interface + */ +void dBusInterface_Uninit(void) { + T2Debug("%s ++in\n", __FUNCTION__); + + pthread_mutex_lock(&dbusMutex); + + if (!t2dbus_handle.is_initialized) { + pthread_mutex_unlock(&dbusMutex); + return; + } + + /* Stop listener thread */ + stopListenerThread = true; + pthread_mutex_unlock(&dbusMutex); + + if (dbusListenerThread) { + pthread_join(dbusListenerThread, NULL); + } + + pthread_mutex_lock(&dbusMutex); + + /* Clean up D-Bus connection */ + if (t2dbus_handle.connection) { + dbus_connection_remove_filter(t2dbus_handle.connection, dbusMessageFilter, NULL); + dbus_connection_unref(t2dbus_handle.connection); + t2dbus_handle.connection = NULL; + } + + if (t2dbus_handle.unique_name) { + free(t2dbus_handle.unique_name); + t2dbus_handle.unique_name = NULL; + } + + t2dbus_handle.is_initialized = false; + + pthread_mutex_unlock(&dbusMutex); + + T2Debug("%s --out\n", __FUNCTION__); +} + +/** + * @brief Get parameter value via D-Bus + */ +T2ERROR getDbusParameterVal(const char* paramName, char **paramValue) { + T2Debug("%s ++in\n", __FUNCTION__); + + if (!paramName || !paramValue) { + T2Error("Invalid parameters\n"); + return T2ERROR_INVALID_ARGS; + } + + if (!t2dbus_handle.is_initialized) { + if (dBusInterface_Init(NULL) != T2ERROR_SUCCESS) { + return T2ERROR_FAILURE; + } + } + + DBusMessage *msg = NULL; + DBusMessage *reply = NULL; + DBusError error; + dbus_error_init(&error); + + /* Create method call message */ + msg = dbus_message_new_method_call(T2_DBUS_SERVICE_NAME, + T2_DBUS_OBJECT_PATH, + T2_DBUS_INTERFACE_NAME, + T2_DBUS_METHOD_GET_PARAM); + if (!msg) { + T2Error("Failed to create D-Bus message\n"); + return T2ERROR_FAILURE; + } + + /* Append parameter name */ + if (!dbus_message_append_args(msg, DBUS_TYPE_STRING, ¶mName, DBUS_TYPE_INVALID)) { + T2Error("Failed to append arguments\n"); + dbus_message_unref(msg); + return T2ERROR_FAILURE; + } + + /* Send message and get reply */ + reply = dbus_connection_send_with_reply_and_block(t2dbus_handle.connection, msg, + T2_DBUS_DEFAULT_TIMEOUT_MS, &error); + dbus_message_unref(msg); + + if (dbus_error_is_set(&error)) { + T2Error("D-Bus error: %s\n", error.message); + dbus_error_free(&error); + return T2ERROR_FAILURE; + } + + if (!reply) { + T2Error("No reply received\n"); + return T2ERROR_FAILURE; + } + + /* Parse reply */ + char *value = NULL; + if (dbus_message_get_args(reply, &error, + DBUS_TYPE_STRING, &value, + DBUS_TYPE_INVALID)) { + *paramValue = strdup(value); + T2Debug("Retrieved value: %s = %s\n", paramName, *paramValue); + } else { + T2Error("Failed to parse reply: %s\n", error.message); + dbus_error_free(&error); + dbus_message_unref(reply); + return T2ERROR_FAILURE; + } + + dbus_message_unref(reply); + + T2Debug("%s --out\n", __FUNCTION__); + return T2ERROR_SUCCESS; +} + +/** + * @brief Set parameter value via D-Bus + */ +T2ERROR setDbusParameterVal(const char* paramName, const char* paramValue, int paramType) { + T2Debug("%s ++in\n", __FUNCTION__); + + if (!paramName || !paramValue) { + T2Error("Invalid parameters\n"); + return T2ERROR_INVALID_ARGS; + } + + if (!t2dbus_handle.is_initialized) { + if (dBusInterface_Init(NULL) != T2ERROR_SUCCESS) { + return T2ERROR_FAILURE; + } + } + + DBusMessage *msg = NULL; + DBusMessage *reply = NULL; + DBusError error; + dbus_error_init(&error); + + /* Create method call message */ + msg = dbus_message_new_method_call(T2_DBUS_SERVICE_NAME, + T2_DBUS_OBJECT_PATH, + T2_DBUS_INTERFACE_NAME, + T2_DBUS_METHOD_SET_PARAM); + if (!msg) { + T2Error("Failed to create D-Bus message\n"); + return T2ERROR_FAILURE; + } + + /* Append arguments */ + if (!dbus_message_append_args(msg, + DBUS_TYPE_STRING, ¶mName, + DBUS_TYPE_STRING, ¶mValue, + DBUS_TYPE_INT32, ¶mType, + DBUS_TYPE_INVALID)) { + T2Error("Failed to append arguments\n"); + dbus_message_unref(msg); + return T2ERROR_FAILURE; + } + + /* Send message and get reply */ + reply = dbus_connection_send_with_reply_and_block(t2dbus_handle.connection, msg, + T2_DBUS_DEFAULT_TIMEOUT_MS, &error); + dbus_message_unref(msg); + + if (dbus_error_is_set(&error)) { + T2Error("D-Bus error: %s\n", error.message); + dbus_error_free(&error); + return T2ERROR_FAILURE; + } + + if (reply) { + dbus_message_unref(reply); + } + + T2Debug("%s --out\n", __FUNCTION__); + return T2ERROR_SUCCESS; +} + +/** + * @brief Get multiple profile parameter values via D-Bus + */ +Vector* getDbusProfileParamValues(Vector *paramList, int execcount) { + T2Debug("%s ++in\n", __FUNCTION__); + + if (!paramList) { + T2Error("Invalid parameter list\n"); + return NULL; + } + + if (!t2dbus_handle.is_initialized) { + if (dBusInterface_Init(NULL) != T2ERROR_SUCCESS) { + return NULL; + } + } + + Vector *profileValueList = NULL; + Vector_Create(&profileValueList); + + /* Iterate through parameters and fetch values */ + for (size_t i = 0; i < Vector_Size(paramList); i++) { + Param *param = (Param *)Vector_At(paramList, i); + if (!param) continue; + + profileValues *profVals = (profileValues *)malloc(sizeof(profileValues)); + if (!profVals) continue; + + /* Check skip frequency */ + if (param->skipFreq > 0 && (execcount % (param->skipFreq + 1) != 0)) { + T2Debug("Skipping parameter: %s as per skipFreq: %d\n", + param->name, param->skipFreq); + profVals->paramValues = NULL; + profVals->paramValueCount = 0; + Vector_PushBack(profileValueList, profVals); + continue; + } + + /* Get parameter value */ + char *value = NULL; + if (getDbusParameterVal(param->alias, &value) == T2ERROR_SUCCESS && value) { + tr181ValStruct_t **paramValues = (tr181ValStruct_t **)malloc(sizeof(tr181ValStruct_t *)); + paramValues[0] = (tr181ValStruct_t *)malloc(sizeof(tr181ValStruct_t)); + paramValues[0]->parameterName = strdup(param->alias); + paramValues[0]->parameterValue = value; + + profVals->paramValues = paramValues; + profVals->paramValueCount = 1; + } else { + /* Parameter not found */ + tr181ValStruct_t **paramValues = (tr181ValStruct_t **)malloc(sizeof(tr181ValStruct_t *)); + paramValues[0] = (tr181ValStruct_t *)malloc(sizeof(tr181ValStruct_t)); + paramValues[0]->parameterName = strdup(param->alias); + paramValues[0]->parameterValue = strdup("NULL"); + + profVals->paramValues = paramValues; + profVals->paramValueCount = 1; + } + + Vector_PushBack(profileValueList, profVals); + } + + T2Debug("%s --out\n", __FUNCTION__); + return profileValueList; +} + +/** + * @brief Publish telemetry event via D-Bus signal + */ +T2ERROR dbusPublishEvent(const char* eventName, const char* eventValue) { + T2Debug("%s ++in\n", __FUNCTION__); + + if (!eventName || !eventValue) { + T2Error("Invalid event parameters\n"); + return T2ERROR_INVALID_ARGS; + } + + if (!t2dbus_handle.is_initialized) { + if (dBusInterface_Init(NULL) != T2ERROR_SUCCESS) { + return T2ERROR_FAILURE; + } + } + + DBusMessage *signal = NULL; + + /* Create signal */ + signal = dbus_message_new_signal(T2_DBUS_OBJECT_PATH, + T2_DBUS_INTERFACE_NAME, + T2_DBUS_SIGNAL_EVENT); + if (!signal) { + T2Error("Failed to create D-Bus signal\n"); + return T2ERROR_FAILURE; + } + + /* Append arguments */ + if (!dbus_message_append_args(signal, + DBUS_TYPE_STRING, &eventName, + DBUS_TYPE_STRING, &eventValue, + DBUS_TYPE_INVALID)) { + T2Error("Failed to append signal arguments\n"); + dbus_message_unref(signal); + return T2ERROR_FAILURE; + } + + /* Send signal */ + if (!dbus_connection_send(t2dbus_handle.connection, signal, NULL)) { + T2Error("Failed to send D-Bus signal\n"); + dbus_message_unref(signal); + return T2ERROR_FAILURE; + } + + dbus_connection_flush(t2dbus_handle.connection); + dbus_message_unref(signal); + + T2Debug("Published event: %s = %s\n", eventName, eventValue); + T2Debug("%s --out\n", __FUNCTION__); + + return T2ERROR_SUCCESS; +} + +/** + * @brief Subscribe to D-Bus signal + */ +T2ERROR dbusSubscribeSignal(const char* signal_name) { + T2Debug("%s ++in\n", __FUNCTION__); + + if (!signal_name) { + T2Error("Invalid signal name\n"); + return T2ERROR_INVALID_ARGS; + } + + if (!t2dbus_handle.is_initialized) { + if (dBusInterface_Init(NULL) != T2ERROR_SUCCESS) { + return T2ERROR_FAILURE; + } + } + + char rule[512]; + DBusError error; + dbus_error_init(&error); + + /* Create match rule */ + snprintf(rule, sizeof(rule), + "type='signal',interface='%s',member='%s'", + T2_DBUS_INTERFACE_NAME, signal_name); + + dbus_bus_add_match(t2dbus_handle.connection, rule, &error); + + if (dbus_error_is_set(&error)) { + T2Error("Failed to add match rule: %s\n", error.message); + dbus_error_free(&error); + return T2ERROR_FAILURE; + } + + T2Info("Subscribed to signal: %s\n", signal_name); + T2Debug("%s --out\n", __FUNCTION__); + + return T2ERROR_SUCCESS; +} + +/** + * @brief Unsubscribe from D-Bus signal + */ +T2ERROR dbusUnsubscribeSignal(const char* signal_name) { + T2Debug("%s ++in\n", __FUNCTION__); + + if (!signal_name) { + T2Error("Invalid signal name\n"); + return T2ERROR_INVALID_ARGS; + } + + if (!t2dbus_handle.is_initialized) { + return T2ERROR_NOT_INITIALIZED; + } + + char rule[512]; + DBusError error; + dbus_error_init(&error); + + /* Create match rule */ + snprintf(rule, sizeof(rule), + "type='signal',interface='%s',member='%s'", + T2_DBUS_INTERFACE_NAME, signal_name); + + dbus_bus_remove_match(t2dbus_handle.connection, rule, &error); + + if (dbus_error_is_set(&error)) { + T2Error("Failed to remove match rule: %s\n", error.message); + dbus_error_free(&error); + return T2ERROR_FAILURE; + } + + T2Info("Unsubscribed from signal: %s\n", signal_name); + T2Debug("%s --out\n", __FUNCTION__); + + return T2ERROR_SUCCESS; +} + +/** + * @brief Register for telemetry event notifications + */ +T2ERROR registerDbusT2EventListener(TelemetryEventCallback eventCB) { + T2Debug("%s ++in\n", __FUNCTION__); + + if (!eventCB) { + T2Error("Invalid callback\n"); + return T2ERROR_INVALID_ARGS; + } + + eventCallBack = eventCB; + + /* Subscribe to event signal */ + if (dbusSubscribeSignal(T2_DBUS_SIGNAL_EVENT) != T2ERROR_SUCCESS) { + T2Error("Failed to subscribe to event signal\n"); + return T2ERROR_FAILURE; + } + + T2Debug("%s --out\n", __FUNCTION__); + return T2ERROR_SUCCESS; +} + +/** + * @brief Unregister from telemetry event notifications + */ +T2ERROR unregisterDbusT2EventListener(void) { + T2Debug("%s ++in\n", __FUNCTION__); + + eventCallBack = NULL; + + /* Unsubscribe from event signal */ + dbusUnsubscribeSignal(T2_DBUS_SIGNAL_EVENT); + + T2Debug("%s --out\n", __FUNCTION__); + return T2ERROR_SUCCESS; +} + +/** + * @brief Publish report upload status + */ +void dbusPublishReportUploadStatus(const char* status) { + T2Debug("%s ++in\n", __FUNCTION__); + + if (!status) { + T2Error("Invalid status\n"); + return; + } + + if (!t2dbus_handle.is_initialized) { + T2Warning("D-Bus not initialized\n"); + return; + } + + DBusMessage *signal = dbus_message_new_signal(T2_DBUS_OBJECT_PATH, + T2_DBUS_INTERFACE_NAME, + T2_DBUS_SIGNAL_UPLOAD_STATUS); + if (!signal) { + T2Error("Failed to create signal\n"); + return; + } + + if (!dbus_message_append_args(signal, DBUS_TYPE_STRING, &status, DBUS_TYPE_INVALID)) { + T2Error("Failed to append arguments\n"); + dbus_message_unref(signal); + return; + } + + dbus_connection_send(t2dbus_handle.connection, signal, NULL); + dbus_connection_flush(t2dbus_handle.connection); + dbus_message_unref(signal); + + T2Info("Published upload status: %s\n", status); + T2Debug("%s --out\n", __FUNCTION__); +} + +/** + * @brief Set T2 event receiver state + */ +void dbusSetT2EventReceiveState(int t2_state) { + t2ReadyStatus = t2_state; + T2Info("T2 state set to: %d\n", t2_state); +} + +/** + * @brief Check if a D-Bus method exists + */ +bool dbusCheckMethodExists(const char* methodName) { + T2Debug("%s ++in: %s\n", __FUNCTION__, methodName); + + if (!methodName) { + return false; + } + + /* For now, return true for standard methods */ + /* In production, this should introspect the remote object */ + + T2Debug("%s --out\n", __FUNCTION__); + return true; +} + +/** * @brief Get marker list for component via D-Bus method call + */ +T2ERROR dbusGetMarkerList(const char* component, char** markerList) { + T2Debug("%s ++in\n", __FUNCTION__); + + if (!component || !markerList) { + T2Error("Invalid arguments\n"); + return T2ERROR_INVALID_ARGS; + } + + if (!t2dbus_handle.is_initialized) { + T2Error("D-Bus not initialized\n"); + return T2ERROR_NOT_INITIALIZED; + } + + DBusMessage *msg = NULL; + DBusMessage *reply = NULL; + DBusError error; + dbus_error_init(&error); + + /* Construct parameter name: Telemetry.ReportProfiles.{component}.EventMarkerList */ + char paramName[256]; + snprintf(paramName, sizeof(paramName), "Telemetry.ReportProfiles.%s.EventMarkerList", component); + + /* Create method call message */ + msg = dbus_message_new_method_call(T2_DBUS_SERVICE_NAME, + T2_DBUS_OBJECT_PATH, + T2_DBUS_INTERFACE_NAME, + "GetMarkerList"); + if (!msg) { + T2Error("Failed to create method call message\n"); + return T2ERROR_FAILURE; + } + + /* Append component name */ + if (!dbus_message_append_args(msg, DBUS_TYPE_STRING, &component, DBUS_TYPE_INVALID)) { + T2Error("Failed to append arguments\n"); + dbus_message_unref(msg); + return T2ERROR_FAILURE; + } + + /* Send message and get reply */ + reply = dbus_connection_send_with_reply_and_block(t2dbus_handle.connection, msg, + T2_DBUS_DEFAULT_TIMEOUT_MS, &error); + dbus_message_unref(msg); + + if (dbus_error_is_set(&error)) { + T2Error("D-Bus method call failed: %s\n", error.message); + dbus_error_free(&error); + return T2ERROR_FAILURE; + } + + if (!reply) { + T2Error("No reply received\n"); + return T2ERROR_FAILURE; + } + + /* Parse reply - expecting a string containing the marker list */ + char *value = NULL; + if (dbus_message_get_args(reply, &error, + DBUS_TYPE_STRING, &value, + DBUS_TYPE_INVALID)) { + *markerList = strdup(value); + T2Debug("Retrieved marker list for %s\n", component); + } else { + T2Error("Failed to parse reply: %s\n", error.message); + dbus_error_free(&error); + dbus_message_unref(reply); + return T2ERROR_FAILURE; + } + + dbus_message_unref(reply); + + T2Debug("%s --out\n", __FUNCTION__); + return T2ERROR_SUCCESS; +} + +/** + * @brief Get operational status via D-Bus method call + */ +T2ERROR dbusGetOperationalStatus(uint32_t* status) { + T2Debug("%s ++in\n", __FUNCTION__); + + if (!status) { + T2Error("Invalid arguments\n"); + return T2ERROR_INVALID_ARGS; + } + + if (!t2dbus_handle.is_initialized) { + T2Error("D-Bus not initialized\n"); + return T2ERROR_NOT_INITIALIZED; + } + + DBusMessage *msg = NULL; + DBusMessage *reply = NULL; + DBusError error; + dbus_error_init(&error); + + /* Create method call message */ + msg = dbus_message_new_method_call(T2_DBUS_SERVICE_NAME, + T2_DBUS_OBJECT_PATH, + T2_DBUS_INTERFACE_NAME, + "GetOperationalStatus"); + if (!msg) { + T2Error("Failed to create method call message\n"); + return T2ERROR_FAILURE; + } + + /* Send message and get reply */ + reply = dbus_connection_send_with_reply_and_block(t2dbus_handle.connection, msg, + T2_DBUS_DEFAULT_TIMEOUT_MS, &error); + dbus_message_unref(msg); + + if (dbus_error_is_set(&error)) { + T2Error("D-Bus method call failed: %s\n", error.message); + dbus_error_free(&error); + return T2ERROR_FAILURE; + } + + if (!reply) { + T2Error("No reply received\n"); + return T2ERROR_FAILURE; + } + + /* Parse reply - expecting UINT32 */ + if (dbus_message_get_args(reply, &error, + DBUS_TYPE_UINT32, status, + DBUS_TYPE_INVALID)) { + T2Debug("Retrieved operational status: %u\n", *status); + } else { + T2Error("Failed to parse reply: %s\n", error.message); + dbus_error_free(&error); + dbus_message_unref(reply); + return T2ERROR_FAILURE; + } + + dbus_message_unref(reply); + + T2Debug("%s --out\n", __FUNCTION__); + return T2ERROR_SUCCESS; +} + +/** + * @brief Subscribe to profile update notifications + */ +T2ERROR dbusSubscribeProfileUpdate(void (*callback)(void)) { + T2Debug("%s ++in\n", __FUNCTION__); + + if (!callback) { + T2Error("Invalid callback\n"); + return T2ERROR_INVALID_ARGS; + } + + if (!t2dbus_handle.is_initialized) { + T2Error("D-Bus not initialized\n"); + return T2ERROR_NOT_INITIALIZED; + } + + /* Store callback */ + profileUpdateCallback = callback; + + /* Subscribe to ProfileUpdate signal */ + char rule[512]; + DBusError error; + dbus_error_init(&error); + + snprintf(rule, sizeof(rule), + "type='signal',interface='%s',member='%s'", + T2_DBUS_INTERFACE_NAME, T2_DBUS_SIGNAL_PROFILE_UPDATE); + + dbus_bus_add_match(t2dbus_handle.connection, rule, &error); + + if (dbus_error_is_set(&error)) { + T2Error("Failed to add match rule: %s\n", error.message); + dbus_error_free(&error); + return T2ERROR_FAILURE; + } + + T2Info("Subscribed to ProfileUpdate signal\n"); + T2Debug("%s --out\n", __FUNCTION__); + + return T2ERROR_SUCCESS; +} + +/** * @brief Process incoming D-Bus messages + */ +T2ERROR dbusProcessMessages(int timeout_ms) { + if (!t2dbus_handle.is_initialized || !t2dbus_handle.connection) { + return T2ERROR_NOT_INITIALIZED; + } + + dbus_connection_read_write_dispatch(t2dbus_handle.connection, timeout_ms); + + return T2ERROR_SUCCESS; +} + +/** + \ No newline at end of file diff --git a/source/ccspinterface/dbusInterface.h b/source/ccspinterface/dbusInterface.h new file mode 100755 index 00000000..b5e7ab7a --- /dev/null +++ b/source/ccspinterface/dbusInterface.h @@ -0,0 +1,258 @@ +/* + * If not stated otherwise in this file or this component's LICENSE file the + * following copyright and licenses apply: + * + * Copyright 2026 RDK Management + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. +*/ + +/** + * @file dbusInterface.h + * @brief D-Bus Interface for Telemetry 2.0 + * + * This header provides D-Bus based inter-process communication APIs + * as an alternative to RBUS for the Telemetry 2.0 framework. + * + * Key Features: + * - Parameter get/set operations + * - Event publishing and subscription + * - Method invocation + * - Signal handling + */ + +#ifndef _DBUSINTERFACE_H_ +#define _DBUSINTERFACE_H_ + +#include +#include +#include +#include +#include "busInterface.h" +#include "telemetry2_0.h" + +/* D-Bus Service Information */ +#define T2_DBUS_SERVICE_NAME "telemetry.t2" +#define T2_DBUS_OBJECT_PATH "/telemetry/t2" +#define T2_DBUS_INTERFACE_NAME "telemetry.t2.interface" + +/* D-Bus Method Names */ +#define T2_DBUS_METHOD_GET_PARAM "GetParameter" +#define T2_DBUS_METHOD_SET_PARAM "SetParameter" +#define T2_DBUS_METHOD_SUBSCRIBE "SubscribeEvent" +#define T2_DBUS_METHOD_UNSUBSCRIBE "UnsubscribeEvent" +#define T2_DBUS_METHOD_CALL "CallMethod" + +/* D-Bus Signal Names */ +#define T2_DBUS_SIGNAL_EVENT "TelemetryEvent" +#define T2_DBUS_SIGNAL_PROFILE_UPDATE "ProfileUpdate" +#define T2_DBUS_SIGNAL_UPLOAD_STATUS "UploadStatus" + +/* D-Bus Error Codes */ +#define T2_DBUS_ERROR_SUCCESS 0 +#define T2_DBUS_ERROR_FAILURE -1 +#define T2_DBUS_ERROR_OUT_OF_MEMORY -2 +#define T2_DBUS_ERROR_INVALID_PARAM -3 +#define T2_DBUS_ERROR_NOT_INITIALIZED -4 +#define T2_DBUS_ERROR_TIMEOUT -5 +#define T2_DBUS_ERROR_NO_ELEMENT -6 + +/* Timeout values */ +#define T2_DBUS_DEFAULT_TIMEOUT_MS 10000 /* 10 seconds */ +#define T2_DBUS_METHOD_TIMEOUT_MS 10000 /* 10 seconds */ + +/** + * @brief D-Bus connection handle + */ +typedef struct { + DBusConnection *connection; + char *unique_name; + bool is_initialized; +} T2DbusHandle_t; + +/** + * @brief D-Bus method callback pointer + */ +typedef void (*dbusMethodCallBackPtr)(DBusMessage *reply, int retStatus); + +/** + * @brief Check if D-Bus is initialized + * @return true if initialized, false otherwise + */ +bool isDbusInitialized(void); + +/** + * @brief Initialize D-Bus interface for Telemetry 2.0 + * @param component_name Unique component name for registration + * @return T2ERROR_SUCCESS on success, T2ERROR_FAILURE on failure + */ +T2ERROR dBusInterface_Init(const char *component_name); + +/** + * @brief Uninitialize D-Bus interface + */ +void dBusInterface_Uninit(void); + +/** + * @brief Get parameter value via D-Bus + * @param paramName Parameter name to query + * @param paramValue Pointer to store retrieved value (caller must free) + * @return T2ERROR_SUCCESS on success, T2ERROR_FAILURE on failure + */ +T2ERROR getDbusParameterVal(const char* paramName, char **paramValue); + +/** + * @brief Set parameter value via D-Bus + * @param paramName Parameter name to set + * @param paramValue Value to set + * @param paramType Type of parameter (string, int, boolean, etc.) + * @return T2ERROR_SUCCESS on success, T2ERROR_FAILURE on failure + */ +T2ERROR setDbusParameterVal(const char* paramName, const char* paramValue, int paramType); + +/** + * @brief Get multiple profile parameter values via D-Bus + * @param paramList Vector containing list of parameters to query + * @param execcount Execution count for skip frequency calculation + * @return Vector of profileValues structures + */ +Vector* getDbusProfileParamValues(Vector *paramList, int execcount); + +/** + * @brief Register for telemetry event notifications via D-Bus + * @param eventCB Callback function to handle events + * @return T2ERROR_SUCCESS on success, T2ERROR_FAILURE on failure + */ +T2ERROR registerDbusT2EventListener(TelemetryEventCallback eventCB); + +/** + * @brief Unregister from telemetry event notifications + * @return T2ERROR_SUCCESS on success, T2ERROR_FAILURE on failure + */ +T2ERROR unregisterDbusT2EventListener(void); + +/** + * @brief Subscribe to a specific D-Bus signal + * @param signal_name Name of the signal to subscribe + * @return T2ERROR_SUCCESS on success, T2ERROR_FAILURE on failure + */ +T2ERROR dbusSubscribeSignal(const char* signal_name); + +/** + * @brief Unsubscribe from a specific D-Bus signal + * @param signal_name Name of the signal to unsubscribe + * @return T2ERROR_SUCCESS on success, T2ERROR_FAILURE on failure + */ +T2ERROR dbusUnsubscribeSignal(const char* signal_name); + +/** + * @brief Publish telemetry event via D-Bus signal + * @param eventName Event name/marker + * @param eventValue Event value + * @return T2ERROR_SUCCESS on success, T2ERROR_FAILURE on failure + */ +T2ERROR dbusPublishEvent(const char* eventName, const char* eventValue); + +/** + * @brief Get marker list for component via D-Bus method call + * @param component Component name + * @param markerList Pointer to store marker list string (caller must free) + * @return T2ERROR_SUCCESS on success, T2ERROR_FAILURE on failure + */ +T2ERROR dbusGetMarkerList(const char* component, char** markerList); + +/** + * @brief Get operational status via D-Bus method call + * @param status Pointer to store status value + * @return T2ERROR_SUCCESS on success, T2ERROR_FAILURE on failure + */ +T2ERROR dbusGetOperationalStatus(uint32_t* status); + +/** + * @brief Subscribe to profile update notifications + * @param callback Callback function to invoke on profile update + * @return T2ERROR_SUCCESS on success, T2ERROR_FAILURE on failure + */ +T2ERROR dbusSubscribeProfileUpdate(void (*callback)(void)); + +/** + * @brief Call a D-Bus method + * @param methodName Method name to invoke + * @param inputParams Input parameters as D-Bus message + * @param payload Payload data + * @param callback Callback function for asynchronous response + * @return T2ERROR_SUCCESS on success, T2ERROR_FAILURE on failure + */ +T2ERROR dbusMethodCaller(const char *methodName, DBusMessage* inputParams, + const char* payload, dbusMethodCallBackPtr callback); + +/** + * @brief Check if a D-Bus method exists + * @param methodName Name of the method to check + * @return true if method exists, false otherwise + */ +bool dbusCheckMethodExists(const char* methodName); + +/** + * @brief Subscribe to trigger condition reports + * @param reference Reference parameter name + * @param subscription true to subscribe, false to unsubscribe + * @return T2ERROR_SUCCESS on success, T2ERROR_FAILURE on failure + */ +T2ERROR T2DbusReportEventConsumer(const char* reference, bool subscription); + +/** + * @brief Register consumer for trigger conditions + * @param triggerConditionList List of trigger conditions + * @return T2ERROR_SUCCESS on success, T2ERROR_FAILURE on failure + */ +T2ERROR dbusT2ConsumerReg(Vector *triggerConditionList); + +/** + * @brief Unregister consumer for trigger conditions + * @param triggerConditionList List of trigger conditions + * @return T2ERROR_SUCCESS on success, T2ERROR_FAILURE on failure + */ +T2ERROR dbusT2ConsumerUnReg(Vector *triggerConditionList); + +/** + * @brief Publish report upload status via D-Bus + * @param status Status string to publish + */ +void dbusPublishReportUploadStatus(const char* status); + +/** + * @brief Set T2 event receiver state + * @param t2_state State value to set + */ +void dbusSetT2EventReceiveState(int t2_state); + +/** + * @brief Process incoming D-Bus messages + * @param timeout_ms Timeout in milliseconds (-1 for blocking) + * @return T2ERROR_SUCCESS on success, T2ERROR_FAILURE on failure + */ +T2ERROR dbusProcessMessages(int timeout_ms); + +/** + * @brief Create D-Bus message iterator for parameters + * @param iter D-Bus message iterator + * @param paramName Parameter name + * @param paramValue Parameter value + * @param paramType Parameter type + * @return T2ERROR_SUCCESS on success, T2ERROR_FAILURE on failure + */ +T2ERROR dbusAppendParameter(DBusMessageIter *iter, const char* paramName, + const char* paramValue, int paramType); + +#endif /* _DBUSINTERFACE_H_ */ diff --git a/source/commonlib/Makefile.am b/source/commonlib/Makefile.am index c058b698..bb9cea25 100644 --- a/source/commonlib/Makefile.am +++ b/source/commonlib/Makefile.am @@ -25,28 +25,28 @@ lib_LTLIBRARIES = libtelemetry_msgsender.la libtelemetry_msgsender_la_SOURCES = telemetry_busmessage_sender.c libtelemetry_msgsender_la_LDFLAGS = -shared -libtelemetry_msgsender_la_LIBADD = -lrbus ${top_builddir}/source/utils/libt2utils.la +libtelemetry_msgsender_la_LIBADD = -ldbus-1 ${top_builddir}/source/utils/libt2utils.la ${top_builddir}/source/ccspinterface/libccspinterface.la if ENABLE_CCSP_SUPPORT libtelemetry_msgsender_la_LIBADD += -lccsp_common endif -libtelemetry_msgsender_la_CPPFLAGS = -fPIC -I${PKG_CONFIG_SYSROOT_DIR}$(includedir)/dbus-1.0 \ - -I${PKG_CONFIG_SYSROOT_DIR}$(libdir)/dbus-1.0/include \ - -I${PKG_CONFIG_SYSROOT_DIR}$(includedir)/rbus \ - -I${top_srcdir}/source/utils \ +libtelemetry_msgsender_la_CPPFLAGS = -fPIC -I${PKG_CONFIG_SYSROOT_DIR}$(includedir)/dbus-1.0 \\ + -I${PKG_CONFIG_SYSROOT_DIR}$(libdir)/dbus-1.0/include \\ + -I${top_srcdir}/source/utils \\ + -I${top_srcdir}/source/ccspinterface \\ -I${top_srcdir}/include libtelemetry_msgsender_la_DEPENDENCIES = ${top_builddir}/source/utils/libt2utils.la bin_PROGRAMS = telemetry2_0_client telemetry2_0_client_SOURCES = telemetry_client.c telemetry_busmessage_sender.c -telemetry2_0_client_LDADD = -lrbus ${top_builddir}/source/utils/libt2utils.la -lpthread +telemetry2_0_client_LDADD = -ldbus-1 ${top_builddir}/source/utils/libt2utils.la ${top_builddir}/source/ccspinterface/libccspinterface.la -lpthread if ENABLE_CCSP_SUPPORT telemetry2_0_client_LDADD += -lccsp_common endif -telemetry2_0_client_CPPFLAGS = -fPIC -I${PKG_CONFIG_SYSROOT_DIR}$(includedir)/dbus-1.0 \ - -I${PKG_CONFIG_SYSROOT_DIR}$(libdir)/dbus-1.0/include \ - -I${PKG_CONFIG_SYSROOT_DIR}$(includedir)/ccsp \ - -I${PKG_CONFIG_SYSROOT_DIR}$(includedir)/rbus \ - -I${top_srcdir}/source/utils \ +telemetry2_0_client_CPPFLAGS = -fPIC -I${PKG_CONFIG_SYSROOT_DIR}$(includedir)/dbus-1.0 \\ + -I${PKG_CONFIG_SYSROOT_DIR}$(libdir)/dbus-1.0/include \\ + -I${PKG_CONFIG_SYSROOT_DIR}$(includedir)/ccsp \\ + -I${top_srcdir}/source/utils \\ + -I${top_srcdir}/source/ccspinterface \\ -I${top_srcdir}/include telemetry2_0_client_DEPENDENCIES = ${top_builddir}/source/utils/libt2utils.la diff --git a/source/commonlib/telemetry_busmessage_sender.c b/source/commonlib/telemetry_busmessage_sender.c index c5d43127..3a0b9211 100644 --- a/source/commonlib/telemetry_busmessage_sender.c +++ b/source/commonlib/telemetry_busmessage_sender.c @@ -26,16 +26,10 @@ #include #include #include - -#if defined(CCSP_SUPPORT_ENABLED) -#include -#include -#include -#endif -#include +#include #include "telemetry_busmessage_sender.h" - +#include "../ccspinterface/dbusInterface.h" #include "t2collection.h" #include "vector.h" #include "telemetry2_0.h" @@ -48,13 +42,9 @@ #define T2_SCRIPT_EVENT_COMPONENT "telemetry_client" #define SENDER_LOG_FILE "/tmp/t2_sender_debug.log" -static const char* CCSP_FIXED_COMP_ID = "com.cisco.spvtg.ccsp.t2commonlib" ; - static char *componentName = NULL; -static void *bus_handle = NULL; static bool isRFCT2Enable = false ; static bool isT2Ready = false; -static bool isRbusEnabled = false ; static int count = 0; static pthread_mutex_t initMtx = PTHREAD_MUTEX_INITIALIZER; static bool isMutexInitialized = false ; @@ -144,167 +134,6 @@ static void uninitMutex() pthread_mutex_unlock(&initMtx); } -#if defined(CCSP_SUPPORT_ENABLED) -T2ERROR getParamValues(char **paramNames, const int paramNamesCount, parameterValStruct_t ***valStructs, int *valSize) -{ - if (paramNames == NULL || paramNamesCount <= 0) - { - EVENT_ERROR("paramNames is NULL or paramNamesCount <= 0 - returning\n"); - return T2ERROR_INVALID_ARGS; - } - - int ret = CcspBaseIf_getParameterValues(bus_handle, destCompName, (char*)destCompPath, paramNames, - paramNamesCount, valSize, valStructs); - if (ret != CCSP_SUCCESS) - { - EVENT_ERROR("CcspBaseIf_getParameterValues failed for : %s with ret = %d\n", paramNames[0], - ret); - return T2ERROR_FAILURE; - } - return T2ERROR_SUCCESS; -} - -static void freeParamValue(parameterValStruct_t **valStructs, int valSize) -{ - free_parameterValStruct_t(bus_handle, valSize, valStructs); -} - -static T2ERROR getCCSPParamVal(const char* paramName, char **paramValue) -{ - parameterValStruct_t **valStructs = NULL; - int valSize = 0; - char *paramNames[1] = {NULL}; - paramNames[0] = strdup(paramName); - if(T2ERROR_SUCCESS != getParamValues(paramNames, 1, &valStructs, &valSize)) - { - EVENT_ERROR("Unable to get %s\n", paramName); - return T2ERROR_FAILURE; - } - *paramValue = strdup(valStructs[0]->parameterValue); - free(paramNames[0]); - freeParamValue(valStructs, valSize); - return T2ERROR_SUCCESS; -} -#endif - - -static void rBusInterface_Uninit( ) -{ - rbus_close(bus_handle); -} - -static T2ERROR initMessageBus( ) -{ - // EVENT_DEBUG("%s ++in\n", __FUNCTION__); - T2ERROR status = T2ERROR_SUCCESS; - char* component_id = (char*)CCSP_FIXED_COMP_ID; -#if defined(CCSP_SUPPORT_ENABLED) - char *pCfg = (char*)CCSP_MSG_BUS_CFG; -#endif - - if(RBUS_ENABLED == rbus_checkStatus()) - { - // EVENT_DEBUG("%s:%d, T2:rbus is enabled\n", __func__, __LINE__); - char commonLibName[124] = { '\0' }; - // Bus handles should be unique across the system - if(componentName) - { - snprintf(commonLibName, 124, "%s%s", "t2_lib_", componentName); - } - else - { - snprintf(commonLibName, 124, "%s", component_id); - } - rbusError_t status_rbus = rbus_open((rbusHandle_t*) &bus_handle, commonLibName); - if(status_rbus != RBUS_ERROR_SUCCESS) - { - EVENT_ERROR("%s:%d, init using component name %s failed with error code %d \n", __func__, __LINE__, commonLibName, status); - status = T2ERROR_FAILURE; - } - isRbusEnabled = true; - } -#if defined(CCSP_SUPPORT_ENABLED) - else - { - int ret = 0 ; - ret = CCSP_Message_Bus_Init(component_id, pCfg, &bus_handle, (CCSP_MESSAGE_BUS_MALLOC)Ansc_AllocateMemory_Callback, Ansc_FreeMemory_Callback); - if(ret == -1) - { - EVENT_ERROR("%s:%d, T2:initMessageBus failed\n", __func__, __LINE__); - status = T2ERROR_FAILURE ; - } - else - { - status = T2ERROR_SUCCESS ; - } - } -#endif // CCSP_SUPPORT_ENABLED - // EVENT_DEBUG("%s --out\n", __FUNCTION__); - return status; -} - -static T2ERROR getRbusParameterVal(const char* paramName, char **paramValue) -{ - - rbusError_t ret = RBUS_ERROR_SUCCESS; - rbusValue_t paramValue_t; - rbusValueType_t rbusValueType ; - char *stringValue = NULL; -#if 0 - rbusSetOptions_t opts; - opts.commit = true; -#endif - - if(!bus_handle && T2ERROR_SUCCESS != initMessageBus()) - { - return T2ERROR_FAILURE; - } - - ret = rbus_get(bus_handle, paramName, ¶mValue_t); - if(ret != RBUS_ERROR_SUCCESS) - { - EVENT_ERROR("Unable to get %s\n", paramName); - return T2ERROR_FAILURE; - } - rbusValueType = rbusValue_GetType(paramValue_t); - if(rbusValueType == RBUS_BOOLEAN) - { - if (rbusValue_GetBoolean(paramValue_t)) - { - stringValue = strdup("true"); - } - else - { - stringValue = strdup("false"); - } - } - else - { - stringValue = rbusValue_ToString(paramValue_t, NULL, 0); - } - *paramValue = stringValue; - rbusValue_Release(paramValue_t); - - return T2ERROR_SUCCESS; -} - -T2ERROR getParamValue(const char* paramName, char **paramValue) -{ - T2ERROR ret = T2ERROR_FAILURE ; - if(isRbusEnabled) - { - ret = getRbusParameterVal(paramName, paramValue); - } -#if defined(CCSP_SUPPORT_ENABLED) - else - { - ret = getCCSPParamVal(paramName, paramValue); - } -#endif - - return ret; -} - void *cacheEventToFile(void *arg) { char *telemetry_data = (char *)arg; @@ -414,204 +243,133 @@ static bool initRFC( ) */ int filtered_event_send(const char* data, const char *markerName) { - rbusError_t ret = RBUS_ERROR_SUCCESS; + T2ERROR ret = T2ERROR_SUCCESS; int status = 0 ; EVENT_DEBUG("%s ++in\n", __FUNCTION__); - if(!bus_handle) + + if(!isDbusInitialized()) { - EVENT_ERROR("bus_handle is null .. exiting !!! \n"); - return ret; + EVENT_ERROR("DBUS not initialized .. exiting !!! \n"); + return -1; } - if(isRbusEnabled) + // Filter data from marker list + if(componentName && (0 != strcmp(componentName, T2_SCRIPT_EVENT_COMPONENT))) // Events from scripts needs to be sent without filtering { - - // Filter data from marker list - if(componentName && (0 != strcmp(componentName, T2_SCRIPT_EVENT_COMPONENT))) // Events from scripts needs to be sent without filtering + EVENT_DEBUG("%s markerListMutex lock & get list of marker for component %s \n", __FUNCTION__, componentName); + pthread_mutex_lock(&markerListMutex); + bool isEventingEnabled = false; + if(markerName && eventMarkerMap) { - - EVENT_DEBUG("%s markerListMutex lock & get list of marker for component %s \n", __FUNCTION__, componentName); - pthread_mutex_lock(&markerListMutex); - bool isEventingEnabled = false; - if(markerName && eventMarkerMap) + if(hash_map_get(eventMarkerMap, markerName)) { - if(hash_map_get(eventMarkerMap, markerName)) - { - isEventingEnabled = true; - } - } - else - { - EVENT_DEBUG("%s eventMarkerMap for component %s is empty \n", __FUNCTION__, componentName ); - } - EVENT_DEBUG("%s markerListMutex unlock\n", __FUNCTION__ ); - pthread_mutex_unlock(&markerListMutex); - if(!isEventingEnabled) - { - EVENT_DEBUG("%s markerName %s not found in event list for component %s . Unlock markerListMutex . \n", __FUNCTION__, markerName, componentName); - return status; + isEventingEnabled = true; } } - // End of event filtering - - rbusProperty_t objProperty = NULL ; - rbusValue_t objVal, value; - rbusSetOptions_t options = {0}; - options.commit = true; - - rbusValue_Init(&objVal); - rbusValue_SetString(objVal, data); - rbusProperty_Init(&objProperty, markerName, objVal); - - rbusValue_Init(&value); - rbusValue_SetProperty(value, objProperty); - - EVENT_DEBUG("rbus_set with param [%s] with %s and value [%s]\n", T2_EVENT_PARAM, markerName, data); - ret = rbus_set(bus_handle, T2_EVENT_PARAM, value, &options); - if(ret != RBUS_ERROR_SUCCESS) + else { - EVENT_ERROR("rbus_set Failed for [%s] with error [%d]\n", T2_EVENT_PARAM, ret); - EVENT_DEBUG(" !!! Error !!! rbus_set Failed for [%s] with error [%d]\n", T2_EVENT_PARAM, ret); - status = -1 ; + EVENT_DEBUG("%s eventMarkerMap for component %s is empty \n", __FUNCTION__, componentName ); } - else + EVENT_DEBUG("%s markerListMutex unlock\n", __FUNCTION__ ); + pthread_mutex_unlock(&markerListMutex); + if(!isEventingEnabled) { - status = 0 ; + EVENT_DEBUG("%s markerName %s not found in event list for component %s . Unlock markerListMutex . \n", __FUNCTION__, markerName, componentName); + return status; } - // Release all rbus data structures - rbusValue_Release(value); - rbusProperty_Release(objProperty); - rbusValue_Release(objVal); + } + // End of event filtering + EVENT_DEBUG("dbusPublishEvent with marker [%s] and value [%s]\n", markerName, data); + ret = dbusPublishEvent(markerName, data); + if(ret != T2ERROR_SUCCESS) + { + EVENT_ERROR("dbusPublishEvent Failed for marker [%s] with error [%d]\n", markerName, ret); + EVENT_DEBUG(" !!! Error !!! dbusPublishEvent Failed for marker [%s] with error [%d]\n", markerName, ret); + status = -1 ; } -#if defined(CCSP_SUPPORT_ENABLED) else { - int eventDataLen = strlen(markerName) + strlen(data) + strlen(MESSAGE_DELIMITER) + 1; - char* buffer = (char*) malloc(eventDataLen * sizeof(char)); - if(buffer) - { - snprintf(buffer, eventDataLen, "%s%s%s", markerName, MESSAGE_DELIMITER, data); - ret = CcspBaseIf_SendTelemetryDataSignal(bus_handle, buffer); - if(ret != CCSP_SUCCESS) - { - status = -1; - } - free(buffer); - } - else - { - EVENT_ERROR("Unable to allocate meory for event [%s]\n", markerName); - status = -1 ; - } + status = 0 ; } -#endif // CCSP_SUPPORT_ENABLED + EVENT_DEBUG("%s --out with status %d \n", __FUNCTION__, status); return status; } /** - * Receives an rbus object as value which conatins a list of rbusPropertyObject - * rbusProperty name will the eventName and value will be null + * Get marker list from T2 daemon via DBUS */ -static T2ERROR doPopulateEventMarkerList( ) +static T2ERROR doPopulateEventMarkerList(void) { - - T2ERROR status = T2ERROR_SUCCESS; - char deNameSpace[1][124] = {{ '\0' }}; - if(!isRbusEnabled) - { - return T2ERROR_SUCCESS; - } - EVENT_DEBUG("%s ++in\n", __FUNCTION__); - rbusError_t ret = RBUS_ERROR_SUCCESS; - rbusValue_t paramValue_t; - - if(!bus_handle && T2ERROR_SUCCESS != initMessageBus()) + T2ERROR status = T2ERROR_SUCCESS; + + if(!isDbusInitialized()) { - EVENT_ERROR("Unable to get message bus handles \n"); - EVENT_DEBUG("%s --out\n", __FUNCTION__); + EVENT_ERROR("DBUS not initialized\n"); return T2ERROR_FAILURE; } - - snprintf(deNameSpace[0], 124, "%s%s%s", T2_ROOT_PARAMETER, componentName, T2_EVENT_LIST_PARAM_SUFFIX); - EVENT_DEBUG("rbus mode : Query marker list with data element = %s \n", deNameSpace[0]); - + pthread_mutex_lock(&markerListMutex); EVENT_DEBUG("Lock markerListMutex & Clean up eventMarkerMap \n"); + if(eventMarkerMap != NULL) { hash_map_destroy(eventMarkerMap, free); eventMarkerMap = NULL; } - - ret = rbus_get(bus_handle, deNameSpace[0], ¶mValue_t); - if(ret != RBUS_ERROR_SUCCESS) - { - EVENT_ERROR("rbus mode : No event list configured in profiles %s and return value %d\n", deNameSpace[0], ret); - pthread_mutex_unlock(&markerListMutex); - EVENT_DEBUG("rbus mode : No event list configured in profiles %s and return value %d. Unlock markerListMutex\n", deNameSpace[0], ret); - EVENT_DEBUG("%s --out\n", __FUNCTION__); - return T2ERROR_SUCCESS; - } - - rbusValueType_t type_t = rbusValue_GetType(paramValue_t); - if(type_t != RBUS_OBJECT) + + // Get marker list via DBUS method call + char* markerListStr = NULL; + status = dbusGetMarkerList(componentName, &markerListStr); + + if(status != T2ERROR_SUCCESS || !markerListStr) { - EVENT_ERROR("rbus mode : Unexpected data object received for %s get query \n", deNameSpace[0]); - rbusValue_Release(paramValue_t); + EVENT_ERROR("dbusGetMarkerList failed for component %s\n", componentName); pthread_mutex_unlock(&markerListMutex); EVENT_DEBUG("Unlock markerListMutex\n"); EVENT_DEBUG("%s --out\n", __FUNCTION__); return T2ERROR_FAILURE; } - - rbusObject_t objectValue = rbusValue_GetObject(paramValue_t); - if(objectValue) - { - eventMarkerMap = hash_map_create(); - rbusProperty_t rbusPropertyList = rbusObject_GetProperties(objectValue); - EVENT_DEBUG("\t rbus mode : Update event map for component %s with below events : \n", componentName); - while(NULL != rbusPropertyList) + + // Parse marker list string (format: comma-separated marker names) + eventMarkerMap = hash_map_create(); + EVENT_DEBUG("\t Update event map for component %s with below events : \n", componentName); + + char* markerListCopy = strdup(markerListStr); + char* token = strtok(markerListCopy, ","); + while(token != NULL) + { + // Trim leading whitespace + while(*token == ' ' || *token == '\t') token++; + // Trim trailing whitespace + char* end = token + strlen(token) - 1; + while(end > token && (*end == ' ' || *end == '\t' || *end == '\n')) { + *end = '\0'; + end--; + } + + if(strlen(token) > 0) { - const char* eventname = rbusProperty_GetName(rbusPropertyList); - if(eventname && strlen(eventname) > 0) - { - EVENT_DEBUG("\t %s\n", eventname); - hash_map_put(eventMarkerMap, (void*) strdup(eventname), (void*) strdup(eventname), free); - } - rbusPropertyList = rbusProperty_GetNext(rbusPropertyList); + EVENT_DEBUG("\t %s\n", token); + hash_map_put(eventMarkerMap, (void*)strdup(token), (void*)strdup(token), free); } + token = strtok(NULL, ","); } - else - { - EVENT_ERROR("rbus mode : No configured event markers for %s \n", componentName); - } - EVENT_DEBUG("Unlock markerListMutex\n"); + + free(markerListCopy); + free(markerListStr); pthread_mutex_unlock(&markerListMutex); - rbusValue_Release(paramValue_t); + EVENT_DEBUG("Unlock markerListMutex\n"); EVENT_DEBUG("%s --out\n", __FUNCTION__); return status; - } -static void rbusEventReceiveHandler(rbusHandle_t handle, rbusEvent_t const* event, rbusEventSubscription_t* subscription) +static void dbusProfileUpdateHandler(void) { - (void)handle;//To fix compiler warning. - (void)subscription;//To fix compiler warning. - const char* eventName = event->name; - if(eventName) - { - if(0 == strcmp(eventName, T2_PROFILE_UPDATED_NOTIFY)) - { - doPopulateEventMarkerList(); - } - } - else - { - EVENT_ERROR("eventName is null \n"); - } + EVENT_DEBUG("Profile update notification received via DBUS\n"); + doPopulateEventMarkerList(); } static bool isCachingRequired( ) @@ -642,28 +400,20 @@ static bool isCachingRequired( ) // Always check for t2 is ready to accept events. Shutdown target can bring down t2 process at runtime uint32_t t2ReadyStatus; - rbusError_t retVal = RBUS_ERROR_SUCCESS; + T2ERROR retVal = dbusGetOperationalStatus(&t2ReadyStatus); - retVal = rbus_getUint(bus_handle, T2_OPERATIONAL_STATUS, &t2ReadyStatus); - - if(retVal != RBUS_ERROR_SUCCESS) + if(retVal != T2ERROR_SUCCESS) { return true; } - else - { - EVENT_DEBUG("value for %s is : %d\n", T2_OPERATIONAL_STATUS, t2ReadyStatus); - if((t2ReadyStatus & T2_STATE_COMPONENT_READY) == 0) + + EVENT_DEBUG("Operational status: %d\n", t2ReadyStatus); + if((t2ReadyStatus & T2_STATE_COMPONENT_READY) == 0) { return true; } } - if(!isRbusEnabled) - { - isT2Ready = true; - } - if(!isT2Ready) { if(componentName && (0 != strcmp(componentName, "telemetry_client"))) @@ -675,13 +425,14 @@ static bool isCachingRequired( ) } else { - rbusError_t ret = RBUS_ERROR_SUCCESS; + // Fetch marker list and subscribe to profile updates doPopulateEventMarkerList(); - ret = rbusEvent_Subscribe(bus_handle, T2_PROFILE_UPDATED_NOTIFY, rbusEventReceiveHandler, "T2Event", 0); - if(ret != RBUS_ERROR_SUCCESS) + + T2ERROR ret = dbusSubscribeProfileUpdate(dbusProfileUpdateHandler); + if(ret != T2ERROR_SUCCESS) { - EVENT_ERROR("Unable to subscribe to event %s with rbus error code : %d\n", T2_PROFILE_UPDATED_NOTIFY, ret); - EVENT_DEBUG("Unable to subscribe to event %s with rbus error code : %d\n", T2_PROFILE_UPDATED_NOTIFY, ret); + EVENT_ERROR("Unable to subscribe to ProfileUpdate signal with error : %d\n", ret); + EVENT_DEBUG("Unable to subscribe to ProfileUpdate signal with error : %d\n", ret); } isT2Ready = true; } @@ -734,6 +485,13 @@ static int report_or_cache_data(char* telemetry_data, const char* markerName) void t2_init(char *component) { componentName = strdup(component); + + // Initialize DBUS connection + T2ERROR ret = dBusInterface_Init(componentName); + if(ret != T2ERROR_SUCCESS) + { + EVENT_ERROR(\"DBUS initialization failed for %s\\n\", componentName); + } } void t2_uninit(void) @@ -743,12 +501,10 @@ void t2_uninit(void) free(componentName); componentName = NULL ; } - - if(isRbusEnabled) - { - rBusInterface_Uninit(); - } - + + // Uninitialize DBUS + dBusInterface_Uninit(); + uninitMutex(); } From e66495d2b484526d8624254b79d8771a0108ef6a Mon Sep 17 00:00:00 2001 From: Muhammed rafi Date: Sat, 17 Jan 2026 01:43:22 +0000 Subject: [PATCH 02/23] event send change --- source/commonlib/Makefile.am | 6 +- .../commonlib/telemetry_busmessage_sender.c | 481 +++++++++++++++++- 2 files changed, 472 insertions(+), 15 deletions(-) diff --git a/source/commonlib/Makefile.am b/source/commonlib/Makefile.am index bb9cea25..adea4de2 100644 --- a/source/commonlib/Makefile.am +++ b/source/commonlib/Makefile.am @@ -25,21 +25,20 @@ lib_LTLIBRARIES = libtelemetry_msgsender.la libtelemetry_msgsender_la_SOURCES = telemetry_busmessage_sender.c libtelemetry_msgsender_la_LDFLAGS = -shared -libtelemetry_msgsender_la_LIBADD = -ldbus-1 ${top_builddir}/source/utils/libt2utils.la ${top_builddir}/source/ccspinterface/libccspinterface.la +libtelemetry_msgsender_la_LIBADD = -ldbus-1 ${top_builddir}/source/utils/libt2utils.la if ENABLE_CCSP_SUPPORT libtelemetry_msgsender_la_LIBADD += -lccsp_common endif libtelemetry_msgsender_la_CPPFLAGS = -fPIC -I${PKG_CONFIG_SYSROOT_DIR}$(includedir)/dbus-1.0 \\ -I${PKG_CONFIG_SYSROOT_DIR}$(libdir)/dbus-1.0/include \\ -I${top_srcdir}/source/utils \\ - -I${top_srcdir}/source/ccspinterface \\ -I${top_srcdir}/include libtelemetry_msgsender_la_DEPENDENCIES = ${top_builddir}/source/utils/libt2utils.la bin_PROGRAMS = telemetry2_0_client telemetry2_0_client_SOURCES = telemetry_client.c telemetry_busmessage_sender.c -telemetry2_0_client_LDADD = -ldbus-1 ${top_builddir}/source/utils/libt2utils.la ${top_builddir}/source/ccspinterface/libccspinterface.la -lpthread +telemetry2_0_client_LDADD = -ldbus-1 ${top_builddir}/source/utils/libt2utils.la -lpthread if ENABLE_CCSP_SUPPORT telemetry2_0_client_LDADD += -lccsp_common endif @@ -47,6 +46,5 @@ telemetry2_0_client_CPPFLAGS = -fPIC -I${PKG_CONFIG_SYSROOT_DIR}$(includedir)/db -I${PKG_CONFIG_SYSROOT_DIR}$(libdir)/dbus-1.0/include \\ -I${PKG_CONFIG_SYSROOT_DIR}$(includedir)/ccsp \\ -I${top_srcdir}/source/utils \\ - -I${top_srcdir}/source/ccspinterface \\ -I${top_srcdir}/include telemetry2_0_client_DEPENDENCIES = ${top_builddir}/source/utils/libt2utils.la diff --git a/source/commonlib/telemetry_busmessage_sender.c b/source/commonlib/telemetry_busmessage_sender.c index 3a0b9211..751dd28f 100644 --- a/source/commonlib/telemetry_busmessage_sender.c +++ b/source/commonlib/telemetry_busmessage_sender.c @@ -29,7 +29,6 @@ #include #include "telemetry_busmessage_sender.h" -#include "../ccspinterface/dbusInterface.h" #include "t2collection.h" #include "vector.h" #include "telemetry2_0.h" @@ -42,6 +41,27 @@ #define T2_SCRIPT_EVENT_COMPONENT "telemetry_client" #define SENDER_LOG_FILE "/tmp/t2_sender_debug.log" +/* D-Bus Service Configuration */ +#define T2_DBUS_SERVICE_NAME "telemetry.t2" +#define T2_DBUS_OBJECT_PATH "/telemetry/t2" +#define T2_DBUS_INTERFACE_NAME "telemetry.t2.interface" +#define T2_DBUS_SIGNAL_EVENT "TelemetryEvent" +#define T2_DBUS_SIGNAL_PROFILE_UPDATE "ProfileUpdate" +#define T2_DBUS_DEFAULT_TIMEOUT_MS 5000 + +/* D-Bus Connection Handle */ +typedef struct { + DBusConnection *connection; + char *unique_name; + bool is_initialized; +} T2DbusHandle_t; + +static T2DbusHandle_t t2dbus_handle = {NULL, NULL, false}; +static void (*profileUpdateCallback)(void) = NULL; +static pthread_mutex_t dbusMutex = PTHREAD_MUTEX_INITIALIZER; +static pthread_t dbusListenerThread; +static bool stopListenerThread = false; + static char *componentName = NULL; static bool isRFCT2Enable = false ; static bool isT2Ready = false; @@ -93,6 +113,426 @@ static void EVENT_DEBUG(char* format, ...) } +/** + * @brief Check if D-Bus is initialized + */ +static bool isDbusInitialized(void) { + return t2dbus_handle.is_initialized; +} + +/** + * @brief D-Bus filter function for incoming messages + */ +static DBusHandlerResult dbusMessageFilter(DBusConnection *connection, + DBusMessage *message, + void *user_data) { + (void)connection; + (void)user_data; + + if (dbus_message_is_signal(message, T2_DBUS_INTERFACE_NAME, T2_DBUS_SIGNAL_PROFILE_UPDATE)) { + EVENT_DEBUG("Received ProfileUpdate signal\n"); + if (profileUpdateCallback) { + profileUpdateCallback(); + } + return DBUS_HANDLER_RESULT_HANDLED; + } + + return DBUS_HANDLER_RESULT_NOT_YET_HANDLED; +} + +/** + * @brief D-Bus listener thread function + */ +static void* dbusListenerThreadFunc(void *arg) { + (void)arg; + + EVENT_DEBUG("%s ++in\n", __FUNCTION__); + + while (!stopListenerThread && t2dbus_handle.connection) { + /* Process messages with timeout */ + dbus_connection_read_write_dispatch(t2dbus_handle.connection, 100); + } + + EVENT_DEBUG("%s --out\n", __FUNCTION__); + return NULL; +} + +/** + * @brief Initialize D-Bus connection + */ +static T2ERROR dBusInterface_Init(const char *component_name) { + EVENT_DEBUG("%s ++in\n", __FUNCTION__); + + pthread_mutex_lock(&dbusMutex); + + if (t2dbus_handle.is_initialized) { + EVENT_DEBUG("D-Bus interface already initialized\n"); + pthread_mutex_unlock(&dbusMutex); + return T2ERROR_SUCCESS; + } + + DBusError error; + dbus_error_init(&error); + + /* Connect to session bus for local IPC */ + t2dbus_handle.connection = dbus_bus_get(DBUS_BUS_SESSION, &error); + if (dbus_error_is_set(&error)) { + EVENT_ERROR("D-Bus connection error: %s\n", error.message); + dbus_error_free(&error); + pthread_mutex_unlock(&dbusMutex); + return T2ERROR_FAILURE; + } + + if (!t2dbus_handle.connection) { + EVENT_ERROR("Failed to get D-Bus connection\n"); + pthread_mutex_unlock(&dbusMutex); + return T2ERROR_FAILURE; + } + + /* Request well-known name */ + char service_name[256]; + if (component_name) { + snprintf(service_name, sizeof(service_name), "%s.%s", + T2_DBUS_SERVICE_NAME, component_name); + } else { + snprintf(service_name, sizeof(service_name), "%s", T2_DBUS_SERVICE_NAME); + } + + int ret = dbus_bus_request_name(t2dbus_handle.connection, service_name, + DBUS_NAME_FLAG_REPLACE_EXISTING, &error); + if (dbus_error_is_set(&error)) { + EVENT_ERROR("D-Bus name request error: %s\n", error.message); + dbus_error_free(&error); + dbus_connection_unref(t2dbus_handle.connection); + t2dbus_handle.connection = NULL; + pthread_mutex_unlock(&dbusMutex); + return T2ERROR_FAILURE; + } + + if (ret != DBUS_REQUEST_NAME_REPLY_PRIMARY_OWNER) { + EVENT_DEBUG("Not primary owner of D-Bus name\n"); + } + + /* Store unique name */ + t2dbus_handle.unique_name = strdup(dbus_bus_get_unique_name(t2dbus_handle.connection)); + + /* Add message filter */ + dbus_connection_add_filter(t2dbus_handle.connection, dbusMessageFilter, NULL, NULL); + + t2dbus_handle.is_initialized = true; + + /* Start listener thread */ + stopListenerThread = false; + if (pthread_create(&dbusListenerThread, NULL, dbusListenerThreadFunc, NULL) != 0) { + EVENT_ERROR("Failed to create D-Bus listener thread\n"); + dbus_connection_remove_filter(t2dbus_handle.connection, dbusMessageFilter, NULL); + dbus_connection_unref(t2dbus_handle.connection); + if (t2dbus_handle.unique_name) { + free(t2dbus_handle.unique_name); + t2dbus_handle.unique_name = NULL; + } + t2dbus_handle.connection = NULL; + t2dbus_handle.is_initialized = false; + pthread_mutex_unlock(&dbusMutex); + return T2ERROR_FAILURE; + } + + pthread_mutex_unlock(&dbusMutex); + + EVENT_DEBUG("D-Bus interface initialized successfully with name: %s\n", service_name); + EVENT_DEBUG("%s --out\n", __FUNCTION__); + + return T2ERROR_SUCCESS; +} + +/** + * @brief Uninitialize D-Bus interface + */ +static void dBusInterface_Uninit(void) { + EVENT_DEBUG("%s ++in\n", __FUNCTION__); + + pthread_mutex_lock(&dbusMutex); + + if (!t2dbus_handle.is_initialized) { + pthread_mutex_unlock(&dbusMutex); + return; + } + + /* Stop listener thread */ + stopListenerThread = true; + pthread_mutex_unlock(&dbusMutex); + + if (dbusListenerThread) { + pthread_join(dbusListenerThread, NULL); + } + + pthread_mutex_lock(&dbusMutex); + + /* Clean up D-Bus connection */ + if (t2dbus_handle.connection) { + dbus_connection_remove_filter(t2dbus_handle.connection, dbusMessageFilter, NULL); + dbus_connection_unref(t2dbus_handle.connection); + t2dbus_handle.connection = NULL; + } + + if (t2dbus_handle.unique_name) { + free(t2dbus_handle.unique_name); + t2dbus_handle.unique_name = NULL; + } + + t2dbus_handle.is_initialized = false; + + pthread_mutex_unlock(&dbusMutex); + + EVENT_DEBUG("%s --out\n", __FUNCTION__); +} + +/** + * @brief Publish telemetry event via D-Bus signal + */ +static T2ERROR dbusPublishEvent(const char* eventName, const char* eventValue) { + EVENT_DEBUG("%s ++in\n", __FUNCTION__); + + if (!eventName || !eventValue) { + EVENT_ERROR("Invalid event parameters\n"); + return T2ERROR_INVALID_ARGS; + } + + EVENT_DEBUG("Publishing event - Name: %s, Value length: %zu\n", eventName, strlen(eventValue)); + + if (!t2dbus_handle.is_initialized) { + EVENT_ERROR("D-Bus not initialized\n"); + return T2ERROR_INTERNAL_ERROR; + } + + EVENT_DEBUG("D-Bus handle initialized, connection: %p\n", (void*)t2dbus_handle.connection); + + DBusMessage *signal = NULL; + + /* Create signal */ + EVENT_DEBUG("Creating D-Bus signal on path: %s, interface: %s\n", T2_DBUS_OBJECT_PATH, T2_DBUS_INTERFACE_NAME); + signal = dbus_message_new_signal(T2_DBUS_OBJECT_PATH, + T2_DBUS_INTERFACE_NAME, + T2_DBUS_SIGNAL_EVENT); + if (!signal) { + EVENT_ERROR("Failed to create D-Bus signal\n"); + return T2ERROR_FAILURE; + } + + EVENT_DEBUG("D-Bus signal created successfully, appending arguments\n"); + + /* Append arguments */ + if (!dbus_message_append_args(signal, + DBUS_TYPE_STRING, &eventName, + DBUS_TYPE_STRING, &eventValue, + DBUS_TYPE_INVALID)) { + EVENT_ERROR("Failed to append signal arguments\n"); + dbus_message_unref(signal); + return T2ERROR_FAILURE; + } + + EVENT_DEBUG("Arguments appended successfully to signal\n"); + + /* Send signal */ + EVENT_DEBUG("Sending D-Bus signal to connection\n"); + if (!dbus_connection_send(t2dbus_handle.connection, signal, NULL)) { + EVENT_ERROR("Failed to send D-Bus signal\n"); + dbus_message_unref(signal); + return T2ERROR_FAILURE; + } + + EVENT_DEBUG("D-Bus signal sent, flushing connection\n"); + dbus_connection_flush(t2dbus_handle.connection); + EVENT_DEBUG("D-Bus connection flushed successfully\n"); + dbus_message_unref(signal); + + EVENT_DEBUG("Published event: %s = %s\n", eventName, eventValue); + EVENT_DEBUG("%s --out\n", __FUNCTION__); + + return T2ERROR_SUCCESS; +} + +/** + * @brief Get marker list for component via D-Bus method call + */ +static T2ERROR dbusGetMarkerList(const char* component, char** markerList) { + EVENT_DEBUG("%s ++in\n", __FUNCTION__); + + if (!component || !markerList) { + EVENT_ERROR("Invalid arguments\n"); + return T2ERROR_INVALID_ARGS; + } + + if (!t2dbus_handle.is_initialized) { + EVENT_ERROR("D-Bus not initialized\n"); + return T2ERROR_NOT_INITIALIZED; + } + + DBusMessage *msg = NULL; + DBusMessage *reply = NULL; + DBusError error; + dbus_error_init(&error); + + /* Create method call message */ + msg = dbus_message_new_method_call(T2_DBUS_SERVICE_NAME, + T2_DBUS_OBJECT_PATH, + T2_DBUS_INTERFACE_NAME, + "GetMarkerList"); + if (!msg) { + EVENT_ERROR("Failed to create method call message\n"); + return T2ERROR_FAILURE; + } + + /* Append component name */ + if (!dbus_message_append_args(msg, DBUS_TYPE_STRING, &component, DBUS_TYPE_INVALID)) { + EVENT_ERROR("Failed to append arguments\n"); + dbus_message_unref(msg); + return T2ERROR_FAILURE; + } + + /* Send message and get reply */ + reply = dbus_connection_send_with_reply_and_block(t2dbus_handle.connection, msg, + T2_DBUS_DEFAULT_TIMEOUT_MS, &error); + dbus_message_unref(msg); + + if (dbus_error_is_set(&error)) { + EVENT_ERROR("D-Bus method call failed: %s\n", error.message); + dbus_error_free(&error); + return T2ERROR_FAILURE; + } + + if (!reply) { + EVENT_ERROR("No reply received\n"); + return T2ERROR_FAILURE; + } + + /* Parse reply - expecting a string containing the marker list */ + char *value = NULL; + if (dbus_message_get_args(reply, &error, + DBUS_TYPE_STRING, &value, + DBUS_TYPE_INVALID)) { + *markerList = strdup(value); + EVENT_DEBUG("Retrieved marker list for %s\n", component); + } else { + EVENT_ERROR("Failed to parse reply: %s\n", error.message); + dbus_error_free(&error); + dbus_message_unref(reply); + return T2ERROR_FAILURE; + } + + dbus_message_unref(reply); + + EVENT_DEBUG("%s --out\n", __FUNCTION__); + return T2ERROR_SUCCESS; +} + +/** + * @brief Get operational status via D-Bus method call + */ +static T2ERROR dbusGetOperationalStatus(uint32_t* status) { + EVENT_DEBUG("%s ++in\n", __FUNCTION__); + + if (!status) { + EVENT_ERROR("Invalid arguments\n"); + return T2ERROR_INVALID_ARGS; + } + + if (!t2dbus_handle.is_initialized) { + EVENT_ERROR("D-Bus not initialized\n"); + return T2ERROR_NOT_INITIALIZED; + } + + DBusMessage *msg = NULL; + DBusMessage *reply = NULL; + DBusError error; + dbus_error_init(&error); + + /* Create method call message */ + msg = dbus_message_new_method_call(T2_DBUS_SERVICE_NAME, + T2_DBUS_OBJECT_PATH, + T2_DBUS_INTERFACE_NAME, + "GetOperationalStatus"); + if (!msg) { + EVENT_ERROR("Failed to create method call message\n"); + return T2ERROR_FAILURE; + } + + /* Send message and get reply */ + reply = dbus_connection_send_with_reply_and_block(t2dbus_handle.connection, msg, + T2_DBUS_DEFAULT_TIMEOUT_MS, &error); + dbus_message_unref(msg); + + if (dbus_error_is_set(&error)) { + EVENT_ERROR("D-Bus method call failed: %s\n", error.message); + dbus_error_free(&error); + return T2ERROR_FAILURE; + } + + if (!reply) { + EVENT_ERROR("No reply received\n"); + return T2ERROR_FAILURE; + } + + /* Parse reply - expecting UINT32 */ + if (dbus_message_get_args(reply, &error, + DBUS_TYPE_UINT32, status, + DBUS_TYPE_INVALID)) { + EVENT_DEBUG("Retrieved operational status: %u\n", *status); + } else { + EVENT_ERROR("Failed to parse reply: %s\n", error.message); + dbus_error_free(&error); + dbus_message_unref(reply); + return T2ERROR_FAILURE; + } + + dbus_message_unref(reply); + + EVENT_DEBUG("%s --out\n", __FUNCTION__); + return T2ERROR_SUCCESS; +} + +/** + * @brief Subscribe to profile update notifications + */ +static T2ERROR dbusSubscribeProfileUpdate(void (*callback)(void)) { + EVENT_DEBUG("%s ++in\n", __FUNCTION__); + + if (!callback) { + EVENT_ERROR("Invalid callback\n"); + return T2ERROR_INVALID_ARGS; + } + + if (!t2dbus_handle.is_initialized) { + EVENT_ERROR("D-Bus not initialized\n"); + return T2ERROR_NOT_INITIALIZED; + } + + /* Store callback */ + profileUpdateCallback = callback; + + /* Subscribe to ProfileUpdate signal */ + char rule[512]; + DBusError error; + dbus_error_init(&error); + + snprintf(rule, sizeof(rule), + "type='signal',interface='%s',member='%s'", + T2_DBUS_INTERFACE_NAME, T2_DBUS_SIGNAL_PROFILE_UPDATE); + + dbus_bus_add_match(t2dbus_handle.connection, rule, &error); + + if (dbus_error_is_set(&error)) { + EVENT_ERROR("Failed to add match rule: %s\n", error.message); + dbus_error_free(&error); + return T2ERROR_FAILURE; + } + + EVENT_DEBUG("Subscribed to ProfileUpdate signal\n"); + EVENT_DEBUG("%s --out\n", __FUNCTION__); + + return T2ERROR_SUCCESS; +} + static void initMutex() { pthread_mutex_lock(&initMtx); @@ -250,20 +690,27 @@ int filtered_event_send(const char* data, const char *markerName) if(!isDbusInitialized()) { EVENT_ERROR("DBUS not initialized .. exiting !!! \n"); - return -1; + return ret; } // Filter data from marker list if(componentName && (0 != strcmp(componentName, T2_SCRIPT_EVENT_COMPONENT))) // Events from scripts needs to be sent without filtering { EVENT_DEBUG("%s markerListMutex lock & get list of marker for component %s \n", __FUNCTION__, componentName); + EVENT_DEBUG("Filtering event: checking if marker '%s' is in allowed list\n", markerName); pthread_mutex_lock(&markerListMutex); bool isEventingEnabled = false; if(markerName && eventMarkerMap) { + EVENT_DEBUG("Searching marker '%s' in eventMarkerMap\n", markerName); if(hash_map_get(eventMarkerMap, markerName)) { isEventingEnabled = true; + EVENT_DEBUG("Marker '%s' found in allowed list, event enabled\n", markerName); + } + else + { + EVENT_DEBUG("Marker '%s' NOT found in allowed list, event will be filtered\n", markerName); } } else @@ -275,12 +722,18 @@ int filtered_event_send(const char* data, const char *markerName) if(!isEventingEnabled) { EVENT_DEBUG("%s markerName %s not found in event list for component %s . Unlock markerListMutex . \n", __FUNCTION__, markerName, componentName); + EVENT_DEBUG("Event FILTERED OUT - marker '%s' not enabled for component '%s'\n", markerName, componentName); return status; } + EVENT_DEBUG("Event ALLOWED - marker '%s' passed filter for component '%s'\n", markerName, componentName); + } + else + { + EVENT_DEBUG("Skipping filter - component is '%s' (script events or no component)\n", componentName ? componentName : "NULL"); } // End of event filtering - EVENT_DEBUG("dbusPublishEvent with marker [%s] and value [%s]\n", markerName, data); + EVENT_DEBUG("Calling dbusPublishEvent with marker [%s] and value [%s]\n", markerName, data); ret = dbusPublishEvent(markerName, data); if(ret != T2ERROR_SUCCESS) { @@ -338,6 +791,7 @@ static T2ERROR doPopulateEventMarkerList(void) EVENT_DEBUG("\t Update event map for component %s with below events : \n", componentName); char* markerListCopy = strdup(markerListStr); + EVENT_DEBUG("Marker List String : %s \n", markerListStr); char* token = strtok(markerListCopy, ","); while(token != NULL) { @@ -406,12 +860,13 @@ static bool isCachingRequired( ) { return true; } - - EVENT_DEBUG("Operational status: %d\n", t2ReadyStatus); - if((t2ReadyStatus & T2_STATE_COMPONENT_READY) == 0) - { - return true; - } + else + { + EVENT_DEBUG("Operational status: %d\n", t2ReadyStatus); + if((t2ReadyStatus & T2_STATE_COMPONENT_READY) == 0) + { + return true; + } } if(!isT2Ready) @@ -450,9 +905,12 @@ static int report_or_cache_data(char* telemetry_data, const char* markerName) { int ret = 0; pthread_t tid; + EVENT_DEBUG("%s ++in - marker: %s, data length: %zu\n", __FUNCTION__, markerName, strlen(telemetry_data)); pthread_mutex_lock(&eventMutex); + EVENT_DEBUG("Checking if caching is required...\n"); if(isCachingRequired()) { + EVENT_DEBUG("Caching IS required - will cache event to file\n"); EVENT_DEBUG("Caching the event : %s \n", telemetry_data); int eventDataLen = strlen(markerName) + strlen(telemetry_data) + strlen(MESSAGE_DELIMITER) + 1; char* buffer = (char*) malloc(eventDataLen * sizeof(char)); @@ -467,9 +925,10 @@ static int report_or_cache_data(char* telemetry_data, const char* markerName) } pthread_mutex_unlock(&eventMutex); + EVENT_DEBUG("Caching NOT required - will send event via D-Bus\n"); if(isT2Ready) { - // EVENT_DEBUG("T2: Sending event : %s\n", telemetry_data); + EVENT_DEBUG("T2 is ready - sending event via D-Bus: marker=%s\n", markerName); ret = filtered_event_send(telemetry_data, markerName); if(0 != ret) { @@ -490,7 +949,7 @@ void t2_init(char *component) T2ERROR ret = dBusInterface_Init(componentName); if(ret != T2ERROR_SUCCESS) { - EVENT_ERROR(\"DBUS initialization failed for %s\\n\", componentName); + EVENT_ERROR("DBUS initialization failed for %s\n", componentName); } } From 432070d1cf96b6ae6eb10d6cd5fec8f571ba6ad2 Mon Sep 17 00:00:00 2001 From: Muhammed rafi Date: Sat, 17 Jan 2026 02:55:45 +0000 Subject: [PATCH 03/23] build fix --- source/commonlib/Makefile.am | 14 ++--- .../commonlib/telemetry_busmessage_sender.c | 52 +++++++++---------- 2 files changed, 33 insertions(+), 33 deletions(-) diff --git a/source/commonlib/Makefile.am b/source/commonlib/Makefile.am index adea4de2..bdff690b 100644 --- a/source/commonlib/Makefile.am +++ b/source/commonlib/Makefile.am @@ -29,9 +29,9 @@ libtelemetry_msgsender_la_LIBADD = -ldbus-1 ${top_builddir}/source/utils/libt2ut if ENABLE_CCSP_SUPPORT libtelemetry_msgsender_la_LIBADD += -lccsp_common endif -libtelemetry_msgsender_la_CPPFLAGS = -fPIC -I${PKG_CONFIG_SYSROOT_DIR}$(includedir)/dbus-1.0 \\ - -I${PKG_CONFIG_SYSROOT_DIR}$(libdir)/dbus-1.0/include \\ - -I${top_srcdir}/source/utils \\ +libtelemetry_msgsender_la_CPPFLAGS = -fPIC -I/usr/include/dbus-1.0 \ + -I/usr/lib/x86_64-linux-gnu/dbus-1.0/include \ + -I${top_srcdir}/source/utils \ -I${top_srcdir}/include libtelemetry_msgsender_la_DEPENDENCIES = ${top_builddir}/source/utils/libt2utils.la @@ -42,9 +42,9 @@ telemetry2_0_client_LDADD = -ldbus-1 ${top_builddir}/source/utils/libt2utils.la if ENABLE_CCSP_SUPPORT telemetry2_0_client_LDADD += -lccsp_common endif -telemetry2_0_client_CPPFLAGS = -fPIC -I${PKG_CONFIG_SYSROOT_DIR}$(includedir)/dbus-1.0 \\ - -I${PKG_CONFIG_SYSROOT_DIR}$(libdir)/dbus-1.0/include \\ - -I${PKG_CONFIG_SYSROOT_DIR}$(includedir)/ccsp \\ - -I${top_srcdir}/source/utils \\ +telemetry2_0_client_CPPFLAGS = -fPIC -I/usr/include/dbus-1.0 \ + -I/usr/lib/x86_64-linux-gnu/dbus-1.0/include \ + -I/usr/include/ccsp \ + -I${top_srcdir}/source/utils \ -I${top_srcdir}/include telemetry2_0_client_DEPENDENCIES = ${top_builddir}/source/utils/libt2utils.la diff --git a/source/commonlib/telemetry_busmessage_sender.c b/source/commonlib/telemetry_busmessage_sender.c index 751dd28f..67e200a3 100644 --- a/source/commonlib/telemetry_busmessage_sender.c +++ b/source/commonlib/telemetry_busmessage_sender.c @@ -365,7 +365,7 @@ static T2ERROR dbusGetMarkerList(const char* component, char** markerList) { if (!t2dbus_handle.is_initialized) { EVENT_ERROR("D-Bus not initialized\n"); - return T2ERROR_NOT_INITIALIZED; + return T2ERROR_INTERNAL_ERROR; } DBusMessage *msg = NULL; @@ -394,18 +394,18 @@ static T2ERROR dbusGetMarkerList(const char* component, char** markerList) { reply = dbus_connection_send_with_reply_and_block(t2dbus_handle.connection, msg, T2_DBUS_DEFAULT_TIMEOUT_MS, &error); dbus_message_unref(msg); - + if (dbus_error_is_set(&error)) { EVENT_ERROR("D-Bus method call failed: %s\n", error.message); dbus_error_free(&error); return T2ERROR_FAILURE; } - + if (!reply) { EVENT_ERROR("No reply received\n"); return T2ERROR_FAILURE; } - + /* Parse reply - expecting a string containing the marker list */ char *value = NULL; if (dbus_message_get_args(reply, &error, @@ -419,9 +419,9 @@ static T2ERROR dbusGetMarkerList(const char* component, char** markerList) { dbus_message_unref(reply); return T2ERROR_FAILURE; } - + dbus_message_unref(reply); - + EVENT_DEBUG("%s --out\n", __FUNCTION__); return T2ERROR_SUCCESS; } @@ -436,12 +436,12 @@ static T2ERROR dbusGetOperationalStatus(uint32_t* status) { EVENT_ERROR("Invalid arguments\n"); return T2ERROR_INVALID_ARGS; } - + if (!t2dbus_handle.is_initialized) { EVENT_ERROR("D-Bus not initialized\n"); - return T2ERROR_NOT_INITIALIZED; + return T2ERROR_INTERNAL_ERROR; } - + DBusMessage *msg = NULL; DBusMessage *reply = NULL; DBusError error; @@ -501,12 +501,12 @@ static T2ERROR dbusSubscribeProfileUpdate(void (*callback)(void)) { EVENT_ERROR("Invalid callback\n"); return T2ERROR_INVALID_ARGS; } - + if (!t2dbus_handle.is_initialized) { EVENT_ERROR("D-Bus not initialized\n"); - return T2ERROR_NOT_INITIALIZED; + return T2ERROR_INTERNAL_ERROR; } - + /* Store callback */ profileUpdateCallback = callback; @@ -659,20 +659,20 @@ void *cacheEventToFile(void *arg) static bool initRFC( ) { bool status = true ; - // Check for RFC and proceed - if true - else return now . - if(!bus_handle) - { - if(initMessageBus() != 0) - { - EVENT_ERROR("initMessageBus failed\n"); - status = false ; - } - else - { - status = true; - } - isRFCT2Enable = true; - } + // // Check for RFC and proceed - if true - else return now . + // if(!bus_handle) + // { + // if(initMessageBus() != 0) + // { + // EVENT_ERROR("initMessageBus failed\n"); + // status = false ; + // } + // else + // { + // status = true; + // } + // isRFCT2Enable = true; + // } return status; } From 313d69b03e69c16535d7e96669fcd8e66b0a526e Mon Sep 17 00:00:00 2001 From: Muhammed rafi Date: Tue, 20 Jan 2026 01:54:13 +0000 Subject: [PATCH 04/23] test code --- .../commonlib/telemetry_busmessage_sender.c | 97 ++++++++++++----- source/commonlib/telemetry_client.c | 100 +++++++++++++++++- 2 files changed, 170 insertions(+), 27 deletions(-) diff --git a/source/commonlib/telemetry_busmessage_sender.c b/source/commonlib/telemetry_busmessage_sender.c index 67e200a3..f44620b9 100644 --- a/source/commonlib/telemetry_busmessage_sender.c +++ b/source/commonlib/telemetry_busmessage_sender.c @@ -26,9 +26,17 @@ #include #include #include +#if defined(CCSP_SUPPORT_ENABLED) +#include +#include +#include +#endif #include - +# if RBUS_ENABLED +#include +#endif #include "telemetry_busmessage_sender.h" + #include "t2collection.h" #include "vector.h" #include "telemetry2_0.h" @@ -81,6 +89,7 @@ static pthread_mutex_t FileCacheMutex ; static pthread_mutex_t markerListMutex ; static pthread_mutex_t loggerMutex ; +/* static void EVENT_DEBUG(char* format, ...) { @@ -112,6 +121,12 @@ static void EVENT_DEBUG(char* format, ...) pthread_mutex_unlock(&loggerMutex); } +*/ + +#define EVENT_DEBUG(format, ...) \ + fprintf(stderr, "T2DEBUG:%s %s:%d: ", __func__ , __FILE__, __LINE__ ); \ + fprintf(stderr, (format), ##__VA_ARGS__ ); \ + // fprintf(stderr, "\n" ); /** * @brief Check if D-Bus is initialized @@ -142,6 +157,7 @@ static DBusHandlerResult dbusMessageFilter(DBusConnection *connection, /** * @brief D-Bus listener thread function + * Processes incoming D-Bus signals (like ProfileUpdate) */ static void* dbusListenerThreadFunc(void *arg) { (void)arg; @@ -149,10 +165,15 @@ static void* dbusListenerThreadFunc(void *arg) { EVENT_DEBUG("%s ++in\n", __FUNCTION__); while (!stopListenerThread && t2dbus_handle.connection) { - /* Process messages with timeout */ + /* Process messages with 100ms timeout - blocks until message or timeout */ dbus_connection_read_write_dispatch(t2dbus_handle.connection, 100); + + /* Small yield to prevent tight loop CPU hogging + * Note: With proper dbus_threads_init_default(), this shouldn't be needed, + * but helps with CPU usage in practice */ + usleep(1000); // 1ms yield } - + EVENT_DEBUG("%s --out\n", __FUNCTION__); return NULL; } @@ -174,8 +195,16 @@ static T2ERROR dBusInterface_Init(const char *component_name) { DBusError error; dbus_error_init(&error); - /* Connect to session bus for local IPC */ - t2dbus_handle.connection = dbus_bus_get(DBUS_BUS_SESSION, &error); + /* Initialize D-Bus threading support - CRITICAL for multi-threaded use */ + if (!dbus_threads_init_default()) { + EVENT_ERROR("Failed to initialize D-Bus threading support\n"); + pthread_mutex_unlock(&dbusMutex); + return T2ERROR_FAILURE; + } + EVENT_DEBUG("D-Bus threading support initialized\n"); + + /* Connect to system bus for local IPC */ + t2dbus_handle.connection = dbus_bus_get(DBUS_BUS_SYSTEM, &error); if (dbus_error_is_set(&error)) { EVENT_ERROR("D-Bus connection error: %s\n", error.message); dbus_error_free(&error); @@ -431,7 +460,8 @@ static T2ERROR dbusGetMarkerList(const char* component, char** markerList) { */ static T2ERROR dbusGetOperationalStatus(uint32_t* status) { EVENT_DEBUG("%s ++in\n", __FUNCTION__); - + *status = T2_STATE_COMPONENT_READY; + return T2ERROR_SUCCESS; if (!status) { EVENT_ERROR("Invalid arguments\n"); return T2ERROR_INVALID_ARGS; @@ -656,23 +686,29 @@ void *cacheEventToFile(void *arg) return NULL; } +static T2ERROR initMessageBus( ) +{ + // EVENT_DEBUG("%s ++in\n", __FUNCTION__); + T2ERROR status = T2ERROR_SUCCESS; + //TODO: Initialize message bus here - DBUS / RBUS based on build flags + return status; +} + static bool initRFC( ) { bool status = true ; // // Check for RFC and proceed - if true - else return now . - // if(!bus_handle) - // { - // if(initMessageBus() != 0) - // { - // EVENT_ERROR("initMessageBus failed\n"); - // status = false ; - // } - // else - // { - // status = true; - // } - // isRFCT2Enable = true; - // } + + if(initMessageBus() != 0) + { + EVENT_ERROR("initMessageBus failed\n"); + status = false ; + } + else + { + status = true; + } + isRFCT2Enable = true; return status; } @@ -689,7 +725,7 @@ int filtered_event_send(const char* data, const char *markerName) if(!isDbusInitialized()) { - EVENT_ERROR("DBUS not initialized .. exiting !!! \n"); + EVENT_ERROR("DBUS not initialized .. exiting !!!"); return ret; } @@ -828,7 +864,7 @@ static void dbusProfileUpdateHandler(void) static bool isCachingRequired( ) { - + // TODO check complete conditions for caching requirement something is missing /** * Attempts to read from PAM before its ready creates deadlock . * PAM not ready is a definite case for caching the event and avoid bus traffic @@ -854,7 +890,8 @@ static bool isCachingRequired( ) // Always check for t2 is ready to accept events. Shutdown target can bring down t2 process at runtime uint32_t t2ReadyStatus; - T2ERROR retVal = dbusGetOperationalStatus(&t2ReadyStatus); + //TODO check the exact api to replace documentation of rbus_getUint + T2ERROR retVal = dbusGetOperationalStatus(&t2ReadyStatus); // replace of rbus_getUint api if(retVal != T2ERROR_SUCCESS) { @@ -864,13 +901,14 @@ static bool isCachingRequired( ) { EVENT_DEBUG("Operational status: %d\n", t2ReadyStatus); if((t2ReadyStatus & T2_STATE_COMPONENT_READY) == 0) - { - return true; - } + { + return true; + } } if(!isT2Ready) { + EVENT_DEBUG("T2 is not ready yet - checking component specific config\n"); if(componentName && (0 != strcmp(componentName, "telemetry_client"))) { // From other binary applications in rbus mode if t2 daemon is yet to determine state of component specific config from cloud, enable cache @@ -882,7 +920,8 @@ static bool isCachingRequired( ) { // Fetch marker list and subscribe to profile updates doPopulateEventMarkerList(); - + + EVENT_DEBUG("Subscribing to ProfileUpdate signal for component %s\n", componentName); T2ERROR ret = dbusSubscribeProfileUpdate(dbusProfileUpdateHandler); if(ret != T2ERROR_SUCCESS) { @@ -894,6 +933,7 @@ static bool isCachingRequired( ) } else { + EVENT_DEBUG("Component is telemetry_client or NULL - marking T2 as ready\n"); isT2Ready = true; } } @@ -935,6 +975,11 @@ static int report_or_cache_data(char* telemetry_data, const char* markerName) EVENT_ERROR("%s:%d, T2:telemetry data send failed, status = %d \n", __func__, __LINE__, ret); } } + else + { + EVENT_DEBUG("T2 is NOT ready - caching event to file: marker=%s\n", markerName); + } + // Caching format needs to be same for operation between rbus/dbus modes across reboots return ret; } diff --git a/source/commonlib/telemetry_client.c b/source/commonlib/telemetry_client.c index 4acd5040..1d28c658 100644 --- a/source/commonlib/telemetry_client.c +++ b/source/commonlib/telemetry_client.c @@ -18,10 +18,13 @@ */ #include +#include +#include +#include #include #define COMP_NAME "telemetry_client" - +/* int main(int argc, char *argv[]) { (void) argc;// To fix compiler warning @@ -32,3 +35,98 @@ int main(int argc, char *argv[]) return 0; } +*/ +/* +int main(int argc, char *argv[]) +{ + int i = 0, n; + n = (argc < 2) ? 100 : atoi(argv[1]); + // Initialize Telemetry2.0 + t2_init("telemetry_client"); + + while(i <= n) + { + t2_event_d("T2_INFO_Test", i); + i++; + } + t2_uninit(); + printf("Sent %d t2_event_d events.\n", n); + return 0; +} + */ + + +// Thread argument structure +typedef struct { + int value; +} thread_arg_t; + +// Thread function that sends telemetry event +void* send_event_thread(void* arg) +{ + thread_arg_t* t_arg = (thread_arg_t*)arg; + int value = t_arg->value; + free(t_arg); + + printf("Thread %ld: Sending T2_INFO_Test=%d\n", (long)pthread_self(), value); + t2_event_d("T2_INFO_Test", value); + printf("Thread %ld: Event sent successfully\n", (long)pthread_self()); + + return NULL; +} + +int main(int argc, char *argv[]) +{ + int i = 0, n; + n = (argc < 2) ? 100 : atoi(argv[1]); + + // Initialize Telemetry2.0 + t2_init("telemetry_client"); + + printf("Starting multi-threaded telemetry test with %d events\n", n); + printf("Each event will be sent from a separate thread\n\n"); + + // Array to store thread IDs + pthread_t* threads = (pthread_t*)malloc((n + 1) * sizeof(pthread_t)); + if (!threads) { + printf("Failed to allocate memory for threads\n"); + t2_uninit(); + return 1; + } + + // Create a thread for each event + while(i <= n) + { + thread_arg_t* arg = (thread_arg_t*)malloc(sizeof(thread_arg_t)); + if (!arg) { + printf("Failed to allocate memory for thread argument\n"); + break; + } + arg->value = i; + + if (pthread_create(&threads[i], NULL, send_event_thread, (void*)arg) != 0) { + printf("Failed to create thread %d\n", i); + free(arg); + break; + } + + i++; + usleep(100); + } + printf("\nAll %d threads created, waiting for completion...\n\n", i); + + // Wait for all threads to complete + for (int j = 0; j < i; j++) { + pthread_join(threads[j], NULL); + } + + free(threads); + + printf("\n===========================================\n"); + printf("All threads completed!\n"); + printf("Sent %d t2_event_d events from %d threads.\n", i, i); + printf("===========================================\n"); + + t2_uninit(); + return 0; +} From cf44dad23dc0d6ce8a51fa5146fde6414ad01a88 Mon Sep 17 00:00:00 2001 From: Muhammed rafi Date: Tue, 20 Jan 2026 02:04:35 +0000 Subject: [PATCH 05/23] test --- DBUS_MIGRATION_STEP1_2_PLAN.md | 336 --------------- DBUS_MIGRATION_STEP3_BULKDATA_PLAN.md | 594 -------------------------- 2 files changed, 930 deletions(-) delete mode 100755 DBUS_MIGRATION_STEP1_2_PLAN.md delete mode 100755 DBUS_MIGRATION_STEP3_BULKDATA_PLAN.md diff --git a/DBUS_MIGRATION_STEP1_2_PLAN.md b/DBUS_MIGRATION_STEP1_2_PLAN.md deleted file mode 100755 index 089f9f29..00000000 --- a/DBUS_MIGRATION_STEP1_2_PLAN.md +++ /dev/null @@ -1,336 +0,0 @@ -# DBUS Migration Plan: Step 1 & 2 - CommonLib Event Sending - -## Current Status - -**COMPLETED:** -✅ Updated dbusInterface.h with new service name "telemetry.t2" -✅ Added new APIs: `dbusGetMarkerList()`, `dbusGetOperationalStatus()`, `dbusSubscribeProfileUpdate()` -✅ Updated dbusInterface.c with implementations -✅ Includes in telemetry_busmessage_sender.c already changed to use DBUS - -**PENDING:** -❌ Remove all RBUS/CCSP specific code from telemetry_busmessage_sender.c -❌ Replace RBUS operations with DBUS equivalents -❌ Update Makefile.am to link with DBUS libraries - ---- - -## Changes Required in telemetry_busmessage_sender.c - -### 1. Remove These Functions (CCSP/RBUS specific): - -```c -// Lines 138-178: Remove entire CCSP block -#if defined(CCSP_SUPPORT_ENABLED) -T2ERROR getParamValues(...) {...} -static void freeParamValue(...) {...} -static T2ERROR getCCSPParamVal(...) {...} -#endif - -// Lines 183-184: Remove RBUS uninit -static void rBusInterface_Uninit() {...} - -// Lines 186-235: Remove initMessageBus - Replace with DBUS init -static T2ERROR initMessageBus() {...} - -// Lines 237-268: Remove getRbusParameterVal - not needed for commonlib -static T2ERROR getRbusParameterVal(...) {...} -``` - -### 2. Replace filtered_event_send() Function (Lines 407-500) - -**Current RBUS Implementation:** -```c -int filtered_event_send(const char* data, const char *markerName) { - // Uses rbus_set() with rbusProperty, rbusValue - // Complex object creation for RBUS - ... -} -``` - -**New DBUS Implementation:** -```c -int filtered_event_send(const char* data, const char *markerName) { - T2ERROR ret = T2ERROR_SUCCESS; - - // Check DBUS initialized - if(!isDbusInitialized()) { - EVENT_ERROR("DBUS not initialized\n"); - return -1; - } - - // Keep event filtering logic (lines 420-445) AS-IS - // ... marker list filtering code ... - - // Replace RBUS rbus_set() with DBUS signal - ret = dbusPublishEvent(markerName, data); - if(ret != T2ERROR_SUCCESS) { - EVENT_ERROR("dbusPublishEvent Failed\n"); - return -1; - } - return 0; -} -``` - -### 3. Replace doPopulateEventMarkerList() Function (Lines 505-598) - -**Current RBUS Implementation:** -```c -static T2ERROR doPopulateEventMarkerList(void) { - // Uses rbus_get() to fetch marker list as RBUS_OBJECT - // Iterates through rbusProperty list - ... -} -``` - -**New DBUS Implementation:** -```c -static T2ERROR doPopulateEventMarkerList(void) { - EVENT_DEBUG("%s ++in\n", __FUNCTION__); - T2ERROR status = T2ERROR_SUCCESS; - - if(!isDbusInitialized()) { - EVENT_ERROR("DBUS not initialized\n"); - return T2ERROR_FAILURE; - } - - pthread_mutex_lock(&markerListMutex); - - if(eventMarkerMap) { - hash_map_destroy(eventMarkerMap); - eventMarkerMap = NULL; - } - - // Get marker list via DBUS method call - char* markerListStr = NULL; - status = dbusGetMarkerList(componentName, &markerListStr); - - if(status != T2ERROR_SUCCESS || !markerListStr) { - EVENT_ERROR("dbusGetMarkerList failed\n"); - pthread_mutex_unlock(&markerListMutex); - return T2ERROR_FAILURE; - } - - // Parse marker list string (format: "marker1,marker2,marker3") - eventMarkerMap = hash_map_create(); - char* token = strtok(markerListStr, ","); - while(token != NULL) { - // Trim whitespace - while(*token == ' ') token++; - if(strlen(token) > 0) { - EVENT_DEBUG("\t %s\n", token); - hash_map_put(eventMarkerMap, strdup(token), strdup(token), free); - } - token = strtok(NULL, ","); - } - - free(markerListStr); - pthread_mutex_unlock(&markerListMutex); - - EVENT_DEBUG("%s --out\n", __FUNCTION__); - return status; -} -``` - -### 4. Replace rbusEventReceiveHandler() with DBUS Callback (Lines 600-615) - -**Current RBUS Implementation:** -```c -static void rbusEventReceiveHandler(rbusHandle_t handle, rbusEvent_t const* event, ...) { - // RBUS event subscription callback - if(strcmp(eventName, T2_PROFILE_UPDATED_NOTIFY) == 0) { - doPopulateEventMarkerList(); - } -} -``` - -**New DBUS Implementation:** -```c -static void dbusProfileUpdateHandler(void) { - EVENT_DEBUG("Profile update notification received\n"); - doPopulateEventMarkerList(); -} -``` - -### 5. Replace isCachingRequired() Function (Lines 617-690) - -**Current RBUS Implementation:** -```c -static bool isCachingRequired() { - // Uses rbus_getUint() to check T2_OPERATIONAL_STATUS - retVal = rbus_getUint(bus_handle, T2_OPERATIONAL_STATUS, &t2ReadyStatus); - - // Uses rbusEvent_Subscribe() for profile updates - ret = rbusEvent_Subscribe(bus_handle, T2_PROFILE_UPDATED_NOTIFY, rbusEventReceiveHandler, ...); - ... -} -``` - -**New DBUS Implementation:** -```c -static bool isCachingRequired() { - // Keep RFC and PAM initialization checks AS-IS (lines 624-633) - - if(!initRFC()) { - EVENT_ERROR("initRFC failed - cache the events\n"); - return true; - } - - if(!isRFCT2Enable) { - return false; - } - - // Replace rbus_getUint() with DBUS method call - uint32_t t2ReadyStatus; - T2ERROR retVal = dbusGetOperationalStatus(&t2ReadyStatus); - - if(retVal != T2ERROR_SUCCESS) { - return true; - } - - EVENT_DEBUG("Operational status: %d\n", t2ReadyStatus); - if((t2ReadyStatus & T2_STATE_COMPONENT_READY) == 0) { - return true; - } - - if(!isT2Ready) { - if(componentName && (strcmp(componentName, "telemetry_client") != 0)) { - if((t2ReadyStatus & T2_STATE_COMPONENT_READY) == 0) { - return true; - } else { - // Fetch marker list and subscribe to profile updates - doPopulateEventMarkerList(); - - // Subscribe to profile update signal - T2ERROR ret = dbusSubscribeProfileUpdate(dbusProfileUpdateHandler); - if(ret != T2ERROR_SUCCESS) { - EVENT_ERROR("Failed to subscribe to profile updates\n"); - } - isT2Ready = true; - } - } else { - isT2Ready = true; - } - } - - return false; -} -``` - -### 6. Update t2_init() and t2_uninit() Functions (Lines 734-752) - -**Current Implementation:** -```c -void t2_init(char *component) { - componentName = strdup(component); -} - -void t2_uninit(void) { - if(componentName) { - free(componentName); - componentName = NULL; - } - if(isRbusEnabled) { - rBusInterface_Uninit(); - } - uninitMutex(); -} -``` - -**New DBUS Implementation:** -```c -void t2_init(char *component) { - componentName = strdup(component); - - // Initialize DBUS connection - T2ERROR ret = dBusInterface_Init(componentName); - if(ret != T2ERROR_SUCCESS) { - EVENT_ERROR("DBUS initialization failed for %s\n", componentName); - } -} - -void t2_uninit(void) { - if(componentName) { - free(componentName); - componentName = NULL; - } - - // Uninitialize DBUS - dBusInterface_Uninit(); - - uninitMutex(); -} -``` - ---- - -## Changes Required in Makefile.am - -### File: telemetry/source/commonlib/Makefile.am - -**Add DBUS dependencies:** - -```makefile -# Add DBUS CFLAGS and LIBS -AM_CFLAGS = -I$(top_srcdir)/include \ - -I$(top_srcdir)/source/ccspinterface \ - $(DBUS_CFLAGS) \ - ... (existing flags) - -libt2commonlib_la_LIBADD = $(DBUS_LIBS) ... (existing libs) -``` - ---- - -## Testing Plan - -After making these changes, you should: - -1. **Compile:** - ```bash - cd telemetry - ./configure --enable-dbus - make clean - make - ``` - -2. **Check for DBUS symbols:** - ```bash - nm -D .libs/libt2commonlib.so | grep dbus - ``` - -3. **Test with simple client:** - ```bash - # Terminal 1: Monitor DBUS - dbus-monitor --session "interface='telemetry.t2.interface'" - - # Terminal 2: Run test client - ./test_client - ``` - -4. **Expected DBUS traffic:** - - Signal: `TelemetryEvent` with (marker_name, event_value) - - Method call: `GetMarkerList` with component_name - - Method call: `GetOperationalStatus` - - Signal: `ProfileUpdate` - ---- - -## Summary of API Mappings - -| RBUS API | DBUS API | Type | Purpose | -|----------|----------|------|---------| -| `rbus_set(T2_EVENT_PARAM, ...)` | `dbusPublishEvent(marker, value)` | Signal | Send telemetry event | -| `rbusEvent_Subscribe(T2_PROFILE_UPDATED_NOTIFY)` | `dbusSubscribeProfileUpdate(callback)` | Signal | Listen for profile updates | -| `rbus_get("...EventMarkerList", ...)` | `dbusGetMarkerList(component, &list)` | Method | Get marker list | -| `rbus_getUint(T2_OPERATIONAL_STATUS)` | `dbusGetOperationalStatus(&status)` | Method | Check T2 daemon status | - ---- - -## Questions? - -1. Should I proceed with creating the complete modified telemetry_busmessage_sender.c file? -2. Do you want me to create a patch file instead for easier review? -3. Should we test incrementally or make all changes at once? - -Please confirm and I'll proceed with the implementation. diff --git a/DBUS_MIGRATION_STEP3_BULKDATA_PLAN.md b/DBUS_MIGRATION_STEP3_BULKDATA_PLAN.md deleted file mode 100755 index 4f3e3b73..00000000 --- a/DBUS_MIGRATION_STEP3_BULKDATA_PLAN.md +++ /dev/null @@ -1,594 +0,0 @@ -# DBUS Migration Plan: STEP 3 - BulkData Side (T2 Daemon) - -## Overview - -This step implements the **server side** of the DBUS communication in the T2 daemon (BulkData). The daemon will: -1. **Receive telemetry events** via DBUS signals from commonlib clients -2. **Provide marker lists** via DBUS method responses -3. **Provide operational status** via DBUS method responses -4. **Send profile update notifications** via DBUS signals to commonlib clients - ---- - -## Current Status - -**STEP 1 & 2 COMPLETED:** -✅ CommonLib modified to use DBUS (telemetry_busmessage_sender.c) -✅ DBUS interface APIs implemented (dbusInterface.h/c) -✅ Makefile.am updated with DBUS dependencies - -**STEP 3 PENDING:** -❌ Implement DBUS signal receiver for telemetry events in BulkData -❌ Implement DBUS method providers (GetMarkerList, GetOperationalStatus) -❌ Implement DBUS signal sender for profile updates -❌ Update BulkData initialization to register DBUS handlers - ---- - -## Architecture Overview - -``` -┌──────────────────┐ ┌───────────────────────┐ -│ CommonLib │ │ BulkData (T2 Daemon) │ -│ (Client Apps) │ │ │ -├──────────────────┤ ├───────────────────────┤ -│ │ DBUS Signal │ │ -│ dbusPublishEvent├───────────────────────>│ dbusEventHandler() │ -│ (marker, value) │ "TelemetryEvent" │ ↓ │ -│ │ │ T2ER_Push() │ -│ │ │ ↓ │ -│ │ │ Event Queue │ -└──────────────────┘ └───────────────────────┘ - │ │ - │ DBUS Method Call │ - │ "GetMarkerList" │ - └───────────────────────────────────────────>│ - │ │ dbusGetMarkerListHandler() - │<───────────────────────────────────────────┤ getComponentMarkerList() - │ DBUS Method Reply │ - │ (marker1,marker2,...) │ - │ │ - │ DBUS Method Call │ - │ "GetOperationalStatus" │ - └───────────────────────────────────────────>│ - │ │ dbusGetOperationalStatusHandler() - │<───────────────────────────────────────────┤ t2ReadyStatus - │ DBUS Method Reply (uint32) │ - │ │ - │ │ - │ DBUS Signal │ - │ "ProfileUpdate" │ - │<───────────────────────────────────────────┤ publishEventsProfileUpdates() - │ │ (when profiles change) -``` - ---- - -## Files to Modify - -### Primary Files: -1. **`telemetry/source/bulkdata/t2eventreceiver.c`** - Add DBUS event reception -2. **`telemetry/source/bulkdata/t2markers.c`** - Add DBUS method provider for marker list -3. **`telemetry/source/ccspinterface/rbusInterface.c`** - Add DBUS method providers and signal sender -4. **`telemetry/source/telemetry2_0.c`** - Update daemon initialization - -### Supporting Files: -5. **`telemetry/source/ccspinterface/Makefile.am`** - Already has DBUS (verify) -6. **`telemetry/source/bulkdata/Makefile.am`** - May need DBUS includes - ---- - -## Detailed Implementation Plan - -### **STEP 3.1: Implement DBUS Event Reception in BulkData** - -**File:** [`t2eventreceiver.c`](telemetry/source/bulkdata/t2eventreceiver.c) - -**Current RBUS Implementation:** -- Function: `registerRbusT2EventListener()` registers callback for RBUS events -- Callback: `t2rbusEventCallback()` receives RBUS property set events -- Processing: Extracts event name/value and calls `T2ER_Push()` - -**New DBUS Implementation:** - -```c -/** - * @brief DBUS signal handler for telemetry events - * Called when TelemetryEvent signal is received - */ -static DBusHandlerResult dbusEventSignalHandler(DBusConnection *connection, - DBusMessage *message, - void *user_data) -{ - (void)connection; - (void)user_data; - - T2Debug("%s ++in\n", __FUNCTION__); - - if (!dbus_message_is_signal(message, T2_DBUS_INTERFACE_NAME, T2_DBUS_SIGNAL_EVENT)) { - return DBUS_HANDLER_RESULT_NOT_YET_HANDLED; - } - - const char* eventName = NULL; - const char* eventValue = NULL; - DBusError error; - dbus_error_init(&error); - - // Extract event name and value from signal - if (!dbus_message_get_args(message, &error, - DBUS_TYPE_STRING, &eventName, - DBUS_TYPE_STRING, &eventValue, - DBUS_TYPE_INVALID)) { - T2Error("Failed to parse TelemetryEvent signal: %s\n", error.message); - dbus_error_free(&error); - return DBUS_HANDLER_RESULT_HANDLED; - } - - T2Info("Received DBUS event: %s = %s\n", eventName, eventValue); - - // Create rbusProperty for backward compatibility with existing code - rbusProperty_t properties = NULL; - rbusValue_t value; - rbusValue_Init(&value); - rbusValue_SetString(value, eventValue); - rbusProperty_Init(&properties, eventName, value); - - // Push to event queue (reuse existing T2ER_Push logic) - T2ER_Push(properties); - - // Cleanup - rbusValue_Release(value); - rbusProperty_Release(properties); - - T2Debug("%s --out\n", __FUNCTION__); - return DBUS_HANDLER_RESULT_HANDLED; -} - -/** - * @brief Register DBUS telemetry event listener - */ -T2ERROR registerDbusT2EventListener(void) -{ - T2Debug("%s ++in\n", __FUNCTION__); - - if (!isDbusInitialized()) { - T2Error("DBUS not initialized\n"); - return T2ERROR_FAILURE; - } - - // Subscribe to TelemetryEvent signal - T2ERROR ret = registerDbusT2EventListener(dbusEventSignalHandler); - if (ret != T2ERROR_SUCCESS) { - T2Error("Failed to register DBUS event listener\n"); - return T2ERROR_FAILURE; - } - - T2Info("DBUS telemetry event listener registered\n"); - T2Debug("%s --out\n", __FUNCTION__); - return T2ERROR_SUCCESS; -} -``` - -**Changes Required:** -- Add `dbusEventSignalHandler()` function -- Add `registerDbusT2EventListener()` function -- Update `T2ER_Init()` to call `registerDbusT2EventListener()` instead of/alongside RBUS - ---- - -### **STEP 3.2: Implement DBUS Method Provider for Marker List** - -**File:** [`rbusInterface.c`](telemetry/source/ccspinterface/rbusInterface.c) - -**Current RBUS Implementation:** -- Data element: `"Telemetry.ReportProfiles.{component}.EventMarkerList"` -- Handler: `t2PropertyDataGetHandler()` calls `getMarkerListCallBack()` -- Returns: RBUS_OBJECT containing marker names as properties - -**New DBUS Implementation:** - -```c -/** - * @brief DBUS method handler for GetMarkerList - */ -static DBusMessage* dbusGetMarkerListHandler(DBusMessage *msg) -{ - T2Debug("%s ++in\n", __FUNCTION__); - - const char* componentName = NULL; - DBusError error; - dbus_error_init(&error); - - // Extract component name from method call - if (!dbus_message_get_args(msg, &error, - DBUS_TYPE_STRING, &componentName, - DBUS_TYPE_INVALID)) { - T2Error("Failed to parse GetMarkerList arguments: %s\n", error.message); - dbus_error_free(&error); - return dbus_message_new_error(msg, DBUS_ERROR_INVALID_ARGS, "Missing component name"); - } - - T2Debug("GetMarkerList request for component: %s\n", componentName); - - // Get marker list from callback (reuse existing getComponentMarkerList) - Vector* markerList = NULL; - if (getMarkerListCallBack) { - getMarkerListCallBack(componentName, (void**)&markerList); - } - - // Build comma-separated string - char markerListStr[4096] = {0}; - if (markerList && Vector_Size(markerList) > 0) { - for (size_t i = 0; i < Vector_Size(markerList); i++) { - char* marker = (char*)Vector_At(markerList, i); - if (marker) { - if (i > 0) strcat(markerListStr, ","); - strcat(markerListStr, marker); - } - } - } - - T2Debug("Marker list: %s\n", markerListStr); - - // Create reply - DBusMessage* reply = dbus_message_new_method_return(msg); - const char* markerListPtr = markerListStr; - dbus_message_append_args(reply, - DBUS_TYPE_STRING, &markerListPtr, - DBUS_TYPE_INVALID); - - T2Debug("%s --out\n", __FUNCTION__); - return reply; -} -``` - ---- - -### **STEP 3.3: Implement DBUS Method Provider for Operational Status** - -**File:** [`rbusInterface.c`](telemetry/source/ccspinterface/rbusInterface.c) - -**Current RBUS Implementation:** -- Data element: `"Telemetry.OperationalStatus"` -- Handler: `t2PropertyDataGetHandler()` returns `t2ReadyStatus` (uint32) - -**New DBUS Implementation:** - -```c -/** - * @brief DBUS method handler for GetOperationalStatus - */ -static DBusMessage* dbusGetOperationalStatusHandler(DBusMessage *msg) -{ - T2Debug("%s ++in\n", __FUNCTION__); - - // Get current operational status (global variable) - uint32_t status = t2ReadyStatus; - - T2Debug("Operational status: %u\n", status); - - // Create reply - DBusMessage* reply = dbus_message_new_method_return(msg); - dbus_message_append_args(reply, - DBUS_TYPE_UINT32, &status, - DBUS_TYPE_INVALID); - - T2Debug("%s --out\n", __FUNCTION__); - return reply; -} -``` - ---- - -### **STEP 3.4: Implement DBUS Signal Sender for Profile Updates** - -**File:** [`rbusInterface.c`](telemetry/source/ccspinterface/rbusInterface.c) - -**Current RBUS Implementation:** -- Function: `publishEventsProfileUpdates()` -- Uses: `rbusEvent_Publish()` on `"Telemetry.ReportProfiles.ProfilesUpdated"` - -**New DBUS Implementation:** - -```c -/** - * @brief Publish profile update notification via DBUS signal - */ -void dbusPublishProfileUpdate(void) -{ - T2Debug("%s ++in\n", __FUNCTION__); - - if (!isDbusInitialized()) { - T2Error("DBUS not initialized\n"); - return; - } - - DBusMessage *signal = dbus_message_new_signal(T2_DBUS_OBJECT_PATH, - T2_DBUS_INTERFACE_NAME, - T2_DBUS_SIGNAL_PROFILE_UPDATE); - if (!signal) { - T2Error("Failed to create ProfileUpdate signal\n"); - return; - } - - // Send signal (no arguments needed) - if (!dbus_connection_send(getDbuConnection(), signal, NULL)) { - T2Error("Failed to send ProfileUpdate signal\n"); - } else { - dbus_connection_flush(getDbusConnection()); - T2Info("ProfileUpdate signal sent\n"); - } - - dbus_message_unref(signal); - T2Debug("%s --out\n", __FUNCTION__); -} -``` - -**Update existing function:** -```c -void publishEventsProfileUpdates(void) -{ - // Keep RBUS for internal components (if needed) - // Add DBUS for commonlib clients - dbusPublishProfileUpdate(); -} -``` - ---- - -### **STEP 3.5: Register DBUS Method Handlers** - -**File:** [`rbusInterface.c`](telemetry/source/ccspinterface/rbusInterface.c) or new `dbusMethodProvider.c` - -**Create DBUS method object registration:** - -```c -/** - * @brief DBUS method dispatch function - */ -static DBusHandlerResult dbusMethodDispatcher(DBusConnection *connection, - DBusMessage *message, - void *user_data) -{ - (void)connection; - (void)user_data; - - T2Debug("%s ++in\n", __FUNCTION__); - - if (dbus_message_is_method_call(message, T2_DBUS_INTERFACE_NAME, "GetMarkerList")) { - DBusMessage* reply = dbusGetMarkerListHandler(message); - dbus_connection_send(connection, reply, NULL); - dbus_message_unref(reply); - return DBUS_HANDLER_RESULT_HANDLED; - } - else if (dbus_message_is_method_call(message, T2_DBUS_INTERFACE_NAME, "GetOperationalStatus")) { - DBusMessage* reply = dbusGetOperationalStatusHandler(message); - dbus_connection_send(connection, reply, NULL); - dbus_message_unref(reply); - return DBUS_HANDLER_RESULT_HANDLED; - } - - T2Debug("%s --out\n", __FUNCTION__); - return DBUS_HANDLER_RESULT_NOT_YET_HANDLED; -} - -/** - * @brief Register DBUS method providers - */ -T2ERROR registerDbusMethodProviders(void) -{ - T2Debug("%s ++in\n", __FUNCTION__); - - if (!isDbusInitialized()) { - T2Error("DBUS not initialized\n"); - return T2ERROR_FAILURE; - } - - // Register object path with method handler - DBusObjectPathVTable vtable = { - .message_function = dbusMethodDispatcher, - .unregister_function = NULL - }; - - if (!dbus_connection_register_object_path(getDbusConnection(), - T2_DBUS_OBJECT_PATH, - &vtable, - NULL)) { - T2Error("Failed to register DBUS object path\n"); - return T2ERROR_FAILURE; - } - - T2Info("DBUS method providers registered\n"); - T2Debug("%s --out\n", __FUNCTION__); - return T2ERROR_SUCCESS; -} -``` - ---- - -### **STEP 3.6: Update T2 Daemon Initialization** - -**File:** [`telemetry2_0.c`](telemetry/source/telemetry2_0.c) - -**Current Initialization:** -```c -int main(int argc, char *argv[]) -{ - ... - // Initialize RBUS - initRbusInterface(); - ... - // Initialize event receiver - T2ER_Init(); - ... -} -``` - -**Updated Initialization:** -```c -int main(int argc, char *argv[]) -{ - ... - // Initialize DBUS (alongside or instead of RBUS) - T2ERROR ret = dBusInterface_Init("telemetry2_0"); - if (ret != T2ERROR_SUCCESS) { - T2Error("DBUS initialization failed\n"); - // Handle error - } - - // Register DBUS method providers - registerDbusMethodProviders(); - - // Initialize event receiver (will register DBUS event listener) - T2ER_Init(); - ... -} -``` - ---- - -## Summary of Changes - -| Component | Current RBUS | New DBUS | File | -|-----------|-------------|----------|------| -| **Event Reception** | `t2rbusEventCallback()` | `dbusEventSignalHandler()` | t2eventreceiver.c | -| **Marker List Provider** | `t2PropertyDataGetHandler()` | `dbusGetMarkerListHandler()` | rbusInterface.c | -| **Status Provider** | `t2PropertyDataGetHandler()` | `dbusGetOperationalStatusHandler()` | rbusInterface.c | -| **Profile Update Notification** | `rbusEvent_Publish()` | `dbusPublishProfileUpdate()` | rbusInterface.c | -| **Method Registration** | `rbus_regDataElements()` | `registerDbusMethodProviders()` | rbusInterface.c | -| **Daemon Init** | `initRbusInterface()` | `dBusInterface_Init()` | telemetry2_0.c | - ---- - -## API Flow Summary - -### 1. **Telemetry Event Flow** (CommonLib → BulkData) -``` -Client App - ↓ t2_event_s("marker", "value") -CommonLib - ↓ dbusPublishEvent() - ↓ DBUS Signal "TelemetryEvent" -BulkData - ↓ dbusEventSignalHandler() - ↓ T2ER_Push() - ↓ Event Queue Processing -``` - -### 2. **Marker List Request Flow** (CommonLib → BulkData) -``` -Client App - ↓ isCachingRequired() / doPopulateEventMarkerList() -CommonLib - ↓ dbusGetMarkerList("component") - ↓ DBUS Method Call "GetMarkerList" -BulkData - ↓ dbusGetMarkerListHandler() - ↓ getComponentMarkerList() - ↓ DBUS Method Reply("marker1,marker2,...") -CommonLib - ↓ Parse and store in eventMarkerMap -``` - -### 3. **Operational Status Check Flow** (CommonLib → BulkData) -``` -Client App - ↓ isCachingRequired() -CommonLib - ↓ dbusGetOperationalStatus() - ↓ DBUS Method Call "GetOperationalStatus" -BulkData - ↓ dbusGetOperationalStatusHandler() - ↓ Return t2ReadyStatus - ↓ DBUS Method Reply(uint32) -CommonLib - ↓ Check status and decide caching -``` - -### 4. **Profile Update Notification Flow** (BulkData → CommonLib) -``` -BulkData - ↓ Profile configuration changed - ↓ publishEventsProfileUpdates() - ↓ dbusPublishProfileUpdate() - ↓ DBUS Signal "ProfileUpdate" -CommonLib - ↓ dbusProfileUpdateHandler() - ↓ doPopulateEventMarkerList() - ↓ Refresh marker list from daemon -``` - ---- - -## Testing Strategy - -### Unit Tests: -1. **Event Reception:** Send DBUS signal, verify T2ER_Push() called -2. **Marker List:** Call GetMarkerList method, verify correct response -3. **Status Check:** Call GetOperationalStatus, verify status value -4. **Profile Update:** Emit ProfileUpdate signal, verify clients notified - -### Integration Tests: -1. **End-to-End Event:** Client sends event → Daemon receives → Stored in queue -2. **Marker List Sync:** Client requests list → Daemon provides → Client filters events -3. **Status Check:** Client checks status → Decides caching → Sends when ready -4. **Profile Update:** Daemon updates profile → Sends signal → Client refreshes list - -### System Tests: -1. **Full Profile Cycle:** Load profile → Send events → Update profile → Events filtered -2. **Multi-Client:** Multiple clients sending events simultaneously -3. **Stress Test:** 10,000 events from 10 clients concurrently -4. **Failover:** Daemon restart → Clients reconnect → Events cached/restored - ---- - -## Compilation and Testing Commands - -```bash -# Compile -cd telemetry -./configure -make clean -make - -# Check DBUS symbols in daemon -nm -D .libs/telemetry2_0 | grep dbus - -# Run daemon with DBUS monitoring -# Terminal 1: Monitor DBUS -dbus-monitor --session "interface='telemetry.t2.interface'" - -# Terminal 2: Run T2 daemon -./telemetry2_0 - -# Terminal 3: Run test client -./telemetry2_0_client - -# Expected DBUS traffic: -# - Signal: TelemetryEvent(marker, value) -# - Method call: GetMarkerList(component) → Reply(markers) -# - Method call: GetOperationalStatus() → Reply(status) -# - Signal: ProfileUpdate() -``` - ---- - -## Questions for Review - -1. **Backward Compatibility:** Do we need to keep RBUS alongside DBUS for internal components? -2. **Error Handling:** Should DBUS failures fall back to RBUS or cache events? -3. **Threading:** Should DBUS method handlers run in separate thread or main loop? -4. **Data Format:** Is comma-separated marker list format acceptable, or prefer JSON? -5. **Registration:** Should we register DBUS object path in dbusInterface.c or rbusInterface.c? - ---- - -## Next Steps After Review - -Once you review and approve this plan: -1. I'll implement all BulkData changes -2. Update necessary build files (Makefile.am) -3. You test the end-to-end flow -4. We move to Step 4: Complete testing and deployment - -**Ready for your review and feedback!** From 8dd2ffef34e2073fa0a568999938c60f5dbaf1ab Mon Sep 17 00:00:00 2001 From: Muhammed rafi Date: Tue, 20 Jan 2026 05:53:52 +0000 Subject: [PATCH 06/23] bulck data --- source/bulkdata/t2eventreceiver.c | 28 ++- source/bulkdata/t2markers.c | 13 +- source/ccspinterface/dbusInterface.c | 320 ++++++++------------------- source/ccspinterface/dbusInterface.h | 161 +------------- source/telemetry2_0.c | 18 ++ 5 files changed, 138 insertions(+), 402 deletions(-) diff --git a/source/bulkdata/t2eventreceiver.c b/source/bulkdata/t2eventreceiver.c index 5099e0e0..ca773cd5 100644 --- a/source/bulkdata/t2eventreceiver.c +++ b/source/bulkdata/t2eventreceiver.c @@ -29,6 +29,7 @@ #include "t2log_wrapper.h" #include "busInterface.h" #include "dca.h" +#include "dbusInterface.h" #define T2EVENTQUEUE_MAX_LIMIT 200 #define MESSAGE_DELIMITER "<#=#>" @@ -334,15 +335,24 @@ T2ERROR T2ER_Init() EREnabled = true; - if(isRbusEnabled()) - { - T2Debug("Register event call back function T2ER_Push \n"); - registerForTelemetryEvents(T2ER_Push); - } - else - { - T2Debug("Register event call back function T2ER_PushDataWithDelim \n"); - registerForTelemetryEvents(T2ER_PushDataWithDelim); + /* Old RBUS event registration - commented out for DBUS migration */ + // if(isRbusEnabled()) + // { + // T2Debug("Register event call back function T2ER_Push \n"); + // registerForTelemetryEvents(T2ER_Push); + // } + // else + // { + // T2Debug("Register event call back function T2ER_PushDataWithDelim \n"); + // registerForTelemetryEvents(T2ER_PushDataWithDelim); + // } + + /* Register DBUS event listener for TelemetryEvent signals */ + T2ERROR ret = registerDbusT2EventListener(T2ER_Push); + if(ret != T2ERROR_SUCCESS) { + T2Error("Failed to register DBUS event listener with error: %d\n", ret); + } else { + T2Info("DBUS event listener registered successfully\n"); } system("touch /tmp/.t2ReadyToReceiveEvents"); diff --git a/source/bulkdata/t2markers.c b/source/bulkdata/t2markers.c index 20bb3b3e..f72651e6 100644 --- a/source/bulkdata/t2markers.c +++ b/source/bulkdata/t2markers.c @@ -25,6 +25,7 @@ #include "t2eventreceiver.h" #include "t2log_wrapper.h" #include "rbusInterface.h" +#include "dbusInterface.h" /** * Store event markers associated with a component @@ -330,9 +331,19 @@ void createComponentDataElements() char *compName = (char*) Vector_At(componentList, i); if(compName) { - regDEforCompEventList(compName, getComponentMarkerList); + /* Old RBUS registration - commented out for DBUS migration */ + // regDEforCompEventList(compName, getComponentMarkerList); } } pthread_mutex_unlock(&t2CompListMutex); + + /* Register DBUS callback for GetMarkerList method */ + T2ERROR ret = registerGetMarkerListCallback(getComponentMarkerList); + if(ret != T2ERROR_SUCCESS) { + T2Error("Failed to register DBUS marker list callback with error: %d\n", ret); + } else { + T2Info("DBUS marker list callback registered successfully\n"); + } + T2Debug("%s --out\n", __FUNCTION__); } diff --git a/source/ccspinterface/dbusInterface.c b/source/ccspinterface/dbusInterface.c index f704fd33..98161a45 100755 --- a/source/ccspinterface/dbusInterface.c +++ b/source/ccspinterface/dbusInterface.c @@ -151,6 +151,7 @@ static void* dbusListenerThreadFunc(void *arg) { while (!stopListenerThread && t2dbus_handle.connection) { /* Process messages with timeout */ dbus_connection_read_write_dispatch(t2dbus_handle.connection, 100); + uslee(1000); } T2Debug("%s --out\n", __FUNCTION__); @@ -483,60 +484,6 @@ Vector* getDbusProfileParamValues(Vector *paramList, int execcount) { return profileValueList; } -/** - * @brief Publish telemetry event via D-Bus signal - */ -T2ERROR dbusPublishEvent(const char* eventName, const char* eventValue) { - T2Debug("%s ++in\n", __FUNCTION__); - - if (!eventName || !eventValue) { - T2Error("Invalid event parameters\n"); - return T2ERROR_INVALID_ARGS; - } - - if (!t2dbus_handle.is_initialized) { - if (dBusInterface_Init(NULL) != T2ERROR_SUCCESS) { - return T2ERROR_FAILURE; - } - } - - DBusMessage *signal = NULL; - - /* Create signal */ - signal = dbus_message_new_signal(T2_DBUS_OBJECT_PATH, - T2_DBUS_INTERFACE_NAME, - T2_DBUS_SIGNAL_EVENT); - if (!signal) { - T2Error("Failed to create D-Bus signal\n"); - return T2ERROR_FAILURE; - } - - /* Append arguments */ - if (!dbus_message_append_args(signal, - DBUS_TYPE_STRING, &eventName, - DBUS_TYPE_STRING, &eventValue, - DBUS_TYPE_INVALID)) { - T2Error("Failed to append signal arguments\n"); - dbus_message_unref(signal); - return T2ERROR_FAILURE; - } - - /* Send signal */ - if (!dbus_connection_send(t2dbus_handle.connection, signal, NULL)) { - T2Error("Failed to send D-Bus signal\n"); - dbus_message_unref(signal); - return T2ERROR_FAILURE; - } - - dbus_connection_flush(t2dbus_handle.connection); - dbus_message_unref(signal); - - T2Debug("Published event: %s = %s\n", eventName, eventValue); - T2Debug("%s --out\n", __FUNCTION__); - - return T2ERROR_SUCCESS; -} - /** * @brief Subscribe to D-Bus signal */ @@ -550,6 +497,7 @@ T2ERROR dbusSubscribeSignal(const char* signal_name) { if (!t2dbus_handle.is_initialized) { if (dBusInterface_Init(NULL) != T2ERROR_SUCCESS) { + T2ERROR("dbus not initialized\n"); return T2ERROR_FAILURE; } } @@ -691,177 +639,120 @@ void dbusPublishReportUploadStatus(const char* status) { T2Debug("%s --out\n", __FUNCTION__); } -/** - * @brief Set T2 event receiver state - */ -void dbusSetT2EventReceiveState(int t2_state) { - t2ReadyStatus = t2_state; - T2Info("T2 state set to: %d\n", t2_state); -} - -/** - * @brief Check if a D-Bus method exists - */ -bool dbusCheckMethodExists(const char* methodName) { - T2Debug("%s ++in: %s\n", __FUNCTION__, methodName); - - if (!methodName) { - return false; - } - - /* For now, return true for standard methods */ - /* In production, this should introspect the remote object */ +static DBusHandlerResult dbusMethodDispatcher(DBusConnection *conn, + DBusMessage *message, + void *user_data) { + (void)conn; + (void)user_data; - T2Debug("%s --out\n", __FUNCTION__); - return true; -} - -/** * @brief Get marker list for component via D-Bus method call - */ -T2ERROR dbusGetMarkerList(const char* component, char** markerList) { - T2Debug("%s ++in\n", __FUNCTION__); + const char *method = dbus_message_get_member(message); + const char *interface = dbus_message_get_interface(message); - if (!component || !markerList) { - T2Error("Invalid arguments\n"); - return T2ERROR_INVALID_ARGS; + if (!interface || strcmp(interface, T2_DBUS_INTERFACE_NAME) != 0) { + return DBUS_HANDLER_RESULT_NOT_YET_HANDLED; } - if (!t2dbus_handle.is_initialized) { - T2Error("D-Bus not initialized\n"); - return T2ERROR_NOT_INITIALIZED; + if (!method) { + return DBUS_HANDLER_RESULT_NOT_YET_HANDLED; } - DBusMessage *msg = NULL; - DBusMessage *reply = NULL; - DBusError error; - dbus_error_init(&error); - - /* Construct parameter name: Telemetry.ReportProfiles.{component}.EventMarkerList */ - char paramName[256]; - snprintf(paramName, sizeof(paramName), "Telemetry.ReportProfiles.%s.EventMarkerList", component); + T2Debug("Received method call: %s\n", method); - /* Create method call message */ - msg = dbus_message_new_method_call(T2_DBUS_SERVICE_NAME, - T2_DBUS_OBJECT_PATH, - T2_DBUS_INTERFACE_NAME, - "GetMarkerList"); - if (!msg) { - T2Error("Failed to create method call message\n"); - return T2ERROR_FAILURE; - } + DBusMessage *reply = NULL; - /* Append component name */ - if (!dbus_message_append_args(msg, DBUS_TYPE_STRING, &component, DBUS_TYPE_INVALID)) { - T2Error("Failed to append arguments\n"); - dbus_message_unref(msg); - return T2ERROR_FAILURE; + if (strcmp(method, "GetMarkerList") == 0) { + const char *component = NULL; + DBusError error; + dbus_error_init(&error); + + if (!dbus_message_get_args(message, &error, + DBUS_TYPE_STRING, &component, + DBUS_TYPE_INVALID)) { + T2Error("Failed to parse GetMarkerList args: %s\n", error.message); + dbus_error_free(&error); + reply = dbus_message_new_error(message, DBUS_ERROR_INVALID_ARGS, + "Expected string argument"); + } else if (!getMarkerListCallBack) { + T2Error("GetMarkerList callback not registered\n"); + reply = dbus_message_new_error(message, DBUS_ERROR_FAILED, + "Marker list callback not initialized"); + } else { + Vector *markerList = NULL; + getMarkerListCallBack(component, (void**)&markerList); + + char markerListStr[4096] = ""; + if (markerList && Vector_Size(markerList) > 0) { + for (size_t i = 0; i < Vector_Size(markerList); i++) { + char *marker = (char*)Vector_At(markerList, i); + if (marker) { + if (i > 0) strcat(markerListStr, ","); + strcat(markerListStr, marker); + } + } + Vector_Destroy(markerList, free); + } + + reply = dbus_message_new_method_return(message); + const char *result = markerListStr; + dbus_message_append_args(reply, + DBUS_TYPE_STRING, &result, + DBUS_TYPE_INVALID); + T2Debug("Returning marker list: %s\n", markerListStr); + } } - - /* Send message and get reply */ - reply = dbus_connection_send_with_reply_and_block(t2dbus_handle.connection, msg, - T2_DBUS_DEFAULT_TIMEOUT_MS, &error); - dbus_message_unref(msg); - - if (dbus_error_is_set(&error)) { - T2Error("D-Bus method call failed: %s\n", error.message); - dbus_error_free(&error); - return T2ERROR_FAILURE; + else if (strcmp(method, "GetOperationalStatus") == 0) { + reply = dbus_message_new_method_return(message); + dbus_message_append_args(reply, + DBUS_TYPE_UINT32, &t2ReadyStatus, + DBUS_TYPE_INVALID); + T2Debug("Returning operational status: %u\n", t2ReadyStatus); } - - if (!reply) { - T2Error("No reply received\n"); - return T2ERROR_FAILURE; + else { + return DBUS_HANDLER_RESULT_NOT_YET_HANDLED; } - /* Parse reply - expecting a string containing the marker list */ - char *value = NULL; - if (dbus_message_get_args(reply, &error, - DBUS_TYPE_STRING, &value, - DBUS_TYPE_INVALID)) { - *markerList = strdup(value); - T2Debug("Retrieved marker list for %s\n", component); - } else { - T2Error("Failed to parse reply: %s\n", error.message); - dbus_error_free(&error); + if (reply) { + dbus_connection_send(conn, reply, NULL); + dbus_connection_flush(conn); dbus_message_unref(reply); - return T2ERROR_FAILURE; + return DBUS_HANDLER_RESULT_HANDLED; } - dbus_message_unref(reply); - - T2Debug("%s --out\n", __FUNCTION__); - return T2ERROR_SUCCESS; + return DBUS_HANDLER_RESULT_NOT_YET_HANDLED; } -/** - * @brief Get operational status via D-Bus method call - */ -T2ERROR dbusGetOperationalStatus(uint32_t* status) { +T2ERROR registerDbusMethodProviders(void) { T2Debug("%s ++in\n", __FUNCTION__); - if (!status) { - T2Error("Invalid arguments\n"); - return T2ERROR_INVALID_ARGS; - } - if (!t2dbus_handle.is_initialized) { T2Error("D-Bus not initialized\n"); return T2ERROR_NOT_INITIALIZED; } - DBusMessage *msg = NULL; - DBusMessage *reply = NULL; - DBusError error; - dbus_error_init(&error); - - /* Create method call message */ - msg = dbus_message_new_method_call(T2_DBUS_SERVICE_NAME, - T2_DBUS_OBJECT_PATH, - T2_DBUS_INTERFACE_NAME, - "GetOperationalStatus"); - if (!msg) { - T2Error("Failed to create method call message\n"); - return T2ERROR_FAILURE; - } - - /* Send message and get reply */ - reply = dbus_connection_send_with_reply_and_block(t2dbus_handle.connection, msg, - T2_DBUS_DEFAULT_TIMEOUT_MS, &error); - dbus_message_unref(msg); - - if (dbus_error_is_set(&error)) { - T2Error("D-Bus method call failed: %s\n", error.message); - dbus_error_free(&error); - return T2ERROR_FAILURE; - } - - if (!reply) { - T2Error("No reply received\n"); + static const DBusObjectPathVTable vtable = { + NULL, + dbusMethodDispatcher, + NULL, + NULL, + NULL, + NULL + }; + + if (!dbus_connection_register_object_path(t2dbus_handle.connection, + T2_DBUS_OBJECT_PATH, + &vtable, + NULL)) { + T2Error("Failed to register object path\n"); return T2ERROR_FAILURE; } - /* Parse reply - expecting UINT32 */ - if (dbus_message_get_args(reply, &error, - DBUS_TYPE_UINT32, status, - DBUS_TYPE_INVALID)) { - T2Debug("Retrieved operational status: %u\n", *status); - } else { - T2Error("Failed to parse reply: %s\n", error.message); - dbus_error_free(&error); - dbus_message_unref(reply); - return T2ERROR_FAILURE; - } - - dbus_message_unref(reply); - + T2Info("Registered D-Bus method providers at %s\n", T2_DBUS_OBJECT_PATH); T2Debug("%s --out\n", __FUNCTION__); + return T2ERROR_SUCCESS; } -/** - * @brief Subscribe to profile update notifications - */ -T2ERROR dbusSubscribeProfileUpdate(void (*callback)(void)) { +T2ERROR registerGetMarkerListCallback(T2EventMarkerListCallback callback) { T2Debug("%s ++in\n", __FUNCTION__); if (!callback) { @@ -869,48 +760,11 @@ T2ERROR dbusSubscribeProfileUpdate(void (*callback)(void)) { return T2ERROR_INVALID_ARGS; } - if (!t2dbus_handle.is_initialized) { - T2Error("D-Bus not initialized\n"); - return T2ERROR_NOT_INITIALIZED; - } - - /* Store callback */ - profileUpdateCallback = callback; - - /* Subscribe to ProfileUpdate signal */ - char rule[512]; - DBusError error; - dbus_error_init(&error); - - snprintf(rule, sizeof(rule), - "type='signal',interface='%s',member='%s'", - T2_DBUS_INTERFACE_NAME, T2_DBUS_SIGNAL_PROFILE_UPDATE); - - dbus_bus_add_match(t2dbus_handle.connection, rule, &error); - - if (dbus_error_is_set(&error)) { - T2Error("Failed to add match rule: %s\n", error.message); - dbus_error_free(&error); - return T2ERROR_FAILURE; - } - - T2Info("Subscribed to ProfileUpdate signal\n"); + getMarkerListCallBack = callback; + T2Info("Registered GetMarkerList callback\n"); T2Debug("%s --out\n", __FUNCTION__); return T2ERROR_SUCCESS; } -/** * @brief Process incoming D-Bus messages - */ -T2ERROR dbusProcessMessages(int timeout_ms) { - if (!t2dbus_handle.is_initialized || !t2dbus_handle.connection) { - return T2ERROR_NOT_INITIALIZED; - } - - dbus_connection_read_write_dispatch(t2dbus_handle.connection, timeout_ms); - - return T2ERROR_SUCCESS; -} - -/** \ No newline at end of file diff --git a/source/ccspinterface/dbusInterface.h b/source/ccspinterface/dbusInterface.h index b5e7ab7a..efedf5c6 100755 --- a/source/ccspinterface/dbusInterface.h +++ b/source/ccspinterface/dbusInterface.h @@ -71,188 +71,31 @@ #define T2_DBUS_DEFAULT_TIMEOUT_MS 10000 /* 10 seconds */ #define T2_DBUS_METHOD_TIMEOUT_MS 10000 /* 10 seconds */ -/** - * @brief D-Bus connection handle - */ typedef struct { DBusConnection *connection; char *unique_name; bool is_initialized; } T2DbusHandle_t; -/** - * @brief D-Bus method callback pointer - */ typedef void (*dbusMethodCallBackPtr)(DBusMessage *reply, int retStatus); -/** - * @brief Check if D-Bus is initialized - * @return true if initialized, false otherwise - */ bool isDbusInitialized(void); - -/** - * @brief Initialize D-Bus interface for Telemetry 2.0 - * @param component_name Unique component name for registration - * @return T2ERROR_SUCCESS on success, T2ERROR_FAILURE on failure - */ T2ERROR dBusInterface_Init(const char *component_name); - -/** - * @brief Uninitialize D-Bus interface - */ void dBusInterface_Uninit(void); -/** - * @brief Get parameter value via D-Bus - * @param paramName Parameter name to query - * @param paramValue Pointer to store retrieved value (caller must free) - * @return T2ERROR_SUCCESS on success, T2ERROR_FAILURE on failure - */ T2ERROR getDbusParameterVal(const char* paramName, char **paramValue); - -/** - * @brief Set parameter value via D-Bus - * @param paramName Parameter name to set - * @param paramValue Value to set - * @param paramType Type of parameter (string, int, boolean, etc.) - * @return T2ERROR_SUCCESS on success, T2ERROR_FAILURE on failure - */ T2ERROR setDbusParameterVal(const char* paramName, const char* paramValue, int paramType); - -/** - * @brief Get multiple profile parameter values via D-Bus - * @param paramList Vector containing list of parameters to query - * @param execcount Execution count for skip frequency calculation - * @return Vector of profileValues structures - */ Vector* getDbusProfileParamValues(Vector *paramList, int execcount); -/** - * @brief Register for telemetry event notifications via D-Bus - * @param eventCB Callback function to handle events - * @return T2ERROR_SUCCESS on success, T2ERROR_FAILURE on failure - */ T2ERROR registerDbusT2EventListener(TelemetryEventCallback eventCB); - -/** - * @brief Unregister from telemetry event notifications - * @return T2ERROR_SUCCESS on success, T2ERROR_FAILURE on failure - */ T2ERROR unregisterDbusT2EventListener(void); -/** - * @brief Subscribe to a specific D-Bus signal - * @param signal_name Name of the signal to subscribe - * @return T2ERROR_SUCCESS on success, T2ERROR_FAILURE on failure - */ T2ERROR dbusSubscribeSignal(const char* signal_name); - -/** - * @brief Unsubscribe from a specific D-Bus signal - * @param signal_name Name of the signal to unsubscribe - * @return T2ERROR_SUCCESS on success, T2ERROR_FAILURE on failure - */ T2ERROR dbusUnsubscribeSignal(const char* signal_name); -/** - * @brief Publish telemetry event via D-Bus signal - * @param eventName Event name/marker - * @param eventValue Event value - * @return T2ERROR_SUCCESS on success, T2ERROR_FAILURE on failure - */ -T2ERROR dbusPublishEvent(const char* eventName, const char* eventValue); - -/** - * @brief Get marker list for component via D-Bus method call - * @param component Component name - * @param markerList Pointer to store marker list string (caller must free) - * @return T2ERROR_SUCCESS on success, T2ERROR_FAILURE on failure - */ -T2ERROR dbusGetMarkerList(const char* component, char** markerList); - -/** - * @brief Get operational status via D-Bus method call - * @param status Pointer to store status value - * @return T2ERROR_SUCCESS on success, T2ERROR_FAILURE on failure - */ -T2ERROR dbusGetOperationalStatus(uint32_t* status); - -/** - * @brief Subscribe to profile update notifications - * @param callback Callback function to invoke on profile update - * @return T2ERROR_SUCCESS on success, T2ERROR_FAILURE on failure - */ -T2ERROR dbusSubscribeProfileUpdate(void (*callback)(void)); - -/** - * @brief Call a D-Bus method - * @param methodName Method name to invoke - * @param inputParams Input parameters as D-Bus message - * @param payload Payload data - * @param callback Callback function for asynchronous response - * @return T2ERROR_SUCCESS on success, T2ERROR_FAILURE on failure - */ -T2ERROR dbusMethodCaller(const char *methodName, DBusMessage* inputParams, - const char* payload, dbusMethodCallBackPtr callback); - -/** - * @brief Check if a D-Bus method exists - * @param methodName Name of the method to check - * @return true if method exists, false otherwise - */ -bool dbusCheckMethodExists(const char* methodName); - -/** - * @brief Subscribe to trigger condition reports - * @param reference Reference parameter name - * @param subscription true to subscribe, false to unsubscribe - * @return T2ERROR_SUCCESS on success, T2ERROR_FAILURE on failure - */ -T2ERROR T2DbusReportEventConsumer(const char* reference, bool subscription); - -/** - * @brief Register consumer for trigger conditions - * @param triggerConditionList List of trigger conditions - * @return T2ERROR_SUCCESS on success, T2ERROR_FAILURE on failure - */ -T2ERROR dbusT2ConsumerReg(Vector *triggerConditionList); - -/** - * @brief Unregister consumer for trigger conditions - * @param triggerConditionList List of trigger conditions - * @return T2ERROR_SUCCESS on success, T2ERROR_FAILURE on failure - */ -T2ERROR dbusT2ConsumerUnReg(Vector *triggerConditionList); - -/** - * @brief Publish report upload status via D-Bus - * @param status Status string to publish - */ void dbusPublishReportUploadStatus(const char* status); -/** - * @brief Set T2 event receiver state - * @param t2_state State value to set - */ -void dbusSetT2EventReceiveState(int t2_state); - -/** - * @brief Process incoming D-Bus messages - * @param timeout_ms Timeout in milliseconds (-1 for blocking) - * @return T2ERROR_SUCCESS on success, T2ERROR_FAILURE on failure - */ -T2ERROR dbusProcessMessages(int timeout_ms); - -/** - * @brief Create D-Bus message iterator for parameters - * @param iter D-Bus message iterator - * @param paramName Parameter name - * @param paramValue Parameter value - * @param paramType Parameter type - * @return T2ERROR_SUCCESS on success, T2ERROR_FAILURE on failure - */ -T2ERROR dbusAppendParameter(DBusMessageIter *iter, const char* paramName, - const char* paramValue, int paramType); +T2ERROR registerDbusMethodProviders(void); +T2ERROR registerGetMarkerListCallback(T2EventMarkerListCallback callback); #endif /* _DBUSINTERFACE_H_ */ diff --git a/source/telemetry2_0.c b/source/telemetry2_0.c index c9dce45b..5dee2c68 100644 --- a/source/telemetry2_0.c +++ b/source/telemetry2_0.c @@ -17,6 +17,7 @@ * limitations under the License. */ #include "telemetry2_0.h" +#include "dbusInterface.h" #include #include @@ -252,6 +253,23 @@ static void t2DaemonMainModeInit( ) eh = newBreakPadWrapExceptionHandler(); #endif #endif + + /* Initialize DBUS for CommonLib <-> BulkData communication */ + T2ERROR dbusRet = dBusInterface_Init("telemetry2_0"); + if(dbusRet != T2ERROR_SUCCESS) { + T2Error("DBUS initialization failed for telemetry2_0 daemon with error: %d - proceeding without DBUS support\n", dbusRet); + } else { + T2Info("DBUS interface initialized successfully\n"); + + /* Register DBUS method providers for GetMarkerList and GetOperationalStatus */ + dbusRet = registerDbusMethodProviders(); + if(dbusRet != T2ERROR_SUCCESS) { + T2Error("DBUS method provider registration failed with error: %d\n", dbusRet); + } else { + T2Info("DBUS method providers registered successfully\n"); + } + } + /** * Create a Signal Mask for signals that need to be blocked while using fork */ From fbc6847e57fb2b666389abd1e84610f0060961f2 Mon Sep 17 00:00:00 2001 From: Muhammed rafi Date: Tue, 20 Jan 2026 06:38:31 +0000 Subject: [PATCH 07/23] bulckdata error fix --- source/Makefile.am | 4 +-- source/bulkdata/Makefile.am | 4 +-- source/ccspinterface/Makefile.am | 8 +++--- source/ccspinterface/dbusInterface.c | 25 ++++--------------- .../commonlib/telemetry_busmessage_sender.c | 3 +-- 5 files changed, 14 insertions(+), 30 deletions(-) diff --git a/source/Makefile.am b/source/Makefile.am index f6866597..6ed9f2ae 100644 --- a/source/Makefile.am +++ b/source/Makefile.am @@ -41,8 +41,8 @@ bin_PROGRAMS = telemetry2_0 telemetry2_0_SOURCES = telemetry2_0.c telemetry2_0_CFLAGS = -DFEATURE_SUPPORT_RDKLOG -D_FILE_OFFSET_BITS=64 -D_TIME_BITS=64 -telemetry2_0_CPPFLAGS = -fPIC -I${PKG_CONFIG_SYSROOT_DIR}$(includedir)/dbus-1.0 \ - -I${PKG_CONFIG_SYSROOT_DIR}$(libdir)/dbus-1.0/include \ +telemetry2_0_CPPFLAGS = -fPIC -I/usr/include/dbus-1.0 \ + -I/usr/lib/x86_64-linux-gnu/dbus-1.0/include \ -I${PKG_CONFIG_SYSROOT_DIR}$(includedir)/ \ -I${PKG_CONFIG_SYSROOT_DIR}$(includedir)/rbus \ -I${top_srcdir}/include \ diff --git a/source/bulkdata/Makefile.am b/source/bulkdata/Makefile.am index 78a5690e..ff93adca 100644 --- a/source/bulkdata/Makefile.am +++ b/source/bulkdata/Makefile.am @@ -23,8 +23,8 @@ lib_LTLIBRARIES = libbulkdata.la libbulkdata_la_SOURCES = reportprofiles.c profile.c profilexconf.c t2eventreceiver.c t2markers.c datamodel.c libbulkdata_la_LDFLAGS = -shared -fPIC -lcjson -lmsgpackc libbulkdata_la_LIBADD = ${top_builddir}/source/utils/libt2utils.la ${top_builddir}/source/dcautil/libdcautil.la ${top_builddir}/source/protocol/http/libhttp.la ${top_builddir}/source/protocol/rbusMethod/librbusmethod.la ${top_builddir}/source/ccspinterface/libccspinterface.la ${top_builddir}/source/reportgen/libreportgen.la ${top_builddir}/source/scheduler/libscheduler.la ${top_builddir}/source/xconf-client/libxconfclient.la -libbulkdata_la_CPPFLAGS = -fPIC -I${PKG_CONFIG_SYSROOT_DIR}$(includedir)/dbus-1.0 \ - -I${PKG_CONFIG_SYSROOT_DIR}$(libdir)/dbus-1.0/include \ +libbulkdata_la_CPPFLAGS = -fPIC -I/usr/include/dbus-1.0 \ + -I/usr/lib/x86_64-linux-gnu/dbus-1.0/include \ -I${PKG_CONFIG_SYSROOT_DIR}$(includedir) \ -I${PKG_CONFIG_SYSROOT_DIR}$(includedir)/rbus \ -I${top_srcdir}/source/utils \ diff --git a/source/ccspinterface/Makefile.am b/source/ccspinterface/Makefile.am index af372e01..52aa433b 100644 --- a/source/ccspinterface/Makefile.am +++ b/source/ccspinterface/Makefile.am @@ -20,16 +20,16 @@ AM_CFLAGS = lib_LTLIBRARIES = libccspinterface.la -libccspinterface_la_SOURCES = busInterface.c rbusInterface.c +libccspinterface_la_SOURCES = busInterface.c rbusInterface.c dbusInterface.c libccspinterface_la_CFLAGS = $(GLIB_CFLAGS) -libccspinterface_la_LDFLAGS = -shared -fPIC -lrbus $(GLIB_LIBS) +libccspinterface_la_LDFLAGS = -shared -fPIC -lrbus -ldbus-1 $(GLIB_LIBS) if ENABLE_CCSP_SUPPORT libccspinterface_la_LDFLAGS += -lccsp_common libccspinterface_la_SOURCES += ccspinterface.c endif -libccspinterface_la_CPPFLAGS = -fPIC $(CPPFLAGS) -I${PKG_CONFIG_SYSROOT_DIR}$(includedir)/dbus-1.0 \ - -I${PKG_CONFIG_SYSROOT_DIR}$(libdir)/dbus-1.0/include \ +libccspinterface_la_CPPFLAGS = -fPIC $(CPPFLAGS) -I/usr/include/dbus-1.0 \ + -I/usr/lib/x86_64-linux-gnu/dbus-1.0/include \ -I${PKG_CONFIG_SYSROOT_DIR}$(includedir)/ \ -I${PKG_CONFIG_SYSROOT_DIR}$(includedir)/ccsp \ -I${PKG_CONFIG_SYSROOT_DIR}$(includedir)/rbus \ diff --git a/source/ccspinterface/dbusInterface.c b/source/ccspinterface/dbusInterface.c index 98161a45..6fc577ca 100755 --- a/source/ccspinterface/dbusInterface.c +++ b/source/ccspinterface/dbusInterface.c @@ -57,31 +57,15 @@ static void (*profileUpdateCallback)(void) = NULL; /* Callback handlers */ static TelemetryEventCallback eventCallBack = NULL; static T2EventMarkerListCallback getMarkerListCallBack = NULL; -static dataModelCallBack dmProcessingCallBack = NULL; -static dataModelMsgPckCallBack dmMsgPckProcessingCallBack = NULL; -static dataModelSavedJsonCallBack dmSavedJsonProcessingCallBack = NULL; -static dataModelSavedMsgPackCallBack dmSavedMsgPackProcessingCallBack = NULL; -static profilememCallBack profilememUsedCallBack = NULL; -static dataModelReportOnDemandCallBack reportOnDemandCallBack = NULL; -static triggerReportOnCondtionCallBack reportOnConditionCallBack = NULL; -static xconfPrivacyModesDoNotShareCallBack privacyModesDoNotShareCallBack = NULL; -static ReportProfilesDeleteDNDCallBack mprofilesDeleteCallBack = NULL; /* State variables */ static uint32_t t2ReadyStatus = T2_STATE_NOT_READY; -static char* reportProfileVal = NULL; -static char* tmpReportProfileVal = NULL; -static char* reportProfilemsgPckVal = NULL; /* Threading */ static pthread_mutex_t dbusMutex = PTHREAD_MUTEX_INITIALIZER; static pthread_t dbusListenerThread; static bool stopListenerThread = false; -/* Component to parameter map */ -static hash_map_t *compTr181ParamMap = NULL; -static pthread_mutex_t compParamMap = PTHREAD_MUTEX_INITIALIZER; - /** * @brief Check if D-Bus is initialized */ @@ -151,7 +135,7 @@ static void* dbusListenerThreadFunc(void *arg) { while (!stopListenerThread && t2dbus_handle.connection) { /* Process messages with timeout */ dbus_connection_read_write_dispatch(t2dbus_handle.connection, 100); - uslee(1000); + usleep(1000); } T2Debug("%s --out\n", __FUNCTION__); @@ -497,7 +481,7 @@ T2ERROR dbusSubscribeSignal(const char* signal_name) { if (!t2dbus_handle.is_initialized) { if (dBusInterface_Init(NULL) != T2ERROR_SUCCESS) { - T2ERROR("dbus not initialized\n"); + T2Error("dbus not initialized\n"); return T2ERROR_FAILURE; } } @@ -537,7 +521,8 @@ T2ERROR dbusUnsubscribeSignal(const char* signal_name) { } if (!t2dbus_handle.is_initialized) { - return T2ERROR_NOT_INITIALIZED; + T2Error("D-Bus not initialized\n"); + return T2ERROR_FAILURE; } char rule[512]; @@ -726,7 +711,7 @@ T2ERROR registerDbusMethodProviders(void) { if (!t2dbus_handle.is_initialized) { T2Error("D-Bus not initialized\n"); - return T2ERROR_NOT_INITIALIZED; + return T2ERROR_FAILURE; } static const DBusObjectPathVTable vtable = { diff --git a/source/commonlib/telemetry_busmessage_sender.c b/source/commonlib/telemetry_busmessage_sender.c index f44620b9..7247511d 100644 --- a/source/commonlib/telemetry_busmessage_sender.c +++ b/source/commonlib/telemetry_busmessage_sender.c @@ -460,8 +460,7 @@ static T2ERROR dbusGetMarkerList(const char* component, char** markerList) { */ static T2ERROR dbusGetOperationalStatus(uint32_t* status) { EVENT_DEBUG("%s ++in\n", __FUNCTION__); - *status = T2_STATE_COMPONENT_READY; - return T2ERROR_SUCCESS; + if (!status) { EVENT_ERROR("Invalid arguments\n"); return T2ERROR_INVALID_ARGS; From 14a9c3d07cb62bd48719743a9166022840a1c750 Mon Sep 17 00:00:00 2001 From: Muhammed rafi c Date: Tue, 27 Jan 2026 10:59:14 +0000 Subject: [PATCH 08/23] dbusInterface code updated --- source/ccspinterface/dbusInterface.c | 630 +++++++++++---------------- source/ccspinterface/dbusInterface.h | 14 +- 2 files changed, 259 insertions(+), 385 deletions(-) diff --git a/source/ccspinterface/dbusInterface.c b/source/ccspinterface/dbusInterface.c index 6fc577ca..0a92824d 100755 --- a/source/ccspinterface/dbusInterface.c +++ b/source/ccspinterface/dbusInterface.c @@ -43,13 +43,6 @@ #define BUFF_LEN 1024 #define MAX_PARAM_LEN 128 -/* D-Bus Service Configuration */ -#define T2_DBUS_SERVICE_NAME "telemetry.t2" -#define T2_DBUS_OBJECT_PATH "/telemetry/t2" -#define T2_DBUS_INTERFACE_NAME "telemetry.t2.interface" -#define T2_DBUS_SIGNAL_EVENT "TelemetryEvent" -#define T2_DBUS_SIGNAL_PROFILE_UPDATE "ProfileUpdate" - /* Global D-Bus handle */ static T2DbusHandle_t t2dbus_handle = {NULL, NULL, false}; static void (*profileUpdateCallback)(void) = NULL; @@ -73,54 +66,205 @@ bool isDbusInitialized(void) { return t2dbus_handle.is_initialized; } -/** - * @brief D-Bus filter function for incoming messages - */ -static DBusHandlerResult dbusMessageFilter(DBusConnection *connection, - DBusMessage *message, - void *user_data) { - (void)connection; - (void)user_data; - - T2Debug("%s ++in\n", __FUNCTION__); +/* Handle GetOperationalStatus Method */ +static DBusHandlerResult handle_get_operational_status(DBusConnection *connection, DBusMessage *message) { + T2Debug("handle_get_operational_status: Received GetOperationalStatus method call"); + + DBusError error; + dbus_error_init(&error); + + const char* param_name = NULL; + if (!dbus_message_get_args(message, &error, + DBUS_TYPE_STRING, ¶m_name, + DBUS_TYPE_INVALID)) { + T2Error("Failed to parse GetOperationalStatus arguments: %s", error.message); + dbus_error_free(&error); + return DBUS_HANDLER_RESULT_NOT_YET_HANDLED; + } + + T2Info("GetOperationalStatus called with param_name: %s", param_name); + + uint32_t value = 0; - if (dbus_message_is_signal(message, T2_DBUS_INTERFACE_NAME, T2_DBUS_SIGNAL_EVENT)) { - DBusMessageIter args; - char *eventName = NULL; - char *eventValue = NULL; + /* Check if requesting operational status */ + if (g_server_ready) { + value = t2ReadyStatus; + T2Info("Returning operational status: READY (0x%08X)", value); + } else { + value = 0; + T2Info("Returning operational status: NOT READY (0x%08X)", value); + } + + /* Create reply */ + DBusMessage *reply = dbus_message_new_method_return(message); + if (!reply) { + T2Error("Failed to create reply message"); + return DBUS_HANDLER_RESULT_NEED_MEMORY; + } + + if (!dbus_message_append_args(reply, + DBUS_TYPE_UINT32, &value, + DBUS_TYPE_INVALID)) { + T2Error("Failed to append reply arguments"); + dbus_message_unref(reply); + return DBUS_HANDLER_RESULT_NEED_MEMORY; + } + + if (!dbus_connection_send(connection, reply, NULL)) { + T2Error("Failed to send reply"); + dbus_message_unref(reply); + return DBUS_HANDLER_RESULT_NEED_MEMORY; + } + + T2Debug("GetOperationalStatus: Reply sent successfully"); + dbus_message_unref(reply); + // dbus_connection_flush(connection); + + return DBUS_HANDLER_RESULT_HANDLED; +} + +/* Handle SendT2Event Method */ +static DBusHandlerResult handle_send_t2_event(DBusConnection *connection, DBusMessage *message) { + T2Debug("handle_send_t2_event: Received SendT2Event method call"); + + DBusError error; + dbus_error_init(&error); + + const char* marker_name = NULL; + const char* data = NULL; + + if (!dbus_message_get_args(message, &error, + DBUS_TYPE_STRING, &marker_name, + DBUS_TYPE_STRING, &data, + DBUS_TYPE_INVALID)) { + T2Error("Failed to parse SendT2Event arguments: %s", error.message); + dbus_error_free(&error); + return DBUS_HANDLER_RESULT_NOT_YET_HANDLED; + } + + if (marker_name && data && eventCallBack) { + T2Debug("Received event: name=%s, value=%s\n", marker_name, data); + eventCallBack(strdup(marker_name), strdup(data)); + } + + /* Create empty reply (method returns void) */ + DBusMessage *reply = dbus_message_new_method_return(message); + if (!reply) { + T2Error("Failed to create reply message"); + return DBUS_HANDLER_RESULT_NEED_MEMORY; + } + + if (!dbus_connection_send(connection, reply, NULL)) { + T2Error("Failed to send reply"); + dbus_message_unref(reply); + return DBUS_HANDLER_RESULT_NEED_MEMORY; + } + + T2Debug("SendT2Event: Reply sent successfully"); + dbus_message_unref(reply); + // dbus_connection_flush(connection); + + return DBUS_HANDLER_RESULT_HANDLED; +} + +/* Handle GetMarkerList Method */ +static DBusHandlerResult handle_get_marker_list(DBusConnection *connection, DBusMessage *message) { + T2Debug("handle_get_marker_list: Received GetMarkerList method call"); + + DBusMessage *reply = NULL; + DBusError error; + dbus_error_init(&error); + + const char* component_name = NULL; + if (!dbus_message_get_args(message, &error, + DBUS_TYPE_STRING, &component_name, + DBUS_TYPE_INVALID)) { + T2Error("Failed to parse GetMarkerList arguments: %s", error.message); + dbus_error_free(&error); + return DBUS_HANDLER_RESULT_NOT_YET_HANDLED; + } - if (!dbus_message_iter_init(message, &args)) { - T2Error("Event signal has no arguments\n"); - } else { - /* Get event name */ - if (dbus_message_iter_get_arg_type(&args) == DBUS_TYPE_STRING) { - dbus_message_iter_get_basic(&args, &eventName); - dbus_message_iter_next(&args); - } - - /* Get event value */ - if (dbus_message_iter_get_arg_type(&args) == DBUS_TYPE_STRING) { - dbus_message_iter_get_basic(&args, &eventValue); - } - - if (eventName && eventValue && eventCallBack) { - T2Debug("Received event: name=%s, value=%s\n", eventName, eventValue); - eventCallBack(strdup(eventName), strdup(eventValue)); + T2Info("GetMarkerList called for component: %s", component_name); + + if (!getMarkerListCallBack) { + T2Error("GetMarkerList callback not registered\n"); + reply = dbus_message_new_error(message, DBUS_ERROR_FAILED, + "Marker list callback not initialized"); + } + else + { + Vector *markerList = NULL; + getMarkerListCallBack(component_name, (void**)&markerList); + char markerListStr[4096] = ""; + if (markerList && Vector_Size(markerList) > 0) { + for (size_t i = 0; i < Vector_Size(markerList); i++) { + char *marker = (char*)Vector_At(markerList, i); + if (marker) { + if (i > 0) strcat(markerListStr, ","); + strcat(markerListStr, marker); + } } + Vector_Destroy(markerList, free); } - - return DBUS_HANDLER_RESULT_HANDLED; + + reply = dbus_message_new_method_return(message); + if (!reply) { + T2Error("Failed to create reply message"); + return DBUS_HANDLER_RESULT_NEED_MEMORY; + } + const char *result = markerListStr; + + if (!dbus_message_append_args(reply, + DBUS_TYPE_STRING, &result, + DBUS_TYPE_INVALID)) { + T2Error("Failed to append reply arguments"); + dbus_message_unref(reply); + return DBUS_HANDLER_RESULT_NEED_MEMORY; + } + + T2Debug("Returning marker list: %s\n", markerListStr); + + if (!dbus_connection_send(connection, reply, NULL)) { + T2Error("Failed to send reply"); + dbus_message_unref(reply); + return DBUS_HANDLER_RESULT_NEED_MEMORY; + } + + // dbus_connection_flush(connection); + T2Debug("GetMarkerList: Reply sent successfully"); + dbus_message_unref(reply); } - else if (dbus_message_is_signal(message, T2_DBUS_INTERFACE_NAME, T2_DBUS_SIGNAL_PROFILE_UPDATE)) { - T2Info("Received ProfileUpdate signal\n"); - /* Invoke profile update callback */ - if (profileUpdateCallback) { - profileUpdateCallback(); + + return DBUS_HANDLER_RESULT_HANDLED; +} + +/* Message Handler */ +static DBusHandlerResult message_handler(DBusConnection *connection, DBusMessage *message, void *user_data) { + (void)user_data; + + const char* interface = dbus_message_get_interface(message); + const char* member = dbus_message_get_member(message); + const char* path = dbus_message_get_path(message); + + T2Debug("Received D-Bus message: interface=%s, member=%s, path=%s", + interface ? interface : "NULL", + member ? member : "NULL", + path ? path : "NULL"); + + /* Check if message is for our interface */ + if (interface && strcmp(interface, T2_DBUS_INTERFACE_NAME) == 0) + { + if (dbus_message_is_method_call(message, T2_DBUS_INTERFACE_NAME, "GetOperationalStatus")) { + return handle_get_operational_status(connection, message); + } + else if (dbus_message_is_method_call(message, T2_DBUS_INTERFACE_NAME, "SendT2Event")) { + return handle_send_t2_event(connection, message); + } + else if (dbus_message_is_method_call(message, T2_DBUS_INTERFACE_NAME, "GetMarkerList")) { + return handle_get_marker_list(connection, message); } - return DBUS_HANDLER_RESULT_HANDLED; } - - T2Debug("%s --out\n", __FUNCTION__); + return DBUS_HANDLER_RESULT_NOT_YET_HANDLED; } @@ -133,15 +277,46 @@ static void* dbusListenerThreadFunc(void *arg) { T2Debug("%s ++in\n", __FUNCTION__); while (!stopListenerThread && t2dbus_handle.connection) { - /* Process messages with timeout */ dbus_connection_read_write_dispatch(t2dbus_handle.connection, 100); usleep(1000); } - T2Debug("%s --out\n", __FUNCTION__); return NULL; } +T2ERROR publishdbusEventsProfileUpdates(void) +{ + T2Debug("%s ++in\n", __FUNCTION__); + if(!t2dbus_handle.is_initialized) + { + T2Error("D-Bus not initialized\n"); + return T2ERROR_INTERNAL_ERROR; + } + + DBusMessage *signal = dbus_message_new_signal(T2_DBUS_OBJECT_PATH, + T2_DBUS_EVENT_INTERFACE_NAME, + T2_DBUS_SIGNAL_PROFILE_UPDATE); + if (!signal) { + T2Error("Failed to create ProfileUpdate signal"); + return T2ERROR_FAILURE; + } + + /* Send signal - this queues the message */ + dbus_uint32_t serial = 0; + if (!dbus_connection_send(t2dbus_handle.connection, signal, &serial)) { + T2Error("Failed to send ProfileUpdate signal - out of memory"); + dbus_message_unref(signal); + return T2ERROR_FAILURE; + } + + //dbus_message_unref(signal); + + /* Flush to ensure signal is sent immediately */ + //dbus_connection_flush(t2dbus_handle.connection); + + T2Debug("ProfileUpdate signal sent successfully (serial=%u)", serial); +} + /** * @brief Initialize D-Bus interface */ @@ -158,6 +333,11 @@ T2ERROR dBusInterface_Init(const char *component_name) { DBusError error; dbus_error_init(&error); + + if (!dbus_threads_init_default()) { + LOG_ERROR("Failed to initialize D-Bus threading"); + return 1; + } /* Connect to system bus */ t2dbus_handle.connection = dbus_bus_get(DBUS_BUS_SYSTEM, &error); @@ -174,16 +354,9 @@ T2ERROR dBusInterface_Init(const char *component_name) { return T2ERROR_FAILURE; } - /* Request well-known name */ - char service_name[256]; - if (component_name) { - snprintf(service_name, sizeof(service_name), "%s.%s", - T2_DBUS_SERVICE_NAME, component_name); - } else { - snprintf(service_name, sizeof(service_name), "%s", T2_DBUS_SERVICE_NAME); - } + - int ret = dbus_bus_request_name(t2dbus_handle.connection, service_name, + int ret = dbus_bus_request_name(t2dbus_handle.connection, T2_DBUS_SERVICE_NAME, DBUS_NAME_FLAG_REPLACE_EXISTING, &error); if (dbus_error_is_set(&error)) { T2Error("D-Bus name request error: %s\n", error.message); @@ -195,15 +368,33 @@ T2ERROR dBusInterface_Init(const char *component_name) { } if (ret != DBUS_REQUEST_NAME_REPLY_PRIMARY_OWNER) { - T2Warning("Not primary owner of D-Bus name\n"); + T2Error("Not primary owner of the name (ret=%d)", ret); + dbus_connection_unref(t2dbus_handle.connection); + t2dbus_handle.connection = NULL; + pthread_mutex_unlock(&dbusMutex); + return T2ERROR_FAILURE; } + T2Info("Acquired service name: %s", T2_DBUS_SERVICE_NAME); /* Store unique name */ t2dbus_handle.unique_name = strdup(dbus_bus_get_unique_name(t2dbus_handle.connection)); - - /* Add message filter */ - dbus_connection_add_filter(t2dbus_handle.connection, dbusMessageFilter, NULL, NULL); - + + /* Register object path */ + DBusObjectPathVTable vtable = { + .message_function = message_handler, + .unregister_function = NULL + }; + + if (!dbus_connection_register_object_path(t2dbus_handle.connection, T2_DBUS_OBJECT_PATH, + &vtable, NULL)) { + T2Error("Failed to register object path"); + dbus_connection_unref(t2dbus_handle.connection); + return T2ERROR_FAILURE; + } + T2Info("Registered object path: %s", T2_DBUS_OBJECT_PATH); + + //TODO check ready status based on component initialization + t2ReadyStatus = T2_STATE_COMPONENT_READY; t2dbus_handle.is_initialized = true; /* Start listener thread */ @@ -214,10 +405,11 @@ T2ERROR dBusInterface_Init(const char *component_name) { pthread_mutex_unlock(&dbusMutex); return T2ERROR_FAILURE; } + //TODO change to detached thread pthread_mutex_unlock(&dbusMutex); - T2Info("D-Bus interface initialized successfully with name: %s\n", service_name); + T2Info("D-Bus interface initialized successfully with name: %s\n", T2_DBUS_SERVICE_NAME); T2Debug("%s --out\n", __FUNCTION__); return T2ERROR_SUCCESS; @@ -248,7 +440,6 @@ void dBusInterface_Uninit(void) { /* Clean up D-Bus connection */ if (t2dbus_handle.connection) { - dbus_connection_remove_filter(t2dbus_handle.connection, dbusMessageFilter, NULL); dbus_connection_unref(t2dbus_handle.connection); t2dbus_handle.connection = NULL; } @@ -402,151 +593,6 @@ T2ERROR setDbusParameterVal(const char* paramName, const char* paramValue, int p return T2ERROR_SUCCESS; } -/** - * @brief Get multiple profile parameter values via D-Bus - */ -Vector* getDbusProfileParamValues(Vector *paramList, int execcount) { - T2Debug("%s ++in\n", __FUNCTION__); - - if (!paramList) { - T2Error("Invalid parameter list\n"); - return NULL; - } - - if (!t2dbus_handle.is_initialized) { - if (dBusInterface_Init(NULL) != T2ERROR_SUCCESS) { - return NULL; - } - } - - Vector *profileValueList = NULL; - Vector_Create(&profileValueList); - - /* Iterate through parameters and fetch values */ - for (size_t i = 0; i < Vector_Size(paramList); i++) { - Param *param = (Param *)Vector_At(paramList, i); - if (!param) continue; - - profileValues *profVals = (profileValues *)malloc(sizeof(profileValues)); - if (!profVals) continue; - - /* Check skip frequency */ - if (param->skipFreq > 0 && (execcount % (param->skipFreq + 1) != 0)) { - T2Debug("Skipping parameter: %s as per skipFreq: %d\n", - param->name, param->skipFreq); - profVals->paramValues = NULL; - profVals->paramValueCount = 0; - Vector_PushBack(profileValueList, profVals); - continue; - } - - /* Get parameter value */ - char *value = NULL; - if (getDbusParameterVal(param->alias, &value) == T2ERROR_SUCCESS && value) { - tr181ValStruct_t **paramValues = (tr181ValStruct_t **)malloc(sizeof(tr181ValStruct_t *)); - paramValues[0] = (tr181ValStruct_t *)malloc(sizeof(tr181ValStruct_t)); - paramValues[0]->parameterName = strdup(param->alias); - paramValues[0]->parameterValue = value; - - profVals->paramValues = paramValues; - profVals->paramValueCount = 1; - } else { - /* Parameter not found */ - tr181ValStruct_t **paramValues = (tr181ValStruct_t **)malloc(sizeof(tr181ValStruct_t *)); - paramValues[0] = (tr181ValStruct_t *)malloc(sizeof(tr181ValStruct_t)); - paramValues[0]->parameterName = strdup(param->alias); - paramValues[0]->parameterValue = strdup("NULL"); - - profVals->paramValues = paramValues; - profVals->paramValueCount = 1; - } - - Vector_PushBack(profileValueList, profVals); - } - - T2Debug("%s --out\n", __FUNCTION__); - return profileValueList; -} - -/** - * @brief Subscribe to D-Bus signal - */ -T2ERROR dbusSubscribeSignal(const char* signal_name) { - T2Debug("%s ++in\n", __FUNCTION__); - - if (!signal_name) { - T2Error("Invalid signal name\n"); - return T2ERROR_INVALID_ARGS; - } - - if (!t2dbus_handle.is_initialized) { - if (dBusInterface_Init(NULL) != T2ERROR_SUCCESS) { - T2Error("dbus not initialized\n"); - return T2ERROR_FAILURE; - } - } - - char rule[512]; - DBusError error; - dbus_error_init(&error); - - /* Create match rule */ - snprintf(rule, sizeof(rule), - "type='signal',interface='%s',member='%s'", - T2_DBUS_INTERFACE_NAME, signal_name); - - dbus_bus_add_match(t2dbus_handle.connection, rule, &error); - - if (dbus_error_is_set(&error)) { - T2Error("Failed to add match rule: %s\n", error.message); - dbus_error_free(&error); - return T2ERROR_FAILURE; - } - - T2Info("Subscribed to signal: %s\n", signal_name); - T2Debug("%s --out\n", __FUNCTION__); - - return T2ERROR_SUCCESS; -} - -/** - * @brief Unsubscribe from D-Bus signal - */ -T2ERROR dbusUnsubscribeSignal(const char* signal_name) { - T2Debug("%s ++in\n", __FUNCTION__); - - if (!signal_name) { - T2Error("Invalid signal name\n"); - return T2ERROR_INVALID_ARGS; - } - - if (!t2dbus_handle.is_initialized) { - T2Error("D-Bus not initialized\n"); - return T2ERROR_FAILURE; - } - - char rule[512]; - DBusError error; - dbus_error_init(&error); - - /* Create match rule */ - snprintf(rule, sizeof(rule), - "type='signal',interface='%s',member='%s'", - T2_DBUS_INTERFACE_NAME, signal_name); - - dbus_bus_remove_match(t2dbus_handle.connection, rule, &error); - - if (dbus_error_is_set(&error)) { - T2Error("Failed to remove match rule: %s\n", error.message); - dbus_error_free(&error); - return T2ERROR_FAILURE; - } - - T2Info("Unsubscribed from signal: %s\n", signal_name); - T2Debug("%s --out\n", __FUNCTION__); - - return T2ERROR_SUCCESS; -} /** * @brief Register for telemetry event notifications @@ -561,12 +607,6 @@ T2ERROR registerDbusT2EventListener(TelemetryEventCallback eventCB) { eventCallBack = eventCB; - /* Subscribe to event signal */ - if (dbusSubscribeSignal(T2_DBUS_SIGNAL_EVENT) != T2ERROR_SUCCESS) { - T2Error("Failed to subscribe to event signal\n"); - return T2ERROR_FAILURE; - } - T2Debug("%s --out\n", __FUNCTION__); return T2ERROR_SUCCESS; } @@ -579,164 +619,10 @@ T2ERROR unregisterDbusT2EventListener(void) { eventCallBack = NULL; - /* Unsubscribe from event signal */ - dbusUnsubscribeSignal(T2_DBUS_SIGNAL_EVENT); - T2Debug("%s --out\n", __FUNCTION__); return T2ERROR_SUCCESS; } -/** - * @brief Publish report upload status - */ -void dbusPublishReportUploadStatus(const char* status) { - T2Debug("%s ++in\n", __FUNCTION__); - - if (!status) { - T2Error("Invalid status\n"); - return; - } - - if (!t2dbus_handle.is_initialized) { - T2Warning("D-Bus not initialized\n"); - return; - } - - DBusMessage *signal = dbus_message_new_signal(T2_DBUS_OBJECT_PATH, - T2_DBUS_INTERFACE_NAME, - T2_DBUS_SIGNAL_UPLOAD_STATUS); - if (!signal) { - T2Error("Failed to create signal\n"); - return; - } - - if (!dbus_message_append_args(signal, DBUS_TYPE_STRING, &status, DBUS_TYPE_INVALID)) { - T2Error("Failed to append arguments\n"); - dbus_message_unref(signal); - return; - } - - dbus_connection_send(t2dbus_handle.connection, signal, NULL); - dbus_connection_flush(t2dbus_handle.connection); - dbus_message_unref(signal); - - T2Info("Published upload status: %s\n", status); - T2Debug("%s --out\n", __FUNCTION__); -} - -static DBusHandlerResult dbusMethodDispatcher(DBusConnection *conn, - DBusMessage *message, - void *user_data) { - (void)conn; - (void)user_data; - - const char *method = dbus_message_get_member(message); - const char *interface = dbus_message_get_interface(message); - - if (!interface || strcmp(interface, T2_DBUS_INTERFACE_NAME) != 0) { - return DBUS_HANDLER_RESULT_NOT_YET_HANDLED; - } - - if (!method) { - return DBUS_HANDLER_RESULT_NOT_YET_HANDLED; - } - - T2Debug("Received method call: %s\n", method); - - DBusMessage *reply = NULL; - - if (strcmp(method, "GetMarkerList") == 0) { - const char *component = NULL; - DBusError error; - dbus_error_init(&error); - - if (!dbus_message_get_args(message, &error, - DBUS_TYPE_STRING, &component, - DBUS_TYPE_INVALID)) { - T2Error("Failed to parse GetMarkerList args: %s\n", error.message); - dbus_error_free(&error); - reply = dbus_message_new_error(message, DBUS_ERROR_INVALID_ARGS, - "Expected string argument"); - } else if (!getMarkerListCallBack) { - T2Error("GetMarkerList callback not registered\n"); - reply = dbus_message_new_error(message, DBUS_ERROR_FAILED, - "Marker list callback not initialized"); - } else { - Vector *markerList = NULL; - getMarkerListCallBack(component, (void**)&markerList); - - char markerListStr[4096] = ""; - if (markerList && Vector_Size(markerList) > 0) { - for (size_t i = 0; i < Vector_Size(markerList); i++) { - char *marker = (char*)Vector_At(markerList, i); - if (marker) { - if (i > 0) strcat(markerListStr, ","); - strcat(markerListStr, marker); - } - } - Vector_Destroy(markerList, free); - } - - reply = dbus_message_new_method_return(message); - const char *result = markerListStr; - dbus_message_append_args(reply, - DBUS_TYPE_STRING, &result, - DBUS_TYPE_INVALID); - T2Debug("Returning marker list: %s\n", markerListStr); - } - } - else if (strcmp(method, "GetOperationalStatus") == 0) { - reply = dbus_message_new_method_return(message); - dbus_message_append_args(reply, - DBUS_TYPE_UINT32, &t2ReadyStatus, - DBUS_TYPE_INVALID); - T2Debug("Returning operational status: %u\n", t2ReadyStatus); - } - else { - return DBUS_HANDLER_RESULT_NOT_YET_HANDLED; - } - - if (reply) { - dbus_connection_send(conn, reply, NULL); - dbus_connection_flush(conn); - dbus_message_unref(reply); - return DBUS_HANDLER_RESULT_HANDLED; - } - - return DBUS_HANDLER_RESULT_NOT_YET_HANDLED; -} - -T2ERROR registerDbusMethodProviders(void) { - T2Debug("%s ++in\n", __FUNCTION__); - - if (!t2dbus_handle.is_initialized) { - T2Error("D-Bus not initialized\n"); - return T2ERROR_FAILURE; - } - - static const DBusObjectPathVTable vtable = { - NULL, - dbusMethodDispatcher, - NULL, - NULL, - NULL, - NULL - }; - - if (!dbus_connection_register_object_path(t2dbus_handle.connection, - T2_DBUS_OBJECT_PATH, - &vtable, - NULL)) { - T2Error("Failed to register object path\n"); - return T2ERROR_FAILURE; - } - - T2Info("Registered D-Bus method providers at %s\n", T2_DBUS_OBJECT_PATH); - T2Debug("%s --out\n", __FUNCTION__); - - return T2ERROR_SUCCESS; -} - T2ERROR registerGetMarkerListCallback(T2EventMarkerListCallback callback) { T2Debug("%s ++in\n", __FUNCTION__); @@ -751,5 +637,3 @@ T2ERROR registerGetMarkerListCallback(T2EventMarkerListCallback callback) { return T2ERROR_SUCCESS; } - - \ No newline at end of file diff --git a/source/ccspinterface/dbusInterface.h b/source/ccspinterface/dbusInterface.h index efedf5c6..c53bb15f 100755 --- a/source/ccspinterface/dbusInterface.h +++ b/source/ccspinterface/dbusInterface.h @@ -45,18 +45,14 @@ #define T2_DBUS_SERVICE_NAME "telemetry.t2" #define T2_DBUS_OBJECT_PATH "/telemetry/t2" #define T2_DBUS_INTERFACE_NAME "telemetry.t2.interface" +#define T2_DBUS_EVENT_INTERFACE_NAME "telemetry.t2.event.interface" /* D-Bus Method Names */ #define T2_DBUS_METHOD_GET_PARAM "GetParameter" #define T2_DBUS_METHOD_SET_PARAM "SetParameter" -#define T2_DBUS_METHOD_SUBSCRIBE "SubscribeEvent" -#define T2_DBUS_METHOD_UNSUBSCRIBE "UnsubscribeEvent" -#define T2_DBUS_METHOD_CALL "CallMethod" /* D-Bus Signal Names */ -#define T2_DBUS_SIGNAL_EVENT "TelemetryEvent" #define T2_DBUS_SIGNAL_PROFILE_UPDATE "ProfileUpdate" -#define T2_DBUS_SIGNAL_UPLOAD_STATUS "UploadStatus" /* D-Bus Error Codes */ #define T2_DBUS_ERROR_SUCCESS 0 @@ -85,17 +81,11 @@ void dBusInterface_Uninit(void); T2ERROR getDbusParameterVal(const char* paramName, char **paramValue); T2ERROR setDbusParameterVal(const char* paramName, const char* paramValue, int paramType); -Vector* getDbusProfileParamValues(Vector *paramList, int execcount); T2ERROR registerDbusT2EventListener(TelemetryEventCallback eventCB); T2ERROR unregisterDbusT2EventListener(void); -T2ERROR dbusSubscribeSignal(const char* signal_name); -T2ERROR dbusUnsubscribeSignal(const char* signal_name); - -void dbusPublishReportUploadStatus(const char* status); - -T2ERROR registerDbusMethodProviders(void); +T2ERROR publishdbusEventsProfileUpdates(void); T2ERROR registerGetMarkerListCallback(T2EventMarkerListCallback callback); #endif /* _DBUSINTERFACE_H_ */ From 787397a558d78036e165e3d9b2d33a916bca3a38 Mon Sep 17 00:00:00 2001 From: Muhammed rafi c Date: Tue, 27 Jan 2026 11:46:42 +0000 Subject: [PATCH 09/23] update the server side code --- source/bulkdata/t2eventreceiver.c | 27 +++++++++------------------ source/bulkdata/t2markers.c | 11 +---------- source/ccspinterface/busInterface.c | 14 ++++++++++++++ source/ccspinterface/dbusInterface.c | 22 ++++++++-------------- source/ccspinterface/dbusInterface.h | 2 +- source/telemetry2_0.c | 16 ---------------- 6 files changed, 33 insertions(+), 59 deletions(-) diff --git a/source/bulkdata/t2eventreceiver.c b/source/bulkdata/t2eventreceiver.c index ca773cd5..aba564b0 100644 --- a/source/bulkdata/t2eventreceiver.c +++ b/source/bulkdata/t2eventreceiver.c @@ -335,24 +335,15 @@ T2ERROR T2ER_Init() EREnabled = true; - /* Old RBUS event registration - commented out for DBUS migration */ - // if(isRbusEnabled()) - // { - // T2Debug("Register event call back function T2ER_Push \n"); - // registerForTelemetryEvents(T2ER_Push); - // } - // else - // { - // T2Debug("Register event call back function T2ER_PushDataWithDelim \n"); - // registerForTelemetryEvents(T2ER_PushDataWithDelim); - // } - - /* Register DBUS event listener for TelemetryEvent signals */ - T2ERROR ret = registerDbusT2EventListener(T2ER_Push); - if(ret != T2ERROR_SUCCESS) { - T2Error("Failed to register DBUS event listener with error: %d\n", ret); - } else { - T2Info("DBUS event listener registered successfully\n"); + if(isRbusEnabled()) + { + T2Debug("Register event call back function T2ER_Push \n"); + registerForTelemetryEvents(T2ER_Push); + } + else + { + T2Debug("Register event call back function T2ER_PushDataWithDelim \n"); + registerForTelemetryEvents(T2ER_PushDataWithDelim); } system("touch /tmp/.t2ReadyToReceiveEvents"); diff --git a/source/bulkdata/t2markers.c b/source/bulkdata/t2markers.c index f72651e6..baf6aab9 100644 --- a/source/bulkdata/t2markers.c +++ b/source/bulkdata/t2markers.c @@ -331,19 +331,10 @@ void createComponentDataElements() char *compName = (char*) Vector_At(componentList, i); if(compName) { - /* Old RBUS registration - commented out for DBUS migration */ - // regDEforCompEventList(compName, getComponentMarkerList); + regDEforCompEventList(compName, getComponentMarkerList); } } pthread_mutex_unlock(&t2CompListMutex); - /* Register DBUS callback for GetMarkerList method */ - T2ERROR ret = registerGetMarkerListCallback(getComponentMarkerList); - if(ret != T2ERROR_SUCCESS) { - T2Error("Failed to register DBUS marker list callback with error: %d\n", ret); - } else { - T2Info("DBUS marker list callback registered successfully\n"); - } - T2Debug("%s --out\n", __FUNCTION__); } diff --git a/source/ccspinterface/busInterface.c b/source/ccspinterface/busInterface.c index 60c0051a..93c0ccda 100644 --- a/source/ccspinterface/busInterface.c +++ b/source/ccspinterface/busInterface.c @@ -29,6 +29,7 @@ #endif #include "rbusInterface.h" +#include "dbusInterface.h" static bool isRbus = false ; static bool isBusInit = false ; @@ -59,6 +60,15 @@ static bool busInit( ) T2Debug("%s --RBUS mode is active \n", __FUNCTION__); //CID 158206:Unchecked return value } isBusInit = true; + + if (dBusInterface_Init() == T2ERROR_SUCCESS) + { + T2Debug("%s --DBUS mode is active \n", __FUNCTION__); //CID 158206:Unchecked return value + } + else + { + T2Error("%s --DBUS init failed \n", __FUNCTION__); + } } T2Debug("%s --out \n", __FUNCTION__); return isBusInit; @@ -119,11 +129,15 @@ T2ERROR registerForTelemetryEvents(TelemetryEventCallback eventCB) { T2ERROR ret = T2ERROR_FAILURE; T2Debug("%s ++in\n", __FUNCTION__); + if(!isBusInit) { busInit(); } + ret = registerDbusT2EventListener(eventCB); + + if (isRbus) { ret = registerRbusT2EventListener(eventCB); diff --git a/source/ccspinterface/dbusInterface.c b/source/ccspinterface/dbusInterface.c index 0a92824d..32cb9c48 100755 --- a/source/ccspinterface/dbusInterface.c +++ b/source/ccspinterface/dbusInterface.c @@ -45,7 +45,6 @@ /* Global D-Bus handle */ static T2DbusHandle_t t2dbus_handle = {NULL, NULL, false}; -static void (*profileUpdateCallback)(void) = NULL; /* Callback handlers */ static TelemetryEventCallback eventCallBack = NULL; @@ -85,15 +84,9 @@ static DBusHandlerResult handle_get_operational_status(DBusConnection *connectio T2Info("GetOperationalStatus called with param_name: %s", param_name); uint32_t value = 0; - - /* Check if requesting operational status */ - if (g_server_ready) { - value = t2ReadyStatus; - T2Info("Returning operational status: READY (0x%08X)", value); - } else { - value = 0; - T2Info("Returning operational status: NOT READY (0x%08X)", value); - } + /* TODO check oprtational status of specific component param_name will componet name */ + value = t2ReadyStatus; + T2Info("Returning operational status for %s: 0x%08X", param_name, value); /* Create reply */ DBusMessage *reply = dbus_message_new_method_return(message); @@ -315,12 +308,13 @@ T2ERROR publishdbusEventsProfileUpdates(void) //dbus_connection_flush(t2dbus_handle.connection); T2Debug("ProfileUpdate signal sent successfully (serial=%u)", serial); + return T2ERROR_SUCCESS; } /** * @brief Initialize D-Bus interface */ -T2ERROR dBusInterface_Init(const char *component_name) { +T2ERROR dBusInterface_Init() { T2Debug("%s ++in\n", __FUNCTION__); pthread_mutex_lock(&dbusMutex); @@ -335,7 +329,7 @@ T2ERROR dBusInterface_Init(const char *component_name) { dbus_error_init(&error); if (!dbus_threads_init_default()) { - LOG_ERROR("Failed to initialize D-Bus threading"); + T2Error("Failed to initialize D-Bus threading"); return 1; } @@ -468,7 +462,7 @@ T2ERROR getDbusParameterVal(const char* paramName, char **paramValue) { } if (!t2dbus_handle.is_initialized) { - if (dBusInterface_Init(NULL) != T2ERROR_SUCCESS) { + if (dBusInterface_Init() != T2ERROR_SUCCESS) { return T2ERROR_FAILURE; } } @@ -543,7 +537,7 @@ T2ERROR setDbusParameterVal(const char* paramName, const char* paramValue, int p } if (!t2dbus_handle.is_initialized) { - if (dBusInterface_Init(NULL) != T2ERROR_SUCCESS) { + if (dBusInterface_Init() != T2ERROR_SUCCESS) { return T2ERROR_FAILURE; } } diff --git a/source/ccspinterface/dbusInterface.h b/source/ccspinterface/dbusInterface.h index c53bb15f..6d958290 100755 --- a/source/ccspinterface/dbusInterface.h +++ b/source/ccspinterface/dbusInterface.h @@ -76,7 +76,7 @@ typedef struct { typedef void (*dbusMethodCallBackPtr)(DBusMessage *reply, int retStatus); bool isDbusInitialized(void); -T2ERROR dBusInterface_Init(const char *component_name); +T2ERROR dBusInterface_Init(void); void dBusInterface_Uninit(void); T2ERROR getDbusParameterVal(const char* paramName, char **paramValue); diff --git a/source/telemetry2_0.c b/source/telemetry2_0.c index 5dee2c68..059e976a 100644 --- a/source/telemetry2_0.c +++ b/source/telemetry2_0.c @@ -254,22 +254,6 @@ static void t2DaemonMainModeInit( ) #endif #endif - /* Initialize DBUS for CommonLib <-> BulkData communication */ - T2ERROR dbusRet = dBusInterface_Init("telemetry2_0"); - if(dbusRet != T2ERROR_SUCCESS) { - T2Error("DBUS initialization failed for telemetry2_0 daemon with error: %d - proceeding without DBUS support\n", dbusRet); - } else { - T2Info("DBUS interface initialized successfully\n"); - - /* Register DBUS method providers for GetMarkerList and GetOperationalStatus */ - dbusRet = registerDbusMethodProviders(); - if(dbusRet != T2ERROR_SUCCESS) { - T2Error("DBUS method provider registration failed with error: %d\n", dbusRet); - } else { - T2Info("DBUS method providers registered successfully\n"); - } - } - /** * Create a Signal Mask for signals that need to be blocked while using fork */ From adfa20ca27b4ca347aa336ef0e372fac45200e82 Mon Sep 17 00:00:00 2001 From: Muhammed rafi c Date: Tue, 27 Jan 2026 12:32:58 +0000 Subject: [PATCH 10/23] updated client code --- source/bulkdata/t2eventreceiver.c | 1 - source/bulkdata/t2markers.c | 2 - source/ccspinterface/busInterface.c | 2 - .../commonlib/telemetry_busmessage_sender.c | 1552 +++++++++++------ source/telemetry2_0.c | 2 - 5 files changed, 974 insertions(+), 585 deletions(-) diff --git a/source/bulkdata/t2eventreceiver.c b/source/bulkdata/t2eventreceiver.c index aba564b0..5099e0e0 100644 --- a/source/bulkdata/t2eventreceiver.c +++ b/source/bulkdata/t2eventreceiver.c @@ -29,7 +29,6 @@ #include "t2log_wrapper.h" #include "busInterface.h" #include "dca.h" -#include "dbusInterface.h" #define T2EVENTQUEUE_MAX_LIMIT 200 #define MESSAGE_DELIMITER "<#=#>" diff --git a/source/bulkdata/t2markers.c b/source/bulkdata/t2markers.c index baf6aab9..20bb3b3e 100644 --- a/source/bulkdata/t2markers.c +++ b/source/bulkdata/t2markers.c @@ -25,7 +25,6 @@ #include "t2eventreceiver.h" #include "t2log_wrapper.h" #include "rbusInterface.h" -#include "dbusInterface.h" /** * Store event markers associated with a component @@ -335,6 +334,5 @@ void createComponentDataElements() } } pthread_mutex_unlock(&t2CompListMutex); - T2Debug("%s --out\n", __FUNCTION__); } diff --git a/source/ccspinterface/busInterface.c b/source/ccspinterface/busInterface.c index 93c0ccda..9c3ed504 100644 --- a/source/ccspinterface/busInterface.c +++ b/source/ccspinterface/busInterface.c @@ -129,7 +129,6 @@ T2ERROR registerForTelemetryEvents(TelemetryEventCallback eventCB) { T2ERROR ret = T2ERROR_FAILURE; T2Debug("%s ++in\n", __FUNCTION__); - if(!isBusInit) { busInit(); @@ -137,7 +136,6 @@ T2ERROR registerForTelemetryEvents(TelemetryEventCallback eventCB) ret = registerDbusT2EventListener(eventCB); - if (isRbus) { ret = registerRbusT2EventListener(eventCB); diff --git a/source/commonlib/telemetry_busmessage_sender.c b/source/commonlib/telemetry_busmessage_sender.c index 7247511d..a2ce076a 100644 --- a/source/commonlib/telemetry_busmessage_sender.c +++ b/source/commonlib/telemetry_busmessage_sender.c @@ -26,15 +26,17 @@ #include #include #include + #if defined(CCSP_SUPPORT_ENABLED) #include #include #include #endif #include -# if RBUS_ENABLED +#if defined(RBUS_SUPPORT_ENABLED) #include #endif + #include "telemetry_busmessage_sender.h" #include "t2collection.h" @@ -49,31 +51,23 @@ #define T2_SCRIPT_EVENT_COMPONENT "telemetry_client" #define SENDER_LOG_FILE "/tmp/t2_sender_debug.log" -/* D-Bus Service Configuration */ +/* D-Bus Configuration */ #define T2_DBUS_SERVICE_NAME "telemetry.t2" #define T2_DBUS_OBJECT_PATH "/telemetry/t2" #define T2_DBUS_INTERFACE_NAME "telemetry.t2.interface" -#define T2_DBUS_SIGNAL_EVENT "TelemetryEvent" -#define T2_DBUS_SIGNAL_PROFILE_UPDATE "ProfileUpdate" -#define T2_DBUS_DEFAULT_TIMEOUT_MS 5000 - -/* D-Bus Connection Handle */ -typedef struct { - DBusConnection *connection; - char *unique_name; - bool is_initialized; -} T2DbusHandle_t; - -static T2DbusHandle_t t2dbus_handle = {NULL, NULL, false}; -static void (*profileUpdateCallback)(void) = NULL; -static pthread_mutex_t dbusMutex = PTHREAD_MUTEX_INITIALIZER; -static pthread_t dbusListenerThread; -static bool stopListenerThread = false; +#define T2_DBUS_EVENT_INTERFACE_NAME "telemetry.t2.event.interface" + +static const char* CCSP_FIXED_COMP_ID = "com.cisco.spvtg.ccsp.t2commonlib" ; static char *componentName = NULL; +static void *bus_handle = NULL; /* For method calls (main thread) */ +static void *signal_bus_handle = NULL; /* For signal listening (event thread) */ static bool isRFCT2Enable = false ; static bool isT2Ready = false; -static int count = 0; +#if defined(RBUS_SUPPORT_ENABLED) +static bool isRbusEnabled = false ; +#endif +static bool isDbusEnabled = false ; static pthread_mutex_t initMtx = PTHREAD_MUTEX_INITIALIZER; static bool isMutexInitialized = false ; @@ -89,7 +83,11 @@ static pthread_mutex_t FileCacheMutex ; static pthread_mutex_t markerListMutex ; static pthread_mutex_t loggerMutex ; -/* +// D-Bus event loop thread +static pthread_t dbus_event_thread; +static bool dbus_event_thread_running = false; + +#if defined(RBUS_SUPPORT_ENABLED) static void EVENT_DEBUG(char* format, ...) { @@ -104,13 +102,23 @@ static void EVENT_DEBUG(char* format, ...) logHandle = fopen(SENDER_LOG_FILE, "a+"); if(logHandle) { - time_t rawtime; - struct tm* timeinfo; + struct timespec ts; + struct tm timeinfo; - time(&rawtime); - timeinfo = localtime(&rawtime); - static char timeBuffer[20] = { '\0' }; - strftime(timeBuffer, sizeof(timeBuffer), "%Y-%m-%d %H:%M:%S", timeinfo); + if(clock_gettime(CLOCK_REALTIME, &ts) == -1) + { + fclose(logHandle); + pthread_mutex_unlock(&loggerMutex); + return; + } + + char timeBuffer[24] = { '\0' }; + long msecs; + + localtime_r(&ts.tv_sec, &timeinfo); + msecs = ts.tv_nsec / 1000000; + strftime(timeBuffer, sizeof(timeBuffer), "%Y-%m-%d %H:%M:%S", &timeinfo); + snprintf(timeBuffer + strlen(timeBuffer), sizeof(timeBuffer) - strlen(timeBuffer), ".%03ld", msecs); fprintf(logHandle, "%s : ", timeBuffer); va_list argList; va_start(argList, format); @@ -121,486 +129,482 @@ static void EVENT_DEBUG(char* format, ...) pthread_mutex_unlock(&loggerMutex); } -*/ - -#define EVENT_DEBUG(format, ...) \ - fprintf(stderr, "T2DEBUG:%s %s:%d: ", __func__ , __FILE__, __LINE__ ); \ +#else +#define EVENT_DEBUG(format, ...) do { \ + struct timespec ts; \ + struct tm timeinfo; \ + char timeBuffer[32]; \ + if (clock_gettime(CLOCK_REALTIME, &ts) == 0) { \ + localtime_r(&ts.tv_sec, &timeinfo); \ + long msecs = ts.tv_nsec / 1000000; \ + strftime(timeBuffer, sizeof(timeBuffer), "%Y-%m-%d %H:%M:%S", &timeinfo); \ + snprintf(timeBuffer + strlen(timeBuffer), sizeof(timeBuffer) - strlen(timeBuffer), ".%03ld", msecs); \ + fprintf(stderr, "[%s] T2DEBUG:%s %s:%d: ", timeBuffer, __func__ , __FILE__, __LINE__ ); \ + } else { \ + fprintf(stderr, "T2DEBUG:%s %s:%d: ", __func__ , __FILE__, __LINE__ ); \ + } \ fprintf(stderr, (format), ##__VA_ARGS__ ); \ - // fprintf(stderr, "\n" ); +} while(0) +#endif -/** - * @brief Check if D-Bus is initialized - */ -static bool isDbusInitialized(void) { - return t2dbus_handle.is_initialized; -} +static void initMutex() +{ + pthread_mutex_lock(&initMtx); + if ( !isMutexInitialized ) + { + isMutexInitialized = true ; + pthread_mutexattr_init(&mutexAttr); + pthread_mutexattr_settype(&mutexAttr, PTHREAD_MUTEX_RECURSIVE); -/** - * @brief D-Bus filter function for incoming messages - */ -static DBusHandlerResult dbusMessageFilter(DBusConnection *connection, - DBusMessage *message, - void *user_data) { - (void)connection; - (void)user_data; - - if (dbus_message_is_signal(message, T2_DBUS_INTERFACE_NAME, T2_DBUS_SIGNAL_PROFILE_UPDATE)) { - EVENT_DEBUG("Received ProfileUpdate signal\n"); - if (profileUpdateCallback) { - profileUpdateCallback(); - } - return DBUS_HANDLER_RESULT_HANDLED; + pthread_mutex_init(&sMutex, &mutexAttr); + pthread_mutex_init(&fMutex, &mutexAttr); + pthread_mutex_init(&dMutex, &mutexAttr); + pthread_mutex_init(&eventMutex, &mutexAttr); + pthread_mutex_init(&FileCacheMutex, &mutexAttr); + pthread_mutex_init(&markerListMutex, &mutexAttr); + pthread_mutex_init(&loggerMutex, &mutexAttr); } - - return DBUS_HANDLER_RESULT_NOT_YET_HANDLED; + pthread_mutex_unlock(&initMtx); } -/** - * @brief D-Bus listener thread function - * Processes incoming D-Bus signals (like ProfileUpdate) - */ -static void* dbusListenerThreadFunc(void *arg) { - (void)arg; - - EVENT_DEBUG("%s ++in\n", __FUNCTION__); - - while (!stopListenerThread && t2dbus_handle.connection) { - /* Process messages with 100ms timeout - blocks until message or timeout */ - dbus_connection_read_write_dispatch(t2dbus_handle.connection, 100); - - /* Small yield to prevent tight loop CPU hogging - * Note: With proper dbus_threads_init_default(), this shouldn't be needed, - * but helps with CPU usage in practice */ - usleep(1000); // 1ms yield - } +static void uninitMutex() +{ + pthread_mutex_lock(&initMtx); + pthread_mutex_lock(&FileCacheMutex); + pthread_mutex_unlock(&FileCacheMutex); + if ( isMutexInitialized ) + { + isMutexInitialized = false ; - EVENT_DEBUG("%s --out\n", __FUNCTION__); - return NULL; -} + pthread_mutex_destroy(&sMutex); + pthread_mutex_destroy(&fMutex); + pthread_mutex_destroy(&dMutex); + pthread_mutex_destroy(&FileCacheMutex); + pthread_mutex_destroy(&markerListMutex); + pthread_mutex_destroy(&loggerMutex); -/** - * @brief Initialize D-Bus connection - */ -static T2ERROR dBusInterface_Init(const char *component_name) { - EVENT_DEBUG("%s ++in\n", __FUNCTION__); - - pthread_mutex_lock(&dbusMutex); - - if (t2dbus_handle.is_initialized) { - EVENT_DEBUG("D-Bus interface already initialized\n"); - pthread_mutex_unlock(&dbusMutex); - return T2ERROR_SUCCESS; - } - - DBusError error; - dbus_error_init(&error); - - /* Initialize D-Bus threading support - CRITICAL for multi-threaded use */ - if (!dbus_threads_init_default()) { - EVENT_ERROR("Failed to initialize D-Bus threading support\n"); - pthread_mutex_unlock(&dbusMutex); - return T2ERROR_FAILURE; - } - EVENT_DEBUG("D-Bus threading support initialized\n"); - - /* Connect to system bus for local IPC */ - t2dbus_handle.connection = dbus_bus_get(DBUS_BUS_SYSTEM, &error); - if (dbus_error_is_set(&error)) { - EVENT_ERROR("D-Bus connection error: %s\n", error.message); - dbus_error_free(&error); - pthread_mutex_unlock(&dbusMutex); - return T2ERROR_FAILURE; - } - - if (!t2dbus_handle.connection) { - EVENT_ERROR("Failed to get D-Bus connection\n"); - pthread_mutex_unlock(&dbusMutex); - return T2ERROR_FAILURE; + pthread_mutexattr_destroy(&mutexAttr); } - - /* Request well-known name */ - char service_name[256]; - if (component_name) { - snprintf(service_name, sizeof(service_name), "%s.%s", - T2_DBUS_SERVICE_NAME, component_name); - } else { - snprintf(service_name, sizeof(service_name), "%s", T2_DBUS_SERVICE_NAME); + pthread_mutex_unlock(&initMtx); +} + +#if defined(CCSP_SUPPORT_ENABLED) +T2ERROR getParamValues(char **paramNames, const int paramNamesCount, parameterValStruct_t ***valStructs, int *valSize) +{ + if (paramNames == NULL || paramNamesCount <= 0) + { + EVENT_ERROR("paramNames is NULL or paramNamesCount <= 0 - returning\n"); + return T2ERROR_INVALID_ARGS; } - - int ret = dbus_bus_request_name(t2dbus_handle.connection, service_name, - DBUS_NAME_FLAG_REPLACE_EXISTING, &error); - if (dbus_error_is_set(&error)) { - EVENT_ERROR("D-Bus name request error: %s\n", error.message); - dbus_error_free(&error); - dbus_connection_unref(t2dbus_handle.connection); - t2dbus_handle.connection = NULL; - pthread_mutex_unlock(&dbusMutex); + + int ret = CcspBaseIf_getParameterValues(bus_handle, destCompName, (char*)destCompPath, paramNames, + paramNamesCount, valSize, valStructs); + if (ret != CCSP_SUCCESS) + { + EVENT_ERROR("CcspBaseIf_getParameterValues failed for : %s with ret = %d\n", paramNames[0], + ret); return T2ERROR_FAILURE; } - - if (ret != DBUS_REQUEST_NAME_REPLY_PRIMARY_OWNER) { - EVENT_DEBUG("Not primary owner of D-Bus name\n"); - } - - /* Store unique name */ - t2dbus_handle.unique_name = strdup(dbus_bus_get_unique_name(t2dbus_handle.connection)); - - /* Add message filter */ - dbus_connection_add_filter(t2dbus_handle.connection, dbusMessageFilter, NULL, NULL); - - t2dbus_handle.is_initialized = true; - - /* Start listener thread */ - stopListenerThread = false; - if (pthread_create(&dbusListenerThread, NULL, dbusListenerThreadFunc, NULL) != 0) { - EVENT_ERROR("Failed to create D-Bus listener thread\n"); - dbus_connection_remove_filter(t2dbus_handle.connection, dbusMessageFilter, NULL); - dbus_connection_unref(t2dbus_handle.connection); - if (t2dbus_handle.unique_name) { - free(t2dbus_handle.unique_name); - t2dbus_handle.unique_name = NULL; - } - t2dbus_handle.connection = NULL; - t2dbus_handle.is_initialized = false; - pthread_mutex_unlock(&dbusMutex); + return T2ERROR_SUCCESS; +} + +static void freeParamValue(parameterValStruct_t **valStructs, int valSize) +{ + free_parameterValStruct_t(bus_handle, valSize, valStructs); +} + +static T2ERROR getCCSPParamVal(const char* paramName, char **paramValue) +{ + parameterValStruct_t **valStructs = NULL; + int valSize = 0; + char *paramNames[1] = {NULL}; + paramNames[0] = strdup(paramName); + if(T2ERROR_SUCCESS != getParamValues(paramNames, 1, &valStructs, &valSize)) + { + EVENT_ERROR("Unable to get %s\n", paramName); return T2ERROR_FAILURE; } - - pthread_mutex_unlock(&dbusMutex); - - EVENT_DEBUG("D-Bus interface initialized successfully with name: %s\n", service_name); - EVENT_DEBUG("%s --out\n", __FUNCTION__); - + *paramValue = strdup(valStructs[0]->parameterValue); + free(paramNames[0]); + freeParamValue(valStructs, valSize); return T2ERROR_SUCCESS; } +#endif -/** - * @brief Uninitialize D-Bus interface - */ -static void dBusInterface_Uninit(void) { - EVENT_DEBUG("%s ++in\n", __FUNCTION__); - - pthread_mutex_lock(&dbusMutex); - - if (!t2dbus_handle.is_initialized) { - pthread_mutex_unlock(&dbusMutex); - return; - } - - /* Stop listener thread */ - stopListenerThread = true; - pthread_mutex_unlock(&dbusMutex); - - if (dbusListenerThread) { - pthread_join(dbusListenerThread, NULL); - } - - pthread_mutex_lock(&dbusMutex); - - /* Clean up D-Bus connection */ - if (t2dbus_handle.connection) { - dbus_connection_remove_filter(t2dbus_handle.connection, dbusMessageFilter, NULL); - dbus_connection_unref(t2dbus_handle.connection); - t2dbus_handle.connection = NULL; - } - - if (t2dbus_handle.unique_name) { - free(t2dbus_handle.unique_name); - t2dbus_handle.unique_name = NULL; - } - - t2dbus_handle.is_initialized = false; - - pthread_mutex_unlock(&dbusMutex); - - EVENT_DEBUG("%s --out\n", __FUNCTION__); +#if defined(RBUS_SUPPORT_ENABLED) +static void rBusInterface_Uninit( ) +{ + rbus_close(bus_handle); } +#endif -/** - * @brief Publish telemetry event via D-Bus signal - */ -static T2ERROR dbusPublishEvent(const char* eventName, const char* eventValue) { - EVENT_DEBUG("%s ++in\n", __FUNCTION__); - - if (!eventName || !eventValue) { - EVENT_ERROR("Invalid event parameters\n"); - return T2ERROR_INVALID_ARGS; - } - - EVENT_DEBUG("Publishing event - Name: %s, Value length: %zu\n", eventName, strlen(eventValue)); - - if (!t2dbus_handle.is_initialized) { - EVENT_ERROR("D-Bus not initialized\n"); - return T2ERROR_INTERNAL_ERROR; - } - - EVENT_DEBUG("D-Bus handle initialized, connection: %p\n", (void*)t2dbus_handle.connection); - - DBusMessage *signal = NULL; - - /* Create signal */ - EVENT_DEBUG("Creating D-Bus signal on path: %s, interface: %s\n", T2_DBUS_OBJECT_PATH, T2_DBUS_INTERFACE_NAME); - signal = dbus_message_new_signal(T2_DBUS_OBJECT_PATH, - T2_DBUS_INTERFACE_NAME, - T2_DBUS_SIGNAL_EVENT); - if (!signal) { - EVENT_ERROR("Failed to create D-Bus signal\n"); - return T2ERROR_FAILURE; +static void dBusInterface_Uninit(void) +{ + if(isDbusEnabled) + { + // Stop D-Bus event loop thread + if (dbus_event_thread_running) + { + EVENT_DEBUG("D-Bus: Stopping event loop thread\n"); + dbus_event_thread_running = false; + // Thread is detached and will exit on its own - no need to wait + } + + // Flush all pending messages before closing connections + if (bus_handle) + { + EVENT_DEBUG("D-Bus: Flushing pending method call messages\n"); + dbus_connection_flush((DBusConnection*)bus_handle); + } + + if (signal_bus_handle) + { + EVENT_DEBUG("D-Bus: Flushing pending signal messages\n"); + dbus_connection_flush((DBusConnection*)signal_bus_handle); + dbus_connection_unref((DBusConnection*)signal_bus_handle); + signal_bus_handle = NULL; + } + + if (bus_handle) + { + dbus_connection_unref((DBusConnection*)bus_handle); + bus_handle = NULL; + } + + isDbusEnabled = false; } +} + +static int dbus_checkStatus(void) +{ + // Check if D-Bus is available by attempting to connect + DBusError error; + dbus_error_init(&error); + DBusConnection *test_conn = dbus_bus_get(DBUS_BUS_SYSTEM, &error); - EVENT_DEBUG("D-Bus signal created successfully, appending arguments\n"); - - /* Append arguments */ - if (!dbus_message_append_args(signal, - DBUS_TYPE_STRING, &eventName, - DBUS_TYPE_STRING, &eventValue, - DBUS_TYPE_INVALID)) { - EVENT_ERROR("Failed to append signal arguments\n"); - dbus_message_unref(signal); - return T2ERROR_FAILURE; + if (dbus_error_is_set(&error)) + { + dbus_error_free(&error); + return -1; // D-Bus not available } - EVENT_DEBUG("Arguments appended successfully to signal\n"); - - /* Send signal */ - EVENT_DEBUG("Sending D-Bus signal to connection\n"); - if (!dbus_connection_send(t2dbus_handle.connection, signal, NULL)) { - EVENT_ERROR("Failed to send D-Bus signal\n"); - dbus_message_unref(signal); - return T2ERROR_FAILURE; + if (test_conn) + { + dbus_connection_unref(test_conn); + isDbusEnabled = true; + return 0; // D-Bus available } - EVENT_DEBUG("D-Bus signal sent, flushing connection\n"); - dbus_connection_flush(t2dbus_handle.connection); - EVENT_DEBUG("D-Bus connection flushed successfully\n"); - dbus_message_unref(signal); - - EVENT_DEBUG("Published event: %s = %s\n", eventName, eventValue); - EVENT_DEBUG("%s --out\n", __FUNCTION__); - - return T2ERROR_SUCCESS; + return -1; } -/** - * @brief Get marker list for component via D-Bus method call - */ -static T2ERROR dbusGetMarkerList(const char* component, char** markerList) { - EVENT_DEBUG("%s ++in\n", __FUNCTION__); - - if (!component || !markerList) { - EVENT_ERROR("Invalid arguments\n"); +static T2ERROR dbus_getGetOperationalStatus(const char* paramName, uint32_t* value) +{ + if (!paramName || !value) + { return T2ERROR_INVALID_ARGS; } - if (!t2dbus_handle.is_initialized) { - EVENT_ERROR("D-Bus not initialized\n"); - return T2ERROR_INTERNAL_ERROR; + if (!bus_handle) + { + return T2ERROR_FAILURE; } + // D-Bus method call to get uint32 parameter DBusMessage *msg = NULL; DBusMessage *reply = NULL; DBusError error; dbus_error_init(&error); - /* Create method call message */ msg = dbus_message_new_method_call(T2_DBUS_SERVICE_NAME, T2_DBUS_OBJECT_PATH, T2_DBUS_INTERFACE_NAME, - "GetMarkerList"); - if (!msg) { - EVENT_ERROR("Failed to create method call message\n"); + "GetOperationalStatus"); + if (!msg) + { + EVENT_ERROR("%s:%d, D-Bus failed to create method call message\n", __func__, __LINE__); return T2ERROR_FAILURE; } - /* Append component name */ - if (!dbus_message_append_args(msg, DBUS_TYPE_STRING, &component, DBUS_TYPE_INVALID)) { - EVENT_ERROR("Failed to append arguments\n"); + if (!dbus_message_append_args(msg, DBUS_TYPE_STRING, ¶mName, DBUS_TYPE_INVALID)) + { dbus_message_unref(msg); return T2ERROR_FAILURE; } - /* Send message and get reply */ - reply = dbus_connection_send_with_reply_and_block(t2dbus_handle.connection, msg, - T2_DBUS_DEFAULT_TIMEOUT_MS, &error); + // Timeout: 1000ms - GetOperationalStatus should respond quickly + // This prevents hanging if server is down/unresponsive + reply = dbus_connection_send_with_reply_and_block((DBusConnection*)bus_handle, msg, 1000, &error); dbus_message_unref(msg); - if (dbus_error_is_set(&error)) { - EVENT_ERROR("D-Bus method call failed: %s\n", error.message); + if (dbus_error_is_set(&error)) + { + EVENT_ERROR("%s:%d, D-Bus error: %s\n", __func__, __LINE__, error.message); dbus_error_free(&error); return T2ERROR_FAILURE; } - - if (!reply) { - EVENT_ERROR("No reply received\n"); + + if (!reply) + { return T2ERROR_FAILURE; } - /* Parse reply - expecting a string containing the marker list */ - char *value = NULL; - if (dbus_message_get_args(reply, &error, - DBUS_TYPE_STRING, &value, - DBUS_TYPE_INVALID)) { - *markerList = strdup(value); - EVENT_DEBUG("Retrieved marker list for %s\n", component); - } else { - EVENT_ERROR("Failed to parse reply: %s\n", error.message); - dbus_error_free(&error); + if (dbus_message_get_args(reply, &error, DBUS_TYPE_UINT32, value, DBUS_TYPE_INVALID)) + { + dbus_message_unref(reply); + EVENT_DEBUG("%s:%d, D-Bus got uint32 value: %u\n", __func__, __LINE__, *value); + return T2ERROR_SUCCESS; + } + else + { + if (dbus_error_is_set(&error)) + { + EVENT_ERROR("%s:%d, D-Bus error: %s\n", __func__, __LINE__, error.message); + dbus_error_free(&error); + } dbus_message_unref(reply); return T2ERROR_FAILURE; } - - dbus_message_unref(reply); - - EVENT_DEBUG("%s --out\n", __FUNCTION__); - return T2ERROR_SUCCESS; } -/** - * @brief Get operational status via D-Bus method call - */ -static T2ERROR dbusGetOperationalStatus(uint32_t* status) { +static T2ERROR initMessageBus( ) +{ EVENT_DEBUG("%s ++in\n", __FUNCTION__); - - if (!status) { - EVENT_ERROR("Invalid arguments\n"); - return T2ERROR_INVALID_ARGS; - } - - if (!t2dbus_handle.is_initialized) { - EVENT_ERROR("D-Bus not initialized\n"); - return T2ERROR_INTERNAL_ERROR; - } + T2ERROR status = T2ERROR_SUCCESS; + char* component_id = (char*)CCSP_FIXED_COMP_ID; +#if defined(CCSP_SUPPORT_ENABLED) + char *pCfg = (char*)CCSP_MSG_BUS_CFG; +#endif - DBusMessage *msg = NULL; - DBusMessage *reply = NULL; - DBusError error; - dbus_error_init(&error); - - /* Create method call message */ - msg = dbus_message_new_method_call(T2_DBUS_SERVICE_NAME, - T2_DBUS_OBJECT_PATH, - T2_DBUS_INTERFACE_NAME, - "GetOperationalStatus"); - if (!msg) { - EVENT_ERROR("Failed to create method call message\n"); - return T2ERROR_FAILURE; +#if defined(RBUS_SUPPORT_ENABLED) + if(RBUS_ENABLED == rbus_checkStatus()) + { + // EVENT_DEBUG("%s:%d, T2:rbus is enabled\n", __func__, __LINE__); + char commonLibName[124] = { '\0' }; + // Bus handles should be unique across the system + if(componentName) + { + snprintf(commonLibName, 124, "%s%s", "t2_lib_", componentName); + } + else + { + snprintf(commonLibName, 124, "%s", component_id); + } + rbusError_t status_rbus = rbus_open((rbusHandle_t*) &bus_handle, commonLibName); + if(status_rbus != RBUS_ERROR_SUCCESS) + { + EVENT_ERROR("%s:%d, init using component name %s failed with error code %d \n", __func__, __LINE__, commonLibName, status); + status = T2ERROR_FAILURE; + } + isRbusEnabled = true; } - - /* Send message and get reply */ - reply = dbus_connection_send_with_reply_and_block(t2dbus_handle.connection, msg, - T2_DBUS_DEFAULT_TIMEOUT_MS, &error); - dbus_message_unref(msg); - - if (dbus_error_is_set(&error)) { - EVENT_ERROR("D-Bus method call failed: %s\n", error.message); - dbus_error_free(&error); - return T2ERROR_FAILURE; + else +#endif + if(0 == dbus_checkStatus()) + { + // D-Bus is available - initialize threading support first + if (!dbus_threads_init_default()) + { + EVENT_ERROR("%s:%d, Failed to initialize D-Bus threading\n", __func__, __LINE__); + return T2ERROR_FAILURE; + } + EVENT_DEBUG("%s:%d, D-Bus threading initialized\n", __func__, __LINE__); + + char dbusName[124] = { '\0' }; + char signalDbusName[124] = { '\0' }; + if(componentName) + { + snprintf(dbusName, 124, "telemetry.t2.lib_%s", componentName); + snprintf(signalDbusName, 124, "telemetry.t2.lib_%s_signals", componentName); + } + else + { + snprintf(dbusName, 124, "%s", component_id); + snprintf(signalDbusName, 124, "%s_signals", component_id); + } + + DBusError error; + dbus_error_init(&error); + + /* Initialize METHOD call connection */ + bus_handle = (void*)dbus_bus_get(DBUS_BUS_SYSTEM, &error); + + if (dbus_error_is_set(&error)) + { + EVENT_ERROR("%s:%d, D-Bus method call connection init failed: %s\n", __func__, __LINE__, error.message); + dbus_error_free(&error); + status = T2ERROR_FAILURE; + } + else if (bus_handle) + { + int ret = dbus_bus_request_name((DBusConnection*)bus_handle, dbusName, + DBUS_NAME_FLAG_REPLACE_EXISTING, &error); + if (dbus_error_is_set(&error)) + { + EVENT_ERROR("%s:%d, D-Bus method call name request failed: %s\n", __func__, __LINE__, error.message); + dbus_error_free(&error); + dbus_connection_unref((DBusConnection*)bus_handle); + bus_handle = NULL; + status = T2ERROR_FAILURE; + } + else if (ret != DBUS_REQUEST_NAME_REPLY_PRIMARY_OWNER && ret != DBUS_REQUEST_NAME_REPLY_ALREADY_OWNER) + { + EVENT_ERROR("%s:%d, D-Bus method call name request returned: %d\n", __func__, __LINE__, ret); + dbus_connection_unref((DBusConnection*)bus_handle); + bus_handle = NULL; + status = T2ERROR_FAILURE; + } + else + { + EVENT_DEBUG("%s:%d, D-Bus method call connection initialized as: %s\n", __func__, __LINE__, dbusName); + + /* Initialize SIGNAL connection separately */ + signal_bus_handle = (void*)dbus_bus_get(DBUS_BUS_SYSTEM, &error); + + if (dbus_error_is_set(&error)) + { + EVENT_ERROR("%s:%d, D-Bus signal connection init failed: %s\n", __func__, __LINE__, error.message); + dbus_error_free(&error); + /* Continue without signal support */ + signal_bus_handle = NULL; + } + else if (signal_bus_handle) + { + ret = dbus_bus_request_name((DBusConnection*)signal_bus_handle, signalDbusName, + DBUS_NAME_FLAG_REPLACE_EXISTING, &error); + if (dbus_error_is_set(&error)) + { + EVENT_ERROR("%s:%d, D-Bus signal name request failed: %s\n", __func__, __LINE__, error.message); + dbus_error_free(&error); + dbus_connection_unref((DBusConnection*)signal_bus_handle); + signal_bus_handle = NULL; + } + else if (ret != DBUS_REQUEST_NAME_REPLY_PRIMARY_OWNER && ret != DBUS_REQUEST_NAME_REPLY_ALREADY_OWNER) + { + EVENT_ERROR("%s:%d, D-Bus signal name request returned: %d\n", __func__, __LINE__, ret); + dbus_connection_unref((DBusConnection*)signal_bus_handle); + signal_bus_handle = NULL; + } + else + { + EVENT_DEBUG("%s:%d, D-Bus signal connection initialized as: %s\n", __func__, __LINE__, signalDbusName); + } + } + + if (signal_bus_handle && bus_handle) + { + status = T2ERROR_SUCCESS; + EVENT_DEBUG("%s:%d, D-Bus initialized successfully with separate connections\n", __func__, __LINE__); + } + else if (bus_handle) + { + /* Allow operation with method calls only if signal connection failed */ + status = T2ERROR_SUCCESS; + EVENT_ERROR("%s:%d, D-Bus initialized with method calls only (signal connection failed)\n", __func__, __LINE__); + } + } + } + else + { + status = T2ERROR_FAILURE; + } } - - if (!reply) { - EVENT_ERROR("No reply received\n"); - return T2ERROR_FAILURE; + else + { + EVENT_ERROR("%s:%d, T2:No supported dbus available\n", __func__, __LINE__); + status = T2ERROR_FAILURE; } - - /* Parse reply - expecting UINT32 */ - if (dbus_message_get_args(reply, &error, - DBUS_TYPE_UINT32, status, - DBUS_TYPE_INVALID)) { - EVENT_DEBUG("Retrieved operational status: %u\n", *status); - } else { - EVENT_ERROR("Failed to parse reply: %s\n", error.message); - dbus_error_free(&error); - dbus_message_unref(reply); - return T2ERROR_FAILURE; +#if defined(CCSP_SUPPORT_ENABLED) + else + { + int ret = 0 ; + ret = CCSP_Message_Bus_Init(component_id, pCfg, &bus_handle, (CCSP_MESSAGE_BUS_MALLOC)Ansc_AllocateMemory_Callback, Ansc_FreeMemory_Callback); + if(ret == -1) + { + EVENT_ERROR("%s:%d, T2:initMessageBus failed\n", __func__, __LINE__); + status = T2ERROR_FAILURE ; + } + else + { + status = T2ERROR_SUCCESS ; + } } - - dbus_message_unref(reply); - +#endif // CCSP_SUPPORT_ENABLED EVENT_DEBUG("%s --out\n", __FUNCTION__); - return T2ERROR_SUCCESS; + return status; } -/** - * @brief Subscribe to profile update notifications - */ -static T2ERROR dbusSubscribeProfileUpdate(void (*callback)(void)) { - EVENT_DEBUG("%s ++in\n", __FUNCTION__); - - if (!callback) { - EVENT_ERROR("Invalid callback\n"); - return T2ERROR_INVALID_ARGS; - } +#if defined(RBUS_SUPPORT_ENABLED) +static T2ERROR getRbusParameterVal(const char* paramName, char **paramValue) +{ - if (!t2dbus_handle.is_initialized) { - EVENT_ERROR("D-Bus not initialized\n"); - return T2ERROR_INTERNAL_ERROR; - } + rbusError_t ret = RBUS_ERROR_SUCCESS; + rbusValue_t paramValue_t; + rbusValueType_t rbusValueType ; + char *stringValue = NULL; +#if 0 + rbusSetOptions_t opts; + opts.commit = true; +#endif - /* Store callback */ - profileUpdateCallback = callback; - - /* Subscribe to ProfileUpdate signal */ - char rule[512]; - DBusError error; - dbus_error_init(&error); - - snprintf(rule, sizeof(rule), - "type='signal',interface='%s',member='%s'", - T2_DBUS_INTERFACE_NAME, T2_DBUS_SIGNAL_PROFILE_UPDATE); - - dbus_bus_add_match(t2dbus_handle.connection, rule, &error); - - if (dbus_error_is_set(&error)) { - EVENT_ERROR("Failed to add match rule: %s\n", error.message); - dbus_error_free(&error); + if(!bus_handle && T2ERROR_SUCCESS != initMessageBus()) + { return T2ERROR_FAILURE; } - - EVENT_DEBUG("Subscribed to ProfileUpdate signal\n"); - EVENT_DEBUG("%s --out\n", __FUNCTION__); - - return T2ERROR_SUCCESS; -} -static void initMutex() -{ - pthread_mutex_lock(&initMtx); - if ( !isMutexInitialized ) + ret = rbus_get(bus_handle, paramName, ¶mValue_t); + if(ret != RBUS_ERROR_SUCCESS) { - isMutexInitialized = true ; - pthread_mutexattr_init(&mutexAttr); - pthread_mutexattr_settype(&mutexAttr, PTHREAD_MUTEX_RECURSIVE); - - pthread_mutex_init(&sMutex, &mutexAttr); - pthread_mutex_init(&fMutex, &mutexAttr); - pthread_mutex_init(&dMutex, &mutexAttr); - pthread_mutex_init(&eventMutex, &mutexAttr); - pthread_mutex_init(&FileCacheMutex, &mutexAttr); - pthread_mutex_init(&markerListMutex, &mutexAttr); - pthread_mutex_init(&loggerMutex, &mutexAttr); + EVENT_ERROR("Unable to get %s\n", paramName); + return T2ERROR_FAILURE; } - pthread_mutex_unlock(&initMtx); -} - -static void uninitMutex() -{ - pthread_mutex_lock(&initMtx); - pthread_mutex_lock(&FileCacheMutex); - pthread_mutex_unlock(&FileCacheMutex); - if ( isMutexInitialized ) + rbusValueType = rbusValue_GetType(paramValue_t); + if(rbusValueType == RBUS_BOOLEAN) { - isMutexInitialized = false ; - - pthread_mutex_destroy(&sMutex); - pthread_mutex_destroy(&fMutex); - pthread_mutex_destroy(&dMutex); - pthread_mutex_destroy(&FileCacheMutex); - pthread_mutex_destroy(&markerListMutex); - pthread_mutex_destroy(&loggerMutex); + if (rbusValue_GetBoolean(paramValue_t)) + { + stringValue = strdup("true"); + } + else + { + stringValue = strdup("false"); + } + } + else + { + stringValue = rbusValue_ToString(paramValue_t, NULL, 0); + } + *paramValue = stringValue; + rbusValue_Release(paramValue_t); - pthread_mutexattr_destroy(&mutexAttr); + return T2ERROR_SUCCESS; +} +#endif + +T2ERROR getParamValue(const char* paramName, char **paramValue) +{ + T2ERROR ret = T2ERROR_FAILURE ; +#if defined(RBUS_SUPPORT_ENABLED) + if(isRbusEnabled) + { + ret = getRbusParameterVal(paramName, paramValue); } - pthread_mutex_unlock(&initMtx); + else +#endif +#if defined(CCSP_SUPPORT_ENABLED) + { + ret = getCCSPParamVal(paramName, paramValue); + } +#else + { + // D-Bus mode - not implemented for parameter get + (void)paramName; + (void)paramValue; + ret = T2ERROR_FAILURE; + } +#endif + + return ret; } void *cacheEventToFile(void *arg) @@ -614,8 +618,9 @@ void *cacheEventToFile(void *arg) fl.l_len = 0; fl.l_pid = 0; FILE *fs = NULL; - char path[100]; pthread_detach(pthread_self()); + int ch; + int count = 0; EVENT_ERROR("%s:%d, Caching the event to File\n", __func__, __LINE__); if(telemetry_data == NULL) { @@ -651,12 +656,25 @@ void *cacheEventToFile(void *arg) EVENT_ERROR("%s: File open error %s\n", __FUNCTION__, T2_CACHE_FILE); goto unlock; } - fs = popen ("cat /tmp/t2_caching_file | wc -l", "r"); - if(fs != NULL) + + fs = fopen(T2_CACHE_FILE, "r"); + if (fs != NULL) { - fgets(path, 100, fs); - count = atoi ( path ); - pclose(fs); + while ((ch = fgetc(fs)) != EOF) + { + if (ch == '\n') + { + count++; + } + } + + //If the file is not empty and does not contain a newline, call it one line + if (count == 0 && ftell(fs) > 0) + { + count++; + } + fclose(fs); + fs = NULL; } if(count < MAX_EVENT_CACHE) { @@ -685,29 +703,26 @@ void *cacheEventToFile(void *arg) return NULL; } -static T2ERROR initMessageBus( ) -{ - // EVENT_DEBUG("%s ++in\n", __FUNCTION__); - T2ERROR status = T2ERROR_SUCCESS; - //TODO: Initialize message bus here - DBUS / RBUS based on build flags - return status; -} - static bool initRFC( ) { bool status = true ; - // // Check for RFC and proceed - if true - else return now . - - if(initMessageBus() != 0) - { - EVENT_ERROR("initMessageBus failed\n"); - status = false ; - } - else + // Check for RFC and proceed - if true - else return now . + //TODO: Implement RFC check here + if(!bus_handle && !signal_bus_handle) { - status = true; + EVENT_DEBUG("%s:%d, T2: Initializing Message Bus\n", __func__, __LINE__); + if(initMessageBus() != 0) + { + EVENT_ERROR("initMessageBus failed\n"); + status = false ; + } + else + { + EVENT_DEBUG("initMessageBus successful\n"); + status = true; + } + isRFCT2Enable = true; } - isRFCT2Enable = true; return status; } @@ -718,152 +733,460 @@ static bool initRFC( ) */ int filtered_event_send(const char* data, const char *markerName) { - T2ERROR ret = T2ERROR_SUCCESS; int status = 0 ; EVENT_DEBUG("%s ++in\n", __FUNCTION__); - - if(!isDbusInitialized()) + if(!bus_handle) { - EVENT_ERROR("DBUS not initialized .. exiting !!!"); - return ret; + EVENT_ERROR("bus_handle is null .. exiting !!! \n"); + return status; } - // Filter data from marker list - if(componentName && (0 != strcmp(componentName, T2_SCRIPT_EVENT_COMPONENT))) // Events from scripts needs to be sent without filtering +#if defined(RBUS_SUPPORT_ENABLED) + if(isRbusEnabled) { - EVENT_DEBUG("%s markerListMutex lock & get list of marker for component %s \n", __FUNCTION__, componentName); - EVENT_DEBUG("Filtering event: checking if marker '%s' is in allowed list\n", markerName); - pthread_mutex_lock(&markerListMutex); - bool isEventingEnabled = false; - if(markerName && eventMarkerMap) + + // Filter data from marker list + if(componentName && (0 != strcmp(componentName, T2_SCRIPT_EVENT_COMPONENT))) // Events from scripts needs to be sent without filtering { - EVENT_DEBUG("Searching marker '%s' in eventMarkerMap\n", markerName); - if(hash_map_get(eventMarkerMap, markerName)) + + EVENT_DEBUG("%s markerListMutex lock & get list of marker for component %s \n", __FUNCTION__, componentName); + pthread_mutex_lock(&markerListMutex); + bool isEventingEnabled = false; + if(markerName && eventMarkerMap) { - isEventingEnabled = true; - EVENT_DEBUG("Marker '%s' found in allowed list, event enabled\n", markerName); + if(hash_map_get(eventMarkerMap, markerName)) + { + isEventingEnabled = true; + } } else { - EVENT_DEBUG("Marker '%s' NOT found in allowed list, event will be filtered\n", markerName); + EVENT_DEBUG("%s eventMarkerMap for component %s is empty \n", __FUNCTION__, componentName ); + } + EVENT_DEBUG("%s markerListMutex unlock\n", __FUNCTION__ ); + pthread_mutex_unlock(&markerListMutex); + if(!isEventingEnabled) + { + EVENT_DEBUG("%s markerName %s not found in event list for component %s . Unlock markerListMutex . \n", __FUNCTION__, markerName, componentName); + return status; } } - else + // End of event filtering + + rbusProperty_t objProperty = NULL ; + rbusValue_t objVal, value; + rbusSetOptions_t options = {0}; + options.commit = true; + + rbusValue_Init(&objVal); + rbusValue_SetString(objVal, data); + rbusProperty_Init(&objProperty, markerName, objVal); + + rbusValue_Init(&value); + rbusValue_SetProperty(value, objProperty); + + EVENT_DEBUG("rbus_set with param [%s] with %s and value [%s]\n", T2_EVENT_PARAM, markerName, data); + ret = rbus_set(bus_handle, T2_EVENT_PARAM, value, &options); + if(ret != RBUS_ERROR_SUCCESS) { - EVENT_DEBUG("%s eventMarkerMap for component %s is empty \n", __FUNCTION__, componentName ); + EVENT_ERROR("rbus_set Failed for [%s] with error [%d]\n", T2_EVENT_PARAM, ret); + EVENT_DEBUG(" !!! Error !!! rbus_set Failed for [%s] with error [%d]\n", T2_EVENT_PARAM, ret); + status = -1 ; } - EVENT_DEBUG("%s markerListMutex unlock\n", __FUNCTION__ ); - pthread_mutex_unlock(&markerListMutex); - if(!isEventingEnabled) + else { - EVENT_DEBUG("%s markerName %s not found in event list for component %s . Unlock markerListMutex . \n", __FUNCTION__, markerName, componentName); - EVENT_DEBUG("Event FILTERED OUT - marker '%s' not enabled for component '%s'\n", markerName, componentName); - return status; + status = 0 ; } - EVENT_DEBUG("Event ALLOWED - marker '%s' passed filter for component '%s'\n", markerName, componentName); + // Release all rbus data structures + rbusValue_Release(value); + rbusProperty_Release(objProperty); + rbusValue_Release(objVal); + } else +#endif + if(isDbusEnabled && bus_handle) { - EVENT_DEBUG("Skipping filter - component is '%s' (script events or no component)\n", componentName ? componentName : "NULL"); - } - // End of event filtering + // Filter data from marker list + if(componentName && (0 != strcmp(componentName, T2_SCRIPT_EVENT_COMPONENT))) // Events from scripts needs to be sent without filtering + { + EVENT_DEBUG("%s markerListMutex lock & get list of marker for component %s \n", __FUNCTION__, componentName); + pthread_mutex_lock(&markerListMutex); + bool isEventingEnabled = false; + if(markerName && eventMarkerMap) + { + if(hash_map_get(eventMarkerMap, markerName)) + { + isEventingEnabled = true; + } + } + else + { + EVENT_DEBUG("%s eventMarkerMap for component %s is empty \n", __FUNCTION__, componentName ); + } + EVENT_DEBUG("%s markerListMutex unlock\n", __FUNCTION__ ); + pthread_mutex_unlock(&markerListMutex); + if(!isEventingEnabled) + { + EVENT_DEBUG("%s markerName %s not found in event list for component %s . Unlock markerListMutex . \n", __FUNCTION__, markerName, componentName); + return status; + } + } - EVENT_DEBUG("Calling dbusPublishEvent with marker [%s] and value [%s]\n", markerName, data); - ret = dbusPublishEvent(markerName, data); - if(ret != T2ERROR_SUCCESS) + // D-Bus method call to send event + DBusMessage *msg = NULL; + DBusError error; + dbus_error_init(&error); + + msg = dbus_message_new_method_call(T2_DBUS_SERVICE_NAME, + T2_DBUS_OBJECT_PATH, + T2_DBUS_INTERFACE_NAME, + "SendT2Event"); + if (!msg) + { + EVENT_ERROR("Failed to create D-Bus method call message\n"); + status = -1; + } + else + { + if (!dbus_message_append_args(msg, + DBUS_TYPE_STRING, &markerName, + DBUS_TYPE_STRING, &data, + DBUS_TYPE_INVALID)) + { + EVENT_ERROR("Failed to append D-Bus method call arguments\n"); + dbus_message_unref(msg); + status = -1; + } + else + { + // Send method call without waiting for reply + if (!dbus_connection_send((DBusConnection*)bus_handle, msg, NULL)) + { + EVENT_ERROR("Failed to send D-Bus method call\n"); + status = -1; + } + else + { + // Flush the connection to ensure message is actually sent + //dbus_connection_flush((DBusConnection*)bus_handle); + EVENT_DEBUG("call sent for event marker [%s] with data [%s]\n", markerName, data); + status = 0; + } + dbus_message_unref(msg); + } + } + } + else { - EVENT_ERROR("dbusPublishEvent Failed for marker [%s] with error [%d]\n", markerName, ret); - EVENT_DEBUG(" !!! Error !!! dbusPublishEvent Failed for marker [%s] with error [%d]\n", markerName, ret); + EVENT_ERROR("No supported bus available for sending event\n"); status = -1 ; } +#if defined(CCSP_SUPPORT_ENABLED) else { - status = 0 ; + int eventDataLen = strlen(markerName) + strlen(data) + strlen(MESSAGE_DELIMITER) + 1; + char* buffer = (char*) malloc(eventDataLen * sizeof(char)); + if(buffer) + { + snprintf(buffer, eventDataLen, "%s%s%s", markerName, MESSAGE_DELIMITER, data); + int ret = CcspBaseIf_SendTelemetryDataSignal(bus_handle, buffer); + if(ret != CCSP_SUCCESS) + { + status = -1; + } + free(buffer); + } + else + { + EVENT_ERROR("Unable to allocate meory for event [%s]\n", markerName); + status = -1 ; + } } - +#endif // CCSP_SUPPORT_ENABLED EVENT_DEBUG("%s --out with status %d \n", __FUNCTION__, status); return status; } /** - * Get marker list from T2 daemon via DBUS + * Receives an rbus object as value which conatins a list of rbusPropertyObject + * rbusProperty name will the eventName and value will be null */ -static T2ERROR doPopulateEventMarkerList(void) +static T2ERROR doPopulateEventMarkerList( ) { - EVENT_DEBUG("%s ++in\n", __FUNCTION__); - T2ERROR status = T2ERROR_SUCCESS; - - if(!isDbusInitialized()) + +#if defined(RBUS_SUPPORT_ENABLED) + char deNameSpace[1][124] = {{ '\0' }}; + if(!isRbusEnabled) { - EVENT_ERROR("DBUS not initialized\n"); - return T2ERROR_FAILURE; + // Fall through to D-Bus implementation } + else + { + EVENT_DEBUG("%s ++in\n", __FUNCTION__); + rbusError_t ret = RBUS_ERROR_SUCCESS; + rbusValue_t paramValue_t; + + if(!bus_handle && T2ERROR_SUCCESS != initMessageBus()) + { + EVENT_ERROR("Unable to get message bus handles \n"); + EVENT_DEBUG("%s --out\n", __FUNCTION__); + return T2ERROR_FAILURE; + } + + snprintf(deNameSpace[0], 124, "%s%s%s", T2_ROOT_PARAMETER, componentName, T2_EVENT_LIST_PARAM_SUFFIX); + EVENT_DEBUG("rbus mode : Query marker list with data element = %s \n", deNameSpace[0]); + + pthread_mutex_lock(&markerListMutex); + EVENT_DEBUG("Lock markerListMutex & Clean up eventMarkerMap \n"); + if(eventMarkerMap != NULL) + { + hash_map_destroy(eventMarkerMap, free); + eventMarkerMap = NULL; + } + + ret = rbus_get(bus_handle, deNameSpace[0], ¶mValue_t); + if(ret != RBUS_ERROR_SUCCESS) + { + EVENT_ERROR("rbus mode : No event list configured in profiles %s and return value %d\n", deNameSpace[0], ret); + pthread_mutex_unlock(&markerListMutex); + EVENT_DEBUG("rbus mode : No event list configured in profiles %s and return value %d. Unlock markerListMutex\n", deNameSpace[0], ret); + EVENT_DEBUG("%s --out\n", __FUNCTION__); + return T2ERROR_SUCCESS; + } + + rbusValueType_t type_t = rbusValue_GetType(paramValue_t); + if(type_t != RBUS_OBJECT) + { + EVENT_ERROR("rbus mode : Unexpected data object received for %s get query \n", deNameSpace[0]); + rbusValue_Release(paramValue_t); + pthread_mutex_unlock(&markerListMutex); + EVENT_DEBUG("Unlock markerListMutex\n"); + EVENT_DEBUG("%s --out\n", __FUNCTION__); + return T2ERROR_FAILURE; + } + + rbusObject_t objectValue = rbusValue_GetObject(paramValue_t); + if(objectValue) + { + eventMarkerMap = hash_map_create(); + rbusProperty_t rbusPropertyList = rbusObject_GetProperties(objectValue); + EVENT_DEBUG("\t rbus mode : Update event map for component %s with below events : \n", componentName); + while(NULL != rbusPropertyList) + { + const char* eventname = rbusProperty_GetName(rbusPropertyList); + if(eventname && strlen(eventname) > 0) + { + EVENT_DEBUG("\t %s\n", eventname); + hash_map_put(eventMarkerMap, (void*) strdup(eventname), (void*) strdup(eventname), free); + } + rbusPropertyList = rbusProperty_GetNext(rbusPropertyList); + } + } + else + { + EVENT_ERROR("rbus mode : No configured event markers for %s \n", componentName); + } + EVENT_DEBUG("Unlock markerListMutex\n"); + pthread_mutex_unlock(&markerListMutex); + rbusValue_Release(paramValue_t); + EVENT_DEBUG("%s --out\n", __FUNCTION__); + return status; + } +#endif + + // D-Bus implementation + if(isDbusEnabled && bus_handle) + { + EVENT_DEBUG("%s ++in \n", __FUNCTION__); + + if(!bus_handle && T2ERROR_SUCCESS != initMessageBus()) + { + EVENT_ERROR("Unable to get message bus handles \n"); + EVENT_DEBUG("%s --out\n", __FUNCTION__); + return T2ERROR_FAILURE; + } + + pthread_mutex_lock(&markerListMutex); + EVENT_DEBUG("Lock markerListMutex & Clean up eventMarkerMap \n"); + if(eventMarkerMap != NULL) + { + hash_map_destroy(eventMarkerMap, free); + eventMarkerMap = NULL; + } + + // Get marker list via D-Bus method call + DBusMessage *msg = NULL; + DBusMessage *reply = NULL; + DBusError error; + dbus_error_init(&error); + + msg = dbus_message_new_method_call(T2_DBUS_SERVICE_NAME, + T2_DBUS_OBJECT_PATH, + T2_DBUS_INTERFACE_NAME, + "GetMarkerList"); + if (!msg) + { + EVENT_ERROR("D-Bus mode: Failed to create method call message\n"); + pthread_mutex_unlock(&markerListMutex); + return T2ERROR_FAILURE; + } + + if (!dbus_message_append_args(msg, DBUS_TYPE_STRING, &componentName, DBUS_TYPE_INVALID)) + { + EVENT_ERROR("D-Bus mode: Failed to append arguments\n"); + dbus_message_unref(msg); + pthread_mutex_unlock(&markerListMutex); + return T2ERROR_FAILURE; + } + // TODO : check markers list size and set timeout accordingly + // Timeout: 500ms + reply = dbus_connection_send_with_reply_and_block((DBusConnection*)bus_handle, msg, 500, &error); + dbus_message_unref(msg); + + if (dbus_error_is_set(&error)) + { + EVENT_ERROR("D-Bus mode: Method call failed: %s\n", error.message); + dbus_error_free(&error); + pthread_mutex_unlock(&markerListMutex); + EVENT_DEBUG("D-Bus mode: No event list configured. Unlock markerListMutex\n"); + return T2ERROR_SUCCESS; + } + + if (!reply) + { + EVENT_ERROR("D-Bus mode: No reply received\n"); + pthread_mutex_unlock(&markerListMutex); + return T2ERROR_SUCCESS; + } + + // Parse reply - expecting a string containing comma-separated marker list + char *markerListStr = NULL; + if (dbus_message_get_args(reply, &error, + DBUS_TYPE_STRING, &markerListStr, + DBUS_TYPE_INVALID)) + { + if(markerListStr && strlen(markerListStr) > 0) + { + eventMarkerMap = hash_map_create(); + EVENT_DEBUG("\t D-Bus mode: Update event map for component %s with below events :", componentName); + + char* markerListCopy = strdup(markerListStr); + char* token = strtok(markerListCopy, ","); + while(token != NULL) + { + // Trim whitespace + while(*token == ' ' || *token == '\t') token++; + char* end = token + strlen(token) - 1; + while(end > token && (*end == ' ' || *end == '\t' || *end == '\n')) { + *end = '\0'; + end--; + } + + if(strlen(token) > 0) + { + EVENT_DEBUG("\t %s\n", token); + hash_map_put(eventMarkerMap, (void*)strdup(token), (void*)strdup(token), free); + } + token = strtok(NULL, ","); + } + free(markerListCopy); + } + else + { + EVENT_ERROR("D-Bus mode: No configured event markers for %s\n", componentName); + } + } + else + { + EVENT_ERROR("D-Bus mode: Failed to parse reply: %s\n", error.message); + dbus_error_free(&error); + } + + dbus_message_unref(reply); + EVENT_DEBUG("Unlock markerListMutex\n"); + pthread_mutex_unlock(&markerListMutex); + EVENT_DEBUG("%s --out\n", __FUNCTION__); + return T2ERROR_SUCCESS; + } + else + { + EVENT_ERROR("No dbus supported message bus available\n"); + } + + return T2ERROR_FAILURE; +} + +#if defined(RBUS_SUPPORT_ENABLED) +static void rbusEventReceiveHandler(rbusHandle_t handle, rbusEvent_t const* event, rbusEventSubscription_t* subscription) +{ + (void)handle;//To fix compiler warning. + (void)subscription;//To fix compiler warning. + const char* eventName = event->name; + if(eventName) + { + if(0 == strcmp(eventName, T2_PROFILE_UPDATED_NOTIFY)) + { + doPopulateEventMarkerList(); + } + } + else + { + EVENT_ERROR("eventName is null \n"); + } +} +#endif + +static DBusHandlerResult dbusEventReceiveHandler(DBusConnection *connection, DBusMessage *message, void *user_data) +{ + (void)connection; + (void)user_data; - pthread_mutex_lock(&markerListMutex); - EVENT_DEBUG("Lock markerListMutex & Clean up eventMarkerMap \n"); - - if(eventMarkerMap != NULL) + if (dbus_message_is_signal(message, T2_DBUS_EVENT_INTERFACE_NAME, "ProfileUpdate")) { - hash_map_destroy(eventMarkerMap, free); - eventMarkerMap = NULL; + EVENT_DEBUG("D-Bus: *** ProfileUpdate signal RECEIVED - updating marker list ***\n"); + doPopulateEventMarkerList(); + return DBUS_HANDLER_RESULT_HANDLED; } - // Get marker list via DBUS method call - char* markerListStr = NULL; - status = dbusGetMarkerList(componentName, &markerListStr); + return DBUS_HANDLER_RESULT_NOT_YET_HANDLED; +} + +// D-Bus event loop thread function - processes BOTH connections +static void* dbus_event_loop_thread(void *arg) +{ + (void)arg; - if(status != T2ERROR_SUCCESS || !markerListStr) + if (!signal_bus_handle) { - EVENT_ERROR("dbusGetMarkerList failed for component %s\n", componentName); - pthread_mutex_unlock(&markerListMutex); - EVENT_DEBUG("Unlock markerListMutex\n"); - EVENT_DEBUG("%s --out\n", __FUNCTION__); - return T2ERROR_FAILURE; + EVENT_ERROR("Signal bus handle is NULL\n"); + return NULL; } - // Parse marker list string (format: comma-separated marker names) - eventMarkerMap = hash_map_create(); - EVENT_DEBUG("\t Update event map for component %s with below events : \n", componentName); + EVENT_DEBUG("D-Bus: Event loop thread started (processing both connections)\n"); - char* markerListCopy = strdup(markerListStr); - EVENT_DEBUG("Marker List String : %s \n", markerListStr); - char* token = strtok(markerListCopy, ","); - while(token != NULL) - { - // Trim leading whitespace - while(*token == ' ' || *token == '\t') token++; - // Trim trailing whitespace - char* end = token + strlen(token) - 1; - while(end > token && (*end == ' ' || *end == '\t' || *end == '\n')) { - *end = '\0'; - end--; - } + while (dbus_event_thread_running) + { + // Process signal connection (for ProfileUpdate signals) + dbus_connection_read_write_dispatch((DBusConnection*)signal_bus_handle, 0); - if(strlen(token) > 0) + // Process method call connection (flush outgoing SendT2Event messages) + if (bus_handle) { - EVENT_DEBUG("\t %s\n", token); - hash_map_put(eventMarkerMap, (void*)strdup(token), (void*)strdup(token), free); + dbus_connection_read_write_dispatch((DBusConnection*)bus_handle, 0); } - token = strtok(NULL, ","); + + // Small sleep to avoid busy-waiting + usleep(100000); // 100ms } - free(markerListCopy); - free(markerListStr); - pthread_mutex_unlock(&markerListMutex); - EVENT_DEBUG("Unlock markerListMutex\n"); - EVENT_DEBUG("%s --out\n", __FUNCTION__); - return status; -} - -static void dbusProfileUpdateHandler(void) -{ - EVENT_DEBUG("Profile update notification received via DBUS\n"); - doPopulateEventMarkerList(); + EVENT_DEBUG("D-Bus: Event loop thread exiting\n"); + return NULL; } static bool isCachingRequired( ) { - // TODO check complete conditions for caching requirement something is missing + /** * Attempts to read from PAM before its ready creates deadlock . * PAM not ready is a definite case for caching the event and avoid bus traffic @@ -889,25 +1212,52 @@ static bool isCachingRequired( ) // Always check for t2 is ready to accept events. Shutdown target can bring down t2 process at runtime uint32_t t2ReadyStatus; - //TODO check the exact api to replace documentation of rbus_getUint - T2ERROR retVal = dbusGetOperationalStatus(&t2ReadyStatus); // replace of rbus_getUint api + T2ERROR retVal = T2ERROR_FAILURE; + +#if defined(RBUS_SUPPORT_ENABLED) + if(isRbusEnabled) + { + rbusError_t rbusRetVal = rbus_getUint(bus_handle, T2_OPERATIONAL_STATUS, &t2ReadyStatus); + retVal = (rbusRetVal == RBUS_ERROR_SUCCESS) ? T2ERROR_SUCCESS : T2ERROR_FAILURE; + } + else +#endif + if(isDbusEnabled && bus_handle) + { + retVal = dbus_getGetOperationalStatus(T2_OPERATIONAL_STATUS, &t2ReadyStatus); + // retVal = T2ERROR_SUCCESS; // Temporarily bypass D-Bus get for operational status + // t2ReadyStatus = T2_STATE_COMPONENT_READY; // Assume ready for now + EVENT_DEBUG("%s:%d, D-Bus t2ReadyStatus: %u\n", __func__, __LINE__, t2ReadyStatus); + } if(retVal != T2ERROR_SUCCESS) { + EVENT_ERROR("Unable to get %s\n", T2_OPERATIONAL_STATUS); return true; } else { - EVENT_DEBUG("Operational status: %d\n", t2ReadyStatus); + EVENT_DEBUG("value for %s is : %d\n", T2_OPERATIONAL_STATUS, t2ReadyStatus); if((t2ReadyStatus & T2_STATE_COMPONENT_READY) == 0) { return true; } } +#if defined(RBUS_SUPPORT_ENABLED) + if(!isRbusEnabled) + { + // Fall through to D-Bus handling + } + else + { + isT2Ready = true; + } +#endif + if(!isT2Ready) { - EVENT_DEBUG("T2 is not ready yet - checking component specific config\n"); + EVENT_DEBUG("T2 is not ready yet, subscribe to profile update event/signals \n"); if(componentName && (0 != strcmp(componentName, "telemetry_client"))) { // From other binary applications in rbus mode if t2 daemon is yet to determine state of component specific config from cloud, enable cache @@ -917,22 +1267,74 @@ static bool isCachingRequired( ) } else { - // Fetch marker list and subscribe to profile updates - doPopulateEventMarkerList(); - - EVENT_DEBUG("Subscribing to ProfileUpdate signal for component %s\n", componentName); - T2ERROR ret = dbusSubscribeProfileUpdate(dbusProfileUpdateHandler); - if(ret != T2ERROR_SUCCESS) +#if defined(RBUS_SUPPORT_ENABLED) + if(isRbusEnabled) + { + rbusError_t ret = RBUS_ERROR_SUCCESS; + doPopulateEventMarkerList(); + ret = rbusEvent_Subscribe(bus_handle, T2_PROFILE_UPDATED_NOTIFY, rbusEventReceiveHandler, "T2Event", 0); + if(ret != RBUS_ERROR_SUCCESS) + { + EVENT_ERROR("Unable to subscribe to event %s with rbus error code : %d\n", T2_PROFILE_UPDATED_NOTIFY, ret); + EVENT_DEBUG("Unable to subscribe to event %s with rbus error code : %d\n", T2_PROFILE_UPDATED_NOTIFY, ret); + } + isT2Ready = true; + } + else +#endif + if(isDbusEnabled && signal_bus_handle) { - EVENT_ERROR("Unable to subscribe to ProfileUpdate signal with error : %d\n", ret); - EVENT_DEBUG("Unable to subscribe to ProfileUpdate signal with error : %d\n", ret); + EVENT_DEBUG("D-Bus: Starting ProfileUpdate signal subscription setup\n"); + doPopulateEventMarkerList(); + + // Subscribe to D-Bus ProfileUpdate signal using SIGNAL connection + char rule[512]; + DBusError error; + dbus_error_init(&error); + + snprintf(rule, sizeof(rule), + "type='signal',path='%s',interface='%s',member='ProfileUpdate'", + T2_DBUS_OBJECT_PATH, T2_DBUS_EVENT_INTERFACE_NAME); + + EVENT_DEBUG("D-Bus: Adding match rule: %s\n", rule); + EVENT_DEBUG("D-Bus: Event Interface: %s, Path: %s\n", T2_DBUS_EVENT_INTERFACE_NAME, T2_DBUS_OBJECT_PATH); + + dbus_bus_add_match((DBusConnection*)signal_bus_handle, rule, &error); + + if (dbus_error_is_set(&error)) + { + EVENT_ERROR("Unable to subscribe to ProfileUpdate signal: %s\n", error.message); + dbus_error_free(&error); + } + else + { + EVENT_DEBUG("D-Bus: Match rule added successfully\n"); + // Add message filter for handling signals on SIGNAL connection + dbus_connection_add_filter((DBusConnection*)signal_bus_handle, dbusEventReceiveHandler, NULL, NULL); + EVENT_DEBUG("D-Bus: Now listening for ProfileUpdate signals on interface '%s'\n", T2_DBUS_EVENT_INTERFACE_NAME); + + // Start D-Bus event loop thread to process incoming signals + if (!dbus_event_thread_running) + { + dbus_event_thread_running = true; + if (pthread_create(&dbus_event_thread, NULL, dbus_event_loop_thread, NULL) == 0) + { + EVENT_DEBUG("D-Bus: Event loop thread created successfully\n"); + pthread_detach(dbus_event_thread); + } + else + { + EVENT_ERROR("D-Bus: Failed to create event loop thread\n"); + dbus_event_thread_running = false; + } + } + } + isT2Ready = true; } - isT2Ready = true; } } else { - EVENT_DEBUG("Component is telemetry_client or NULL - marking T2 as ready\n"); isT2Ready = true; } } @@ -944,12 +1346,9 @@ static int report_or_cache_data(char* telemetry_data, const char* markerName) { int ret = 0; pthread_t tid; - EVENT_DEBUG("%s ++in - marker: %s, data length: %zu\n", __FUNCTION__, markerName, strlen(telemetry_data)); pthread_mutex_lock(&eventMutex); - EVENT_DEBUG("Checking if caching is required...\n"); if(isCachingRequired()) { - EVENT_DEBUG("Caching IS required - will cache event to file\n"); EVENT_DEBUG("Caching the event : %s \n", telemetry_data); int eventDataLen = strlen(markerName) + strlen(telemetry_data) + strlen(MESSAGE_DELIMITER) + 1; char* buffer = (char*) malloc(eventDataLen * sizeof(char)); @@ -964,21 +1363,15 @@ static int report_or_cache_data(char* telemetry_data, const char* markerName) } pthread_mutex_unlock(&eventMutex); - EVENT_DEBUG("Caching NOT required - will send event via D-Bus\n"); if(isT2Ready) { - EVENT_DEBUG("T2 is ready - sending event via D-Bus: marker=%s\n", markerName); + // EVENT_DEBUG("T2: Sending event : %s\n", telemetry_data); ret = filtered_event_send(telemetry_data, markerName); if(0 != ret) { EVENT_ERROR("%s:%d, T2:telemetry data send failed, status = %d \n", __func__, __LINE__, ret); } } - else - { - EVENT_DEBUG("T2 is NOT ready - caching event to file: marker=%s\n", markerName); - } - // Caching format needs to be same for operation between rbus/dbus modes across reboots return ret; } @@ -988,13 +1381,7 @@ static int report_or_cache_data(char* telemetry_data, const char* markerName) void t2_init(char *component) { componentName = strdup(component); - - // Initialize DBUS connection - T2ERROR ret = dBusInterface_Init(componentName); - if(ret != T2ERROR_SUCCESS) - { - EVENT_ERROR("DBUS initialization failed for %s\n", componentName); - } + isCachingRequired(); } void t2_uninit(void) @@ -1004,10 +1391,19 @@ void t2_uninit(void) free(componentName); componentName = NULL ; } - - // Uninitialize DBUS - dBusInterface_Uninit(); - + +#if defined(RBUS_SUPPORT_ENABLED) + if(isRbusEnabled) + { + rBusInterface_Uninit(); + } + else +#endif + if(isDbusEnabled) + { + dBusInterface_Uninit(); + } + uninitMutex(); } diff --git a/source/telemetry2_0.c b/source/telemetry2_0.c index 059e976a..c9dce45b 100644 --- a/source/telemetry2_0.c +++ b/source/telemetry2_0.c @@ -17,7 +17,6 @@ * limitations under the License. */ #include "telemetry2_0.h" -#include "dbusInterface.h" #include #include @@ -253,7 +252,6 @@ static void t2DaemonMainModeInit( ) eh = newBreakPadWrapExceptionHandler(); #endif #endif - /** * Create a Signal Mask for signals that need to be blocked while using fork */ From e5c84d8de2c1e6f7e02900441a3ff5595f6f92dd Mon Sep 17 00:00:00 2001 From: Muhammed rafi c Date: Tue, 27 Jan 2026 13:21:35 +0000 Subject: [PATCH 11/23] build script updated --- build_inside_container.sh | 2 +- source/Makefile.am | 4 ++-- source/bulkdata/Makefile.am | 4 ++-- 3 files changed, 5 insertions(+), 5 deletions(-) diff --git a/build_inside_container.sh b/build_inside_container.sh index 72467960..b2e2003a 100755 --- a/build_inside_container.sh +++ b/build_inside_container.sh @@ -27,7 +27,7 @@ autoreconf --install # FLags to print compiler warnings DEBUG_CFLAGS="-Wall -Werror -Wextra" -export CFLAGS=" ${DEBUG_CFLAGS} -I${INSTALL_DIR}/include/rtmessage -I${INSTALL_DIR}/include/msgpack -I${INSTALL_DIR}/include/rbus -I${INSTALL_DIR}/include -I/usr/include/glib-2.0 -I/usr/lib/x86_64-linux-gnu/glib-2.0/include -I/usr/local/include -DFEATURE_SUPPORT_WEBCONFIG -DRDK_LOGGER -DPERSIST_LOG_MON_REF -DDCMAGENT" +export CFLAGS=" ${DEBUG_CFLAGS} -I/usr/lib/x86_64-linux-gnu/dbus-1.0/include -I/usr/include/dbus-1.0 -I${INSTALL_DIR}/include/rtmessage -I${INSTALL_DIR}/include/msgpack -I${INSTALL_DIR}/include/rbus -I${INSTALL_DIR}/include -I/usr/include/glib-2.0 -I/usr/lib/x86_64-linux-gnu/glib-2.0/include -I/usr/local/include -DFEATURE_SUPPORT_WEBCONFIG -DRDK_LOGGER -DPERSIST_LOG_MON_REF -DDCMAGENT" export LDFLAGS="-L/usr/lib/x86_64-linux-gnu -lglib-2.0" diff --git a/source/Makefile.am b/source/Makefile.am index 6ed9f2ae..3cbe1848 100644 --- a/source/Makefile.am +++ b/source/Makefile.am @@ -41,8 +41,8 @@ bin_PROGRAMS = telemetry2_0 telemetry2_0_SOURCES = telemetry2_0.c telemetry2_0_CFLAGS = -DFEATURE_SUPPORT_RDKLOG -D_FILE_OFFSET_BITS=64 -D_TIME_BITS=64 -telemetry2_0_CPPFLAGS = -fPIC -I/usr/include/dbus-1.0 \ - -I/usr/lib/x86_64-linux-gnu/dbus-1.0/include \ +telemetry2_0_CPPFLAGS = -fPIC -I${PKG_CONFIG_SYSROOT_DIR}$(includedir)/usr/include/dbus-1.0 \ + -I${PKG_CONFIG_SYSROOT_DIR}$(libdir)/dbus-1.0/include \ -I${PKG_CONFIG_SYSROOT_DIR}$(includedir)/ \ -I${PKG_CONFIG_SYSROOT_DIR}$(includedir)/rbus \ -I${top_srcdir}/include \ diff --git a/source/bulkdata/Makefile.am b/source/bulkdata/Makefile.am index ff93adca..78a5690e 100644 --- a/source/bulkdata/Makefile.am +++ b/source/bulkdata/Makefile.am @@ -23,8 +23,8 @@ lib_LTLIBRARIES = libbulkdata.la libbulkdata_la_SOURCES = reportprofiles.c profile.c profilexconf.c t2eventreceiver.c t2markers.c datamodel.c libbulkdata_la_LDFLAGS = -shared -fPIC -lcjson -lmsgpackc libbulkdata_la_LIBADD = ${top_builddir}/source/utils/libt2utils.la ${top_builddir}/source/dcautil/libdcautil.la ${top_builddir}/source/protocol/http/libhttp.la ${top_builddir}/source/protocol/rbusMethod/librbusmethod.la ${top_builddir}/source/ccspinterface/libccspinterface.la ${top_builddir}/source/reportgen/libreportgen.la ${top_builddir}/source/scheduler/libscheduler.la ${top_builddir}/source/xconf-client/libxconfclient.la -libbulkdata_la_CPPFLAGS = -fPIC -I/usr/include/dbus-1.0 \ - -I/usr/lib/x86_64-linux-gnu/dbus-1.0/include \ +libbulkdata_la_CPPFLAGS = -fPIC -I${PKG_CONFIG_SYSROOT_DIR}$(includedir)/dbus-1.0 \ + -I${PKG_CONFIG_SYSROOT_DIR}$(libdir)/dbus-1.0/include \ -I${PKG_CONFIG_SYSROOT_DIR}$(includedir) \ -I${PKG_CONFIG_SYSROOT_DIR}$(includedir)/rbus \ -I${top_srcdir}/source/utils \ From e18714660474491805145f2bd85c7013a781344d Mon Sep 17 00:00:00 2001 From: Muhammed rafi c Date: Tue, 27 Jan 2026 13:25:36 +0000 Subject: [PATCH 12/23] update build include path --- source/Makefile.am | 2 +- source/ccspinterface/Makefile.am | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/source/Makefile.am b/source/Makefile.am index 3cbe1848..f6866597 100644 --- a/source/Makefile.am +++ b/source/Makefile.am @@ -41,7 +41,7 @@ bin_PROGRAMS = telemetry2_0 telemetry2_0_SOURCES = telemetry2_0.c telemetry2_0_CFLAGS = -DFEATURE_SUPPORT_RDKLOG -D_FILE_OFFSET_BITS=64 -D_TIME_BITS=64 -telemetry2_0_CPPFLAGS = -fPIC -I${PKG_CONFIG_SYSROOT_DIR}$(includedir)/usr/include/dbus-1.0 \ +telemetry2_0_CPPFLAGS = -fPIC -I${PKG_CONFIG_SYSROOT_DIR}$(includedir)/dbus-1.0 \ -I${PKG_CONFIG_SYSROOT_DIR}$(libdir)/dbus-1.0/include \ -I${PKG_CONFIG_SYSROOT_DIR}$(includedir)/ \ -I${PKG_CONFIG_SYSROOT_DIR}$(includedir)/rbus \ diff --git a/source/ccspinterface/Makefile.am b/source/ccspinterface/Makefile.am index 52aa433b..13ddb27e 100644 --- a/source/ccspinterface/Makefile.am +++ b/source/ccspinterface/Makefile.am @@ -28,8 +28,8 @@ libccspinterface_la_LDFLAGS += -lccsp_common libccspinterface_la_SOURCES += ccspinterface.c endif -libccspinterface_la_CPPFLAGS = -fPIC $(CPPFLAGS) -I/usr/include/dbus-1.0 \ - -I/usr/lib/x86_64-linux-gnu/dbus-1.0/include \ +libccspinterface_la_CPPFLAGS = -fPIC $(CPPFLAGS) -I${PKG_CONFIG_SYSROOT_DIR}$(includedir)/dbus-1.0 \ + -I${PKG_CONFIG_SYSROOT_DIR}$(libdir)/dbus-1.0/include \ -I${PKG_CONFIG_SYSROOT_DIR}$(includedir)/ \ -I${PKG_CONFIG_SYSROOT_DIR}$(includedir)/ccsp \ -I${PKG_CONFIG_SYSROOT_DIR}$(includedir)/rbus \ From 08d9433a6e916db62dd216fd5ae18c028488d122 Mon Sep 17 00:00:00 2001 From: Muhammed rafi c Date: Wed, 28 Jan 2026 12:14:25 +0000 Subject: [PATCH 13/23] profile update event added --- source/bulkdata/reportprofiles.c | 10 +- source/bulkdata/t2eventreceiver.c | 4 +- source/ccspinterface/busInterface.c | 14 ++- source/ccspinterface/busInterface.h | 1 + source/ccspinterface/dbusInterface.c | 95 ++++++++-------- .../commonlib/telemetry_busmessage_sender.c | 3 +- source/commonlib/telemetry_client.c | 14 +-- source/utils/t2log_wrapper.c | 102 ++++++++++++++++++ 8 files changed, 182 insertions(+), 61 deletions(-) diff --git a/source/bulkdata/reportprofiles.c b/source/bulkdata/reportprofiles.c index dbe48be5..b647f7b3 100644 --- a/source/bulkdata/reportprofiles.c +++ b/source/bulkdata/reportprofiles.c @@ -315,7 +315,9 @@ T2ERROR ReportProfiles_setProfileXConf(ProfileXConf *profile) { unregisterDEforCompEventList(); createComponentDataElements(); - publishEventsProfileUpdates(); + //publishEventsProfileUpdates(); + publishDBUSEventsProfileUpdates(); + } T2ER_StartDispatchThread(); @@ -1082,7 +1084,8 @@ void ReportProfiles_ProcessReportProfilesBlob(cJSON *profiles_root, bool rprofil { createComponentDataElements(); // Notify registered components that profile has received an update - publishEventsProfileUpdates(); + //publishEventsProfileUpdates(); + publishDBUSEventsProfileUpdates(); getMarkerCompRbusSub(true); } hash_map_destroy(receivedProfileHashMap, freeReportProfileHashMap); @@ -1451,7 +1454,8 @@ int __ReportProfiles_ProcessReportProfilesMsgPackBlob(void *msgpack, bool checkP { createComponentDataElements(); // Notify registered components that profile has received an update - publishEventsProfileUpdates(); + // publishEventsProfileUpdates(); + publishDBUSEventsProfileUpdates(); getMarkerCompRbusSub(true); } msgpack_unpacked_destroy(&result); diff --git a/source/bulkdata/t2eventreceiver.c b/source/bulkdata/t2eventreceiver.c index 5099e0e0..804ddcbf 100644 --- a/source/bulkdata/t2eventreceiver.c +++ b/source/bulkdata/t2eventreceiver.c @@ -196,13 +196,13 @@ void T2ER_Push(char* eventName, char* eventValue) } else { - T2Debug("Received eventInfo : %s value : %s\n", eventName, (char* ) eventValue); + T2Info("Received eventInfo : %s value : %s\n", eventName, (char* ) eventValue); T2Event *event = (T2Event *) malloc(sizeof(T2Event)); if(event != NULL) { event->name = strdup(eventName); event->value = strdup(eventValue); - T2Debug("Adding eventName : %s eventValue : %s to t2event queue\n", event->name, event->value); + T2Info("Adding eventName : %s eventValue : %s to t2event queue\n", event->name, event->value); t2_queue_push(eQueue, (void *) event); if(!stopDispatchThread) { diff --git a/source/ccspinterface/busInterface.c b/source/ccspinterface/busInterface.c index 9c3ed504..4e33f877 100644 --- a/source/ccspinterface/busInterface.c +++ b/source/ccspinterface/busInterface.c @@ -122,6 +122,17 @@ Vector* getProfileParameterValues(Vector *paramList, int count) return profileValueList; } +T2ERROR publishDBUSEventsProfileUpdates() +{ + T2Debug("%s ++in\n", __FUNCTION__); + T2ERROR ret = T2ERROR_FAILURE ; + T2Info("Publishing dbus event for t2profile update notification to components \n"); + // ret = publishdbusEventsProfileUpdates(); + + T2Debug("%s --out\n", __FUNCTION__); + return ret; +} + /** * Register with right bus call back dpending on dbus/rbus mode */ @@ -138,7 +149,8 @@ T2ERROR registerForTelemetryEvents(TelemetryEventCallback eventCB) if (isRbus) { - ret = registerRbusT2EventListener(eventCB); + // ret = registerRbusT2EventListener(eventCB); + T2Info("RBUS repeaceled with dbus\n"); #ifdef DCMAGENT /* Register DCM Events */ diff --git a/source/ccspinterface/busInterface.h b/source/ccspinterface/busInterface.h index de0f33e9..d51f3ef6 100644 --- a/source/ccspinterface/busInterface.h +++ b/source/ccspinterface/busInterface.h @@ -101,6 +101,7 @@ void unregisterDEforCompEventList(); T2ERROR regDEforProfileDataModel(callBackHandlers* cbHandlers); T2ERROR publishEventsProfileUpdates() ; +T2ERROR publishDBUSEventsProfileUpdates(); #ifdef DCMAGENT /* DCM RBus event Publish functions */ diff --git a/source/ccspinterface/dbusInterface.c b/source/ccspinterface/dbusInterface.c index 32cb9c48..2c6a61d9 100755 --- a/source/ccspinterface/dbusInterface.c +++ b/source/ccspinterface/dbusInterface.c @@ -67,7 +67,7 @@ bool isDbusInitialized(void) { /* Handle GetOperationalStatus Method */ static DBusHandlerResult handle_get_operational_status(DBusConnection *connection, DBusMessage *message) { - T2Debug("handle_get_operational_status: Received GetOperationalStatus method call"); + T2Info("handle_get_operational_status: Received GetOperationalStatus method call\n"); DBusError error; dbus_error_init(&error); @@ -76,49 +76,49 @@ static DBusHandlerResult handle_get_operational_status(DBusConnection *connectio if (!dbus_message_get_args(message, &error, DBUS_TYPE_STRING, ¶m_name, DBUS_TYPE_INVALID)) { - T2Error("Failed to parse GetOperationalStatus arguments: %s", error.message); + T2Error("Failed to parse GetOperationalStatus arguments: %s\n", error.message); dbus_error_free(&error); return DBUS_HANDLER_RESULT_NOT_YET_HANDLED; } - T2Info("GetOperationalStatus called with param_name: %s", param_name); + T2Info("GetOperationalStatus called with param_name: %s\n", param_name); uint32_t value = 0; /* TODO check oprtational status of specific component param_name will componet name */ value = t2ReadyStatus; - T2Info("Returning operational status for %s: 0x%08X", param_name, value); + T2Info("Returning operational status for %s: 0x%08X\n", param_name, value); /* Create reply */ DBusMessage *reply = dbus_message_new_method_return(message); if (!reply) { - T2Error("Failed to create reply message"); + T2Error("Failed to create reply message\n"); return DBUS_HANDLER_RESULT_NEED_MEMORY; } if (!dbus_message_append_args(reply, DBUS_TYPE_UINT32, &value, DBUS_TYPE_INVALID)) { - T2Error("Failed to append reply arguments"); + T2Error("Failed to append reply arguments\n"); dbus_message_unref(reply); return DBUS_HANDLER_RESULT_NEED_MEMORY; } if (!dbus_connection_send(connection, reply, NULL)) { - T2Error("Failed to send reply"); + T2Error("Failed to send reply\n"); dbus_message_unref(reply); return DBUS_HANDLER_RESULT_NEED_MEMORY; } - T2Debug("GetOperationalStatus: Reply sent successfully"); + T2Info("GetOperationalStatus: Reply sent successfully\n"); dbus_message_unref(reply); - // dbus_connection_flush(connection); + dbus_connection_flush(connection); return DBUS_HANDLER_RESULT_HANDLED; } /* Handle SendT2Event Method */ static DBusHandlerResult handle_send_t2_event(DBusConnection *connection, DBusMessage *message) { - T2Debug("handle_send_t2_event: Received SendT2Event method call"); + T2Info("handle_send_t2_event: Received SendT2Event method call\n"); DBusError error; dbus_error_init(&error); @@ -130,39 +130,39 @@ static DBusHandlerResult handle_send_t2_event(DBusConnection *connection, DBusMe DBUS_TYPE_STRING, &marker_name, DBUS_TYPE_STRING, &data, DBUS_TYPE_INVALID)) { - T2Error("Failed to parse SendT2Event arguments: %s", error.message); + T2Error("Failed to parse SendT2Event arguments: %s\n", error.message); dbus_error_free(&error); return DBUS_HANDLER_RESULT_NOT_YET_HANDLED; } if (marker_name && data && eventCallBack) { - T2Debug("Received event: name=%s, value=%s\n", marker_name, data); + T2Info("Received event: name=%s, value=%s\n", marker_name, data); eventCallBack(strdup(marker_name), strdup(data)); } /* Create empty reply (method returns void) */ DBusMessage *reply = dbus_message_new_method_return(message); if (!reply) { - T2Error("Failed to create reply message"); + T2Error("Failed to create reply message\n"); return DBUS_HANDLER_RESULT_NEED_MEMORY; } if (!dbus_connection_send(connection, reply, NULL)) { - T2Error("Failed to send reply"); + T2Error("Failed to send reply\n"); dbus_message_unref(reply); return DBUS_HANDLER_RESULT_NEED_MEMORY; } - T2Debug("SendT2Event: Reply sent successfully"); + T2Info("SendT2Event: Reply sent successfully\n"); dbus_message_unref(reply); - // dbus_connection_flush(connection); + dbus_connection_flush(connection); return DBUS_HANDLER_RESULT_HANDLED; } /* Handle GetMarkerList Method */ static DBusHandlerResult handle_get_marker_list(DBusConnection *connection, DBusMessage *message) { - T2Debug("handle_get_marker_list: Received GetMarkerList method call"); + T2Info("handle_get_marker_list: Received GetMarkerList method call\n"); DBusMessage *reply = NULL; DBusError error; @@ -172,17 +172,22 @@ static DBusHandlerResult handle_get_marker_list(DBusConnection *connection, DBus if (!dbus_message_get_args(message, &error, DBUS_TYPE_STRING, &component_name, DBUS_TYPE_INVALID)) { - T2Error("Failed to parse GetMarkerList arguments: %s", error.message); + T2Error("Failed to parse GetMarkerList arguments: %s\n", error.message); dbus_error_free(&error); return DBUS_HANDLER_RESULT_NOT_YET_HANDLED; } - - T2Info("GetMarkerList called for component: %s", component_name); + + T2Info("GetMarkerList called for component: %s\n", component_name); if (!getMarkerListCallBack) { T2Error("GetMarkerList callback not registered\n"); reply = dbus_message_new_error(message, DBUS_ERROR_FAILED, "Marker list callback not initialized"); + if (reply) { + dbus_connection_send(connection, reply, NULL); + dbus_connection_flush(connection); + dbus_message_unref(reply); + } } else { @@ -202,7 +207,7 @@ static DBusHandlerResult handle_get_marker_list(DBusConnection *connection, DBus reply = dbus_message_new_method_return(message); if (!reply) { - T2Error("Failed to create reply message"); + T2Error("Failed to create reply message\n"); return DBUS_HANDLER_RESULT_NEED_MEMORY; } const char *result = markerListStr; @@ -210,21 +215,21 @@ static DBusHandlerResult handle_get_marker_list(DBusConnection *connection, DBus if (!dbus_message_append_args(reply, DBUS_TYPE_STRING, &result, DBUS_TYPE_INVALID)) { - T2Error("Failed to append reply arguments"); + T2Error("Failed to append reply arguments\n"); dbus_message_unref(reply); return DBUS_HANDLER_RESULT_NEED_MEMORY; } - T2Debug("Returning marker list: %s\n", markerListStr); + T2Info("Returning marker list: %s\n", markerListStr); if (!dbus_connection_send(connection, reply, NULL)) { - T2Error("Failed to send reply"); + T2Error("Failed to send reply\n"); dbus_message_unref(reply); return DBUS_HANDLER_RESULT_NEED_MEMORY; } - // dbus_connection_flush(connection); - T2Debug("GetMarkerList: Reply sent successfully"); + dbus_connection_flush(connection); + T2Info("GetMarkerList: Reply sent successfully\n"); dbus_message_unref(reply); } @@ -239,7 +244,7 @@ static DBusHandlerResult message_handler(DBusConnection *connection, DBusMessage const char* member = dbus_message_get_member(message); const char* path = dbus_message_get_path(message); - T2Debug("Received D-Bus message: interface=%s, member=%s, path=%s", + T2Info("Received D-Bus message: interface=%s, member=%s, path=%s\n", interface ? interface : "NULL", member ? member : "NULL", path ? path : "NULL"); @@ -267,37 +272,37 @@ static DBusHandlerResult message_handler(DBusConnection *connection, DBusMessage static void* dbusListenerThreadFunc(void *arg) { (void)arg; - T2Debug("%s ++in\n", __FUNCTION__); + T2Info("%s ++in\n", __FUNCTION__); while (!stopListenerThread && t2dbus_handle.connection) { dbus_connection_read_write_dispatch(t2dbus_handle.connection, 100); usleep(1000); } - T2Debug("%s --out\n", __FUNCTION__); + T2Info("%s --out\n", __FUNCTION__); return NULL; } T2ERROR publishdbusEventsProfileUpdates(void) { - T2Debug("%s ++in\n", __FUNCTION__); - if(!t2dbus_handle.is_initialized) - { - T2Error("D-Bus not initialized\n"); - return T2ERROR_INTERNAL_ERROR; + T2Info("%s ++in\n", __FUNCTION__); + if (!t2dbus_handle.is_initialized) { + if (dBusInterface_Init() != T2ERROR_SUCCESS) { + return T2ERROR_FAILURE; + } } DBusMessage *signal = dbus_message_new_signal(T2_DBUS_OBJECT_PATH, T2_DBUS_EVENT_INTERFACE_NAME, T2_DBUS_SIGNAL_PROFILE_UPDATE); if (!signal) { - T2Error("Failed to create ProfileUpdate signal"); + T2Error("Failed to create ProfileUpdate signal\n"); return T2ERROR_FAILURE; } /* Send signal - this queues the message */ dbus_uint32_t serial = 0; if (!dbus_connection_send(t2dbus_handle.connection, signal, &serial)) { - T2Error("Failed to send ProfileUpdate signal - out of memory"); + T2Error("Failed to send ProfileUpdate signal - out of memory\n"); dbus_message_unref(signal); return T2ERROR_FAILURE; } @@ -307,7 +312,7 @@ T2ERROR publishdbusEventsProfileUpdates(void) /* Flush to ensure signal is sent immediately */ //dbus_connection_flush(t2dbus_handle.connection); - T2Debug("ProfileUpdate signal sent successfully (serial=%u)", serial); + T2Info("ProfileUpdate signal sent successfully (serial=%u)\n", serial); return T2ERROR_SUCCESS; } @@ -329,7 +334,7 @@ T2ERROR dBusInterface_Init() { dbus_error_init(&error); if (!dbus_threads_init_default()) { - T2Error("Failed to initialize D-Bus threading"); + T2Error("Failed to initialize D-Bus threading\n"); return 1; } @@ -347,9 +352,7 @@ T2ERROR dBusInterface_Init() { pthread_mutex_unlock(&dbusMutex); return T2ERROR_FAILURE; } - - - + T2Info("Connected to D-Bus system bus\n"); int ret = dbus_bus_request_name(t2dbus_handle.connection, T2_DBUS_SERVICE_NAME, DBUS_NAME_FLAG_REPLACE_EXISTING, &error); if (dbus_error_is_set(&error)) { @@ -362,14 +365,14 @@ T2ERROR dBusInterface_Init() { } if (ret != DBUS_REQUEST_NAME_REPLY_PRIMARY_OWNER) { - T2Error("Not primary owner of the name (ret=%d)", ret); + T2Error("Not primary owner of the name (ret=%d)\n", ret); dbus_connection_unref(t2dbus_handle.connection); t2dbus_handle.connection = NULL; pthread_mutex_unlock(&dbusMutex); return T2ERROR_FAILURE; } - T2Info("Acquired service name: %s", T2_DBUS_SERVICE_NAME); + T2Info("Acquired service name: %s\n", T2_DBUS_SERVICE_NAME); /* Store unique name */ t2dbus_handle.unique_name = strdup(dbus_bus_get_unique_name(t2dbus_handle.connection)); @@ -381,12 +384,11 @@ T2ERROR dBusInterface_Init() { if (!dbus_connection_register_object_path(t2dbus_handle.connection, T2_DBUS_OBJECT_PATH, &vtable, NULL)) { - T2Error("Failed to register object path"); + T2Error("Failed to register object path\n"); dbus_connection_unref(t2dbus_handle.connection); return T2ERROR_FAILURE; } - T2Info("Registered object path: %s", T2_DBUS_OBJECT_PATH); - + T2Info("Registered object path: %s\n", T2_DBUS_OBJECT_PATH); //TODO check ready status based on component initialization t2ReadyStatus = T2_STATE_COMPONENT_READY; t2dbus_handle.is_initialized = true; @@ -599,6 +601,7 @@ T2ERROR registerDbusT2EventListener(TelemetryEventCallback eventCB) { return T2ERROR_INVALID_ARGS; } + T2Info("Registering D-Bus telemetry event listener\n"); eventCallBack = eventCB; T2Debug("%s --out\n", __FUNCTION__); diff --git a/source/commonlib/telemetry_busmessage_sender.c b/source/commonlib/telemetry_busmessage_sender.c index a2ce076a..f702d4ab 100644 --- a/source/commonlib/telemetry_busmessage_sender.c +++ b/source/commonlib/telemetry_busmessage_sender.c @@ -1238,7 +1238,7 @@ static bool isCachingRequired( ) else { EVENT_DEBUG("value for %s is : %d\n", T2_OPERATIONAL_STATUS, t2ReadyStatus); - if((t2ReadyStatus & T2_STATE_COMPONENT_READY) == 0) + if((t2ReadyStatus & T2_STATE_READY) == 0) { return true; } @@ -1381,7 +1381,6 @@ static int report_or_cache_data(char* telemetry_data, const char* markerName) void t2_init(char *component) { componentName = strdup(component); - isCachingRequired(); } void t2_uninit(void) diff --git a/source/commonlib/telemetry_client.c b/source/commonlib/telemetry_client.c index 1d28c658..0c370e0d 100644 --- a/source/commonlib/telemetry_client.c +++ b/source/commonlib/telemetry_client.c @@ -23,8 +23,8 @@ #include #include -#define COMP_NAME "telemetry_client" -/* +#define COMP_NAME "client_one" + int main(int argc, char *argv[]) { (void) argc;// To fix compiler warning @@ -35,8 +35,8 @@ int main(int argc, char *argv[]) return 0; } -*/ -/* + +#if 0 int main(int argc, char *argv[]) { int i = 0, n; @@ -53,9 +53,8 @@ int main(int argc, char *argv[]) printf("Sent %d t2_event_d events.\n", n); return 0; } - */ - - +#endif +#if 0 // Thread argument structure typedef struct { int value; @@ -130,3 +129,4 @@ int main(int argc, char *argv[]) t2_uninit(); return 0; } +#endif \ No newline at end of file diff --git a/source/utils/t2log_wrapper.c b/source/utils/t2log_wrapper.c index d433e149..4e97d7ab 100644 --- a/source/utils/t2log_wrapper.c +++ b/source/utils/t2log_wrapper.c @@ -1,3 +1,5 @@ + + /* * If not stated otherwise in this file or this component's LICENSE file the * following copyright and licenses apply: @@ -24,6 +26,8 @@ #include #include #include +#include +#include #ifdef GTEST_ENABLE #include "test/rdk_logger/include/rdk_debug.h" #else @@ -31,6 +35,22 @@ #endif unsigned int rdkLogLevel = RDK_LOG_INFO; +static pthread_mutex_t loggerMutex = PTHREAD_MUTEX_INITIALIZER; + +/* Convert log level to string */ +static const char* getLogLevelString(unsigned int level) +{ + switch(level) + { + case RDK_LOG_FATAL: return "FATAL"; + case RDK_LOG_ERROR: return "ERROR"; + case RDK_LOG_WARN: return "WARN"; + case RDK_LOG_NOTICE: return "NOTICE"; + case RDK_LOG_INFO: return "INFO"; + case RDK_LOG_DEBUG: return "DEBUG"; + default: return "UNKNOWN"; + } +} void LOGInit() { @@ -42,6 +62,7 @@ void LOGInit() } +#if 0 void T2Log(unsigned int level, const char *msg, ...) { va_list arg; @@ -92,3 +113,84 @@ void T2Log(unsigned int level, const char *msg, ...) free(pTempChar); } } +#endif + +void T2Log(unsigned int level, const char *msg, ...) +{ + va_list arg; + char *pTempChar = NULL; + int ret = 0; + FILE *logHandle = NULL; + + if (NULL == msg) + { + return; + } + + /* Check if debug logging is enabled for RDK_LOG_DEBUG (level 5) */ + if (level == RDK_LOG_DEBUG) + { + if (access(ENABLE_DEBUG_FLAG, F_OK) == -1) + { + return; + } + } + + /* Compose the log message */ + va_start(arg, msg); + int messageLen = vsnprintf(NULL, 0, msg, arg); + va_end(arg); + + if (messageLen < 1) + { + return; + } + + messageLen++; + pTempChar = (char *)malloc(messageLen); + if (!pTempChar) + { + return; + } + + memset(pTempChar, '\0', messageLen); + va_start(arg, msg); + ret = vsnprintf(pTempChar, messageLen, msg, arg); + va_end(arg); + + if (ret < 0) + { + free(pTempChar); + return; + } + + /* Write to log file with timestamp */ + pthread_mutex_lock(&loggerMutex); + logHandle = fopen("/opt/logs/t2.log", "a+"); + if (logHandle) + { + struct timespec ts; + struct tm timeinfo; + + if (clock_gettime(CLOCK_REALTIME, &ts) == -1) + { + fclose(logHandle); + pthread_mutex_unlock(&loggerMutex); + free(pTempChar); + return; + } + + char timeBuffer[24] = { '\0' }; + long msecs; + + localtime_r(&ts.tv_sec, &timeinfo); + msecs = ts.tv_nsec / 1000000; + strftime(timeBuffer, sizeof(timeBuffer), "%Y-%m-%d %H:%M:%S", &timeinfo); + snprintf(timeBuffer + strlen(timeBuffer), sizeof(timeBuffer) - strlen(timeBuffer), ".%03ld", msecs); + fprintf(logHandle, "%s [%s] : %s", timeBuffer, getLogLevelString(level), pTempChar); + fclose(logHandle); + } + pthread_mutex_unlock(&loggerMutex); + + free(pTempChar); +} From 31fbac5046415dab62658407d7180d4f3367097c Mon Sep 17 00:00:00 2001 From: Muhammed rafi c Date: Thu, 29 Jan 2026 04:12:06 +0000 Subject: [PATCH 14/23] RDKLogger update --- source/bulkdata/t2markers.c | 1 + source/utils/t2log_wrapper.c | 37 +++++++++++++++++++----------------- 2 files changed, 21 insertions(+), 17 deletions(-) diff --git a/source/bulkdata/t2markers.c b/source/bulkdata/t2markers.c index 20bb3b3e..9ff7dc59 100644 --- a/source/bulkdata/t2markers.c +++ b/source/bulkdata/t2markers.c @@ -330,6 +330,7 @@ void createComponentDataElements() char *compName = (char*) Vector_At(componentList, i); if(compName) { + T2Info("Register data element for component %s \n", compName); regDEforCompEventList(compName, getComponentMarkerList); } } diff --git a/source/utils/t2log_wrapper.c b/source/utils/t2log_wrapper.c index 4e97d7ab..1aa851fe 100644 --- a/source/utils/t2log_wrapper.c +++ b/source/utils/t2log_wrapper.c @@ -35,22 +35,6 @@ #endif unsigned int rdkLogLevel = RDK_LOG_INFO; -static pthread_mutex_t loggerMutex = PTHREAD_MUTEX_INITIALIZER; - -/* Convert log level to string */ -static const char* getLogLevelString(unsigned int level) -{ - switch(level) - { - case RDK_LOG_FATAL: return "FATAL"; - case RDK_LOG_ERROR: return "ERROR"; - case RDK_LOG_WARN: return "WARN"; - case RDK_LOG_NOTICE: return "NOTICE"; - case RDK_LOG_INFO: return "INFO"; - case RDK_LOG_DEBUG: return "DEBUG"; - default: return "UNKNOWN"; - } -} void LOGInit() { @@ -62,7 +46,7 @@ void LOGInit() } -#if 0 +#if 1 void T2Log(unsigned int level, const char *msg, ...) { va_list arg; @@ -114,6 +98,24 @@ void T2Log(unsigned int level, const char *msg, ...) } } #endif +#if 0 + +static pthread_mutex_t loggerMutex = PTHREAD_MUTEX_INITIALIZER; + +/* Convert log level to string */ +static const char* getLogLevelString(unsigned int level) +{ + switch(level) + { + case RDK_LOG_FATAL: return "FATAL"; + case RDK_LOG_ERROR: return "ERROR"; + case RDK_LOG_WARN: return "WARN"; + case RDK_LOG_NOTICE: return "NOTICE"; + case RDK_LOG_INFO: return "INFO"; + case RDK_LOG_DEBUG: return "DEBUG"; + default: return "UNKNOWN"; + } +} void T2Log(unsigned int level, const char *msg, ...) { @@ -194,3 +196,4 @@ void T2Log(unsigned int level, const char *msg, ...) free(pTempChar); } +#endif \ No newline at end of file From 0eef33e317db6f9b8b93c09c8a0e36f18a0657f5 Mon Sep 17 00:00:00 2001 From: Muhammed rafi c Date: Thu, 29 Jan 2026 07:17:17 +0000 Subject: [PATCH 15/23] update the profileupdate event --- source/bulkdata/t2markers.c | 12 +++++++++++- source/ccspinterface/busInterface.c | 13 ++++++++++++- source/ccspinterface/busInterface.h | 3 ++- source/ccspinterface/dbusInterface.c | 2 +- source/ccspinterface/dbusInterface.h | 2 +- source/commonlib/telemetry_busmessage_sender.c | 10 +++++----- 6 files changed, 32 insertions(+), 10 deletions(-) diff --git a/source/bulkdata/t2markers.c b/source/bulkdata/t2markers.c index 9ff7dc59..3a19baec 100644 --- a/source/bulkdata/t2markers.c +++ b/source/bulkdata/t2markers.c @@ -331,7 +331,17 @@ void createComponentDataElements() if(compName) { T2Info("Register data element for component %s \n", compName); - regDEforCompEventList(compName, getComponentMarkerList); + //TODO componet specific dbus inteface registration like rbus data element registration + if(T2ERROR_SUCCESS == registerGetMarkerListCallback(getComponentMarkerList)) + { + T2Info("Registered get marker list callback for component %s \n", compName); + i = length; // exit for loop because dbus uses common callback for all components + } + else + { + T2Error("Failed to register get marker list callback for component %s \n", compName); + } + //regDEforCompEventList(compName, getComponentMarkerList); } } pthread_mutex_unlock(&t2CompListMutex); diff --git a/source/ccspinterface/busInterface.c b/source/ccspinterface/busInterface.c index 4e33f877..684d9bc5 100644 --- a/source/ccspinterface/busInterface.c +++ b/source/ccspinterface/busInterface.c @@ -127,7 +127,18 @@ T2ERROR publishDBUSEventsProfileUpdates() T2Debug("%s ++in\n", __FUNCTION__); T2ERROR ret = T2ERROR_FAILURE ; T2Info("Publishing dbus event for t2profile update notification to components \n"); - // ret = publishdbusEventsProfileUpdates(); + ret = publishdbusEventsProfileUpdates(); + + T2Debug("%s --out\n", __FUNCTION__); + return ret; +} + +T2ERROR registerGetMarkerListCallback(T2EventMarkerListCallback callback) +{ + T2Debug("%s ++in\n", __FUNCTION__); + T2ERROR ret = T2ERROR_FAILURE ; + + ret = registerDbusHandlerGetMarkerListCallback(callback); T2Debug("%s --out\n", __FUNCTION__); return ret; diff --git a/source/ccspinterface/busInterface.h b/source/ccspinterface/busInterface.h index d51f3ef6..bf90243a 100644 --- a/source/ccspinterface/busInterface.h +++ b/source/ccspinterface/busInterface.h @@ -93,7 +93,8 @@ T2ERROR registerForTelemetryEvents(TelemetryEventCallback eventCB); // Needs to be called only in rBus mode T2ERROR regDEforCompEventList(const char* componentName, T2EventMarkerListCallback callBackHandler) ; - +// Common callback registration for dbus +T2ERROR registerGetMarkerListCallback(T2EventMarkerListCallback callback); void setT2EventReceiveState(int T2_STATE); void unregisterDEforCompEventList(); diff --git a/source/ccspinterface/dbusInterface.c b/source/ccspinterface/dbusInterface.c index 2c6a61d9..710c0595 100755 --- a/source/ccspinterface/dbusInterface.c +++ b/source/ccspinterface/dbusInterface.c @@ -620,7 +620,7 @@ T2ERROR unregisterDbusT2EventListener(void) { return T2ERROR_SUCCESS; } -T2ERROR registerGetMarkerListCallback(T2EventMarkerListCallback callback) { +T2ERROR registerDbusHandlerGetMarkerListCallback(T2EventMarkerListCallback callback) { T2Debug("%s ++in\n", __FUNCTION__); if (!callback) { diff --git a/source/ccspinterface/dbusInterface.h b/source/ccspinterface/dbusInterface.h index 6d958290..21464610 100755 --- a/source/ccspinterface/dbusInterface.h +++ b/source/ccspinterface/dbusInterface.h @@ -86,6 +86,6 @@ T2ERROR registerDbusT2EventListener(TelemetryEventCallback eventCB); T2ERROR unregisterDbusT2EventListener(void); T2ERROR publishdbusEventsProfileUpdates(void); -T2ERROR registerGetMarkerListCallback(T2EventMarkerListCallback callback); +T2ERROR registerDbusHandlerGetMarkerListCallback(T2EventMarkerListCallback callback); #endif /* _DBUSINTERFACE_H_ */ diff --git a/source/commonlib/telemetry_busmessage_sender.c b/source/commonlib/telemetry_busmessage_sender.c index f702d4ab..b6a3e9f7 100644 --- a/source/commonlib/telemetry_busmessage_sender.c +++ b/source/commonlib/telemetry_busmessage_sender.c @@ -714,7 +714,7 @@ static bool initRFC( ) if(initMessageBus() != 0) { EVENT_ERROR("initMessageBus failed\n"); - status = false ; + status = false; } else { @@ -810,7 +810,7 @@ int filtered_event_send(const char* data, const char *markerName) // Filter data from marker list if(componentName && (0 != strcmp(componentName, T2_SCRIPT_EVENT_COMPONENT))) // Events from scripts needs to be sent without filtering { - EVENT_DEBUG("%s markerListMutex lock & get list of marker for component %s \n", __FUNCTION__, componentName); + EVENT_DEBUG("markerListMutex lock & component %s , marker %s\n", componentName, markerName); pthread_mutex_lock(&markerListMutex); bool isEventingEnabled = false; if(markerName && eventMarkerMap) @@ -822,13 +822,13 @@ int filtered_event_send(const char* data, const char *markerName) } else { - EVENT_DEBUG("%s eventMarkerMap for component %s is empty \n", __FUNCTION__, componentName ); + EVENT_DEBUG("eventMarkerMap for component %s is empty \n", componentName ); } EVENT_DEBUG("%s markerListMutex unlock\n", __FUNCTION__ ); pthread_mutex_unlock(&markerListMutex); if(!isEventingEnabled) { - EVENT_DEBUG("%s markerName %s not found in event list for component %s . Unlock markerListMutex . \n", __FUNCTION__, markerName, componentName); + EVENT_DEBUG("markerName %s not found in event list for component %s . Unlock markerListMutex . \n", markerName, componentName); return status; } } @@ -1069,7 +1069,7 @@ static T2ERROR doPopulateEventMarkerList( ) if(markerListStr && strlen(markerListStr) > 0) { eventMarkerMap = hash_map_create(); - EVENT_DEBUG("\t D-Bus mode: Update event map for component %s with below events :", componentName); + EVENT_DEBUG("Update event map for component %s with below events :\n", componentName); char* markerListCopy = strdup(markerListStr); char* token = strtok(markerListCopy, ","); From f15b73cdf98fdb054052f220cb3265e22003c959 Mon Sep 17 00:00:00 2001 From: Muhammed rafi c Date: Thu, 29 Jan 2026 09:39:07 +0000 Subject: [PATCH 16/23] wellknown name changed --- .../commonlib/telemetry_busmessage_sender.c | 83 ++++--------------- 1 file changed, 16 insertions(+), 67 deletions(-) diff --git a/source/commonlib/telemetry_busmessage_sender.c b/source/commonlib/telemetry_busmessage_sender.c index b6a3e9f7..247981d7 100644 --- a/source/commonlib/telemetry_busmessage_sender.c +++ b/source/commonlib/telemetry_busmessage_sender.c @@ -435,77 +435,26 @@ static T2ERROR initMessageBus( ) dbus_error_free(&error); status = T2ERROR_FAILURE; } - else if (bus_handle) + + /* Initialize SIGNAL connection separately */ + signal_bus_handle = (void*)dbus_bus_get(DBUS_BUS_SYSTEM, &error); + + if (dbus_error_is_set(&error)) { - int ret = dbus_bus_request_name((DBusConnection*)bus_handle, dbusName, - DBUS_NAME_FLAG_REPLACE_EXISTING, &error); - if (dbus_error_is_set(&error)) - { - EVENT_ERROR("%s:%d, D-Bus method call name request failed: %s\n", __func__, __LINE__, error.message); - dbus_error_free(&error); - dbus_connection_unref((DBusConnection*)bus_handle); - bus_handle = NULL; - status = T2ERROR_FAILURE; - } - else if (ret != DBUS_REQUEST_NAME_REPLY_PRIMARY_OWNER && ret != DBUS_REQUEST_NAME_REPLY_ALREADY_OWNER) - { - EVENT_ERROR("%s:%d, D-Bus method call name request returned: %d\n", __func__, __LINE__, ret); - dbus_connection_unref((DBusConnection*)bus_handle); - bus_handle = NULL; - status = T2ERROR_FAILURE; - } - else - { - EVENT_DEBUG("%s:%d, D-Bus method call connection initialized as: %s\n", __func__, __LINE__, dbusName); - - /* Initialize SIGNAL connection separately */ - signal_bus_handle = (void*)dbus_bus_get(DBUS_BUS_SYSTEM, &error); - - if (dbus_error_is_set(&error)) - { - EVENT_ERROR("%s:%d, D-Bus signal connection init failed: %s\n", __func__, __LINE__, error.message); - dbus_error_free(&error); - /* Continue without signal support */ - signal_bus_handle = NULL; - } - else if (signal_bus_handle) - { - ret = dbus_bus_request_name((DBusConnection*)signal_bus_handle, signalDbusName, - DBUS_NAME_FLAG_REPLACE_EXISTING, &error); - if (dbus_error_is_set(&error)) - { - EVENT_ERROR("%s:%d, D-Bus signal name request failed: %s\n", __func__, __LINE__, error.message); - dbus_error_free(&error); - dbus_connection_unref((DBusConnection*)signal_bus_handle); - signal_bus_handle = NULL; - } - else if (ret != DBUS_REQUEST_NAME_REPLY_PRIMARY_OWNER && ret != DBUS_REQUEST_NAME_REPLY_ALREADY_OWNER) - { - EVENT_ERROR("%s:%d, D-Bus signal name request returned: %d\n", __func__, __LINE__, ret); - dbus_connection_unref((DBusConnection*)signal_bus_handle); - signal_bus_handle = NULL; - } - else - { - EVENT_DEBUG("%s:%d, D-Bus signal connection initialized as: %s\n", __func__, __LINE__, signalDbusName); - } - } - - if (signal_bus_handle && bus_handle) - { - status = T2ERROR_SUCCESS; - EVENT_DEBUG("%s:%d, D-Bus initialized successfully with separate connections\n", __func__, __LINE__); - } - else if (bus_handle) - { - /* Allow operation with method calls only if signal connection failed */ - status = T2ERROR_SUCCESS; - EVENT_ERROR("%s:%d, D-Bus initialized with method calls only (signal connection failed)\n", __func__, __LINE__); - } - } + EVENT_ERROR("%s:%d, D-Bus signal connection init failed: %s\n", __func__, __LINE__, error.message); + dbus_error_free(&error); + /* Continue without signal support */ + signal_bus_handle = NULL; + } + + if (signal_bus_handle && bus_handle) + { + status = T2ERROR_SUCCESS; + EVENT_DEBUG("%s:%d, D-Bus initialized successfully with separate connections\n", __func__, __LINE__); } else { + EVENT_ERROR("%s:%d, D-Bus initialization failed\n", __func__, __LINE__); status = T2ERROR_FAILURE; } } From b847138f6ab8c9b25db766d0f380edaa4db541c8 Mon Sep 17 00:00:00 2001 From: Muhammed rafi c Date: Thu, 29 Jan 2026 10:16:16 +0000 Subject: [PATCH 17/23] client name updated --- source/commonlib/telemetry_client.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/source/commonlib/telemetry_client.c b/source/commonlib/telemetry_client.c index 0c370e0d..19460498 100644 --- a/source/commonlib/telemetry_client.c +++ b/source/commonlib/telemetry_client.c @@ -23,7 +23,7 @@ #include #include -#define COMP_NAME "client_one" +#define COMP_NAME "telemetry_client" int main(int argc, char *argv[]) { From b1e8760cd4c74957df3ebc811a795b18e5b9fe61 Mon Sep 17 00:00:00 2001 From: Muhammed rafi c Date: Thu, 29 Jan 2026 17:00:56 +0000 Subject: [PATCH 18/23] client side log updated --- source/ccspinterface/dbusInterface.c | 23 ++++++++----------- .../commonlib/telemetry_busmessage_sender.c | 13 +++-------- 2 files changed, 13 insertions(+), 23 deletions(-) diff --git a/source/ccspinterface/dbusInterface.c b/source/ccspinterface/dbusInterface.c index 710c0595..1b51780d 100755 --- a/source/ccspinterface/dbusInterface.c +++ b/source/ccspinterface/dbusInterface.c @@ -67,7 +67,6 @@ bool isDbusInitialized(void) { /* Handle GetOperationalStatus Method */ static DBusHandlerResult handle_get_operational_status(DBusConnection *connection, DBusMessage *message) { - T2Info("handle_get_operational_status: Received GetOperationalStatus method call\n"); DBusError error; dbus_error_init(&error); @@ -81,7 +80,7 @@ static DBusHandlerResult handle_get_operational_status(DBusConnection *connectio return DBUS_HANDLER_RESULT_NOT_YET_HANDLED; } - T2Info("GetOperationalStatus called with param_name: %s\n", param_name); + T2Debug("GetOperationalStatus called with param_name: %s\n", param_name); uint32_t value = 0; /* TODO check oprtational status of specific component param_name will componet name */ @@ -109,7 +108,6 @@ static DBusHandlerResult handle_get_operational_status(DBusConnection *connectio return DBUS_HANDLER_RESULT_NEED_MEMORY; } - T2Info("GetOperationalStatus: Reply sent successfully\n"); dbus_message_unref(reply); dbus_connection_flush(connection); @@ -118,7 +116,7 @@ static DBusHandlerResult handle_get_operational_status(DBusConnection *connectio /* Handle SendT2Event Method */ static DBusHandlerResult handle_send_t2_event(DBusConnection *connection, DBusMessage *message) { - T2Info("handle_send_t2_event: Received SendT2Event method call\n"); + T2Debug("handle_send_t2_event: Received SendT2Event method call\n"); DBusError error; dbus_error_init(&error); @@ -153,7 +151,7 @@ static DBusHandlerResult handle_send_t2_event(DBusConnection *connection, DBusMe return DBUS_HANDLER_RESULT_NEED_MEMORY; } - T2Info("SendT2Event: Reply sent successfully\n"); + T2Debug("SendT2Event: Reply sent successfully\n"); dbus_message_unref(reply); dbus_connection_flush(connection); @@ -162,8 +160,7 @@ static DBusHandlerResult handle_send_t2_event(DBusConnection *connection, DBusMe /* Handle GetMarkerList Method */ static DBusHandlerResult handle_get_marker_list(DBusConnection *connection, DBusMessage *message) { - T2Info("handle_get_marker_list: Received GetMarkerList method call\n"); - + T2Debug("handle_get_marker_list: Received GetMarkerList method call\n"); DBusMessage *reply = NULL; DBusError error; dbus_error_init(&error); @@ -229,7 +226,7 @@ static DBusHandlerResult handle_get_marker_list(DBusConnection *connection, DBus } dbus_connection_flush(connection); - T2Info("GetMarkerList: Reply sent successfully\n"); + T2Debug("GetMarkerList: Reply sent successfully\n"); dbus_message_unref(reply); } @@ -244,7 +241,7 @@ static DBusHandlerResult message_handler(DBusConnection *connection, DBusMessage const char* member = dbus_message_get_member(message); const char* path = dbus_message_get_path(message); - T2Info("Received D-Bus message: interface=%s, member=%s, path=%s\n", + T2Debug("Received D-Bus message: interface=%s, member=%s, path=%s\n", interface ? interface : "NULL", member ? member : "NULL", path ? path : "NULL"); @@ -272,19 +269,19 @@ static DBusHandlerResult message_handler(DBusConnection *connection, DBusMessage static void* dbusListenerThreadFunc(void *arg) { (void)arg; - T2Info("%s ++in\n", __FUNCTION__); + T2Debug("%s ++in\n", __FUNCTION__); while (!stopListenerThread && t2dbus_handle.connection) { dbus_connection_read_write_dispatch(t2dbus_handle.connection, 100); usleep(1000); } - T2Info("%s --out\n", __FUNCTION__); + T2Debug("%s --out\n", __FUNCTION__); return NULL; } T2ERROR publishdbusEventsProfileUpdates(void) { - T2Info("%s ++in\n", __FUNCTION__); + T2Debug("%s ++in\n", __FUNCTION__); if (!t2dbus_handle.is_initialized) { if (dBusInterface_Init() != T2ERROR_SUCCESS) { return T2ERROR_FAILURE; @@ -312,7 +309,7 @@ T2ERROR publishdbusEventsProfileUpdates(void) /* Flush to ensure signal is sent immediately */ //dbus_connection_flush(t2dbus_handle.connection); - T2Info("ProfileUpdate signal sent successfully (serial=%u)\n", serial); + T2Debug("ProfileUpdate signal sent successfully (serial=%u)\n", serial); return T2ERROR_SUCCESS; } diff --git a/source/commonlib/telemetry_busmessage_sender.c b/source/commonlib/telemetry_busmessage_sender.c index 247981d7..58fc3b99 100644 --- a/source/commonlib/telemetry_busmessage_sender.c +++ b/source/commonlib/telemetry_busmessage_sender.c @@ -87,7 +87,6 @@ static pthread_mutex_t loggerMutex ; static pthread_t dbus_event_thread; static bool dbus_event_thread_running = false; -#if defined(RBUS_SUPPORT_ENABLED) static void EVENT_DEBUG(char* format, ...) { @@ -129,7 +128,7 @@ static void EVENT_DEBUG(char* format, ...) pthread_mutex_unlock(&loggerMutex); } -#else +#if 0 #define EVENT_DEBUG(format, ...) do { \ struct timespec ts; \ struct tm timeinfo; \ @@ -777,7 +776,7 @@ int filtered_event_send(const char* data, const char *markerName) pthread_mutex_unlock(&markerListMutex); if(!isEventingEnabled) { - EVENT_DEBUG("markerName %s not found in event list for component %s . Unlock markerListMutex . \n", markerName, componentName); + EVENT_DEBUG("markerName %s not found in event list for component %s \n", markerName, componentName); return status; } } @@ -1245,9 +1244,6 @@ static bool isCachingRequired( ) "type='signal',path='%s',interface='%s',member='ProfileUpdate'", T2_DBUS_OBJECT_PATH, T2_DBUS_EVENT_INTERFACE_NAME); - EVENT_DEBUG("D-Bus: Adding match rule: %s\n", rule); - EVENT_DEBUG("D-Bus: Event Interface: %s, Path: %s\n", T2_DBUS_EVENT_INTERFACE_NAME, T2_DBUS_OBJECT_PATH); - dbus_bus_add_match((DBusConnection*)signal_bus_handle, rule, &error); if (dbus_error_is_set(&error)) @@ -1257,10 +1253,8 @@ static bool isCachingRequired( ) } else { - EVENT_DEBUG("D-Bus: Match rule added successfully\n"); - // Add message filter for handling signals on SIGNAL connection dbus_connection_add_filter((DBusConnection*)signal_bus_handle, dbusEventReceiveHandler, NULL, NULL); - EVENT_DEBUG("D-Bus: Now listening for ProfileUpdate signals on interface '%s'\n", T2_DBUS_EVENT_INTERFACE_NAME); + EVENT_DEBUG("Now listening for ProfileUpdate signals on interface '%s'\n", T2_DBUS_EVENT_INTERFACE_NAME); // Start D-Bus event loop thread to process incoming signals if (!dbus_event_thread_running) @@ -1268,7 +1262,6 @@ static bool isCachingRequired( ) dbus_event_thread_running = true; if (pthread_create(&dbus_event_thread, NULL, dbus_event_loop_thread, NULL) == 0) { - EVENT_DEBUG("D-Bus: Event loop thread created successfully\n"); pthread_detach(dbus_event_thread); } else From 6c4202c7373a10a8e1b4c8a19bb50fcb678f9c53 Mon Sep 17 00:00:00 2001 From: Muhammed rafi c Date: Thu, 29 Jan 2026 18:07:21 +0000 Subject: [PATCH 19/23] dbus_connection_flush removed --- source/ccspinterface/dbusInterface.c | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/source/ccspinterface/dbusInterface.c b/source/ccspinterface/dbusInterface.c index 1b51780d..e8b6d167 100755 --- a/source/ccspinterface/dbusInterface.c +++ b/source/ccspinterface/dbusInterface.c @@ -109,7 +109,7 @@ static DBusHandlerResult handle_get_operational_status(DBusConnection *connectio } dbus_message_unref(reply); - dbus_connection_flush(connection); + //dbus_connection_flush(connection); return DBUS_HANDLER_RESULT_HANDLED; } @@ -153,7 +153,7 @@ static DBusHandlerResult handle_send_t2_event(DBusConnection *connection, DBusMe T2Debug("SendT2Event: Reply sent successfully\n"); dbus_message_unref(reply); - dbus_connection_flush(connection); + //dbus_connection_flush(connection); return DBUS_HANDLER_RESULT_HANDLED; } @@ -182,7 +182,7 @@ static DBusHandlerResult handle_get_marker_list(DBusConnection *connection, DBus "Marker list callback not initialized"); if (reply) { dbus_connection_send(connection, reply, NULL); - dbus_connection_flush(connection); + //dbus_connection_flush(connection); dbus_message_unref(reply); } } @@ -225,7 +225,7 @@ static DBusHandlerResult handle_get_marker_list(DBusConnection *connection, DBus return DBUS_HANDLER_RESULT_NEED_MEMORY; } - dbus_connection_flush(connection); + //dbus_connection_flush(connection); T2Debug("GetMarkerList: Reply sent successfully\n"); dbus_message_unref(reply); } From d15e6257383b139e6ca7c1563bb5b49f3b5218c5 Mon Sep 17 00:00:00 2001 From: Muhammed rafi c Date: Fri, 30 Jan 2026 05:52:32 +0000 Subject: [PATCH 20/23] sendEvent with return --- source/ccspinterface/dbusInterface.c | 17 ++++++- .../commonlib/telemetry_busmessage_sender.c | 45 +++++++++++++++---- 2 files changed, 52 insertions(+), 10 deletions(-) diff --git a/source/ccspinterface/dbusInterface.c b/source/ccspinterface/dbusInterface.c index e8b6d167..cfb30bf8 100755 --- a/source/ccspinterface/dbusInterface.c +++ b/source/ccspinterface/dbusInterface.c @@ -123,6 +123,7 @@ static DBusHandlerResult handle_send_t2_event(DBusConnection *connection, DBusMe const char* marker_name = NULL; const char* data = NULL; + dbus_bool_t success = FALSE; if (!dbus_message_get_args(message, &error, DBUS_TYPE_STRING, &marker_name, @@ -136,22 +137,34 @@ static DBusHandlerResult handle_send_t2_event(DBusConnection *connection, DBusMe if (marker_name && data && eventCallBack) { T2Info("Received event: name=%s, value=%s\n", marker_name, data); eventCallBack(strdup(marker_name), strdup(data)); + success = TRUE; + } else { + T2Error("Failed to process event - invalid parameters or callback not registered\n"); + success = FALSE; } - /* Create empty reply (method returns void) */ + /* Create reply with success status */ DBusMessage *reply = dbus_message_new_method_return(message); if (!reply) { T2Error("Failed to create reply message\n"); return DBUS_HANDLER_RESULT_NEED_MEMORY; } + if (!dbus_message_append_args(reply, + DBUS_TYPE_BOOLEAN, &success, + DBUS_TYPE_INVALID)) { + T2Error("Failed to append reply arguments\n"); + dbus_message_unref(reply); + return DBUS_HANDLER_RESULT_NEED_MEMORY; + } + if (!dbus_connection_send(connection, reply, NULL)) { T2Error("Failed to send reply\n"); dbus_message_unref(reply); return DBUS_HANDLER_RESULT_NEED_MEMORY; } - T2Debug("SendT2Event: Reply sent successfully\n"); + T2Debug("SendT2Event: Reply sent successfully with status=%s\n", success ? "true" : "false"); dbus_message_unref(reply); //dbus_connection_flush(connection); diff --git a/source/commonlib/telemetry_busmessage_sender.c b/source/commonlib/telemetry_busmessage_sender.c index 58fc3b99..6fbd5c67 100644 --- a/source/commonlib/telemetry_busmessage_sender.c +++ b/source/commonlib/telemetry_busmessage_sender.c @@ -783,6 +783,7 @@ int filtered_event_send(const char* data, const char *markerName) // D-Bus method call to send event DBusMessage *msg = NULL; + DBusMessage *reply = NULL; DBusError error; dbus_error_init(&error); @@ -808,20 +809,48 @@ int filtered_event_send(const char* data, const char *markerName) } else { - // Send method call without waiting for reply - if (!dbus_connection_send((DBusConnection*)bus_handle, msg, NULL)) + // Send method call and wait for reply with timeout (1000ms) + reply = dbus_connection_send_with_reply_and_block((DBusConnection*)bus_handle, msg, 1000, &error); + dbus_message_unref(msg); + + if (dbus_error_is_set(&error)) + { + EVENT_ERROR("D-Bus method call failed: %s\n", error.message); + dbus_error_free(&error); + status = -1; + } + else if (!reply) { - EVENT_ERROR("Failed to send D-Bus method call\n"); + EVENT_ERROR("No reply received from SendT2Event\n"); status = -1; } else { - // Flush the connection to ensure message is actually sent - //dbus_connection_flush((DBusConnection*)bus_handle); - EVENT_DEBUG("call sent for event marker [%s] with data [%s]\n", markerName, data); - status = 0; + // Parse boolean success status from reply + dbus_bool_t success = FALSE; + if (dbus_message_get_args(reply, &error, + DBUS_TYPE_BOOLEAN, &success, + DBUS_TYPE_INVALID)) + { + if (success) + { + EVENT_DEBUG("SendT2Event succeeded for marker [%s] with data [%s]\n", markerName, data); + status = 0; + } + else + { + EVENT_ERROR("SendT2Event returned failure for marker [%s]\n", markerName); + status = -1; + } + } + else + { + EVENT_ERROR("Failed to parse reply: %s\n", error.message); + dbus_error_free(&error); + status = -1; + } + dbus_message_unref(reply); } - dbus_message_unref(msg); } } } From 3f8f32f5d31fcb60ef9da72c2151ef449eba18a9 Mon Sep 17 00:00:00 2001 From: Muhammed rafi c Date: Fri, 30 Jan 2026 08:45:58 +0000 Subject: [PATCH 21/23] block timeout changed --- source/ccspinterface/dbusInterface.c | 4 ++-- source/commonlib/telemetry_busmessage_sender.c | 13 ++++--------- 2 files changed, 6 insertions(+), 11 deletions(-) diff --git a/source/ccspinterface/dbusInterface.c b/source/ccspinterface/dbusInterface.c index cfb30bf8..41513472 100755 --- a/source/ccspinterface/dbusInterface.c +++ b/source/ccspinterface/dbusInterface.c @@ -285,8 +285,8 @@ static void* dbusListenerThreadFunc(void *arg) { T2Debug("%s ++in\n", __FUNCTION__); while (!stopListenerThread && t2dbus_handle.connection) { - dbus_connection_read_write_dispatch(t2dbus_handle.connection, 100); - usleep(1000); + dbus_connection_read_write_dispatch(t2dbus_handle.connection, 0); + usleep(1000); // Sleep for 1ms to avoid busy-waiting } T2Debug("%s --out\n", __FUNCTION__); return NULL; diff --git a/source/commonlib/telemetry_busmessage_sender.c b/source/commonlib/telemetry_busmessage_sender.c index 6fbd5c67..5c520117 100644 --- a/source/commonlib/telemetry_busmessage_sender.c +++ b/source/commonlib/telemetry_busmessage_sender.c @@ -809,7 +809,7 @@ int filtered_event_send(const char* data, const char *markerName) } else { - // Send method call and wait for reply with timeout (1000ms) + // Send method call and wait for reply with timeout (1000 ms) reply = dbus_connection_send_with_reply_and_block((DBusConnection*)bus_handle, msg, 1000, &error); dbus_message_unref(msg); @@ -1134,7 +1134,7 @@ static void* dbus_event_loop_thread(void *arg) { (void)arg; - if (!signal_bus_handle) + if (!signal_bus_handle || !bus_handle) { EVENT_ERROR("Signal bus handle is NULL\n"); return NULL; @@ -1146,13 +1146,8 @@ static void* dbus_event_loop_thread(void *arg) { // Process signal connection (for ProfileUpdate signals) dbus_connection_read_write_dispatch((DBusConnection*)signal_bus_handle, 0); - - // Process method call connection (flush outgoing SendT2Event messages) - if (bus_handle) - { - dbus_connection_read_write_dispatch((DBusConnection*)bus_handle, 0); - } - + dbus_connection_read_write_dispatch((DBusConnection*)bus_handle, 0); + // Small sleep to avoid busy-waiting usleep(100000); // 100ms } From 318c40f694e2f923797838da4a7d066cb4c222c2 Mon Sep 17 00:00:00 2001 From: Muhammed rafi c Date: Tue, 3 Feb 2026 10:32:22 +0000 Subject: [PATCH 22/23] spnning time out changed --- source/ccspinterface/dbusInterface.c | 2 +- source/commonlib/telemetry_busmessage_sender.c | 14 +++++++------- 2 files changed, 8 insertions(+), 8 deletions(-) diff --git a/source/ccspinterface/dbusInterface.c b/source/ccspinterface/dbusInterface.c index 41513472..138e61c2 100755 --- a/source/ccspinterface/dbusInterface.c +++ b/source/ccspinterface/dbusInterface.c @@ -286,7 +286,7 @@ static void* dbusListenerThreadFunc(void *arg) { while (!stopListenerThread && t2dbus_handle.connection) { dbus_connection_read_write_dispatch(t2dbus_handle.connection, 0); - usleep(1000); // Sleep for 1ms to avoid busy-waiting + usleep(1); // Sleep for 1us to avoid busy-waiting } T2Debug("%s --out\n", __FUNCTION__); return NULL; diff --git a/source/commonlib/telemetry_busmessage_sender.c b/source/commonlib/telemetry_busmessage_sender.c index 5c520117..a9df1925 100644 --- a/source/commonlib/telemetry_busmessage_sender.c +++ b/source/commonlib/telemetry_busmessage_sender.c @@ -331,9 +331,9 @@ static T2ERROR dbus_getGetOperationalStatus(const char* paramName, uint32_t* val return T2ERROR_FAILURE; } - // Timeout: 1000ms - GetOperationalStatus should respond quickly + // Timeout: 10ms - GetOperationalStatus should respond quickly // This prevents hanging if server is down/unresponsive - reply = dbus_connection_send_with_reply_and_block((DBusConnection*)bus_handle, msg, 1000, &error); + reply = dbus_connection_send_with_reply_and_block((DBusConnection*)bus_handle, msg, 10, &error); dbus_message_unref(msg); if (dbus_error_is_set(&error)) @@ -809,8 +809,8 @@ int filtered_event_send(const char* data, const char *markerName) } else { - // Send method call and wait for reply with timeout (1000 ms) - reply = dbus_connection_send_with_reply_and_block((DBusConnection*)bus_handle, msg, 1000, &error); + // Send method call and wait for reply with timeout (10 ms) + reply = dbus_connection_send_with_reply_and_block((DBusConnection*)bus_handle, msg, 10`, &error); dbus_message_unref(msg); if (dbus_error_is_set(&error)) @@ -1017,8 +1017,8 @@ static T2ERROR doPopulateEventMarkerList( ) return T2ERROR_FAILURE; } // TODO : check markers list size and set timeout accordingly - // Timeout: 500ms - reply = dbus_connection_send_with_reply_and_block((DBusConnection*)bus_handle, msg, 500, &error); + // Timeout: 10ms + reply = dbus_connection_send_with_reply_and_block((DBusConnection*)bus_handle, msg, 10, &error); dbus_message_unref(msg); if (dbus_error_is_set(&error)) @@ -1149,7 +1149,7 @@ static void* dbus_event_loop_thread(void *arg) dbus_connection_read_write_dispatch((DBusConnection*)bus_handle, 0); // Small sleep to avoid busy-waiting - usleep(100000); // 100ms + usleep(1); // 1us } EVENT_DEBUG("D-Bus: Event loop thread exiting\n"); From 837c4ab02b0a6d0062453f0c8b001105d98bcfd1 Mon Sep 17 00:00:00 2001 From: Muhammed rafi c Date: Tue, 3 Feb 2026 11:04:42 +0000 Subject: [PATCH 23/23] Error fix --- source/commonlib/telemetry_busmessage_sender.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/source/commonlib/telemetry_busmessage_sender.c b/source/commonlib/telemetry_busmessage_sender.c index a9df1925..2dad3ef8 100644 --- a/source/commonlib/telemetry_busmessage_sender.c +++ b/source/commonlib/telemetry_busmessage_sender.c @@ -810,7 +810,7 @@ int filtered_event_send(const char* data, const char *markerName) else { // Send method call and wait for reply with timeout (10 ms) - reply = dbus_connection_send_with_reply_and_block((DBusConnection*)bus_handle, msg, 10`, &error); + reply = dbus_connection_send_with_reply_and_block((DBusConnection*)bus_handle, msg, 10, &error); dbus_message_unref(msg); if (dbus_error_is_set(&error))