问题描述
我有一个结构IoT_Publish_Message_Params,需要准备该结构才能在AWS IoT上准备发布。当我将字符串作为有效负载传递时,下面的代码片段可以完全正常工作。
/**
* @brief Publish Message Parameters Type
*
* Defines a type for MQTT Publish messages. Used for both incoming and out going messages
*
*/
typedef struct {
QoS qos; ///< Message Quality of Service
uint8_t isRetained; ///< Retained messages are \b NOT supported by the AWS IoT Service at the time of this SDK release.
uint8_t isDup; ///< Is this message a duplicate QoS > 0 message? Handled automatically by the MQTT client.
uint16_t id; ///< Message sequence identifier. Handled automatically by the MQTT client.
void *payload; ///< Pointer to MQTT message payload (bytes).
size_t payloadLen; ///< Length of MQTT payload.
} IoT_Publish_Message_Params;
IoT_Publish_Message_Params paramsQOS0;
sprintf(cPayload,"%s : %d ","Hello from HOME!!",i);
paramsQOS0.qos = QOS0;
paramsQOS0.payload = (void *) cPayload;
paramsQOS0.isRetained = 0;
paramsQOS0.payloadLen = strlen(cPayload);
rc = aws_iot_mqtt_publish(&client,TOPIC,TOPIC_LEN,¶msQOS0);
现在,我想发送实际的JSON有效负载,但我不确定如何做到这一点。我尝试使用cJSON创建JSON对象:
cJSON *root,*fmt;
root=cJSON_CreateObject();
paramsQOS0.payload = (void *) root
cJSON_AddItemToObject(root,"response",fmt=cJSON_CreateObject());
cJSON_AddNumberToObject(fmt,"hello",123);
cJSON_AddNumberToObject(fmt,"bye",321);
但是,我的问题是,我如何通过IoT_Publish_Message_Params.payloadLen传递?以及如何将json对象传递给IoT_Publish_Message_Params.payload?
解决方法
如我所见,您有两个选择。将JSON作为字符串或原始字节发送。
如果您想将其作为字符串发送(例如{"CarType":"BMW","carID":"bmw123"}
),则希望将其转换为字符串。找到了一些代码here。
char* str = cJSON_Print(root);
paramsQOS0.payload = (void *) str;
paramsQOS0.payloadLen = strlen(str);
但是,将其作为原始字节发送会更加有效。为此,您将需要一个指向对象开始的指针以及对象的大小(以字节为单位)。快速扫描GitHub Page,我发现cJSON_GetArraySize
显然返回了对象的大小。
然后它应该看起来像这样:
paramsQOS0.payload = (void *) root;
paramsQOS0.payloadLen = cJSON_GetArraySize(root); // Not sure about this one
免责声明,我没有使用cJSON,也没有测试代码。我正在尝试向您显示方向。
, IoT_Publish_Message_Params
具有payload
和payloadLen
成员,因此您可以提供任何有效的内存和要发送的字节长度。在第一个示例中,您提供了一个静态分配的字符串及其长度。
JSON是基于字符串的编码协议,因此payload
将是char
指针,并且payloadLen
可以使用strlen
进行计算。
cJSON_Print
返回对象的json字符串,使用其返回的指针并将其分配给payload
。
请阅读cJSON API documentation的使用方法。下面是如何使用修改代码来发送JSON字符串的方法。
IoT_Publish_Message_Params paramsQOS0;
char *json_str;
/* create a json message */
cJSON *root,*response;
root = cJSON_CreateObject();
response = cJSON_CreateObject();
cJSON_AddItemToObject(root,"response",response);
cJSON_AddNumberToObject(response,"hello",123);
cJSON_AddNumberToObject(response,"bye",321);
json_str = cJSON_Print(root);
if (json_str != NULL)
{
paramsQOS0.qos = QOS0;
paramsQOS0.isRetained = 0;
paramsQOS0.payload = json_str;
paramsQOS0.payloadLen = strlen(json_str);
rc = aws_iot_mqtt_publish(&client,TOPIC,TOPIC_LEN,¶msQOS0);
free(json_str);
}
cJSON_Delete(root);