From febcfefd1941f02ff3dd868d31913d25138373b2 Mon Sep 17 00:00:00 2001 From: WMnologo <47595794+WMnologo@users.noreply.github.com> Date: Sat, 8 Mar 2025 02:10:00 +0800 Subject: [PATCH] =?UTF-8?q?=E4=BF=AE=E6=94=B9=E4=BA=86protocol.cc=E6=96=87?= =?UTF-8?q?=E4=BB=B6=E4=B8=AD=E7=9A=84SendIotDescriptors=E6=96=B9=E6=B3=95?= =?UTF-8?q?=EF=BC=8C=E5=AE=9E=E7=8E=B0=E5=B0=86=E5=BE=85=E5=8F=91=E9=80=81?= =?UTF-8?q?=E7=9A=84=E6=B6=88=E6=81=AF=E6=8B=86=E5=88=86=E5=90=8E=E5=8F=91?= =?UTF-8?q?=E9=80=81=EF=BC=8C=E4=BB=A5=E8=A7=A3=E5=86=B34g=E6=A8=A1?= =?UTF-8?q?=E5=9D=97=E5=9C=A8mqtt=E5=8F=91=E5=B8=83=E6=B6=88=E6=81=AF?= =?UTF-8?q?=E8=BF=87=E9=95=BF=E6=97=B6=E5=AF=BC=E8=87=B4=E7=9A=84=E7=BD=91?= =?UTF-8?q?=E7=BB=9C=E5=BC=82=E5=B8=B8=E7=9A=84=E9=97=AE=E9=A2=98=20(#302)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- main/protocols/protocol.cc | 43 ++++++++++++++++++++++++++++++++++++-- 1 file changed, 41 insertions(+), 2 deletions(-) diff --git a/main/protocols/protocol.cc b/main/protocols/protocol.cc index 999a29ea..3672559c 100644 --- a/main/protocols/protocol.cc +++ b/main/protocols/protocol.cc @@ -66,8 +66,47 @@ void Protocol::SendStopListening() { } void Protocol::SendIotDescriptors(const std::string& descriptors) { - std::string message = "{\"session_id\":\"" + session_id_ + "\",\"type\":\"iot\",\"descriptors\":" + descriptors + "}"; - SendText(message); + cJSON* root = cJSON_Parse(descriptors.c_str()); + if (root == nullptr) { + ESP_LOGE(TAG, "Failed to parse IoT descriptors: %s", descriptors.c_str()); + return; + } + + if (!cJSON_IsArray(root)) { + ESP_LOGE(TAG, "IoT descriptors should be an array"); + cJSON_Delete(root); + return; + } + + int arraySize = cJSON_GetArraySize(root); + for (int i = 0; i < arraySize; ++i) { + cJSON* descriptor = cJSON_GetArrayItem(root, i); + if (descriptor == nullptr) { + ESP_LOGE(TAG, "Failed to get IoT descriptor at index %d", i); + continue; + } + + cJSON* messageRoot = cJSON_CreateObject(); + cJSON_AddStringToObject(messageRoot, "session_id", session_id_.c_str()); + cJSON_AddStringToObject(messageRoot, "type", "iot"); + + cJSON* descriptorArray = cJSON_CreateArray(); + cJSON_AddItemToArray(descriptorArray, cJSON_Duplicate(descriptor, 1)); + cJSON_AddItemToObject(messageRoot, "descriptors", descriptorArray); + + char* message = cJSON_Print(messageRoot); + if (message == nullptr) { + ESP_LOGE(TAG, "Failed to print JSON message for IoT descriptor at index %d", i); + cJSON_Delete(messageRoot); + continue; + } + + SendText(std::string(message)); + cJSON_free(message); + cJSON_Delete(messageRoot); + } + + cJSON_Delete(root); } void Protocol::SendIotStates(const std::string& states) {