merge new qcloud sdk

1. qcloud has a great revolution, the protocol has been changed to implement data template, so the old TencentCloud_SDK developed by us will not work fine now(mqtt still works, but data template will not works fine for recently created product/devices).

2. I merge the official qlcoud sdk(include both the iot-hub and iot-explorer sdk) into the componet/conectivity to support new protocol of data template

3. iot-hub sdk, supply the fundamental iot protocol(like mqtt coap, etc.)
iot-explorer sdk, supply the high level service like data template based on mqtt

4. To know how it works, see qcloud_iot_explorer_sdk_data_template、qcloud_iot_hub_sdk_mqtt example(keil project in board\TencentOS_tiny_EVB_MX_Plus\KEIL\qcloud_iot_explorer_sdk_data_template and  board\TencentOS_tiny_EVB_MX_Plus\KEIL\qcloud_iot_hub_sdk_mqtt)
This commit is contained in:
daishengdong
2019-11-14 15:09:00 +08:00
parent 5d86548c23
commit 943db74fc7
705 changed files with 297267 additions and 0 deletions

View File

@@ -0,0 +1,166 @@
/*
* Tencent is pleased to support the open source community by making IoT Hub available.
* Copyright (C) 2019 THL A29 Limited, a Tencent company. All rights reserved.
* Licensed under the MIT License (the "License"); you may not use this file except in
* compliance with the License. You may obtain a copy of the License at
* http://opensource.org/licenses/MIT
* Unless required by applicable law or agreed to in writing, software distributed under the License is
* distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
* either express or implied. See the License for the specific language governing permissions and
* limitations under the License.
*
*/
#ifndef __AT_CLIENT_H__
#define __AT_CLIENT_H__
#ifdef __cplusplus
extern "C" {
#endif
#include "utils_ringbuff.h"
#define AT_FRAME_VERSION "1.0.0"
#define AT_CMD_NAME_LEN 16
#define AT_END_MARK_LEN 4
#define CLINET_BUFF_LEN (1024)
#define RING_BUFF_LEN CLINET_BUFF_LEN //uart ring buffer len
#define GET_CHAR_TIMEOUT_MS (5000)
#define CMD_RESPONSE_INTERVAL_MS (100)
typedef void *(*ParserFunc)(void *userContex);
typedef enum
{
AT_STATUS_UNINITIALIZED = 0,
AT_STATUS_INITIALIZED = 0x55,
AT_STATUS_BUSY = 0xaa,
}at_status;
enum at_resp_status
{
AT_RESP_OK = 0, /* AT response end is OK */
AT_RESP_eLOG_ERROR = -1, /* AT response end is eLOG_ERROR */
AT_RESP_TIMEOUT = -2, /* AT response is timeout */
AT_RESP_BUFF_FULL= -3, /* AT response buffer is full */
};
typedef enum at_resp_status at_resp_status_t;
typedef struct _at_response_
{
/* response buffer */
char *buf;
/* the maximum response buffer size */
int buf_size;
/* the number of setting response lines
* == 0: the response data will auto return when received 'OK' or 'eLOG_ERROR'
* != 0: the response data will return when received setting lines number data */
int line_num;
/* the count of received response lines */
int line_counts;
/* the maximum response time */
uint32_t timeout;
}at_response;
typedef at_response * at_response_t;
/* URC(Unsolicited Result Code) object, such as: 'RING', 'READY' request by AT server */
typedef struct _at_urc_
{
const char *cmd_prefix;
const char *cmd_suffix;
void (*func)(const char *data, size_t size);
}at_urc;
typedef at_urc *at_urc_t;
typedef struct _at_client_
{
at_status status;
char end_sign;
ring_buff_t pRingBuff;
char *recv_buffer;
uint32_t recv_bufsz;
uint32_t cur_recv_len;
void *lock; //pre cmd take the lock wait for resp , another cmd need wait for unlock
at_response_t resp;
at_resp_status_t resp_status;
const at_urc *urc_table;
uint16_t urc_table_size;
#ifdef AT_OS_USED
volatile void *thread_t;
void *resp_sem; // resp received, send sem to notic ack wait
ParserFunc parser; // RX parser
#else
//bool resp_notice;
#endif
}at_client;
typedef at_client *at_client_t;
/* AT client initialize and start*/
int at_client_init(at_client_t *pClient);
/* AT client deinitial*/
int at_client_deinit(at_client_t pClient);
/* get AT client handle*/
at_client_t at_client_get(void);
/*AT connect detect*/
int at_client_wait_connect(uint32_t timeout);
/*wrapper for os and nonos delay*/
void at_delayms(uint32_t delayms);
void at_setFlag(uint32_t flag);
void at_clearFlag(uint32_t flag);
uint32_t at_getFlag(void);
bool at_waitFlag(uint32_t flag, uint32_t timeout);
/* ========================== multiple AT client function ============================ */
/* set AT client a line end sign */
void at_set_end_sign(char ch);
/* Set URC(Unsolicited Result Code) table */
void at_set_urc_table(at_client_t client, const at_urc_t table, uint32_t size);
/* AT client send or receive data */
int at_client_send(at_client_t client, const char *buf, int size, uint32_t timeout);
int at_client_obj_recv(char *buf, int size, int timeout);
/* AT client send commands to AT server and waiter response */
int at_obj_exec_cmd(at_response_t resp, const char *cmd_expr, ...);
#define at_exec_cmd(resp, ...) at_obj_exec_cmd(resp, __VA_ARGS__)
#define at_client_recv(buf, size, timeout) at_client_obj_recv(buf, size, timeout)
/* AT response object create and delete */
at_response_t at_create_resp(uint32_t buf_size, uint32_t line_num, uint32_t timeout);
void at_delete_resp(at_response_t resp);
/* AT response line buffer get and parse response buffer arguments */
const char *at_resp_get_line(at_response_t resp, uint32_t resp_line);
const char *at_resp_get_line_by_kw(at_response_t resp, const char *keyword);
int at_resp_parse_line_args(at_response_t resp, uint32_t resp_line, const char *resp_expr, ...);
int at_resp_parse_line_args_by_kw(at_response_t resp, const char *keyword, const char *resp_expr, ...);
/* ========================== single AT client function ============================ */
void at_client_yeild(at_urc *expect_urc, uint32_t timeout);
#ifdef __cplusplus
}
#endif
#endif /* __AT_H__ */

View File

@@ -0,0 +1,105 @@
/*
* Copyright (c) 2019-2021 Tencent Group. All rights reserved.
* License-Identifier: Apache-2.0
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
#ifndef _AT_SOCKET_INF_H_
#define _AT_SOCKET_INF_H_
#include <stdint.h>
#include <stdio.h>
#include "utils_list.h"
#define UNUSED_SOCKET (-1)
#define MAX_AT_SOCKET_NUM (5)
#define AT_SOCKET_SEND_TIMEOUT_MS (1000)
#define AT_SOCKET_RECV_TIMEOUT_MS (1000)
#define IPV4_STR_MAX_LEN (16)
typedef enum
{
eNET_TCP = 6,
eNET_UDP = 17,
eNET_DEFAULT = 0xff
}eNetProto;
typedef enum {
eSOCKET_ALLOCED = 0,
eSOCKET_CONNECTED ,
eSOCKET_CLOSED
}eSocketState;
/* AT receive package list structure */
typedef struct at_recv_pkt
{
List list;
size_t bfsz_totle;
size_t bfsz_index;
char *buff;
}at_recv_pkt;
typedef enum
{
AT_SOCKET_EVT_RECV = 0,
AT_SOCKET_EVT_CLOSED,
} at_socket_evt_t;
typedef void (*at_evt_cb_t)(int fd, at_socket_evt_t event, char *buff, size_t bfsz);
/*at device driver ops, use at_device_op_register register to at socket*/
typedef struct {
int (*init)(void);
int (*get_local_mac)(char *macbuff, size_t bufflen);
int (*get_local_ip)(char *ip, size_t iplen, char *gw, size_t gwlen, char *mask, size_t masklen);
int (*parse_domain)(const char *host_name, char *host_ip, size_t host_ip_len);
int (*connect)(const char *ip, uint16_t port, eNetProto proto);
int (*send)(int fd, const void *buf, size_t len);
int (*recv_timeout)(int fd, void *buf, size_t len, uint32_t timeout);
int (*close)(int fd);
void (*set_event_cb)(at_socket_evt_t event, at_evt_cb_t cb);
char *deviceName;
} at_device_op_t;
/*at socket context*/
typedef struct
{
int fd; /** socket fd */
List* recvpkt_list;
char remote_ip[IPV4_STR_MAX_LEN];
uint16_t remote_port;
uint32_t send_timeout_ms;
uint32_t recv_timeout_ms;
void *recv_lock;
at_device_op_t *dev_op;
eNetProto net_type;
eSocketState state;
}at_socket_ctx_t;
//at socket api
int at_device_op_register(at_device_op_t *device_op);
int at_socket_init(void);
int at_socket_parse_domain(const char *host_name, char *host_ip, size_t host_ip_len);
int at_socket_get_local_mac(char *macbuff, size_t bufflen);
int at_socket_get_local_ip(char *ip, size_t iplen, char *gw, size_t gwlen, char *mask, size_t masklen);
int at_socket_connect(const char *host, uint16_t port, eNetProto eProto);
int at_socket_close(int fd);
int at_socket_send(int fd, const void *buf, size_t len);
int at_socket_recv(int fd, void *buf, size_t len);
#endif

View File

@@ -0,0 +1,116 @@
/*
* Tencent is pleased to support the open source community by making IoT Hub available.
* Copyright (C) 2019 THL A29 Limited, a Tencent company. All rights reserved.
* Licensed under the MIT License (the "License"); you may not use this file except in
* compliance with the License. You may obtain a copy of the License at
* http://opensource.org/licenses/MIT
* Unless required by applicable law or agreed to in writing, software distributed under the License is
* distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
* either express or implied. See the License for the specific language governing permissions and
* limitations under the License.
*
*/
#ifndef __AT_UART_HAL_H__
#define __AT_UART_HAL_H__
/*
* UART data width
*/
typedef enum {
BAUDRATE_2400 = 2400,
BAUDRATE_4800 = 4800,
BAUDRATE_9600 = 9600,
BAUDRATE_19200 = 19200,
BAUDRATE_115200 = 115200,
BAUDRATE_921600 = 921600,
BAUDRATE_DEFAULT = 115200
} hal_uart_baudr_t;
/*
* UART data width
*/
typedef enum {
DATA_WIDTH_5BIT,
DATA_WIDTH_6BIT,
DATA_WIDTH_7BIT,
DATA_WIDTH_8BIT,
DATA_WIDTH_9BIT
} hal_uart_data_width_t;
/*
* UART stop bits
*/
typedef enum {
STOP_BITS_1,
STOP_BITS_2
} hal_uart_stop_bits_t;
/*
* UART flow control
*/
typedef enum {
FLOW_CONTROL_DISABLED,
FLOW_CONTROL_CTS,
FLOW_CONTROL_RTS,
FLOW_CONTROL_CTS_RTS
} hal_uart_flow_control_t;
/*
* UART parity
*/
typedef enum {
NO_PARITY,
ODD_PARITY,
EVEN_PARITY
} hal_uart_parity_t;
/*
* UART mode
*/
typedef enum {
MODE_TX,
MODE_RX,
MODE_TX_RX
} hal_uart_mode_t;
/*
* UART state
*/
typedef enum {
eUNUSED = 0,
eOPENED = 1,
eCLOSED = 2,
} hal_uart_state_t;
/*
* UART configuration
*/
typedef struct {
uint32_t baud_rate;
hal_uart_data_width_t data_width;
hal_uart_parity_t parity;
hal_uart_stop_bits_t stop_bits;
hal_uart_flow_control_t flow_control;
hal_uart_mode_t mode;
} uart_config_t;
typedef struct {
#ifdef __linux__
int fd; /* uart fd */
#else
void *uart_handle; /* uart handle,like stm32 UART_HandleTypeDef */
#endif
hal_uart_state_t state; /* uart state */
uart_config_t config; /* uart config */
} uart_dev_t;
#ifdef __cplusplus
}
#endif
#endif /* __AT_H__ */

View File

@@ -0,0 +1,49 @@
/*
* Copyright (c) 2019-2021 Tencent Group. All rights reserved.
* License-Identifier: Apache-2.0
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
#ifndef _AT_UTILS_H_
#define _AT_UTILS_H_
#include <stdlib.h>
#include <stdio.h>
#include <stdarg.h>
#define WIDTH_SIZE 32
#ifndef __INT_MAX__
#define __INT_MAX__ 2147483647
#endif
#ifndef INT_MAX
#define INT_MAX (__INT_MAX__)
#endif
#define AT_CMD_COMMA_MARK ','
#define AT_CMD_DQUOTES_MARK '"'
#define __is_print(ch) ((unsigned int)((ch) - ' ') < 127u - ' ')
int at_vprintfln(const char *format, va_list args);
void at_print_raw_cmd(const char *name, const char *cmd, int size);
const char *at_get_last_cmd(int *cmd_size);
int at_req_parse_args(const char *req_args, const char *req_expr, ...);
int at_sscanf(const char * buf, const char * fmt, va_list args);
void at_strip(char *str, const char patten);
void chr_strip(char *str, const char patten);
#endif

View File

@@ -0,0 +1,48 @@
/*
* Tencent is pleased to support the open source community by making IoT Hub available.
* Copyright (C) 2016 THL A29 Limited, a Tencent company. All rights reserved.
* Licensed under the MIT License (the "License"); you may not use this file except in
* compliance with the License. You may obtain a copy of the License at
* http://opensource.org/licenses/MIT
* Unless required by applicable law or agreed to in writing, software distributed under the License is
* distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
* either express or implied. See the License for the specific language governing permissions and
* limitations under the License.
*
*/
#ifndef _DATA_TEMPLATE_ACTION_H_
#define _DATA_TEMPLATE_ACTION_H_
#ifdef __cplusplus
extern "C" {
#endif
#include <stdint.h>
#include <stdbool.h>
#include <stdarg.h>
#include <stddef.h>
#define ACTION_NAME_MAX_LEN (20) // action name max len
#define ACTION_TOKEN_MAX_LEN (32) // action token max len
#define MAX_ACTION_WAIT_REPLY (10)
#define ACTION_MAX_DATA_NUM (255) // input or output max data num
#define REPORT_ACTION "action_reply"
#define CALL_ACTION "action"
int IOT_Action_Init(void *c);
int IOT_Action_Register(void *pTemplate, DeviceAction *pAction, OnActionHandleCallback callback);
int IOT_Action_Remove(void *ptemplate, DeviceAction *pAction);
#ifdef __cplusplus
}
#endif
#endif //_DATA_TEMPLATE_ACTION_H_

View File

@@ -0,0 +1,112 @@
/*
* Tencent is pleased to support the open source community by making IoT Hub available.
* Copyright (C) 2016 THL A29 Limited, a Tencent company. All rights reserved.
* Licensed under the MIT License (the "License"); you may not use this file except in
* compliance with the License. You may obtain a copy of the License at
* http://opensource.org/licenses/MIT
* Unless required by applicable law or agreed to in writing, software distributed under the License is
* distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
* either express or implied. See the License for the specific language governing permissions and
* limitations under the License.
*
*/
/**
* @brief API of data_template
*
*/
#ifndef IOT_TEMPLATE_CLIENT_H_
#define IOT_TEMPLATE_CLIENT_H_
#ifdef __cplusplus
extern "C" {
#endif
#include <stdbool.h>
#include "qcloud_iot_export.h"
#include "qcloud_iot_import.h"
#include "utils_param_check.h"
#include "data_template_client_json.h"
#include "qcloud_iot_device.h"
#include "mqtt_client.h"
#define MAX_CLEAE_DOC_LEN 256
typedef struct _TemplateInnerData {
uint32_t token_num;
int32_t sync_status;
uint32_t eventflags;
List *event_list;
List *reply_list;
List *action_handle_list;
List *property_handle_list;
char *upstream_topic; //upstream topic
char *downstream_topic; //downstream topic
} TemplateInnerData;
typedef struct _Template {
void *mqtt;
void *mutex;
MQTTEventHandler event_handle;
TemplateInnerData inner_data;
} Qcloud_IoT_Template;
/**
* @brief init data template client
*
* @param pTemplate handle to data_template client
*/
int qcloud_iot_template_init(Qcloud_IoT_Template *pTemplate);
/**
* @brief deinit data template client list and topics
*
* @param pClient data template client
*/
void qcloud_iot_template_reset(void *pClient);
/**
* @brief deal upstream msg wait for reply timeout
*
* @param pTemplate data template client
*/
void handle_template_expired_reply(Qcloud_IoT_Template *pTemplate);
/**
* @brief get the clientToken of control message for control_reply
*
* @param void
* @return clientToken
*/
char * get_control_clientToken(void);
/**
* @brief all the upstream data by the way of request
*
* @param pTemplate handle to data_template client
* @param pParams request params
* @param pJsonDoc data buffer for request
* @param sizeOfBuffer length of data buffer
* @return QCLOUD_RET_SUCCESS when success, or err code for failure
*/
int send_template_request(Qcloud_IoT_Template *pTemplate, RequestParams *pParams, char *pJsonDoc, size_t sizeOfBuffer);
/**
* @brief subscribe data_template topic $thing/down/property/%s/%s
*
* @param pShadow shadow client
* @return QCLOUD_RET_SUCCESS for success, or err code for failure
*/
int subscribe_template_downstream_topic(Qcloud_IoT_Template *pTemplate);
#ifdef __cplusplus
}
#endif
#endif /* IOT_TEMPLATE_CLIENT_H_ */

View File

@@ -0,0 +1,59 @@
/*
* Tencent is pleased to support the open source community by making IoT Hub available.
* Copyright (C) 2016 THL A29 Limited, a Tencent company. All rights reserved.
* Licensed under the MIT License (the "License"); you may not use this file except in
* compliance with the License. You may obtain a copy of the License at
* http://opensource.org/licenses/MIT
* Unless required by applicable law or agreed to in writing, software distributed under the License is
* distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
* either express or implied. See the License for the specific language governing permissions and
* limitations under the License.
*
*/
#ifndef IOT_DATA_TEMPLATE_CLIENT_COMMON_H_
#define IOT_DATA_TEMPLATE_CLIENT_COMMON_H_
#ifdef __cplusplus
extern "C" {
#endif
#include "data_template_client.h"
/**
* @brief register a device property
*
* @param pTemplate handle to data_template client
* @param pProperty device property
* @param callback callback when property changes
* @return QCLOUD_RET_SUCCESS for success, or err code for failure
*/
int template_common_register_property_on_delta(Qcloud_IoT_Template *pTemplate, DeviceProperty *pProperty, OnPropRegCallback callback);
/**
* @brief remove a device property
*
* @param pTemplate handle to data_template client
* @param pProperty device property
* @return QCLOUD_RET_SUCCESS for success, or err code for failure
*/
int template_common_remove_property(Qcloud_IoT_Template *ptemplate, DeviceProperty *pProperty);
/**
* @brief check if a device property exists
*
* @param pShadow handle to data_template client
* @param pProperty device property
* @return 0 = not existed
*/
int template_common_check_property_existence(Qcloud_IoT_Template *ptemplate, DeviceProperty *pProperty);
#ifdef __cplusplus
}
#endif
#endif //IOT_DATA_TEMPLATE_CLIENT_COMMON_H_

View File

@@ -0,0 +1,283 @@
/*
* Tencent is pleased to support the open source community by making IoT Hub available.
* Copyright (C) 2016 THL A29 Limited, a Tencent company. All rights reserved.
* Licensed under the MIT License (the "License"); you may not use this file except in
* compliance with the License. You may obtain a copy of the License at
* http://opensource.org/licenses/MIT
* Unless required by applicable law or agreed to in writing, software distributed under the License is
* distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
* either express or implied. See the License for the specific language governing permissions and
* limitations under the License.
*
*/
#ifndef UTILS_METHOD_H_
#define UTILS_METHOD_H_
#ifdef __cplusplus
extern "C" {
#endif
#include "qcloud_iot_export.h"
#include "qcloud_iot_import.h"
#define min(a,b) (a) < (b) ? (a) : (b)
/* Max number of requests in appending state */
#define MAX_APPENDING_REQUEST_AT_ANY_GIVEN_TIME (10)
/* Size of buffer to receive JSON document from server */
#define CLOUD_IOT_JSON_RX_BUF_LEN (QCLOUD_IOT_MQTT_RX_BUF_LEN + 1)
/* Max size of clientToken */
#define MAX_SIZE_OF_CLIENT_TOKEN (MAX_SIZE_OF_CLIENT_ID + 10)
/* Max size of JSON string which only contain clientToken field */
#define MAX_SIZE_OF_JSON_WITH_CLIENT_TOKEN (MAX_SIZE_OF_CLIENT_TOKEN + 20)
#define CLIENT_TOKEN_FIELD "clientToken"
#define METHOD_FIELD "method"
#define TYPE_FIELD "type"
#define ACTION_ID_FIELD "actionId"
#define TIME_STAMP_FIELD "timestamp"
#define REPLY_CODE "code"
#define REPLY_STATUS "status"
#define GET_STATUS "get_status" //method field for get_status
#define GET_STATUS_REPLY "get_status_reply" //method field for get_status reply
#define CONTROL_CMD "control" //method field for control msg
#define CONTROL_CMD_REPLY "control_reply" //method field for control msg reply
#define CLEAR_CONTROL "clear_control" //method field for clear control
#define REPORT_CMD "report" //method field for report
#define REPORT_CMD_REPLY "report_reply" //method field for report reply
#define INFO_CMD "report_info" //method field for report system informaiton
#define INFO_CMD_REPLY "report_info_reply" //method field for report system informaiton reply
#define GET_CONTROL_PARA "data.control"
#define CMD_CONTROL_PARA "params"
/**
* @brief define type of request parameters
*/
typedef struct _RequestParam {
Method method; // method type: GET, REPORT, RINFO, REPLY, CLEAR
uint32_t timeout_sec; // request timeout in second
OnReplyCallback request_callback; // request callback
void *user_context; // user context for callback
} RequestParams;
#define DEFAULT_REQUEST_PARAMS {GET, 4, NULL, NULL};
/**
* @brief type for document request
*/
typedef struct {
char client_token[MAX_SIZE_OF_CLIENT_TOKEN]; // clientToken
Method method; // method type
void *user_context; // user context
Timer timer; // timer for timeout
OnReplyCallback callback; // request response callback
} Request;
/**
* @brief for property and it's callback
*/
typedef struct {
void *property;
OnPropRegCallback callback;
} PropertyHandler;
/**
* @brief save the action registed and its callback
*/
typedef struct {
void *action;
OnActionHandleCallback callback;
} ActionHandler;
/**
* @brief check return value of snprintf
*
* @param returnCode return value of snprintf
* @param maxSizeOfWrite max size of write buffer
* @return QCLOUD_RET_SUCCESS for success, or err code for failure
*/
int check_snprintf_return(int32_t returnCode, size_t maxSizeOfWrite);
/**
* @brief insert source string to the dest string with specified position
*
* @param pSourceStr source string
* @param pDestStr dest string
* @param pos dest string positon
*/
void insert_str(char *pDestStr, char *pSourceStr, int pos);
/**
* add a JSON node to JSON string
*
* @param jsonBuffer JSON string buffer
* @param sizeOfBuffer size of buffer
* @param pKey key of JSON node
* @param pData value of JSON node
* @param type value type of JSON node
* @return QCLOUD_RET_SUCCESS for success, or err code for failure
*/
int put_json_node(char *jsonBuffer, size_t sizeOfBuffer, const char *pKey, void *pData, JsonDataType type);
/**
* add a JSON node to JSON string, data_template's bool type not the same to put_json_node
*
* @param jsonBuffer JSON string buffer
* @param sizeOfBuffer size of buffer
* @param pKey key of JSON node
* @param pData value of JSON node
* @param type value type of JSON node
* @return QCLOUD_RET_SUCCESS for success, or err code for failure
*/
int template_put_json_node(char *jsonBuffer, size_t sizeOfBuffer, const char *pKey, void *pData, JsonDataType type);
/**
* @brief generate a ClientToken
*
* @param pStrBuffer string buffer
* @param sizeOfBuffer size of buffer
* @param tokenNumber shadow token number, increment every time
* @return QCLOUD_RET_SUCCESS for success, or err code for failure
*/
int generate_client_token(char *pStrBuffer, size_t sizeOfBuffer, uint32_t *tokenNumber);
/**
* @brief generate an empty JSON with only clientToken
*
* @param tokenNumber shadow token number, increment every time
* @param pJsonBuffer JSON string buffer
*/
void build_empty_json(uint32_t *tokenNumber, char *pJsonBuffer);
/**
* @brief parse field of clientToken from JSON string
*
* @param pJsonDoc source JSON string
* @param pClientToken pointer to field of ClientToken
* @return true for success
*/
bool parse_client_token(char *pJsonDoc, char **pClientToken);
/**
* @brief parse field of aciont_id from JSON string
*
* @param pJsonDoc source JSON string
* @param pActionID pointer to field of action_id
* @return true for success
*/
bool parse_action_id(char *pJsonDoc, char **pActionID);
/**
* @brief parse field of timestamp from JSON string
*
* @param pJsonDoc source JSON string
* @param pTimestamp pointer to field of timestamp
* @return true for success
*/
bool parse_time_stamp(char *pJsonDoc, int32_t *pTimestamp);
/**
* @brief parse field of input from JSON string
*
* @param pJsonDoc source JSON string
* @param pActionInput filed of params as action input parameters
* @return true for success
*/
bool parse_action_input(char *pJsonDoc, char **pActionInput);
/**
* @brief parse field of status from JSON string
*
* @param pJsonDoc source JSON string
* @param pStatus pointer to field of status
* @return true for success
*/
bool parse_status_return(char *pJsonDoc, char **pStatus);
/**
* @brief parse field of code from JSON string
*
* @param pJsonDoc source JSON string
* @param pCode pointer to field of Code
* @return true for success
*/
bool parse_code_return(char *pJsonDoc, int32_t *pCode);
/**
* @brief update value in JSON if key is matched, not for OBJECT type
*
* @param pJsonDoc JSON string
* @param pProperty device property
* @return true for success
*/
bool update_value_if_key_match(char *pJsonDoc, DeviceProperty *pProperty);
/**
* @brief parse field of method from JSON string
*
* @param pJsonDoc source JSON string
* @param pMethod pointer to field of method
* @return true for success
*/
bool parse_template_method_type(char *pJsonDoc, char **pMethod);
/**
* @brief parse field of control from get_status_reply JSON string
*
* @param pJsonDoc source JSON string
* @param control pointer to field of control
* @return true for success
*/
bool parse_template_get_control(char *pJsonDoc, char **control);
/**
* @brief parse field of control from control JSON string
*
* @param pJsonDoc source JSON string
* @param control pointer to field of control
* @return true for success
*/
bool parse_template_cmd_control(char *pJsonDoc, char **control);
#ifdef __cplusplus
}
#endif
#endif /* QCLOUD_IOT_EXPORT_SHADOW_H_ */

View File

@@ -0,0 +1,69 @@
/*
* Tencent is pleased to support the open source community by making IoT Hub available.
* Copyright (C) 2016 THL A29 Limited, a Tencent company. All rights reserved.
* Licensed under the MIT License (the "License"); you may not use this file except in
* compliance with the License. You may obtain a copy of the License at
* http://opensource.org/licenses/MIT
* Unless required by applicable law or agreed to in writing, software distributed under the License is
* distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
* either express or implied. See the License for the specific language governing permissions and
* limitations under the License.
*
*/
#ifndef _DATA_TEMPLATE_EVENT_H_
#define _DATA_TEMPLATE_EVENT_H_
#ifdef __cplusplus
extern "C" {
#endif
#include <stdint.h>
#include <stdbool.h>
#include <stdarg.h>
#include <stddef.h>
#define NAME_MAX_LEN (32)
#define TYPE_MAX_LEN (32)
#define EVENT_TOKEN_MAX_LEN (32)
#define SIGLE_EVENT (1)
#define MUTLTI_EVENTS (2)
#define MAX_EVENT_WAIT_REPLY (10)
#define EVENT_MAX_DATA_NUM (255)
#define POST_EVENT "event_post"
#define POST_EVENTS "events_post"
#define REPLY_EVENT "event_reply"
/**
* @brief event's method, post and reply
*/
typedef enum {
eEVENT_POST,
eEVENT_REPLY,
} eEventMethod;
typedef enum _eEventDealType_{
eDEAL_REPLY_CB = 0,
eDEAL_EXPIRED = 1,
}eEventDealType;
typedef struct _sReply_{
char client_token[EVENT_TOKEN_MAX_LEN]; // clientToken for this event reply
void *user_context; // user context
Timer timer; // timer for request timeout
OnEventReplyCallback callback; // callback for this event reply
} sEventReply;
#ifdef __cplusplus
}
#endif
#endif //_DATA_TEMPLATE_EVENT_H_

View File

@@ -0,0 +1,86 @@
#ifndef IOT_GATEWAY_COMMON_H_
#define IOT_GATEWAY_COMMON_H_
#include "qcloud_iot_export.h"
#define GATEWAY_PAYLOAD_BUFFER_LEN 1024
#define GATEWAY_RECEIVE_BUFFER_LEN 1024
#define GATEWAY_LOOP_MAX_COUNT 100
/* The format of operation of gateway topic */
#define GATEWAY_TOPIC_OPERATION_FMT "$gateway/operation/%s/%s"
/* The format of operation result of gateway topic */
#define GATEWAY_TOPIC_OPERATION_RESULT_FMT "$gateway/operation/result/%s/%s"
/* The format of gateway client id */
#define GATEWAY_CLIENT_ID_FMT "%s/%s"
/* The format of operation result of gateway topic */
#define GATEWAY_PAYLOAD_STATUS_FMT "{\"type\":\"%s\",\"payload\":{\"devices\":[{\"product_id\":\"%s\",\"device_name\":\"%s\"}]}}"
/* Subdevice seesion status */
typedef enum _SubdevSessionStatus {
/* Initial */
SUBDEV_SEESION_STATUS_INIT,
/* Online */
SUBDEV_SEESION_STATUS_ONLINE,
/* Offline */
SUBDEV_SEESION_STATUS_OFFLINE,
/* Maximum number of seesion status type */
SUBDEV_SEESION_STATUS_MAX
}SubdevSessionStatus;
/* The structure of subdevice session */
typedef struct _SubdevSession {
char product_id[MAX_SIZE_OF_PRODUCT_ID+1];
char device_name[MAX_SIZE_OF_DEVICE_NAME+1];
SubdevSessionStatus session_status;
struct _SubdevSession *next;
} SubdevSession;
/* The structure of common reply data */
typedef struct _ReplyData{
int32_t result;
char client_id[MAX_SIZE_OF_CLIENT_ID+1];
}ReplyData;
/* The structure of gateway data */
typedef struct _GatewayData {
int32_t sync_status;
ReplyData online;
ReplyData offline;
} GatewayData;
/* The structure of gateway context */
typedef struct _Gateway {
void *mqtt;
SubdevSession *session_list;
GatewayData gateway_data;
MQTTEventHandler event_handle;
int is_construct;
} Gateway;
SubdevSession* subdev_add_session(Gateway *gateway, char *product_id, char *device_name);
SubdevSession* subdev_find_session(Gateway *gateway, char *product_id, char *device_name);
int subdev_remove_session(Gateway *gateway, char *product_id, char *device_name);
int gateway_subscribe_unsubscribe_topic(Gateway *gateway, char *topic_filter, SubscribeParams *params, int is_subscribe);
int gateway_subscribe_unsubscribe_default(Gateway *gateway, GatewayParam* param);
int gateway_publish_sync(Gateway *gateway, char *topic, PublishParams *params, int32_t *result);
#endif /* IOT_GATEWAY_COMMON_H_ */

View File

@@ -0,0 +1,162 @@
/*
* Copyright (c) 2017-2019 Tencent Group. All rights reserved.
* License-Identifier: Apache-2.0
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
/**
* Edit by shockcao@tencent.com 2018/3/15
*/
#ifndef __JSON_PARSER_H__
#define __JSON_PARSER_H__
#include "lite-utils.h"
/**
The descriptions of the json value node type
**/
enum JSONTYPE {
JSNONE = -1,
JSSTRING = 0,
JSOBJECT,
JSARRAY,
JSNUMBER,
JSBOOLEAN,
JSNULL,
JSTYPEMAX
};
/**
The error codes produced by the JSON parsers
**/
enum JSON_PARSE_CODE {
JSON_PARSE_ERR,
JSON_PARSE_OK,
JSON_PARSE_FINISH
};
/**
The return codes produced by the JSON parsers
**/
enum JSON_PARSE_RESULT {
JSON_RESULT_ERR = -1,
JSON_RESULT_OK
};
typedef int (*json_parse_cb)(char *p_cName, int iNameLen, char *p_cValue, int iValueLen, int iValueType,
void *p_Result);
/**
* @brief Parse the JSON string, and iterate through all keys and values,
* then handle the keys and values by callback function.
*
* @param[in] p_cJsonStr @n The JSON string
* @param[in] iStrLen @n The JSON string length
* @param[in] pfnCB @n Callback function
* @param[out] p_CBData @n User data
* @return JSON_RESULT_OK success, JSON_RESULT_ERR failed
* @see None.
* @note None.
**/
int json_parse_name_value(char *p_cJsonStr, int iStrLen, json_parse_cb pfnCB, void *p_CBData);
/**
* @brief Get the value by a specified key from a json string
*
* @param[in] p_cJsonStr @n the JSON string
* @param[in] iStrLen @n the JSON string length
* @param[in] p_cName @n the specified key string
* @param[out] p_iValueLen @n the value length
* @param[out] p_iValueType @n the value type
* @return A pointer to the value
* @see None.
* @note None.
**/
char *json_get_value_by_name(char *p_cJsonStr, int iStrLen, char *p_cName, int *p_iValueLen, int *p_iValueType);
/**
* @brief Get the JSON object point associate with a given type.
*
* @param[in] type @n The object type
* @param[in] str @n The JSON string
* @returns The json object point with the given field type.
* @see None.
* @note None.
*/
char *json_get_object(int type, char *str);
char *json_get_next_object(int type, char *str, char **key, int *key_len, char **val, int *val_len, int *val_type);
/**
* @brief retrieve each key&value pair from the json string
*
* @param[in] str @n Json string to revolve
* @param[in] pos @n cursor
* @param[out] key @n pointer to the next Key object
* @param[out] klen @n Key object length
* @param[out] val @n pointer to the next Value object
* @param[out] vlen @n Value object length
* @param[out] vtype @n Value object type(digital, string, object, array)
* @see None.
* @note None.
*/
#define json_object_for_each_kv(str, pos, key, klen, val, vlen, vtype) \
for (pos = json_get_object(JSOBJECT, str); \
pos!=0 && *pos!=0 && (pos=json_get_next_object(JSOBJECT, pos, &key, &klen, &val, &vlen, &vtype))!=0; )
/**
* @brief retrieve each entry from the json array
*
* @param[in] str @n Json array to revolve
* @param[in] pos @n cursor
* @param[out] entry @n pointer to the next entry from the array
* @param[out] len @n entry length
* @param[out] type @n entry type(digital, string, object, array)
* @see None.
* @note None.
*/
#define json_array_for_each_entry(str, pos, entry, len, type) \
for (pos = json_get_object(JSARRAY, str); \
pos!=0 && *pos!=0 && (pos=json_get_next_object(JSARRAY, ++pos, 0, 0, &entry, &len, &type))!=0; )
/**
* @brief backup the last character to register parameters,
* and set the end character with '\0'
*
* @param[in] json_str @n json string
* @param[in] str_len @n json string lenth
* @param[out] register @n used to backup the last character
* @see None.
* @note None.
*/
#define backup_json_str_last_char(json_str, str_len, register) { \
register = *((char *)json_str + str_len); \
*((char *)json_str + str_len) = '\0'; \
}
/**
* @brief restore the last character from register parameters
*
* @param[in] json_str @n json string
* @param[in] str_len @n json string lenth
* @param[in] register @n used to restore the last character
* @see None.
* @note None.
*/
#define restore_json_str_last_char(json_str, str_len, register) { \
*((char *)json_str + str_len) = register; \
}
#endif /* __JSON_PARSER_H__ */

View File

@@ -0,0 +1,105 @@
/*
* Tencent is pleased to support the open source community by making IoT Hub available.
* Copyright (C) 2016 THL A29 Limited, a Tencent company. All rights reserved.
* Licensed under the MIT License (the "License"); you may not use this file except in
* compliance with the License. You may obtain a copy of the License at
* http://opensource.org/licenses/MIT
* Unless required by applicable law or agreed to in writing, software distributed under the License is
* distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
* either express or implied. See the License for the specific language governing permissions and
* limitations under the License.
*
*/
#ifndef QCLOUD_IOT_LOG_UPLOAD_H_
#define QCLOUD_IOT_LOG_UPLOAD_H_
#ifdef __cplusplus
extern "C" {
#endif
#include "qcloud_iot_export_log.h"
/**
* @brief init the log upload functions
*
* @param init_params
* @return QCLOUD_RET_SUCCESS when success
*/
int init_log_uploader(LogUploadInitParams *init_params);
/**
* @brief free log buffer and finish the log upload functions
*/
void fini_log_uploader(void);
/**
* @brief check if log uploader is init or not
*/
bool is_log_uploader_init(void);
/**
* @brief append one log item to upload buffer
*
* @param log_content
* @param log_size
* @return 0 when success, -1 when fail
*/
int append_to_upload_buffer(const char *log_content, size_t log_size);
/**
* @brief clear current upload buffer
*
* @return
*/
void clear_upload_buffer(void);
/**
* @brief do one upload to server
*
* @param force_upload if true, it will do upload right away, otherwise it will check log_level, buffer left and upload interval
* @return QCLOUD_RET_SUCCESS when success or no log to upload or timer is not expired
*/
int do_log_upload(bool force_upload);
/**
* @brief set the log mqtt client to get system time
*
* @param client
*/
void set_log_mqtt_client(void *client);
/**
* @brief set if only do log upload when communication error with IoT Hub
*
* @param value if true, only do log upload when communication error with IoT Hub
*/
void set_log_upload_in_comm_err(bool value);
/**
* @brief get current upload log_level from IoT Hub
*
* @param client
* @param log_level
* @return QCLOUD_RET_SUCCESS when success
*/
int qcloud_get_log_level(void* client, int *log_level);
/**
* @brief subscribe to upload log_level topic
*
* @param client
* @return QCLOUD_RET_SUCCESS when success
*/
int qcloud_log_topic_subscribe(void *client);
#ifdef __cplusplus
}
#endif
#endif //QCLOUD_IOT_LOG_UPLOAD_H_

View File

@@ -0,0 +1,513 @@
/*
* Tencent is pleased to support the open source community by making IoT Hub available.
* Copyright (C) 2016 THL A29 Limited, a Tencent company. All rights reserved.
* Licensed under the MIT License (the "License"); you may not use this file except in
* compliance with the License. You may obtain a copy of the License at
* http://opensource.org/licenses/MIT
* Unless required by applicable law or agreed to in writing, software distributed under the License is
* distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
* either express or implied. See the License for the specific language governing permissions and
* limitations under the License.
*
*/
#ifndef IOT_MQTT_CLIENT_H_
#define IOT_MQTT_CLIENT_H_
#ifdef __cplusplus
extern "C" {
#endif
#include <stddef.h>
#include <stdbool.h>
#include <stdint.h>
#include "qcloud_iot_export.h"
#include "qcloud_iot_import.h"
#include "utils_param_check.h"
#include "mqtt_client_net.h"
#include "utils_timer.h"
#include "utils_list.h"
/* packet id, random from [1 - 65536] */
#define MAX_PACKET_ID (65535)
/* Max size of conn Id */
#define MAX_CONN_ID_LEN (6)
/* Max number of topic subscribed */
#define MAX_MESSAGE_HANDLERS (10)
/* Max number in repub list */
#define MAX_REPUB_NUM (20)
/* Minimal wait interval when reconnect */
#define MIN_RECONNECT_WAIT_INTERVAL (1000)
/* Minimal MQTT timeout value */
#define MIN_COMMAND_TIMEOUT (500)
/* Maxmal MQTT timeout value */
#define MAX_COMMAND_TIMEOUT (20000)
/* Max size of a topic name */
#define MAX_SIZE_OF_CLOUD_TOPIC ((MAX_SIZE_OF_DEVICE_NAME) + (MAX_SIZE_OF_PRODUCT_ID) + 64 + 6)
/* minimal TLS handshaking timeout value (unit: ms) */
#define QCLOUD_IOT_TLS_HANDSHAKE_TIMEOUT (5 * 1000)
/**
* @brief MQTT Message Type
*/
typedef enum msgTypes {
RESERVED = 0, // Reserved
CONNECT = 1, // Client request to connect to Server
CONNACK = 2, // Connect Acknowledgment
PUBLISH = 3, // Publish message
PUBACK = 4, // Publish Acknowledgment
PUBREC = 5, // Publish Received
PUBREL = 6, // Publish Release
PUBCOMP = 7, // Publish Complete
SUBSCRIBE = 8, // Client Subscribe request
SUBACK = 9, // Subscribe Acknowledgment
UNSUBSCRIBE = 10, // Client Unsubscribe request
UNSUBACK = 11, // Unsubscribe Acknowledgment
PINGREQ = 12, // PING Request
PINGRESP = 13, // PING Response
DISCONNECT = 14 // Client is Disconnecting
} MessageTypes;
typedef enum {
NOTCONNECTED = 0,
CONNECTED = 1
} ConnStatus;
/**
* MQTT byte 1: fixed header
* bits |7654: Message Type | 3:DUP flag | 21:QoS level | 0:RETAIN |
*/
#define MQTT_HEADER_TYPE_SHIFT 0x04
#define MQTT_HEADER_TYPE_MASK 0xF0
#define MQTT_HEADER_DUP_SHIFT 0x03
#define MQTT_HEADER_DUP_MASK 0x08
#define MQTT_HEADER_QOS_SHIFT 0x01
#define MQTT_HEADER_QOS_MASK 0x06
#define MQTT_HEADER_RETAIN_MASK 0x01
/**
* @brief MQTT will options sturcture
*
*/
typedef struct {
char struct_id[4]; // The eyecatcher for this structure. must be MQTW
uint8_t struct_version; // struct version = 0
char *topic_name;
char *message;
uint8_t retained;
QoS qos;
} WillOptions;
/**
* default MQTT will options
*/
#define DEFAULT_WILL_OPTIONS { {'M', 'Q', 'T', 'W'}, 0, NULL, NULL, 0, QOS0 }
/**
* @brief define MQTT connect parameters structure
*
*/
typedef struct {
char *client_id; // unique client id
char *username; // user name
char *password; // passwrod
char conn_id[MAX_CONN_ID_LEN];
char struct_id[4]; // The eyecatcher for this structure. must be MQTC.
uint8_t struct_version; // struct version = 0
uint8_t mqtt_version; // MQTT protocol version: 4 = 3.1.1
uint16_t keep_alive_interval; // keep alive interval, unit: second
uint8_t clean_session; // flag of clean session, refer to MQTT spec 3.1.2.4
uint8_t auto_connect_enable; // enable auto connection or not
#ifdef AUTH_WITH_NOTLS
char *device_secret; // PSK
int device_secret_len; // length of PSK
#endif
} MQTTConnectParams;
/**
* default value of MQTT connect parameters structure
*/
#ifdef AUTH_WITH_NOTLS
#define DEFAULT_MQTTCONNECT_PARAMS { NULL, NULL, NULL, {0}, {'M', 'Q', 'T', 'C'}, 0, 4, 240, 1, 1, NULL, 0}
#else
#define DEFAULT_MQTTCONNECT_PARAMS { NULL, NULL, NULL, {0}, {'M', 'Q', 'T', 'C'}, 0, 4, 240, 1, 1}
#endif
/**
* @brief data structure for topic subscription handle
*/
typedef struct SubTopicHandle {
const char *topic_filter; // topic name, wildcard filter is supported
OnMessageHandler message_handler; // callback when msg of this subscription arrives
OnSubEventHandler sub_event_handler; // callback when event of this subscription happens
void *handler_user_data; // user context for callback
QoS qos; // QoS
} SubTopicHandle;
/**
* @brief MQTT QCloud IoT Client structure
*/
typedef struct Client {
uint8_t is_connected;
uint8_t was_manually_disconnected;
uint8_t is_ping_outstanding; // 1 = ping request is sent while ping response not arrived yet
uint16_t next_packet_id; // MQTT random packet id
uint32_t command_timeout_ms; // MQTT command timeout, unit:ms
uint32_t current_reconnect_wait_interval; // unit:ms
uint32_t counter_network_disconnected; // number of disconnection
size_t write_buf_size; // size of MQTT write buffer
size_t read_buf_size; // size of MQTT read buffer
unsigned char write_buf[QCLOUD_IOT_MQTT_TX_BUF_LEN]; // MQTT write buffer
unsigned char read_buf[QCLOUD_IOT_MQTT_RX_BUF_LEN]; // MQTT read buffer
void *lock_generic; // mutex/lock for this client struture
void *lock_write_buf; // mutex/lock for write buffer
void *lock_list_pub; // mutex/lock for puback waiting list
void *lock_list_sub; // mutex/lock for suback waiting list
List *list_pub_wait_ack; // puback waiting list
List *list_sub_wait_ack; // suback waiting list
MQTTEventHandler event_handle; // callback for MQTT event
MQTTConnectParams options; // handle to connection parameters
Network network_stack; // MQTT network stack
Timer ping_timer; // MQTT ping timer
Timer reconnect_delay_timer; // MQTT reconnect delay timer
SubTopicHandle sub_handles[MAX_MESSAGE_HANDLERS]; // subscription handle array
} Qcloud_IoT_Client;
/**
* @brief MQTT protocol version
*/
typedef enum {
MQTT_3_1_1 = 4
} MQTT_VERSION;
typedef enum MQTT_NODE_STATE {
MQTT_NODE_STATE_NORMANL = 0,
MQTT_NODE_STATE_INVALID,
} MQTTNodeState;
/* topic publish info */
typedef struct REPUBLISH_INFO {
Timer pub_start_time; /* timer for puback waiting */
MQTTNodeState node_state; /* node state in wait list */
uint16_t msg_id; /* packet id */
uint32_t len; /* msg length */
unsigned char *buf; /* msg buffer */
} QcloudIotPubInfo;
/* topic subscribe/unsubscribe info */
typedef struct SUBSCRIBE_INFO {
enum msgTypes type; /* type: sub or unsub */
uint16_t msg_id; /* packet id */
Timer sub_start_time; /* timer for suback waiting */
MQTTNodeState node_state; /* node state in wait list */
SubTopicHandle handler; /* handle of topic subscribed(unsubcribed) */
uint16_t len; /* msg length */
unsigned char *buf; /* msg buffer */
} QcloudIotSubInfo;
/**
* @brief Init MQTT client
*
* @param pClient handle to MQTT client
* @param pParams MQTT init parameters
*
* @return QCLOUD_RET_SUCCESS for success, or err code for failure
*/
int qcloud_iot_mqtt_init(Qcloud_IoT_Client *pClient, MQTTInitParams *pParams);
/**
* @brief Release resources of MQTT client
*
* @param pClient handle to MQTT client
*
* @return QCLOUD_RET_SUCCESS for success, or err code for failure
*/
int qcloud_iot_mqtt_deinit(Qcloud_IoT_Client *pClient);
/**
* @brief Connect with MQTT server
*
* @param pClient handle to MQTT client
* @param pParams MQTT connect parameters
*
* @return QCLOUD_RET_SUCCESS for success, or err code for failure
*/
int qcloud_iot_mqtt_connect(Qcloud_IoT_Client *pClient, MQTTConnectParams *pParams);
/**
* @brief Reconnect with MQTT server and re-subscribe topics if reconnected
*
* @param pClient handle to MQTT client
*
* @return QCLOUD_RET_MQTT_RECONNECTED for success, or err code for failure
*/
int qcloud_iot_mqtt_attempt_reconnect(Qcloud_IoT_Client *pClient);
/**
* @brief Disconnect with MQTT server
*
* @param pClient handle to MQTT client
*
* @return QCLOUD_RET_SUCCESS for success, or err code for failure
*/
int qcloud_iot_mqtt_disconnect(Qcloud_IoT_Client *pClient);
/**
* @brief Publish MQTT message
*
* @param pClient handle to MQTT client
* @param topicName MQTT topic name
* @param pParams publish parameters
*
* @return packet id (>=0) when success, or err code (<0) for failure
*/
int qcloud_iot_mqtt_publish(Qcloud_IoT_Client *pClient, char *topicName, PublishParams *pParams);
/**
* @brief Subscribe MQTT topic
*
* @param pClient handle to MQTT client
* @param topicFilter MQTT topic filter
* @param pParams subscribe parameters
*
* @return packet id (>=0) when success, or err code (<0) for failure
*/
int qcloud_iot_mqtt_subscribe(Qcloud_IoT_Client *pClient, char *topicFilter, SubscribeParams *pParams);
/**
* @brief Re-subscribe MQTT topics
*
* @param pClient handle to MQTT client
*
* @return QCLOUD_RET_SUCCESS for success, or err code for failure
*/
int qcloud_iot_mqtt_resubscribe(Qcloud_IoT_Client *pClient);
/**
* @brief Unsubscribe MQTT topic
*
* @param pClient handle to MQTT client
* @param topicFilter MQTT topic filter
*
* @return packet id (>=0) when success, or err code (<0) for failure
*/
int qcloud_iot_mqtt_unsubscribe(Qcloud_IoT_Client *pClient, char *topicFilter);
/**
* @brief Check connection and keep alive state, read/handle MQTT message in synchronized way
*
* @param pClient handle to MQTT client
* @param timeout_ms timeout value (unit: ms) for this operation
*
* @return QCLOUD_RET_SUCCESS when success, QCLOUD_ERR_MQTT_ATTEMPTING_RECONNECT when try reconnecing, or err code for failure
*/
int qcloud_iot_mqtt_yield(Qcloud_IoT_Client *pClient, uint32_t timeout_ms);
/**
* @brief Check if auto reconnect is enabled or not
*
* @param pClient handle to MQTT client
* @return true if auto reconnect is enabled
*/
bool qcloud_iot_mqtt_is_autoreconnect_enabled(Qcloud_IoT_Client *pClient);
/**
* @brief Set to enable auto reconnect or not
*
* @param pClient handle to MQTT client
* @param value enable or disable
* @return QCLOUD_RET_SUCCESS for success, or err code for failure
*/
int qcloud_iot_mqtt_set_autoreconnect(Qcloud_IoT_Client *pClient, bool value);
/**
* @brief Get the count of disconnection
*
* @param pClient handle to MQTT client
* @return count of disconnection
*/
int qcloud_iot_mqtt_get_network_disconnected_count(Qcloud_IoT_Client *pClient);
/**
* @brief Set the count of disconnection
*
* @param pClient handle to MQTT client
* @return QCLOUD_RET_SUCCESS for success, or err code for failure
*/
int qcloud_iot_mqtt_reset_network_disconnected_count(Qcloud_IoT_Client *pClient);
/**
* @brief Get next packet id
*
* @param pClient
* @return
*/
uint16_t get_next_packet_id(Qcloud_IoT_Client *pClient);
/**
* @brief Get next conn id
*
* @param options
* @return
*/
void get_next_conn_id(char *conn_id);
/**
* @brief Init packet header
* @param header
* @param message_type
* @param qos
* @param dup
* @param retained
* @return
*/
int mqtt_init_packet_header(unsigned char *header, MessageTypes message_type, QoS qos, uint8_t dup, uint8_t retained);
/**
* @brief Read and handle one MQTT msg/ack from server
*
* @param pClient
* @param timer
* @param packet_type
* @param qos
* @return QCLOUD_RET_SUCCESS for success, or err code for failure
*/
int cycle_for_read(Qcloud_IoT_Client *pClient, Timer *timer, uint8_t *packet_type, QoS qos);
/**
* @brief Send the packet in buffer
*
* @param pClient
* @param length
* @param timer
* @return
*/
int send_mqtt_packet(Qcloud_IoT_Client *pClient, size_t length, Timer *timer);
/**
* @brief wait for a specific packet with timeout
*
* only used in single-threaded mode where one command at a time is in process
*
* @param pClient MQTT Client
* @param packet_type MQTT packet type
* @param timer timer with timeout
* @return QCLOUD_RET_SUCCESS for success, or err code for failure
*/
int wait_for_read(Qcloud_IoT_Client *pClient, uint8_t packet_type, Timer *timer, QoS qos);
/**
* @brief Set MQTT connection state
*
* @param pClient MQTT Client
* @param connected 0: disconnected 1: connected
* @return
*/
void set_client_conn_state(Qcloud_IoT_Client *pClient, uint8_t connected);
/**
* @brief Get MQTT connection state
*
* @param pClient MQTT Client
* @return 0: disconnected 1: connected
*/
uint8_t get_client_conn_state(Qcloud_IoT_Client *pClient);
/**
* @brief Check Publish ACK waiting list, remove the node if PUBACK received or timeout
*
* @param pClient MQTT client
* @return QCLOUD_RET_SUCCESS for success, or err code for failure
*/
int qcloud_iot_mqtt_pub_info_proc(Qcloud_IoT_Client *pClient);
/**
* @brief Check Subscribe ACK waiting list, remove the node if SUBACK received or timeout
*
* @param pClient MQTT client
* @return QCLOUD_RET_SUCCESS for success, or err code for failure
*/
int qcloud_iot_mqtt_sub_info_proc(Qcloud_IoT_Client *pClient);
int push_sub_info_to(Qcloud_IoT_Client *c, int len, unsigned short msgId, MessageTypes type,
SubTopicHandle *handler, ListNode **node);
int serialize_pub_ack_packet(unsigned char *buf, size_t buf_len, MessageTypes packet_type, uint8_t dup,
uint16_t packet_id,
uint32_t *serialized_len);
int serialize_packet_with_zero_payload(unsigned char *buf, size_t buf_len, MessageTypes packetType, uint32_t *serialized_len);
int deserialize_publish_packet(unsigned char *dup, QoS *qos, uint8_t *retained, uint16_t *packet_id, char **topicName,
uint16_t *topicNameLen, unsigned char **payload, size_t *payload_len, unsigned char *buf, size_t buf_len);
int deserialize_suback_packet(uint16_t *packet_id, uint32_t max_count, uint32_t *count,
QoS *grantedQoSs, unsigned char *buf, size_t buf_len);
int deserialize_unsuback_packet(uint16_t *packet_id, unsigned char *buf, size_t buf_len);
int deserialize_ack_packet(uint8_t *packet_type, uint8_t *dup, uint16_t *packet_id, unsigned char *buf, size_t buf_len);
#ifdef MQTT_RMDUP_MSG_ENABLED
void reset_repeat_packet_id_buffer(void);
#endif
size_t get_mqtt_packet_len(size_t rem_len);
size_t mqtt_write_packet_rem_len(unsigned char *buf, uint32_t length);
int mqtt_read_packet_rem_len_form_buf(unsigned char *buf, uint32_t *value, uint32_t *readBytesLen);
uint16_t mqtt_read_uint16_t(unsigned char **pptr);
unsigned char mqtt_read_char(unsigned char **pptr);
void mqtt_write_char(unsigned char **pptr, unsigned char c);
void mqtt_write_uint_16(unsigned char **pptr, uint16_t anInt);
void mqtt_write_utf8_string(unsigned char **pptr, const char *string);
#ifdef __cplusplus
}
#endif
#endif //IOT_MQTT_CLIENT_H_

View File

@@ -0,0 +1,38 @@
/*
* Tencent is pleased to support the open source community by making IoT Hub available.
* Copyright (C) 2016 THL A29 Limited, a Tencent company. All rights reserved.
* Licensed under the MIT License (the "License"); you may not use this file except in
* compliance with the License. You may obtain a copy of the License at
* http://opensource.org/licenses/MIT
* Unless required by applicable law or agreed to in writing, software distributed under the License is
* distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
* either express or implied. See the License for the specific language governing permissions and
* limitations under the License.
*
*/
#ifndef IOT_MQTT_CLIENT_NET_H_
#define IOT_MQTT_CLIENT_NET_H_
#ifdef __cplusplus
extern "C" {
#endif
#include "network_interface.h"
/**
* @brief Init network stack
*
* @param pNetwork
* @param pConnectParams
* @return 0 for success
*/
int qcloud_iot_mqtt_network_init(Network *pNetwork);
#ifdef __cplusplus
}
#endif
#endif //IOT_MQTT_CLIENT_NET_H_

View File

@@ -0,0 +1,130 @@
/*
* Tencent is pleased to support the open source community by making IoT Hub available.
* Copyright (C) 2016 THL A29 Limited, a Tencent company. All rights reserved.
* Licensed under the MIT License (the "License"); you may not use this file except in
* compliance with the License. You may obtain a copy of the License at
* http://opensource.org/licenses/MIT
* Unless required by applicable law or agreed to in writing, software distributed under the License is
* distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
* either express or implied. See the License for the specific language governing permissions and
* limitations under the License.
*
*/
#ifndef _NETWORK_INTERFACE_H_
#define _NETWORK_INTERFACE_H_
#ifdef __cplusplus
extern "C" {
#endif
#include <stddef.h>
#include <stdint.h>
#include "qcloud_iot_import.h"
/*
* Type of network interface
*/
typedef enum {
NETWORK_TCP = 0,
NETWORK_UDP = 1,
NETWORK_TLS = 2,
NETWORK_DTLS = 3
} NETWORK_TYPE;
/**
* @brief Define structure for network stack
*/
typedef struct Network Network;
/**
* @brief Define structure for network stack
*
* Network init/connect/read/write/disconnect/state
*/
struct Network {
int (*init)(Network *);
int (*connect)(Network *);
int (*read)(Network *, unsigned char *, size_t, uint32_t, size_t *);
int (*write)(Network *, unsigned char *, size_t, uint32_t, size_t *);
void (*disconnect)(Network *);
int (*is_connected)(Network *);
// connetion handle:
// for non-AT: 0 = not connected, non-zero = connected
// for AT: 0 = valid connection, MAX_UNSINGED_INT = invalid
uintptr_t handle;
#ifndef AUTH_WITH_NOTLS
SSLConnectParams ssl_connect_params;
#endif
const char *host; // server address
int port; // server port
NETWORK_TYPE type;
};
/*
* Init network stack
*/
int network_init(Network *pNetwork);
/* return the handle */
int is_network_connected(Network *pNetwork);
/* network stack API */
#ifdef AT_TCP_ENABLED
#define AT_NO_CONNECTED_FD 0xffffffff
int network_at_tcp_read(Network *pNetwork, unsigned char *data, size_t datalen, uint32_t timeout_ms, size_t *read_len);
int network_at_tcp_write(Network *pNetwork, unsigned char *data, size_t datalen, uint32_t timeout_ms, size_t *written_len);
void network_at_tcp_disconnect(Network *pNetwork);
int network_at_tcp_connect(Network *pNetwork);
int network_at_tcp_init(Network *pNetwork);
#else
int network_tcp_read(Network *pNetwork, unsigned char *data, size_t datalen, uint32_t timeout_ms, size_t *read_len);
int network_tcp_write(Network *pNetwork, unsigned char *data, size_t datalen, uint32_t timeout_ms, size_t *written_len);
void network_tcp_disconnect(Network *pNetwork);
int network_tcp_connect(Network *pNetwork);
int network_tcp_init(Network *pNetwork);
#endif
#ifndef AUTH_WITH_NOTLS
int network_tls_read(Network *pNetwork, unsigned char *data, size_t datalen, uint32_t timeout_ms, size_t *read_len);
int network_tls_write(Network *pNetwork, unsigned char *data, size_t datalen, uint32_t timeout_ms, size_t *written_len);
void network_tls_disconnect(Network *pNetwork);
int network_tls_connect(Network *pNetwork);
int network_tls_init(Network *pNetwork);
#endif
#ifdef COAP_COMM_ENABLED
#ifdef AUTH_WITH_NOTLS
int network_udp_read(Network *pNetwork, unsigned char *data, size_t datalen, uint32_t timeout_ms, size_t *read_len);
int network_udp_write(Network *pNetwork, unsigned char *data, size_t datalen, uint32_t timeout_ms, size_t *written_len);
void network_udp_disconnect(Network *pNetwork);
int network_udp_connect(Network *pNetwork);
int network_udp_init(Network *pNetwork);
#else
int network_dtls_read(Network *pNetwork, unsigned char *data, size_t datalen, uint32_t timeout_ms, size_t *read_len);
int network_dtls_write(Network *pNetwork, unsigned char *data, size_t datalen, uint32_t timeout_ms, size_t *written_len);
void network_dtls_disconnect(Network *pNetwork);
int network_dtls_connect(Network *pNetwork);
int network_dtls_init(Network *pNetwork);
#endif
#endif
#ifdef __cplusplus
}
#endif
#endif /* _NETWORK_INTERFACE_H_ */

View File

@@ -0,0 +1,59 @@
/*
* Tencent is pleased to support the open source community by making IoT Hub available.
* Copyright (C) 2016 THL A29 Limited, a Tencent company. All rights reserved.
* Licensed under the MIT License (the "License"); you may not use this file except in
* compliance with the License. You may obtain a copy of the License at
* http://opensource.org/licenses/MIT
* Unless required by applicable law or agreed to in writing, software distributed under the License is
* distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
* either express or implied. See the License for the specific language governing permissions and
* limitations under the License.
*
*/
#ifndef IOT_OTA_CLIENT_H_
#define IOT_OTA_CLIENT_H_
#ifdef __cplusplus
extern "C" {
#endif
#include <stdint.h>
/* Specify the maximum characters of version */
#define OTA_MAX_TOPIC_LEN (64)
#define TYPE_FIELD "type"
#define MD5_FIELD "md5sum"
#define VERSION_FIELD "version"
#define URL_FIELD "url"
#define FILESIZE_FIELD "file_size"
#define RESULT_FIELD "result_code"
#define REPORT_VERSION_RSP "report_version_rsp"
#define UPDATE_FIRMWARE "update_firmware"
enum {
MQTT_CHANNEL,
COAP_CHANNEL
};
typedef void (*OnOTAMessageCallback)(void *pcontext, const char *msg, uint32_t msgLen);
void *qcloud_osc_init(const char *productId, const char *deviceName, void *channel, OnOTAMessageCallback callback, void *context);
int qcloud_osc_deinit(void *handle);
int qcloud_osc_report_progress(void *handle, const char *msg);
int qcloud_osc_report_version(void *handle, const char *msg);
int qcloud_osc_report_upgrade_result(void *handle, const char *msg);
#ifdef __cplusplus
}
#endif
#endif /* IOT_OTA_CLIENT_H_ */

View File

@@ -0,0 +1,38 @@
/*
* Tencent is pleased to support the open source community by making IoT Hub available.
* Copyright (C) 2016 THL A29 Limited, a Tencent company. All rights reserved.
* Licensed under the MIT License (the "License"); you may not use this file except in
* compliance with the License. You may obtain a copy of the License at
* http://opensource.org/licenses/MIT
* Unless required by applicable law or agreed to in writing, software distributed under the License is
* distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
* either express or implied. See the License for the specific language governing permissions and
* limitations under the License.
*
*/
#ifndef IOT_OTA_FETCH_H_
#define IOT_OTA_FETCH_H_
#ifdef __cplusplus
extern "C" {
#endif
#include <stdint.h>
void *ofc_Init(const char *url, uint32_t offset, uint32_t size);
int32_t qcloud_ofc_connect(void *handle);
int32_t qcloud_ofc_fetch(void *handle, char *buf, uint32_t buf_len, uint32_t timeout_s);
int qcloud_ofc_deinit(void *handle);
#ifdef __cplusplus
}
#endif
#endif /* IOT_OTA_FETCH_H_ */

View File

@@ -0,0 +1,84 @@
/*
* Tencent is pleased to support the open source community by making IoT Hub available.
* Copyright (C) 2016 THL A29 Limited, a Tencent company. All rights reserved.
* Licensed under the MIT License (the "License"); you may not use this file except in
* compliance with the License. You may obtain a copy of the License at
* http://opensource.org/licenses/MIT
* Unless required by applicable law or agreed to in writing, software distributed under the License is
* distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
* either express or implied. See the License for the specific language governing permissions and
* limitations under the License.
*
*/
#ifndef IOT_OTA_LIB_H_
#define IOT_OTA_LIB_H_
#ifdef __cplusplus
extern "C" {
#endif
#include <sys/types.h>
#include <stdint.h>
#include "qcloud_iot_export_ota.h"
void *qcloud_otalib_md5_init(void);
void qcloud_otalib_md5_update(void *md5, const char *buf, size_t buf_len);
void qcloud_otalib_md5_finalize(void *md5, char *output_str);
void qcloud_otalib_md5_deinit(void *md5);
int qcloud_otalib_get_firmware_type(const char *json, char **type);
int qcloud_otalib_get_report_version_result(const char *json);
/**
* @brief Parse firmware info from JSON string
*
* @param json source JSON string
* @param type parsed type
* @param url parsed url
* @param version parsed version
* @param md5 parsed MD5
* @param fileSize parsed file size
* @return QCLOUD_RET_SUCCESS for success, or err code for failure
*/
int qcloud_otalib_get_params(const char *json, char **type, char **url, char **version, char *md5,
uint32_t *fileSize);
/**
* @brief Generate firmware info from id and version
*
* @param buf output buffer
* @param bufLen size of buffer
* @param id firmware id
* @param version firmware version
* @return QCLOUD_RET_SUCCESS for success, or err code for failure
*/
int qcloud_otalib_gen_info_msg(char *buf, size_t bufLen, uint32_t id, const char *version);
/**
* @brief Generate firmware report
*
* @param buf output buffer
* @param bufLen size of buffer
* @param id firmware id
* @param version firmware version
* @param progress download progress
* @param reportType report type
* @return QCLOUD_RET_SUCCESS for success, or err code for failure
*/
int qcloud_otalib_gen_report_msg(char *buf, size_t bufLen, uint32_t id, const char *version, int progress, IOT_OTAReportType reportType);
#ifdef __cplusplus
}
#endif
#endif /* IOT_OTA_LIB_H_ */

View File

@@ -0,0 +1,33 @@
/*
* Tencent is pleased to support the open source community by making IoT Hub available.
* Copyright (C) 2016 THL A29 Limited, a Tencent company. All rights reserved.
* Licensed under the MIT License (the "License"); you may not use this file except in
* compliance with the License. You may obtain a copy of the License at
* http://opensource.org/licenses/MIT
* Unless required by applicable law or agreed to in writing, software distributed under the License is
* distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
* either express or implied. See the License for the specific language governing permissions and
* limitations under the License.
*
*/
#ifndef IOT_CA_H_
#define IOT_CA_H_
#ifdef __cplusplus
extern "C" {
#endif
const char *iot_ca_get(void);
const char *iot_https_ca_get(void);
#ifdef __cplusplus
}
#endif
#endif /* IOT_CA_H_ */

View File

@@ -0,0 +1,53 @@
/*
* Tencent is pleased to support the open source community by making IoT Hub available.
* Copyright (C) 2016 THL A29 Limited, a Tencent company. All rights reserved.
* Licensed under the MIT License (the "License"); you may not use this file except in
* compliance with the License. You may obtain a copy of the License at
* http://opensource.org/licenses/MIT
* Unless required by applicable law or agreed to in writing, software distributed under the License is
* distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
* either express or implied. See the License for the specific language governing permissions and
* limitations under the License.
*
*/
#ifndef QCLOUD_IOT_COMMON_H_
#define QCLOUD_IOT_COMMON_H_
/* IoT C-SDK APPID */
#define QCLOUD_IOT_DEVICE_SDK_APPID "21010406"
/* MQTT server domain */
#define QCLOUD_IOT_MQTT_DIRECT_DOMAIN "iotcloud.tencentdevices.com"
#define MQTT_SERVER_PORT_TLS 8883
#define MQTT_SERVER_PORT_NOTLS 1883
/* CoAP server domain */
#define QCLOUD_IOT_COAP_DEIRECT_DOMAIN "iotcloud.tencentdevices.com"
#define COAP_SERVER_PORT 5684
/* server domain for dynamic registering device */
#define DYN_REG_SERVER_URL "gateway.tencentdevices.com"
#define DYN_REG_SERVER_PORT 80
#define DYN_REG_SERVER_PORT_TLS 443
/* URL for doing log upload */
#define LOG_UPLOAD_SERVER_URL "http://devicelog.iot.cloud.tencent.com/cgi-bin/report-log"
#define LOG_UPLOAD_SERVER_DOMAIN "devicelog.iot.cloud.tencent.com"
#define LOG_UPLOAD_SERVER_PORT 80
/* Max size of a host name */
#define HOST_STR_LENGTH 64
/* Max size of base64 encoded PSK = 64, after decode: 64/4*3 = 48*/
#define DECODE_PSK_LENGTH 48
#endif /* QCLOUD_IOT_COMMON_H_ */

View File

@@ -0,0 +1,36 @@
/*
* Tencent is pleased to support the open source community by making IoT Hub available.
* Copyright (C) 2016 THL A29 Limited, a Tencent company. All rights reserved.
* Licensed under the MIT License (the "License"); you may not use this file except in
* compliance with the License. You may obtain a copy of the License at
* http://opensource.org/licenses/MIT
* Unless required by applicable law or agreed to in writing, software distributed under the License is
* distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
* either express or implied. See the License for the specific language governing permissions and
* limitations under the License.
*
*/
#ifndef IOT_DEVICE_H_
#define IOT_DEVICE_H_
#ifdef __cplusplus
extern "C" {
#endif
#include "qcloud_iot_export.h"
#include "qcloud_iot_import.h"
int iot_device_info_init(void);
int iot_device_info_set(const char *product_id, const char *device_name);
DeviceInfo* iot_device_info_get(void);
#ifdef __cplusplus
}
#endif
#endif /* IOT_DEVICE_H_ */

View File

@@ -0,0 +1,317 @@
/*
* Tencent is pleased to support the open source community by making IoT Hub available.
* Copyright (C) 2016 THL A29 Limited, a Tencent company. All rights reserved.
* Licensed under the MIT License (the "License"); you may not use this file except in
* compliance with the License. You may obtain a copy of the License at
* http://opensource.org/licenses/MIT
* Unless required by applicable law or agreed to in writing, software distributed under the License is
* distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
* either express or implied. See the License for the specific language governing permissions and
* limitations under the License.
*
*/
#ifndef QCLOUD_IOT_UTILS_AES_H_
#define QCLOUD_IOT_UTILS_AES_H_
#ifdef __cplusplus
extern "C" {
#endif
#include <stddef.h>
#include <stdint.h>
//========Platform================================//
#define UTILS_AES_C
#define UTILS_CIPHER_MODE_CBC
//#define UTILS_SELF_TEST
#define UTILS_ERR_PLATFORM_HW_ACCEL_FAILED -0x0070 /**< Hardware accelerator failed */
#define UTILS_ERR_PLATFORM_FEATURE_UNSUPPORTED -0x0072 /**< The requested feature is not supported by the platform */
/* Internal macros meant to be called only from within the library. */
#define UTILS_INTERNAL_VALIDATE_RET( cond, ret ) do { } while( 0 )
#define UTILS_INTERNAL_VALIDATE( cond ) do { } while( 0 )
//==============================================//
/* padlock.c and aesni.c rely on these values! */
#define UTILS_AES_ENCRYPT 1 /**< AES encryption. */
#define UTILS_AES_DECRYPT 0 /**< AES decryption. */
#define UTILS_AES_BLOCK_LEN 16
#define AES_KEY_BITS_128 128
#define AES_KEY_BITS_192 192
#define AES_KEY_BITS_256 256
/* Error codes in range 0x0020-0x0022 */
#define UTILS_ERR_AES_INVALID_KEY_LENGTH -0x0020 /**< Invalid key length. */
#define UTILS_ERR_AES_INVALID_INPUT_LENGTH -0x0022 /**< Invalid data input length. */
/* Error codes in range 0x0021-0x0025 */
#define UTILS_ERR_AES_BAD_INPUT_DATA -0x0021 /**< Invalid input data. */
/* UTILS_ERR_AES_FEATURE_UNAVAILABLE is deprecated and should not be used. */
#define UTILS_ERR_AES_FEATURE_UNAVAILABLE -0x0023 /**< Feature not available. For example, an unsupported AES key size. */
/* UTILS_ERR_AES_HW_ACCEL_FAILED is deprecated and should not be used. */
#define UTILS_ERR_AES_HW_ACCEL_FAILED -0x0025 /**< AES hardware accelerator failed. */
#if !defined(UTILS_AES_ALT)
// Regular implementation
//
/**
* \brief The AES context-type definition.
*/
typedef struct utils_aes_context
{
int nr; /*!< The number of rounds. */
uint32_t *rk; /*!< AES round keys. */
uint32_t buf[68]; /*!< Unaligned data buffer. This buffer can
hold 32 extra Bytes, which can be used for
one of the following purposes:
<ul><li>Alignment if VIA padlock is
used.</li>
<li>Simplifying key expansion in the 256-bit
case by generating an extra round key.
</li></ul> */
}
utils_aes_context;
#else /* UTILS_AES_ALT */
#include "aes_alt.h"
#endif /* UTILS_AES_ALT */
/**
* \brief This function initializes the specified AES context.
*
* It must be the first API called before using
* the context.
*
* \param ctx The AES context to initialize. This must not be \c NULL.
*/
void utils_aes_init( utils_aes_context *ctx );
/**
* \brief This function releases and clears the specified AES context.
*
* \param ctx The AES context to clear.
* If this is \c NULL, this function does nothing.
* Otherwise, the context must have been at least initialized.
*/
void utils_aes_free( utils_aes_context *ctx );
/**
* \brief This function sets the encryption key.
*
* \param ctx The AES context to which the key should be bound.
* It must be initialized.
* \param key The encryption key.
* This must be a readable buffer of size \p keybits bits.
* \param keybits The size of data passed in bits. Valid options are:
* <ul><li>128 bits</li>
* <li>192 bits</li>
* <li>256 bits</li></ul>
*
* \return \c 0 on success.
* \return #UTILS_ERR_AES_INVALID_KEY_LENGTH on failure.
*/
int utils_aes_setkey_enc( utils_aes_context *ctx, const unsigned char *key,
unsigned int keybits );
/**
* \brief This function sets the decryption key.
*
* \param ctx The AES context to which the key should be bound.
* It must be initialized.
* \param key The decryption key.
* This must be a readable buffer of size \p keybits bits.
* \param keybits The size of data passed. Valid options are:
* <ul><li>128 bits</li>
* <li>192 bits</li>
* <li>256 bits</li></ul>
*
* \return \c 0 on success.
* \return #UTILS_ERR_AES_INVALID_KEY_LENGTH on failure.
*/
int utils_aes_setkey_dec( utils_aes_context *ctx, const unsigned char *key,
unsigned int keybits );
/**
* \brief This function performs an AES single-block encryption or
* decryption operation.
*
* It performs the operation defined in the \p mode parameter
* (encrypt or decrypt), on the input data buffer defined in
* the \p input parameter.
*
* utils_aes_init(), and either utils_aes_setkey_enc() or
* utils_aes_setkey_dec() must be called before the first
* call to this API with the same context.
*
* \param ctx The AES context to use for encryption or decryption.
* It must be initialized and bound to a key.
* \param mode The AES operation: #UTILS_AES_ENCRYPT or
* #UTILS_AES_DECRYPT.
* \param input The buffer holding the input data.
* It must be readable and at least \c 16 Bytes long.
* \param output The buffer where the output data will be written.
* It must be writeable and at least \c 16 Bytes long.
* \return \c 0 on success.
*/
int utils_aes_crypt_ecb( utils_aes_context *ctx,
int mode,
const unsigned char input[16],
unsigned char output[16] );
#if defined(UTILS_CIPHER_MODE_CBC)
/**
* \brief This function performs an AES-CBC encryption or decryption operation
* on full blocks.
*
* It performs the operation defined in the \p mode
* parameter (encrypt/decrypt), on the input data buffer defined in
* the \p input parameter.
*
* It can be called as many times as needed, until all the input
* data is processed. utils_aes_init(), and either
* utils_aes_setkey_enc() or utils_aes_setkey_dec() must be called
* before the first call to this API with the same context.
*
* \note This function operates on full blocks, that is, the input size
* must be a multiple of the AES block size of \c 16 Bytes.
*
* \note Upon exit, the content of the IV is updated so that you can
* call the same function again on the next
* block(s) of data and get the same result as if it was
* encrypted in one call. This allows a "streaming" usage.
* If you need to retain the contents of the IV, you should
* either save it manually or use the cipher module instead.
*
*
* \param ctx The AES context to use for encryption or decryption.
* It must be initialized and bound to a key.
* \param mode The AES operation: #UTILS_AES_ENCRYPT or
* #UTILS_AES_DECRYPT.
* \param length The length of the input data in Bytes. This must be a
* multiple of the block size (\c 16 Bytes).
* \param iv Initialization vector (updated after use).
* It must be a readable and writeable buffer of \c 16 Bytes.
* \param input The buffer holding the input data.
* It must be readable and of size \p length Bytes.
* \param output The buffer holding the output data.
* It must be writeable and of size \p length Bytes.
*
* \return \c 0 on success.
* \return #UTILS_ERR_AES_INVALID_INPUT_LENGTH
* on failure.
*/
int utils_aes_crypt_cbc( utils_aes_context *ctx,
int mode,
size_t length,
unsigned char iv[16],
const unsigned char *input,
unsigned char *output );
#endif /* UTILS_CIPHER_MODE_CBC */
/**
* \brief Internal AES block encryption function. This is only
* exposed to allow overriding it using
* \c UTILS_AES_ENCRYPT_ALT.
*
* \param ctx The AES context to use for encryption.
* \param input The plaintext block.
* \param output The output (ciphertext) block.
*
* \return \c 0 on success.
*/
int utils_internal_aes_encrypt( utils_aes_context *ctx,
const unsigned char input[16],
unsigned char output[16] );
/**
* \brief Internal AES block decryption function. This is only
* exposed to allow overriding it using see
* \c UTILS_AES_DECRYPT_ALT.
*
* \param ctx The AES context to use for decryption.
* \param input The ciphertext block.
* \param output The output (plaintext) block.
*
* \return \c 0 on success.
*/
int utils_internal_aes_decrypt( utils_aes_context *ctx,
const unsigned char input[16],
unsigned char output[16] );
#if !defined(UTILS_DEPRECATED_REMOVED)
#if defined(UTILS_DEPRECATED_WARNING)
#define UTILS_DEPRECATED __attribute__((deprecated))
#else
#define UTILS_DEPRECATED
#endif
/**
* \brief Deprecated internal AES block encryption function
* without return value.
*
* \deprecated Superseded by utils_internal_aes_encrypt()
*
* \param ctx The AES context to use for encryption.
* \param input Plaintext block.
* \param output Output (ciphertext) block.
*/
UTILS_DEPRECATED void utils_aes_encrypt( utils_aes_context *ctx,
const unsigned char input[16],
unsigned char output[16] );
/**
* \brief Deprecated internal AES block decryption function
* without return value.
*
* \deprecated Superseded by utils_internal_aes_decrypt()
*
* \param ctx The AES context to use for decryption.
* \param input Ciphertext block.
* \param output Output (plaintext) block.
*/
UTILS_DEPRECATED void utils_aes_decrypt( utils_aes_context *ctx,
const unsigned char input[16],
unsigned char output[16] );
#undef UTILS_DEPRECATED
#endif /* !UTILS_DEPRECATED_REMOVED */
#if defined(UTILS_SELF_TEST)
/**
* \brief Checkup routine.
*
* \return \c 0 on success.
* \return \c 1 on failure.
*/
int utils_aes_self_test( int verbose );
#endif /* UTILS_SELF_TEST */
int aes_sample(int verbose);
int utils_aes_cbc(uint8_t *pInData, uint32_t datalen,
uint8_t *pOutData, uint32_t outBuffLen,
uint8_t mode, uint8_t *pKey,
uint16_t keybits, uint8_t *iv);
#ifdef __cplusplus
}
#endif
#endif

View File

@@ -0,0 +1,37 @@
/*
* Tencent is pleased to support the open source community by making IoT Hub available.
* Copyright (C) 2016 THL A29 Limited, a Tencent company. All rights reserved.
* Licensed under the MIT License (the "License"); you may not use this file except in
* compliance with the License. You may obtain a copy of the License at
* http://opensource.org/licenses/MIT
* Unless required by applicable law or agreed to in writing, software distributed under the License is
* distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
* either express or implied. See the License for the specific language governing permissions and
* limitations under the License.
*
*/
#ifndef QCLOUD_IOT_UTILS_BASE64_H_
#define QCLOUD_IOT_UTILS_BASE64_H_
#ifdef __cplusplus
extern "C" {
#endif
#include <stdio.h>
#include "qcloud_iot_export_log.h"
#include "qcloud_iot_export_error.h"
int qcloud_iot_utils_base64encode( unsigned char *dst, size_t dlen, size_t *olen,
const unsigned char *src, size_t slen );
int qcloud_iot_utils_base64decode( unsigned char *dst, size_t dlen, size_t *olen,
const unsigned char *src, size_t slen );
#ifdef __cplusplus
}
#endif
#endif /* QCLOUD_IOT_UTILS_BASE64_H_ */

View File

@@ -0,0 +1,26 @@
/*
* Tencent is pleased to support the open source community by making IoT Hub available.
* Copyright (C) 2016 THL A29 Limited, a Tencent company. All rights reserved.
* Licensed under the MIT License (the "License"); you may not use this file except in
* compliance with the License. You may obtain a copy of the License at
* http://opensource.org/licenses/MIT
* Unless required by applicable law or agreed to in writing, software distributed under the License is
* distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
* either express or implied. See the License for the specific language governing permissions and
* limitations under the License.
*
*/
#ifndef QCLOUD_IOT_UTILS_HMAC_H_
#define QCLOUD_IOT_UTILS_HMAC_H_
#include <string.h>
void utils_hmac_md5(const char *msg, int msg_len, char *digest, const char *key, int key_len);
void utils_hmac_sha1(const char *msg, int msg_len, char *digest, const char *key, int key_len);
#endif

View File

@@ -0,0 +1,82 @@
/*
* Tencent is pleased to support the open source community by making IoT Hub available.
* Copyright (C) 2016 THL A29 Limited, a Tencent company. All rights reserved.
* Licensed under the MIT License (the "License"); you may not use this file except in
* compliance with the License. You may obtain a copy of the License at
* http://opensource.org/licenses/MIT
* Unless required by applicable law or agreed to in writing, software distributed under the License is
* distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
* either express or implied. See the License for the specific language governing permissions and
* limitations under the License.
*
*/
#ifndef QCLOUD_IOT_UTILS_HTTPC_H_
#define QCLOUD_IOT_UTILS_HTTPC_H_
#ifdef __cplusplus
extern "C" {
#endif
#include <stdbool.h>
#include "network_interface.h"
#define HTTP_PORT 80
#define HTTPS_PORT 443
typedef enum {
HTTP_GET,
HTTP_POST,
HTTP_PUT,
HTTP_DELETE,
HTTP_HEAD
} HttpMethod;
typedef struct {
int remote_port;
int response_code;
char *header;
char *auth_user;
char *auth_password;
Network network_stack;
} HTTPClient;
typedef struct {
bool is_more; // if more data to check
bool is_chunked; // if response in chunked data
int retrieve_len; // length of retrieve
int response_content_len; // length of resposne content
int post_buf_len; // post data length
int response_buf_len; // length of response data buffer
char *post_content_type; // type of post content
char *post_buf; // post data buffer
char *response_buf; // response data buffer
} HTTPClientData;
/**
* @brief do one http request
*
* @param client http client
* @param url server url
* @param port server port
* @param ca_crt_dir ca path
* @param method type of request
* @param client_data http data
* @return QCLOUD_RET_SUCCESS for success, or err code for failure
*/
int qcloud_http_client_common(HTTPClient *client, const char *url, int port, const char *ca_crt, HttpMethod method, HTTPClientData *client_data);
int qcloud_http_recv_data(HTTPClient *client, uint32_t timeout_ms, HTTPClientData *client_data);
int qcloud_http_client_connect(HTTPClient *client, const char *url, int port, const char *ca_crt);
void qcloud_http_client_close(HTTPClient *client);
#ifdef __cplusplus
}
#endif
#endif /* QCLOUD_IOT_UTILS_HTTPC_H_ */

View File

@@ -0,0 +1,97 @@
/*
* Tencent is pleased to support the open source community by making IoT Hub available.
* Copyright (C) 2016 THL A29 Limited, a Tencent company. All rights reserved.
* Licensed under the MIT License (the "License"); you may not use this file except in
* compliance with the License. You may obtain a copy of the License at
* http://opensource.org/licenses/MIT
* Unless required by applicable law or agreed to in writing, software distributed under the License is
* distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
* either express or implied. See the License for the specific language governing permissions and
* limitations under the License.
*
*/
#ifndef QCLOUD_IOT_UTILS_LIST_H_
#define QCLOUD_IOT_UTILS_LIST_H_
#ifdef __cplusplus
extern "C" {
#endif
#include <stdlib.h>
/*
* ListNode iterator direction
*/
typedef enum {
LIST_HEAD,
LIST_TAIL
} ListDirection;
/*
* define list node
*/
typedef struct ListNode {
struct ListNode *prev;
struct ListNode *next;
void *val;
} ListNode;
/*
* Double Linked List
*/
typedef struct {
ListNode *head;
ListNode *tail;
unsigned int len;
void (*free)(void *val);
int (*match)(void *a, void *b);
} List;
/*
* list iterator
*/
typedef struct {
ListNode *next;
ListDirection direction;
} ListIterator;
/* create node */
ListNode *list_node_new(void *val);
/* create list */
List *list_new(void);
ListNode *list_rpush(List *self, ListNode *node);
ListNode *list_lpush(List *self, ListNode *node);
ListNode *list_find(List *self, void *val);
ListNode *list_at(List *self, int index);
ListNode *list_rpop(List *self);
ListNode *list_lpop(List *self);
void list_remove(List *self, ListNode *node);
void list_destroy(List *self);
/* create iterator */
ListIterator *list_iterator_new(List *list, ListDirection direction);
ListIterator *list_iterator_new_from_node(ListNode *node, ListDirection direction);
ListNode *list_iterator_next(ListIterator *self);
void list_iterator_destroy(ListIterator *self);
#ifdef __cplusplus
}
#endif
#endif //QCLOUD_IOT_UTILS_LIST_H_

View File

@@ -0,0 +1,94 @@
/*
* Tencent is pleased to support the open source community by making IoT Hub available.
* Copyright (C) 2016 THL A29 Limited, a Tencent company. All rights reserved.
* Licensed under the MIT License (the "License"); you may not use this file except in
* compliance with the License. You may obtain a copy of the License at
* http://opensource.org/licenses/MIT
* Unless required by applicable law or agreed to in writing, software distributed under the License is
* distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
* either express or implied. See the License for the specific language governing permissions and
* limitations under the License.
*
*/
#ifndef QCLOUD_IOT_UTILS_MD5_H_
#define QCLOUD_IOT_UTILS_MD5_H_
#include "qcloud_iot_import.h"
typedef struct {
uint32_t total[2]; /*!< number of bytes processed */
uint32_t state[4]; /*!< intermediate digest state */
unsigned char buffer[64]; /*!< data block being processed */
} iot_md5_context;
/**
* @brief init MD5 context
*
* @param ctx MD5 context
*/
void utils_md5_init(iot_md5_context *ctx);
/**
* @brief free MD5 context
*
* @param ctx MD5 context
*/
void utils_md5_free(iot_md5_context *ctx);
/**
* @brief clone MD5 context
*
* @param dst destination MD5 context
* @param src source MD5 context
*/
void utils_md5_clone(iot_md5_context *dst,
const iot_md5_context *src);
/**
* @brief start MD5 calculation
*
* @param ctx MD5 context
*/
void utils_md5_starts(iot_md5_context *ctx);
/**
* @brief MD5 update
*
* @param ctx MD5 context
* @param input input data
* @param ilen data length
*/
void utils_md5_update(iot_md5_context *ctx, const unsigned char *input, size_t ilen);
/**
* @brief finish MD5 calculation
*
* @param ctx MD5 context
* @param output MD5 result
*/
void utils_md5_finish(iot_md5_context *ctx, unsigned char output[16]);
/* MD5 internal process */
void utils_md5_process(iot_md5_context *ctx, const unsigned char data[64]);
/**
* @brief Output = MD5( input buffer )
*
* @param input data input
* @param ilen data lenght
* @param output MD5 result
*/
void utils_md5(const unsigned char *input, size_t ilen, unsigned char output[16]);
int8_t utils_hb2hex(uint8_t hb);
#endif

View File

@@ -0,0 +1,85 @@
/*
* Tencent is pleased to support the open source community by making IoT Hub available.
* Copyright (C) 2016 THL A29 Limited, a Tencent company. All rights reserved.
* Licensed under the MIT License (the "License"); you may not use this file except in
* compliance with the License. You may obtain a copy of the License at
* http://opensource.org/licenses/MIT
* Unless required by applicable law or agreed to in writing, software distributed under the License is
* distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
* either express or implied. See the License for the specific language governing permissions and
* limitations under the License.
*
*/
#ifndef _UTILS_PARAM_CHECK_H_
#define _UTILS_PARAM_CHECK_H_
#if defined(__cplusplus)
extern "C" {
#endif
#include "qcloud_iot_export_log.h"
#define NUMBERIC_SANITY_CHECK(num, err) \
do { \
if (0 == (num)) { \
Log_e("Invalid argument, numeric 0"); \
return (err); \
} \
} while(0)
#define NUMBERIC_SANITY_CHECK_RTN(num) \
do { \
if (0 == (num)) { \
Log_e("Invalid argument, numeric 0"); \
return; \
} \
} while(0)
#define POINTER_SANITY_CHECK(ptr, err) \
do { \
if (NULL == (ptr)) { \
Log_e("Invalid argument, %s = %p", #ptr, ptr); \
return (err); \
} \
} while(0)
#define POINTER_SANITY_CHECK_RTN(ptr) \
do { \
if (NULL == (ptr)) { \
Log_e("Invalid argument, %s = %p", #ptr, ptr); \
return; \
} \
} while(0)
#define STRING_PTR_SANITY_CHECK(ptr, err) \
do { \
if (NULL == (ptr)) { \
Log_e("Invalid argument, %s = %p", #ptr, (ptr)); \
return (err); \
} \
if (0 == strlen((ptr))) { \
Log_e("Invalid argument, %s = '%s'", #ptr, (ptr)); \
return (err); \
} \
} while(0)
#define STRING_PTR_SANITY_CHECK_RTN(ptr) \
do { \
if (NULL == (ptr)) { \
Log_e("Invalid argument, %s = %p", #ptr, (ptr)); \
return; \
} \
if (0 == strlen((ptr))) { \
Log_e("Invalid argument, %s = '%s'", #ptr, (ptr)); \
return; \
} \
} while(0)
#if defined(__cplusplus)
}
#endif
#endif /* _UTILS_PARAM_CHECK_H_ */

View File

@@ -0,0 +1,50 @@
/*
* Tencent is pleased to support the open source community by making IoT Hub available.
* Copyright (C) 2019 THL A29 Limited, a Tencent company. All rights reserved.
* Licensed under the MIT License (the "License"); you may not use this file except in
* compliance with the License. You may obtain a copy of the License at
* http://opensource.org/licenses/MIT
* Unless required by applicable law or agreed to in writing, software distributed under the License is
* distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
* either express or implied. See the License for the specific language governing permissions and
* limitations under the License.
*
*/
#ifndef __AT_RING_BUFF_H__
#define __AT_RING_BUFF_H__
#include "stdbool.h"
#include "stdint.h"
#define RINGBUFF_OK 0 /* No error, everything OK. */
#define RINGBUFF_ERR -1 /* Out of memory error. */
#define RINGBUFF_EMPTY -3 /* Timeout. */
#define RINGBUFF_FULL -4 /* Routing problem. */
#define RINGBUFF_TOO_SHORT -5
typedef struct _ring_buff_
{
uint32_t size;
uint32_t readpoint;
uint32_t writepoint;
char* buffer;
bool full;
} sRingbuff;
typedef sRingbuff* ring_buff_t;
int ring_buff_init(sRingbuff* ring_buff, char* buff, uint32_t size );
int ring_buff_flush(sRingbuff* ring_buff);
int ring_buff_push_data(sRingbuff* ring_buff, uint8_t *pData, int len);
int ring_buff_pop_data(sRingbuff* ring_buff, uint8_t *pData, int len);
#endif // __ringbuff_h__

View File

@@ -0,0 +1,90 @@
/*
* Tencent is pleased to support the open source community by making IoT Hub available.
* Copyright (C) 2016 THL A29 Limited, a Tencent company. All rights reserved.
* Licensed under the MIT License (the "License"); you may not use this file except in
* compliance with the License. You may obtain a copy of the License at
* http://opensource.org/licenses/MIT
* Unless required by applicable law or agreed to in writing, software distributed under the License is
* distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
* either express or implied. See the License for the specific language governing permissions and
* limitations under the License.
*
*/
#ifndef QCLOUD_IOT_UTILS_SHA1_H_
#define QCLOUD_IOT_UTILS_SHA1_H_
#include "qcloud_iot_import.h"
/**
* \brief SHA-1 context structure
*/
typedef struct {
uint32_t total[2]; /*!< number of bytes processed */
uint32_t state[5]; /*!< intermediate digest state */
unsigned char buffer[64]; /*!< data block being processed */
} iot_sha1_context;
/**
* \brief Initialize SHA-1 context
*
* \param ctx SHA-1 context to be initialized
*/
void utils_sha1_init(iot_sha1_context *ctx);
/**
* \brief Clear SHA-1 context
*
* \param ctx SHA-1 context to be cleared
*/
void utils_sha1_free(iot_sha1_context *ctx);
/**
* \brief Clone (the state of) a SHA-1 context
*
* \param dst The destination context
* \param src The context to be cloned
*/
void utils_sha1_clone(iot_sha1_context *dst,
const iot_sha1_context *src);
/**
* \brief SHA-1 context setup
*
* \param ctx context to be initialized
*/
void utils_sha1_starts(iot_sha1_context *ctx);
/**
* \brief SHA-1 process buffer
*
* \param ctx SHA-1 context
* \param input buffer holding the data
* \param ilen length of the input data
*/
void utils_sha1_update(iot_sha1_context *ctx, const unsigned char *input, size_t ilen);
/**
* \brief SHA-1 final digest
*
* \param ctx SHA-1 context
* \param output SHA-1 checksum result
*/
void utils_sha1_finish(iot_sha1_context *ctx, unsigned char output[20]);
/* Internal use */
void utils_sha1_process(iot_sha1_context *ctx, const unsigned char data[64]);
/**
* \brief Output = SHA-1( input buffer )
*
* \param input buffer holding the data
* \param ilen length of the input data
* \param output SHA-1 checksum result
*/
void utils_sha1(const unsigned char *input, size_t ilen, unsigned char output[20]);
#endif

View File

@@ -0,0 +1,80 @@
/*
* Tencent is pleased to support the open source community by making IoT Hub available.
* Copyright (C) 2016 THL A29 Limited, a Tencent company. All rights reserved.
* Licensed under the MIT License (the "License"); you may not use this file except in
* compliance with the License. You may obtain a copy of the License at
* http://opensource.org/licenses/MIT
* Unless required by applicable law or agreed to in writing, software distributed under the License is
* distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
* either express or implied. See the License for the specific language governing permissions and
* limitations under the License.
*
*/
#ifndef QCLOUD_IOT_UTILS_TIMER_H_
#define QCLOUD_IOT_UTILS_TIMER_H_
#ifdef __cplusplus
extern "C" {
#endif
// Add the platform specific timer includes to define the Timer struct
#include "qcloud_iot_import.h"
/**
* @brief Check if a timer is expired
*
* Call this function passing in a timer to check if that timer has expired.
*
* @param timer - pointer to the timer to be checked for expiration
* @return bool - true = timer expired, false = timer not expired
*/
bool expired(Timer *timer);
/**
* @brief Create a timer (milliseconds)
*
* Sets the timer to expire in a specified number of milliseconds.
*
* @param timer - pointer to the timer to be set to expire in milliseconds
* @param timeout_ms - set the timer to expire in this number of milliseconds
*/
void countdown_ms(Timer *timer, unsigned int timeout_ms);
/**
* @brief Create a timer (seconds)
*
* Sets the timer to expire in a specified number of seconds.
*
* @param timer - pointer to the timer to be set to expire in seconds
* @param timeout - set the timer to expire in this number of seconds
*/
void countdown(Timer *timer, unsigned int timeout);
/**
* @brief Check the time remaining on a give timer
*
* Checks the input timer and returns the number of milliseconds remaining on the timer.
*
* @param timer - pointer to the timer to be set to checked
* @return int - milliseconds left on the countdown timer
*/
int left_ms(Timer *timer);
/**
* @brief Initialize a timer
*
* Performs any initialization required to the timer passed in.
*
* @param timer - pointer to the timer to be initialized
*/
void InitTimer(Timer *timer);
#ifdef __cplusplus
}
#endif
#endif //QCLOUD_IOT_UTILS_TIMER_H_