update qcloud sdk

1. iot-hub sdk update to 3.2.0
2. iot-explorer update to 3.1.1
This commit is contained in:
daishengdong
2020-05-07 11:11:04 +08:00
parent c8e39739d3
commit 3e631cd96a
594 changed files with 47287 additions and 44165 deletions

View File

@@ -28,51 +28,51 @@
#include "data_template_client_json.h"
#include "qcloud_iot_export_data_template.h"
//Action Subscribe
static int _parse_action_input(DeviceAction *pAction, char *pInput)
{
int i;
char *temp;
DeviceProperty *pActionInput = pAction->pInput;
//Action Subscribe
static int _parse_action_input(DeviceAction *pAction, char *pInput)
{
int i;
char *temp;
DeviceProperty *pActionInput = pAction->pInput;
//check and copy
for (i = 0; i < pAction->input_num; i++) {
if (JSTRING == pActionInput[i].type) {
pActionInput[i].data = LITE_json_value_of(pActionInput[i].key, pInput);
if(NULL == pActionInput[i].data) {
Log_e("action input data [%s] not found!", pActionInput[i].key);
return -1;
}
} else {
temp = LITE_json_value_of(pActionInput[i].key, pInput);
if(NULL == temp) {
Log_e("action input data [%s] not found!", pActionInput[i].key);
return -1;
}
if(JINT32 == pActionInput[i].type) {
if (sscanf(temp, "%" SCNi32, (int32_t *)pActionInput[i].data) != 1) {
HAL_Free(temp);
Log_e("parse code failed, errCode: %d", QCLOUD_ERR_JSON_PARSE);
return -1;
}
} else if( JFLOAT == pActionInput[i].type) {
if (sscanf(temp, "%f", (float *)pActionInput[i].data) != 1) {
HAL_Free(temp);
Log_e("parse code failed, errCode: %d", QCLOUD_ERR_JSON_PARSE);
return -1;
}
} else if( JUINT32 == pActionInput[i].type) {
if (sscanf(temp, "%" SCNu32, (uint32_t *) pActionInput[i].data) != 1) {
HAL_Free(temp);
Log_e("parse code failed, errCode: %d", QCLOUD_ERR_JSON_PARSE);
return -1;
}
}
HAL_Free(temp);
}
}
//check and copy
for (i = 0; i < pAction->input_num; i++) {
if (JSTRING == pActionInput[i].type) {
pActionInput[i].data = LITE_json_value_of(pActionInput[i].key, pInput);
if (NULL == pActionInput[i].data) {
Log_e("action input data [%s] not found!", pActionInput[i].key);
return -1;
}
} else {
temp = LITE_json_value_of(pActionInput[i].key, pInput);
if (NULL == temp) {
Log_e("action input data [%s] not found!", pActionInput[i].key);
return -1;
}
if (JINT32 == pActionInput[i].type) {
if (sscanf(temp, "%" SCNi32, (int32_t *)pActionInput[i].data) != 1) {
HAL_Free(temp);
Log_e("parse code failed, errCode: %d", QCLOUD_ERR_JSON_PARSE);
return -1;
}
} else if ( JFLOAT == pActionInput[i].type) {
if (sscanf(temp, "%f", (float *)pActionInput[i].data) != 1) {
HAL_Free(temp);
Log_e("parse code failed, errCode: %d", QCLOUD_ERR_JSON_PARSE);
return -1;
}
} else if ( JUINT32 == pActionInput[i].type) {
if (sscanf(temp, "%" SCNu32, (uint32_t *) pActionInput[i].data) != 1) {
HAL_Free(temp);
Log_e("parse code failed, errCode: %d", QCLOUD_ERR_JSON_PARSE);
return -1;
}
}
HAL_Free(temp);
}
}
return 0;
return 0;
}
static void _handle_aciton(Qcloud_IoT_Template *pTemplate, List *list, const char *pClientToken, const char *pActionId, uint32_t timestamp, char *pInput)
@@ -100,18 +100,18 @@ static void _handle_aciton(Qcloud_IoT_Template *pTemplate, List *list, const cha
Log_e("node's value is invalid!");
continue;
}
ActionHandler *pActionHandle = (ActionHandler *)node->val;
// check action id and call callback
if(0 == strcmp(pActionId,((DeviceAction*)pActionHandle->action)->pActionId)){
if(NULL != pActionHandle->callback) {
if(!_parse_action_input(pActionHandle->action, pInput)) {
((DeviceAction*)pActionHandle->action)->timestamp = timestamp;
pActionHandle->callback(pTemplate, pClientToken, pActionHandle->action);
}
}
}
ActionHandler *pActionHandle = (ActionHandler *)node->val;
// check action id and call callback
if (0 == strcmp(pActionId, ((DeviceAction*)pActionHandle->action)->pActionId)) {
if (NULL != pActionHandle->callback) {
if (!_parse_action_input(pActionHandle->action, pInput)) {
((DeviceAction*)pActionHandle->action)->timestamp = timestamp;
pActionHandle->callback(pTemplate, pClientToken, pActionHandle->action);
}
}
}
}
list_iterator_destroy(iter);
}
@@ -119,93 +119,92 @@ static void _handle_aciton(Qcloud_IoT_Template *pTemplate, List *list, const cha
IOT_FUNC_EXIT;
}
static void _on_action_handle_callback(void *pClient, MQTTMessage *message, void *pUserData)
static void _on_action_handle_callback(void *pClient, MQTTMessage *message, void *pUserData)
{
POINTER_SANITY_CHECK_RTN(message);
Qcloud_IoT_Client *mqtt_client = (Qcloud_IoT_Client *)pClient;
Qcloud_IoT_Template *template_client = (Qcloud_IoT_Template*)mqtt_client->event_handle.context;
POINTER_SANITY_CHECK_RTN(message);
// Qcloud_IoT_Client *mqtt_client = (Qcloud_IoT_Client *)pClient;
// Qcloud_IoT_Template *template_client = (Qcloud_IoT_Template*)mqtt_client->event_handle.context;
Qcloud_IoT_Template *template_client = (Qcloud_IoT_Template *)pUserData;
char *type_str = NULL;
char *type_str = NULL;
char* client_token = NULL;
char* action_id = NULL;
char *pInput = NULL;
int timestamp = 0;
Log_d("recv:%.*s",(int) message->payload_len, (char *) message->payload);
char *pInput = NULL;
int timestamp = 0;
// prase_method
if (!parse_template_method_type((char *) message->payload, &type_str))
{
Log_d("recv:%.*s", (int) message->payload_len, (char *) message->payload);
// prase_method
if (!parse_template_method_type((char *) message->payload, &type_str)) {
Log_e("Fail to parse method!");
goto EXIT;
}
if (strcmp(type_str, CALL_ACTION)) {
goto EXIT;
}
goto EXIT;
}
// prase client Token
// prase client Token
if (!parse_client_token((char *) message->payload, &client_token)) {
Log_e("fail to parse client token!");
goto EXIT;
}
// prase action ID
if (!parse_action_id((char *) message->payload, &action_id)) {
// prase action ID
if (!parse_action_id((char *) message->payload, &action_id)) {
Log_e("fail to parse action id!");
goto EXIT;
}
// prase timestamp
if (!parse_time_stamp((char *) message->payload, &timestamp)) {
// prase timestamp
if (!parse_time_stamp((char *) message->payload, &timestamp)) {
Log_e("fail to parse timestamp!");
goto EXIT;
}
// prase action input
if (!parse_action_input((char *) message->payload, &pInput)) {
// prase action input
if (!parse_action_input((char *) message->payload, &pInput)) {
Log_e("fail to parse action input!");
goto EXIT;
}
}
//find action ID in register list and call handle
if (template_client != NULL)
//find action ID in register list and call handle
if (template_client != NULL)
_handle_aciton(template_client, template_client->inner_data.action_handle_list, client_token, action_id, timestamp, pInput);
EXIT:
HAL_Free(type_str);
HAL_Free(client_token);
HAL_Free(pInput);
return;
HAL_Free(type_str);
HAL_Free(client_token);
HAL_Free(pInput);
return;
}
int IOT_Action_Init(void *c)
{
Qcloud_IoT_Template *pTemplate = (Qcloud_IoT_Template *)c;
static char topic_name[MAX_SIZE_OF_CLOUD_TOPIC] = {0};
Qcloud_IoT_Template *pTemplate = (Qcloud_IoT_Template *)c;
static char topic_name[MAX_SIZE_OF_CLOUD_TOPIC] = {0};
int size = HAL_Snprintf(topic_name, MAX_SIZE_OF_CLOUD_TOPIC, "$thing/down/action/%s/%s", iot_device_info_get()->product_id, iot_device_info_get()->device_name);
if (size < 0 || size > sizeof(topic_name) - 1)
{
Log_e("topic content length not enough! content size:%d buf size:%d", size, (int)sizeof(topic_name));
return QCLOUD_ERR_FAILURE;
}
int size = HAL_Snprintf(topic_name, MAX_SIZE_OF_CLOUD_TOPIC, "$thing/down/action/%s/%s", iot_device_info_get()->product_id, iot_device_info_get()->device_name);
SubscribeParams sub_params = DEFAULT_SUB_PARAMS;
sub_params.on_message_handler = _on_action_handle_callback;
return IOT_MQTT_Subscribe(pTemplate->mqtt, topic_name, &sub_params);
if (size < 0 || size > sizeof(topic_name) - 1) {
Log_e("topic content length not enough! content size:%d buf size:%d", size, (int)sizeof(topic_name));
return QCLOUD_ERR_FAILURE;
}
SubscribeParams sub_params = DEFAULT_SUB_PARAMS;
sub_params.on_message_handler = _on_action_handle_callback;
sub_params.user_data = pTemplate;
return IOT_MQTT_Subscribe(pTemplate->mqtt, topic_name, &sub_params);
}
//Action register
//Action register
static int _add_action_handle_to_template_list(Qcloud_IoT_Template *pTemplate, DeviceAction *pAction, OnActionHandleCallback callback)
{
IOT_FUNC_ENTRY;
ActionHandler *action_handle = (ActionHandler *)HAL_Malloc(sizeof(ActionHandler));
if (NULL == action_handle)
{
if (NULL == action_handle) {
Log_e("run memory malloc is error!");
IOT_FUNC_EXIT_RC(QCLOUD_ERR_FAILURE);
}
@@ -236,14 +235,14 @@ int IOT_Action_Register(void *pTemplate, DeviceAction *pAction, OnActionHandleCa
{
IOT_FUNC_ENTRY;
Qcloud_IoT_Template *ptemplate = (Qcloud_IoT_Template *)pTemplate;
Qcloud_IoT_Template *ptemplate = (Qcloud_IoT_Template *)pTemplate;
POINTER_SANITY_CHECK(pTemplate, QCLOUD_ERR_INVAL);
POINTER_SANITY_CHECK(callback, QCLOUD_ERR_INVAL);
POINTER_SANITY_CHECK(pAction, QCLOUD_ERR_INVAL);
if (_check_action_existence(ptemplate, pAction))
IOT_FUNC_EXIT_RC(QCLOUD_ERR_ACTION_EXIST);
if (_check_action_existence(ptemplate, pAction))
IOT_FUNC_EXIT_RC(QCLOUD_ERR_ACTION_EXIST);
int rc;
HAL_MutexLock(ptemplate->mutex);
@@ -255,9 +254,9 @@ int IOT_Action_Register(void *pTemplate, DeviceAction *pAction, OnActionHandleCa
int IOT_Action_Remove(void *pTemplate, DeviceAction *pAction)
{
Qcloud_IoT_Template *ptemplate = (Qcloud_IoT_Template *)pTemplate;
if (!_check_action_existence(ptemplate, pAction))
IOT_FUNC_EXIT_RC(QCLOUD_ERR_NOT_ACTION_EXIST);
Qcloud_IoT_Template *ptemplate = (Qcloud_IoT_Template *)pTemplate;
if (!_check_action_existence(ptemplate, pAction))
IOT_FUNC_EXIT_RC(QCLOUD_ERR_NOT_ACTION_EXIST);
int rc = QCLOUD_RET_SUCCESS;
@@ -271,130 +270,129 @@ int IOT_Action_Remove(void *pTemplate, DeviceAction *pAction)
list_remove(ptemplate->inner_data.action_handle_list, node);
}
HAL_MutexUnlock(ptemplate->mutex);
return rc;
}
//Action post to server
static int _iot_action_json_init(void *handle, char *jsonBuffer, size_t sizeOfBuffer, const char *pClientToken, DeviceAction *pAction)
static int _iot_action_json_init(void *handle, char *jsonBuffer, size_t sizeOfBuffer, const char *pClientToken, DeviceAction *pAction)
{
POINTER_SANITY_CHECK(jsonBuffer, QCLOUD_ERR_INVAL);
int32_t rc_of_snprintf;
memset(jsonBuffer, 0, sizeOfBuffer);
rc_of_snprintf = HAL_Snprintf(jsonBuffer, sizeOfBuffer, "{\"method\":\"%s\", \"clientToken\":\"%s\", ", REPORT_ACTION, pClientToken);
POINTER_SANITY_CHECK(jsonBuffer, QCLOUD_ERR_INVAL);
int32_t rc_of_snprintf;
memset(jsonBuffer, 0, sizeOfBuffer);
rc_of_snprintf = HAL_Snprintf(jsonBuffer, sizeOfBuffer, "{\"method\":\"%s\", \"clientToken\":\"%s\", ", REPORT_ACTION, pClientToken);
return check_snprintf_return(rc_of_snprintf, sizeOfBuffer);
}
static int _iot_construct_action_json(void *handle, char *jsonBuffer, size_t sizeOfBuffer, const char *pClientToken, DeviceAction *pAction, sReplyPara *replyPara)
{
size_t remain_size = 0;
int32_t rc_of_snprintf = 0;
uint8_t i;
Qcloud_IoT_Template* ptemplate = (Qcloud_IoT_Template *)handle;
POINTER_SANITY_CHECK(ptemplate, QCLOUD_ERR_INVAL);
POINTER_SANITY_CHECK(jsonBuffer, QCLOUD_ERR_INVAL);
POINTER_SANITY_CHECK(pClientToken, QCLOUD_ERR_INVAL);
POINTER_SANITY_CHECK(pAction, QCLOUD_ERR_INVAL);
static int _iot_construct_action_json(void *handle, char *jsonBuffer, size_t sizeOfBuffer, const char *pClientToken, DeviceAction *pAction, sReplyPara *replyPara)
{
size_t remain_size = 0;
int32_t rc_of_snprintf = 0;
uint8_t i;
Qcloud_IoT_Template* ptemplate = (Qcloud_IoT_Template *)handle;
int rc = _iot_action_json_init(ptemplate, jsonBuffer, sizeOfBuffer, pClientToken, pAction);
if (rc != QCLOUD_RET_SUCCESS) {
Log_e("event json init failed: %d", rc);
return rc;
}
POINTER_SANITY_CHECK(ptemplate, QCLOUD_ERR_INVAL);
POINTER_SANITY_CHECK(jsonBuffer, QCLOUD_ERR_INVAL);
POINTER_SANITY_CHECK(pClientToken, QCLOUD_ERR_INVAL);
POINTER_SANITY_CHECK(pAction, QCLOUD_ERR_INVAL);
if ((remain_size = sizeOfBuffer - strlen(jsonBuffer)) <= 1) {
return QCLOUD_ERR_JSON_BUFFER_TOO_SMALL;
}
int rc = _iot_action_json_init(ptemplate, jsonBuffer, sizeOfBuffer, pClientToken, pAction);
if (rc != QCLOUD_RET_SUCCESS) {
Log_e("event json init failed: %d", rc);
return rc;
}
if ((remain_size = sizeOfBuffer - strlen(jsonBuffer)) <= 1) {
return QCLOUD_ERR_JSON_BUFFER_TOO_SMALL;
}
rc_of_snprintf = HAL_Snprintf(jsonBuffer + strlen(jsonBuffer), remain_size, "\"code\":%d, \"status\":\"%s\", \"response\":{",\
replyPara->code, replyPara->status_msg);
rc_of_snprintf = HAL_Snprintf(jsonBuffer + strlen(jsonBuffer), remain_size, "\"code\":%d, \"status\":\"%s\", \"response\":{", \
replyPara->code, replyPara->status_msg);
rc = check_snprintf_return(rc_of_snprintf, remain_size);
if (rc != QCLOUD_RET_SUCCESS) {
return rc;
}
rc = check_snprintf_return(rc_of_snprintf, remain_size);
if (rc != QCLOUD_RET_SUCCESS) {
return rc;
}
if ((remain_size = sizeOfBuffer - strlen(jsonBuffer)) <= 1) {
return QCLOUD_ERR_JSON_BUFFER_TOO_SMALL;
}
if ((remain_size = sizeOfBuffer - strlen(jsonBuffer)) <= 1) {
return QCLOUD_ERR_JSON_BUFFER_TOO_SMALL;
}
DeviceProperty *pJsonNode = pAction->pOutput;
for (i = 0; i < pAction->output_num; i++) {
if (pJsonNode != NULL && pJsonNode->key != NULL) {
rc = template_put_json_node(jsonBuffer, remain_size, pJsonNode->key, pJsonNode->data, pJsonNode->type);
DeviceProperty *pJsonNode = pAction->pOutput;
for (i = 0; i < pAction->output_num; i++) {
if (pJsonNode != NULL && pJsonNode->key != NULL) {
rc = template_put_json_node(jsonBuffer, remain_size, pJsonNode->key, pJsonNode->data, pJsonNode->type);
if (rc != QCLOUD_RET_SUCCESS) {
return rc;
}
} else {
Log_e("%dth/%d null event property data", i, pAction->output_num);
return QCLOUD_ERR_INVAL;
}
pJsonNode++;
}
if ((remain_size = sizeOfBuffer - strlen(jsonBuffer)) <= 1) {
return QCLOUD_ERR_JSON_BUFFER_TOO_SMALL;
}
rc_of_snprintf = HAL_Snprintf(jsonBuffer + strlen(jsonBuffer) - 1, remain_size, "}" );
if (rc != QCLOUD_RET_SUCCESS) {
return rc;
}
} else {
Log_e("%dth/%d null event property data", i, pAction->output_num);
return QCLOUD_ERR_INVAL;
}
pJsonNode++;
}
if ((remain_size = sizeOfBuffer - strlen(jsonBuffer)) <= 1) {
return QCLOUD_ERR_JSON_BUFFER_TOO_SMALL;
}
rc = check_snprintf_return(rc_of_snprintf, remain_size);
if (rc != QCLOUD_RET_SUCCESS) {
return rc;
}
rc_of_snprintf = HAL_Snprintf(jsonBuffer + strlen(jsonBuffer) - 1, remain_size, "}" );
//finish json
if ((remain_size = sizeOfBuffer - strlen(jsonBuffer)) < 1) {
return QCLOUD_ERR_JSON_BUFFER_TOO_SMALL;
}
rc_of_snprintf = HAL_Snprintf(jsonBuffer + strlen(jsonBuffer), remain_size, "}");
return check_snprintf_return(rc_of_snprintf, remain_size);
}
rc = check_snprintf_return(rc_of_snprintf, remain_size);
if (rc != QCLOUD_RET_SUCCESS) {
return rc;
}
//finish json
if ((remain_size = sizeOfBuffer - strlen(jsonBuffer)) < 1) {
return QCLOUD_ERR_JSON_BUFFER_TOO_SMALL;
}
rc_of_snprintf = HAL_Snprintf(jsonBuffer + strlen(jsonBuffer), remain_size, "}");
return check_snprintf_return(rc_of_snprintf, remain_size);
}
static int _publish_action_to_cloud(void *c, char *pJsonDoc)
{
IOT_FUNC_ENTRY;
int rc = QCLOUD_RET_SUCCESS;
char topic[MAX_SIZE_OF_CLOUD_TOPIC] = {0};
Qcloud_IoT_Template *ptemplate = (Qcloud_IoT_Template *)c;
IOT_FUNC_ENTRY;
int rc = QCLOUD_RET_SUCCESS;
char topic[MAX_SIZE_OF_CLOUD_TOPIC] = {0};
Qcloud_IoT_Template *ptemplate = (Qcloud_IoT_Template *)c;
int size = HAL_Snprintf(topic, MAX_SIZE_OF_CLOUD_TOPIC, "$thing/up/action/%s/%s", iot_device_info_get()->product_id, iot_device_info_get()->device_name);
if (size < 0 || size > sizeof(topic) - 1)
{
Log_e("topic content length not enough! content size:%d buf size:%d", size, (int)sizeof(topic));
return QCLOUD_ERR_FAILURE;
}
int size = HAL_Snprintf(topic, MAX_SIZE_OF_CLOUD_TOPIC, "$thing/up/action/%s/%s", iot_device_info_get()->product_id, iot_device_info_get()->device_name);
if (size < 0 || size > sizeof(topic) - 1) {
Log_e("topic content length not enough! content size:%d buf size:%d", size, (int)sizeof(topic));
return QCLOUD_ERR_FAILURE;
}
PublishParams pubParams = DEFAULT_PUB_PARAMS;
pubParams.qos = QOS1;
pubParams.payload_len = strlen(pJsonDoc);
pubParams.payload = (char *) pJsonDoc;
PublishParams pubParams = DEFAULT_PUB_PARAMS;
pubParams.qos = QOS1;
pubParams.payload_len = strlen(pJsonDoc);
pubParams.payload = (char *) pJsonDoc;
rc = IOT_MQTT_Publish(ptemplate->mqtt, topic, &pubParams);
rc = IOT_MQTT_Publish(ptemplate->mqtt, topic, &pubParams);
IOT_FUNC_EXIT_RC(rc);
IOT_FUNC_EXIT_RC(rc);
}
int IOT_ACTION_REPLY(void *pClient, const char *pClientToken, char *pJsonDoc, size_t sizeOfBuffer, DeviceAction *pAction, sReplyPara *replyPara)
int IOT_ACTION_REPLY(void *pClient, const char *pClientToken, char *pJsonDoc, size_t sizeOfBuffer, DeviceAction *pAction, sReplyPara *replyPara)
{
int rc;
rc = _iot_construct_action_json(pClient, pJsonDoc, sizeOfBuffer, pClientToken, pAction, replyPara);
if (rc != QCLOUD_RET_SUCCESS) {
Log_e("construct action json fail, %d",rc);
return rc;
}
rc = _publish_action_to_cloud(pClient, pJsonDoc);
if (rc < 0) {
Log_e("publish action to cloud fail, %d",rc);
}
int rc;
return rc;
rc = _iot_construct_action_json(pClient, pJsonDoc, sizeOfBuffer, pClientToken, pAction, replyPara);
if (rc != QCLOUD_RET_SUCCESS) {
Log_e("construct action json fail, %d", rc);
return rc;
}
rc = _publish_action_to_cloud(pClient, pJsonDoc);
if (rc < 0) {
Log_e("publish action to cloud fail, %d", rc);
}
return rc;
}
#endif
#endif

View File

@@ -28,8 +28,7 @@ static int _add_property_handle_to_template_list(Qcloud_IoT_Template *pTemplate,
IOT_FUNC_ENTRY;
PropertyHandler *property_handle = (PropertyHandler *)HAL_Malloc(sizeof(PropertyHandler));
if (NULL == property_handle)
{
if (NULL == property_handle) {
Log_e("run memory malloc is error!");
IOT_FUNC_EXIT_RC(QCLOUD_ERR_FAILURE);
}
@@ -72,7 +71,7 @@ int template_common_remove_property(Qcloud_IoT_Template *ptemplate, DeviceProper
list_remove(ptemplate->inner_data.property_handle_list, node);
}
HAL_MutexUnlock(ptemplate->mutex);
return rc;
}

View File

@@ -29,7 +29,8 @@ extern "C" {
#include "qcloud_iot_export_method.h"
int check_snprintf_return(int32_t returnCode, size_t maxSizeOfWrite) {
int check_snprintf_return(int32_t returnCode, size_t maxSizeOfWrite)
{
if (returnCode >= maxSizeOfWrite) {
return QCLOUD_ERR_JSON_BUFFER_TRUNCATED;
@@ -40,7 +41,8 @@ int check_snprintf_return(int32_t returnCode, size_t maxSizeOfWrite) {
return QCLOUD_RET_SUCCESS;
}
void insert_str(char *pDestStr, char *pSourceStr, int pos) {
void insert_str(char *pDestStr, char *pSourceStr, int pos)
{
int len = strlen(pDestStr);
int nlen = strlen(pSourceStr);
int i;
@@ -55,35 +57,36 @@ void insert_str(char *pDestStr, char *pSourceStr, int pos) {
}
static int _direct_update_value(char *value, DeviceProperty *pProperty) {
static int _direct_update_value(char *value, DeviceProperty *pProperty)
{
int rc = QCLOUD_RET_SUCCESS;
if (pProperty->type == JBOOL) {
rc = LITE_get_boolean(pProperty->data, value);
rc = LITE_get_boolean(pProperty->data, value);
} else if (pProperty->type == JINT32) {
rc = LITE_get_int32(pProperty->data, value);
rc = LITE_get_int32(pProperty->data, value);
} else if (pProperty->type == JINT16) {
rc = LITE_get_int16(pProperty->data, value);
rc = LITE_get_int16(pProperty->data, value);
} else if (pProperty->type == JINT8) {
rc = LITE_get_int8(pProperty->data, value);
rc = LITE_get_int8(pProperty->data, value);
} else if (pProperty->type == JUINT32) {
rc = LITE_get_uint32(pProperty->data, value);
rc = LITE_get_uint32(pProperty->data, value);
} else if (pProperty->type == JUINT16) {
rc = LITE_get_uint16(pProperty->data, value);
rc = LITE_get_uint16(pProperty->data, value);
} else if (pProperty->type == JUINT8) {
rc = LITE_get_uint8(pProperty->data, value);
rc = LITE_get_uint8(pProperty->data, value);
} else if (pProperty->type == JFLOAT) {
rc = LITE_get_float(pProperty->data, value);
rc = LITE_get_float(pProperty->data, value);
} else if (pProperty->type == JDOUBLE) {
rc = LITE_get_double(pProperty->data, value);
}else if(pProperty->type == JSTRING){
rc = LITE_get_string(pProperty->data, value, pProperty->data_buff_len);
}else if(pProperty->type == JOBJECT){
Log_d("Json type wait to be deal,%s",value);
}else{
Log_e("pProperty type unknow,%d",pProperty->type);
}
rc = LITE_get_double(pProperty->data, value);
} else if (pProperty->type == JSTRING) {
rc = LITE_get_string(pProperty->data, value, pProperty->data_buff_len);
} else if (pProperty->type == JOBJECT) {
Log_d("Json type wait to be deal,%s", value);
} else {
Log_e("pProperty type unknow,%d", pProperty->type);
}
return rc;
}
@@ -95,14 +98,16 @@ static int _direct_update_value(char *value, DeviceProperty *pProperty) {
* @param maxSizeOfJsonDocument max size of JSON string
* @return length after adding
*/
static int32_t _add_client_token(char *pJsonDocument, size_t maxSizeOfJsonDocument, uint32_t *tokenNumber) {
static int32_t _add_client_token(char *pJsonDocument, size_t maxSizeOfJsonDocument, uint32_t *tokenNumber)
{
int32_t rc_of_snprintf = HAL_Snprintf(pJsonDocument, maxSizeOfJsonDocument, "%s-%u", iot_device_info_get()->product_id, (*tokenNumber)++);
return rc_of_snprintf;
}
int put_json_node(char *jsonBuffer, size_t sizeOfBuffer, const char *pKey, void *pData, JsonDataType type) {
int put_json_node(char *jsonBuffer, size_t sizeOfBuffer, const char *pKey, void *pData, JsonDataType type)
{
int rc;
int32_t rc_of_snprintf = 0;
@@ -127,35 +132,35 @@ int put_json_node(char *jsonBuffer, size_t sizeOfBuffer, const char *pKey, void
} else {
if (type == JINT32) {
rc_of_snprintf = HAL_Snprintf(jsonBuffer + strlen(jsonBuffer), remain_size, "%"
PRIi32
",", *(int32_t *) (pData));
PRIi32
",", *(int32_t *) (pData));
} else if (type == JINT16) {
rc_of_snprintf = HAL_Snprintf(jsonBuffer + strlen(jsonBuffer), remain_size, "%"
PRIi16
",", *(int16_t *) (pData));
PRIi16
",", *(int16_t *) (pData));
} else if (type == JINT8) {
rc_of_snprintf = HAL_Snprintf(jsonBuffer + strlen(jsonBuffer), remain_size, "%"
PRIi8
",", *(int8_t *) (pData));
PRIi8
",", *(int8_t *) (pData));
} else if (type == JUINT32) {
rc_of_snprintf = HAL_Snprintf(jsonBuffer + strlen(jsonBuffer), remain_size, "%"
PRIu32
",", *(uint32_t *) (pData));
PRIu32
",", *(uint32_t *) (pData));
} else if (type == JUINT16) {
rc_of_snprintf = HAL_Snprintf(jsonBuffer + strlen(jsonBuffer), remain_size, "%"
PRIu16
",", *(uint16_t *) (pData));
PRIu16
",", *(uint16_t *) (pData));
} else if (type == JUINT8) {
rc_of_snprintf = HAL_Snprintf(jsonBuffer + strlen(jsonBuffer), remain_size, "%"
PRIu8
",", *(uint8_t *) (pData));
PRIu8
",", *(uint8_t *) (pData));
} else if (type == JDOUBLE) {
rc_of_snprintf = HAL_Snprintf(jsonBuffer + strlen(jsonBuffer), remain_size, "%f,", *(double *) (pData));
} else if (type == JFLOAT) {
rc_of_snprintf = HAL_Snprintf(jsonBuffer + strlen(jsonBuffer), remain_size, "%f,", *(float *) (pData));
} else if (type == JBOOL) {
} else if (type == JBOOL) {
rc_of_snprintf = HAL_Snprintf(jsonBuffer + strlen(jsonBuffer), remain_size, "%s,",
*(bool *) (pData) ? "true" : "false");
*(bool *) (pData) ? "true" : "false");
} else if (type == JSTRING) {
rc_of_snprintf = HAL_Snprintf(jsonBuffer + strlen(jsonBuffer), remain_size, "\"%s\",", (char *) (pData));
} else if (type == JOBJECT) {
@@ -168,7 +173,8 @@ int put_json_node(char *jsonBuffer, size_t sizeOfBuffer, const char *pKey, void
return rc;
}
int template_put_json_node(char *jsonBuffer, size_t sizeOfBuffer, const char *pKey, void *pData, JsonDataType type) {
int template_put_json_node(char *jsonBuffer, size_t sizeOfBuffer, const char *pKey, void *pData, JsonDataType type)
{
int rc;
int32_t rc_of_snprintf = 0;
@@ -193,35 +199,35 @@ int template_put_json_node(char *jsonBuffer, size_t sizeOfBuffer, const char *pK
} else {
if (type == JINT32) {
rc_of_snprintf = HAL_Snprintf(jsonBuffer + strlen(jsonBuffer), remain_size, "%"
PRIi32
",", *(int32_t *) (pData));
PRIi32
",", *(int32_t *) (pData));
} else if (type == JINT16) {
rc_of_snprintf = HAL_Snprintf(jsonBuffer + strlen(jsonBuffer), remain_size, "%"
PRIi16
",", *(int16_t *) (pData));
PRIi16
",", *(int16_t *) (pData));
} else if (type == JINT8) {
rc_of_snprintf = HAL_Snprintf(jsonBuffer + strlen(jsonBuffer), remain_size, "%"
PRIi8
",", *(int8_t *) (pData));
PRIi8
",", *(int8_t *) (pData));
} else if (type == JUINT32) {
rc_of_snprintf = HAL_Snprintf(jsonBuffer + strlen(jsonBuffer), remain_size, "%"
PRIu32
",", *(uint32_t *) (pData));
PRIu32
",", *(uint32_t *) (pData));
} else if (type == JUINT16) {
rc_of_snprintf = HAL_Snprintf(jsonBuffer + strlen(jsonBuffer), remain_size, "%"
PRIu16
",", *(uint16_t *) (pData));
PRIu16
",", *(uint16_t *) (pData));
} else if (type == JUINT8) {
rc_of_snprintf = HAL_Snprintf(jsonBuffer + strlen(jsonBuffer), remain_size, "%"
PRIu8
",", *(uint8_t *) (pData));
PRIu8
",", *(uint8_t *) (pData));
} else if (type == JDOUBLE) {
rc_of_snprintf = HAL_Snprintf(jsonBuffer + strlen(jsonBuffer), remain_size, "%f,", *(double *) (pData));
} else if (type == JFLOAT) {
rc_of_snprintf = HAL_Snprintf(jsonBuffer + strlen(jsonBuffer), remain_size, "%f,", *(float *) (pData));
} else if (type == JBOOL) {
} else if (type == JBOOL) {
rc_of_snprintf = HAL_Snprintf(jsonBuffer + strlen(jsonBuffer), remain_size, "%u,",
*(bool *) (pData) ? 1 : 0);
*(bool *) (pData) ? 1 : 0);
} else if (type == JSTRING) {
rc_of_snprintf = HAL_Snprintf(jsonBuffer + strlen(jsonBuffer), remain_size, "\"%s\",", (char *) (pData));
} else if (type == JOBJECT) {
@@ -234,106 +240,111 @@ int template_put_json_node(char *jsonBuffer, size_t sizeOfBuffer, const char *pK
return rc;
}
int generate_client_token(char *pStrBuffer, size_t sizeOfBuffer, uint32_t *tokenNumber) {
int generate_client_token(char *pStrBuffer, size_t sizeOfBuffer, uint32_t *tokenNumber)
{
return _add_client_token(pStrBuffer, sizeOfBuffer, tokenNumber);
}
void build_empty_json(uint32_t *tokenNumber, char *pJsonBuffer) {
HAL_Snprintf(pJsonBuffer, MAX_SIZE_OF_JSON_WITH_CLIENT_TOKEN, "{\"clientToken\":\"%s-%u\"}", iot_device_info_get()->product_id, (*tokenNumber)++);
void build_empty_json(uint32_t *tokenNumber, char *pJsonBuffer)
{
HAL_Snprintf(pJsonBuffer, MAX_SIZE_OF_JSON_WITH_CLIENT_TOKEN, "{\"clientToken\":\"%s-%u\"}", iot_device_info_get()->product_id, (*tokenNumber)++);
}
bool parse_client_token(char *pJsonDoc, char **pClientToken) {
*pClientToken = LITE_json_value_of(CLIENT_TOKEN_FIELD, pJsonDoc);
return *pClientToken == NULL ? false : true;
bool parse_client_token(char *pJsonDoc, char **pClientToken)
{
*pClientToken = LITE_json_value_of(CLIENT_TOKEN_FIELD, pJsonDoc);
return *pClientToken == NULL ? false : true;
}
bool parse_action_id(char *pJsonDoc, char **pActionID) {
*pActionID = LITE_json_value_of(ACTION_ID_FIELD, pJsonDoc);
return *pActionID == NULL ? false : true;
bool parse_action_id(char *pJsonDoc, char **pActionID)
{
*pActionID = LITE_json_value_of(ACTION_ID_FIELD, pJsonDoc);
return *pActionID == NULL ? false : true;
}
bool parse_time_stamp(char *pJsonDoc, int32_t *pTimestamp) {
bool parse_time_stamp(char *pJsonDoc, int32_t *pTimestamp)
{
bool ret = false;
bool ret = false;
char *timestamp = LITE_json_value_of(TIME_STAMP_FIELD, pJsonDoc);
if (timestamp == NULL) return false;
char *timestamp = LITE_json_value_of(TIME_STAMP_FIELD, pJsonDoc);
if (timestamp == NULL) return false;
if (sscanf(timestamp, "%" SCNu32, pTimestamp) != 1) {
Log_e("parse code failed, errCode: %d", QCLOUD_ERR_JSON_PARSE);
}
else {
ret = true;
}
if (sscanf(timestamp, "%" SCNu32, pTimestamp) != 1) {
Log_e("parse code failed, errCode: %d", QCLOUD_ERR_JSON_PARSE);
} else {
ret = true;
}
HAL_Free(timestamp);
HAL_Free(timestamp);
return ret;
return ret;
}
bool parse_action_input(char *pJsonDoc, char **pActionInput)
{
*pActionInput = LITE_json_value_of(CMD_CONTROL_PARA, pJsonDoc);
return *pActionInput == NULL ? false : true;
return *pActionInput == NULL ? false : true;
}
bool parse_code_return(char *pJsonDoc, int32_t *pCode) {
bool parse_code_return(char *pJsonDoc, int32_t *pCode)
{
bool ret = false;
bool ret = false;
char *code = LITE_json_value_of(REPLY_CODE, pJsonDoc);
if (code == NULL) return false;
char *code = LITE_json_value_of(REPLY_CODE, pJsonDoc);
if (code == NULL) return false;
if (sscanf(code, "%" SCNi32, pCode) != 1) {
Log_e("parse code failed, errCode: %d", QCLOUD_ERR_JSON_PARSE);
}
else {
ret = true;
}
if (sscanf(code, "%" SCNi32, pCode) != 1) {
Log_e("parse code failed, errCode: %d", QCLOUD_ERR_JSON_PARSE);
} else {
ret = true;
}
HAL_Free(code);
HAL_Free(code);
return ret;
return ret;
}
bool parse_status_return(char *pJsonDoc, char **pStatus) {
*pStatus = LITE_json_value_of(REPLY_STATUS, pJsonDoc);
return *pStatus == NULL ? false : true;
bool parse_status_return(char *pJsonDoc, char **pStatus)
{
*pStatus = LITE_json_value_of(REPLY_STATUS, pJsonDoc);
return *pStatus == NULL ? false : true;
}
bool update_value_if_key_match(char *pJsonDoc, DeviceProperty *pProperty) {
bool update_value_if_key_match(char *pJsonDoc, DeviceProperty *pProperty)
{
bool ret = false;
bool ret = false;
char* property_data = LITE_json_value_of(pProperty->key, pJsonDoc);
if ((property_data == NULL) || !(strncmp(property_data, "null", 4))
||!(strncmp(property_data, "NULL", 4))) {
}
else {
_direct_update_value(property_data, pProperty);
ret = true;
HAL_Free(property_data);
}
char* property_data = LITE_json_value_of(pProperty->key, pJsonDoc);
if ((property_data == NULL) || !(strncmp(property_data, "null", 4))
|| !(strncmp(property_data, "NULL", 4))) {
} else {
_direct_update_value(property_data, pProperty);
ret = true;
HAL_Free(property_data);
}
return ret;
return ret;
}
bool parse_template_method_type(char *pJsonDoc, char **pMethod)
{
*pMethod = LITE_json_value_of(METHOD_FIELD, pJsonDoc);
return *pMethod == NULL ? false : true;
*pMethod = LITE_json_value_of(METHOD_FIELD, pJsonDoc);
return *pMethod == NULL ? false : true;
}
bool parse_template_get_control(char *pJsonDoc, char **control)
{
*control = LITE_json_value_of(GET_CONTROL_PARA, pJsonDoc);
return *control == NULL ? false : true;
return *control == NULL ? false : true;
}
bool parse_template_cmd_control(char *pJsonDoc, char **control)
{
*control = LITE_json_value_of(CMD_CONTROL_PARA, pJsonDoc);
return *control == NULL ? false : true;
return *control == NULL ? false : true;
}

View File

@@ -46,8 +46,7 @@ static int _unsubscribe_template_downstream_topic(void* pClient)
char downstream_topic[MAX_SIZE_OF_CLOUD_TOPIC] = {0};
int size = HAL_Snprintf(downstream_topic, MAX_SIZE_OF_CLOUD_TOPIC, "$thing/down/property/%s/%s", iot_device_info_get()->product_id, iot_device_info_get()->device_name);
if (size < 0 || size > MAX_SIZE_OF_CLOUD_TOPIC - 1)
{
if (size < 0 || size > MAX_SIZE_OF_CLOUD_TOPIC - 1) {
Log_e("buf size < topic length!");
IOT_FUNC_EXIT_RC(QCLOUD_ERR_FAILURE);
}
@@ -63,14 +62,13 @@ static int _unsubscribe_template_downstream_topic(void* pClient)
/**
* @brief add request to data_template request wait for reply list
*/
*/
static int _add_request_to_template_list(Qcloud_IoT_Template *pTemplate, const char *pClientToken, RequestParams *pParams)
{
IOT_FUNC_ENTRY;
HAL_MutexLock(pTemplate->mutex);
if (pTemplate->inner_data.reply_list->len >= MAX_APPENDING_REQUEST_AT_ANY_GIVEN_TIME)
{
if (pTemplate->inner_data.reply_list->len >= MAX_APPENDING_REQUEST_AT_ANY_GIVEN_TIME) {
HAL_MutexUnlock(pTemplate->mutex);
IOT_FUNC_EXIT_RC(QCLOUD_ERR_MAX_APPENDING_REQUEST);
}
@@ -112,20 +110,19 @@ static int _add_request_to_template_list(Qcloud_IoT_Template *pTemplate, const c
* @param method method type
* @param pJsonDoc JSON to publish
* @return QCLOUD_RET_SUCCESS for success, or err code for failure
*/
*/
int _publish_to_template_upstream_topic(Qcloud_IoT_Template *pTemplate, Method method, char *pJsonDoc)
{
IOT_FUNC_ENTRY;
int rc = QCLOUD_RET_SUCCESS;
char topic[MAX_SIZE_OF_CLOUD_TOPIC] = {0};
int size;
int size;
size = HAL_Snprintf(topic, MAX_SIZE_OF_CLOUD_TOPIC, "$thing/up/property/%s/%s", iot_device_info_get()->product_id, iot_device_info_get()->device_name);
if (size < 0 || size > MAX_SIZE_OF_CLOUD_TOPIC - 1)
{
size = HAL_Snprintf(topic, MAX_SIZE_OF_CLOUD_TOPIC, "$thing/up/property/%s/%s", iot_device_info_get()->product_id, iot_device_info_get()->device_name);
if (size < 0 || size > MAX_SIZE_OF_CLOUD_TOPIC - 1) {
Log_e("buf size < topic length!");
IOT_FUNC_EXIT_RC(QCLOUD_ERR_FAILURE);
}
@@ -153,25 +150,25 @@ static int _set_template_json_type(char *pJsonDoc, size_t sizeOfBuffer, Method m
POINTER_SANITY_CHECK(pJsonDoc, QCLOUD_ERR_INVAL);
char *method_str = NULL;
switch (method) {
case GET:
method_str = GET_STATUS;
break;
case REPORT:
method_str = REPORT_CMD;
break;
case RINFO:
method_str = INFO_CMD;
break;
case REPLY:
method_str = CONTROL_CMD_REPLY;
break;
case CLEAR:
method_str = CLEAR_CONTROL;
break;
default:
Log_e("unexpected method!");
rc = QCLOUD_ERR_INVAL;
break;
case GET:
method_str = GET_STATUS;
break;
case REPORT:
method_str = REPORT_CMD;
break;
case RINFO:
method_str = INFO_CMD;
break;
case REPLY:
method_str = CONTROL_CMD_REPLY;
break;
case CLEAR:
method_str = CLEAR_CONTROL;
break;
default:
Log_e("unexpected method!");
rc = QCLOUD_ERR_INVAL;
break;
}
if (rc != QCLOUD_RET_SUCCESS)
IOT_FUNC_EXIT_RC(rc);
@@ -242,8 +239,7 @@ static void _handle_template_expired_reply_callback(Qcloud_IoT_Template *pTempla
if (NULL == request)
IOT_FUNC_EXIT;
if (expired(&request->timer))
{
if (expired(&request->timer)) {
if (request->callback != NULL) {
request->callback(pTemplate, request->method, ACK_TIMEOUT, sg_template_cloud_rcv_buf, request);
}
@@ -257,13 +253,13 @@ static void _handle_template_expired_reply_callback(Qcloud_IoT_Template *pTempla
static void _set_control_clientToken(const char *pClientToken)
{
memset(sg_template_clientToken, '\0', MAX_SIZE_OF_CLIENT_TOKEN);
strncpy(sg_template_clientToken, pClientToken, MAX_SIZE_OF_CLIENT_TOKEN);
memset(sg_template_clientToken, '\0', MAX_SIZE_OF_CLIENT_TOKEN);
strncpy(sg_template_clientToken, pClientToken, MAX_SIZE_OF_CLIENT_TOKEN);
}
char * get_control_clientToken(void)
{
return sg_template_clientToken;
return sg_template_clientToken;
}
void qcloud_iot_template_reset(void *pClient)
@@ -277,20 +273,18 @@ void qcloud_iot_template_reset(void *pClient)
_unsubscribe_template_downstream_topic(template_client->mqtt);
if (template_client->inner_data.reply_list)
{
if (template_client->inner_data.reply_list) {
list_destroy(template_client->inner_data.reply_list);
}
if (template_client->inner_data.event_list)
{
if (template_client->inner_data.event_list) {
list_destroy(template_client->inner_data.event_list);
}
}
int qcloud_iot_template_init(Qcloud_IoT_Template *pTemplate)
int qcloud_iot_template_init(Qcloud_IoT_Template *pTemplate)
{
IOT_FUNC_ENTRY;
IOT_FUNC_ENTRY;
POINTER_SANITY_CHECK(pTemplate, QCLOUD_ERR_INVAL);
@@ -299,46 +293,41 @@ int qcloud_iot_template_init(Qcloud_IoT_Template *pTemplate)
IOT_FUNC_EXIT_RC(QCLOUD_ERR_FAILURE);
pTemplate->inner_data.property_handle_list = list_new();
if (pTemplate->inner_data.property_handle_list)
{
if (pTemplate->inner_data.property_handle_list) {
pTemplate->inner_data.property_handle_list->free = HAL_Free;
}
else {
Log_e("no memory to allocate property_handle_list");
IOT_FUNC_EXIT_RC(QCLOUD_ERR_FAILURE);
} else {
Log_e("no memory to allocate property_handle_list");
IOT_FUNC_EXIT_RC(QCLOUD_ERR_FAILURE);
}
pTemplate->inner_data.reply_list = list_new();
if (pTemplate->inner_data.reply_list)
{
pTemplate->inner_data.reply_list->free = HAL_Free;
} else {
Log_e("no memory to allocate reply_list");
IOT_FUNC_EXIT_RC(QCLOUD_ERR_FAILURE);
}
pTemplate->inner_data.event_list = list_new();
if (pTemplate->inner_data.event_list)
{
pTemplate->inner_data.event_list->free = HAL_Free;
} else {
Log_e("no memory to allocate event_list");
IOT_FUNC_EXIT_RC(QCLOUD_ERR_FAILURE);
}
pTemplate->inner_data.reply_list = list_new();
if (pTemplate->inner_data.reply_list) {
pTemplate->inner_data.reply_list->free = HAL_Free;
} else {
Log_e("no memory to allocate reply_list");
IOT_FUNC_EXIT_RC(QCLOUD_ERR_FAILURE);
}
pTemplate->inner_data.action_handle_list = list_new();
if (pTemplate->inner_data.action_handle_list)
{
pTemplate->inner_data.action_handle_list->free = HAL_Free;
} else {
Log_e("no memory to allocate action_handle_list");
IOT_FUNC_EXIT_RC(QCLOUD_ERR_FAILURE);
}
pTemplate->inner_data.event_list = list_new();
if (pTemplate->inner_data.event_list) {
pTemplate->inner_data.event_list->free = HAL_Free;
} else {
Log_e("no memory to allocate event_list");
IOT_FUNC_EXIT_RC(QCLOUD_ERR_FAILURE);
}
IOT_FUNC_EXIT_RC(QCLOUD_RET_SUCCESS);
pTemplate->inner_data.action_handle_list = list_new();
if (pTemplate->inner_data.action_handle_list) {
pTemplate->inner_data.action_handle_list->free = HAL_Free;
} else {
Log_e("no memory to allocate action_handle_list");
IOT_FUNC_EXIT_RC(QCLOUD_ERR_FAILURE);
}
IOT_FUNC_EXIT_RC(QCLOUD_RET_SUCCESS);
}
void handle_template_expired_reply(Qcloud_IoT_Template *pTemplate)
void handle_template_expired_reply(Qcloud_IoT_Template *pTemplate)
{
IOT_FUNC_ENTRY;
@@ -410,11 +399,9 @@ static void _handle_control(Qcloud_IoT_Template *pTemplate, char* control_str)
}
if (property_handle->property != NULL) {
if (update_value_if_key_match(control_str, property_handle->property))
{
if (property_handle->callback != NULL)
{
if (update_value_if_key_match(control_str, property_handle->property)) {
if (property_handle->callback != NULL) {
property_handle->callback(pTemplate, control_str, strlen(control_str), property_handle->property);
}
node = NULL;
@@ -439,42 +426,39 @@ static void _handle_template_reply_callback(Qcloud_IoT_Template *pTemplate, List
if (NULL == request)
IOT_FUNC_EXIT;
if (strcmp(request->client_token, pClientToken) == 0)
{
if (strcmp(request->client_token, pClientToken) == 0) {
ReplyAck status = ACK_NONE;
// check operation success or not according to code field of reply message
int32_t reply_code = 0;
bool parse_success = parse_code_return(sg_template_cloud_rcv_buf, &reply_code);
if (parse_success) {
if (reply_code == 0) {
status = ACK_ACCEPTED;
} else {
status = ACK_REJECTED;
}
if (reply_code == 0) {
status = ACK_ACCEPTED;
} else {
status = ACK_REJECTED;
}
if (strcmp(pType, GET_STATUS_REPLY) == 0 && status == ACK_ACCEPTED)
{
char* control_str = NULL;
if (parse_template_get_control(sg_template_cloud_rcv_buf, &control_str)) {
Log_d("control data from get_status_reply");
_set_control_clientToken(pClientToken);
_handle_control(pTemplate, control_str);
HAL_Free(control_str);
*((ReplyAck *)request->user_context) = ACK_ACCEPTED; //prepare for clear_control
}
}
if (request->callback != NULL) {
request->callback(pTemplate, request->method, status, sg_template_cloud_rcv_buf, request);
}
if (strcmp(pType, GET_STATUS_REPLY) == 0 && status == ACK_ACCEPTED) {
char* control_str = NULL;
if (parse_template_get_control(sg_template_cloud_rcv_buf, &control_str)) {
Log_d("control data from get_status_reply");
_set_control_clientToken(pClientToken);
_handle_control(pTemplate, control_str);
HAL_Free(control_str);
*((ReplyAck *)request->user_context) = ACK_ACCEPTED; //prepare for clear_control
}
}
if (request->callback != NULL) {
request->callback(pTemplate, request->method, status, sg_template_cloud_rcv_buf, request);
}
} else {
Log_e("parse template operation result code failed.");
}
else {
Log_e("parse template operation result code failed.");
}
list_remove(list, *node);
*node = NULL;
@@ -490,8 +474,10 @@ static void _on_template_downstream_topic_handler(void *pClient, MQTTMessage *me
POINTER_SANITY_CHECK_RTN(pClient);
POINTER_SANITY_CHECK_RTN(message);
Qcloud_IoT_Client *mqtt_client = (Qcloud_IoT_Client *)pClient;
Qcloud_IoT_Template *template_client = (Qcloud_IoT_Template*)mqtt_client->event_handle.context;
// Qcloud_IoT_Client *mqtt_client = (Qcloud_IoT_Client *)pClient;
// Qcloud_IoT_Template *template_client = (Qcloud_IoT_Template*)mqtt_client->event_handle.context;
Qcloud_IoT_Template *template_client = (Qcloud_IoT_Template*)pUserdata;
const char *topic = message->ptopic;
size_t topic_len = message->topic_len;
@@ -508,38 +494,37 @@ static void _on_template_downstream_topic_handler(void *pClient, MQTTMessage *me
}
int cloud_rcv_len = min(CLOUD_IOT_JSON_RX_BUF_LEN - 1, message->payload_len);
memset(sg_template_cloud_rcv_buf, 0, sizeof(sg_template_cloud_rcv_buf));
memset(sg_template_cloud_rcv_buf, 0, sizeof(sg_template_cloud_rcv_buf));
memcpy(sg_template_cloud_rcv_buf, message->payload, cloud_rcv_len + 1);
sg_template_cloud_rcv_buf[cloud_rcv_len] = '\0'; // jsmn_parse relies on a string
//Log_d("recv:%s", sg_template_cloud_rcv_buf);
//Log_d("recv:%s", sg_template_cloud_rcv_buf);
//parse the message type from topic $thing/down/property
if (!parse_template_method_type(sg_template_cloud_rcv_buf, &type_str))
{
//parse the message type from topic $thing/down/property
if (!parse_template_method_type(sg_template_cloud_rcv_buf, &type_str)) {
Log_e("Fail to parse method!");
goto End;
}
if (!parse_client_token(sg_template_cloud_rcv_buf, &client_token)) {
Log_e("Fail to parse client token! Json=%s", sg_template_cloud_rcv_buf);
goto End;
Log_e("Fail to parse client token! Json=%s", sg_template_cloud_rcv_buf);
goto End;
}
//handle control message
if (!strcmp(type_str, CONTROL_CMD)) {
HAL_MutexLock(template_client->mutex);
char* control_str = NULL;
if (parse_template_cmd_control(sg_template_cloud_rcv_buf, &control_str)) {
Log_d("control_str:%s", control_str);
_set_control_clientToken(client_token);
_handle_control(template_client, control_str);
HAL_Free(control_str);
}
HAL_MutexUnlock(template_client->mutex);
goto End;
}
//handle control message
if (!strcmp(type_str, CONTROL_CMD)) {
HAL_MutexLock(template_client->mutex);
char* control_str = NULL;
if (parse_template_cmd_control(sg_template_cloud_rcv_buf, &control_str)) {
Log_d("control_str:%s", control_str);
_set_control_clientToken(client_token);
_handle_control(template_client, control_str);
HAL_Free(control_str);
}
HAL_MutexUnlock(template_client->mutex);
goto End;
}
if (template_client != NULL)
_traverse_template_list(template_client, template_client->inner_data.reply_list, client_token, type_str, _handle_template_reply_callback);
@@ -555,16 +540,15 @@ int subscribe_template_downstream_topic(Qcloud_IoT_Template *pTemplate)
IOT_FUNC_ENTRY;
int rc;
int size;
int size;
if (pTemplate->inner_data.downstream_topic == NULL) {
char *downstream_topic = (char *)HAL_Malloc(MAX_SIZE_OF_CLOUD_TOPIC * sizeof(char));
if (downstream_topic == NULL) IOT_FUNC_EXIT_RC(QCLOUD_ERR_FAILURE);
memset(downstream_topic, 0x0, MAX_SIZE_OF_CLOUD_TOPIC);
size = HAL_Snprintf(downstream_topic, MAX_SIZE_OF_CLOUD_TOPIC, "$thing/down/property/%s/%s", iot_device_info_get()->product_id, iot_device_info_get()->device_name);
if (size < 0 || size > MAX_SIZE_OF_CLOUD_TOPIC - 1)
{
size = HAL_Snprintf(downstream_topic, MAX_SIZE_OF_CLOUD_TOPIC, "$thing/down/property/%s/%s", iot_device_info_get()->product_id, iot_device_info_get()->device_name);
if (size < 0 || size > MAX_SIZE_OF_CLOUD_TOPIC - 1) {
Log_e("buf size < topic length!");
HAL_Free(downstream_topic);
IOT_FUNC_EXIT_RC(QCLOUD_ERR_FAILURE);
@@ -575,6 +559,7 @@ int subscribe_template_downstream_topic(Qcloud_IoT_Template *pTemplate)
SubscribeParams subscribe_params = DEFAULT_SUB_PARAMS;
subscribe_params.on_message_handler = _on_template_downstream_topic_handler;
subscribe_params.qos = QOS0;
subscribe_params.user_data = pTemplate;
rc = IOT_MQTT_Subscribe(pTemplate->mqtt, pTemplate->inner_data.downstream_topic, &subscribe_params);
if (rc < 0) {

View File

@@ -13,7 +13,7 @@
*
*/
#ifdef __cplusplus
#ifdef __cplusplus
extern "C" {
#endif
@@ -61,26 +61,26 @@ static void _traverse_event_list(Qcloud_IoT_Template *pTemplate, List *list, con
Log_e("node's value is invalid!");
continue;
}
sEventReply *pReply = (sEventReply *)node->val;
/*timeout check*/
if(eDEAL_EXPIRED == eDealType){
if(expired(&pReply->timer)){
Log_e("eventToken[%s] timeout",pReply->client_token);
list_remove(list, node);
node = NULL;
}
}
/*match event wait for reply by clientToken*/
if((eDEAL_REPLY_CB == eDealType) && (0 == strcmp(pClientToken, pReply->client_token))){
if(NULL != pReply->callback){
pReply->callback(pTemplate, message);
Log_d("eventToken[%s] released",pReply->client_token);
list_remove(list, node);
node = NULL;
}
}
sEventReply *pReply = (sEventReply *)node->val;
/*timeout check*/
if (eDEAL_EXPIRED == eDealType) {
if (expired(&pReply->timer)) {
Log_e("eventToken[%s] timeout", pReply->client_token);
list_remove(list, node);
node = NULL;
}
}
/*match event wait for reply by clientToken*/
if ((eDEAL_REPLY_CB == eDealType) && (0 == strcmp(pClientToken, pReply->client_token))) {
if (NULL != pReply->callback) {
pReply->callback(pTemplate, message);
Log_d("eventToken[%s] released", pReply->client_token);
list_remove(list, node);
node = NULL;
}
}
}
list_iterator_destroy(iter);
@@ -90,44 +90,46 @@ static void _traverse_event_list(Qcloud_IoT_Template *pTemplate, List *list, con
IOT_FUNC_EXIT;
}
static void _on_event_reply_callback(void *pClient, MQTTMessage *message, void *userData)
static void _on_event_reply_callback(void *pClient, MQTTMessage *message, void *userData)
{
POINTER_SANITY_CHECK_RTN(message);
Qcloud_IoT_Client *mqtt_client = (Qcloud_IoT_Client *)pClient;
Qcloud_IoT_Template *template_client = (Qcloud_IoT_Template*)mqtt_client->event_handle.context;
POINTER_SANITY_CHECK_RTN(message);
// Qcloud_IoT_Client *mqtt_client = (Qcloud_IoT_Client *)pClient;
// Qcloud_IoT_Template *template_client = (Qcloud_IoT_Template*)mqtt_client->event_handle.context;
Qcloud_IoT_Template *template_client = (Qcloud_IoT_Template*)userData;
int32_t code;
int32_t code;
char* client_token = NULL;
char* status = NULL;
char* status = NULL;
Log_d("recv:%.*s",(int) message->payload_len, (char *) message->payload);
// parse clientToken from payload
Log_d("recv:%.*s", (int) message->payload_len, (char *) message->payload);
// parse clientToken from payload
if (!parse_client_token((char *) message->payload, &client_token)) {
Log_e("fail to parse client token!");
return;
}
// parse code from payload
if(!parse_code_return((char *) message->payload, &code)){
// parse code from payload
if (!parse_code_return((char *) message->payload, &code)) {
Log_e("fail to parse code");
return;
}
if(!parse_status_return((char *) message->payload, &status)){
// Log_d("no status return");
if (!parse_status_return((char *) message->payload, &status)) {
// Log_d("no status return");
}
Log_d("eventToken:%s code:%d status:%s", client_token, code, status);
Log_d("eventToken:%s code:%d status:%s", client_token, code, status);
if (template_client != NULL)
_traverse_event_list(template_client, template_client->inner_data.event_list, client_token, message, eDEAL_REPLY_CB);
HAL_Free(client_token);
HAL_Free(status);
HAL_Free(status);
return;
return;
}
/**
@@ -138,10 +140,9 @@ static sEventReply * _create_event_add_to_list(Qcloud_IoT_Template *pTemplate, O
IOT_FUNC_ENTRY;
HAL_MutexLock(pTemplate->mutex);
if (pTemplate->inner_data.event_list->len >= MAX_EVENT_WAIT_REPLY)
{
if (pTemplate->inner_data.event_list->len >= MAX_EVENT_WAIT_REPLY) {
HAL_MutexUnlock(pTemplate->mutex);
Log_e("Too many event wait for reply");
Log_e("Too many event wait for reply");
IOT_FUNC_EXIT_RC(NULL);
}
@@ -153,18 +154,18 @@ static sEventReply * _create_event_add_to_list(Qcloud_IoT_Template *pTemplate, O
}
pReply->callback = replyCb;
pReply->user_context = pTemplate;
pReply->user_context = pTemplate;
InitTimer(&(pReply->timer));
countdown(&(pReply->timer), reply_timeout_ms);
HAL_Snprintf(pReply->client_token, EVENT_TOKEN_MAX_LEN, "%s-%u", iot_device_info_get()->product_id, pTemplate->inner_data.token_num++);
HAL_Snprintf(pReply->client_token, EVENT_TOKEN_MAX_LEN, "%s-%u", iot_device_info_get()->product_id, pTemplate->inner_data.token_num++);
ListNode *node = list_node_new(pReply);
if (NULL == node) {
HAL_MutexUnlock(pTemplate->mutex);
Log_e("run list_node_new is error!");
HAL_Free(pReply);
HAL_Free(pReply);
IOT_FUNC_EXIT_RC(NULL);
}
@@ -173,218 +174,217 @@ static sEventReply * _create_event_add_to_list(Qcloud_IoT_Template *pTemplate, O
HAL_MutexUnlock(pTemplate->mutex);
IOT_FUNC_EXIT_RC(pReply);
}
}
static int _iot_event_json_init(void *handle, char *jsonBuffer, size_t sizeOfBuffer, uint8_t event_count, OnEventReplyCallback replyCb, uint32_t reply_timeout_ms)
{
POINTER_SANITY_CHECK(jsonBuffer, QCLOUD_ERR_INVAL);
Qcloud_IoT_Template* ptemplate = (Qcloud_IoT_Template *)handle;
int32_t rc_of_snprintf;
sEventReply *pReply;
pReply = _create_event_add_to_list(ptemplate, replyCb, reply_timeout_ms);
if(!pReply){
Log_e("create event failed");
return QCLOUD_ERR_FAILURE;
}
POINTER_SANITY_CHECK(jsonBuffer, QCLOUD_ERR_INVAL);
memset(jsonBuffer, 0, sizeOfBuffer);
if(event_count > SIGLE_EVENT){
rc_of_snprintf = HAL_Snprintf(jsonBuffer, sizeOfBuffer, "{\"method\":\"%s\", \"clientToken\":\"%s\", ", \
POST_EVENTS, pReply->client_token);
}else{
rc_of_snprintf = HAL_Snprintf(jsonBuffer, sizeOfBuffer, "{\"method\":\"%s\", \"clientToken\":\"%s\", ", \
POST_EVENT, pReply->client_token);
}
Qcloud_IoT_Template* ptemplate = (Qcloud_IoT_Template *)handle;
int32_t rc_of_snprintf;
sEventReply *pReply;
pReply = _create_event_add_to_list(ptemplate, replyCb, reply_timeout_ms);
if (!pReply) {
Log_e("create event failed");
return QCLOUD_ERR_FAILURE;
}
memset(jsonBuffer, 0, sizeOfBuffer);
if (event_count > SIGLE_EVENT) {
rc_of_snprintf = HAL_Snprintf(jsonBuffer, sizeOfBuffer, "{\"method\":\"%s\", \"clientToken\":\"%s\", ", \
POST_EVENTS, pReply->client_token);
} else {
rc_of_snprintf = HAL_Snprintf(jsonBuffer, sizeOfBuffer, "{\"method\":\"%s\", \"clientToken\":\"%s\", ", \
POST_EVENT, pReply->client_token);
}
return check_snprintf_return(rc_of_snprintf, sizeOfBuffer);
}
static int _iot_construct_event_json(void *handle, char *jsonBuffer, size_t sizeOfBuffer,
uint8_t event_count,
sEvent *pEventArry[],
OnEventReplyCallback replyCb,
uint32_t reply_timeout_ms)
{
size_t remain_size = 0;
int32_t rc_of_snprintf = 0;
uint8_t i,j;
Qcloud_IoT_Template* ptemplate = (Qcloud_IoT_Template *)handle;
POINTER_SANITY_CHECK(ptemplate, QCLOUD_ERR_INVAL);
POINTER_SANITY_CHECK(jsonBuffer, QCLOUD_ERR_INVAL);
POINTER_SANITY_CHECK(pEventArry, QCLOUD_ERR_INVAL);
int rc = _iot_event_json_init(ptemplate, jsonBuffer, sizeOfBuffer, event_count, replyCb, reply_timeout_ms);
if (rc != QCLOUD_RET_SUCCESS) {
Log_e("event json init failed: %d", rc);
return rc;
}
//Log_d("event_count:%d, Doc_init:%s",event_count, jsonBuffer);
if ((remain_size = sizeOfBuffer - strlen(jsonBuffer)) <= 1) {
return QCLOUD_ERR_JSON_BUFFER_TOO_SMALL;
}
if(event_count > SIGLE_EVENT){//mutlti event
rc_of_snprintf = HAL_Snprintf(jsonBuffer + strlen(jsonBuffer), remain_size, "\"events\":[");
rc = check_snprintf_return(rc_of_snprintf, remain_size);
if (rc != QCLOUD_RET_SUCCESS) {
return rc;
}
if ((remain_size = sizeOfBuffer - strlen(jsonBuffer)) <= 1) {
return QCLOUD_ERR_JSON_BUFFER_TOO_SMALL;
}
for(i = 0; i < event_count; i++){
sEvent *pEvent = pEventArry[i];
if(NULL == pEvent){
Log_e("%dth/%d null event", i, event_count);
return QCLOUD_ERR_INVAL;
}
if(0 == pEvent->timestamp){ //no accurate UTC time, set 0
rc_of_snprintf = HAL_Snprintf(jsonBuffer + strlen(jsonBuffer), remain_size, "{\"eventId\":\"%s\", \"type\":\"%s\", \"timestamp\":0, \"params\":{",\
pEvent->event_name, pEvent->type);
}else{ // accurate UTC time is second,change to ms
rc_of_snprintf = HAL_Snprintf(jsonBuffer + strlen(jsonBuffer), remain_size, "{\"eventId\":\"%s\", \"type\":\"%s\", \"timestamp\":%u000, \"params\":{",\
pEvent->event_name, pEvent->type, pEvent->timestamp);
}
rc = check_snprintf_return(rc_of_snprintf, remain_size);
if (rc != QCLOUD_RET_SUCCESS) {
return rc;
}
if ((remain_size = sizeOfBuffer - strlen(jsonBuffer)) <= 1) {
return QCLOUD_ERR_JSON_BUFFER_TOO_SMALL;
}
DeviceProperty *pJsonNode = pEvent->pEventData;
for (j = 0; j < pEvent->eventDataNum; j++) {
if (pJsonNode != NULL && pJsonNode->key != NULL) {
rc = template_put_json_node(jsonBuffer, remain_size, pJsonNode->key, pJsonNode->data, pJsonNode->type);
if (rc != QCLOUD_RET_SUCCESS) {
return rc;
}
} else {
Log_e("%dth/%d null event property data", i, pEvent->eventDataNum);
return QCLOUD_ERR_INVAL;
}
pJsonNode++;
}
if ((remain_size = sizeOfBuffer - strlen(jsonBuffer)) <= 1) {
return QCLOUD_ERR_JSON_BUFFER_TOO_SMALL;
}
rc_of_snprintf = HAL_Snprintf(jsonBuffer + strlen(jsonBuffer)-1, remain_size, "}}," );
rc = check_snprintf_return(rc_of_snprintf, remain_size);
if (rc != QCLOUD_RET_SUCCESS) {
return rc;
}
pEvent++;
}
if ((remain_size = sizeOfBuffer - strlen(jsonBuffer)) <= 1) {
return QCLOUD_ERR_JSON_BUFFER_TOO_SMALL;
}
rc_of_snprintf = HAL_Snprintf(jsonBuffer + strlen(jsonBuffer) - 1, remain_size, "]");
rc = check_snprintf_return(rc_of_snprintf, remain_size);
if (rc != QCLOUD_RET_SUCCESS) {
return rc;
}
}else{ //single
sEvent *pEvent = pEventArry[0];
if(0 == pEvent->timestamp){ //no accurate UTC time, set 0
rc_of_snprintf = HAL_Snprintf(jsonBuffer + strlen(jsonBuffer), remain_size, "\"eventId\":\"%s\", \"type\":\"%s\", \"timestamp\":0, \"params\":{",\
pEvent->event_name, pEvent->type);
}else{ // accurate UTC time is second,change to ms
rc_of_snprintf = HAL_Snprintf(jsonBuffer + strlen(jsonBuffer), remain_size, "\"eventId\":\"%s\", \"type\":\"%s\", \"timestamp\":%u000, \"params\":{",\
pEvent->event_name, pEvent->type, pEvent->timestamp);
}
rc = check_snprintf_return(rc_of_snprintf, remain_size);
if (rc != QCLOUD_RET_SUCCESS) {
return rc;
}
if ((remain_size = sizeOfBuffer - strlen(jsonBuffer)) <= 1) {
return QCLOUD_ERR_JSON_BUFFER_TOO_SMALL;
}
DeviceProperty *pJsonNode = pEvent->pEventData;
for (i = 0; i < pEvent->eventDataNum; i++) {
if (pJsonNode != NULL && pJsonNode->key != NULL) {
rc = template_put_json_node(jsonBuffer, remain_size, pJsonNode->key, pJsonNode->data, pJsonNode->type);
if (rc != QCLOUD_RET_SUCCESS) {
return rc;
}
} else {
Log_e("%dth/%d null event property data", i, pEvent->eventDataNum);
return QCLOUD_ERR_INVAL;
}
pJsonNode++;
}
if ((remain_size = sizeOfBuffer - strlen(jsonBuffer)) <= 1) {
return QCLOUD_ERR_JSON_BUFFER_TOO_SMALL;
}
rc_of_snprintf = HAL_Snprintf(jsonBuffer + strlen(jsonBuffer) - 1, remain_size, "}" );
rc = check_snprintf_return(rc_of_snprintf, remain_size);
if (rc != QCLOUD_RET_SUCCESS) {
return rc;
}
}
//finish json
if ((remain_size = sizeOfBuffer - strlen(jsonBuffer)) < 1) {
return QCLOUD_ERR_JSON_BUFFER_TOO_SMALL;
}
rc_of_snprintf = HAL_Snprintf(jsonBuffer + strlen(jsonBuffer), remain_size, "}");
return check_snprintf_return(rc_of_snprintf, remain_size);
}
static int _publish_event_to_cloud(void *c, char *pJsonDoc)
uint8_t event_count,
sEvent *pEventArry[],
OnEventReplyCallback replyCb,
uint32_t reply_timeout_ms)
{
IOT_FUNC_ENTRY;
int rc = QCLOUD_RET_SUCCESS;
char topic[MAX_SIZE_OF_CLOUD_TOPIC] = {0};
Qcloud_IoT_Template *ptemplate = (Qcloud_IoT_Template *)c;
size_t remain_size = 0;
int32_t rc_of_snprintf = 0;
uint8_t i, j;
Qcloud_IoT_Template* ptemplate = (Qcloud_IoT_Template *)handle;
POINTER_SANITY_CHECK(ptemplate, QCLOUD_ERR_INVAL);
POINTER_SANITY_CHECK(jsonBuffer, QCLOUD_ERR_INVAL);
POINTER_SANITY_CHECK(pEventArry, QCLOUD_ERR_INVAL);
int rc = _iot_event_json_init(ptemplate, jsonBuffer, sizeOfBuffer, event_count, replyCb, reply_timeout_ms);
if (rc != QCLOUD_RET_SUCCESS) {
Log_e("event json init failed: %d", rc);
return rc;
}
//Log_d("event_count:%d, Doc_init:%s",event_count, jsonBuffer);
if ((remain_size = sizeOfBuffer - strlen(jsonBuffer)) <= 1) {
return QCLOUD_ERR_JSON_BUFFER_TOO_SMALL;
}
if (event_count > SIGLE_EVENT) { //mutlti event
rc_of_snprintf = HAL_Snprintf(jsonBuffer + strlen(jsonBuffer), remain_size, "\"events\":[");
rc = check_snprintf_return(rc_of_snprintf, remain_size);
if (rc != QCLOUD_RET_SUCCESS) {
return rc;
}
if ((remain_size = sizeOfBuffer - strlen(jsonBuffer)) <= 1) {
return QCLOUD_ERR_JSON_BUFFER_TOO_SMALL;
}
for (i = 0; i < event_count; i++) {
sEvent *pEvent = pEventArry[i];
if (NULL == pEvent) {
Log_e("%dth/%d null event", i, event_count);
return QCLOUD_ERR_INVAL;
}
if (0 == pEvent->timestamp) { //no accurate UTC time, set 0
rc_of_snprintf = HAL_Snprintf(jsonBuffer + strlen(jsonBuffer), remain_size, "{\"eventId\":\"%s\", \"type\":\"%s\", \"timestamp\":0, \"params\":{", \
pEvent->event_name, pEvent->type);
} else { // accurate UTC time is second,change to ms
rc_of_snprintf = HAL_Snprintf(jsonBuffer + strlen(jsonBuffer), remain_size, "{\"eventId\":\"%s\", \"type\":\"%s\", \"timestamp\":%u000, \"params\":{", \
pEvent->event_name, pEvent->type, pEvent->timestamp);
}
int size = HAL_Snprintf(topic, MAX_SIZE_OF_CLOUD_TOPIC, "$thing/up/event/%s/%s", iot_device_info_get()->product_id, iot_device_info_get()->device_name);
if (size < 0 || size > sizeof(topic) - 1)
{
Log_e("topic content length not enough! content size:%d buf size:%d", size, (int)sizeof(topic));
return QCLOUD_ERR_FAILURE;
}
rc = check_snprintf_return(rc_of_snprintf, remain_size);
if (rc != QCLOUD_RET_SUCCESS) {
return rc;
}
PublishParams pubParams = DEFAULT_PUB_PARAMS;
pubParams.qos = QOS0;
pubParams.payload_len = strlen(pJsonDoc);
pubParams.payload = (char *) pJsonDoc;
if ((remain_size = sizeOfBuffer - strlen(jsonBuffer)) <= 1) {
return QCLOUD_ERR_JSON_BUFFER_TOO_SMALL;
}
rc = IOT_MQTT_Publish(ptemplate->mqtt, topic, &pubParams);
DeviceProperty *pJsonNode = pEvent->pEventData;
for (j = 0; j < pEvent->eventDataNum; j++) {
if (pJsonNode != NULL && pJsonNode->key != NULL) {
rc = template_put_json_node(jsonBuffer, remain_size, pJsonNode->key, pJsonNode->data, pJsonNode->type);
IOT_FUNC_EXIT_RC(rc);
if (rc != QCLOUD_RET_SUCCESS) {
return rc;
}
} else {
Log_e("%dth/%d null event property data", i, pEvent->eventDataNum);
return QCLOUD_ERR_INVAL;
}
pJsonNode++;
}
if ((remain_size = sizeOfBuffer - strlen(jsonBuffer)) <= 1) {
return QCLOUD_ERR_JSON_BUFFER_TOO_SMALL;
}
rc_of_snprintf = HAL_Snprintf(jsonBuffer + strlen(jsonBuffer) - 1, remain_size, "}}," );
rc = check_snprintf_return(rc_of_snprintf, remain_size);
if (rc != QCLOUD_RET_SUCCESS) {
return rc;
}
pEvent++;
}
if ((remain_size = sizeOfBuffer - strlen(jsonBuffer)) <= 1) {
return QCLOUD_ERR_JSON_BUFFER_TOO_SMALL;
}
rc_of_snprintf = HAL_Snprintf(jsonBuffer + strlen(jsonBuffer) - 1, remain_size, "]");
rc = check_snprintf_return(rc_of_snprintf, remain_size);
if (rc != QCLOUD_RET_SUCCESS) {
return rc;
}
} else { //single
sEvent *pEvent = pEventArry[0];
if (0 == pEvent->timestamp) { //no accurate UTC time, set 0
rc_of_snprintf = HAL_Snprintf(jsonBuffer + strlen(jsonBuffer), remain_size, "{\"eventId\":\"%s\", \"type\":\"%s\", \"timestamp\":0, \"params\":{", \
pEvent->event_name, pEvent->type);
} else { // accurate UTC time is second,change to ms
rc_of_snprintf = HAL_Snprintf(jsonBuffer + strlen(jsonBuffer), remain_size, "\"eventId\":\"%s\", \"type\":\"%s\", \"timestamp\":%u000, \"params\":{", \
pEvent->event_name, pEvent->type, pEvent->timestamp);
}
rc = check_snprintf_return(rc_of_snprintf, remain_size);
if (rc != QCLOUD_RET_SUCCESS) {
return rc;
}
if ((remain_size = sizeOfBuffer - strlen(jsonBuffer)) <= 1) {
return QCLOUD_ERR_JSON_BUFFER_TOO_SMALL;
}
DeviceProperty *pJsonNode = pEvent->pEventData;
for (i = 0; i < pEvent->eventDataNum; i++) {
if (pJsonNode != NULL && pJsonNode->key != NULL) {
rc = template_put_json_node(jsonBuffer, remain_size, pJsonNode->key, pJsonNode->data, pJsonNode->type);
if (rc != QCLOUD_RET_SUCCESS) {
return rc;
}
} else {
Log_e("%dth/%d null event property data", i, pEvent->eventDataNum);
return QCLOUD_ERR_INVAL;
}
pJsonNode++;
}
if ((remain_size = sizeOfBuffer - strlen(jsonBuffer)) <= 1) {
return QCLOUD_ERR_JSON_BUFFER_TOO_SMALL;
}
rc_of_snprintf = HAL_Snprintf(jsonBuffer + strlen(jsonBuffer) - 1, remain_size, "}" );
rc = check_snprintf_return(rc_of_snprintf, remain_size);
if (rc != QCLOUD_RET_SUCCESS) {
return rc;
}
}
//finish json
if ((remain_size = sizeOfBuffer - strlen(jsonBuffer)) < 1) {
return QCLOUD_ERR_JSON_BUFFER_TOO_SMALL;
}
rc_of_snprintf = HAL_Snprintf(jsonBuffer + strlen(jsonBuffer), remain_size, "}");
return check_snprintf_return(rc_of_snprintf, remain_size);
}
void handle_template_expired_event(void *client)
static int _publish_event_to_cloud(void *c, char *pJsonDoc)
{
IOT_FUNC_ENTRY;
Qcloud_IoT_Template *pTemplate = (Qcloud_IoT_Template *)client;
int rc = QCLOUD_RET_SUCCESS;
char topic[MAX_SIZE_OF_CLOUD_TOPIC] = {0};
Qcloud_IoT_Template *ptemplate = (Qcloud_IoT_Template *)c;
int size = HAL_Snprintf(topic, MAX_SIZE_OF_CLOUD_TOPIC, "$thing/up/event/%s/%s", iot_device_info_get()->product_id, iot_device_info_get()->device_name);
if (size < 0 || size > sizeof(topic) - 1) {
Log_e("topic content length not enough! content size:%d buf size:%d", size, (int)sizeof(topic));
return QCLOUD_ERR_FAILURE;
}
PublishParams pubParams = DEFAULT_PUB_PARAMS;
pubParams.qos = QOS1;
pubParams.payload_len = strlen(pJsonDoc);
pubParams.payload = (char *) pJsonDoc;
rc = IOT_MQTT_Publish(ptemplate->mqtt, topic, &pubParams);
IOT_FUNC_EXIT_RC(rc);
}
void handle_template_expired_event(void *client)
{
IOT_FUNC_ENTRY;
Qcloud_IoT_Template *pTemplate = (Qcloud_IoT_Template *)client;
_traverse_event_list(pTemplate, pTemplate->inner_data.event_list, NULL, NULL, eDEAL_EXPIRED);
@@ -393,98 +393,98 @@ void handle_template_expired_event(void *client)
void IOT_Event_setFlag(void *client, uint32_t flag)
{
Qcloud_IoT_Template *pTemplate = (Qcloud_IoT_Template *)client;
pTemplate->inner_data.eventflags |= flag&0xffffffff;
Qcloud_IoT_Template *pTemplate = (Qcloud_IoT_Template *)client;
pTemplate->inner_data.eventflags |= flag & 0xffffffff;
}
void IOT_Event_clearFlag(void *client, uint32_t flag)
{
Qcloud_IoT_Template *pTemplate = (Qcloud_IoT_Template *)client;
Qcloud_IoT_Template *pTemplate = (Qcloud_IoT_Template *)client;
pTemplate->inner_data.eventflags &= (~flag)&0xffffffff;
pTemplate->inner_data.eventflags &= (~flag) & 0xffffffff;
}
uint32_t IOT_Event_getFlag(void *client)
{
Qcloud_IoT_Template *pTemplate = (Qcloud_IoT_Template *)client;
Qcloud_IoT_Template *pTemplate = (Qcloud_IoT_Template *)client;
return pTemplate->inner_data.eventflags;
}
return pTemplate->inner_data.eventflags;
}
int IOT_Event_Init(void *c)
{
static char topic_name[MAX_SIZE_OF_CLOUD_TOPIC] = {0};
Qcloud_IoT_Template *pTemplate = (Qcloud_IoT_Template *)c;
static char topic_name[MAX_SIZE_OF_CLOUD_TOPIC] = {0};
Qcloud_IoT_Template *pTemplate = (Qcloud_IoT_Template *)c;
int size = HAL_Snprintf(topic_name, MAX_SIZE_OF_CLOUD_TOPIC, "$thing/down/event/%s/%s", iot_device_info_get()->product_id, iot_device_info_get()->device_name);
int size = HAL_Snprintf(topic_name, MAX_SIZE_OF_CLOUD_TOPIC, "$thing/down/event/%s/%s", iot_device_info_get()->product_id, iot_device_info_get()->device_name);
if (size < 0 || size > sizeof(topic_name) - 1)
{
Log_e("topic content length not enough! content size:%d buf size:%d", size, (int)sizeof(topic_name));
return QCLOUD_ERR_FAILURE;
}
SubscribeParams sub_params = DEFAULT_SUB_PARAMS;
sub_params.on_message_handler = _on_event_reply_callback;
return IOT_MQTT_Subscribe(pTemplate->mqtt, topic_name, &sub_params);
if (size < 0 || size > sizeof(topic_name) - 1) {
Log_e("topic content length not enough! content size:%d buf size:%d", size, (int)sizeof(topic_name));
return QCLOUD_ERR_FAILURE;
}
SubscribeParams sub_params = DEFAULT_SUB_PARAMS;
sub_params.on_message_handler = _on_event_reply_callback;
sub_params.user_data = pTemplate;
return IOT_MQTT_Subscribe(pTemplate->mqtt, topic_name, &sub_params);
}
int IOT_Post_Event(void *pClient, char *pJsonDoc, size_t sizeOfBuffer, uint8_t event_count, sEvent *pEventArry[], OnEventReplyCallback replyCb)
int IOT_Post_Event(void *pClient, char *pJsonDoc, size_t sizeOfBuffer, uint8_t event_count, sEvent *pEventArry[], OnEventReplyCallback replyCb)
{
int rc;
rc = _iot_construct_event_json(pClient, pJsonDoc, sizeOfBuffer, event_count, pEventArry, replyCb, QCLOUD_IOT_MQTT_COMMAND_TIMEOUT);
if (rc != QCLOUD_RET_SUCCESS) {
Log_e("construct event json fail, %d",rc);
return rc;
}
rc = _publish_event_to_cloud(pClient, pJsonDoc);
if (rc < 0) {
Log_e("publish event to cloud fail, %d",rc);
}
int rc;
return rc;
rc = _iot_construct_event_json(pClient, pJsonDoc, sizeOfBuffer, event_count, pEventArry, replyCb, QCLOUD_IOT_MQTT_COMMAND_TIMEOUT);
if (rc != QCLOUD_RET_SUCCESS) {
Log_e("construct event json fail, %d", rc);
return rc;
}
rc = _publish_event_to_cloud(pClient, pJsonDoc);
if (rc < 0) {
Log_e("publish event to cloud fail, %d", rc);
}
return rc;
}
int IOT_Post_Event_Raw(void *pClient, char *pJsonDoc, size_t sizeOfBuffer, char *pEventMsg, OnEventReplyCallback replyCb)
int IOT_Post_Event_Raw(void *pClient, char *pJsonDoc, size_t sizeOfBuffer, char *pEventMsg, OnEventReplyCallback replyCb)
{
int rc;
size_t remain_size = 0;
int32_t rc_of_snprintf;
int rc;
size_t remain_size = 0;
int32_t rc_of_snprintf;
Qcloud_IoT_Template* ptemplate = (Qcloud_IoT_Template *)pClient;
Qcloud_IoT_Template* ptemplate = (Qcloud_IoT_Template *)pClient;
POINTER_SANITY_CHECK(ptemplate, QCLOUD_ERR_INVAL);
POINTER_SANITY_CHECK(pJsonDoc, QCLOUD_ERR_INVAL);
POINTER_SANITY_CHECK(pEventMsg, QCLOUD_ERR_INVAL);
POINTER_SANITY_CHECK(ptemplate, QCLOUD_ERR_INVAL);
POINTER_SANITY_CHECK(pJsonDoc, QCLOUD_ERR_INVAL);
POINTER_SANITY_CHECK(pEventMsg, QCLOUD_ERR_INVAL);
rc = _iot_event_json_init(ptemplate, pJsonDoc, sizeOfBuffer, MUTLTI_EVENTS, replyCb, QCLOUD_IOT_MQTT_COMMAND_TIMEOUT);
if (rc != QCLOUD_RET_SUCCESS) {
Log_e("event json init failed: %d", rc);
return rc;
}
rc = _iot_event_json_init(ptemplate, pJsonDoc, sizeOfBuffer, MUTLTI_EVENTS, replyCb, QCLOUD_IOT_MQTT_COMMAND_TIMEOUT);
if (rc != QCLOUD_RET_SUCCESS) {
Log_e("event json init failed: %d", rc);
return rc;
}
if ((remain_size = sizeOfBuffer - strlen(pJsonDoc)) <= 1) {
return QCLOUD_ERR_JSON_BUFFER_TOO_SMALL;
}
if ((remain_size = sizeOfBuffer - strlen(pJsonDoc)) <= 1) {
return QCLOUD_ERR_JSON_BUFFER_TOO_SMALL;
}
rc_of_snprintf = HAL_Snprintf(pJsonDoc + strlen(pJsonDoc), remain_size, "\"events\":[%s]}", pEventMsg);
rc = check_snprintf_return(rc_of_snprintf, remain_size);
if (rc != QCLOUD_RET_SUCCESS) {
return rc;
}
rc_of_snprintf = HAL_Snprintf(pJsonDoc + strlen(pJsonDoc), remain_size, "\"events\":[%s]}", pEventMsg);
rc = check_snprintf_return(rc_of_snprintf, remain_size);
if (rc != QCLOUD_RET_SUCCESS) {
return rc;
}
Log_d("JsonDoc:%s", pJsonDoc);
rc = _publish_event_to_cloud(pClient, pJsonDoc);
if (rc < 0 ) {
Log_e("publish event raw to cloud fail, %d",rc);
}
Log_d("JsonDoc:%s", pJsonDoc);
return rc;
rc = _publish_event_to_cloud(pClient, pJsonDoc);
if (rc < 0 ) {
Log_e("publish event raw to cloud fail, %d", rc);
}
return rc;
}
#endif

View File

@@ -0,0 +1,303 @@
#include <string.h>
#include "utils_param_check.h"
#include "gateway_common.h"
#include "mqtt_client.h"
static Gateway sg_gateway = {0};
void _gateway_event_handler(void *client, void *context, MQTTEventMsg *msg)
{
uintptr_t packet_id = (uintptr_t)msg->msg;
Gateway* gateway = (Gateway*)context;
POINTER_SANITY_CHECK_RTN(context);
POINTER_SANITY_CHECK_RTN(msg);
MQTTMessage* topic_info = (MQTTMessage*)msg->msg;
switch (msg->event_type) {
case MQTT_EVENT_SUBCRIBE_SUCCESS:
case MQTT_EVENT_UNSUBCRIBE_SUCCESS:
Log_d("gateway sub|unsub(%d) success, packet-id=%u", msg->event_type, (unsigned int)packet_id);
if (gateway->gateway_data.sync_status == packet_id) {
gateway->gateway_data.sync_status = 0;
return;
}
break;
case MQTT_EVENT_SUBCRIBE_TIMEOUT:
case MQTT_EVENT_UNSUBCRIBE_TIMEOUT:
case MQTT_EVENT_SUBCRIBE_NACK:
case MQTT_EVENT_UNSUBCRIBE_NACK:
Log_d("gateway timeout|nack(%d) event, packet-id=%u", msg->event_type, (unsigned int)packet_id);
if (gateway->gateway_data.sync_status == packet_id) {
gateway->gateway_data.sync_status = -1;
return;
}
break;
case MQTT_EVENT_PUBLISH_RECVEIVED:
Log_d("gateway topic message arrived but without any related handle: topic=%.*s, topic_msg=%.*s",
topic_info->topic_len,
topic_info->ptopic,
topic_info->payload_len,
topic_info->payload);
break;
default:
break;
}
if (gateway->event_handle.h_fp != NULL) {
gateway->event_handle.h_fp(client, gateway->event_handle.context, msg);
}
return;
}
void* IOT_Gateway_Construct(GatewayInitParam* init_param)
{
int rc = 0;
GatewayParam param = DEFAULT_GATEWAY_PARAMS;
POINTER_SANITY_CHECK(init_param, NULL);
if (sg_gateway.is_construct) {
Log_e("gateway have been construct");
IOT_FUNC_EXIT_RC(NULL);
}
memset(&sg_gateway, 0, sizeof(Gateway));
/* replace user event handle */
sg_gateway.event_handle.h_fp = init_param->init_param.event_handle.h_fp;
sg_gateway.event_handle.context = init_param->init_param.event_handle.context;
/* set _gateway_event_handler as mqtt event handle */
init_param->init_param.event_handle.h_fp = _gateway_event_handler;
init_param->init_param.event_handle.context = &sg_gateway;
/* construct MQTT client */
sg_gateway.mqtt = IOT_MQTT_Construct(&init_param->init_param);
if (NULL == sg_gateway.mqtt) {
Log_e("construct MQTT failed");
IOT_FUNC_EXIT_RC(NULL);
}
/* subscribe default topic */
param.product_id = init_param->init_param.product_id;
param.device_name = init_param->init_param.device_name;
rc = gateway_subscribe_unsubscribe_default(&sg_gateway, &param);
if (QCLOUD_RET_SUCCESS != rc) {
Log_e("subscribe default topic failed");
IOT_Gateway_Destroy((void*)&sg_gateway);
IOT_FUNC_EXIT_RC(NULL);
}
sg_gateway.is_construct = 1;
return &sg_gateway;
}
int IOT_Gateway_Subdev_Online(void *client, GatewayParam* param)
{
int rc = 0;
char topic[MAX_SIZE_OF_CLOUD_TOPIC + 1] = {0};
char payload[GATEWAY_PAYLOAD_BUFFER_LEN + 1] = {0};
int size = 0;
SubdevSession* session = NULL;
PublishParams params = DEFAULT_PUB_PARAMS;
Gateway* gateway = (Gateway*)client;
POINTER_SANITY_CHECK(gateway, QCLOUD_ERR_INVAL);
POINTER_SANITY_CHECK(param, QCLOUD_ERR_INVAL);
STRING_PTR_SANITY_CHECK(param->product_id, QCLOUD_ERR_INVAL);
STRING_PTR_SANITY_CHECK(param->device_name, QCLOUD_ERR_INVAL);
STRING_PTR_SANITY_CHECK(param->subdev_product_id, QCLOUD_ERR_INVAL);
STRING_PTR_SANITY_CHECK(param->subdev_device_name, QCLOUD_ERR_INVAL);
session = subdev_find_session(gateway, param->subdev_product_id, param->subdev_device_name);
if (NULL == session) {
Log_d("there is no session, create a new session");
/* create subdev session */
session = subdev_add_session(gateway, param->subdev_product_id, param->subdev_device_name);
if (NULL == session) {
Log_e("create session error!");
IOT_FUNC_EXIT_RC(QCLOUD_ERR_GATEWAY_CREATE_SESSION_FAIL);
}
} else {
if (SUBDEV_SEESION_STATUS_ONLINE == session->session_status) {
Log_i("device have online");
IOT_FUNC_EXIT_RC(QCLOUD_ERR_GATEWAY_SUBDEV_ONLINE);
}
}
size = HAL_Snprintf(topic, MAX_SIZE_OF_CLOUD_TOPIC + 1, GATEWAY_TOPIC_OPERATION_FMT, param->product_id, param->device_name);
if (size < 0 || size > MAX_SIZE_OF_CLOUD_TOPIC) {
Log_e("buf size < topic length!");
IOT_FUNC_EXIT_RC(QCLOUD_ERR_FAILURE);
}
size = HAL_Snprintf(payload, GATEWAY_PAYLOAD_BUFFER_LEN + 1, GATEWAY_PAYLOAD_STATUS_FMT, "online", param->subdev_product_id, param->subdev_device_name);
if (size < 0 || size > GATEWAY_PAYLOAD_BUFFER_LEN) {
Log_e("buf size < payload length!");
IOT_FUNC_EXIT_RC(QCLOUD_ERR_FAILURE);
}
size = HAL_Snprintf(gateway->gateway_data.online.client_id, MAX_SIZE_OF_CLIENT_ID, GATEWAY_CLIENT_ID_FMT, param->subdev_product_id, param->subdev_device_name);
if (size < 0 || size > MAX_SIZE_OF_CLIENT_ID) {
Log_e("buf size < client_id length!");
IOT_FUNC_EXIT_RC(QCLOUD_ERR_FAILURE);
}
gateway->gateway_data.online.result = -2;
params.qos = QOS0;
params.payload_len = strlen(payload);
params.payload = (char *) payload;
/* publish packet */
rc = gateway_publish_sync(gateway, topic, &params, &gateway->gateway_data.online.result);
if (QCLOUD_RET_SUCCESS != rc) {
subdev_remove_session(gateway, param->subdev_product_id, param->subdev_device_name);
IOT_FUNC_EXIT_RC(rc);
}
session->session_status = SUBDEV_SEESION_STATUS_ONLINE;
IOT_FUNC_EXIT_RC(QCLOUD_RET_SUCCESS);
}
int IOT_Gateway_Subdev_Offline(void *client, GatewayParam* param)
{
int rc = 0;
char topic[MAX_SIZE_OF_CLOUD_TOPIC + 1] = {0};
char payload[GATEWAY_PAYLOAD_BUFFER_LEN + 1] = {0};
int size = 0;
SubdevSession* session = NULL;
Gateway* gateway = (Gateway*)client;
POINTER_SANITY_CHECK(gateway, QCLOUD_ERR_INVAL);
POINTER_SANITY_CHECK(param, QCLOUD_ERR_INVAL);
STRING_PTR_SANITY_CHECK(param->product_id, QCLOUD_ERR_INVAL);
STRING_PTR_SANITY_CHECK(param->device_name, QCLOUD_ERR_INVAL);
STRING_PTR_SANITY_CHECK(param->subdev_product_id, QCLOUD_ERR_INVAL);
STRING_PTR_SANITY_CHECK(param->subdev_device_name, QCLOUD_ERR_INVAL);
session = subdev_find_session(gateway, param->subdev_product_id, param->subdev_device_name);
if (NULL == session) {
Log_d("no session, can not offline");
IOT_FUNC_EXIT_RC(QCLOUD_ERR_GATEWAY_SESSION_NO_EXIST);
}
if (SUBDEV_SEESION_STATUS_OFFLINE == session->session_status) {
Log_i("device have offline");
/* free session */
subdev_remove_session(gateway, param->subdev_product_id, param->subdev_device_name);
IOT_FUNC_EXIT_RC(QCLOUD_ERR_GATEWAY_SUBDEV_OFFLINE);
}
size = HAL_Snprintf(topic, MAX_SIZE_OF_CLOUD_TOPIC + 1, GATEWAY_TOPIC_OPERATION_FMT, param->product_id, param->device_name);
if (size < 0 || size > MAX_SIZE_OF_CLOUD_TOPIC) {
Log_e("buf size < topic length!");
IOT_FUNC_EXIT_RC(QCLOUD_ERR_FAILURE);
}
size = HAL_Snprintf(payload, GATEWAY_PAYLOAD_BUFFER_LEN + 1, GATEWAY_PAYLOAD_STATUS_FMT, "offline", param->subdev_product_id, param->subdev_device_name);
if (size < 0 || size > GATEWAY_PAYLOAD_BUFFER_LEN) {
Log_e("buf size < payload length!");
IOT_FUNC_EXIT_RC(QCLOUD_ERR_FAILURE);
}
size = HAL_Snprintf(gateway->gateway_data.offline.client_id, MAX_SIZE_OF_CLIENT_ID, GATEWAY_CLIENT_ID_FMT, param->subdev_product_id, param->subdev_device_name);
if (size < 0 || size > MAX_SIZE_OF_CLIENT_ID) {
Log_e("buf size < client_id length!");
IOT_FUNC_EXIT_RC(QCLOUD_ERR_FAILURE);
}
gateway->gateway_data.offline.result = -2;
PublishParams params = DEFAULT_PUB_PARAMS;
params.qos = QOS0;
params.payload_len = strlen(payload);
params.payload = (char *) payload;
/* publish packet */
rc = gateway_publish_sync(gateway, topic, &params, &gateway->gateway_data.offline.result);
if (QCLOUD_RET_SUCCESS != rc) {
IOT_FUNC_EXIT_RC(rc);
}
session->session_status = SUBDEV_SEESION_STATUS_OFFLINE;
/* free session */
subdev_remove_session(gateway, param->subdev_product_id, param->subdev_device_name);
IOT_FUNC_EXIT_RC(QCLOUD_RET_SUCCESS);
}
int IOT_Gateway_Destroy(void *client)
{
int ret;
Gateway* gateway = (Gateway*)client;
POINTER_SANITY_CHECK(gateway, QCLOUD_ERR_INVAL);
ret = IOT_MQTT_Destroy(&gateway->mqtt);
gateway->is_construct = 0;
return ret;
}
void *IOT_Gateway_Get_MQTT_Client(void *client)
{
Gateway* gateway = (Gateway*)client;
return (NULL == gateway) ? NULL : (gateway->mqtt);
}
int IOT_Gateway_Yield(void *client, uint32_t timeout_ms)
{
Gateway* gateway = (Gateway*)client;
POINTER_SANITY_CHECK(gateway, QCLOUD_ERR_INVAL);
return IOT_MQTT_Yield(gateway->mqtt, timeout_ms);
}
int IOT_Gateway_Subscribe(void *client, char *topic_filter, SubscribeParams *params)
{
Gateway* gateway = (Gateway*)client;
POINTER_SANITY_CHECK(gateway, QCLOUD_ERR_INVAL);
return IOT_MQTT_Subscribe(gateway->mqtt, topic_filter, params);
}
int IOT_Gateway_Unsubscribe(void *client, char *topic_filter)
{
Gateway* gateway = (Gateway*)client;
POINTER_SANITY_CHECK(gateway, QCLOUD_ERR_INVAL);
return IOT_MQTT_Unsubscribe(gateway->mqtt, topic_filter);
}
int IOT_Gateway_Publish(void *client, char *topic_name, PublishParams *params)
{
Gateway* gateway = (Gateway*)client;
POINTER_SANITY_CHECK(gateway, QCLOUD_ERR_INVAL);
return IOT_MQTT_Publish(gateway->mqtt, topic_name, params);
}

View File

@@ -0,0 +1,351 @@
#include "lite-utils.h"
#include "mqtt_client.h"
#include "gateway_common.h"
static char cloud_rcv_buf[GATEWAY_RECEIVE_BUFFER_LEN];
static bool get_json_type(char *json, char **v)
{
*v = LITE_json_value_of("type", json);
return *v == NULL ? false : true;
}
static bool get_json_devices(char *json, char **v)
{
*v = LITE_json_value_of("payload.devices", json);
return *v == NULL ? false : true;
}
static bool get_json_result(char *json, int32_t* res)
{
char *v = LITE_json_value_of("result", json);
if (v == NULL) {
return false;
}
if (LITE_get_int32(res, v) != QCLOUD_RET_SUCCESS) {
HAL_Free(v);
return false;
}
HAL_Free(v);
return true;
}
static bool get_json_product_id(char *json, char **v)
{
*v = LITE_json_value_of("product_id", json);
return *v == NULL ? false : true;
}
static bool get_json_device_name(char *json, char **v)
{
*v = LITE_json_value_of("device_name", json);
return *v == NULL ? false : true;
}
static void _gateway_message_handler(void *client, MQTTMessage *message, void *user_data)
{
Qcloud_IoT_Client *mqtt = NULL;
Gateway *gateway = NULL;
char *topic = NULL;
size_t topic_len = 0;
int cloud_rcv_len = 0;
char *type = NULL;
char *devices = NULL, *devices_strip = NULL;
char *product_id = NULL;
char *device_name = NULL;
int32_t result = 0;
char client_id[MAX_SIZE_OF_CLIENT_ID + 1] = {0};
int size = 0;
POINTER_SANITY_CHECK_RTN(client);
POINTER_SANITY_CHECK_RTN(message);
mqtt = (Qcloud_IoT_Client *)client;
gateway = (Gateway*)mqtt->event_handle.context;
POINTER_SANITY_CHECK_RTN(gateway);
topic = (char *)message->ptopic;
topic_len = message->topic_len;
if (NULL == topic || topic_len <= 0) {
Log_e("topic == NULL or topic_len <= 0.");
return;
}
if (message->payload_len > GATEWAY_RECEIVE_BUFFER_LEN) {
Log_e("message->payload_len > GATEWAY_RECEIVE_BUFFER_LEN.");
return;
}
cloud_rcv_len = Min(GATEWAY_RECEIVE_BUFFER_LEN - 1, message->payload_len);
memcpy(cloud_rcv_buf, message->payload, cloud_rcv_len + 1);
cloud_rcv_buf[cloud_rcv_len] = '\0'; // jsmn_parse relies on a string
// Log_d("recv:%s", cloud_rcv_buf);
if (!get_json_type(cloud_rcv_buf, &type)) {
Log_e("Fail to parse type from msg: %s", cloud_rcv_buf);
return;
}
if (!get_json_devices(cloud_rcv_buf, &devices)) {
Log_e("Fail to parse devices from msg: %s", cloud_rcv_buf);
HAL_Free(type);
return;
}
if (devices[0] == '[') {
devices_strip = devices + 1;
} else {
devices_strip = devices;
}
if (!get_json_result(devices_strip, &result)) {
Log_e("Fail to parse result from msg: %s", cloud_rcv_buf);
HAL_Free(type);
HAL_Free(devices);
return;
}
if (!get_json_product_id(devices_strip, &product_id)) {
Log_e("Fail to parse product_id from msg: %s", cloud_rcv_buf);
HAL_Free(type);
HAL_Free(devices);
return;
}
if (!get_json_device_name(devices_strip, &device_name)) {
Log_e("Fail to parse device_name from msg: %s", cloud_rcv_buf);
HAL_Free(type);
HAL_Free(devices);
HAL_Free(product_id);
return;
}
size = HAL_Snprintf(client_id, MAX_SIZE_OF_CLIENT_ID + 1, GATEWAY_CLIENT_ID_FMT, product_id, device_name);
if (size < 0 || size > MAX_SIZE_OF_CLIENT_ID) {
Log_e("generate client_id fail.");
HAL_Free(type);
HAL_Free(devices);
HAL_Free(product_id);
HAL_Free(device_name);
return;
}
if (strncmp(type, "online", sizeof("online") - 1) == 0) {
if (strncmp(client_id, gateway->gateway_data.online.client_id, size) == 0) {
Log_i("client_id(%s), online result %d", client_id, result);
gateway->gateway_data.online.result = result;
}
} else if (strncmp(type, "offline", sizeof("offline") - 1) == 0) {
if (strncmp(client_id, gateway->gateway_data.offline.client_id, size) == 0) {
Log_i("client_id(%s), offline result %d", client_id, result);
gateway->gateway_data.offline.result = result;
}
}
HAL_Free(type);
HAL_Free(devices);
HAL_Free(product_id);
HAL_Free(device_name);
return;
}
int gateway_subscribe_unsubscribe_topic(Gateway *gateway, char *topic_filter, SubscribeParams *params, int is_subscribe)
{
int rc = 0;
int loop_count = 0;
uint32_t status = -1;
POINTER_SANITY_CHECK(gateway, QCLOUD_ERR_INVAL);
POINTER_SANITY_CHECK(params, QCLOUD_ERR_INVAL);
STRING_PTR_SANITY_CHECK(topic_filter, QCLOUD_ERR_INVAL);
params->qos = QOS1;
gateway->gateway_data.sync_status = status;
if (is_subscribe) {
/* subscribe */
rc = IOT_MQTT_Subscribe(gateway->mqtt, topic_filter, params);
} else {
/* unsubscribe */
rc = IOT_MQTT_Unsubscribe(gateway->mqtt, topic_filter);
}
if (rc < 0) {
Log_e("subscribe or un(%d), result(%d)", is_subscribe, rc);
IOT_FUNC_EXIT_RC(rc);
}
gateway->gateway_data.sync_status = status = rc;
while (status == gateway->gateway_data.sync_status) {
if (loop_count > GATEWAY_LOOP_MAX_COUNT) {
Log_i("loop max count, time out");
IOT_FUNC_EXIT_RC(QCLOUD_ERR_FAILURE);
}
IOT_Gateway_Yield(gateway, 200);
loop_count++;
}
if (gateway->gateway_data.sync_status != 0) {
Log_e("gateway->gateway_data.sync_status(%u) != 0", gateway->gateway_data.sync_status);
IOT_FUNC_EXIT_RC(QCLOUD_ERR_FAILURE);
}
IOT_FUNC_EXIT_RC(QCLOUD_RET_SUCCESS);
}
int gateway_subscribe_unsubscribe_default(Gateway *gateway, GatewayParam *param)
{
int rc = 0;
int size = 0;
char topic_filter[MAX_SIZE_OF_CLOUD_TOPIC + 1] = {0};
SubscribeParams subscribe_params = DEFAULT_SUB_PARAMS;
POINTER_SANITY_CHECK(param, QCLOUD_ERR_INVAL);
STRING_PTR_SANITY_CHECK(param->product_id, QCLOUD_ERR_INVAL);
STRING_PTR_SANITY_CHECK(param->device_name, QCLOUD_ERR_INVAL);
//subscribe online/offline operation reslut
size = HAL_Snprintf(topic_filter, MAX_SIZE_OF_CLOUD_TOPIC + 1, GATEWAY_TOPIC_OPERATION_RESULT_FMT, param->product_id, param->device_name);
if (size < 0 || size > MAX_SIZE_OF_CLOUD_TOPIC) {
Log_e("buf size < topic length!");
IOT_FUNC_EXIT_RC(QCLOUD_ERR_FAILURE);
}
subscribe_params.on_message_handler = _gateway_message_handler;
rc = gateway_subscribe_unsubscribe_topic(gateway, topic_filter, &subscribe_params, IOT_TRUE);
if (QCLOUD_RET_SUCCESS != rc) {
IOT_FUNC_EXIT_RC(rc);
}
IOT_FUNC_EXIT_RC(QCLOUD_RET_SUCCESS);
}
SubdevSession* subdev_find_session(Gateway *gateway, char *product_id, char *device_name)
{
SubdevSession* session = NULL;
POINTER_SANITY_CHECK(gateway, NULL);
STRING_PTR_SANITY_CHECK(product_id, NULL);
STRING_PTR_SANITY_CHECK(device_name, NULL);
session = gateway->session_list;
/* session is exist */
while (session) {
if (0 == strcmp(session->product_id, product_id) &&
0 == strcmp(session->device_name, device_name)) {
IOT_FUNC_EXIT_RC(session);
}
session = session->next;
}
IOT_FUNC_EXIT_RC(NULL);
}
SubdevSession* subdev_add_session(Gateway *gateway, char *product_id, char *device_name)
{
SubdevSession* session = NULL;
POINTER_SANITY_CHECK(gateway, NULL);
STRING_PTR_SANITY_CHECK(product_id, NULL);
STRING_PTR_SANITY_CHECK(device_name, NULL);
session = HAL_Malloc(sizeof(SubdevSession));
if (session == NULL) {
Log_e("Not enough memory");
IOT_FUNC_EXIT_RC(NULL);
}
/* add session to list */
session->next = gateway->session_list;
gateway->session_list = session;
int size = strlen(product_id);
strncpy(session->product_id, product_id, size);
session->product_id[size] = '\0';
size = strlen(device_name);
strncpy(session->device_name, device_name, size);
session->device_name[size] = '\0';
session->session_status = SUBDEV_SEESION_STATUS_INIT;
IOT_FUNC_EXIT_RC(session);
}
int subdev_remove_session(Gateway *gateway, char *product_id, char *device_name)
{
SubdevSession* cur_session = NULL;
SubdevSession* pre_session = NULL;
POINTER_SANITY_CHECK(gateway, QCLOUD_ERR_FAILURE);
STRING_PTR_SANITY_CHECK(product_id, QCLOUD_ERR_FAILURE);
STRING_PTR_SANITY_CHECK(device_name, QCLOUD_ERR_FAILURE);
pre_session = cur_session = gateway->session_list;
if (NULL == cur_session) {
Log_e("session list is empty");
IOT_FUNC_EXIT_RC(QCLOUD_RET_SUCCESS);
}
/* session is exist */
while (cur_session) {
if (0 == strcmp(cur_session->product_id, product_id) &&
0 == strcmp(cur_session->device_name, device_name) ) {
if (cur_session == gateway->session_list) {
gateway->session_list = cur_session->next;
} else {
pre_session->next = cur_session->next;
}
HAL_Free(cur_session);
IOT_FUNC_EXIT_RC(QCLOUD_RET_SUCCESS);
}
pre_session = cur_session;
cur_session = cur_session->next;
}
IOT_FUNC_EXIT_RC(QCLOUD_ERR_FAILURE);
}
int gateway_publish_sync(Gateway *gateway, char *topic, PublishParams *params, int32_t *result)
{
int rc = 0;
int loop_count = 0;
int32_t res = *result;
POINTER_SANITY_CHECK(gateway, QCLOUD_ERR_INVAL);
rc = IOT_Gateway_Publish(gateway, topic, params);
if (rc < 0) {
Log_e("publish fail.");
IOT_FUNC_EXIT_RC(QCLOUD_ERR_FAILURE);
}
/* wait for response */
while (res == *result) {
if (loop_count > GATEWAY_LOOP_MAX_COUNT) {
Log_i("loop max count, time out.");
IOT_FUNC_EXIT_RC(QCLOUD_ERR_GATEWAY_SESSION_TIMEOUT);
}
#ifndef MULTITHREAD_ENABLED
IOT_Gateway_Yield(gateway, 200);
#else
HAL_SleepMs(1);
#endif
loop_count++;
}
if (*result != 0) {
IOT_FUNC_EXIT_RC(QCLOUD_ERR_FAILURE);
}
IOT_FUNC_EXIT_RC(QCLOUD_RET_SUCCESS);
}

View File

@@ -35,26 +35,26 @@ extern "C" {
#define OTA_VERSION_STR_LEN_MAX (32)
typedef struct {
const char *product_id; /* point to product id */
const char *device_name; /* point to device name */
const char *product_id; /* point to product id */
const char *device_name; /* point to device name */
uint32_t id; /* message id */
IOT_OTA_State_Code state; /* OTA state */
uint32_t size_last_fetched; /* size of last downloaded */
uint32_t size_fetched; /* size of already downloaded */
uint32_t size_file; /* size of file */
uint32_t id; /* message id */
IOT_OTA_State_Code state; /* OTA state */
uint32_t size_last_fetched; /* size of last downloaded */
uint32_t size_fetched; /* size of already downloaded */
uint32_t size_file; /* size of file */
char *purl; /* point to URL */
char *version; /* point to string */
char md5sum[33]; /* MD5 string */
char *purl; /* point to URL */
char *version; /* point to string */
char md5sum[33]; /* MD5 string */
void *md5; /* MD5 handle */
void *ch_signal; /* channel handle of signal exchanged with OTA server */
void *ch_fetch; /* channel handle of download */
void *md5; /* MD5 handle */
void *ch_signal; /* channel handle of signal exchanged with OTA server */
void *ch_fetch; /* channel handle of download */
int err; /* last error code */
int err; /* last error code */
short current_signal_type;
short current_signal_type;
Timer report_timer;
@@ -70,7 +70,8 @@ static int _ota_check_progress(IOT_OTA_Progress_Code progress)
}
/* callback when OTA topic msg is received */
static void _ota_callback(void *pcontext, const char *msg, uint32_t msg_len) {
static void _ota_callback(void *pcontext, const char *msg, uint32_t msg_len)
{
#define OTA_JSON_TYPE_VALUE_LENGTH 64
char *json_type = NULL;
@@ -83,8 +84,8 @@ static void _ota_callback(void *pcontext, const char *msg, uint32_t msg_len) {
}
if (msg == NULL || msg_len <= 0) {
Log_e("OTA response message is NULL");
return;
Log_e("OTA response message is NULL");
return;
}
if (qcloud_otalib_get_firmware_type(msg, &json_type) != QCLOUD_RET_SUCCESS) {
@@ -93,29 +94,27 @@ static void _ota_callback(void *pcontext, const char *msg, uint32_t msg_len) {
}
if (!strcmp(json_type, REPORT_VERSION_RSP)) {
if (qcloud_otalib_get_report_version_result(msg) < QCLOUD_RET_SUCCESS) {
if (qcloud_otalib_get_report_version_result(msg) < QCLOUD_RET_SUCCESS) {
Log_e("Report version failed!");
h_ota->err = IOT_OTA_ERR_REPORT_VERSION;
h_ota->state = IOT_OTAS_FETCHED;
}
else {
Log_i("Report version success!");
}
goto End;
}
else {
} else {
Log_i("Report version success!");
}
goto End;
} else {
if (strcmp(json_type, UPDATE_FIRMWARE) != 0) {
Log_e("Netheir Report version result nor update firmware! type: %s", json_type);
Log_e("Netheir Report version result nor update firmware! type: %s", json_type);
goto End;
}
if(NULL != json_type) {
if (NULL != json_type) {
HAL_Free(json_type);
json_type = NULL;
}
if (0 != qcloud_otalib_get_params(msg, &json_type, &h_ota->purl, &h_ota->version,
h_ota->md5sum, &h_ota->size_file)) {
h_ota->md5sum, &h_ota->size_file)) {
Log_e("Get firmware parameter failed");
goto End;
}
@@ -124,16 +123,16 @@ static void _ota_callback(void *pcontext, const char *msg, uint32_t msg_len) {
}
End:
if (json_type != NULL) HAL_Free(json_type);
if (json_type != NULL) HAL_Free(json_type);
#undef OTA_JSON_TYPE_VALUE_LENGTH
}
static void IOT_OTA_ResetStatus(void *handle)
{
OTA_Struct_t *h_ota = (OTA_Struct_t *) handle;
h_ota->state = IOT_OTAS_INITED;
}
OTA_Struct_t *h_ota = (OTA_Struct_t *) handle;
h_ota->state = IOT_OTAS_INITED;
}
static int IOT_OTA_ReportProgress(void *handle, IOT_OTA_Progress_Code progress, IOT_OTAReportType reportType)
{
@@ -197,7 +196,7 @@ static int IOT_OTA_ReportUpgradeResult(void *handle, const char *version, IOT_OT
POINTER_SANITY_CHECK(handle, IOT_OTA_ERR_INVALID_PARAM);
POINTER_SANITY_CHECK(version, IOT_OTA_ERR_INVALID_PARAM);
int ret, len;
char *msg_upgrade;
OTA_Struct_t *h_ota = (OTA_Struct_t *)handle;
@@ -254,7 +253,7 @@ void *IOT_OTA_Init(const char *product_id, const char *device_name, void *ch_sig
POINTER_SANITY_CHECK(product_id, NULL);
POINTER_SANITY_CHECK(device_name, NULL);
POINTER_SANITY_CHECK(ch_signal, NULL);
OTA_Struct_t *h_ota = NULL;
if (NULL == (h_ota = HAL_Malloc(sizeof(OTA_Struct_t)))) {
@@ -341,31 +340,31 @@ int IOT_OTA_Destroy(void *handle)
/*support continuous transmission of breakpoints*/
int IOT_OTA_StartDownload(void *handle, uint32_t offset, uint32_t size)
{
OTA_Struct_t *h_ota = (OTA_Struct_t *) handle;
int Ret;
OTA_Struct_t *h_ota = (OTA_Struct_t *) handle;
int Ret;
h_ota->size_fetched += offset;
h_ota->ch_fetch = ofc_Init(h_ota->purl, offset, size);
h_ota->size_fetched = offset;
h_ota->ch_fetch = ofc_Init(h_ota->purl, offset, size);
if (NULL == h_ota->ch_fetch) {
Log_e("Initialize fetch module failed");
return QCLOUD_ERR_FAILURE;
return QCLOUD_ERR_FAILURE;
}
Ret = qcloud_ofc_connect(h_ota->ch_fetch);
Ret = qcloud_ofc_connect(h_ota->ch_fetch);
if (QCLOUD_RET_SUCCESS != Ret) {
Log_e("Connect fetch module failed");
h_ota->state = IOT_OTAS_DISCONNECTED;
h_ota->state = IOT_OTAS_DISCONNECTED;
}
return Ret;
return Ret;
}
/*support continuous transmission of breakpoints*/
void IOT_OTA_UpdateClientMd5(void *handle, char * buff, uint32_t size)
{
OTA_Struct_t *h_ota = (OTA_Struct_t *) handle;
OTA_Struct_t *h_ota = (OTA_Struct_t *) handle;
qcloud_otalib_md5_update(h_ota->md5, buff, size);
qcloud_otalib_md5_update(h_ota->md5, buff, size);
}
int IOT_OTA_ReportVersion(void *handle, const char *version)
@@ -433,31 +432,31 @@ int IOT_OTA_ReportUpgradeBegin(void *handle)
int IOT_OTA_ReportUpgradeSuccess(void *handle, const char *version)
{
OTA_Struct_t *h_ota = (OTA_Struct_t *) handle;
int ret;
OTA_Struct_t *h_ota = (OTA_Struct_t *) handle;
int ret;
if(NULL == version){
ret = IOT_OTA_ReportUpgradeResult(handle, h_ota->version, IOT_OTAR_UPGRADE_SUCCESS);
}else{
ret = IOT_OTA_ReportUpgradeResult(handle, version, IOT_OTAR_UPGRADE_SUCCESS);
}
return ret;
if (NULL == version) {
ret = IOT_OTA_ReportUpgradeResult(handle, h_ota->version, IOT_OTAR_UPGRADE_SUCCESS);
} else {
ret = IOT_OTA_ReportUpgradeResult(handle, version, IOT_OTAR_UPGRADE_SUCCESS);
}
return ret;
}
int IOT_OTA_ReportUpgradeFail(void *handle, const char *version)
{
OTA_Struct_t *h_ota = (OTA_Struct_t *) handle;
int ret;
OTA_Struct_t *h_ota = (OTA_Struct_t *) handle;
int ret;
if(NULL == version){
ret = IOT_OTA_ReportUpgradeResult(handle, h_ota->version, IOT_OTAR_UPGRADE_FAIL);
}else{
ret = IOT_OTA_ReportUpgradeResult(handle, version, IOT_OTAR_UPGRADE_FAIL);
}
return ret;
if (NULL == version) {
ret = IOT_OTA_ReportUpgradeResult(handle, h_ota->version, IOT_OTAR_UPGRADE_FAIL);
} else {
ret = IOT_OTA_ReportUpgradeResult(handle, version, IOT_OTAR_UPGRADE_FAIL);
}
return ret;
}
@@ -529,8 +528,8 @@ int IOT_OTA_FetchYield(void *handle, char *buf, uint32_t buf_len, uint32_t timeo
} else if (ret == IOT_OTA_ERR_FETCH_TIMEOUT) { // fetch timeout
IOT_OTA_ReportUpgradeResult(h_ota, h_ota->version, IOT_OTAR_DOWNLOAD_TIMEOUT);
h_ota->err = ret;
}
}
return ret;
} else if (0 == h_ota->size_fetched) {
/* force report status in the first */

View File

@@ -41,30 +41,30 @@ typedef struct {
} OTAHTTPStruct;
static int is_begin_with(const char * str1,char *str2)
#ifdef OTA_USE_HTTPS
static int is_begin_with(const char * str1, char *str2)
{
if(str1 == NULL || str2 == NULL)
if (str1 == NULL || str2 == NULL)
return -1;
int len1 = strlen(str1);
int len2 = strlen(str2);
if((len1 < len2) || (len1 == 0 || len2 == 0))
if ((len1 < len2) || (len1 == 0 || len2 == 0))
return -1;
char *p = str2;
int i = 0;
while(*p != '\0')
{
if(*p != str1[i])
return 0;
while (*p != '\0') {
if (*p != str1[i])
return 0;
p++;
i++;
}
return 1;
}
#endif
static char sg_head_content[OTA_HTTP_HEAD_CONTENT_LEN];
void *ofc_Init(const char *url, uint32_t offset, uint32_t size)
{
{
OTAHTTPStruct *h_odc;
if (NULL == (h_odc = HAL_Malloc(sizeof(OTAHTTPStruct)))) {
@@ -73,14 +73,14 @@ void *ofc_Init(const char *url, uint32_t offset, uint32_t size)
}
memset(h_odc, 0, sizeof(OTAHTTPStruct));
memset(sg_head_content, 0, OTA_HTTP_HEAD_CONTENT_LEN);
HAL_Snprintf(sg_head_content, OTA_HTTP_HEAD_CONTENT_LEN,\
"Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8\r\n"\
"Accept-Encoding: gzip, deflate\r\n"\
"Range: bytes=%d-%d\r\n",
offset, size);
memset(sg_head_content, 0, OTA_HTTP_HEAD_CONTENT_LEN);
HAL_Snprintf(sg_head_content, OTA_HTTP_HEAD_CONTENT_LEN, \
"Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8\r\n"\
"Accept-Encoding: gzip, deflate\r\n"\
"Range: bytes=%d-%d\r\n",
offset, size);
Log_d("head_content:%s", sg_head_content);
Log_d("head_content:%s", sg_head_content);
/* set http request-header parameter */
h_odc->http.header = sg_head_content;
h_odc->url = url;
@@ -97,11 +97,12 @@ int32_t qcloud_ofc_connect(void *handle)
int port = 80;
const char *ca_crt = NULL;
if (is_begin_with(h_odc->url, "https"))
{
#ifdef OTA_USE_HTTPS
if (is_begin_with(h_odc->url, "https")) {
port = 443;
ca_crt = iot_https_ca_get();
}
#endif
int32_t rc = qcloud_http_client_common(&h_odc->http, h_odc->url, port, ca_crt, HTTP_GET, &h_odc->http_data);
@@ -119,18 +120,18 @@ int32_t qcloud_ofc_fetch(void *handle, char *buf, uint32_t bufLen, uint32_t time
h_odc->http_data.response_buf = buf;
h_odc->http_data.response_buf_len = bufLen;
diff = h_odc->http_data.response_content_len - h_odc->http_data.retrieve_len;
int rc = qcloud_http_recv_data(&h_odc->http, timeout_s * 1000, &h_odc->http_data);
if (QCLOUD_RET_SUCCESS != rc) {
if (rc == QCLOUD_ERR_HTTP_NOT_FOUND)
IOT_FUNC_EXIT_RC(IOT_OTA_ERR_FETCH_NOT_EXIST);
if (rc == QCLOUD_ERR_HTTP_AUTH)
IOT_FUNC_EXIT_RC(IOT_OTA_ERR_FETCH_AUTH_FAIL);
if (rc == QCLOUD_ERR_HTTP_TIMEOUT)
IOT_FUNC_EXIT_RC(IOT_OTA_ERR_FETCH_TIMEOUT);
IOT_FUNC_EXIT_RC(rc);
}

View File

@@ -33,7 +33,7 @@ extern "C" {
/* Get the specific @key value, and copy to @dest */
/* 0, successful; -1, failed */
static int _qcloud_otalib_get_firmware_fixlen_para(const char *json_doc, const char *key,
char *dest, size_t dest_len)
char *dest, size_t dest_len)
{
IOT_FUNC_ENTRY;
@@ -41,17 +41,17 @@ static int _qcloud_otalib_get_firmware_fixlen_para(const char *json_doc, const c
char* key_bak = HAL_Malloc(strlen(key) + 1);
if (key_bak == NULL) {
Log_e("not enough memory for malloc key");
ret = IOT_OTA_ERR_FAIL;
IOT_FUNC_EXIT_RC(ret);
Log_e("not enough memory for malloc key");
ret = IOT_OTA_ERR_FAIL;
IOT_FUNC_EXIT_RC(ret);
}
char* json_doc_bak = HAL_Malloc(strlen(json_doc) + 1);
if (json_doc_bak == NULL) {
Log_e("not enough memory for malloc json");
HAL_Free(key_bak);
ret = IOT_OTA_ERR_FAIL;
IOT_FUNC_EXIT_RC(ret);
Log_e("not enough memory for malloc json");
HAL_Free(key_bak);
ret = IOT_OTA_ERR_FAIL;
IOT_FUNC_EXIT_RC(ret);
}
strcpy(key_bak, key);
@@ -59,29 +59,27 @@ static int _qcloud_otalib_get_firmware_fixlen_para(const char *json_doc, const c
char* value = LITE_json_value_of(key_bak, json_doc_bak);
if (value == NULL) {
Log_e("Not '%s' key in json doc of OTA", key);
ret = IOT_OTA_ERR_FAIL;
}
else {
uint32_t val_len = strlen(value);
if (val_len > dest_len) {
Log_e("value length of the key is too long");
ret = IOT_OTA_ERR_FAIL;
}
else {
memcpy(dest, value, val_len);
ret = QCLOUD_RET_SUCCESS;
}
Log_e("Not '%s' key in json doc of OTA", key);
ret = IOT_OTA_ERR_FAIL;
} else {
uint32_t val_len = strlen(value);
if (val_len > dest_len) {
Log_e("value length of the key is too long");
ret = IOT_OTA_ERR_FAIL;
} else {
memcpy(dest, value, val_len);
ret = QCLOUD_RET_SUCCESS;
}
HAL_Free(value);
HAL_Free(value);
}
if (key_bak != NULL) {
HAL_Free(key_bak);
}
if (json_doc_bak != NULL) {
HAL_Free(json_doc_bak);
}
if (key_bak != NULL) {
HAL_Free(key_bak);
}
if (json_doc_bak != NULL) {
HAL_Free(json_doc_bak);
}
IOT_FUNC_EXIT_RC(ret);
}
@@ -99,17 +97,17 @@ static int _qcloud_otalib_get_firmware_varlen_para(const char *json_doc, const c
char* key_bak = HAL_Malloc(strlen(key) + 1);
if (key_bak == NULL) {
Log_e("not enough memory for malloc key");
ret = IOT_OTA_ERR_FAIL;
IOT_FUNC_EXIT_RC(ret);
Log_e("not enough memory for malloc key");
ret = IOT_OTA_ERR_FAIL;
IOT_FUNC_EXIT_RC(ret);
}
char* json_doc_bak = HAL_Malloc(strlen(json_doc) + 1);
if (json_doc_bak == NULL) {
Log_e("not enough memory for malloc json");
HAL_Free(key_bak);
ret = IOT_OTA_ERR_FAIL;
IOT_FUNC_EXIT_RC(ret);
Log_e("not enough memory for malloc json");
HAL_Free(key_bak);
ret = IOT_OTA_ERR_FAIL;
IOT_FUNC_EXIT_RC(ret);
}
strcpy(key_bak, key);
@@ -117,16 +115,16 @@ static int _qcloud_otalib_get_firmware_varlen_para(const char *json_doc, const c
*dest = LITE_json_value_of(key_bak, json_doc_bak);
if (*dest == NULL) {
Log_e("Not '%s' key in json '%s' doc of OTA", key_bak, json_doc_bak);
ret = IOT_OTA_ERR_FAIL;
Log_e("Not '%s' key in json '%s' doc of OTA", key_bak, json_doc_bak);
ret = IOT_OTA_ERR_FAIL;
}
if (key_bak != NULL) {
HAL_Free(key_bak);
}
if (json_doc_bak != NULL) {
HAL_Free(json_doc_bak);
}
if (key_bak != NULL) {
HAL_Free(key_bak);
}
if (json_doc_bak != NULL) {
HAL_Free(json_doc_bak);
}
IOT_FUNC_EXIT_RC(ret);
@@ -184,16 +182,16 @@ int qcloud_otalib_get_report_version_result(const char *json)
int rc = _qcloud_otalib_get_firmware_varlen_para(json, RESULT_FIELD, &result_code);
if ( rc != QCLOUD_RET_SUCCESS || strcmp(result_code, "0") != 0) {
if(NULL != result_code) HAL_Free(result_code);
if (NULL != result_code) HAL_Free(result_code);
IOT_FUNC_EXIT_RC(IOT_OTA_ERR_FAIL);
}
if(NULL != result_code) HAL_Free(result_code);
if (NULL != result_code) HAL_Free(result_code);
IOT_FUNC_EXIT_RC(QCLOUD_RET_SUCCESS);
}
int qcloud_otalib_get_params(const char *json, char **type, char **url, char **version, char *md5,
uint32_t *fileSize)
uint32_t *fileSize)
{
#define OTA_FILESIZE_STR_LEN (16)
@@ -266,45 +264,45 @@ int qcloud_otalib_gen_report_msg(char *buf, size_t bufLen, uint32_t id, const ch
switch (reportType) {
/* report OTA download begin */
case IOT_OTAR_DOWNLOAD_BEGIN:
ret = HAL_Snprintf(buf,
bufLen,
"{\"type\": \"report_progress\", \"report\": {\"progress\": {\"state\":\"downloading\", \"percent\":\"0\", \"result_code\":\"0\", \"result_msg\":\"\"}, \"version\": \"%s\"}}", version);
break;
ret = HAL_Snprintf(buf,
bufLen,
"{\"type\": \"report_progress\", \"report\": {\"progress\": {\"state\":\"downloading\", \"percent\":\"0\", \"result_code\":\"0\", \"result_msg\":\"\"}, \"version\": \"%s\"}}", version);
break;
/* report OTA download progress */
case IOT_OTAR_DOWNLOADING:
ret = HAL_Snprintf(buf,
bufLen,
"{\"type\": \"report_progress\", \"report\": {\"progress\": {\"state\":\"downloading\", \"percent\":\"%d\", \"result_code\":\"0\", \"result_msg\":\"\"}, \"version\": \"%s\"}}",
progress, version);
break;
ret = HAL_Snprintf(buf,
bufLen,
"{\"type\": \"report_progress\", \"report\": {\"progress\": {\"state\":\"downloading\", \"percent\":\"%d\", \"result_code\":\"0\", \"result_msg\":\"\"}, \"version\": \"%s\"}}",
progress, version);
break;
case IOT_OTAR_DOWNLOAD_TIMEOUT:
case IOT_OTAR_FILE_NOT_EXIST:
case IOT_OTAR_MD5_NOT_MATCH:
case IOT_OTAR_AUTH_FAIL:
case IOT_OTAR_UPGRADE_FAIL:
ret = HAL_Snprintf(buf,
bufLen,
"{\"type\": \"report_progress\", \"report\": {\"progress\": {\"state\":\"fail\", \"result_code\":\"%d\", \"result_msg\":\"time_out\"}, \"version\": \"%s\"}}", reportType, version);
break;
ret = HAL_Snprintf(buf,
bufLen,
"{\"type\": \"report_progress\", \"report\": {\"progress\": {\"state\":\"fail\", \"result_code\":\"%d\", \"result_msg\":\"time_out\"}, \"version\": \"%s\"}}", reportType, version);
break;
/* report OTA upgrade begin */
case IOT_OTAR_UPGRADE_BEGIN:
ret = HAL_Snprintf(buf,
bufLen,
"{\"type\": \"report_progress\", \"report\":{\"progress\":{\"state\":\"burning\", \"result_code\":\"0\", \"result_msg\":\"\"}, \"version\":\"%s\"}}",
version);
break;
ret = HAL_Snprintf(buf,
bufLen,
"{\"type\": \"report_progress\", \"report\":{\"progress\":{\"state\":\"burning\", \"result_code\":\"0\", \"result_msg\":\"\"}, \"version\":\"%s\"}}",
version);
break;
/* report OTA upgrade finish */
case IOT_OTAR_UPGRADE_SUCCESS:
ret = HAL_Snprintf(buf,
bufLen,
"{\"type\": \"report_progress\", \"report\":{\"progress\":{\"state\":\"done\", \"result_code\":\"0\", \"result_msg\":\"\"}, \"version\":\"%s\"}}",
version);
break;
ret = HAL_Snprintf(buf,
bufLen,
"{\"type\": \"report_progress\", \"report\":{\"progress\":{\"state\":\"done\", \"result_code\":\"0\", \"result_msg\":\"\"}, \"version\":\"%s\"}}",
version);
break;
default:
IOT_FUNC_EXIT_RC(IOT_OTA_ERR_FAIL);
break;
IOT_FUNC_EXIT_RC(IOT_OTA_ERR_FAIL);
break;
}

View File

@@ -28,13 +28,13 @@ extern "C" {
/* OSC, OTA signal channel */
typedef struct {
void *mqtt; //MQTT cient
void *mqtt; //MQTT cient
const char *product_id;
const char *device_name;
const char *product_id;
const char *device_name;
char topic_upgrade[OTA_MAX_TOPIC_LEN]; //OTA MQTT Topic
OnOTAMessageCallback msg_callback;
char topic_upgrade[OTA_MAX_TOPIC_LEN]; //OTA MQTT Topic
OnOTAMessageCallback msg_callback;
void *context;
} OTA_MQTT_Struct_t;
@@ -50,7 +50,7 @@ static int _otamqtt_gen_topic_name(char *buf, size_t bufLen, const char *OTATopi
ret = HAL_Snprintf(buf, bufLen, "$ota/%s/%s/%s", OTATopicType, productId, deviceName);
if(ret >= bufLen) IOT_FUNC_EXIT_RC(IOT_OTA_ERR_FAIL);
if (ret >= bufLen) IOT_FUNC_EXIT_RC(IOT_OTA_ERR_FAIL);
if (ret < 0) {
Log_e("HAL_Snprintf failed");
@@ -80,8 +80,8 @@ static int _otamqtt_publish(OTA_MQTT_Struct_t *handle, const char *topicType, in
/* inform OTA to topic: "/ota/device/progress/$(product_id)/$(device_name)" */
ret = _otamqtt_gen_topic_name(topic_name, OTA_MAX_TOPIC_LEN, topicType, handle->product_id, handle->device_name);
if (ret < 0) {
Log_e("generate topic name of info failed");
IOT_FUNC_EXIT_RC(IOT_OTA_ERR_FAIL);
Log_e("generate topic name of info failed");
IOT_FUNC_EXIT_RC(IOT_OTA_ERR_FAIL);
}
ret = IOT_MQTT_Publish(handle->mqtt, topic_name, &pub_params);
@@ -147,7 +147,7 @@ void *qcloud_osc_init(const char *productId, const char *deviceName, void *chann
do_exit:
if (NULL != h_osc) {
HAL_Free(h_osc);
HAL_Free(h_osc);
}
return NULL;
@@ -182,7 +182,7 @@ int qcloud_osc_report_upgrade_result(void *handle, const char *msg)
return _otamqtt_publish(handle, "report", QOS1, msg);
}
#endif
#endif
#ifdef __cplusplus
}

View File

@@ -25,7 +25,7 @@ extern "C" {
#include "qcloud_iot_import.h"
#ifdef SYSTEM_COMM
#ifdef SYSTEM_COMM
#include "qcloud_iot_export_system.h"
#include "mqtt_client.h"
@@ -35,27 +35,28 @@ extern "C" {
typedef struct _sys_mqtt_state {
bool topic_sub_ok;
bool result_recv_ok;
long time;
}SysMQTTState;
long time;
} SysMQTTState;
static SysMQTTState sg_state = {
.topic_sub_ok = false,
.result_recv_ok = false,
.time = 0};
.topic_sub_ok = false,
.result_recv_ok = false,
.time = 0
};
static void _system_mqtt_message_callback(void *pClient, MQTTMessage *message, void *pUserData)
{
#define MAX_RECV_LEN (512)
POINTER_SANITY_CHECK_RTN(message);
POINTER_SANITY_CHECK_RTN(message);
static char rcv_buf[MAX_RECV_LEN + 1];
size_t len = (message->payload_len > MAX_RECV_LEN)?MAX_RECV_LEN:(message->payload_len);
size_t len = (message->payload_len > MAX_RECV_LEN) ? MAX_RECV_LEN : (message->payload_len);
if(message->payload_len > MAX_RECV_LEN){
Log_e("payload len oversize");
}
if (message->payload_len > MAX_RECV_LEN) {
Log_e("payload len oversize");
}
memcpy(rcv_buf, message->payload, len);
rcv_buf[len] = '\0'; // jsmn_parse relies on a string
SysMQTTState *state = (SysMQTTState *)pUserData;
@@ -75,28 +76,28 @@ static void _system_mqtt_sub_event_handler(void *pclient, MQTTEventType event_ty
{
SysMQTTState *state = (SysMQTTState *)pUserData;
switch(event_type) {
switch (event_type) {
case MQTT_EVENT_SUBCRIBE_SUCCESS:
Log_d("mqtt sys topic subscribe success");
state->topic_sub_ok = true;
state->topic_sub_ok = true;
break;
case MQTT_EVENT_SUBCRIBE_TIMEOUT:
Log_i("mqtt sys topic subscribe timeout");
state->topic_sub_ok = false;
state->topic_sub_ok = false;
break;
case MQTT_EVENT_SUBCRIBE_NACK:
Log_i("mqtt sys topic subscribe NACK");
state->topic_sub_ok = false;
state->topic_sub_ok = false;
break;
case MQTT_EVENT_UNSUBSCRIBE:
Log_i("mqtt sys topic has been unsubscribed");
state->topic_sub_ok = false;;
state->topic_sub_ok = false;;
break;
case MQTT_EVENT_CLIENT_DESTROY:
Log_i("mqtt client has been destroyed");
state->topic_sub_ok = false;;
state->topic_sub_ok = false;;
break;
default:
return;
@@ -122,7 +123,7 @@ static int _iot_system_info_get_publish(void *pClient)
pub_params.payload = payload_content;
pub_params.payload_len = strlen(payload_content);
return IOT_MQTT_Publish(mqtt_client, topic_name, &pub_params);
return IOT_MQTT_Publish(mqtt_client, topic_name, &pub_params);
}
static int _iot_system_info_result_subscribe(void *pClient)
@@ -134,8 +135,7 @@ static int _iot_system_info_result_subscribe(void *pClient)
char topic_name[128] = {0};
int size = HAL_Snprintf(topic_name, sizeof(topic_name), "$sys/operation/result/%s/%s", dev_info->product_id, dev_info->device_name);
if (size < 0 || size > sizeof(topic_name) - 1)
{
if (size < 0 || size > sizeof(topic_name) - 1) {
Log_e("topic content length not enough! content size:%d buf size:%d", size, (int)sizeof(topic_name));
return QCLOUD_ERR_FAILURE;
}
@@ -159,8 +159,8 @@ int IOT_Get_SysTime(void* pClient, long *time)
// subscribe sys topic: $sys/operation/get/${productid}/${devicename}
// skip this if the subscription is done and valid
if(!sg_state.topic_sub_ok){
for(cntSub = 0; cntSub < 3; cntSub++){
if (!sg_state.topic_sub_ok) {
for (cntSub = 0; cntSub < 3; cntSub++) {
ret = _iot_system_info_result_subscribe(mqtt_client);
if (ret < 0) {
Log_w("_iot_system_info_result_subscribe failed: %d, cnt: %d", ret, cntSub);
@@ -169,39 +169,39 @@ int IOT_Get_SysTime(void* pClient, long *time)
/* wait for sub ack */
ret = qcloud_iot_mqtt_yield((Qcloud_IoT_Client *)pClient, 100);
if(sg_state.topic_sub_ok) {
if (sg_state.topic_sub_ok) {
break;
}
}
}
// return failure if subscribe failed
if(!sg_state.topic_sub_ok){
if (!sg_state.topic_sub_ok) {
Log_e("Subscribe sys topic failed!");
return QCLOUD_ERR_FAILURE;
}
sg_state.result_recv_ok = false;
// publish msg to get system timestamp
ret = _iot_system_info_get_publish(mqtt_client);
if (ret < 0) {
Log_e("client publish sys topic failed :%d.", ret);
ret = _iot_system_info_get_publish(mqtt_client);
if (ret < 0) {
Log_e("client publish sys topic failed :%d.", ret);
return ret;
}
}
do {
ret = qcloud_iot_mqtt_yield((Qcloud_IoT_Client *)pClient, 100);
cntRev++;
} while(!sg_state.result_recv_ok && cntRev < 20);
} while (!sg_state.result_recv_ok && cntRev < 20);
if (sg_state.result_recv_ok) {
if (sg_state.result_recv_ok) {
*time = sg_state.time;
ret = QCLOUD_RET_SUCCESS;
ret = QCLOUD_RET_SUCCESS;
} else {
*time = 0;
ret = QCLOUD_ERR_FAILURE;
}
}
return ret;
}