update qcloud sdk

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

View File

@@ -0,0 +1,160 @@
/*
* Tencent is pleased to support the open source community by making IoT Hub available.
* Copyright (C) 2018-2020 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 "config.h"
#include "stddef.h"
#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_ERROR = -1, /* AT response end is 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 '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
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,87 @@
/*
* Tencent is pleased to support the open source community by making IoT Hub available.
* Copyright (C) 2018-2020 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_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,103 @@
/*
* Tencent is pleased to support the open source community by making IoT Hub available.
* Copyright (C) 2018-2020 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,46 @@
/*
* Tencent is pleased to support the open source community by making IoT Hub available.
* Copyright (C) 2018-2020 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_UTILS_H_
#define _AT_UTILS_H_
#include <stdarg.h>
#include <stdio.h>
#include <stdlib.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,471 @@
/*
* Tencent is pleased to support the open source community by making IoT Hub available.
* Copyright (C) 2018-2020 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_COAP_CLIENT_H_
#define IOT_COAP_CLIENT_H_
#ifdef __cplusplus
extern "C" {
#endif
#include <stddef.h>
#include <sys/types.h>
#include "coap_client_net.h"
#include "network_interface.h"
#include "qcloud_iot_common.h"
#include "qcloud_iot_export.h"
#include "utils_list.h"
#include "utils_timer.h"
/* COAP protocol version */
#define COAP_MSG_VER (0x01)
/* COAP init token */
#define COAP_MSG_INIT_TOKEN (0x01020304)
/* Minimal command timeout of CoAP ACK/RESP */
#define MIN_COMMAND_TIMEOUT (500)
/* Maximal command timeout of CoAP ACK/RESP */
#define MAX_COMMAND_TIMEOUT (5000)
/* Max size of conn Id */
#define COAP_MAX_CONN_ID_LEN (6)
/* Max size of Message id */
#define COAP_MSG_MAX_MSG_ID ((1 << 16) - 1)
/* Max size of Topic length */
#define URI_PATH_MAX_LEN (128)
/* CoAP auth success */
#define COAP_TRUE (1)
/* CoAP auth fail */
#define COAP_FALSE (0)
/* unique CoAP auth URI */
#define COAP_AUTH_URI ("txauth9w0BAQsFA")
/* Max size of token */
#define COAP_MSG_MAX_TOKEN_LEN (8)
/* COAP Max code class */
#define COAP_MSG_MAX_CODE_CLASS (7)
/* COAP Max code detail */
#define COAP_MSG_MAX_CODE_DETAIL (31)
/* Get field of Option num */
#define COAP_MSG_OPTION_NUM(option) ((option)->option_num)
/* Get field of Next Option */
#define COAP_MSG_OP_NEXT(option) ((option)->next)
/* If COAP msg is empty */
#define COAP_MSG_IS_EMPTY(message) (((message)->code_class == 0) && ((message)->code_detail == 0))
/* If COAP msg is empty ACK */
#define COAP_MSG_IS_EMPTY_ACK(message) (((message)->code_class == 2) && ((message)->code_detail == 3))
/* If COAP msg is RESP */
#define COAP_MSG_IS_EMPTY_RSP(message) (((message)->code_class == 2) && ((message)->code_detail == 5))
/**
* @brief COAP msg type
*/
typedef enum {
COAP_MSG_REQ = 0,
COAP_MSG_SUCCESS = 2,
COAP_MSG_CLIENT_ERR = 4,
COAP_MSG_SERVER_ERR = 5,
COAP_MSG_SDKINTERNAL_ERR = 6,
} CoAPMessageClass;
/**
* @brief COAP msg type
*/
typedef enum { COAP_MSG_GET = 1, COAP_MSG_POST = 2, COAP_MSG_PUT = 3, COAP_MSG_DELETE = 4 } CoAPRequestMethod;
typedef enum {
/* CoAP Success Response code detail */
COAP_MSG_CODE_201_CREATED = 01, /* Mapping to CoAP codeClass.codeDetail 2.01 */
COAP_MSG_CODE_202_DELETED = 02, /* Mapping to CoAP codeClass.codeDetail 2.02 */
COAP_MSG_CODE_203_VALID = 03, /* Mapping to CoAP codeClass.codeDetail 2.03 */
COAP_MSG_CODE_204_CHANGED = 04, /* Mapping to CoAP codeClass.codeDetail 2.04 */
COAP_MSG_CODE_205_CONTENT = 05, /* Mapping to CoAP codeClass.codeDetail 2.05 */
COAP_MSG_CODE_231_CONTINUE = 31, /* Mapping to CoAP codeClass.codeDetail 2.31 */
/* CoAP Client Error Response code detail */
COAP_MSG_CODE_400_BAD_REQUEST = 00, /* Mapping to CoAP codeClass.codeDetail 4.00 */
COAP_MSG_CODE_401_UNAUTHORIZED = 01, /* Mapping to CoAP codeClass.codeDetail 4.01 */
COAP_MSG_CODE_402_BAD_OPTION = 02, /* Mapping to CoAP codeClass.codeDetail 4.02 */
COAP_MSG_CODE_403_FORBIDDEN = 03, /* Mapping to CoAP codeClass.codeDetail 4.03 */
COAP_MSG_CODE_404_NOT_FOUND = 04, /* Mapping to CoAP codeClass.codeDetail 4.04 */
COAP_MSG_CODE_405_METHOD_NOT_ALLOWED = 05, /* Mapping to CoAP codeClass.codeDetail 4.05 */
COAP_MSG_CODE_406_NOT_ACCEPTABLE = 06, /* Mapping to CoAP codeClass.codeDetail 4.06 */
COAP_MSG_CODE_408_REQUEST_ENTITY_INCOMPLETE = 8, /* Mapping to CoAP codeClass.codeDetail 4.08 */
COAP_MSG_CODE_412_PRECONDITION_FAILED = 12, /* Mapping to CoAP codeClass.codeDetail 4.12 */
COAP_MSG_CODE_413_REQUEST_ENTITY_TOO_LARGE = 13, /* Mapping to CoAP codeClass.codeDetail 4.13 */
COAP_MSG_CODE_415_UNSUPPORTED_CONTENT_FORMAT = 15, /* Mapping to CoAP codeClass.codeDetail 4.15 */
/* CoAP Server Error Response code detail */
COAP_MSG_CODE_500_INTERNAL_SERVER_ERROR = 00, /* Mapping to CoAP codeClass.codeDetail 5.00 */
COAP_MSG_CODE_501_NOT_IMPLEMENTED = 01, /* Mapping to CoAP codeClass.codeDetail 5.01 */
COAP_MSG_CODE_502_BAD_GATEWAY = 02, /* Mapping to CoAP codeClass.codeDetail 5.02 */
COAP_MSG_CODE_503_SERVICE_UNAVAILABLE = 03, /* Mapping to CoAP codeClass.codeDetail 5.03 */
COAP_MSG_CODE_504_GATEWAY_TIMEOUT = 04, /* Mapping to CoAP codeClass.codeDetail 5.04 */
COAP_MSG_CODE_505_PROXYING_NOT_SUPPORTED = 05, /* Mapping to CoAP codeClass.codeDetail 5.05 */
COAP_MSG_CODE_600_TIMEOUT = 00, /* Mapping to self define CoAP codeClass.codeDetail 6.00 */
} CoAPRespCodeDetail;
/**
* @brief Option number enumeration
*/
typedef enum {
COAP_MSG_IF_MATCH = 1, // If-Match option number
COAP_MSG_URI_HOST = 3, // URI-Host option number
COAP_MSG_ETAG = 4, // Entity-Tag option number
COAP_MSG_IF_NONE_MATCH = 5, // If-None-Match option number
COAP_MSG_URI_PORT = 7, // URI-Port option number
COAP_MSG_LOCATION_PATH = 8, // Location-Path option number
COAP_MSG_URI_PATH = 11, // URI-Path option number
COAP_MSG_CONTENT_FORMAT = 12, // Content-Format option number
COAP_MSG_MAX_AGE = 14, // Max-Age option number
COAP_MSG_URI_QUERY = 15, // URI-Query option number
COAP_MSG_ACCEPT = 17, // Accept option number
COAP_MSG_LOCATION_QUERY = 20, // Location-Query option number
COAP_MSG_BLOCK2 = 23, // Block2 option number
COAP_MSG_BLOCK1 = 27, // Block1 option number
COAP_MSG_SIZE2 = 28, // Size2 option number
COAP_MSG_PROXY_URI = 35, // Proxy-URI option number
COAP_MSG_PROXY_SCHEME = 39, // Proxy-Scheme option number
COAP_MSG_SIZE1 = 60, // Size1 option number
COAP_MSG_AUTH_TOKEN = 61, // auth token option number
COAP_MSG_NEED_RESP = 62, // CoAP need content response
} CoAPMsgOptionNum;
/* CoAP QCloud IoT Client structure */
typedef struct Client {
char is_authed; // CoAP Client auth or not
char conn_id[COAP_MAX_CONN_ID_LEN]; // conn id for a CoAP connection
unsigned int message_token; // msg token
char *auth_token; // auth token
int auth_token_len;
uint16_t next_msg_id; // COAP msg id
size_t send_buf_size; // size of write buffer
size_t read_buf_size; // size of read buffer
unsigned char send_buf[COAP_SENDMSG_MAX_BUFLEN];
unsigned char recv_buf[COAP_RECVMSG_MAX_BUFLEN];
void *lock_send_buf; // mutex/lock for write buffer
void *lock_list_wait_ack; // mutex/lock for wait ack list
Network network_stack; // MQTT network stack
uint32_t command_timeout_ms; // CoAP command timeout, unit:ms
List *message_list; // msg list
unsigned char max_retry_count; // Max retry count
CoAPEventHandler event_handle; // event callback
DeviceInfo device_info;
char host_addr[HOST_STR_LENGTH];
#ifdef AUTH_MODE_CERT
char cert_file_path[FILE_PATH_MAX_LEN]; // full path of device cert file
char key_file_path[FILE_PATH_MAX_LEN]; // full path of device key file
#else
unsigned char psk_decode[DECODE_PSK_LENGTH];
#endif
} CoAPClient;
/**
* @brief CoAP Option
*/
typedef struct coap_msg_op {
unsigned short option_num; // Option number
unsigned val_len; // Option length
char * val; // Pointer to a buffer containing the option value
struct coap_msg_op *next; // Pointer to the next option structure in the list
} CoAPMsgOption;
/**
* @brief CoAP Option list
*/
typedef struct {
CoAPMsgOption *first; // Pointer to the first option structure in the list
CoAPMsgOption *last; // Pointer to the last option structure in the list
} CoAPMsgOptionList;
/**
* @brief CoAP node state
*/
typedef enum {
COAP_NODE_STATE_NORMANL = 0,
COAP_NODE_STATE_INVALID,
} CoAPNodeState;
typedef struct {
CoAPNodeState node_state;
void * user_context;
unsigned short msg_id;
char acked;
unsigned char token_len;
unsigned char token[COAP_MSG_MAX_TOKEN_LEN];
unsigned char retrans_count;
Timer start_time;
unsigned char *message;
unsigned int msglen;
OnRespCallback handler;
} CoAPMsgSendInfo;
/**
* @brief COAP msg type
*/
typedef enum {
COAP_MSG_CON = 0x0, /**< msg need to wait for ACK */
COAP_MSG_NON = 0x1, /**< msg no need to wait for ACK */
COAP_MSG_ACK = 0x2, /**< msg ACK */
COAP_MSG_RST = 0x3 /**< msg Reset */
} CoAPMsgType;
/**
* @brief CoAP message structure
*/
typedef struct {
unsigned version; // CoAP protocol version
CoAPMsgType type; // msg type
unsigned code_class; // Code class
unsigned code_detail; // Code detail
unsigned short msg_id; // msg id
char * pay_load; // msg payload
size_t pay_load_len; // length of payload
char token[COAP_MSG_MAX_TOKEN_LEN]; // msg token
unsigned token_len; // length of token
CoAPMsgOptionList op_list; // Option list
OnRespCallback handler; // CoAP Response msg callback
void * user_context; // user context
} CoAPMessage;
#define DEFAULT_COAP_MESSAGE \
{ \
COAP_MSG_VER, COAP_MSG_CON, COAP_MSG_REQ, COAP_MSG_POST, 0, NULL, 0, {0}, 0, {0}, NULL, NULL \
}
/**
* @brief Init CoAPClient
*
* @param pClient reference to CoAP client
* @param pParams CoAP init parameters
* @return QCLOUD_RET_SUCCESS for success, or err code for failure
*/
int qcloud_iot_coap_init(CoAPClient *pClient, CoAPInitParams *pParams);
/**
* @brief Generate next CoAPMessage msg Id
*
* @param pClient reference to CoAP client
* @return msg Id
*/
uint16_t get_next_coap_msg_id(CoAPClient *pClient);
/**
* @brief Generate next CoAPMessage msg token
*
* @param pClient reference to CoAP client
* @param tokenData msg token
* @return token length
*/
unsigned int get_coap_message_token(CoAPClient *client, char *tokenData);
/**
* @brief set message type
*
* @param message CoAP msg
* @param
* @return QCLOUD_RET_SUCCESS for success, or err code for failure
*/
int coap_message_type_set(CoAPMessage *message, unsigned type);
/**
* @brief set message code
*
* @param message CoAP msg
* @param code_class CoAPMessageClass
* @param code_detail
* @return QCLOUD_RET_SUCCESS for success, or err code for failure
*/
int coap_message_code_set(CoAPMessage *message, unsigned code_class, unsigned code_detail);
/**
* @brief set message Id
*
* @param message CoAP msg
* @param msg_id
* @return QCLOUD_RET_SUCCESS for success, or err code for failure
*/
int coap_message_id_set(CoAPMessage *message, unsigned msg_id);
/**
* @brief set msg token
*
* @param message CoAP msg
* @param buf token string
* @param len token length
* @return QCLOUD_RET_SUCCESS for success, or err code for failure
*/
int coap_message_token_set(CoAPMessage *message, char *buf, size_t len);
/**
* @brief set msg payload
*
* @param message CoAP msg
* @param buf msg payload buffer
* @param len length of payload
* @return QCLOUD_RET_SUCCESS for success, or err code for failure
*/
int coap_message_payload_set(CoAPMessage *message, char *buf, size_t len);
/**
* @brief add msg option
*
* @param message CoAP msg
* @param num option number
* @param len option length
* @param val option string
* @return QCLOUD_RET_SUCCESS for success, or err code for failure
*/
int coap_message_option_add(CoAPMessage *message, unsigned num, unsigned len, const char *val);
/**
* @brief set msg callback
*
* @param message CoAP msg
* @param callback
* @return QCLOUD_RET_SUCCESS for success, or err code for failure
*/
int coap_message_callback_set(CoAPMessage *message, OnRespCallback callback);
/**
* @brief set user context
*
* @param message CoAP msg
* @param userContext
* @return QCLOUD_RET_SUCCESS for success, or err code for failure
*/
int coap_message_context_set(CoAPMessage *message, void *userContext);
/**
* @brief create CoAPMsgOption from option number/len/val
*
* @param num CoAP option number
* @param len CoAP option string len
* @param val CoAP option string value
* @return QCLOUD_RET_SUCCESS for success, or err code for failure
*/
CoAPMsgOption *qcloud_iot_coap_option_init(unsigned num, unsigned len, const char *val);
/**
* @brief destroy CoAPMessage
*
* @param[in,out] message
*/
void coap_message_destroy(CoAPMessage *message);
/**
* @brief Read and handle CoAP msg
*
* @param pClient CoAPClient
* @param timeout_ms timeout value in millisecond
* @return QCLOUD_RET_SUCCESS for success, or err code for failure
*/
int coap_message_cycle(CoAPClient *client, uint32_t timeout_ms);
/**
* @brief Send CoAP msg
*
* @param client CoAPClient
* @param message msg to send
* @return QCLOUD_RET_SUCCESS for success, or err code for failure
*/
ssize_t coap_message_send(CoAPClient *client, CoAPMessage *message);
/**
* @brief Read CoAP msg
*
* @param client CoAPClient
* @param timeout_ms timeout value in millisecond
* @return QCLOUD_RET_SUCCESS for success, or err code for failure
*/
ssize_t coap_message_recv(CoAPClient *client, uint32_t timeout_ms);
/**
* @brief do CoAPClient auth
*
* @param client CoAPClient
* @return QCLOUD_RET_SUCCESS for success, or err code for failure
*/
int coap_client_auth(CoAPClient *client);
/**
* @brief Parse a message
*
* @param[in,out] message Pointer to a message structure
* @param[in] buf Pointer to a buffer containing the message
* @param[in] len Length of the buffer
*
* @returns Operation status
* @retval 0 Success
* @retval <0 Error
*/
ssize_t deserialize_coap_message(CoAPMessage *message, char *buf, size_t len);
/**
* @brief Format a message
*
* @param[in] message Pointer to a message structure
* @param[out] buf Pointer to a buffer to contain the formatted message
* @param[in] len Length of the buffer
*
* @returns Length of the formatted message or error code
* @retval >0 Length of the formatted message
* @retval <0 Error
*/
ssize_t serialize_coap_message(CoAPMessage *message, char *buf, size_t len);
void coap_msg_dump(CoAPMessage *msg);
#ifdef __cplusplus
}
#endif
#endif /* IOT_COAP_CLIENT_H_ */

View File

@@ -0,0 +1,32 @@
/*
* Tencent is pleased to support the open source community by making IoT Hub available.
* Copyright (C) 2018-2020 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_COAP_CLIENT_NET_H_
#define IOT_COAP_CLIENT_NET_H_
#ifdef __cplusplus
extern "C" {
#endif
#include <stdio.h>
#include "network_interface.h"
int qcloud_iot_coap_network_init(Network *pNetwork);
#ifdef __cplusplus
}
#endif
#endif /* IOT_COAP_CLIENT_NET_H_ */

View File

@@ -0,0 +1,97 @@
/*
* Tencent is pleased to support the open source community by making IoT Hub available.
* Copyright (C) 2018-2020 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_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;
char recv_buf[GATEWAY_RECEIVE_BUFFER_LEN];
} 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,141 @@
/*
* Tencent is pleased to support the open source community by making IoT Hub available.
* Copyright (C) 2018-2020 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 __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,103 @@
/*
* Tencent is pleased to support the open source community by making IoT Hub available.
* Copyright (C) 2018-2020 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,563 @@
/*
* Tencent is pleased to support the open source community by making IoT Hub available.
* Copyright (C) 2018-2020 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 <stdbool.h>
#include <stddef.h>
#include <stdint.h>
#include "mqtt_client_net.h"
#include "qcloud_iot_common.h"
#include "qcloud_iot_export.h"
#include "qcloud_iot_import.h"
#include "utils_list.h"
#include "utils_param_check.h"
#include "utils_timer.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)
#define MQTT_RMDUP_MSG_ENABLED
/**
* @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 data structure for system time service
*/
typedef struct _sys_mqtt_state {
bool topic_sub_ok;
bool result_recv_ok;
long time;
} SysMQTTState;
/**
* @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
DeviceInfo device_info;
char host_addr[HOST_STR_LENGTH];
#ifdef AUTH_MODE_CERT
char cert_file_path[FILE_PATH_MAX_LEN]; // full path of device cert file
char key_file_path[FILE_PATH_MAX_LEN]; // full path of device key file
#else
unsigned char psk_decode[DECODE_PSK_LENGTH];
#endif
#ifdef MQTT_RMDUP_MSG_ENABLED
#define MQTT_MAX_REPEAT_BUF_LEN 10
uint16_t repeat_packet_id_buf[MQTT_MAX_REPEAT_BUF_LEN];
unsigned int current_packet_id_cnt;
#endif
#ifdef SYSTEM_COMM
SysMQTTState sys_state;
#endif
#ifdef MULTITHREAD_ENABLED
bool thread_running;
int thread_exit_code;
#endif
} 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_fini(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 if MQTT topic has been subscribed or not
*
* @param pClient handle to MQTT client
* @param topicFilter MQTT topic filter
*
* @return true when successfully subscribed, or false if not yet
*/
bool qcloud_iot_mqtt_is_sub_ready(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);
// workaround wrapper for qcloud_iot_mqtt_yield for multi-thread mode
int qcloud_iot_mqtt_yield_mt(Qcloud_IoT_Client *mqtt_client, 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(Qcloud_IoT_Client *pClient);
#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) 2018-2020 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,127 @@
/*
* Tencent is pleased to support the open source community by making IoT Hub available.
* Copyright (C) 2018-2020 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,57 @@
/*
* Tencent is pleased to support the open source community by making IoT Hub available.
* Copyright (C) 2018-2020 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,37 @@
/*
* Tencent is pleased to support the open source community by making IoT Hub available.
* Copyright (C) 2018-2020 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,82 @@
/*
* Tencent is pleased to support the open source community by making IoT Hub available.
* Copyright (C) 2018-2020 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 <stdint.h>
#include <sys/types.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,31 @@
/*
* Tencent is pleased to support the open source community by making IoT Hub available.
* Copyright (C) 2018-2020 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,47 @@
/*
* Tencent is pleased to support the open source community by making IoT Hub available.
* Copyright (C) 2018-2020 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,32 @@
/*
* Tencent is pleased to support the open source community by making IoT Hub available.
* Copyright (C) 2018-2020 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_set(DeviceInfo *device_info, const char *product_id, const char *device_name);
#ifdef __cplusplus
}
#endif
#endif /* IOT_DEVICE_H_ */

View File

@@ -0,0 +1,121 @@
/*
* Tencent is pleased to support the open source community by making IoT Hub available.
* Copyright (C) 2018-2020 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_SHADOW_CLIENT_H_
#define IOT_SHADOW_CLIENT_H_
#ifdef __cplusplus
extern "C" {
#endif
#include <stdbool.h>
#include "mqtt_client.h"
#include "qcloud_iot_device.h"
#include "qcloud_iot_export.h"
#include "qcloud_iot_import.h"
#include "shadow_client_json.h"
#include "utils_param_check.h"
/* Max number of requests in appending state */
#define MAX_APPENDING_REQUEST_AT_ANY_GIVEN_TIME (10)
/* 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)
/* Size of buffer to receive JSON document from server */
#define CLOUD_IOT_JSON_RX_BUF_LEN (QCLOUD_IOT_MQTT_RX_BUF_LEN + 1)
/**
* @brief define type of request parameters
*/
typedef struct _RequestParam {
Method method; // method type: GET, UPDATE, DELETE
uint32_t timeout_sec; // request timeout in second
OnRequestCallback request_callback; // request callback
void *user_context; // user context for callback
} RequestParams;
#define DEFAULT_REQUEST_PARAMS {GET, 4, NULL, NULL};
/**
* @brief for property and it's callback
*/
typedef struct {
void *property;
OnPropRegCallback callback;
} PropertyHandler;
typedef struct _ShadowInnerData {
uint32_t token_num;
int32_t sync_status;
List * request_list;
List * property_handle_list;
char * result_topic;
} ShadowInnerData;
typedef struct _Shadow {
void * mqtt;
void * mutex;
eShadowType shadow_type;
MQTTEventHandler event_handle;
ShadowInnerData inner_data;
char shadow_recv_buf[CLOUD_IOT_JSON_RX_BUF_LEN];
} Qcloud_IoT_Shadow;
int qcloud_iot_shadow_init(Qcloud_IoT_Shadow *pShadow);
void qcloud_iot_shadow_reset(void *pClient);
/**
* @brief handle the expired requests in list
*
* @param pShadow shadow client
*/
void handle_expired_request(Qcloud_IoT_Shadow *pShadow);
/**
* @brief Entry of all shadow JSON request
*
* @param pShadow shadow client
* @param pParams request param
* @param pJsonDoc JSON buffer
* @param sizeOfBuffer size of buffer
* @return QCLOUD_RET_SUCCESS for success, or err code for failure
*/
int do_shadow_request(Qcloud_IoT_Shadow *pShadow, RequestParams *pParams, char *pJsonDoc, size_t sizeOfBuffer);
/**
* @brief subscribe shadow topic $shadow/operation/result
*
* @param pShadow shadow client
* @return QCLOUD_RET_SUCCESS for success, or err code for failure
*/
int subscribe_operation_result_to_cloud(Qcloud_IoT_Shadow *pShadow);
#ifdef __cplusplus
}
#endif
#endif /* IOT_SHADOW_CLIENT_H_ */

View File

@@ -0,0 +1,58 @@
/*
* Tencent is pleased to support the open source community by making IoT Hub available.
* Copyright (C) 2018-2020 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_SHADOW_CLIENT_COMMON_H_
#define IOT_SHADOW_CLIENT_COMMON_H_
#ifdef __cplusplus
extern "C" {
#endif
#include "shadow_client.h"
/**
* @brief register a device property
*
* @param pShadow shadow client
* @param pProperty device property
* @param callback callback when property changes
* @return QCLOUD_RET_SUCCESS for success, or err code for failure
*/
int shadow_common_register_property_on_delta(Qcloud_IoT_Shadow *pShadow, DeviceProperty *pProperty,
OnPropRegCallback callback);
/**
* @brief remove a device property
*
* @param pShadow shadow client
* @param pProperty device property
* @return QCLOUD_RET_SUCCESS for success, or err code for failure
*/
int shadow_common_remove_property(Qcloud_IoT_Shadow *pshadow, DeviceProperty *pProperty);
/**
* @brief check if a device property exists
*
* @param pShadow shadow client
* @param pProperty device property
* @return 0 = not existed
*/
int shadow_common_check_property_existence(Qcloud_IoT_Shadow *pshadow, DeviceProperty *pProperty);
#ifdef __cplusplus
}
#endif
#endif // IOT_SHADOW_CLIENT_COMMON_H_

View File

@@ -0,0 +1,186 @@
/*
* Tencent is pleased to support the open source community by making IoT Hub available.
* Copyright (C) 2018-2020 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_SHADOW_CLIENT_JSON_H_
#define IOT_SHADOW_CLIENT_JSON_H_
#ifdef __cplusplus
extern "C" {
#endif
#include <stdarg.h>
#include <stdbool.h>
#include <stddef.h>
#include <stdint.h>
#include "qcloud_iot_export.h"
#include "qcloud_iot_import.h"
#define VERSION_FIELD "version"
#define TYPE_FIELD "type"
#define CLIENT_TOKEN_FIELD "clientToken"
#define RESULT_FIELD "result"
#define OPERATION_DELTA "delta"
#define OPERATION_GET "get"
#define OPERATION_UPDATE "update"
#define PAYLOAD_STATE "payload.state"
#define PAYLOAD_VERSION "payload.version"
#define PAYLOAD_STATE_DELTA "payload.state.delta"
#define REPLY_CODE "code"
#define REPLY_STATUS "status"
/**
* 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 event 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 event_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
* @param product_id device product ID
* @return QCLOUD_RET_SUCCESS for success, or err code for failure
*/
int generate_client_token(char *pStrBuffer, size_t sizeOfBuffer, uint32_t *tokenNumber, char *product_id);
/**
* @brief generate an empty JSON with only clientToken
*
* @param tokenNumber shadow token number, increment every time
* @param pJsonBuffer JSON string buffer
* @param product_id device product ID
*/
void build_empty_json(uint32_t *tokenNumber, char *pJsonBuffer, char *product_id);
/**
* @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 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 parse field of version from JSON string
*
* @param pJsonDoc source JSON string
* @param pVersionNumber pointer to version
* @return true for success
*/
bool parse_version_num(char *pJsonDoc, uint32_t *pVersionNumber);
/**
* @brief parse field of state from JSON string
*
* @param pJsonDoc source JSON string
* @param pState pointer to field of state
* @return true for success
*/
bool parse_shadow_state(char *pJsonDoc, char **pState);
/**
* @brief parse field of type from JSON string
*
* @param pJsonDoc source JSON string
* @param pType pointer to field of tyde
* @return true for success
*/
bool parse_shadow_operation_type(char *pJsonDoc, char **pType);
/**
* @brief parse field of result from JSON string
*
* @param pJsonDoc source JSON string
* @param pResultCode pointer to result code
* @return true for success
*/
bool parse_shadow_operation_result_code(char *pJsonDoc, int16_t *pResultCode);
/**
* @brief parse field of delta from JSON string
*
* @param pJsonDoc source JSON string
* @param pDelta pointer to field of delta
* @return true for success
*/
bool parse_shadow_operation_delta(char *pJsonDoc, char **pDelta);
/**
* @brief parse field of get from JSON string
*
* @param pJsonDoc source JSON string
* @param pDelta pointer to field of delta
* @return true for success
*/
bool parse_shadow_operation_get(char *pJsonDoc, char **pDelta);
/**
* @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);
#ifdef __cplusplus
}
#endif
#endif // IOT_SHADOW_CLIENT_JSON_H_

View File

@@ -0,0 +1,293 @@
/*
* Tencent is pleased to support the open source community by making IoT Hub available.
* Copyright (C) 2018-2020 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,35 @@
/*
* Tencent is pleased to support the open source community by making IoT Hub available.
* Copyright (C) 2018-2020 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_error.h"
#include "qcloud_iot_export_log.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,25 @@
/*
* Tencent is pleased to support the open source community by making IoT Hub available.
* Copyright (C) 2018-2020 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,76 @@
/*
* Tencent is pleased to support the open source community by making IoT Hub available.
* Copyright (C) 2018-2020 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,92 @@
/*
* Tencent is pleased to support the open source community by making IoT Hub available.
* Copyright (C) 2018-2020 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,87 @@
/*
* Tencent is pleased to support the open source community by making IoT Hub available.
* Copyright (C) 2018-2020 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) 2018-2020 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,42 @@
/*
* Tencent is pleased to support the open source community by making IoT Hub available.
* Copyright (C) 2018-2020 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,88 @@
/*
* Tencent is pleased to support the open source community by making IoT Hub available.
* Copyright (C) 2018-2020 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,79 @@
/*
* Tencent is pleased to support the open source community by making IoT Hub available.
* Copyright (C) 2018-2020 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_