1.新增esp-idf设备端sdk

This commit is contained in:
zhuangpeng.li
2024-08-05 15:46:10 +08:00
parent 642cf21648
commit 7983f72429
425 changed files with 113377 additions and 0 deletions

View File

@@ -0,0 +1,22 @@
/*
* Copyright (C) 2015-2018 Alibaba Group Holding Limited
*/
#ifndef __COAP_DESERIALIZE_H__
#define __COAP_DESERIALIZE_H__
#include <stdio.h>
#include "iotx_coap_internal.h"
#ifdef __cplusplus
extern "C" {
#endif /* __cplusplus */
int CoAPDeserialize_Message(CoAPMessage *msg, unsigned char *buf, int buflen);
#ifdef __cplusplus
}
#endif /* __cplusplus */
#endif

View File

@@ -0,0 +1,139 @@
/*
* Copyright (C) 2015-2018 Alibaba Group Holding Limited
*/
#include <stdio.h>
#include <string.h>
#include "iotx_coap_internal.h"
int CoAPDeserialize_Header(CoAPMessage *msg, unsigned char *buf)
{
msg->header.version = ((buf[0] >> 6) & 0x03);
msg->header.type = ((buf[0] >> 4) & 0x03);
msg->header.tokenlen = (buf[0] & 0x0F);
msg->header.code = buf[1];
msg->header.msgid = buf[2] << 8;
msg->header.msgid += buf[3];
return 4;
}
int CoAPDeserialize_Token(CoAPMessage *msg, unsigned char *buf)
{
memcpy(msg->token, buf, msg->header.tokenlen);
return msg->header.tokenlen;
}
static int CoAPDeserialize_Option(CoAPMsgOption *option, unsigned char *buf, unsigned short *predeltas)
{
unsigned char *ptr = buf;
unsigned short optdelta = 0;
unsigned short optlen = 0;
unsigned short predelta = 0;
optdelta = (*ptr & 0xF0) >> 4;
optlen = (*ptr & 0x0F);
ptr++;
predelta = *predeltas;
if (13 == optdelta) {
predelta += 13 + *ptr;
ptr ++;
} else if (14 == optdelta) {
predelta += 269;
predelta += (*ptr << 8);
predelta += *(ptr + 1);
ptr += 2;
} else {
predelta += optdelta;
}
option->num = predelta;
if (13 == optlen) {
optlen = 13 + *ptr;
ptr ++;
} else if (14 == optlen) {
optlen = 269;
optlen += (*ptr << 8);
optlen += *(ptr + 1);
ptr += 2;
}
option->len = optlen;
option->val = ptr;
*predeltas = option->num;
return (ptr - buf + option->len);
}
int CoAPDeserialize_Options(CoAPMessage *msg, unsigned char *buf, int buflen)
{
int index = 0;
int count = 0;
unsigned char *ptr = buf;
unsigned short len = 0;
unsigned short optdeltas = 0;
msg->optcount = 0;
while ((count < buflen) && (0xFF != *ptr)) {
len = CoAPDeserialize_Option(&msg->options[index], ptr, &optdeltas);
msg->optcount += 1;
ptr += len;
index ++;
count += len;
}
return (int)(ptr - buf);
}
int CoAPDeserialize_Payload(CoAPMessage *msg, unsigned char *buf, int buflen)
{
unsigned char *ptr = buf;
if (0xFF == *ptr) {
ptr ++;
} else {
return 0;
}
msg->payloadlen = buflen - 1;
msg->payload = (unsigned char *)ptr;
return buflen;
}
int CoAPDeserialize_Message(CoAPMessage *msg, unsigned char *buf, int buflen)
{
int count = 0;
int remlen = buflen;
unsigned char *ptr = buf;
if (NULL == buf || NULL == msg) {
return COAP_ERROR_INVALID_PARAM;
}
if (buflen < 4) {
return COAP_ERROR_INVALID_LENGTH;
}
/* Deserialize CoAP header. */
count = CoAPDeserialize_Header(msg, ptr);
ptr += count;
remlen -= count;
/* Deserialize the token, if any. */
count = CoAPDeserialize_Token(msg, ptr);
ptr += count;
remlen -= count;
count = CoAPDeserialize_Options(msg, ptr, remlen);
ptr += count;
remlen -= count;
CoAPDeserialize_Payload(msg, ptr, remlen);
return COAP_SUCCESS;
}

View File

@@ -0,0 +1,317 @@
/*
* Copyright (C) 2015-2018 Alibaba Group Holding Limited
*/
#include <stdio.h>
#include "iotx_coap_internal.h"
#include "CoAPSerialize.h"
#include "CoAPDeserialize.h"
#if 0
#include "CoAPResource.h"
#include "CoAPObserve.h"
#include "CoAPInternal.h"
#endif
#include "CoAPPlatform.h"
#define COAPAckMsg(header) \
((header.code == COAP_MSG_CODE_EMPTY_MESSAGE) \
&&(header.type == COAP_MESSAGE_TYPE_ACK))
#define CoAPRespMsg(header)\
((header.code >= 0x40) && (header.code < 0xc0))
#define CoAPPingMsg(header)\
((header.code == COAP_MSG_CODE_EMPTY_MESSAGE)\
&& (header.type == COAP_MESSAGE_TYPE_CON))
#define CoAPResetMsg(header)\
(header.type == COAP_MESSAGE_TYPE_RST)
#define CoAPCONRespMsg(header)\
((header.code == COAP_MSG_CODE_205_CONTENT) \
&& (header.type == COAP_MESSAGE_TYPE_CON))
#define CoAPReqMsg(header)\
((1 <= header.code) && (32 > header.code))
#define COAP_CUR_VERSION 1
#define COAP_WAIT_TIME_MS 2000
#define COAP_MAX_MESSAGE_ID 65535
#define COAP_MAX_RETRY_COUNT 4
#define COAP_ACK_TIMEOUT 2
#define COAP_ACK_RANDOM_FACTOR 1
#define COAP_MAX_TRANSMISSION_SPAN 10
int CoAPStrOption_add(CoAPMessage *message, unsigned short optnum, unsigned char *data, unsigned short datalen)
{
unsigned char *ptr = NULL;
if (COAP_MSG_MAX_OPTION_NUM <= message->optcount) {
return COAP_ERROR_INVALID_PARAM;
}
message->options[message->optcount].num = optnum - message->optdelta;
message->options[message->optcount].len = datalen;
ptr = (unsigned char *)coap_malloc(datalen);
if (NULL == ptr) {
return COAP_ERROR_MALLOC;
}
memset(ptr, 0x00, datalen);
memcpy(ptr, data, datalen);
message->options[message->optcount].val = ptr;
message->optdelta = optnum;
message->optcount ++;
return COAP_SUCCESS;
}
int CoAPStrOption_get(CoAPMessage *message, unsigned short optnum, unsigned char *data, unsigned short *datalen)
{
unsigned char index = 0;
for (index = 0; index < message->optcount; index++) {
if (message->options[index].num == optnum) {
if (*datalen >= message->options[index].len) {
memcpy(data, message->options[index].val, message->options[index].len);
*datalen = message->options[index].len;
return COAP_SUCCESS;
} else {
return COAP_ERROR_INVALID_LENGTH;
}
}
}
return COAP_ERROR_NOT_FOUND;
}
int CoAPUintOption_add(CoAPMessage *message, unsigned short optnum, unsigned int data)
{
unsigned char *ptr = NULL;
if (COAP_MSG_MAX_OPTION_NUM <= message->optcount) {
return COAP_ERROR_INVALID_PARAM;
}
message->options[message->optcount].num = optnum - message->optdelta;
if (0 == data) {
message->options[message->optcount].len = 0;
} else if (255 >= data) {
message->options[message->optcount].len = 1;
ptr = (unsigned char *)coap_malloc(1);
if (NULL != ptr) {
*ptr = (unsigned char)data;
}
} else if (65535 >= data) {
message->options[message->optcount].len = 2;
ptr = (unsigned char *)coap_malloc(2);
if (NULL != ptr) {
*ptr = (unsigned char)((data & 0xFF00) >> 8);
*(ptr + 1) = (unsigned char)(data & 0x00FF);
}
} else {
message->options[message->optcount].len = 4;
ptr = (unsigned char *)coap_malloc(4);
if (NULL != ptr) {
*ptr = (unsigned char)((data & 0xFF000000) >> 24);
*(ptr + 1) = (unsigned char)((data & 0x00FF0000) >> 16);
*(ptr + 2) = (unsigned char)((data & 0x0000FF00) >> 8);
*(ptr + 3) = (unsigned char)(data & 0x000000FF);
}
}
message->options[message->optcount].val = ptr;
message->optdelta = optnum;
message->optcount += 1;
return COAP_SUCCESS;
}
int CoAPUintOption_get(CoAPMessage *message,
unsigned short optnum,
unsigned int *data)
{
unsigned char index = 0;
for (index = 0; index < message->optcount; index++) {
if (message->options[index].num == optnum) {
int byte = 0;
switch (message->options[index].len) {
case 1:
*data |= message->options[index].val[byte++];
break;
case 2:
*data |= (message->options[index].val[byte++] << 8);
*data |= message->options[index].val[byte++];
break;
case 3:
*data |= (message->options[index].val[byte++] << 16);
*data |= (message->options[index].val[byte++] << 8);
*data |= message->options[index].val[byte++];
break;
case 4:
*data |= (message->options[index].val[byte++] << 24);
*data |= (message->options[index].val[byte++] << 16);
*data |= (message->options[index].val[byte++] << 8);
*data |= message->options[index].val[byte++];
break;
default:
*data = 0;
break;
}
return COAP_SUCCESS;
}
}
return COAP_ERROR_NOT_FOUND;
}
int CoAPOption_present(CoAPMessage *message, unsigned short option)
{
unsigned char index = 0;
for (index = 0; index < message->optcount; index++) {
if (message->options[index].num == option) {
return COAP_SUCCESS;
}
}
return COAP_ERROR_NOT_FOUND;
}
int CoAPMessageId_set(CoAPMessage *message, unsigned short msgid)
{
if (NULL == message) {
return COAP_ERROR_NULL;
}
message->header.msgid = msgid;
return COAP_SUCCESS;
}
int CoAPMessageType_set(CoAPMessage *message, unsigned char type)
{
if (NULL == message) {
return COAP_ERROR_NULL;
}
if (COAP_MESSAGE_TYPE_CON != type && COAP_MESSAGE_TYPE_NON != type
&& COAP_MESSAGE_TYPE_ACK != type && COAP_MESSAGE_TYPE_RST != type) {
return COAP_ERROR_INVALID_PARAM;
}
message->header.type = type;
return COAP_SUCCESS;
}
int CoAPMessageCode_set(CoAPMessage *message, CoAPMessageCode code)
{
if (NULL == message) {
return COAP_ERROR_NULL;
}
message->header.code = code;
return COAP_SUCCESS;
}
int CoAPMessageCode_get(CoAPMessage *message, CoAPMessageCode *code)
{
if (NULL == message || NULL == code) {
return COAP_ERROR_NULL;
}
*code = message->header.code;
return COAP_SUCCESS;
}
int CoAPMessageToken_set(CoAPMessage *message, unsigned char *token,
unsigned char tokenlen)
{
if (NULL == message || NULL == token) {
return COAP_ERROR_NULL;
}
if (COAP_MSG_MAX_TOKEN_LEN < tokenlen) {
return COAP_ERROR_INVALID_LENGTH;
}
memcpy(message->token, token, tokenlen);
message->header.tokenlen = tokenlen;
return COAP_SUCCESS;
}
int CoAPMessageUserData_set(CoAPMessage *message, void *userdata)
{
if (NULL == message || NULL == userdata) {
return COAP_ERROR_NULL;
}
message->user = userdata;
return COAP_SUCCESS;
}
int CoAPMessageKeep_Set(CoAPMessage *message, int keep)
{
if (NULL == message || keep < 0) {
return COAP_ERROR_NULL;
}
message->keep = keep;
return COAP_SUCCESS;
}
int CoAPMessagePayload_set(CoAPMessage *message, unsigned char *payload,
unsigned short payloadlen)
{
if (NULL == message || (0 < payloadlen && NULL == payload)) {
return COAP_ERROR_NULL;
}
message->payload = payload;
message->payloadlen = payloadlen;
return COAP_SUCCESS;
}
int CoAPMessage_init(CoAPMessage *message)
{
int count = 0;
if (NULL == message) {
return COAP_ERROR_NULL;
}
memset(message, 0x00, sizeof(CoAPMessage));
message->header.version = COAP_CUR_VERSION;
message->header.type = COAP_MESSAGE_TYPE_ACK;
message->header.tokenlen = 0;
message->header.code = COAP_MSG_CODE_EMPTY_MESSAGE;
message->header.msgid = 0;
message->payload = NULL;
message->payloadlen = 0;
message->optcount = 0;
message->optdelta = 0;
message->handler = NULL;
message->keep = 0;
for (count = 0; count < COAP_MSG_MAX_OPTION_NUM; count++) {
message->options[count].len = 0;
message->options[count].num = 0;
message->options[count].val = NULL;
}
return COAP_SUCCESS;
}
int CoAPMessage_destory(CoAPMessage *message)
{
int count = 0;
if (NULL == message) {
return COAP_ERROR_NULL;
}
for (count = 0; count < COAP_MSG_MAX_OPTION_NUM; count++) {
if (NULL != message->options[count].val) {
coap_free(message->options[count].val);
message->options[count].val = NULL;
}
}
return COAP_SUCCESS;
}

View File

@@ -0,0 +1,49 @@
/*
* Copyright (C) 2015-2018 Alibaba Group Holding Limited
*/
#ifndef __COAP_PLATFORM_OS_H__
#define __COAP_PLATFORM_OS_H__
#include <stdio.h>
#include "iotx_coap_internal.h"
#ifdef __cplusplus
extern "C" {
#endif /* __cplusplus */
#ifdef INFRA_MEM_STATS
#include "infra_mem_stats.h"
#define coap_malloc(size) LITE_malloc(size, MEM_MAGIC, "coap.local")
#define coap_free(ptr) LITE_free(ptr)
#else
#define coap_malloc(size) HAL_Malloc(size)
#define coap_free(ptr) {HAL_Free((void *)ptr);ptr = NULL;}
#endif
#ifdef INFRA_LOG
#include "infra_log.h"
#define COAP_ERR(...) log_err("coap_local", __VA_ARGS__)
#define COAP_WRN(...) log_warning("coap_local", __VA_ARGS__)
#define COAP_INFO(...) log_info("coap_local", __VA_ARGS__)
#define COAP_TRC(...) log_debug("coap_local", __VA_ARGS__)
#define COAP_DUMP(...) log_debug("coap_local", __VA_ARGS__)
#define COAP_DEBUG(...) log_debug("coap_local", __VA_ARGS__)
#define COAP_FLOW(...) log_flow("coap_local", __VA_ARGS__)
#else
#define COAP_ERR(...)
#define COAP_WRN(...)
#define COAP_INFO(...)
#define COAP_TRC(...)
#define COAP_DUMP(...)
#define COAP_DEBUG(...)
#define COAP_FLOW(...)
#endif
int platform_is_multicast(const char *ip_str);
#ifdef __cplusplus
}
#endif /* __cplusplus */
#endif

View File

@@ -0,0 +1,24 @@
/*
* Copyright (C) 2015-2018 Alibaba Group Holding Limited
*/
#ifndef __COAP_SERIALIZE_H__
#define __COAP_SERIALIZE_H__
#include "iotx_coap_internal.h"
#ifdef __cplusplus
extern "C" {
#endif /* __cplusplus */
unsigned short CoAPSerialize_MessageLength(CoAPMessage *msg);
int CoAPSerialize_Message(CoAPMessage *msg, unsigned char *buf, unsigned short buflen);
#ifdef __cplusplus
}
#endif /* __cplusplus */
#endif

View File

@@ -0,0 +1,222 @@
/*
* Copyright (C) 2015-2018 Alibaba Group Holding Limited
*/
#include <stdio.h>
#include <string.h>
#include "CoAPSerialize.h"
#include "iotx_coap_internal.h"
int CoAPSerialize_Header(CoAPMessage *msg, unsigned char *buf, unsigned short buflen)
{
if(4 > buflen){
return 0;
}
buf[0] = (((msg->header.version & 0x3) << 6) | ((msg->header.type & 0x3) << 4))
| (msg->header.tokenlen & 0x0F);
buf[1] = msg->header.code;
buf[2] = (msg->header.msgid & 0xFF00) >> 8;
buf[3] = (msg->header.msgid & 0x00FF);
return 4;
}
int CoAPSerialize_Token(CoAPMessage *msg, unsigned char * buf, unsigned short buflen)
{
int i = 0;
if(buflen < msg->header.tokenlen){
return 0;
}
for (i = 0; i < msg->header.tokenlen; i++){
buf[i] = msg->token[i];
}
return msg->header.tokenlen;
}
static unsigned short CoAPSerialize_Option(CoAPMsgOption *option, unsigned char *buf)
{
unsigned char *ptr = buf;
if(269 <= option->num){
*ptr = ((14 & 0x0F) << 4);
}
else if(13 <= option->num){
*ptr = ((13 & 0x0F) << 4);
}
else{
*ptr = option->num << 4;
}
if (269 <= option->len){
*ptr |= (14 & 0x0F);
}
else if(13 <= option->len){
*ptr |= (13 & 0x0F);
}
else{
*ptr |= (option->len & 0x0F);
}
ptr ++;
if (269 <= option->num){
*ptr = (unsigned char)(((option->num - 269) & 0xFF00) >> 8);
*(ptr+1) = (unsigned char)(((option->num - 269) & 0x00FF));
ptr += 2;
}
else if(13 <= option->num){
*ptr = (unsigned char)(option->num - 13);
ptr ++;
}
if (269 <= option->len){
*ptr = (unsigned char)(((option->len - 269) & 0xFF00) >> 8);
*(ptr+1) = (unsigned char)(((option->len - 269) & 0x00FF));
ptr += 2;
}
else if(13 <= option->len){
*ptr = (unsigned char)(option->len - 13);
ptr ++;
}
memcpy(ptr, option->val, option->len);
ptr += option->len;
return (int)(ptr - buf);
}
unsigned short CoAPSerialize_Options(CoAPMessage *msg, unsigned char * buf, unsigned short buflen)
{
int i = 0;
unsigned short count = 0;
for (i = 0; i < msg->optcount; i++)
{
unsigned short len = 0;
len = CoAPSerialize_Option(&msg->options[i], &buf[count]);
if (0 < len){
count += len;
}
else{
return 0;
}
}
return count;
}
static unsigned short CoAPSerialize_OptionLen(CoAPMsgOption *option)
{
unsigned short len = 1;
if(269 <= option->num){
len += 2;
}
else if(13 <= option->num){
len += 1;
}
else{
}
if (269 <= option->len){
len += 2;
}
else if(13 <= option->len){
len += 1;
}
else{
}
len += option->len;
return len;
}
unsigned short CoAPSerialize_OptionsLen(CoAPMessage *msg)
{
int i = 0;
unsigned short count = 0;
for (i = 0; i < msg->optcount; i++)
{
unsigned short len = 0;
len = CoAPSerialize_OptionLen(&msg->options[i]);
if (0 < len){
count += len;
}
else{
return 0;
}
}
return count;
}
int CoAPSerialize_Payload(CoAPMessage *msg, unsigned char *buf, int buflen)
{
if(msg->payloadlen + 1 > buflen){
return 0;
}
if(msg->payloadlen > 0 && NULL != msg->payload)
{
*buf = 0xFF;
buf ++;
memcpy(buf, msg->payload, msg->payloadlen);
return msg->payloadlen + 1;
}
else{
return 0;
}
}
unsigned short CoAPSerialize_MessageLength(CoAPMessage *msg)
{
unsigned short msglen = 4;
msglen += msg->header.tokenlen;
msglen += CoAPSerialize_OptionsLen(msg);
if(0 < msg->payloadlen){
msglen += msg->payloadlen;
msglen += 1; /*CoAP payload marker*/
}
return msglen;
}
int CoAPSerialize_Message(CoAPMessage *msg, unsigned char *buf, unsigned short buflen)
{
unsigned char *ptr = buf;
unsigned short count = 0;
unsigned short remlen = buflen;
if(NULL == buf || NULL == msg){
return COAP_ERROR_INVALID_PARAM;
}
count = CoAPSerialize_Header(msg, ptr, remlen);
ptr += count;
remlen -= count;
count = CoAPSerialize_Token(msg, ptr, remlen);
ptr += count;
remlen -= count;
count = CoAPSerialize_Options(msg, ptr, remlen);
ptr += count;
remlen -= count;
count = CoAPSerialize_Payload(msg, ptr, remlen);
ptr += count;
remlen -= count;
return (buflen-remlen);
}

View File

@@ -0,0 +1,210 @@
/*
* Copyright (C) 2015-2018 Alibaba Group Holding Limited
*/
#ifndef __IOTX_COAP_API_H__
#define __IOTX_COAP_API_H__
#if defined(__cplusplus)
extern "C" {
#endif
#include "infra_defs.h"
/*iotx return code definition*/
typedef enum {
IOTX_ERR_RECV_MSG_TIMEOUT = -9, /*Receive message timeout */
IOTX_ERR_SEND_MSG_FAILED = -8, /* Send message failed*/
IOTX_ERR_MSG_TOO_LOOG = -7, /* The payload too loog */
IOTX_ERR_URI_TOO_LOOG = -6, /* URI length too long */
IOTX_ERR_NOT_AUTHED = -5, /* Client isn't authed */
IOTX_ERR_AUTH_FAILED = -4, /* Client authed failed */
IOTX_ERR_BUFF_TOO_SHORT = -3, /* Buffer too short */
IOTX_ERR_NO_MEM = -2, /* Malloc failed */
IOTX_ERR_INVALID_PARAM = -1, /* Invalid parameter */
IOTX_SUCCESS = 0, /* Success */
} iotx_ret_code_t;
/* The message payload encode format */
typedef enum {
IOTX_CONTENT_TYPE_JSON,
IOTX_CONTENT_TYPE_CBOR,
} iotx_content_type_t;
/* The message type */
typedef enum {
IOTX_MESSAGE_CON = 0, /* confirmable message */
IOTX_MESSAGE_NON = 1, /* non-confirmable message */
IOTX_MESSAGE_ACK = 2, /* acknowledgement message */
IOTX_MESSAGE_RST = 3, /* reset message */
} iotx_msg_type_t;
/* IoTx events to notify application */
typedef enum {
IOTX_COAP_EVENT_SEND_FAILED = 0,
IOTX_COAP_EVENT_RECV_FAILED = 1,
IOTX_COAP_EVENT_AUTH_FAILED = 2,
} iotx_coap_event_t;
typedef enum {
IOTX_COAP_RESP_CODE_CONTENT = 0x45, /* Mapping to 2.05, Content*/
IOTX_COAP_RESP_CODE_BAD_REQUEST = 0x80, /* Mapping to 4.00, Bad Request*/
IOTX_COAP_RESP_CODE_UNAUTHORIZED = 0x81, /* Mapping to 4.01, Token is invalid or expire*/
IOTX_COAP_RESP_CODE_NOT_FOUND = 0x84, /* Mapping to 4.04, Path or uri is not found*/
IOTX_COAP_RESP_CODE_URL_TOO_LONG = 0x8E, /* Mapping to 4.14, The request url is too long*/
IOTX_COAP_RESP_CODE_INTERNAL_SERVER_ERROR = 0xA0,/* Mapping to 5.00, Internal server error*/
} iotx_coap_resp_code_t;
/* Callback function to notify the application events.*/
typedef void (*iotx_event_handle_t)(void *context, iotx_coap_event_t event, void *p_data);
/*IoTx device*/
typedef struct {
char product_key[IOTX_PRODUCT_KEY_LEN + 1];
char device_name[IOTX_DEVICE_NAME_LEN + 1];
char device_id[IOTX_PRODUCT_KEY_LEN + IOTX_DEVICE_NAME_LEN + 2];
char device_secret[IOTX_DEVICE_SECRET_LEN + 1];
} iotx_deviceinfo_t;
typedef struct {
char product_key[IOTX_PRODUCT_KEY_LEN + 1];
char device_name[IOTX_DEVICE_NAME_LEN + 1];
char device_id[IOTX_PRODUCT_KEY_LEN + IOTX_DEVICE_NAME_LEN + 2];
char device_secret[IOTX_DEVICE_SECRET_LEN + 1];
char module_vendor_id[IOTX_PARTNER_ID_LEN + 1];
} iotx_device_info_t;
/* IoTx initializa parameters */
typedef struct {
char *p_url; /*Can be NULL*/
int wait_time_ms; /*unit is micro second*/
iotx_device_info_t *p_devinfo; /*Device info*/
iotx_event_handle_t event_handle; /*TODO, not supported now*/
} iotx_coap_config_t;
/* Callback function to handle the response message.*/
typedef void (*iotx_response_callback_t)(void *p_arg, void *p_message);
/* IoTx message definition */
typedef struct {
unsigned char *p_payload;
unsigned short payload_len;
iotx_content_type_t content_type;
iotx_msg_type_t msg_type;
void *user_data;
iotx_response_callback_t resp_callback;
} iotx_message_t;
/*iotx coap context definition*/
typedef void iotx_coap_context_t;
/** @defgroup group_api api
* @{
*/
/** @defgroup group_api_coap coap
* @{
*/
/**
* @brief Initialize the CoAP client.
* This function initialize the data structures and network,
* and create the DTLS session.
*
* @param [in] p_config: Specify the CoAP client parameter.
*
* @retval NULL : Initialize failed.
* @retval NOT_NULL : The contex of CoAP client.
* @see None.
*/
iotx_coap_context_t *IOT_CoAP_Init(iotx_coap_config_t *p_config);
/**
* @brief De-initialize the CoAP client.
* This function release CoAP DTLS session.
* and release the related resource.
*
* @param [in] p_context: Pointer of contex, specify the CoAP client.
*
* @return None.
* @see None.
*/
DLL_IOT_API void IOT_CoAP_Deinit(iotx_coap_context_t **p_context);
/**
* @brief Handle device name authentication with remote server.
*
* @param [in] p_context: Pointer of contex, specify the CoAP client.
*
* @retval IOTX_SUCCESS : Authenticate success.
* @retval IOTX_ERR_SEND_MSG_FAILED : Send authentication message failed.
* @retval IOTX_ERR_AUTH_FAILED : Authenticate failed or timeout.
* @see iotx_ret_code_t.
*/
DLL_IOT_API int IOT_CoAP_DeviceNameAuth(iotx_coap_context_t *p_context);
/**
* @brief Handle CoAP response packet from remote server,
* and process timeout request etc..
*
* @param [in] p_context : Pointer of contex, specify the CoAP client.
*
* @return status.
* @see iotx_ret_code_t.
*/
DLL_IOT_API int IOT_CoAP_Yield(iotx_coap_context_t *p_context);
/**
* @brief Send a message with specific path to server.
* Client must authentication with server before send message.
*
* @param [in] p_context : Pointer of contex, specify the CoAP client.
* @param [in] p_path: Specify the path name.
* @param [in] p_message: Message to be sent.
*
* @retval IOTX_SUCCESS : Send the message success.
* @retval IOTX_ERR_MSG_TOO_LOOG : The message length is too long.
* @retval IOTX_ERR_NOT_AUTHED : The client hasn't authenticated with server
* @see iotx_ret_code_t.
*/
DLL_IOT_API int IOT_CoAP_SendMessage(iotx_coap_context_t *p_context, char *p_path, iotx_message_t *p_message);
/**
* @brief Retrieves the length and payload pointer of specified message.
*
* @param [in] p_message: Pointer to the message to get the payload. Should not be NULL.
* @param [out] pp_payload: Pointer to the payload.
* @param [out] p_len: Size of the payload.
*
* @retval IOTX_SUCCESS : Get the payload success.
* @retval IOTX_ERR_INVALID_PARAM : Can't get the payload due to invalid parameter.
* @see iotx_ret_code_t.
**/
DLL_IOT_API int IOT_CoAP_GetMessagePayload(void *p_message, unsigned char **pp_payload, int *p_len);
/**
* @brief Get the response code from a CoAP message.
*
* @param [in] p_message: Pointer to the message to add the address information to.
* Should not be NULL.
* @param [out] p_resp_code: The response code.
*
* @retval IOTX_SUCCESS : When get the response code to message success.
* @retval IOTX_ERR_INVALID_PARAM : Pointer to the message is NULL.
* @see iotx_ret_code_t.
**/
DLL_IOT_API int IOT_CoAP_GetMessageCode(void *p_message, iotx_coap_resp_code_t *p_resp_code);
/** @} */ /* end of api_coap */
/** @} */ /* end of api */
#if defined(__cplusplus)
}
#endif
#endif

View File

@@ -0,0 +1,90 @@
#ifndef _COAP_WRAPPER_H_
#define _COAP_WRAPPER_H_
#include "infra_types.h"
#include "infra_defs.h"
#include "infra_compat.h"
#include "wrappers_defs.h"
void *HAL_Malloc(uint32_t size);
void HAL_Free(void *ptr);
void HAL_SleepMs(uint32_t ms);
uint64_t HAL_UptimeMs(void);
void HAL_Srandom(uint32_t seed);
uint32_t HAL_Random(uint32_t region);
void HAL_Printf(const char *fmt, ...);
int HAL_Snprintf(char *str, const int len, const char *fmt, ...);
int HAL_GetProductKey(char product_key[IOTX_PRODUCT_KEY_LEN]);
int HAL_GetDeviceName(char device_name[IOTX_DEVICE_NAME_LEN]);
int HAL_GetDeviceSecret(char device_secret[IOTX_DEVICE_SECRET_LEN]);
int HAL_SetProductKey(char *product_key);
int HAL_SetProductSecret(char *product_secret);
int HAL_SetDeviceName(char *device_name);
int HAL_SetDeviceSecret(char *device_secret);
DLL_HAL_API int HAL_DTLSHooks_set(dtls_hooks_t *hooks);
DLL_HAL_API DTLSContext *HAL_DTLSSession_create(coap_dtls_options_t *p_options);
DLL_HAL_API unsigned int HAL_DTLSSession_write(DTLSContext *context,
const unsigned char *p_data,
unsigned int *p_datalen);
DLL_HAL_API unsigned int HAL_DTLSSession_read(DTLSContext *context,
unsigned char *p_data,
unsigned int *p_datalen,
unsigned int timeout_ms);
DLL_HAL_API unsigned int HAL_DTLSSession_free(DTLSContext *context);
intptr_t HAL_UDP_create(char *host, unsigned short port);
intptr_t HAL_UDP_create_without_connect(const char *host, unsigned short port);
int HAL_UDP_write(intptr_t p_socket,
const unsigned char *p_data,
unsigned int datalen);
int HAL_UDP_readTimeout(intptr_t p_socket,
unsigned char *p_data,
unsigned int datalen,
unsigned int timeout);
int HAL_UDP_close_without_connect(intptr_t sockfd);
int HAL_UDP_recvfrom(intptr_t sockfd,
NetworkAddr *p_remote,
unsigned char *p_data,
unsigned int datalen,
unsigned int timeout_ms);
int HAL_UDP_sendto(intptr_t sockfd,
const NetworkAddr *p_remote,
const unsigned char *p_data,
unsigned int datalen,
unsigned int timeout_ms);
int HAL_UDP_joinmulticast(intptr_t sockfd,
char *p_group);
uint32_t HAL_Wifi_Get_IP(char ip_str[NETWORK_ADDR_LEN], const char *ifname);
p_HAL_Aes128_t HAL_Aes128_Init(
const uint8_t *key,
const uint8_t *iv,
AES_DIR_t dir);
int HAL_Aes128_Destroy(p_HAL_Aes128_t aes);
int HAL_Aes128_Cbc_Encrypt(
p_HAL_Aes128_t aes,
const void *src,
size_t blockNum,
void *dst);
int HAL_Aes128_Cbc_Decrypt(
p_HAL_Aes128_t aes,
const void *src,
size_t blockNum,
void *dst);
void *HAL_MutexCreate(void);
void HAL_MutexDestroy(void *mutex);
void HAL_MutexLock(void *mutex);
void HAL_MutexUnlock(void *mutex);
void *HAL_SemaphoreCreate(void);
void HAL_SemaphoreDestroy(void *sem);
int HAL_SemaphoreWait(void *sem, uint32_t timeout_ms);
void HAL_SemaphorePost(void *sem);
int HAL_ThreadCreate(
void **thread_handle,
void *(*work_routine)(void *),
void *arg,
hal_os_thread_param_t *hal_os_thread_param,
int *stack_used);
void HAL_ThreadDelete(void *thread_handle);
#endif

View File

@@ -0,0 +1,2 @@
#include "CoAPServer.h"
#include "iotx_coap_internal.h"

View File

@@ -0,0 +1,17 @@
#ifndef __IOTX_COAP_CONFIG__
#define __IOTX_COAP_CONFIG__
#define COAP_MSG_MAX_TOKEN_LEN 8
#define COAP_MSG_MAX_OPTION_NUM 12
#define COAP_MSG_MAX_PATH_LEN 128
#ifndef COAP_LARGE_MEMORY_SUPPORT
#define COAP_MSG_MAX_PDU_LEN 1280
#else
#define COAP_MSG_MAX_PDU_LEN 4096
#endif
#ifndef CONFIG_COAP_AUTH_TIMEOUT
#define CONFIG_COAP_AUTH_TIMEOUT (3 * 1000)
#endif
#endif

View File

@@ -0,0 +1,242 @@
/*
* Copyright (C) 2015-2018 Alibaba Group Holding Limited
*/
#ifndef __IOTX_COAP_INTERNAL__
#define __IOTX_COAP_INTERNAL__
#include <stdio.h>
#include <string.h>
#include "infra_string.h"
#include "infra_compat.h"
#include "infra_types.h"
#include "infra_defs.h"
#include "infra_log.h"
#include "infra_json_parser.h"
#include "infra_cjson.h"
#include "infra_list.h"
#include "infra_md5.h"
#include "infra_sha256.h"
#include "infra_report.h"
#include "iotx_coap_config.h"
#include "coap_wrapper.h"
#include "iotx_coap_config.h"
#ifdef __cplusplus
extern "C" {
#endif /* __cplusplus */
/*CoAP Content Type*/
#define COAP_CT_TEXT_PLAIN 0 /* text/plain (UTF-8) */
#define COAP_CT_APP_LINK_FORMAT 40 /* application/link-format */
#define COAP_CT_APP_XML 41 /* application/xml */
#define COAP_CT_APP_OCTET_STREAM 42 /* application/octet-stream */
#define COAP_CT_APP_RDF_XML 43 /* application/rdf+xml */
#define COAP_CT_APP_EXI 47 /* application/exi */
#define COAP_CT_APP_JSON 50 /* application/json */
#define COAP_CT_APP_CBOR 60 /* application/cbor */
/*CoAP option types. */
#define COAP_OPTION_IF_MATCH 1 /* C, opaque, 0-8 B, (none) */
#define COAP_OPTION_URI_HOST 3 /* C, String, 1-255 B, destination address */
#define COAP_OPTION_ETAG 4 /* E, opaque, 1-8 B, (none) */
#define COAP_OPTION_IF_NONE_MATCH 5 /* empty, 0 B, (none) */
#define COAP_OPTION_OBSERVE 6 /* E, empty/uint, 0 B/0-3 B, (none)*/
#define COAP_OPTION_URI_PORT 7 /* C, uint, 0-2 B, destination port */
#define COAP_OPTION_LOCATION_PATH 8 /* E, String, 0-255 B, - */
#define COAP_OPTION_URI_PATH 11 /* C, String, 0-255 B, (none) */
#define COAP_OPTION_CONTENT_FORMAT 12 /* E, uint, 0-2 B, (none) */
#define COAP_OPTION_MAXAGE 14 /* E, uint, 0--4 B, 60 Seconds */
#define COAP_OPTION_URI_QUERY 15 /* C, String, 1-255 B, (none) */
#define COAP_OPTION_ACCEPT 17 /* C, uint, 0-2 B, (none) */
#define COAP_OPTION_LOCATION_QUERY 20 /* E, String, 0-255 B, (none) */
#define COAP_OPTION_BLOCK2 23 /* C, uint, 0--3 B, (none) */
#define COAP_OPTION_BLOCK1 27 /* C, uint, 0--3 B, (none) */
#define COAP_OPTION_PROXY_URI 35 /* C, String, 1-1024 B, (none) */
#define COAP_OPTION_PROXY_SCHEME 39 /* C, String, 1-255 B, (none) */
#define COAP_OPTION_SIZE1 60 /* E, uint, 0-4 B, (none) */
#define COAP_OPTION_AUTH_TOKEN 61 /* C, String, 1-255B, (none)*/
#define COAP_PERM_NONE 0x0000
#define COAP_PERM_GET 0x0001
#define COAP_PERM_POST 0x0002
#define COAP_PERM_PUT 0x0004
#define COAP_PERM_DELETE 0x0008
#define COAP_PERM_OBSERVE 0x0100
/*CoAP Message types*/
#define COAP_MESSAGE_TYPE_CON 0
#define COAP_MESSAGE_TYPE_NON 1
#define COAP_MESSAGE_TYPE_ACK 2
#define COAP_MESSAGE_TYPE_RST 3
/* CoAP module error code base */
#define COAP_ERROR_BASE (1<<8)
#define COAP_ERROR_DTLS_BASE (1<<16)
/* CoAP base error code */
#define COAP_SUCCESS (0) /* Successful */
#define COAP_ERROR_INVALID_PARAM (COAP_ERROR_BASE | 1) /* Invalid Parameter */
#define COAP_ERROR_NULL (COAP_ERROR_BASE | 2) /* Null Pointer */
#define COAP_ERROR_MALLOC (COAP_ERROR_BASE | 3)
#define COAP_ERROR_INVALID_LENGTH (COAP_ERROR_BASE | 4) /* Invalid Length */
#define COAP_ERROR_DATA_SIZE (COAP_ERROR_BASE | 5) /* Data size exceeds limit */
#define COAP_ERROR_INVALID_URI (COAP_ERROR_BASE | 6)
#define COAP_ERROR_NOT_FOUND (COAP_ERROR_BASE | 7)
#define COAP_ERROR_NET_INIT_FAILED (COAP_ERROR_BASE | 8)
#define COAP_ERROR_INTERNAL (COAP_ERROR_BASE | 9) /* Internal Error */
#define COAP_ERROR_WRITE_FAILED (COAP_ERROR_BASE | 10)
#define COAP_ERROR_READ_FAILED (COAP_ERROR_BASE | 11)
#define COAP_ERROR_ENCRYPT_FAILED (COAP_ERROR_BASE | 12)
#define COAP_ERROR_UNSUPPORTED (COAP_ERROR_BASE | 13)
#define COAP_ERROR_OBJ_ALREADY_EXIST (COAP_ERROR_BASE | 14)
#define COAP_MSG_CODE_DEF(N) (((N)/100 << 5) | (N)%100)
/*CoAP Message codes*/
typedef enum {
/* CoAP Empty Message */
COAP_MSG_CODE_EMPTY_MESSAGE = COAP_MSG_CODE_DEF(0), /* Mapping to CoAP code 0.00 */
/* CoAP Method Codes */
COAP_MSG_CODE_GET = COAP_MSG_CODE_DEF(1), /* CoAP Get method */
COAP_MSG_CODE_POST = COAP_MSG_CODE_DEF(2), /* CoAP Post method */
COAP_MSG_CODE_PUT = COAP_MSG_CODE_DEF(3), /* CoAP Put method */
COAP_MSG_CODE_DELETE = COAP_MSG_CODE_DEF(4), /* CoAP Delete method */
/* CoAP Success Response Codes */
COAP_MSG_CODE_201_CREATED = COAP_MSG_CODE_DEF(201), /* Mapping to CoAP code 2.01, Hex:0x41, Created */
COAP_MSG_CODE_202_DELETED = COAP_MSG_CODE_DEF(202), /* Mapping to CoAP code 2.02, Hex:0x42, Deleted*/
COAP_MSG_CODE_203_VALID = COAP_MSG_CODE_DEF(203), /* Mapping to CoAP code 2.03, Hex:0x43, Valid*/
COAP_MSG_CODE_204_CHANGED = COAP_MSG_CODE_DEF(204), /* Mapping to CoAP code 2.04, Hex:0x44, Changed*/
COAP_MSG_CODE_205_CONTENT = COAP_MSG_CODE_DEF(205), /* Mapping to CoAP code 2.05, Hex:0x45, Content*/
COAP_MSG_CODE_231_CONTINUE = COAP_MSG_CODE_DEF(231), /* Mapping to CoAP code 2.31, Hex:0x5F, Continue*/
/* CoAP Client Error Response Codes */
COAP_MSG_CODE_400_BAD_REQUEST = COAP_MSG_CODE_DEF(400), /* Mapping to CoAP code 4.00, Hex:0x80, Bad Request */
COAP_MSG_CODE_401_UNAUTHORIZED = COAP_MSG_CODE_DEF(401), /* Mapping to CoAP code 4.01, Hex:0x81, Unauthorized */
COAP_MSG_CODE_402_BAD_OPTION = COAP_MSG_CODE_DEF(402), /* Mapping to CoAP code 4.02, Hex:0x82, Bad Option */
COAP_MSG_CODE_403_FORBIDDEN = COAP_MSG_CODE_DEF(403), /* Mapping to CoAP code 4.03, Hex:0x83, Forbidden */
COAP_MSG_CODE_404_NOT_FOUND = COAP_MSG_CODE_DEF(404), /* Mapping to CoAP code 4.04, Hex:0x84, Not Found */
COAP_MSG_CODE_405_METHOD_NOT_ALLOWED = COAP_MSG_CODE_DEF(405), /* Mapping to CoAP code 4.05, Hex:0x85, Method Not Allowed */
COAP_MSG_CODE_406_NOT_ACCEPTABLE = COAP_MSG_CODE_DEF(406), /* Mapping to CoAP code 4.06, Hex:0x86, Not Acceptable */
COAP_MSG_CODE_408_REQUEST_ENTITY_INCOMPLETE = COAP_MSG_CODE_DEF(408), /* Mapping to CoAP code 4.08, Hex:0x88, Request Entity Incomplete */
COAP_MSG_CODE_412_PRECONDITION_FAILED = COAP_MSG_CODE_DEF(412), /* Mapping to CoAP code 4.12, Hex:0x8C, Precondition Failed */
COAP_MSG_CODE_413_REQUEST_ENTITY_TOO_LARGE = COAP_MSG_CODE_DEF(413), /* Mapping to CoAP code 4.13, Hex:0x8D, Request Entity Too Large */
COAP_MSG_CODE_415_UNSUPPORTED_CONTENT_FORMAT = COAP_MSG_CODE_DEF(415), /* Mapping to CoAP code 4.15, Hex:0x8F, Unsupported Content-Format */
/* CoAP Server Error Response Codes */
COAP_MSG_CODE_500_INTERNAL_SERVER_ERROR = COAP_MSG_CODE_DEF(500), /* Mapping to CoAP code 5.00, Hex:0xA0, Internal Server Error */
COAP_MSG_CODE_501_NOT_IMPLEMENTED = COAP_MSG_CODE_DEF(501), /* Mapping to CoAP code 5.01, Hex:0xA1, Not Implemented */
COAP_MSG_CODE_502_BAD_GATEWAY = COAP_MSG_CODE_DEF(502), /* Mapping to CoAP code 5.02, Hex:0xA2, Bad Gateway */
COAP_MSG_CODE_503_SERVICE_UNAVAILABLE = COAP_MSG_CODE_DEF(503), /* Mapping to CoAP code 5.03, Hex:0xA3, Service Unavailable */
COAP_MSG_CODE_504_GATEWAY_TIMEOUT = COAP_MSG_CODE_DEF(504), /* Mapping to CoAP code 5.04, Hex:0xA4, Gateway Timeout */
COAP_MSG_CODE_505_PROXYING_NOT_SUPPORTED = COAP_MSG_CODE_DEF(505) /* Mapping to CoAP code 5.05, Hex:0xA5, Proxying Not Supported */
} CoAPMessageCode;
typedef enum {
COAP_REQUEST_SUCCESS = 0,
COAP_RECV_RESP_TIMEOUT,
COAP_RECV_RESP_SUC,
} CoAPReqResult;
typedef struct {
int len;
unsigned char *data;
} CoAPLenString;
typedef struct {
unsigned char version : 2;
unsigned char type : 2;
unsigned char tokenlen : 4;
unsigned char code;
unsigned short msgid;
} CoAPMsgHeader;
typedef struct {
unsigned short num;
unsigned short len;
unsigned char *val;
} CoAPMsgOption;
typedef void CoAPContext;
typedef struct CoAPMessage CoAPMessage;
typedef void (*CoAPSendMsgHandler)(CoAPContext *context, CoAPReqResult result, void *userdata, NetworkAddr *remote,
CoAPMessage *message);
typedef void (*CoAPEventNotifier)(unsigned int event, NetworkAddr *remote, void *message);
typedef void (*CoAPRecvMsgHandler)(CoAPContext *context, const char *paths, NetworkAddr *remote, CoAPMessage *message);
typedef int (*CoAPDataEncrypt)(CoAPContext *context, const char *paths, NetworkAddr *addr, CoAPMessage *message,
CoAPLenString *src, CoAPLenString *dest);
typedef void (*CoAPRespMsgHandler)(void *data, void *message);
struct CoAPMessage {
CoAPMsgHeader header;
unsigned char token[COAP_MSG_MAX_TOKEN_LEN];
CoAPMsgOption options[COAP_MSG_MAX_OPTION_NUM];
unsigned char optcount;
unsigned char optdelta;
unsigned short payloadlen;
unsigned char *payload;
CoAPSendMsgHandler handler;
CoAPRespMsgHandler resp;
void *user;
int keep;
};
/* CoAP message options APIs*/
extern int CoAPStrOption_add(CoAPMessage *message, unsigned short optnum,
unsigned char *data, unsigned short datalen);
extern int CoAPStrOption_get(CoAPMessage *message, unsigned short optnum,
unsigned char *data, unsigned short *datalen);
extern int CoAPUintOption_add(CoAPMessage *message, unsigned short optnum,
unsigned int data);
extern int CoAPUintOption_get(CoAPMessage *message,
unsigned short optnum,
unsigned int *data);
extern int CoAPOption_present(CoAPMessage *message, unsigned short option);
extern int CoAPMessageId_set(CoAPMessage *message, unsigned short msgid);
extern int CoAPMessageType_set(CoAPMessage *message, unsigned char type);
extern int CoAPMessageCode_set(CoAPMessage *message, CoAPMessageCode code);
extern int CoAPMessageCode_get(CoAPMessage *message, CoAPMessageCode *code);
extern int CoAPMessageToken_set(CoAPMessage *message, unsigned char *token,
unsigned char tokenlen);
extern int CoAPMessageUserData_set(CoAPMessage *message, void *userdata);
extern int CoAPMessageKeep_Set(CoAPMessage *message, int keep);
extern int CoAPMessagePayload_set(CoAPMessage *message, unsigned char *payload,
unsigned short payloadlen);
extern int CoAPMessageHandler_set(CoAPMessage *message, CoAPSendMsgHandler handler);
extern int CoAPMessage_init(CoAPMessage *message);
extern int CoAPMessage_destory(CoAPMessage *message);
#ifdef __cplusplus
}
#endif /* __cplusplus */
#endif

View File

@@ -0,0 +1,251 @@
/*
* Copyright (C) 2015-2018 Alibaba Group Holding Limited
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "ctype.h"
#include "iotx_coap_internal.h"
#include "CoAPPlatform.h"
#include "CoAPInternal.h"
#include "CoAPNetwork.h"
#include "CoAPExport.h"
#include "CoAPObserve.h"
#define COAP_DEFAULT_PORT 5683 /* CoAP default UDP port */
#define COAPS_DEFAULT_PORT 5684 /* CoAP default UDP port for secure transmission */
#define COAP_DEFAULT_SENDLIST_MAXCOUNT 8
#define COAP_DEFAULT_RES_MAXCOUNT 8
#define COAP_DEFAULT_OBS_MAXCOUNT 8
#define COAP_DEFAULT_SCHEME "coap" /* the default scheme for CoAP URIs */
#define COAP_DEFAULT_HOST_LEN 128
#define COAP_DEFAULT_WAIT_TIME_MS 2000
CoAPContext *CoAPContext_create(CoAPInitParam *param)
{
CoAPIntContext *p_ctx = NULL;
NetworkInit network_param;
memset(&network_param, 0x00, sizeof(NetworkInit));
p_ctx = coap_malloc(sizeof(CoAPIntContext));
if (NULL == p_ctx) {
COAP_ERR("malloc for coap context failed");
goto err;
}
COAP_DEBUG("Send List Max-Count: %d", param->send_maxcount);
COAP_DEBUG("Observe Server Max-Count: %d", param->obs_maxcount);
COAP_DEBUG("Observe Client Max-Count: %d", param->obs_maxcount);
COAP_DEBUG("Resource Max-Count: %d", param->res_maxcount);
COAP_DEBUG("MultiCast Address: %s:%d", param->group, param->port);
COAP_DEBUG("Send/Recv Wait time: %dms", param->waittime);
memset(p_ctx, 0, sizeof(CoAPIntContext));
p_ctx->message_id = 1;
p_ctx->notifier = param->notifier;
p_ctx->appdata = param->appdata;
#ifdef USE_SENDBUFF
p_ctx->sendbuf = coap_malloc(COAP_MSG_MAX_PDU_LEN);
if (NULL == p_ctx->sendbuf) {
COAP_ERR("not enough memory");
goto err;
}
memset(p_ctx->sendbuf, 0x00, COAP_MSG_MAX_PDU_LEN);
#endif
p_ctx->recvbuf = coap_malloc(COAP_MSG_MAX_PDU_LEN);
if (NULL == p_ctx->recvbuf) {
COAP_ERR("not enough memory");
goto err;
}
memset(p_ctx->recvbuf, 0x00, COAP_MSG_MAX_PDU_LEN);
if (0 == param->waittime) {
p_ctx->waittime = COAP_DEFAULT_WAIT_TIME_MS;
} else {
p_ctx->waittime = param->waittime;
}
p_ctx->mutex = HAL_MutexCreate();
if (NULL == p_ctx->mutex) {
COAP_ERR("Mutex Create failed");
goto err;
}
/*Init message send list mutex*/
p_ctx->sendlist.list_mutex = HAL_MutexCreate();
HAL_MutexLock(p_ctx->sendlist.list_mutex);
/*CoAP message send list*/
INIT_LIST_HEAD(&p_ctx->sendlist.list);
p_ctx->sendlist.count = 0;
HAL_MutexUnlock(p_ctx->sendlist.list_mutex);
if (0 != param->send_maxcount) {
p_ctx->sendlist.maxcount = param->send_maxcount;
} else {
p_ctx->sendlist.maxcount = COAP_DEFAULT_SENDLIST_MAXCOUNT;
}
if (0 == param->res_maxcount) {
param->res_maxcount = COAP_DEFAULT_RES_MAXCOUNT;
}
CoAPResource_init(p_ctx, param->res_maxcount);
#ifndef COAP_OBSERVE_SERVER_DISABLE
if (0 == param->obs_maxcount) {
param->obs_maxcount = COAP_DEFAULT_OBS_MAXCOUNT;
}
CoAPObsServer_init(p_ctx, param->obs_maxcount);
#endif
#ifndef COAP_OBSERVE_CLIENT_DISABLE
if (0 == param->obs_maxcount) {
param->obs_maxcount = COAP_DEFAULT_OBS_MAXCOUNT;
}
CoAPObsClient_init(p_ctx, param->obs_maxcount);
#endif
#ifdef COAP_DTLS_SUPPORT
network_param.type = COAP_NETWORK_DTLS;
network_param.port = COAPS_DEFAULT_PORT;
#else
network_param.type = COAP_NETWORK_NOSEC;
network_param.port = param->port;
network_param.group = param->group;
#endif
/*CoAP network init*/
p_ctx->p_network = CoAPNetwork_init(&network_param);
if (NULL == p_ctx->p_network) {
COAP_ERR("CoAP Network init failed, exit");
goto err;
}
return p_ctx;
err:
if (NULL == p_ctx) {
return p_ctx;
}
if (NULL != p_ctx->recvbuf) {
coap_free(p_ctx->recvbuf);
p_ctx->recvbuf = NULL;
}
#ifdef USE_SENDBUFF
if (NULL != p_ctx->sendbuf) {
coap_free(p_ctx->sendbuf);
p_ctx->sendbuf = NULL;
}
#endif
#ifndef COAP_OBSERVE_SERVER_DISABLE
CoAPObsServer_deinit(p_ctx);
#endif
#ifndef COAP_OBSERVE_CLIENT_DISABLE
CoAPObsClient_deinit(p_ctx);
#endif
CoAPResource_deinit(p_ctx);
if (NULL != p_ctx->sendlist.list_mutex) {
HAL_MutexDestroy(p_ctx->sendlist.list_mutex);
p_ctx->sendlist.list_mutex = NULL;
}
if (NULL != p_ctx->mutex) {
HAL_MutexDestroy(p_ctx->mutex);
p_ctx->mutex = NULL;
}
coap_free(p_ctx);
p_ctx = NULL;
/* TODO: release the resource */
return (CoAPContext *)p_ctx;
}
void *CoAPContextAppdata_get(CoAPContext *context)
{
CoAPIntContext *p_ctx = (CoAPIntContext *)context;
if (NULL == p_ctx) {
return NULL;
}
return (void *)p_ctx->appdata;
}
void CoAPContext_free(CoAPContext *context)
{
CoAPIntContext *p_ctx = NULL;
CoAPSendNode *cur = NULL, *next = NULL;
if (NULL == context) {
return;
}
p_ctx = (CoAPIntContext *)context;
CoAPNetwork_deinit(p_ctx->p_network);
COAP_DEBUG("CoAP Network Deinit");
HAL_MutexLock(p_ctx->sendlist.list_mutex);
list_for_each_entry_safe(cur, next, &p_ctx->sendlist.list, sendlist, CoAPSendNode) {
if (NULL != cur) {
if (NULL != cur->message) {
coap_free(cur->message);
cur->message = NULL;
}
coap_free(cur);
cur = NULL;
}
}
INIT_LIST_HEAD(&p_ctx->sendlist.list);
HAL_MutexUnlock(p_ctx->sendlist.list_mutex);
HAL_MutexDestroy(p_ctx->sendlist.list_mutex);
p_ctx->sendlist.list_mutex = NULL;
HAL_MutexDestroy(p_ctx->mutex);
p_ctx->mutex = NULL;
COAP_DEBUG("Release Send List and Memory");
#ifndef COAP_OBSERVE_SERVER_DISABLE
CoAPObsServer_deinit(p_ctx);
COAP_DEBUG("CoAP Observe Server Deinit");
#endif
#ifndef COAP_OBSERVE_CLIENT_DISABLE
CoAPObsClient_deinit(p_ctx);
COAP_DEBUG("CoAP Observe Client Deinit");
#endif
CoAPResource_deinit(p_ctx);
COAP_DEBUG("CoAP Resource unregister");
if (NULL != p_ctx->recvbuf) {
coap_free(p_ctx->recvbuf);
p_ctx->recvbuf = NULL;
COAP_DEBUG("Release The Recv Memory");
}
#ifdef USE_SENDBUFF
if (NULL != p_ctx->sendbuf) {
coap_free(p_ctx->sendbuf);
p_ctx->sendbuf = NULL;
COAP_DEBUG("Release The Send Memory");
}
#endif
if (NULL != p_ctx) {
coap_free(p_ctx);
p_ctx = NULL;
COAP_DEBUG("Release The CoAP Context");
}
}

View File

@@ -0,0 +1,110 @@
/*
* Copyright (C) 2015-2018 Alibaba Group Holding Limited
*/
#ifndef __COAP_EXPORT_H__
#define __COAP_EXPORT_H__
#include "../iotx_coap_internal.h"
#ifdef __cplusplus
extern "C" {
#endif /* __cplusplus */
typedef struct {
unsigned char send_maxcount; /*list maximal count*/
unsigned char obs_maxcount; /*observe maximal count*/
unsigned short port; /* Local port */
char *group; /* Multicast address */
unsigned int waittime;
CoAPEventNotifier notifier;
void *appdata;
unsigned char res_maxcount;
} CoAPInitParam;
typedef enum {
PATH_NORMAL,
PATH_FILTER,
} path_type_t;
CoAPContext *CoAPContext_create(CoAPInitParam *param);
void CoAPContext_free(CoAPContext *context);
void *CoAPContextAppdata_get(CoAPContext *context);
/* CoAP message options APIs*/
extern int CoAPStrOption_add(CoAPMessage *message, unsigned short optnum,
unsigned char *data, unsigned short datalen);
extern int CoAPStrOption_get(CoAPMessage *message, unsigned short optnum,
unsigned char *data, unsigned short *datalen);
extern int CoAPUintOption_add(CoAPMessage *message, unsigned short optnum,
unsigned int data);
extern int CoAPUintOption_get(CoAPMessage *message,
unsigned short optnum,
unsigned int *data);
extern int CoAPOption_present(CoAPMessage *message, unsigned short option);
/*CoAP Message APIs*/
extern unsigned short CoAPMessageId_gen(CoAPContext *context);
extern int CoAPMessageId_set(CoAPMessage *message, unsigned short msgid);
extern int CoAPMessageType_set(CoAPMessage *message, unsigned char type);
extern int CoAPMessageCode_set(CoAPMessage *message, CoAPMessageCode code);
extern int CoAPMessageCode_get(CoAPMessage *message, CoAPMessageCode *code);
extern int CoAPMessageToken_set(CoAPMessage *message, unsigned char *token,
unsigned char tokenlen);
extern int CoAPMessageUserData_set(CoAPMessage *message, void *userdata);
extern int CoAPMessageKeep_Set(CoAPMessage *message, int keep);
extern int CoAPMessagePayload_set(CoAPMessage *message, unsigned char *payload,
unsigned short payloadlen);
extern int CoAPMessageHandler_set(CoAPMessage *message, CoAPSendMsgHandler handler);
extern int CoAPMessage_init(CoAPMessage *message);
extern int CoAPMessage_destory(CoAPMessage *message);
extern int CoAPMessage_send(CoAPContext *context, NetworkAddr *remote, CoAPMessage *message);
extern int CoAPMessage_process(CoAPContext *context, unsigned int timeout);
extern int CoAPMessage_retransmit(CoAPContext *context);
extern int CoAPMessage_cycle(CoAPContext *context);
extern int CoAPMessage_cancel(CoAPContext *context, CoAPMessage *message);
extern int CoAPMessageId_cancel(CoAPContext *context, unsigned short msgid);
extern void CoAPMessage_dump(NetworkAddr *remote, CoAPMessage *message);
/*CoAP Resource APIs*/
extern int CoAPResource_register(CoAPContext *context, const char *path,
unsigned short permission, unsigned int ctype,
unsigned int maxage, CoAPRecvMsgHandler callback);
/*CoAP observe APIs*/
extern int CoAPObsServer_add(CoAPContext *context, const char *path, NetworkAddr *remote, CoAPMessage *request);
extern int CoAPObsServer_notify(CoAPContext *context,
const char *path, unsigned char *payload,
unsigned short payloadlen, CoAPDataEncrypt handler);
#ifdef __cplusplus
}
#endif /* __cplusplus */
#endif

View File

@@ -0,0 +1,48 @@
/*
* Copyright (C) 2015-2018 Alibaba Group Holding Limited
*/
#ifndef __COAP_INTERNAL_H__
#define __COAP_INTERNAL_H__
#include "CoAPNetwork.h"
#include "CoAPExport.h"
#include "iotx_coap_internal.h"
#ifdef __cplusplus
extern "C" {
#endif /* __cplusplus */
typedef struct
{
void *list_mutex;
struct list_head list;
unsigned char count;
unsigned char maxcount;
}CoAPList;
typedef struct
{
unsigned short message_id;
NetworkContext *p_network;
CoAPEventNotifier notifier;
unsigned char *sendbuf;
unsigned char *recvbuf;
CoAPList sendlist;
CoAPList obsserver;
CoAPList obsclient;
CoAPList resource;
unsigned int waittime;
void *appdata;
void *mutex;
}CoAPIntContext;
#ifdef __cplusplus
}
#endif /* __cplusplus */
#endif

View File

@@ -0,0 +1,675 @@
/*
* Copyright (C) 2015-2018 Alibaba Group Holding Limited
*/
#include <stdio.h>
#include "CoAPExport.h"
#include "CoAPSerialize.h"
#include "CoAPDeserialize.h"
#include "CoAPResource.h"
#include "CoAPObserve.h"
#include "CoAPPlatform.h"
#include "CoAPInternal.h"
#include "iotx_coap_internal.h"
#define COAPAckMsg(header) \
((header.code == COAP_MSG_CODE_EMPTY_MESSAGE) \
&&(header.type == COAP_MESSAGE_TYPE_ACK))
#define CoAPRespMsg(header)\
((header.code >= 0x40) && (header.code < 0xc0))
#define CoAPPingMsg(header)\
((header.code == COAP_MSG_CODE_EMPTY_MESSAGE)\
&& (header.type == COAP_MESSAGE_TYPE_CON))
#define CoAPResetMsg(header)\
(header.type == COAP_MESSAGE_TYPE_RST)
#define CoAPCONRespMsg(header)\
((header.code == COAP_MSG_CODE_205_CONTENT) \
&& (header.type == COAP_MESSAGE_TYPE_CON))
#define CoAPReqMsg(header)\
((1 <= header.code) && (32 > header.code))
#define NOKEEP 0
#define KEEPING 1
#define TOREMOVEKEEP 2
#define COAP_CUR_VERSION 1
#define COAP_MAX_MESSAGE_ID 65535
#define COAP_MAX_RETRY_COUNT 8
#define COAP_ACK_TIMEOUT 600
#define COAP_ACK_RANDOM_FACTOR 1
unsigned short CoAPMessageId_gen(CoAPContext *context)
{
unsigned short msg_id = 0;
CoAPIntContext *ctx = NULL;
if (!context) {
return msg_id;
}
ctx = (CoAPIntContext *)context;
HAL_MutexLock(ctx->mutex);
msg_id = ((COAP_MAX_MESSAGE_ID == ctx->message_id) ? (ctx->message_id = 1) : ctx->message_id++);
HAL_MutexUnlock(ctx->mutex);
return msg_id;
}
int CoAPMessageHandler_set(CoAPMessage *message, CoAPSendMsgHandler handler)
{
if (NULL == message) {
return COAP_ERROR_NULL;
}
message->handler = handler;
return COAP_SUCCESS;
}
static int CoAPMessageList_add(CoAPContext *context, NetworkAddr *remote,
CoAPMessage *message, unsigned char *buffer, int len)
{
CoAPIntContext *ctx = (CoAPIntContext *)context;
CoAPSendNode *node = NULL;
uint64_t tick ;
node = coap_malloc(sizeof(CoAPSendNode));
if (NULL != node) {
memset(node, 0x00, sizeof(CoAPSendNode));
node->acked = 0;
node->user = message->user;
node->header = message->header;
node->handler = message->handler;
node->msglen = len;
node->message = buffer;
node->timeout_val = COAP_ACK_TIMEOUT * COAP_ACK_RANDOM_FACTOR;
memcpy(&node->remote, remote, sizeof(NetworkAddr));
if (platform_is_multicast((const char *)remote->addr) || 1 == message->keep) {
COAP_FLOW("The message %d need keep", message->header.msgid);
node->keep = KEEPING;
} else {
node->keep = NOKEEP;
}
tick = HAL_UptimeMs ();
if (COAP_MESSAGE_TYPE_CON == message->header.type) {
node->timeout = node->timeout_val + tick;
node->retrans_count = COAP_MAX_RETRY_COUNT;
} else {
node->timeout = node->timeout_val * 4 + tick;
node->retrans_count = 0;
}
memcpy(node->token, message->token, message->header.tokenlen);
HAL_MutexLock(ctx->sendlist.list_mutex);
if (ctx->sendlist.count >= ctx->sendlist.maxcount) {
HAL_MutexUnlock(ctx->sendlist.list_mutex);
coap_free(node);
COAP_INFO("The send list is full");
return COAP_ERROR_DATA_SIZE;
} else {
list_add_tail(&node->sendlist, &ctx->sendlist.list);
ctx->sendlist.count ++;
HAL_MutexUnlock(ctx->sendlist.list_mutex);
return COAP_SUCCESS;
}
} else {
return COAP_ERROR_NULL;
}
}
void CoAPMessageToken_dump(unsigned char *token, unsigned char tokenlen)
{
int index = 0, count = 0;
int total = 2 * COAP_MSG_MAX_TOKEN_LEN;
char buff[2 * COAP_MSG_MAX_TOKEN_LEN + 1] = {0}, *ptr = NULL;
ptr = buff;
for (index = 0; index < tokenlen; index++) {
count = HAL_Snprintf(ptr, total, "%02X", token[index]);
ptr += count;
total -= count;
}
COAP_FLOW("Token Len : %d", tokenlen);
COAP_FLOW("Token : %s", buff);
}
void CoAPMessage_dump(NetworkAddr *remote, CoAPMessage *message)
{
int ret = COAP_SUCCESS;
unsigned int ctype;
unsigned char code, msgclass, detail;
if (NULL == remote || NULL == message) {
return;
}
code = (unsigned char)message->header.code;
msgclass = code >> 5;
detail = code & 0x1F;
COAP_FLOW("*********Message Info**********");
COAP_FLOW("Version : %d", message->header.version);
COAP_FLOW("Code : %d.%02d(0x%x)", msgclass, detail, code);
COAP_FLOW("Type : 0x%x", message->header.type);
COAP_FLOW("Msgid : %d", message->header.msgid);
COAP_FLOW("Option : %d", message->optcount);
COAP_FLOW("Payload Len : %d", message->payloadlen);
CoAPMessageToken_dump(message->token, message->header.tokenlen);
COAP_FLOW("Remote : %s:%d", remote->addr, remote->port);
ret = CoAPUintOption_get(message, COAP_OPTION_CONTENT_FORMAT, &ctype);
if (COAP_SUCCESS == ret && NULL != message->payload
&& (COAP_CT_APP_OCTET_STREAM != ctype && COAP_CT_APP_CBOR != ctype)) {
/* COAP_FLOW("Payload : %s", message->payload); */
}
COAP_FLOW("********************************");
}
int CoAPMessage_send(CoAPContext *context, NetworkAddr *remote, CoAPMessage *message)
{
int ret = COAP_SUCCESS;
unsigned short msglen = 0;
unsigned char *buff = NULL;
unsigned short readlen = 0;
CoAPIntContext *ctx = NULL;
if (NULL == message || NULL == context) {
return (COAP_ERROR_INVALID_PARAM);
}
ctx = (CoAPIntContext *)context;
msglen = CoAPSerialize_MessageLength(message);
if (COAP_MSG_MAX_PDU_LEN < msglen) {
COAP_INFO("The message length %d is too loog", msglen);
return COAP_ERROR_DATA_SIZE;
}
buff = (unsigned char *)coap_malloc(msglen);
if (NULL == buff) {
COAP_INFO("Malloc memory failed");
return COAP_ERROR_NULL;
}
memset(buff, 0x00, msglen);
msglen = CoAPSerialize_Message(message, buff, msglen);
#ifndef COAP_OBSERVE_CLIENT_DISABLE
CoAPObsClient_delete(ctx, message);
#endif
readlen = CoAPNetwork_write(ctx->p_network, remote,
buff, (unsigned int)msglen, ctx->waittime);
if (msglen == readlen) {/*Send message success*/
if (CoAPReqMsg(message->header) || CoAPCONRespMsg(message->header)) {
COAP_FLOW("The message id %d len %d send success, add to the list",
message->header.msgid, msglen);
ret = CoAPMessageList_add(ctx, remote, message, buff, msglen);
if (COAP_SUCCESS != ret) {
coap_free(buff);
COAP_ERR("Add the message %d to list failed", message->header.msgid);
return ret;
}
} else {
coap_free(buff);
COAP_FLOW("The message %d isn't CON msg, needless to be retransmitted",
message->header.msgid);
}
} else {
coap_free(buff);
COAP_ERR("CoAP transport write failed, send message %d return %d", message->header.msgid, ret);
return COAP_ERROR_WRITE_FAILED;
}
CoAPMessage_dump(remote, message);
return COAP_SUCCESS;
}
int CoAPMessage_cancel(CoAPContext *context, CoAPMessage *message)
{
CoAPSendNode *node = NULL, *next = NULL;
CoAPIntContext *ctx = (CoAPIntContext *)context;
if (NULL == context || NULL == message) {
return COAP_ERROR_NULL;
}
HAL_MutexLock(ctx->sendlist.list_mutex);
list_for_each_entry_safe(node, next, &ctx->sendlist.list, sendlist, CoAPSendNode) {
if (node->header.msgid == message->header.msgid) {
list_del(&node->sendlist);
ctx->sendlist.count--;
COAP_INFO("Cancel message %d from list, cur count %d",
node->header.msgid, ctx->sendlist.count);
coap_free(node->message);
coap_free(node);
}
}
HAL_MutexUnlock(ctx->sendlist.list_mutex);
return COAP_SUCCESS;
}
int CoAPMessageId_cancel(CoAPContext *context, unsigned short msgid)
{
CoAPSendNode *node = NULL, *next = NULL;
CoAPIntContext *ctx = (CoAPIntContext *)context;
if (NULL == context || NULL == ctx->sendlist.list_mutex) {
return COAP_ERROR_NULL;
}
HAL_MutexLock(ctx->sendlist.list_mutex);
list_for_each_entry_safe(node, next, &ctx->sendlist.list, sendlist, CoAPSendNode) {
if (NULL != node) {
if (node->header.msgid == msgid) {
list_del(&node->sendlist);
ctx->sendlist.count--;
COAP_FLOW("Cancel message %d from list, cur count %d",
node->header.msgid, ctx->sendlist.count);
coap_free(node->message);
coap_free(node);
}
}
}
HAL_MutexUnlock(ctx->sendlist.list_mutex);
return COAP_SUCCESS;
}
static int CoAPAckMessage_handle(CoAPContext *context, CoAPMessage *message)
{
CoAPSendNode *node = NULL, *next;
CoAPIntContext *ctx = (CoAPIntContext *)context;
HAL_MutexLock(ctx->sendlist.list_mutex);
list_for_each_entry_safe(node, next, &ctx->sendlist.list, sendlist, CoAPSendNode) {
if (node->header.msgid == message->header.msgid) {
CoAPSendMsgHandler handler = node->handler;
void *user_data = node->user;
NetworkAddr remote = {0};
memcpy(&remote, &node->remote, sizeof(remote));
node->acked = 1;
if (CoAPRespMsg(node->header)) { /* CON response message */
list_del(&node->sendlist);
coap_free(node->message);
coap_free(node);
ctx->sendlist.count --;
COAP_DEBUG("The CON response message %d receive ACK, remove it", message->header.msgid);
}
if (handler) handler(ctx, COAP_RECV_RESP_SUC, user_data, &remote, NULL);
HAL_MutexUnlock(ctx->sendlist.list_mutex);
return COAP_SUCCESS;
}
}
HAL_MutexUnlock(ctx->sendlist.list_mutex);
return COAP_SUCCESS;
}
static int CoAPAckMessage_send(CoAPContext *context, NetworkAddr *remote, unsigned short msgid)
{
int ret = COAP_SUCCESS;
CoAPMessage message;
CoAPIntContext *ctx = (CoAPIntContext *)context;
CoAPMessage_init(&message);
CoAPMessageId_set(&message, msgid);
COAP_DEBUG("Send Ack Response Message");
ret = CoAPMessage_send(ctx, remote, &message);
CoAPMessage_destory(&message);
return ret;
}
static int CoAPRestMessage_send(CoAPContext *context, NetworkAddr *remote, unsigned short msgid)
{
int ret = COAP_SUCCESS;
CoAPMessage message;
CoAPIntContext *ctx = (CoAPIntContext *)context;
CoAPMessage_init(&message);
CoAPMessageType_set(&message, COAP_MESSAGE_TYPE_RST);
CoAPMessageId_set(&message, msgid);
COAP_DEBUG("Send Rest Pong Message");
ret = CoAPMessage_send(ctx, remote, &message);
CoAPMessage_destory(&message);
return ret;
}
static int CoAPErrRespMessage_send(CoAPContext *context, NetworkAddr *remote, CoAPMessage *message,
unsigned char err_code)
{
CoAPMessage response;
int ret = COAP_SUCCESS;
CoAPIntContext *ctx = (CoAPIntContext *)context;
CoAPMessage_init(&response);
CoAPMessageCode_set(&response, err_code);
CoAPMessageId_set(&response, message->header.msgid);
CoAPMessageToken_set(&response, message->token, message->header.tokenlen);
if (COAP_MESSAGE_TYPE_CON == message->header.type) {
CoAPMessageType_set(&response, COAP_MESSAGE_TYPE_ACK);
} else {
CoAPMessageType_set(&response, message->header.type);
}
COAP_FLOW("Send Error Response Message");
ret = CoAPMessage_send(ctx, remote, &response);
CoAPMessage_destory(&response);
return ret;
}
static int CoAPRespMessage_handle(CoAPContext *context, NetworkAddr *remote, CoAPMessage *message)
{
char found = 0;
CoAPSendNode *node = NULL, *next = NULL;
CoAPIntContext *ctx = (CoAPIntContext *)context;
if (COAP_MESSAGE_TYPE_CON == message->header.type) {
CoAPAckMessage_send(ctx, remote, message->header.msgid);
}
HAL_MutexLock(ctx->sendlist.list_mutex);
list_for_each_entry_safe(node, next, &ctx->sendlist.list, sendlist, CoAPSendNode) {
if (0 != node->header.tokenlen && node->header.tokenlen == message->header.tokenlen
&& 0 == memcmp(node->token, message->token, message->header.tokenlen)) {
if (!node->keep) {
list_del(&node->sendlist);
ctx->sendlist.count--;
COAP_FLOW("Remove the message id %d from list", node->header.msgid);
} else {
COAP_FLOW("Find the message id %d, It need keep", node->header.msgid);
}
found = 1;
break;
}
}
if (found && NULL != node) {
message->user = node->user;
/* TODO: comment it */
/*
if (COAP_MSG_CODE_400_BAD_REQUEST <= message->header.code) {
if (NULL != ctx->notifier) {
ctx->notifier(message->header.code, remote, message);
}
}
*/
if (NULL != node->handler) {
CoAPSendMsgHandler handler = node->handler;
#ifndef COAP_OBSERVE_CLIENT_DISABLE
CoAPObsClient_add(ctx, message, remote, node);
#endif
HAL_MutexUnlock(ctx->sendlist.list_mutex);
COAP_FLOW("Call the response message callback %p", handler);
handler(ctx, COAP_REQUEST_SUCCESS, message->user, remote, message);
} else {
HAL_MutexUnlock(ctx->sendlist.list_mutex);
}
if (!node->keep) {
if (NULL != node->message) {
coap_free(node->message);
}
coap_free(node);
COAP_DEBUG("The message needless keep, free it");
}
} else {
HAL_MutexUnlock(ctx->sendlist.list_mutex);
#ifndef COAP_OBSERVE_CLIENT_DISABLE
CoAPObsClient_add(ctx, message, remote, NULL);
#endif
}
return COAP_ERROR_NOT_FOUND;
}
#define PACKET_INTERVAL_THRE_MS 800
#define PACKET_TRIGGER_NUM 100
static int CoAPRequestMessage_ack_send(CoAPContext *context, NetworkAddr *remote, unsigned short msgid)
{
int ret = COAP_SUCCESS;
CoAPMessage message;
CoAPIntContext *ctx = (CoAPIntContext *)context;
CoAPMessage_init(&message);
CoAPMessageId_set(&message, msgid);
COAP_INFO("Send Ack Response Message: %d", msgid);
ret = CoAPMessage_send(ctx, remote, &message);
CoAPMessage_destory(&message);
return ret;
}
static int CoAPRequestMessage_handle(CoAPContext *context, NetworkAddr *remote, CoAPMessage *message)
{
int index = 0;
int ret = COAP_SUCCESS;
CoAPResource *resource = NULL;
unsigned char path[COAP_MSG_MAX_PATH_LEN] = {0};
unsigned char *tmp = path;
CoAPIntContext *ctx = (CoAPIntContext *)context;
COAP_FLOW("CoAPRequestMessage_handle: %p", ctx);
/* TODO: if need only one callback */
for (index = 0; index < message->optcount; index++) {
if (COAP_OPTION_URI_PATH == message->options[index].num) {
if ((COAP_MSG_MAX_PATH_LEN - 1) >= (tmp - path + message->options[index].len)) {
*tmp = '/';
tmp += 1;
strncpy((char *)tmp, (const char *)message->options[index].val, message->options[index].len);
tmp += message->options[index].len;
}
}
}
if (strcmp("/sys/device/info/notify", (const char *)path)) {
COAP_DEBUG("Request path is %s", path);
}
resource = CoAPResourceByPath_get(ctx, (char *)path);
if (NULL != resource) {
if (NULL != resource->callback) {
if (((resource->permission) & (1 << ((message->header.code) - 1))) > 0) {
if (message->header.type == COAP_MESSAGE_TYPE_CON) {
CoAPRequestMessage_ack_send(ctx, remote, message->header.msgid);
}
resource->callback(ctx, (char *)path, remote, message);
} else {
COAP_FLOW("The resource %s isn't allowed", resource->path);
ret = CoAPErrRespMessage_send(ctx, remote, message, COAP_MSG_CODE_405_METHOD_NOT_ALLOWED);
}
} else {
COAP_FLOW("The resource %s handler isn't exist", resource->path);
ret = CoAPErrRespMessage_send(ctx, remote, message, COAP_MSG_CODE_405_METHOD_NOT_ALLOWED);
}
} else {
COAP_FLOW("The resource %s isn't found", path);
ret = CoAPErrRespMessage_send(ctx, remote, message, COAP_MSG_CODE_404_NOT_FOUND);
}
return ret;
}
static void CoAPMessage_handle(CoAPContext *context,
NetworkAddr *remote,
unsigned char *buf,
unsigned short datalen)
{
int ret = COAP_SUCCESS;
CoAPMessage message;
CoAPIntContext *ctx = (CoAPIntContext *)context;
COAP_FLOW("CoAPMessage_handle: %p", ctx);
memset(&message, 0x00, sizeof(CoAPMessage));
ret = CoAPDeserialize_Message(&message, buf, datalen);
if (COAP_SUCCESS != ret) {
if (NULL != ctx->notifier) {
/* TODO: */
/* context->notifier(context, event); */
}
}
COAP_FLOW("--------Receive a Message------");
CoAPMessage_dump(remote, &message);
if (COAPAckMsg(message.header) || CoAPResetMsg(message.header)) {
/* TODO: implement handle client observe */
/* TODO: if need call response callback */
CoAPAckMessage_handle(ctx, &message);
} else if (CoAPRespMsg(message.header)) {
CoAPRespMessage_handle(ctx, remote, &message);
} else if (CoAPPingMsg(message.header)) {
CoAPRestMessage_send(ctx, remote, message.header.msgid);
} else if (CoAPReqMsg(message.header)) {
CoAPRequestMessage_handle(ctx, remote, &message);
} else {
COAP_INFO("Weird packet,drop it");
}
}
int CoAPMessage_process(CoAPContext *context, unsigned int timeout)
{
int len = 0;
NetworkAddr remote;
char ip_addr[17] = {0};
CoAPIntContext *ctx = (CoAPIntContext *)context;
if (NULL == context) {
return COAP_ERROR_NULL;
}
HAL_Wifi_Get_IP(ip_addr, NULL);
while (1) {
memset(&remote, 0x00, sizeof(NetworkAddr));
memset(ctx->recvbuf, 0x00, COAP_MSG_MAX_PDU_LEN);
len = CoAPNetwork_read(ctx->p_network,
&remote,
ctx->recvbuf,
COAP_MSG_MAX_PDU_LEN, timeout);
if (strncmp((const char *)ip_addr, (const char *)remote.addr, sizeof(ip_addr)) == 0) /* drop the packet from itself*/
continue;
if (len > 0) {
CoAPMessage_handle(ctx, &remote, ctx->recvbuf, len);
} else {
return len;
}
}
}
static void Check_timeout (void *context)
{
CoAPIntContext *ctx = (CoAPIntContext *)context;
CoAPSendNode *node = NULL, *next = NULL, *timeout_node = NULL;
uint64_t tick = HAL_UptimeMs ();
do {
timeout_node = NULL;
HAL_MutexLock(ctx->sendlist.list_mutex);
list_for_each_entry_safe(node, next, &ctx->sendlist.list, sendlist, CoAPSendNode) {
if (node->keep != NOKEEP) {
continue;
}
if ((node->retrans_count > 0) || (node->timeout >= tick)) {
continue;
}
/*Remove the node from the list*/
list_del_init(&node->sendlist);
ctx->sendlist.count--;
COAP_INFO("Retransmit timeout,remove the message id %d count %d",
node->header.msgid, ctx->sendlist.count);
#ifndef COAP_OBSERVE_SERVER_DISABLE
CoapObsServerAll_delete(ctx, &node->remote);
#endif
timeout_node = node;
break;
}
HAL_MutexUnlock(ctx->sendlist.list_mutex);
if (timeout_node) {
if(NULL != timeout_node->handler){
timeout_node->handler(ctx, COAP_RECV_RESP_TIMEOUT, timeout_node->user, &timeout_node->remote, NULL);
}
coap_free(timeout_node->message);
coap_free(timeout_node);
}
} while (timeout_node);
}
static void Retansmit (void *context)
{
CoAPIntContext *ctx = (CoAPIntContext *)context;
CoAPSendNode *node = NULL, *next = NULL;
unsigned int ret = 0;
uint64_t tick = HAL_UptimeMs ();
HAL_MutexLock(ctx->sendlist.list_mutex);
list_for_each_entry_safe(node, next, &ctx->sendlist.list, sendlist, CoAPSendNode) {
if (NULL == node || node->timeout > tick ) {
continue;
}
if (node->retrans_count > 0) {
/*If has received ack message, don't resend the message*/
if(0 == node->acked){
COAP_DEBUG("Retansmit the message id %d len %d", node->header.msgid, node->msglen);
ret = CoAPNetwork_write(ctx->p_network, &node->remote, node->message, node->msglen, ctx->waittime);
if (ret != COAP_SUCCESS) {
}
}
node->timeout_val = node->timeout_val * 3 / 2;
-- node->retrans_count;
if (node->retrans_count == 0) {
node->timeout = tick + COAP_ACK_TIMEOUT;
} else {
node->timeout = tick + node->timeout_val;
}
COAP_FLOW("node->timeout_val = %d , node->timeout=%d ,tick=%d", node->timeout_val,node->timeout,tick);
}
}
HAL_MutexUnlock(ctx->sendlist.list_mutex);
}
extern void *coap_yield_mutex;
int CoAPMessage_cycle(CoAPContext *context)
{
int res = 0;
CoAPIntContext *ctx = (CoAPIntContext *)context;
if (NULL == context) {
return COAP_ERROR_NULL;
}
if (coap_yield_mutex != NULL) {
HAL_MutexLock(coap_yield_mutex);
}
res = CoAPMessage_process(ctx, ctx->waittime);
Retansmit (ctx);
Check_timeout (ctx);
if (coap_yield_mutex != NULL) {
HAL_MutexUnlock(coap_yield_mutex);
}
if (res < 0) {
HAL_SleepMs(20);
}
return res;
}

View File

@@ -0,0 +1,88 @@
/*
* Copyright (C) 2015-2018 Alibaba Group Holding Limited
*/
#ifndef __COAP_MESSAGE_H__
#define __COAP_MESSAGE_H__
#include "CoAPExport.h"
#ifdef __cplusplus
extern "C" {
#endif /* __cplusplus */
typedef struct
{
CoAPMsgHeader header;
unsigned char retrans_count;
unsigned char token[COAP_MSG_MAX_TOKEN_LEN];
unsigned long long timeout;
unsigned short timeout_val;
unsigned int msglen;
CoAPSendMsgHandler handler;
NetworkAddr remote;
struct list_head sendlist;
void *user;
unsigned char *message;
int acked;
int keep;
} CoAPSendNode;
int CoAPStrOption_add(CoAPMessage *message, unsigned short optnum,
unsigned char *data, unsigned short datalen);
int CoAPStrOption_get(CoAPMessage *message, unsigned short optnum,
unsigned char *data, unsigned short *datalen);
int CoAPUintOption_add(CoAPMessage *message, unsigned short optnum,
unsigned int data);
int CoAPUintOption_get(CoAPMessage *message,
unsigned short optnum,
unsigned int *data);
int CoAPOption_present(CoAPMessage *message, unsigned short option);
unsigned short CoAPMessageId_gen(CoAPContext *context);
int CoAPMessageId_set(CoAPMessage *message, unsigned short msgid);
int CoAPMessageType_set(CoAPMessage *message, unsigned char type);
int CoAPMessageCode_set(CoAPMessage *message, CoAPMessageCode code);
int CoAPMessageToken_set(CoAPMessage *message, unsigned char *token,
unsigned char tokenlen);
int CoAPMessageUserData_set(CoAPMessage *message, void *userdata);
int CoAPMessageKeep_Set(CoAPMessage *message, int keep);
int CoAPMessagePayload_set(CoAPMessage *message, unsigned char *payload,
unsigned short payloadlen);
int CoAPMessageHandler_set(CoAPMessage *message, CoAPSendMsgHandler handler);
int CoAPMessage_init(CoAPMessage *message);
int CoAPMessage_destory(CoAPMessage *message);
int CoAPMessage_send(CoAPContext *context, NetworkAddr *remote, CoAPMessage *message);
int CoAPMessage_recv(CoAPContext *context, unsigned int timeout, int readcount);
int CoAPMessage_retransmit(CoAPContext *context);
int CoAPMessage_process(CoAPContext *context, unsigned int timeout);
int CoAPMessage_cycle(CoAPContext *context);
int CoAPMessage_cancel(CoAPContext *context, CoAPMessage *message);
#ifdef __cplusplus
}
#endif /* __cplusplus */
#endif

View File

@@ -0,0 +1,137 @@
/*
* Copyright (C) 2015-2018 Alibaba Group Holding Limited
*/
#include <stdint.h>
#include <stdio.h>
#include <string.h>
#include <errno.h>
#include "iotx_coap_internal.h"
#include "CoAPExport.h"
#include "CoAPPlatform.h"
#include "CoAPNetwork.h"
int CoAPNetwork_read(NetworkContext *p_context,
NetworkAddr *p_remote,
unsigned char *p_data,
unsigned int datalen,
unsigned int timeout_ms)
{
int len = 0;
NetworkConf *network = NULL;
if (NULL == p_context || NULL == p_remote || NULL == p_data) {
return -1; /* TODO */
}
network = (NetworkConf *)p_context;
#ifdef COAP_DTLS_SUPPORT
if (COAP_NETWORK_DTLS == network->type) {
} else {
#endif
len = HAL_UDP_recvfrom(network->fd, p_remote, p_data,
datalen, timeout_ms);
/* COAP_DEBUG("[CoAP-NWK]: Network read return %d", len); */
#ifdef COAP_DTLS_SUPPORT
}
#endif
return len;
}
int CoAPNetwork_write(NetworkContext *p_context,
NetworkAddr *p_remote,
const unsigned char *p_data,
unsigned int datalen,
unsigned int timeout_ms)
{
int len = 0;
NetworkConf *network = NULL;
if (NULL == p_context || NULL == p_remote || NULL == p_data) {
return -1; /* TODO */
}
network = (NetworkConf *)p_context;
#ifdef COAP_DTLS_SUPPORT
/* TODO: */
if (COAP_NETWORK_DTLS == network->type) {
} else {
#endif
len = HAL_UDP_sendto(network->fd, p_remote,
p_data, datalen, timeout_ms);
#ifdef COAP_DTLS_SUPPORT
}
#endif
return len;
}
NetworkContext *CoAPNetwork_init(const NetworkInit *p_param)
{
NetworkConf *network = NULL;
if (NULL == p_param) {
return NULL;
}
network = coap_malloc(sizeof(NetworkConf));
if (NULL == network) {
return NULL;
}
memset(network, 0x00, sizeof(NetworkConf));
network->type = p_param->type;
#ifdef COAP_DTLS_SUPPORT
if (COAP_NETWORK_DTLS == network->type) {
/* TODO: */
coap_free(network);
return NULL;
} else {
#endif
/*Create udp socket*/
network->port = p_param->port;
network->fd = (intptr_t)HAL_UDP_create_without_connect(NULL, network->port);
if ((intptr_t) - 1 == network->fd) {
coap_free(network);
return NULL;
}
HAL_UDP_joinmulticast(network->fd, p_param->group);
#ifdef COAP_DTLS_SUPPORT
}
#endif
return (NetworkContext *)network;
}
void CoAPNetwork_deinit(NetworkContext *p_context)
{
NetworkConf *network = NULL;
if (NULL == p_context) {
return;
}
network = (NetworkConf *)p_context;
#ifdef COAP_DTLS_SUPPORT
if (COAP_NETWORK_DTLS == network->type) {
/* TODO: */
} else {
#endif
HAL_UDP_close_without_connect(network->fd);
coap_free(p_context);
p_context = NULL;
#ifdef COAP_DTLS_SUPPORT
}
#endif
return;
}

View File

@@ -0,0 +1,59 @@
/*
* Copyright (C) 2015-2018 Alibaba Group Holding Limited
*/
#ifndef __CoAPNETWORK_H__
#define __CoAPNETWORK_H__
#include <stdint.h>
#ifdef __cplusplus
extern "C" {
#endif /* __cplusplus */
typedef enum {
COAP_NETWORK_NOSEC = 0,
COAP_NETWORK_DTLS,
} CoAPNetworkType;
typedef struct {
CoAPNetworkType type;
unsigned short port;
intptr_t fd;
} NetworkConf;
typedef void NetworkContext;
typedef struct {
CoAPNetworkType type;
char *group;
unsigned short port;
#ifdef COAP_DTLS_SUPPORT
/* TODO: */
#endif
} NetworkInit;
NetworkContext *CoAPNetwork_init(const NetworkInit *p_param);
int CoAPNetwork_write(NetworkContext *p_context,
NetworkAddr *p_remote,
const unsigned char *p_data,
unsigned int datalen,
unsigned int timeout);
int CoAPNetwork_read(NetworkContext *p_context,
NetworkAddr *p_remote,
unsigned char *p_data,
unsigned int datalen,
unsigned int timeout);
void CoAPNetwork_deinit(NetworkContext *p_context);
#ifdef __cplusplus
}
#endif /* __cplusplus */
#endif

View File

@@ -0,0 +1,366 @@
/*
* Copyright (C) 2015-2018 Alibaba Group Holding Limited
*/
#include "CoAPExport.h"
#include "CoAPResource.h"
#include "CoAPObserve.h"
#include "CoAPMessage.h"
#include "iotx_coap_internal.h"
#include "CoAPPlatform.h"
#include "CoAPInternal.h"
#ifndef COAP_OBSERVE_SERVER_DISABLE
int CoAPObsServer_init(CoAPContext *context, unsigned char obs_maxcount)
{
CoAPIntContext *ctx = (CoAPIntContext *)context;
ctx->obsserver.list_mutex = HAL_MutexCreate();
HAL_MutexLock(ctx->obsserver.list_mutex);
INIT_LIST_HEAD(&ctx->obsserver.list);
ctx->obsserver.count = 0;
ctx->obsserver.maxcount = obs_maxcount;
HAL_MutexUnlock(ctx->obsserver.list_mutex);
return COAP_SUCCESS;
}
int CoAPObsServer_deinit(CoAPContext *context)
{
CoAPIntContext *ctx = (CoAPIntContext *)context;
CoapObserver *node = NULL, *next = NULL;
HAL_MutexLock(ctx->obsserver.list_mutex);
list_for_each_entry_safe(node, next, &ctx->obsserver.list, obslist, CoapObserver) {
list_del(&node->obslist);
COAP_DEBUG("Delete %s:%d from observe server", node->remote.addr, node->remote.port);
coap_free(node);
}
ctx->obsserver.count = 0;
ctx->obsserver.maxcount = 0;
HAL_MutexUnlock(ctx->obsserver.list_mutex);
HAL_MutexDestroy(ctx->obsserver.list_mutex);
ctx->obsserver.list_mutex = NULL;
return COAP_SUCCESS;
}
int CoAPObsServer_add(CoAPContext *context, const char *path, NetworkAddr *remote, CoAPMessage *request)
{
int ret = COAP_SUCCESS;
unsigned int observe;
unsigned int acceptype = 0;
CoapObserver *obs = NULL;
CoAPResource *resource = NULL;
CoapObserver *node = NULL;
CoAPIntContext *ctx = (CoAPIntContext *)context;
resource = CoAPResourceByPath_get(ctx, path);
ret = CoAPUintOption_get(request, COAP_OPTION_OBSERVE, &observe);
if (NULL != resource && COAP_SUCCESS == ret && 0 == observe) {
/*Check if the observe client already exist*/
HAL_MutexLock(ctx->obsserver.list_mutex);
list_for_each_entry(node, &ctx->obsserver.list, obslist, CoapObserver) {
if ((node->p_resource_of_interest == resource) &&
(node->remote.port == remote->port) &&
(0 == memcmp(node->remote.addr, remote->addr, NETWORK_ADDR_LEN))) {
COAP_DEBUG("The observe client %s:%d already exist,update it", node->remote.addr, node->remote.port);
memcpy(node->token, request->token, request->header.tokenlen);
node->tokenlen = request->header.tokenlen;
HAL_MutexUnlock(ctx->obsserver.list_mutex);
return COAP_ERROR_OBJ_ALREADY_EXIST;
}
}
HAL_MutexUnlock(ctx->obsserver.list_mutex);
obs = coap_malloc(sizeof(CoapObserver));
if (NULL == obs) {
COAP_ERR("Allocate memory failed");
return COAP_ERROR_MALLOC;
}
memset(obs, 0x00, sizeof(CoapObserver));
obs->msg_type = request->header.type;
obs->p_resource_of_interest = resource;
memcpy(&obs->remote, remote, sizeof(NetworkAddr));
memcpy(obs->token, request->token, request->header.tokenlen);
obs->tokenlen = request->header.tokenlen;
CoAPUintOption_get(request, COAP_OPTION_ACCEPT, &acceptype);
obs->ctype = (acceptype == 0) ? COAP_CT_APP_JSON : acceptype;
obs->observer_sequence_num = 0;
/* TODO: */
/* CoAPObsServer_find(); */
HAL_MutexLock(ctx->obsserver.list_mutex);
if (ctx->obsserver.count >= ctx->obsserver.maxcount) {
HAL_MutexUnlock(ctx->obsserver.list_mutex);
coap_free(obs);
COAP_INFO("Cur have %d observer, max allow %d", ctx->obsserver.count, ctx->obsserver.maxcount);
return COAP_ERROR_DATA_SIZE;
} else {
list_add_tail(&obs->obslist, &ctx->obsserver.list);
ctx->obsserver.count ++;
COAP_DEBUG("Create a observe node, cur have %d nodes", ctx->obsserver.count);
HAL_MutexUnlock(ctx->obsserver.list_mutex);
return COAP_SUCCESS;
}
}
return COAP_ERROR_NOT_FOUND;
}
int CoapObsServer_delete(CoAPContext *context, NetworkAddr *remote,
CoAPResource *resource)
{
CoapObserver *node = NULL, *next = NULL;
CoAPIntContext *ctx = (CoAPIntContext *)context;
HAL_MutexLock(ctx->obsserver.list_mutex);
list_for_each_entry_safe(node, next, &ctx->obsserver.list, obslist, CoapObserver) {
if ((node->p_resource_of_interest == resource) &&
(node->remote.port == remote->port) &&
(0 == memcmp(node->remote.addr, remote->addr, NETWORK_ADDR_LEN))) {
ctx->obsserver.count --;
list_del(&node->obslist);
COAP_DEBUG("Delete %s:%d from observe server", node->remote.addr, node->remote.port);
coap_free(node);
break;
}
}
HAL_MutexUnlock(ctx->obsserver.list_mutex);
return COAP_SUCCESS;
}
int CoapObsServerAll_delete(CoAPContext *context, NetworkAddr *remote)
{
CoapObserver *node = NULL, *next = NULL;
CoAPIntContext *ctx = (CoAPIntContext *)context;
HAL_MutexLock(ctx->obsserver.list_mutex);
list_for_each_entry_safe(node, next, &ctx->obsserver.list, obslist, CoapObserver) {
if (NULL != node && (node->remote.port == remote->port) &&
(0 == memcmp(node->remote.addr, remote->addr, NETWORK_ADDR_LEN))) {
ctx->obsserver.count --;
list_del(&node->obslist);
COAP_DEBUG("Delete %s:%d from observe server, cur observe count %d",
node->remote.addr, node->remote.port, ctx->obsserver.count);
coap_free(node);
}
}
HAL_MutexUnlock(ctx->obsserver.list_mutex);
return COAP_SUCCESS;
}
int CoAPObsServer_notify(CoAPContext *context,
const char *path, unsigned char *payload,
unsigned short payloadlen, CoAPDataEncrypt handler)
{
unsigned int ret = COAP_SUCCESS;
CoAPResource *resource = NULL;
CoapObserver *node = NULL;
CoAPLenString src;
CoAPLenString dest;
CoAPIntContext *ctx = (CoAPIntContext *)context;
resource = CoAPResourceByPath_get(ctx, path);
if (NULL != resource) {
HAL_MutexLock(ctx->obsserver.list_mutex);
list_for_each_entry(node, &ctx->obsserver.list, obslist, CoapObserver) {
if (node->p_resource_of_interest == resource) {
CoAPMessage message;
CoAPMessage_init(&message);
CoAPMessageType_set(&message, node->msg_type);
CoAPMessageCode_set(&message, COAP_MSG_CODE_205_CONTENT);
CoAPMessageId_set(&message, CoAPMessageId_gen(ctx));
CoAPMessageHandler_set(&message, NULL);
CoAPMessageUserData_set(&message, node->p_resource_of_interest);
CoAPMessageToken_set(&message, node->token, node->tokenlen);
CoAPUintOption_add(&message, COAP_OPTION_OBSERVE, node->observer_sequence_num++);
CoAPUintOption_add(&message, COAP_OPTION_CONTENT_FORMAT, node->ctype);
CoAPUintOption_add(&message, COAP_OPTION_MAXAGE, resource->maxage);
COAP_DEBUG("Send notify message path %s to remote %s:%d ",
path, node->remote.addr, node->remote.port);
memset(&dest, 0x00, sizeof(CoAPLenString));
if (NULL != handler) {
src.len = payloadlen;
src.data = payload;
ret = handler(context, path, &node->remote, &message, &src, &dest);
if (COAP_SUCCESS == ret) {
CoAPMessagePayload_set(&message, dest.data, dest.len);
} else {
COAP_INFO("Encrypt payload failed");
}
} else {
CoAPMessagePayload_set(&message, payload, payloadlen);
}
ret = CoAPMessage_send(ctx, &node->remote, &message);
if (NULL != handler && 0 != dest.len && NULL != dest.data) {
coap_free(dest.data);
dest.len = 0;
}
CoAPMessage_destory(&message);
}
}
HAL_MutexUnlock(ctx->obsserver.list_mutex);
}
return ret;
}
#endif
#ifndef COAP_OBSERVE_CLIENT_DISABLE
int CoAPObsClient_init(CoAPContext *context, unsigned char obs_maxcount)
{
CoAPIntContext *ctx = (CoAPIntContext *)context;
ctx->obsclient.list_mutex = HAL_MutexCreate();
HAL_MutexLock(ctx->obsclient.list_mutex);
INIT_LIST_HEAD(&ctx->obsclient.list);
ctx->obsclient.count = 0;
ctx->obsclient.maxcount = obs_maxcount;
HAL_MutexUnlock(ctx->obsclient.list_mutex);
return COAP_SUCCESS;
}
int CoAPObsClient_deinit(CoAPContext *context)
{
CoAPObservable *node = NULL, *next = NULL;
CoAPIntContext *ctx = (CoAPIntContext *)context;
HAL_MutexLock(ctx->obsclient.list_mutex);
list_for_each_entry_safe(node, next, &ctx->obsclient.list, obslist, CoAPObservable) {
list_del(&node->obslist);
coap_free(node);
}
ctx->obsclient.count = 0;
ctx->obsclient.maxcount = 0;
HAL_MutexUnlock(ctx->obsclient.list_mutex);
HAL_MutexDestroy(ctx->obsclient.list_mutex);
ctx->obsclient.list_mutex = NULL;
return COAP_SUCCESS;
}
int CoAPObsClient_add(CoAPContext *context, CoAPMessage *message, NetworkAddr *remote, CoAPSendNode *sendnode)
{
CoAPObservable *node = NULL, *next = NULL;
CoAPIntContext *ctx = (CoAPIntContext *)context;
if (COAP_SUCCESS == CoAPOption_present(message, COAP_OPTION_OBSERVE)) {
COAP_DEBUG("There is Observe option in message, handle it");
if (NULL == sendnode) { /* Not the first response */
HAL_MutexLock(ctx->obsclient.list_mutex);
list_for_each_entry(node, &ctx->obsclient.list, obslist, CoAPObservable) {
if (0 != node->tokenlen && node->tokenlen == message->header.tokenlen
&& 0 == memcmp(node->token, message->token, node->tokenlen)) {
CoAPUintOption_get(message, COAP_OPTION_MAXAGE, &node->max_age);
if (NULL != node->callback) {
COAP_DEBUG("Call the observe client callback %p", node->callback);
node->callback(ctx, COAP_REQUEST_SUCCESS, node->userdata, remote, message);
} else {
COAP_INFO("The observe client callback is NULL");
}
break;
}
}
HAL_MutexUnlock(ctx->obsclient.list_mutex);
} else {
int found = 0;
HAL_MutexLock(ctx->obsclient.list_mutex);
list_for_each_entry(node, &ctx->obsclient.list, obslist, CoAPObservable) {
if (0 != node->tokenlen && node->tokenlen == message->header.tokenlen
&& 0 == memcmp(node->token, message->token, node->tokenlen)) {
found = 1;
break;
}
}
if (!found && ctx->obsclient.count < ctx->obsclient.maxcount) {
CoAPObservable *newnode = coap_malloc(sizeof(CoAPObservable));
if (NULL != newnode) {
memset(newnode, 0x00, sizeof(CoAPObservable));
newnode->tokenlen = message->header.tokenlen;
memcpy(newnode->token, message->token, message->header.tokenlen);
memcpy(&newnode->remote, remote, sizeof(NetworkAddr));
newnode->callback = sendnode->handler;
newnode->userdata = sendnode->user;
CoAPUintOption_get(message, COAP_OPTION_MAXAGE, &newnode->max_age);
list_add_tail(&newnode->obslist, &ctx->obsclient.list);
ctx->obsclient.count ++;
COAP_DEBUG("Add a new obsclient");
}
} else {
COAP_INFO("Cur have %d obsclient, max allow %d", ctx->obsclient.count, ctx->obsclient.maxcount);
}
HAL_MutexUnlock(ctx->obsclient.list_mutex);
}
} else {
HAL_MutexLock(ctx->obsclient.list_mutex);
list_for_each_entry_safe(node, next, &ctx->obsclient.list, obslist, CoAPObservable) {
if (0 != node->tokenlen && node->tokenlen == message->header.tokenlen
&& 0 == memcmp(node->token, message->token, node->tokenlen)) {
list_del(&node->obslist);
ctx->obsclient.count --;
coap_free(node);
break;
}
}
HAL_MutexUnlock(ctx->obsclient.list_mutex);
}
return COAP_SUCCESS;
}
int CoAPObsClient_delete(CoAPContext *context, CoAPMessage *message)
{
int ret = COAP_SUCCESS;
unsigned int observe_option = 0;
CoAPObservable *node = NULL, *next = NULL;
CoAPIntContext *ctx = (CoAPIntContext *)context;
if (NULL == ctx || NULL == message) {
return COAP_ERROR_INVALID_PARAM;
}
if (COAP_MSG_CODE_GET == message->header.code) {
if (COAP_SUCCESS == CoAPOption_present(message, COAP_OPTION_OBSERVE)) {
ret = CoAPUintOption_get(message, COAP_OPTION_OBSERVE, &observe_option);
if (COAP_SUCCESS == ret && 1 == observe_option) {
HAL_MutexLock(ctx->obsclient.list_mutex);
list_for_each_entry_safe(node, next, &ctx->obsclient.list, obslist, CoAPObservable) {
if (0 != node->tokenlen && node->tokenlen == message->header.tokenlen
&& 0 == memcmp(node->token, message->token, node->tokenlen)) {
list_del(&node->obslist);
ctx->obsclient.count --;
coap_free(node);
break;
}
}
HAL_MutexUnlock(ctx->obsclient.list_mutex);
}
}
}
return COAP_SUCCESS;
}
#endif

View File

@@ -0,0 +1,63 @@
/*
* Copyright (C) 2015-2018 Alibaba Group Holding Limited
*/
#ifndef __COAP_OBSERVE_H__
#define __COAP_OBSERVE_H__
#include "CoAPExport.h"
#include "CoAPMessage.h"
#include "CoAPResource.h"
#include "iotx_coap_internal.h"
#ifdef __cplusplus
extern "C" {
#endif /* __cplusplus */
typedef struct
{
NetworkAddr remote;
unsigned char token[COAP_MSG_MAX_TOKEN_LEN];
unsigned char tokenlen;
unsigned char ctype;
CoAPResource *p_resource_of_interest;
unsigned int observer_sequence_num;
CoAPMessageCode msg_type;
struct list_head obslist;
} CoapObserver;
typedef struct
{
NetworkAddr remote;
unsigned char token[COAP_MSG_MAX_TOKEN_LEN];
unsigned char tokenlen;
CoAPSendMsgHandler callback;
unsigned int max_age;
struct list_head obslist;
void *userdata;
} CoAPObservable;
int CoAPObsServer_init(CoAPContext *context, unsigned char obs_maxcount);
int CoAPObsServer_deinit(CoAPContext *context);
int CoAPObsServer_add(CoAPContext *context, const char *path, NetworkAddr *remote, CoAPMessage *request);
int CoapObsServer_delete(CoAPContext *context, NetworkAddr *remote,
CoAPResource *resource);
int CoapObsServerAll_delete(CoAPContext *context, NetworkAddr *remote);
int CoAPObsServer_notify(CoAPContext *context,
const char *path, unsigned char *payload,
unsigned short payloadlen, CoAPDataEncrypt handler);
int CoAPObsClient_init(CoAPContext *context, unsigned char obs_maxcount);
int CoAPObsClient_deinit(CoAPContext *context);
int CoAPObsClient_add(CoAPContext *context, CoAPMessage *message, NetworkAddr *remote, CoAPSendNode *sendnode);
int CoAPObsClient_delete(CoAPContext *context, CoAPMessage *message);
#ifdef __cplusplus
}
#endif /* __cplusplus */
#endif

View File

@@ -0,0 +1,105 @@
/*
* Copyright (C) 2015-2018 Alibaba Group Holding Limited
*/
#include <stdio.h>
#include <ctype.h>
unsigned int platform_aton(const char *ip_str)
{
int c;
unsigned char base;
unsigned int val = 0;
unsigned int parts[4] = {0};
unsigned int *pp = parts;
c = *ip_str;
for (;;) {
/*
* Collect number up to ``.''.
* Values are specified as for C:
* 0x=hex, 0=octal, 1-9=decimal.
*/
if (!isdigit(c))
return (0);
val = 0;
base = 10;
if (c == '0') {
c = *++ip_str;
if (c == 'x' || c == 'X') {
base = 16;
c = *++ip_str;
} else {
base = 8;
}
}
for (;;) {
if (isdigit(c)) {
val = (val * base) + (int)(c - '0');
c = *++ip_str;
} else if (base == 16 && isxdigit(c)) {
val = (val << 4) | (int)(c + 10 - (islower(c) ? 'a' : 'A'));
c = *++ip_str;
} else {
break;
}
}
if (c == '.') {
/*
* Internet format:
* a.b.c.d
* a.b.c (with c treated as 16 bits)
* a.b (with b treated as 24 bits)
*/
if (pp >= parts + 3)
return (0);
*pp++ = val;
c = *++ip_str;
} else {
break;
}
}
/*
* Check for trailing characters.
*/
if (c != '\0' && !isspace(c))
return (0);
/*
* Concoct the address according to
* the number of parts specified.
*/
switch (pp - parts + 1) {
case 0:
return (0); /* initial nondigit */
case 1: /* a -- 32 bits */
break;
case 2: /* a.b -- 8.24 bits */
if (val > 0xffffffUL)
return (0);
val |= parts[0] << 24;
break;
case 3: /* a.b.c -- 8.8.16 bits */
if (val > 0xffff)
return (0);
val |= (parts[0] << 24) | (parts[1] << 16);
break;
case 4: /* a.b.c.d -- 8.8.8.8 bits */
if (val > 0xff)
return (0);
val |= (parts[0] << 24) | (parts[1] << 16) | (parts[2] << 8);
break;
default:
break;
}
return val;
}
int platform_is_multicast(const char *ip_str)
{
unsigned int addr_in;
addr_in = platform_aton(ip_str);
return (addr_in > 0xE00000FF && addr_in <= 0xEFFFFFFF);
}

View File

@@ -0,0 +1,224 @@
/*
* Copyright (C) 2015-2018 Alibaba Group Holding Limited
*/
#include <string.h>
#include "CoAPExport.h"
#include "CoAPResource.h"
#include "CoAPPlatform.h"
#include "CoAPInternal.h"
#include "iotx_coap_internal.h"
#define COAP_PATH_DEFAULT_SUM_LEN (5)
int CoAPPathMD5_sum(const char *path, int len, char outbuf[], int outlen)
{
unsigned char md5[16] = {0};
if (!path || !len || !outbuf || !outlen) {
return -1;
}
utils_md5((unsigned char *)path, (size_t)len, md5);
memcpy(outbuf, md5, outlen > 16 ? 16 : outlen);
return 0;
}
int CoAPResource_init(CoAPContext *context, int res_maxcount)
{
CoAPIntContext *ctx = (CoAPIntContext *)context;
ctx->resource.list_mutex = HAL_MutexCreate();
HAL_MutexLock(ctx->resource.list_mutex);
INIT_LIST_HEAD(&ctx->resource.list);
ctx->resource.count = 0;
ctx->resource.maxcount = res_maxcount;
HAL_MutexUnlock(ctx->resource.list_mutex);
return COAP_SUCCESS;
}
int CoAPResource_deinit(CoAPContext *context)
{
CoAPResource *node = NULL, *next = NULL;
CoAPIntContext *ctx = (CoAPIntContext *)context;
char tmpbuf[2 * COAP_MAX_PATH_CHECKSUM_LEN + 1] = {0};
HAL_MutexLock(ctx->resource.list_mutex);
list_for_each_entry_safe(node, next, &ctx->resource.list, reslist, CoAPResource) {
if (node->path_type == PATH_FILTER && node->filter_path) {
coap_free(node->filter_path);
}
list_del_init(&node->reslist);
infra_hex2str((unsigned char *)node->path, COAP_MAX_PATH_CHECKSUM_LEN, tmpbuf);
COAP_DEBUG("Release the resource %s", tmpbuf);
coap_free(node);
}
ctx->resource.count = 0;
ctx->resource.maxcount = 0;
HAL_MutexUnlock(ctx->resource.list_mutex);
HAL_MutexDestroy(ctx->resource.list_mutex);
ctx->resource.list_mutex = NULL;
return COAP_SUCCESS;
}
CoAPResource *CoAPResource_create(const char *path, path_type_t path_type, unsigned short permission,
unsigned int ctype, unsigned int maxage,
CoAPRecvMsgHandler callback)
{
CoAPResource *resource = NULL;
if (NULL == path) {
return NULL;
}
if (strlen(path) >= COAP_MSG_MAX_PATH_LEN) {
return NULL;
}
resource = coap_malloc(sizeof(CoAPResource));
if (NULL == resource) {
return NULL;
}
memset(resource, 0x00, sizeof(CoAPResource));
if (path_type == PATH_NORMAL) {
resource->path_type = PATH_NORMAL;
CoAPPathMD5_sum(path, strlen(path), resource->path, COAP_PATH_DEFAULT_SUM_LEN);
} else {
int len = strlen(path) + 1;
resource->filter_path = coap_malloc(len);
if (NULL == resource->filter_path) {
coap_free(resource);
return NULL;
}
resource->path_type = PATH_FILTER;
memset(resource->filter_path, 0, len);
strncpy(resource->filter_path, path, strlen(path));
}
resource->callback = callback;
resource->ctype = ctype;
resource->maxage = maxage;
resource->permission = permission;
return resource;
}
int CoAPResource_register(CoAPContext *context, const char *path,
unsigned short permission, unsigned int ctype,
unsigned int maxage, CoAPRecvMsgHandler callback)
{
int exist = 0;
char path_calc[COAP_PATH_DEFAULT_SUM_LEN] = {0};
CoAPResource *node = NULL, *newnode = NULL;
CoAPIntContext *ctx = (CoAPIntContext *)context;
path_type_t type = PATH_NORMAL;
if (context == NULL) {
return FAIL_RETURN;
}
HAL_MutexLock(ctx->resource.list_mutex);
if (ctx->resource.count >= ctx->resource.maxcount) {
HAL_MutexUnlock(ctx->resource.list_mutex);
COAP_INFO("The resource count exceeds limit, cur %d, max %d",
ctx->resource.count, ctx->resource.maxcount);
return COAP_ERROR_DATA_SIZE;
}
if (strstr(path, "/#") != NULL) {
type = PATH_FILTER;
} else {
CoAPPathMD5_sum(path, strlen(path), path_calc, COAP_PATH_DEFAULT_SUM_LEN);
}
list_for_each_entry(node, &ctx->resource.list, reslist, CoAPResource) {
if (type == PATH_NORMAL && node->path_type == PATH_NORMAL) {
if (0 == memcmp(path_calc, node->path, COAP_PATH_DEFAULT_SUM_LEN)) {
/*Alread exist, re-write it*/
COAP_INFO("CoAPResource_register:Alread exist");
exist = 1;
node->callback = callback;
node->ctype = ctype;
node->maxage = maxage;
node->permission = permission;
COAP_INFO("The resource %s already exist, re-write it", path);
break;
}
} else if (type == PATH_FILTER && node->path_type == PATH_FILTER) {
if (strlen(path) == strlen(node->filter_path) && 0 == strncpy((char *)path, node->filter_path, strlen(path))) {
/*Alread exist, re-write it*/
COAP_INFO("CoAPResource_register:Alread exist");
exist = 1;
node->callback = callback;
node->ctype = ctype;
node->maxage = maxage;
node->permission = permission;
COAP_INFO("The resource %s already exist, re-write it", path);
break;
}
}
}
if (0 == exist) {
newnode = CoAPResource_create(path, type, permission, ctype, maxage, callback);
if (NULL != newnode) {
COAP_DEBUG("CoAPResource_register, context:%p, new node", ctx);
list_add_tail(&newnode->reslist, &ctx->resource.list);
ctx->resource.count++;
COAP_DEBUG("Register new resource %s success, count: %d", path, ctx->resource.count);
} else {
COAP_ERR("New resource create failed");
}
}
HAL_MutexUnlock(ctx->resource.list_mutex);
return COAP_SUCCESS;
}
int CoAPResource_unregister(CoAPContext *context, const char *path)
{
COAP_DEBUG("This feature isn't supported");
return COAP_ERROR_UNSUPPORTED;
}
CoAPResource *CoAPResourceByPath_get(CoAPContext *context, const char *path)
{
char path_calc[COAP_PATH_DEFAULT_SUM_LEN] = {0};
CoAPResource *node = NULL;
CoAPIntContext *ctx = (CoAPIntContext *)context;
if (NULL == context || NULL == path) {
COAP_INFO("%s\n", "NULL == context || NULL == path");
return NULL;
}
COAP_FLOW("CoAPResourceByPath_get, context:%p\n", ctx);
CoAPPathMD5_sum(path, strlen(path), path_calc, COAP_PATH_DEFAULT_SUM_LEN);
HAL_MutexLock(ctx->resource.list_mutex);
list_for_each_entry(node, &ctx->resource.list, reslist, CoAPResource) {
if (0 == memcmp(path_calc, node->path, COAP_PATH_DEFAULT_SUM_LEN)) {
HAL_MutexUnlock(ctx->resource.list_mutex);
COAP_DEBUG("Found the resource: %s", path);
return node;
}
if (node->path_type == PATH_FILTER && strlen(node->filter_path) > 0
&& 0 == strncmp(path, node->filter_path, strlen(node->filter_path) - 1)) {
HAL_MutexUnlock(ctx->resource.list_mutex);
COAP_DEBUG("Found the resource: %s", path);
return node;
}
}
HAL_MutexUnlock(ctx->resource.list_mutex);
return NULL;
}

View File

@@ -0,0 +1,48 @@
/*
* Copyright (C) 2015-2018 Alibaba Group Holding Limited
*/
#ifndef __COAP_RESOURCE_H__
#define __COAP_RESOURCE_H__
#include <stdint.h>
#include "iotx_coap_internal.h"
#include "CoAPExport.h"
#ifdef __cplusplus
extern "C" {
#endif /* __cplusplus */
#define COAP_MAX_PATH_CHECKSUM_LEN (5)
typedef struct {
unsigned short permission;
CoAPRecvMsgHandler callback;
unsigned int ctype;
unsigned int maxage;
struct list_head reslist;
char path[COAP_MAX_PATH_CHECKSUM_LEN];
char *filter_path;
path_type_t path_type;
} CoAPResource;
int CoAPResource_init(CoAPContext *context, int res_maxcount);
int CoAPPathMD5_sum(const char *path, int len, char outbuf[], int outlen);
int CoAPResource_register(CoAPContext *context, const char *path,
unsigned short permission, unsigned int ctype,
unsigned int maxage, CoAPRecvMsgHandler callback);
CoAPResource *CoAPResourceByPath_get(CoAPContext *context, const char *path);
int CoAPResource_deinit(CoAPContext *context);
#ifdef __cplusplus
}
#endif /* __cplusplus */
#endif

View File

@@ -0,0 +1,284 @@
/*
* Copyright (C) 2015-2018 Alibaba Group Holding Limited
*/
#include <string.h>
#include "CoAPPlatform.h"
#include "CoAPExport.h"
#include "CoAPServer.h"
#define COAP_INIT_TOKEN (0x01020304)
static unsigned int g_coap_running = 0;
#ifdef COAP_SERV_MULTITHREAD
static void *g_coap_thread = NULL;
static void *g_semphore = NULL;
#endif
static CoAPContext *g_context = NULL;
static unsigned int CoAPServerToken_get(unsigned char *p_encoded_data)
{
static unsigned int value = COAP_INIT_TOKEN;
p_encoded_data[0] = (unsigned char)((value & 0x00FF) >> 0);
p_encoded_data[1] = (unsigned char)((value & 0xFF00) >> 8);
p_encoded_data[2] = (unsigned char)((value & 0xFF0000) >> 16);
p_encoded_data[3] = (unsigned char)((value & 0xFF000000) >> 24);
value++;
return sizeof(unsigned int);
}
static int CoAPServerPath_2_option(char *uri, CoAPMessage *message)
{
char *ptr = NULL;
char *pstr = NULL;
char path[COAP_MSG_MAX_PATH_LEN] = {0};
if (NULL == uri || NULL == message) {
COAP_ERR("Invalid paramter p_path %p, p_message %p", uri, message);
return COAP_ERROR_INVALID_PARAM;
}
if (COAP_MSG_MAX_PATH_LEN <= strlen(uri)) {
COAP_ERR("The uri length is too loog,len = %d", (int)strlen(uri));
return COAP_ERROR_INVALID_LENGTH;
}
COAP_DEBUG("The uri is %s", uri);
ptr = pstr = uri;
while ('\0' != *ptr) {
if ('/' == *ptr) {
if (ptr != pstr) {
memset(path, 0x00, sizeof(path));
strncpy(path, pstr, ptr - pstr);
CoAPStrOption_add(message, COAP_OPTION_URI_PATH,
(unsigned char *)path, (int)strlen(path));
}
pstr = ptr + 1;
}
if ('\0' == *(ptr + 1) && '\0' != *pstr) {
memset(path, 0x00, sizeof(path));
strncpy(path, pstr, sizeof(path) - 1);
CoAPStrOption_add(message, COAP_OPTION_URI_PATH,
(unsigned char *)path, (int)strlen(path));
}
ptr ++;
}
return COAP_SUCCESS;
}
void CoAPServer_thread_leave()
{
g_coap_running = 0;
}
void *coap_yield_mutex = NULL;
static void *CoAPServer_yield(void *param)
{
CoAPContext *context = (CoAPContext *)param;
COAP_DEBUG("Enter to CoAP daemon task");
while (g_coap_running) {
CoAPMessage_cycle(context);
}
#ifdef COAP_SERV_MULTITHREAD
HAL_SemaphorePost(g_semphore);
COAP_INFO("Exit the CoAP daemon task, Post semphore");
HAL_ThreadDelete(NULL);
g_coap_thread = NULL;
#endif
return NULL;
}
typedef void (*func_v_v)(void *);
static func_v_v coapserver_timer = NULL;
void CoAPServer_add_timer(void (*on_timer)(void *))
{
coapserver_timer = on_timer;
}
CoAPContext *CoAPServer_init()
{
CoAPInitParam param = {0};
#ifdef COAP_SERV_MULTITHREAD
int stack_used;
hal_os_thread_param_t task_parms = {0};
#endif
if (NULL == g_context) {
param.appdata = NULL;
param.group = "224.0.1.187";
param.notifier = NULL;
param.obs_maxcount = 16;
param.res_maxcount = 255;
param.port = 5683;
param.send_maxcount = 16;
param.waittime = 50;
#ifdef COAP_SERV_MULTITHREAD
g_semphore = HAL_SemaphoreCreate();
if (NULL == g_semphore) {
COAP_ERR("Semaphore Create failed");
return NULL;
}
coap_yield_mutex = HAL_MutexCreate();
if (NULL == coap_yield_mutex) {
COAP_ERR("coap_yield_mutex Create failed");
HAL_SemaphoreDestroy(g_semphore);
g_semphore = NULL;
return NULL;
}
#endif
g_context = CoAPContext_create(&param);
if (NULL == g_context) {
#ifdef COAP_SERV_MULTITHREAD
HAL_SemaphoreDestroy(g_semphore);
HAL_MutexDestroy(coap_yield_mutex);
g_semphore = NULL;
coap_yield_mutex = NULL;
#endif
COAP_ERR("CoAP Context Create failed");
return NULL;
}
#ifdef COAP_SERV_MULTITHREAD
g_coap_running = 1;
task_parms.stack_size = 4608;
task_parms.name = "CoAPServer_yield";
HAL_ThreadCreate(&g_coap_thread, CoAPServer_yield, (void *)g_context, &task_parms, &stack_used);
#endif
} else {
COAP_INFO("The CoAP Server already init");
}
return (CoAPContext *)g_context;
}
void CoAPServer_deinit(CoAPContext *context)
{
if (context != g_context) {
COAP_INFO("Invalid CoAP Server context");
return;
}
COAP_INFO("CoAP Server deinit");
g_coap_running = 0;
#ifdef COAP_SERV_MULTITHREAD
if (NULL != g_semphore) {
HAL_SemaphoreWait(g_semphore, PLATFORM_WAIT_INFINITE);
COAP_INFO("Wait Semaphore, will exit task");
HAL_SemaphoreDestroy(g_semphore);
g_semphore = NULL;
}
if (NULL != coap_yield_mutex) {
HAL_MutexDestroy(coap_yield_mutex);
coap_yield_mutex = NULL;
}
#endif
if (NULL != context) {
CoAPContext_free(context);
g_context = NULL;
}
}
int CoAPServer_register(CoAPContext *context, const char *uri, CoAPRecvMsgHandler callback)
{
if (NULL == context || g_context != context) {
return COAP_ERROR_INVALID_PARAM;
}
return CoAPResource_register(context, uri, COAP_PERM_GET, COAP_CT_APP_JSON, 60, callback);
}
int CoAPServerMultiCast_send(CoAPContext *context, NetworkAddr *remote, const char *uri, unsigned char *buff,
unsigned short len, CoAPSendMsgHandler callback, unsigned short *msgid)
{
int ret = COAP_SUCCESS;
CoAPMessage message;
unsigned char tokenlen;
unsigned char token[COAP_MSG_MAX_TOKEN_LEN] = {0};
if (NULL == context || g_context != context || NULL == remote
|| NULL == uri || NULL == buff || NULL == msgid) {
return COAP_ERROR_INVALID_PARAM;
}
CoAPMessage_init(&message);
CoAPMessageType_set(&message, COAP_MESSAGE_TYPE_NON);
CoAPMessageCode_set(&message, COAP_MSG_CODE_POST);
CoAPMessageId_set(&message, CoAPMessageId_gen(context));
tokenlen = CoAPServerToken_get(token);
CoAPMessageToken_set(&message, token, tokenlen);
CoAPMessageHandler_set(&message, callback);
CoAPMessageKeep_Set(&message, 1);
CoAPServerPath_2_option((char *)uri, &message);
CoAPUintOption_add(&message, COAP_OPTION_CONTENT_FORMAT, COAP_CT_APP_JSON);
CoAPMessagePayload_set(&message, buff, len);
if (msgid) *msgid = message.header.msgid;
ret = CoAPMessage_send(context, remote, &message);
CoAPMessage_destory(&message);
return ret;
}
int CoAPServerResp_send(CoAPContext *context, NetworkAddr *remote, unsigned char *buff, unsigned short len, void *req,
const char *paths, CoAPSendMsgHandler callback, unsigned short *msgid, char qos)
{
int ret = COAP_SUCCESS;
CoAPMessage response;
unsigned int observe = 0;
CoAPMessage *request = (CoAPMessage *)req;
if (NULL == context || g_context != context || NULL == remote
|| NULL == buff || NULL == paths || NULL == req) {
return COAP_ERROR_INVALID_PARAM;
}
CoAPMessage_init(&response);
CoAPMessageType_set(&response, qos == 0 ? COAP_MESSAGE_TYPE_NON :COAP_MESSAGE_TYPE_CON);
CoAPMessageCode_set(&response, COAP_MSG_CODE_205_CONTENT);
CoAPMessageId_set(&response, request->header.msgid);
CoAPMessageToken_set(&response, request->token, request->header.tokenlen);
CoAPMessageHandler_set(&response, callback);
if (msgid) *msgid = response.header.msgid;
ret = CoAPUintOption_get(request, COAP_OPTION_OBSERVE, &observe);
if (COAP_SUCCESS == ret && 0 == observe) {
CoAPObsServer_add(context, paths, remote, request);
CoAPUintOption_add(&response, COAP_OPTION_OBSERVE, 0);
}
CoAPUintOption_add(&response, COAP_OPTION_CONTENT_FORMAT, COAP_CT_APP_JSON);
CoAPMessagePayload_set(&response, buff, len);
COAP_DEBUG("Send a response message");
ret = CoAPMessage_send(context, remote, &response);
CoAPMessage_destory(&response);
return ret;
}
void CoAPServer_loop(CoAPContext *context)
{
if (g_context != context || 1 == g_coap_running) {
COAP_INFO("The CoAP Server is already running");
return;
}
#ifndef COAP_SERV_MULTITHREAD
g_coap_running = 1;
CoAPServer_yield((void *)context);
#endif
}

View File

@@ -0,0 +1,35 @@
/*
* Copyright (C) 2015-2018 Alibaba Group Holding Limited
*/
#ifndef __COAP_SERVER_H__
#define __COAP_SERVER_H__
#include "CoAPExport.h"
#ifdef __cplusplus
extern "C" {
#endif /* __cplusplus */
#define COAP_SERV_MULTITHREAD
CoAPContext *CoAPServer_init();
void CoAPServer_add_timer (void (*on_timer)(void*));
void CoAPServer_loop(CoAPContext *context);
void CoAPServer_deinit(CoAPContext *context);
int CoAPServer_register(CoAPContext *context, const char *uri, CoAPRecvMsgHandler callback);
int CoAPServerMultiCast_send(CoAPContext *context, NetworkAddr *remote, const char *uri,
unsigned char *buff, unsigned short len, CoAPSendMsgHandler callback, unsigned short *msgid);
int CoAPServerResp_send(CoAPContext *context, NetworkAddr *remote, unsigned char *buff, unsigned short len, void *req,
const char *paths, CoAPSendMsgHandler callback, unsigned short *msgid, char qos);
void CoAPServer_thread_leave();
#ifdef __cplusplus
}
#endif /* __cplusplus */
#endif