support aliyun sdk on TencentOS tiny

sample: examples\aliyun_iotkit_csdk_mqtt
project: board\TencentOS_tiny_EVB_MX_Plus\KEIL\aliyun_iotkit_csdk_mqtt
This commit is contained in:
dcxajichu
2019-10-31 16:36:28 +08:00
parent 30ea36a7ab
commit 8c24d921b0
692 changed files with 199829 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,71 @@
/*
* Copyright (C) 2015-2018 Alibaba Group Holding Limited
*/
#include "Cloud_CoAPNetwork.h"
#include "iotx_coap_internal.h"
#ifndef CLOUD__COAP_EXPORT_H__
#define CLOUD__COAP_EXPORT_H__
/* #define COAP_DTLS_SUPPORT */
typedef CoAPMsgOption Cloud_CoAPMsgOption;
typedef CoAPMessageCode Cloud_CoAPMessageCode;
typedef CoAPMessage Cloud_CoAPMessage ;
#define COAP_OPTION_SEQ 2089
typedef void (*Cloud_CoAPRespMsgHandler)(void *data, void *message);
typedef struct {
void *user;
unsigned short msgid;
char acked;
unsigned char tokenlen;
unsigned char token[8];
unsigned char retrans_count;
unsigned short timeout;
unsigned short timeout_val;
unsigned char *message;
unsigned int msglen;
Cloud_CoAPRespMsgHandler resp;
struct list_head sendlist;
} Cloud_CoAPSendNode;
typedef struct {
unsigned char count;
unsigned char maxcount;
struct list_head sendlist;
} Cloud_CoAPSendList;
typedef void (*Cloud_CoAPEventNotifier)(unsigned int event, void *p_message);
typedef struct {
char *url;
unsigned char maxcount; /*list maximal count*/
unsigned int waittime;
Cloud_CoAPEventNotifier notifier;
} Cloud_CoAPInitParam;
typedef struct {
unsigned short message_id;
coap_network_t network;
Cloud_CoAPEventNotifier notifier;
unsigned char *sendbuf;
unsigned char *recvbuf;
Cloud_CoAPSendList list;
unsigned int waittime;
} Cloud_CoAPContext;
#define COAP_TRC(...) log_debug("coap_cloud", __VA_ARGS__)
#define COAP_DUMP(...) log_debug("coap_cloud", __VA_ARGS__)
#define COAP_DEBUG(...) log_debug("coap_cloud", __VA_ARGS__)
#define COAP_INFO(...) log_info("coap_cloud", __VA_ARGS__)
#define COAP_WRN(...) log_warning("coap_cloud", __VA_ARGS__)
#define COAP_ERR(...) log_err("coap_cloud", __VA_ARGS__)
Cloud_CoAPContext *Cloud_CoAPContext_create(Cloud_CoAPInitParam *param);
void Cloud_CoAPContext_free(Cloud_CoAPContext *p_ctx);
#endif

View File

@@ -0,0 +1,50 @@
/*
* Copyright (C) 2015-2018 Alibaba Group Holding Limited
*/
#include "Cloud_CoAPExport.h"
#ifndef __COAP_HANDLE_MSG_H__
#define __COAP_HANDLE_MSG_H__
int Cloud_CoAPStrOption_add(Cloud_CoAPMessage *message, unsigned short optnum,
unsigned char *data, unsigned short datalen);
int Cloud_CoAPUintOption_add(Cloud_CoAPMessage *message, unsigned short optnum,
unsigned int data);
unsigned short Cloud_CoAPMessageId_gen(Cloud_CoAPContext *context);
int Cloud_CoAPMessageId_set(Cloud_CoAPMessage *message, unsigned short msgid);
int Cloud_CoAPMessageType_set(Cloud_CoAPMessage *message, unsigned char type);
int Cloud_CoAPMessageCode_set(Cloud_CoAPMessage *message, Cloud_CoAPMessageCode code);
int Cloud_CoAPMessageToken_set(Cloud_CoAPMessage *message, unsigned char *token,
unsigned char tokenlen);
int Cloud_CoAPMessageUserData_set(Cloud_CoAPMessage *message, void *userdata);
int Cloud_CoAPMessagePayload_set(Cloud_CoAPMessage *message, unsigned char *payload,
unsigned short payloadlen);
int Cloud_CoAPMessageHandler_set(Cloud_CoAPMessage *message, Cloud_CoAPRespMsgHandler handler);
int Cloud_CoAPMessage_init(Cloud_CoAPMessage *message);
int Cloud_CoAPMessage_destory(Cloud_CoAPMessage *message);
int Cloud_CoAPMessage_send(Cloud_CoAPContext *context, Cloud_CoAPMessage *message);
int Cloud_CoAPMessage_recv(Cloud_CoAPContext *context, unsigned int timeout, int readcount);
int Cloud_CoAPMessage_cycle(Cloud_CoAPContext *context);
#endif

View File

@@ -0,0 +1,51 @@
/*
* Copyright (C) 2015-2018 Alibaba Group Holding Limited
*/
#include <stdint.h>
#ifndef COAP_TRANSPORT_H__
#define COAP_TRANSPORT_H__
typedef enum {
COAP_ENDPOINT_NOSEC = 0,
COAP_ENDPOINT_DTLS,
COAP_ENDPOINT_PSK,
} coap_endpoint_type;
typedef struct {
DTLSContext *context;
} coap_remote_session_t;
typedef struct {
int socket_id;
coap_endpoint_type ep_type;
void *context;
} coap_network_t;
typedef struct {
coap_endpoint_type ep_type;
unsigned char *p_ca_cert_pem;
char *p_host;
unsigned short port;
} coap_network_init_t;
unsigned int Cloud_CoAPNetwork_init(const coap_network_init_t *p_param, coap_network_t *p_network);
unsigned int Cloud_CoAPNetwork_write(coap_network_t *p_network,
const unsigned char *p_data,
unsigned int datalen);
int Cloud_CoAPNetwork_read(coap_network_t *network, unsigned char *data,
unsigned int datalen, unsigned int timeout);
unsigned int Cloud_CoAPNetwork_deinit(coap_network_t *p_network);
#endif

View File

@@ -0,0 +1,26 @@
/*
* Copyright (C) 2015-2018 Alibaba Group Holding Limited
*/
#ifndef __COAP_PLATFORM_OS_H__
#define __COAP_PLATFORM_OS_H__
#include <stdio.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.cloud")
#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 __cplusplus
}
#endif /* __cplusplus */
#endif

View File

@@ -0,0 +1,250 @@
/*
* Copyright (C) 2015-2018 Alibaba Group Holding Limited
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "iotx_coap_internal.h"
#include "ctype.h"
#include "Cloud_CoAPPlatform.h"
#include "Cloud_CoAPNetwork.h"
#include "Cloud_CoAPExport.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_SCHEME "coap" /* the default scheme for CoAP URIs */
#define COAP_DEFAULT_HOST_LEN 128
#define COAP_DEFAULT_WAIT_TIME_MS 2000
unsigned int Cloud_CoAPUri_parse(char *p_uri, coap_endpoint_type *p_endpoint_type,
char host[COAP_DEFAULT_HOST_LEN], unsigned short *port)
{
int len = 0;
char *p = NULL, *q = NULL;
if (NULL == p_uri || NULL == p_endpoint_type) {
return COAP_ERROR_INVALID_PARAM;
}
COAP_DEBUG("The uri is %s", p_uri);
len = strlen(p_uri);
p = p_uri;
q = (char *)COAP_DEFAULT_SCHEME;
while (len && *q && tolower(*p) == *q) {
++p;
++q;
--len;
}
if (*q) {
return COAP_ERROR_INVALID_URI;
}
if (tolower(*p) == 's') {
++p;
--len;
*p_endpoint_type = COAP_ENDPOINT_DTLS;
*port = COAPS_DEFAULT_PORT;
} else if (*p == '-') {
++p;
--len;
q = (char *)"psk";
while (len && *q && tolower(*p) == *q) {
++p;
++q;
--len;
}
if (*q) {
return COAP_ERROR_INVALID_URI;
}
*p_endpoint_type = COAP_ENDPOINT_PSK;
*port = COAP_DEFAULT_PORT;
} else {
*p_endpoint_type = COAP_ENDPOINT_NOSEC;
*port = COAP_DEFAULT_PORT;
}
COAP_DEBUG("The endpoint type is: %d", *p_endpoint_type);
q = (char *)"://";
while (len && *q && tolower(*p) == *q) {
++p;
++q;
--len;
}
if (*q) {
return COAP_ERROR_INVALID_URI;
}
q = p;
while (len && *q != ':') {
++q;
--len;
}
if (p == q) {
return COAP_ERROR_INVALID_URI;
}
if (COAP_DEFAULT_HOST_LEN - 1 < (q - p)) {
return COAP_ERROR_INVALID_URI;
} else {
memset(host, 0x00, COAP_DEFAULT_HOST_LEN);
strncpy(host, p, q - p);
}
COAP_DEBUG("The host name is: %s", host);
if (len && *q == ':') {
p = ++q;
--len;
while (len && isdigit(*q)) {
++q;
--len;
}
if (p < q) {
int uri_port = 0;
while (p < q) {
uri_port = uri_port * 10 + (*p++ - '0');
}
if (uri_port > 65535) {
return COAP_ERROR_INVALID_URI;
}
*port = uri_port;
}
}
COAP_DEBUG("The port is: %d", *port);
return COAP_SUCCESS;
}
Cloud_CoAPContext *Cloud_CoAPContext_create(Cloud_CoAPInitParam *param)
{
unsigned int ret = COAP_SUCCESS;
Cloud_CoAPContext *p_ctx = NULL;
coap_network_init_t network_param;
char host[COAP_DEFAULT_HOST_LEN] = {0};
memset(&network_param, 0x00, sizeof(coap_network_init_t));
p_ctx = coap_malloc(sizeof(Cloud_CoAPContext));
if (NULL == p_ctx) {
COAP_ERR("malloc for coap context failed");
goto err;
}
memset(p_ctx, 0, sizeof(Cloud_CoAPContext));
p_ctx->message_id = 1;
p_ctx->notifier = param->notifier;
p_ctx->sendbuf = coap_malloc(COAP_MSG_MAX_PDU_LEN);
if (NULL == p_ctx->sendbuf) {
COAP_ERR("not enough memory");
goto err;
}
p_ctx->recvbuf = coap_malloc(COAP_MSG_MAX_PDU_LEN);
if (NULL == p_ctx->recvbuf) {
COAP_ERR("not enough memory");
goto err;
}
if (0 == param->waittime) {
p_ctx->waittime = COAP_DEFAULT_WAIT_TIME_MS;
} else {
p_ctx->waittime = param->waittime;
}
/*CoAP message send list*/
INIT_LIST_HEAD(&p_ctx->list.sendlist);
p_ctx->list.count = 0;
p_ctx->list.maxcount = param->maxcount;
/*set the endpoint type by uri schema*/
if (NULL != param->url) {
ret = Cloud_CoAPUri_parse(param->url, &network_param.ep_type, host, &network_param.port);
}
if (COAP_SUCCESS != ret) {
goto err;
}
#ifdef COAP_DTLS_SUPPORT
if (COAP_ENDPOINT_DTLS == network_param.ep_type) {
extern const char *iotx_ca_crt;
network_param.p_ca_cert_pem = (unsigned char *)iotx_ca_crt;
}
#endif
if (COAP_ENDPOINT_NOSEC == network_param.ep_type
|| COAP_ENDPOINT_PSK == network_param.ep_type) {
network_param.p_ca_cert_pem = NULL;
}
network_param.p_host = host;
/*CoAP network init*/
ret = Cloud_CoAPNetwork_init(&network_param, &p_ctx->network);
if (COAP_SUCCESS != ret) {
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;
}
if (NULL != p_ctx->sendbuf) {
coap_free(p_ctx->sendbuf);
p_ctx->sendbuf = NULL;
}
coap_free(p_ctx);
p_ctx = NULL;
return p_ctx;
}
void Cloud_CoAPContext_free(Cloud_CoAPContext *p_ctx)
{
Cloud_CoAPSendNode *cur, *next;
if (NULL == p_ctx) {
return;
}
Cloud_CoAPNetwork_deinit(&p_ctx->network);
list_for_each_entry_safe(cur, next, &p_ctx->list.sendlist, sendlist, Cloud_CoAPSendNode) {
if (NULL != cur) {
if (NULL != cur->message) {
coap_free(cur->message);
cur->message = NULL;
}
coap_free(cur);
cur = NULL;
}
}
if (NULL != p_ctx->recvbuf) {
coap_free(p_ctx->recvbuf);
p_ctx->recvbuf = NULL;
}
if (NULL != p_ctx->sendbuf) {
coap_free(p_ctx->sendbuf);
p_ctx->sendbuf = NULL;
}
if (NULL != p_ctx) {
coap_free(p_ctx);
p_ctx = NULL;
}
}

View File

@@ -0,0 +1,312 @@
/*
* Copyright (C) 2015-2018 Alibaba Group Holding Limited
*/
#include "iotx_coap_internal.h"
#include "Cloud_CoAPExport.h"
#include "CoAPSerialize.h"
#include "CoAPDeserialize.h"
#include "Cloud_CoAPPlatform.h"
#define COAPAckMsg(header) \
((header.code == COAP_MSG_CODE_EMPTY_MESSAGE) \
&&(header.type == COAP_MESSAGE_TYPE_ACK))
#define Cloud_CoAPRespMsg(header)\
((header.code >= 0x40) && (header.code < 0xc0))
#define Cloud_CoAPPingMsg(header)\
((header.code == COAP_MSG_CODE_EMPTY_MESSAGE)\
&& (header.type == COAP_MESSAGE_TYPE_CON))
#define Cloud_CoAPRstMsg(header)\
(header.type == COAP_MESSAGE_TYPE_RST)
#define Cloud_CoAPCONRespMsg(header)\
((header.code == COAP_MSG_CODE_205_CONTENT) \
&& (header.type == COAP_MESSAGE_TYPE_CON))
#define Cloud_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
unsigned short Cloud_CoAPMessageId_gen(Cloud_CoAPContext *context)
{
unsigned short msg_id = 0;
msg_id = ((COAP_MAX_MESSAGE_ID == context->message_id) ? 1 : context->message_id++);
return msg_id;
}
int Cloud_CoAPMessageHandler_set(Cloud_CoAPMessage *message, Cloud_CoAPRespMsgHandler resp)
{
if (NULL == message) {
return COAP_ERROR_NULL;
}
message->resp = resp;
return COAP_SUCCESS;
}
static int Cloud_CoAPMessageList_add(Cloud_CoAPContext *context, Cloud_CoAPMessage *message, int len)
{
Cloud_CoAPSendNode *node = NULL;
node = coap_malloc(sizeof(Cloud_CoAPSendNode));
if (NULL != node) {
node->acked = 0;
node->user = message->user;
node->msgid = message->header.msgid;
node->resp = message->resp;
node->msglen = len;
node->timeout_val = COAP_ACK_TIMEOUT * COAP_ACK_RANDOM_FACTOR;
if (COAP_MESSAGE_TYPE_CON == message->header.type) {
node->timeout = node->timeout_val;
node->retrans_count = 0;
} else {
node->timeout = COAP_MAX_TRANSMISSION_SPAN;
node->retrans_count = COAP_MAX_RETRY_COUNT;
}
node->tokenlen = message->header.tokenlen;
memcpy(node->token, message->token, message->header.tokenlen);
node->message = (unsigned char *)coap_malloc(len);
if (NULL != node->message) {
memcpy(node->message, context->sendbuf, len);
}
if (&context->list.count >= &context->list.maxcount) {
coap_free(node);
return -1;
} else {
list_add_tail(&node->sendlist, &context->list.sendlist);
context->list.count ++;
return 0;
}
} else {
return -1;
}
}
int Cloud_CoAPMessage_send(Cloud_CoAPContext *context, Cloud_CoAPMessage *message)
{
unsigned int ret = COAP_SUCCESS;
unsigned short msglen = 0;
if (NULL == message || NULL == context) {
return (COAP_ERROR_INVALID_PARAM);
}
/* TODO: get the message length */
/* msglen = CoAPSerialize_MessageLength(message); */
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;
}
memset(context->sendbuf, 0x00, COAP_MSG_MAX_PDU_LEN);
msglen = CoAPSerialize_Message(message, context->sendbuf, COAP_MSG_MAX_PDU_LEN);
COAP_DEBUG("----The message length %d-----", msglen);
ret = Cloud_CoAPNetwork_write(&context->network, context->sendbuf, (unsigned int)msglen);
if (COAP_SUCCESS == ret) {
if (Cloud_CoAPReqMsg(message->header) || Cloud_CoAPCONRespMsg(message->header)) {
COAP_DEBUG("Add message id %d len %d to the list",
message->header.msgid, msglen);
Cloud_CoAPMessageList_add(context, message, msglen);
} else {
COAP_DEBUG("The message doesn't need to be retransmitted");
}
} else {
COAP_ERR("CoAP transport write failed, return %d", ret);
}
return ret;
}
static int Cloud_CoAPAckMessage_handle(Cloud_CoAPContext *context, Cloud_CoAPMessage *message)
{
Cloud_CoAPSendNode *node = NULL;
list_for_each_entry(node, &context->list.sendlist, sendlist, Cloud_CoAPSendNode) {
if (node->msgid == message->header.msgid) {
node->acked = 1;
return COAP_SUCCESS;
}
}
return COAP_SUCCESS;
}
static int Cloud_CoAPAckMessage_send(Cloud_CoAPContext *context, unsigned short msgid)
{
Cloud_CoAPMessage message;
CoAPMessage_init(&message);
CoAPMessageId_set(&message, msgid);
return Cloud_CoAPMessage_send(context, &message);
}
static int Cloud_CoAPRespMessage_handle(Cloud_CoAPContext *context, Cloud_CoAPMessage *message)
{
Cloud_CoAPSendNode *node = NULL;
if (COAP_MESSAGE_TYPE_CON == message->header.type) {
Cloud_CoAPAckMessage_send(context, message->header.msgid);
}
list_for_each_entry(node, &context->list.sendlist, sendlist, Cloud_CoAPSendNode) {
if (0 != node->tokenlen && node->tokenlen == message->header.tokenlen
&& 0 == memcmp(node->token, message->token, message->header.tokenlen)) {
#ifdef INFRA_LOG_NETWORK_PAYLOAD
COAP_DEBUG("Find the node by token");
COAP_INFO("Downstream Payload:");
iotx_facility_json_print((const char *)message->payload, LOG_INFO_LEVEL, '<');
#endif
message->user = node->user;
if (COAP_MSG_CODE_400_BAD_REQUEST <= message->header.code) {
/* TODO:i */
if (NULL != context->notifier) {
/* context->notifier(message->header.code, message); */
}
}
if (NULL != node->resp) {
node->resp(node->user, message);
}
COAP_DEBUG("Remove the message id %d from list", node->msgid);
list_del_init(&node->sendlist);
context->list.count--;
if (NULL != node->message) {
coap_free(node->message);
}
coap_free(node);
node = NULL;
return COAP_SUCCESS;
}
}
return COAP_ERROR_NOT_FOUND;
}
static void Cloud_CoAPMessage_handle(Cloud_CoAPContext *context,
unsigned char *buf,
unsigned short datalen)
{
int ret = COAP_SUCCESS;
Cloud_CoAPMessage message;
unsigned char code, msgclass, detail;
memset(&message, 0x00, sizeof(Cloud_CoAPMessage));
ret = CoAPDeserialize_Message(&message, buf, datalen);
code = (unsigned char)message.header.code;
msgclass = code >> 5;
detail = code & 0x1F;
COAP_DEBUG("Version : %d", message.header.version);
COAP_DEBUG("Code : %d.%02d(0x%x)", msgclass, detail, code);
COAP_DEBUG("Type : 0x%x", message.header.type);
COAP_DEBUG("Msgid : %d", message.header.msgid);
COAP_DEBUG("Option : %d", message.optcount);
COAP_DEBUG("Payload Len : %d", message.payloadlen);
msgclass = msgclass;
detail = detail;
if (COAP_SUCCESS != ret) {
if (NULL != context->notifier) {
/* TODO: */
/* context->notifier(context, event); */
}
}
if (COAPAckMsg(message.header)) {
COAP_DEBUG("Receive CoAP ACK Message,ID %d", message.header.msgid);
Cloud_CoAPAckMessage_handle(context, &message);
} else if (Cloud_CoAPRespMsg(message.header)) {
COAP_DEBUG("Receive CoAP Response Message,ID %d", message.header.msgid);
Cloud_CoAPRespMessage_handle(context, &message);
}
}
int Cloud_CoAPMessage_recv(Cloud_CoAPContext *context, unsigned int timeout, int readcount)
{
int len = 0;
int count = readcount;
while (1) {
len = Cloud_CoAPNetwork_read(&context->network, context->recvbuf,
COAP_MSG_MAX_PDU_LEN, timeout);
if (len > 0) {
if (0 == readcount) {
Cloud_CoAPMessage_handle(context, context->recvbuf, len);
} else {
count--;
Cloud_CoAPMessage_handle(context, context->recvbuf, len);
if (0 == count) {
return len;
}
}
} else {
return 0;
}
}
}
int Cloud_CoAPMessage_cycle(Cloud_CoAPContext *context)
{
unsigned int ret = 0;
Cloud_CoAPSendNode *node = NULL, *next = NULL;
Cloud_CoAPMessage_recv(context, context->waittime, 0);
list_for_each_entry_safe(node, next, &context->list.sendlist, sendlist, Cloud_CoAPSendNode) {
if (NULL != node) {
if (node->timeout == 0) {
if (node->retrans_count < COAP_MAX_RETRY_COUNT && (0 == node->acked)) {
node->timeout = node->timeout_val * 2;
node->timeout_val = node->timeout;
node->retrans_count++;
COAP_DEBUG("Retansmit the message id %d len %d", node->msgid, node->msglen);
ret = Cloud_CoAPNetwork_write(&context->network, node->message, node->msglen);
if (ret != COAP_SUCCESS) {
if (NULL != context->notifier) {
/* TODO: */
/* context->notifier(context, event); */
}
}
}
if ((node->timeout > COAP_MAX_TRANSMISSION_SPAN) ||
(node->retrans_count >= COAP_MAX_RETRY_COUNT)) {
if (NULL != context->notifier) {
/* TODO: */
/* context->notifier(context, event); */
}
/*Remove the node from the list*/
list_del_init(&node->sendlist);
context->list.count--;
COAP_INFO("Retransmit timeout,remove the message id %d count %d",
node->msgid, context->list.count);
coap_free(node->message);
coap_free(node);
}
} else {
node->timeout--;
}
}
}
return COAP_SUCCESS;
}

View File

@@ -0,0 +1,212 @@
/*
* 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 "Cloud_CoAPExport.h"
#include "Cloud_CoAPNetwork.h"
#ifdef COAP_DTLS_SUPPORT
static void *Cloud_CoAPDTLS_Malloc(uint32_t size)
{
#ifdef INFRA_MEM_STATS
return LITE_malloc(size, MEM_MAGIC, "dtls");
#else
return HAL_Malloc(size);
#endif
}
static void Cloud_CoAPDTLS_Free(void *ptr)
{
#ifdef INFRA_MEM_STATS
LITE_free(ptr);
#else
HAL_Free((void *)ptr);
#endif
}
static void Cloud_CoAPNetworkDTLS_freeSession(void *p_session);
unsigned int Cloud_CoAPNetworkDTLS_read(void *p_session,
unsigned char *p_data,
unsigned int *p_datalen,
unsigned int timeout)
{
unsigned int err_code = DTLS_SUCCESS;
const unsigned int read_len = *p_datalen;
DTLSContext *context = NULL;
COAP_TRC("<< secure_datagram_read, read buffer len %d, timeout %d", read_len, timeout);
(void)read_len;
if (NULL != p_session) {
/* read dtls application data*/
context = (DTLSContext *)p_session;
err_code = HAL_DTLSSession_read(context, p_data, p_datalen, timeout);
if (DTLS_PEER_CLOSE_NOTIFY == err_code
|| DTLS_FATAL_ALERT_MESSAGE == err_code) {
COAP_INFO("dtls session read failed, return (0x%04x)", err_code);
Cloud_CoAPNetworkDTLS_freeSession(context);
}
if (DTLS_SUCCESS == err_code) {
return COAP_SUCCESS;
} else {
return COAP_ERROR_READ_FAILED;
}
}
return COAP_ERROR_INVALID_PARAM;
}
unsigned int Cloud_CoAPNetworkDTLS_write(void *p_session,
const unsigned char *p_data,
unsigned int *p_datalen)
{
unsigned int err_code = DTLS_SUCCESS;
if (NULL != p_session) {
err_code = HAL_DTLSSession_write((DTLSContext *)p_session, p_data, p_datalen);
if (DTLS_SUCCESS == err_code) {
return COAP_SUCCESS;
} else {
return COAP_ERROR_WRITE_FAILED;
}
}
return COAP_ERROR_INVALID_PARAM;
}
static void Cloud_CoAPNetworkDTLS_freeSession(void *p_session)
{
/* Free the session.*/
HAL_DTLSSession_free((DTLSContext *)p_session);
}
void *Cloud_CoAPNetworkDTLS_createSession(char *p_host,
unsigned short port,
unsigned char *p_ca_cert_pem)
{
DTLSContext *context = NULL;
dtls_hooks_t dtls_hooks;
coap_dtls_options_t dtls_options;
memset(&dtls_hooks, 0, sizeof(dtls_hooks_t));
dtls_hooks.malloc = Cloud_CoAPDTLS_Malloc;
dtls_hooks.free = Cloud_CoAPDTLS_Free;
HAL_DTLSHooks_set(&dtls_hooks);
memset(&dtls_options, 0x00, sizeof(coap_dtls_options_t));
dtls_options.p_ca_cert_pem = p_ca_cert_pem;
dtls_options.p_host = p_host;
dtls_options.port = port;
context = HAL_DTLSSession_create(&dtls_options);
return (void *)context;
}
#endif
unsigned int Cloud_CoAPNetwork_write(coap_network_t *p_network,
const unsigned char *p_data,
unsigned int datalen)
{
int rc = COAP_ERROR_WRITE_FAILED;
#ifdef COAP_DTLS_SUPPORT
if (COAP_ENDPOINT_DTLS == p_network->ep_type) {
rc = Cloud_CoAPNetworkDTLS_write(p_network->context, p_data, &datalen);
} else {
#endif
rc = HAL_UDP_write((intptr_t)p_network->context, p_data, datalen);
COAP_DEBUG("[CoAP-NWK]: Network write return %d", rc);
if (-1 == rc) {
rc = COAP_ERROR_WRITE_FAILED;
} else {
rc = COAP_SUCCESS;
}
#ifdef COAP_DTLS_SUPPORT
}
#endif
return (unsigned int)rc;
}
int Cloud_CoAPNetwork_read(coap_network_t *network, unsigned char *data,
unsigned int datalen, unsigned int timeout)
{
int len = 0;
#ifdef COAP_DTLS_SUPPORT
if (COAP_ENDPOINT_DTLS == network->ep_type) {
len = datalen;
memset(data, 0x00, datalen);
Cloud_CoAPNetworkDTLS_read(network->context, data, (unsigned int *)&len, timeout);
} else {
#endif
memset(data, 0x00, datalen);
len = HAL_UDP_readTimeout((intptr_t)network->context,
data, COAP_MSG_MAX_PDU_LEN, timeout);
#ifdef COAP_DTLS_SUPPORT
}
#endif
if (len > 0) {
COAP_TRC("<< CoAP recv %d bytes data", len);
}
return len;
}
unsigned int Cloud_CoAPNetwork_init(const coap_network_init_t *p_param, coap_network_t *p_network)
{
unsigned int err_code = COAP_SUCCESS;
if (NULL == p_param || NULL == p_network) {
return COAP_ERROR_INVALID_PARAM;
}
/* TODO : Parse the url here */
p_network->ep_type = p_param->ep_type;
#ifdef COAP_DTLS_SUPPORT
if (COAP_ENDPOINT_DTLS == p_param->ep_type) {
p_network->context = Cloud_CoAPNetworkDTLS_createSession(p_param->p_host,
p_param->port, p_param->p_ca_cert_pem);
if (NULL == p_network->context) {
return COAP_ERROR_NET_INIT_FAILED;
}
}
#endif
if (COAP_ENDPOINT_NOSEC == p_param->ep_type
|| COAP_ENDPOINT_PSK == p_param->ep_type) {
/*Create udp socket*/
p_network->context = (void *)HAL_UDP_create(p_param->p_host, p_param->port);
if ((void *) - 1 == p_network->context) {
return COAP_ERROR_NET_INIT_FAILED;
}
}
return err_code;
}
unsigned int Cloud_CoAPNetwork_deinit(coap_network_t *p_network)
{
unsigned int err_code = COAP_SUCCESS;
#ifdef COAP_DTLS_SUPPORT
if (COAP_ENDPOINT_DTLS == p_network->ep_type) {
Cloud_CoAPNetworkDTLS_freeSession(p_network->context);
p_network->context = NULL;
}
#endif
if (COAP_ENDPOINT_NOSEC == p_network->ep_type
|| COAP_ENDPOINT_PSK == p_network->ep_type) {
HAL_UDP_close_without_connect((intptr_t)p_network->context);
}
return err_code;
}

View File

@@ -0,0 +1,45 @@
# README.md: coap cloud
## Contents
```shell
.
├── aos.mk
├── Cloud_CoAPDeserialize.h
├── Cloud_CoAPExport.h
├── Cloud_CoAPMessage.h
├── Cloud_CoAPNetwork.h
├── Cloud_CoAPPlatform.h
├── Cloud_CoAPSerialize.h
├── CMakeLists.txt
├── CoAPDeserialize.c
├── CoAPExport.c
├── CoAPMessage.c
├── CoAPNetwork.c
├── CoAPSerialize.c
├── Config.in
├── iot.mk
├── iotx_ca_cert.c
└── iotx_coap_api.c
```
## Introduction
Implementation of coap protocol and special customization for connecting alicloud iot platform
### Features
### Dependencies
- **hal**. osal and hal to shield different os and hardware
- **infra**. Authentication, net and so on tool set.
## API
Please refer to [coap api](https://code.aliyun.com/edward.yangx/public-docs/wikis/user-guide/linkkit/Prog_Guide/API/CoAP_Provides#iot_coap_init) for API details.
## Reference
Please refer to [coap connect](https://code.aliyun.com/edward.yangx/public-docs/wikis/user-guide/linkkit/Prog_Guide/CoAP_Connect) for example details.

View File

@@ -0,0 +1,952 @@
/*
* Copyright (C) 2015-2018 Alibaba Group Holding Limited
*/
#include <stdio.h>
#include "coap_api.h"
#include "iotx_coap_internal.h"
#include "Cloud_CoAPPlatform.h"
#include "Cloud_CoAPPlatform.h"
#include "Cloud_CoAPMessage.h"
#include "Cloud_CoAPExport.h"
#define IOTX_SIGN_LENGTH (40+1)
#define IOTX_SIGN_SOURCE_LEN (256)
#define IOTX_AUTH_TOKEN_LEN (192+1)
#define IOTX_COAP_INIT_TOKEN (0x01020304)
#define IOTX_LIST_MAX_ITEM (10)
#ifndef INFRA_LOG
#undef HEXDUMP_DEBUG
#undef HEXDUMP_INFO
#define HEXDUMP_DEBUG(...)
#define HEXDUMP_INFO(...)
#endif
#define IOTX_AUTH_STR "auth"
#define IOTX_SIGN_SRC_STR "clientId%sdeviceName%sproductKey%s"
#define IOTX_SIGN_SRC_STR_WITH_SEQ "clientId%sdeviceName%sproductKey%sseq%d"
#define IOTX_AUTH_DEVICENAME_STR "{\"productKey\":\"%s\",\"deviceName\":\"%s\",\"clientId\":\"%s\",\"sign\":\"%s\"}"
#define IOTX_AUTH_DEVICENAME_STR_WITH_SEQ "{\"productKey\":\"%s\",\"deviceName\":\"%s\",\"clientId\":\"%s\",\"sign\":\"%s\",\"seq\":\"%d\"}"
#define IOTX_COAP_ONLINE_DTLS_SERVER_URL "coaps://%s.coap.cn-shanghai.link.aliyuncs.com:5684"
#define IOTX_COAP_ONLINE_PSK_SERVER_URL "coap-psk://%s.coap.cn-shanghai.link.aliyuncs.com:5682"
iotx_coap_context_t *g_coap_context = NULL;
typedef struct {
char *p_auth_token;
int auth_token_len;
char is_authed;
iotx_deviceinfo_t *p_devinfo;
Cloud_CoAPContext *p_coap_ctx;
unsigned int coap_token;
unsigned int seq;
unsigned char key[32];
iotx_event_handle_t event_handle;
} iotx_coap_t;
int iotx_calc_sign(const char *p_device_secret, const char *p_client_id,
const char *p_device_name, const char *p_product_key, char sign[IOTX_SIGN_LENGTH])
{
char *p_msg = NULL;
p_msg = (char *)coap_malloc(IOTX_SIGN_SOURCE_LEN);
if (NULL == p_msg) {
return IOTX_ERR_NO_MEM;
}
memset(sign, 0x00, IOTX_SIGN_LENGTH);
memset(p_msg, 0x00, IOTX_SIGN_SOURCE_LEN);
HAL_Snprintf(p_msg, IOTX_SIGN_SOURCE_LEN,
IOTX_SIGN_SRC_STR,
p_client_id,
p_device_name,
p_product_key);
utils_hmac_md5(p_msg, strlen(p_msg), sign, p_device_secret, strlen(p_device_secret));
coap_free(p_msg);
COAP_DEBUG("The device name sign: %s", sign);
return IOTX_SUCCESS;
}
int iotx_calc_sign_with_seq(const char *p_device_secret, const char *p_client_id,
const char *p_device_name, const char *p_product_key, unsigned int seq, char sign[IOTX_SIGN_LENGTH])
{
char *p_msg = NULL;
p_msg = (char *)coap_malloc(IOTX_SIGN_SOURCE_LEN);
if (NULL == p_msg) {
return IOTX_ERR_NO_MEM;
}
memset(sign, 0x00, IOTX_SIGN_LENGTH);
memset(p_msg, 0x00, IOTX_SIGN_SOURCE_LEN);
HAL_Snprintf(p_msg, IOTX_SIGN_SOURCE_LEN,
IOTX_SIGN_SRC_STR_WITH_SEQ,
p_client_id,
p_device_name,
p_product_key, seq);
COAP_DEBUG("The source string: %s", p_msg);
utils_hmac_md5(p_msg, strlen(p_msg), sign, p_device_secret, strlen(p_device_secret));
coap_free(p_msg);
COAP_DEBUG("The device name sign with seq: %s", sign);
return IOTX_SUCCESS;
}
static int iotx_get_token_from_json(char *p_str, char *p_token, int len)
{
char *p_value = NULL;
if (NULL == p_str || NULL == p_token) {
COAP_ERR("Invalid paramter p_str %p, p_token %p", p_str, p_token);
return IOTX_ERR_INVALID_PARAM;
}
p_value = LITE_json_value_of("token", p_str, 0x1234, "coap.cloud");
if (NULL != p_value) {
if (len - 1 < strlen(p_value)) {
return IOTX_ERR_BUFF_TOO_SHORT;
}
memset(p_token, 0x00, len);
strncpy(p_token, p_value, strlen(p_value));
#ifdef INFRA_MEM_STATS
LITE_free(p_value);
#else
HAL_Free((void *)p_value);
#endif
return IOTX_SUCCESS;
}
return IOTX_ERR_AUTH_FAILED;
}
static int iotx_parse_auth_from_json(char *p_str, iotx_coap_t *p_iotx_coap)
{
int ret = -1;
lite_cjson_t root;
lite_cjson_t node;
unsigned char key[32] = {0};
unsigned char buff[128] = {0};
unsigned char random[32 + 1] = {0};
if (NULL == p_str || NULL == p_iotx_coap) {
return IOTX_ERR_INVALID_PARAM;
}
memset(&root, 0x00, sizeof(lite_cjson_t));
memset(&node, 0x00, sizeof(lite_cjson_t));
ret = lite_cjson_parse(p_str, strlen(p_str), &root);
if (-1 == ret) {
return IOTX_ERR_AUTH_FAILED;
}
ret = lite_cjson_object_item(&root, "token", strlen("token"), &node);
if (-1 == ret) {
return IOTX_ERR_AUTH_FAILED;
}
if (p_iotx_coap->auth_token_len - 1 < node.value_length) {
return IOTX_ERR_BUFF_TOO_SHORT;
}
memset(p_iotx_coap->p_auth_token, 0x00, node.value_length);
strncpy(p_iotx_coap->p_auth_token, node.value, node.value_length);
memset(&node, 0x00, sizeof(lite_cjson_t));
ret = lite_cjson_object_item(&root, "seqOffset", strlen("seqOffset"), &node);
if (-1 == ret) {
return IOTX_ERR_AUTH_FAILED;
}
p_iotx_coap->seq = node.value_int;
memset(&node, 0x00, sizeof(lite_cjson_t));
ret = lite_cjson_object_item(&root, "random", strlen("random"), &node);
if (-1 == ret) {
return IOTX_ERR_AUTH_FAILED;
}
if(node.value_length > 32) {
return IOTX_ERR_BUFF_TOO_SHORT;
}
memcpy(random, node.value, node.value_length);
HAL_Snprintf((char *)buff, sizeof(buff), "%s,%s",
p_iotx_coap->p_devinfo->device_secret, random);
COAP_DEBUG("The src:%s", buff);
utils_sha256(buff, strlen((char *)buff), key);
memcpy(p_iotx_coap->key, key + 8, 16);
COAP_DEBUG("The key is:");
HEXDUMP_DEBUG(key, 32);
COAP_DEBUG("The short key:");
HEXDUMP_DEBUG(p_iotx_coap->key, 16);
return IOTX_SUCCESS;
}
static void iotx_device_name_auth_callback(void *user, void *p_message)
{
int ret_code = IOTX_SUCCESS;
iotx_coap_t *p_iotx_coap = NULL;
Cloud_CoAPMessage *message = (Cloud_CoAPMessage *)p_message;
if (NULL == user) {
COAP_ERR("Invalid paramter, p_arg %p", user);
return ;
}
p_iotx_coap = (iotx_coap_t *)user;
if (NULL == message) {
COAP_ERR("Invalid paramter, message %p", message);
return;
}
COAP_DEBUG("Receive response message:");
COAP_DEBUG("* Response Code : 0x%x", message->header.code);
COAP_DEBUG("* Payload: %s", message->payload);
switch (message->header.code) {
case COAP_MSG_CODE_205_CONTENT: {
if (COAP_ENDPOINT_PSK == p_iotx_coap->p_coap_ctx->network.ep_type) {
ret_code = iotx_parse_auth_from_json((char *)message->payload, p_iotx_coap);
} else {
ret_code = iotx_get_token_from_json((char *)message->payload, p_iotx_coap->p_auth_token, p_iotx_coap->auth_token_len);
}
if (IOTX_SUCCESS == ret_code) {
p_iotx_coap->is_authed = IOT_TRUE;
COAP_INFO("CoAP authenticate success!!!");
}
break;
}
case COAP_MSG_CODE_500_INTERNAL_SERVER_ERROR: {
COAP_INFO("CoAP internal server error, authenticate failed, will retry it");
HAL_SleepMs(1000);
IOT_CoAP_DeviceNameAuth((iotx_coap_context_t *)p_iotx_coap);
break;
}
default:
break;
}
}
static unsigned int iotx_get_coap_token(iotx_coap_t *p_iotx_coap, unsigned char *p_encoded_data)
{
unsigned int value = p_iotx_coap->coap_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);
p_iotx_coap->coap_token++;
return sizeof(unsigned int);
}
void iotx_event_notifyer(unsigned int code, Cloud_CoAPMessage *message)
{
if (NULL == message) {
COAP_ERR("Invalid paramter, message %p", message);
return ;
}
COAP_DEBUG("Error code: 0x%x, payload: %s", code, message->payload);
switch (code) {
case COAP_MSG_CODE_402_BAD_OPTION:
case COAP_MSG_CODE_401_UNAUTHORIZED: {
iotx_coap_t *p_context = NULL;
if (NULL != message->user) {
p_context = (iotx_coap_t *)message->user;
p_context->is_authed = IOT_FALSE;
IOT_CoAP_DeviceNameAuth(p_context);
COAP_INFO("IoTx token expired, will reauthenticate");
}
/* TODO: call event handle to notify application */
/* p_context->event_handle(); */
break;
}
default:
break;
}
}
static void iotx_get_well_known_handler(void *arg, void *p_response)
{
int len = 0;
unsigned char *p_payload = NULL;
iotx_coap_resp_code_t resp_code;
IOT_CoAP_GetMessageCode(p_response, &resp_code);
IOT_CoAP_GetMessagePayload(p_response, &p_payload, &len);
COAP_INFO("[APPL]: Message response code: %d", resp_code);
COAP_INFO("[APPL]: Len: %d, Payload: %s, ", len, p_payload);
}
int iotx_get_well_known(iotx_coap_context_t *p_context)
{
int len = 0;
Cloud_CoAPContext *p_coap_ctx = NULL;
iotx_coap_t *p_iotx_coap = NULL;
Cloud_CoAPMessage message;
unsigned char token[8] = {0};
p_iotx_coap = (iotx_coap_t *)p_context;
p_coap_ctx = (Cloud_CoAPContext *)p_iotx_coap->p_coap_ctx;
CoAPMessage_init(&message);
CoAPMessageType_set(&message, COAP_MESSAGE_TYPE_CON);
CoAPMessageCode_set(&message, COAP_MSG_CODE_GET);
CoAPMessageId_set(&message, Cloud_CoAPMessageId_gen(p_coap_ctx));
len = iotx_get_coap_token(p_iotx_coap, token);
CoAPMessageToken_set(&message, token, len);
Cloud_CoAPMessageHandler_set(&message, iotx_get_well_known_handler);
CoAPStrOption_add(&message, COAP_OPTION_URI_PATH, (unsigned char *)".well-known", strlen(".well-known"));
CoAPStrOption_add(&message, COAP_OPTION_URI_PATH, (unsigned char *)"core", strlen("core"));
CoAPUintOption_add(&message, COAP_OPTION_ACCEPT, COAP_CT_APP_LINK_FORMAT);
CoAPMessageUserData_set(&message, (void *)p_iotx_coap);
Cloud_CoAPMessage_send(p_coap_ctx, &message);
CoAPMessage_destory(&message);
return IOTX_SUCCESS;
}
static void iotx_coap_report_rsphdl(void *arg, void *p_response)
{
int p_payload_len = 0;
unsigned char *p_payload = NULL;
iotx_coap_resp_code_t resp_code;
IOT_CoAP_GetMessageCode(p_response, &resp_code);
IOT_CoAP_GetMessagePayload(p_response, &p_payload, &p_payload_len);
COAP_DEBUG("Report response: CoAP response code = %d", resp_code);
COAP_DEBUG("Report response: CoAP msg_len = %d", p_payload_len);
if (p_payload_len > 0) {
COAP_DEBUG("Report response: CoAP msg = '%.*s'", p_payload_len, p_payload);
} else {
COAP_WRN("Report response: CoAP response payload_len = 0");
}
}
static int coap_report_func(void *handle, const char *topic_name, int req_ack, void *data, int len)
{
iotx_message_t message;
char coap_topic[100] = {0};
(void)req_ack;
memset(&message, 0, sizeof(iotx_message_t));
message.p_payload = (unsigned char *)data;
message.payload_len = len;
message.resp_callback = iotx_coap_report_rsphdl;
message.msg_type = IOTX_MESSAGE_NON;
message.content_type = IOTX_CONTENT_TYPE_JSON;
HAL_Snprintf(coap_topic, 100, "/topic%s", topic_name);
return IOT_CoAP_SendMessage(handle, (char *)coap_topic, &message);
}
int iotx_aes_cbc_encrypt(const unsigned char *src, int len, const unsigned char *key, void *out)
{
char *iv = "543yhjy97ae7fyfg";
int len1 = len & 0xfffffff0;
int len2 = len1 + 16;
int pad = len2 - len;
int ret = 0;
p_HAL_Aes128_t aes_e_h = HAL_Aes128_Init((unsigned char *)key, (unsigned char *)iv, HAL_AES_ENCRYPTION);
if (len1) {
ret = HAL_Aes128_Cbc_Encrypt(aes_e_h, src, len1 >> 4, out);
}
if (!ret && pad) {
char buf[16] = {0};
memcpy(buf, src + len1, len - len1);
memset(buf + len - len1, pad, pad);
ret = HAL_Aes128_Cbc_Encrypt(aes_e_h, buf, 1, (unsigned char *)out + len1);
}
HAL_Aes128_Destroy(aes_e_h);
COAP_DEBUG("to encrypt src: %s, len: %d", src, len2);
return ret == 0 ? len2 : 0;
}
int iotx_aes_cbc_decrypt(const unsigned char *src, int len, const unsigned char *key, void *out)
{
char *iv = "543yhjy97ae7fyfg";
p_HAL_Aes128_t aes_d_h;
int ret = 0;
int n = len >> 4;
aes_d_h = HAL_Aes128_Init((uint8_t *)key, (uint8_t *)iv, HAL_AES_DECRYPTION);
if (!aes_d_h) {
COAP_INFO("fail to decrypt");
return 0;
}
if (n > 1) {
ret = HAL_Aes128_Cbc_Decrypt(aes_d_h, src, n - 1, out);
}
if (ret == 0) {
char *out_c = (char *)out;
int offset = n > 0 ? ((n - 1) << 4) : 0;
out_c[offset] = 0;
if (aes_d_h) {
ret = HAL_Aes128_Cbc_Decrypt(aes_d_h, src + offset, 1, out_c + offset);
} else {
COAP_ERR("fail to decrypt remain data");
}
if (ret == 0) {
char pad = out_c[len - 1];
out_c[len - pad] = 0;
/*
COAP_DEBUG("decrypt data:%s, len:%d", out_c, len - pad);
*/
HAL_Aes128_Destroy(aes_d_h);
return len - pad;
}
}
HAL_Aes128_Destroy(aes_d_h);
return 0;
}
#if AES_CFB_NOPADDING
static int iotx_aes_cfb_encrypt(const unsigned char *src, int len, const unsigned char *key, void *out)
{
int ret = -1;
char *iv = "543yhjy97ae7fyfg";
p_HAL_Aes128_t aes_e_h = HAL_Aes128_Init((unsigned char *)key, (unsigned char *)iv, HAL_AES_ENCRYPTION);
ret = HAL_Aes128_Cfb_Encrypt(aes_e_h, src, len, out);
HAL_Aes128_Destroy(aes_e_h);
COAP_DEBUG("to encrypt src:%s, len:%d", src, len);
return len;
}
int iotx_aes_cfb_decrypt(const unsigned char *src, int len, const unsigned char *key, void *out)
{
int ret = -1;
char *iv = "543yhjy97ae7fyfg";
p_HAL_Aes128_t aes_d_h = HAL_Aes128_Init((unsigned char *)key, (unsigned char *)iv, HAL_AES_ENCRYPTION);
ret = HAL_Aes128_Cfb_Decrypt(aes_d_h, src, len, out);
HAL_Aes128_Destroy(aes_d_h);
return ret;
}
#endif
int IOT_CoAP_DeviceNameAuth(iotx_coap_context_t *p_context)
{
int len = 0;
int ret = COAP_SUCCESS;
Cloud_CoAPContext *p_coap_ctx = NULL;
iotx_coap_t *p_iotx_coap = NULL;
Cloud_CoAPMessage message;
unsigned char *p_payload = NULL;
unsigned char token[8] = {0};
char sign[IOTX_SIGN_LENGTH] = {0};
p_iotx_coap = (iotx_coap_t *)p_context;
if (NULL == p_iotx_coap ||
(NULL != p_iotx_coap &&
(NULL == p_iotx_coap->p_auth_token || NULL == p_iotx_coap->p_coap_ctx || 0 == p_iotx_coap->auth_token_len))) {
COAP_DEBUG("Invalid paramter");
return IOTX_ERR_INVALID_PARAM;
}
p_coap_ctx = (Cloud_CoAPContext *)p_iotx_coap->p_coap_ctx;
CoAPMessage_init(&message);
CoAPMessageType_set(&message, COAP_MESSAGE_TYPE_CON);
CoAPMessageCode_set(&message, COAP_MSG_CODE_POST);
CoAPMessageId_set(&message, Cloud_CoAPMessageId_gen(p_coap_ctx));
len = iotx_get_coap_token(p_iotx_coap, token);
CoAPMessageToken_set(&message, token, len);
Cloud_CoAPMessageHandler_set(&message, iotx_device_name_auth_callback);
CoAPStrOption_add(&message, COAP_OPTION_URI_PATH, (unsigned char *)IOTX_AUTH_STR, strlen(IOTX_AUTH_STR));
CoAPUintOption_add(&message, COAP_OPTION_CONTENT_FORMAT, COAP_CT_APP_JSON);
CoAPUintOption_add(&message, COAP_OPTION_ACCEPT, COAP_CT_APP_JSON);
CoAPMessageUserData_set(&message, (void *)p_iotx_coap);
p_payload = coap_malloc(COAP_MSG_MAX_PDU_LEN);
if (NULL == p_payload) {
CoAPMessage_destory(&message);
return IOTX_ERR_NO_MEM;
}
memset(p_payload, 0x00, COAP_MSG_MAX_PDU_LEN);
if (COAP_ENDPOINT_PSK == p_iotx_coap->p_coap_ctx->network.ep_type) {
iotx_calc_sign_with_seq(p_iotx_coap->p_devinfo->device_secret, p_iotx_coap->p_devinfo->device_id,
p_iotx_coap->p_devinfo->device_name, p_iotx_coap->p_devinfo->product_key, p_iotx_coap->seq, sign);
HAL_Snprintf((char *)p_payload, COAP_MSG_MAX_PDU_LEN,
IOTX_AUTH_DEVICENAME_STR_WITH_SEQ,
p_iotx_coap->p_devinfo->product_key,
p_iotx_coap->p_devinfo->device_name,
p_iotx_coap->p_devinfo->device_id,
sign, p_iotx_coap->seq);
} else {
iotx_calc_sign(p_iotx_coap->p_devinfo->device_secret, p_iotx_coap->p_devinfo->device_id,
p_iotx_coap->p_devinfo->device_name, p_iotx_coap->p_devinfo->product_key, sign);
HAL_Snprintf((char *)p_payload, COAP_MSG_MAX_PDU_LEN,
IOTX_AUTH_DEVICENAME_STR,
p_iotx_coap->p_devinfo->product_key,
p_iotx_coap->p_devinfo->device_name,
p_iotx_coap->p_devinfo->device_id,
sign);
}
CoAPMessagePayload_set(&message, p_payload, strlen((char *)p_payload));
COAP_DEBUG("The payload is: %s", message.payload);
COAP_DEBUG("Send authentication message to server");
ret = Cloud_CoAPMessage_send(p_coap_ctx, &message);
coap_free(p_payload);
CoAPMessage_destory(&message);
if (COAP_SUCCESS != ret) {
COAP_DEBUG("Send authentication message to server failed, ret = %d", ret);
return IOTX_ERR_SEND_MSG_FAILED;
}
ret = Cloud_CoAPMessage_recv(p_coap_ctx, CONFIG_COAP_AUTH_TIMEOUT, 2);
if (0 < ret && !p_iotx_coap->is_authed) {
COAP_INFO("CoAP authenticate failed");
return IOTX_ERR_AUTH_FAILED;
}
iotx_set_report_func(coap_report_func);
/* report module id */
ret = iotx_report_mid(p_context);
if (SUCCESS_RETURN != ret) {
COAP_WRN("Send ModuleId message to server(CoAP) failed, ret = %d", ret);
}
/* report device information */
ret = iotx_report_devinfo(p_context);
if (SUCCESS_RETURN != ret) {
COAP_WRN("Send devinfo message to server(CoAP) failed, ret = %d", ret);
}
#if 0
/* report firmware version */
ret = iotx_report_firmware_version(p_context);
if (SUCCESS_RETURN != ret) {
COAP_DEBUG("Send firmware message to server(CoAP) failed, ret = %d", ret);
return IOTX_ERR_SEND_MSG_FAILED;
}
#endif
return IOTX_SUCCESS;
}
static int iotx_split_path_2_option(char *uri, Cloud_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 IOTX_ERR_INVALID_PARAM;
}
if (IOTX_URI_MAX_LEN < strlen(uri)) {
COAP_ERR("The uri length is too loog,len = %d", (int)strlen(uri));
return IOTX_ERR_URI_TOO_LOOG;
}
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);
COAP_DEBUG("path: %s,len=%d", path, (int)(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);
COAP_DEBUG("path: %s,len=%d", path, (int)strlen(path));
CoAPStrOption_add(message, COAP_OPTION_URI_PATH,
(unsigned char *)path, (int)strlen(path));
}
ptr ++;
}
return IOTX_SUCCESS;
}
uint32_t IOT_CoAP_GetCurToken(iotx_coap_context_t *p_context)
{
iotx_coap_t *p_iotx_coap = NULL;
if (p_context == NULL) {
return IOTX_ERR_INVALID_PARAM;
}
p_iotx_coap = (iotx_coap_t *)p_context;
return p_iotx_coap->coap_token;
}
int IOT_CoAP_SendMessage(iotx_coap_context_t *p_context, char *p_path, iotx_message_t *p_message)
{
int len = 0;
int ret = IOTX_SUCCESS;
Cloud_CoAPContext *p_coap_ctx = NULL;
iotx_coap_t *p_iotx_coap = NULL;
Cloud_CoAPMessage message;
unsigned char token[8] = {0};
unsigned char *payload = NULL;
p_iotx_coap = (iotx_coap_t *)p_context;
if (NULL == p_context || NULL == p_path || NULL == p_message ||
(NULL != p_iotx_coap && NULL == p_iotx_coap->p_coap_ctx)) {
COAP_ERR("Invalid paramter p_context %p, p_uri %p, p_message %p",
p_context, p_path, p_message);
return IOTX_ERR_INVALID_PARAM;
}
#ifdef INFRA_LOG_NETWORK_PAYLOAD
COAP_INFO("Upstream Topic: '%s'", p_path);
COAP_INFO("Upstream Payload:");
iotx_facility_json_print((const char *)p_message->p_payload, LOG_INFO_LEVEL, '>');
#endif
/* as this function only support POST request message, type ACK and RST shall be considered error parameters */
if (p_message->msg_type != IOTX_MESSAGE_CON && p_message->msg_type != IOTX_MESSAGE_NON) {
return IOTX_ERR_INVALID_PARAM;
}
if (p_message->payload_len >= COAP_MSG_MAX_PDU_LEN) {
COAP_ERR("The payload length %d is too loog", p_message->payload_len);
return IOTX_ERR_MSG_TOO_LOOG;
}
p_coap_ctx = (Cloud_CoAPContext *)p_iotx_coap->p_coap_ctx;
if (p_iotx_coap->is_authed) {
/* CoAPMessage_init(&message); */
CoAPMessage_init(&message);
CoAPMessageType_set(&message, p_message->msg_type);
CoAPMessageCode_set(&message, COAP_MSG_CODE_POST);
CoAPMessageId_set(&message, Cloud_CoAPMessageId_gen(p_coap_ctx));
len = iotx_get_coap_token(p_iotx_coap, token);
CoAPMessageToken_set(&message, token, len);
CoAPMessageUserData_set(&message, (void *)p_message->user_data);
Cloud_CoAPMessageHandler_set(&message, p_message->resp_callback);
ret = iotx_split_path_2_option(p_path, &message);
if (IOTX_SUCCESS != ret) {
return ret;
}
if (IOTX_CONTENT_TYPE_CBOR == p_message->content_type) {
CoAPUintOption_add(&message, COAP_OPTION_CONTENT_FORMAT, COAP_CT_APP_CBOR);
CoAPUintOption_add(&message, COAP_OPTION_ACCEPT, COAP_CT_APP_OCTET_STREAM);
} else {
CoAPUintOption_add(&message, COAP_OPTION_CONTENT_FORMAT, COAP_CT_APP_JSON);
CoAPUintOption_add(&message, COAP_OPTION_ACCEPT, COAP_CT_APP_OCTET_STREAM);
}
CoAPStrOption_add(&message, COAP_OPTION_AUTH_TOKEN,
(unsigned char *)p_iotx_coap->p_auth_token, strlen(p_iotx_coap->p_auth_token));
if (COAP_ENDPOINT_PSK == p_iotx_coap->p_coap_ctx->network.ep_type) {
unsigned char buff[32] = {0};
unsigned char seq[33] = {0};
HAL_Snprintf((char *)buff, sizeof(buff) - 1, "%d", p_iotx_coap->seq++);
len = iotx_aes_cbc_encrypt(buff, strlen((char *)buff), p_iotx_coap->key, seq);
if (0 < len) {
CoAPStrOption_add(&message, COAP_OPTION_SEQ, (unsigned char *)seq, len);
} else {
COAP_INFO("Encrypt seq failed");
}
HEXDUMP_DEBUG(seq, len);
payload = (unsigned char *)coap_malloc(COAP_MSG_MAX_PDU_LEN);
if (NULL == payload) {
return IOTX_ERR_NO_MEM;
}
memset(payload, 0x00, COAP_MSG_MAX_PDU_LEN);
len = iotx_aes_cbc_encrypt(p_message->p_payload, p_message->payload_len, p_iotx_coap->key, payload);
if (0 == len) {
coap_free(payload);
payload = NULL;
return IOTX_ERR_INVALID_PARAM;
}
HEXDUMP_DEBUG(payload, len);
CoAPMessagePayload_set(&message, payload, len);
} else {
CoAPMessagePayload_set(&message, p_message->p_payload, p_message->payload_len);
}
ret = Cloud_CoAPMessage_send(p_coap_ctx, &message);
CoAPMessage_destory(&message);
if (NULL != payload) {
coap_free(payload);
payload = NULL;
}
if (COAP_ERROR_DATA_SIZE == ret) {
return IOTX_ERR_MSG_TOO_LOOG;
}
return IOTX_SUCCESS;
} else {
COAP_ERR("The client [%s/%s] still un-authorized yet, return %d",
p_iotx_coap->p_devinfo->product_key,
p_iotx_coap->p_devinfo->device_name,
IOTX_ERR_NOT_AUTHED
);
return IOTX_ERR_NOT_AUTHED;
}
}
int IOT_CoAP_GetMessagePayload(void *p_message, unsigned char **pp_payload, int *p_len)
{
Cloud_CoAPMessage *message = NULL;
iotx_coap_t *p_iotx_coap = NULL;
if (NULL == p_message || NULL == pp_payload || NULL == p_len || NULL == g_coap_context) {
COAP_ERR("Invalid parameter: p_message=%p, pp_payload=%p, p_len=%p",
p_message, pp_payload, p_len);
return IOTX_ERR_INVALID_PARAM;
}
p_iotx_coap = (iotx_coap_t *)g_coap_context;
message = (Cloud_CoAPMessage *)p_message;
COAP_DEBUG("message->payload: %p", message->payload);
COAP_DEBUG("message->payloadlen: %d", message->payloadlen);
if (message->payloadlen >= COAP_MSG_MAX_PDU_LEN) {
COAP_ERR("Invalid parameter: message->payloadlen(%d) out of [0, %d]",
message->payloadlen, COAP_MSG_MAX_PDU_LEN);
return IOTX_ERR_INVALID_PARAM;
}
if (COAP_ENDPOINT_PSK == p_iotx_coap->p_coap_ctx->network.ep_type) {
int len = 0;
unsigned char *payload = NULL;
payload = coap_malloc(COAP_MSG_MAX_PDU_LEN);
if (NULL == payload) {
return IOTX_ERR_NO_MEM;
}
memset(payload, 0x00, COAP_MSG_MAX_PDU_LEN);
HEXDUMP_DEBUG(message->payload, message->payloadlen);
len = iotx_aes_cbc_decrypt(message->payload, message->payloadlen, p_iotx_coap->key, payload);
if (len > 0) {
COAP_DEBUG("payload: %.*s, len %d", len, payload, len);
}
if (len != 0) {
memcpy(message->payload, payload, len);
message->payloadlen = len;
HEXDUMP_DEBUG(payload, len);
}
coap_free(payload);
}
*pp_payload = message->payload;
*p_len = message->payloadlen;
return IOTX_SUCCESS;
}
int IOT_CoAP_GetMessageToken(void *p_message, unsigned int *token)
{
Cloud_CoAPMessage *message = NULL;
if (NULL == p_message || NULL == token) {
COAP_ERR("Invalid paramter p_message %p, token= %p", p_message, token);
return -1;
}
message = (Cloud_CoAPMessage *)p_message;
*token = ((unsigned int)(message->token[3]) & 0xff) << 24;
*token += ((unsigned int)(message->token[2]) & 0xff) << 16;
*token += ((unsigned int)(message->token[1]) & 0xff) << 8;
*token += ((unsigned int)(message->token[0]) & 0xff);
return 0;
}
int IOT_CoAP_GetMessageCode(void *p_message, iotx_coap_resp_code_t *p_resp_code)
{
Cloud_CoAPMessage *message = NULL;
if (NULL == p_message || NULL == p_resp_code) {
COAP_ERR("Invalid paramter p_message %p, p_resp_code %p",
p_message, p_resp_code);
return IOTX_ERR_INVALID_PARAM;
}
message = (Cloud_CoAPMessage *)p_message;
*p_resp_code = (iotx_coap_resp_code_t) message->header.code;
return IOTX_SUCCESS;
}
static unsigned int iotx_get_seq(void)
{
HAL_Srandom((unsigned int)HAL_UptimeMs());
return HAL_Random(0xffffffff) % 10000;
}
iotx_coap_context_t *IOT_CoAP_Init(iotx_coap_config_t *p_config)
{
Cloud_CoAPInitParam param;
char url[128] = {0};
iotx_coap_t *p_iotx_coap = NULL;
if (NULL == p_config) {
COAP_ERR("Invalid paramter p_config %p", p_config);
return NULL;
}
if (NULL == p_config->p_devinfo) {
COAP_ERR("Invalid paramter p_devinfo %p", p_config->p_devinfo);
return NULL;
}
p_iotx_coap = coap_malloc(sizeof(iotx_coap_t));
if (NULL == p_iotx_coap) {
COAP_ERR(" Allocate memory for iotx_coap_context_t failed");
return NULL;
}
memset(p_iotx_coap, 0x00, sizeof(iotx_coap_t));
p_iotx_coap->p_auth_token = coap_malloc(IOTX_AUTH_TOKEN_LEN);
if (NULL == p_iotx_coap->p_auth_token) {
COAP_ERR(" Allocate memory for auth token failed");
goto err;
}
memset(p_iotx_coap->p_auth_token, 0x00, IOTX_AUTH_TOKEN_LEN);
/*Set the client isn't authed*/
p_iotx_coap->is_authed = IOT_FALSE;
p_iotx_coap->auth_token_len = IOTX_AUTH_TOKEN_LEN;
/*Get deivce information*/
p_iotx_coap->p_devinfo = coap_malloc(sizeof(iotx_deviceinfo_t));
if (NULL == p_iotx_coap->p_devinfo) {
COAP_ERR(" Allocate memory for iotx_deviceinfo_t failed");
goto err;
}
memset(p_iotx_coap->p_devinfo, 0x00, sizeof(iotx_deviceinfo_t));
/*It should be implement by the user*/
if (NULL != p_config->p_devinfo) {
memset(p_iotx_coap->p_devinfo, 0x00, sizeof(iotx_deviceinfo_t));
strncpy(p_iotx_coap->p_devinfo->device_id, p_config->p_devinfo->device_id, strlen(p_config->p_devinfo->device_id));
strncpy(p_iotx_coap->p_devinfo->product_key, p_config->p_devinfo->product_key,
strlen(p_config->p_devinfo->product_key));
strncpy(p_iotx_coap->p_devinfo->device_secret, p_config->p_devinfo->device_secret,
strlen(p_config->p_devinfo->device_secret));
strncpy(p_iotx_coap->p_devinfo->device_name, p_config->p_devinfo->device_name,
strlen(p_config->p_devinfo->device_name));
}
/*Init coap token*/
p_iotx_coap->coap_token = IOTX_COAP_INIT_TOKEN;
p_iotx_coap->seq = iotx_get_seq();
memset(p_iotx_coap->key, 0x00, sizeof(p_iotx_coap->key));
/*Create coap context*/
memset(&param, 0x00, sizeof(Cloud_CoAPInitParam));
if (NULL != p_config->p_url) {
param.url = p_config->p_url;
} else {
HAL_Snprintf(url, sizeof(url), IOTX_COAP_ONLINE_PSK_SERVER_URL, p_iotx_coap->p_devinfo->product_key);
param.url = url;
COAP_INFO("Using default CoAP server: %s", url);
}
param.maxcount = IOTX_LIST_MAX_ITEM;
param.notifier = (Cloud_CoAPEventNotifier)iotx_event_notifyer;
param.waittime = p_config->wait_time_ms;
p_iotx_coap->p_coap_ctx = Cloud_CoAPContext_create(&param);
if (NULL == p_iotx_coap->p_coap_ctx) {
COAP_ERR(" Create coap context failed");
goto err;
}
/*Register the event handle to notify the application */
p_iotx_coap->event_handle = p_config->event_handle;
g_coap_context = (iotx_coap_context_t *)p_iotx_coap;
return (iotx_coap_context_t *)p_iotx_coap;
err:
/* Error, release the memory */
if (NULL != p_iotx_coap) {
if (NULL != p_iotx_coap->p_devinfo) {
coap_free(p_iotx_coap->p_devinfo);
}
if (NULL != p_iotx_coap->p_auth_token) {
coap_free(p_iotx_coap->p_auth_token);
}
if (NULL != p_iotx_coap->p_coap_ctx) {
Cloud_CoAPContext_free(p_iotx_coap->p_coap_ctx);
}
p_iotx_coap->auth_token_len = 0;
p_iotx_coap->is_authed = IOT_FALSE;
coap_free(p_iotx_coap);
}
return NULL;
}
void IOT_CoAP_Deinit(iotx_coap_context_t **pp_context)
{
iotx_coap_t *p_iotx_coap = NULL;
if (NULL != pp_context && NULL != *pp_context) {
p_iotx_coap = (iotx_coap_t *)*pp_context;
p_iotx_coap->is_authed = IOT_FALSE;
p_iotx_coap->auth_token_len = 0;
p_iotx_coap->coap_token = IOTX_COAP_INIT_TOKEN;
if (NULL != p_iotx_coap->p_auth_token) {
coap_free(p_iotx_coap->p_auth_token);
p_iotx_coap->p_auth_token = NULL;
}
if (NULL != p_iotx_coap->p_devinfo) {
coap_free(p_iotx_coap->p_devinfo);
p_iotx_coap->p_devinfo = NULL;
}
if (NULL != p_iotx_coap->p_coap_ctx) {
Cloud_CoAPContext_free(p_iotx_coap->p_coap_ctx);
p_iotx_coap->p_coap_ctx = NULL;
}
coap_free(p_iotx_coap);
*pp_context = NULL;
g_coap_context = NULL;
}
}
int IOT_CoAP_Yield(iotx_coap_context_t *p_context)
{
iotx_coap_t *p_iotx_coap = NULL;
p_iotx_coap = (iotx_coap_t *)p_context;
if (NULL == p_iotx_coap || (NULL != p_iotx_coap && NULL == p_iotx_coap->p_coap_ctx)) {
COAP_ERR("Invalid paramter");
return IOTX_ERR_INVALID_PARAM;
}
return Cloud_CoAPMessage_cycle(p_iotx_coap->p_coap_ctx);
}

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.
*/
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.
*/
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.
*/
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.
*/
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.
**/
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.
**/
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);
int HAL_DTLSHooks_set(dtls_hooks_t *hooks);
DTLSContext *HAL_DTLSSession_create(coap_dtls_options_t *p_options);
unsigned int HAL_DTLSSession_write(DTLSContext *context,
const unsigned char *p_data,
unsigned int *p_datalen);
unsigned int HAL_DTLSSession_read(DTLSContext *context,
unsigned char *p_data,
unsigned int *p_datalen,
unsigned int timeout_ms);
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,227 @@
/*
* Copyright (C) 2015-2018 Alibaba Group Holding Limited
*/
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#if !defined(_WIN32)
#include <unistd.h>
#endif
#include "coap_api.h"
#include "coap_wrapper.h"
#define IOTX_DAILY_DTLS_SERVER_URI "coaps://11.239.164.238:5684"
#define IOTX_DAILY_PSK_SERVER_URI "coap-psk://10.101.83.159:5682"
#define IOTX_PRE_DTLS_SERVER_URI "coaps://pre.coap.cn-shanghai.link.aliyuncs.com:5684"
#define IOTX_PRE_NOSEC_SERVER_URI "coap://pre.coap.cn-shanghai.link.aliyuncs.com:5683"
#define IOTX_PRE_PSK_SERVER_URI "coap-psk://pre.coap.cn-shanghai.link.aliyuncs.com:5683"
/* online url */
#define IOTX_ONLINE_DTLS_SERVER_URL "coaps://%s.coap.cn-shanghai.link.aliyuncs.com:5684"
#define IOTX_ONLINE_NOSEC_SERVER_URI "coap://%s.coap.cn-shanghai.link.aliyuncs.com:5683"
#define IOTX_ONLINE_PSK_SERVER_URL "coap-psk://%s.coap.cn-shanghai.link.aliyuncs.com:5682"
char m_coap_client_running = 0;
char m_coap_reconnect = 0;
static void iotx_response_handler(void *arg, void *p_response)
{
int len = 0;
unsigned char *p_payload = NULL;
iotx_coap_resp_code_t resp_code;
IOT_CoAP_GetMessageCode(p_response, &resp_code);
IOT_CoAP_GetMessagePayload(p_response, &p_payload, &len);
HAL_Printf("[APPL]: Message response code: 0x%x\r\n", resp_code);
HAL_Printf("[APPL]: Len: %d, Payload: %s\r\n", len, p_payload);
}
char IOTX_PRODUCT_KEY[IOTX_PRODUCT_KEY_LEN + 1] = {0};
char IOTX_DEVICE_NAME[IOTX_DEVICE_NAME_LEN + 1] = {0};
char IOTX_DEVICE_SECRET[IOTX_DEVICE_SECRET_LEN + 1] = {0};
int iotx_get_devinfo(iotx_deviceinfo_t *p_devinfo)
{
if (NULL == p_devinfo) {
return IOTX_ERR_INVALID_PARAM;
}
memset(p_devinfo, 0x00, sizeof(iotx_deviceinfo_t));
/**< get device info*/
HAL_GetProductKey(p_devinfo->product_key);
HAL_GetDeviceName(p_devinfo->device_name);
HAL_GetDeviceSecret(p_devinfo->device_secret);
memset(p_devinfo->device_id, 0, IOTX_PRODUCT_KEY_LEN + IOTX_DEVICE_NAME_LEN + 2);
HAL_Snprintf(p_devinfo->device_id, IOTX_PRODUCT_KEY_LEN + IOTX_DEVICE_NAME_LEN + 2,
"%s.%s", p_devinfo->product_key, p_devinfo->device_name);
/**< end*/
fprintf(stderr, "*****The Product Key : %s *****\r\n", p_devinfo->product_key);
fprintf(stderr, "*****The Device Name : %s *****\r\n", p_devinfo->device_name);
fprintf(stderr, "*****The Device Secret: %s *****\r\n", p_devinfo->device_secret);
fprintf(stderr, "*****The Device ID : %s *****\r\n", p_devinfo->device_id);
return IOTX_SUCCESS;
}
static void iotx_post_data_to_server(void *param)
{
char path[IOTX_URI_MAX_LEN + 1] = {0};
iotx_message_t message;
iotx_deviceinfo_t devinfo;
memset(&message, 0, sizeof(iotx_message_t));
memset(&devinfo, 0, sizeof(iotx_deviceinfo_t));
message.p_payload = (unsigned char *)"{\"name\":\"hello world\"}";
message.payload_len = strlen("{\"name\":\"hello world\"}");
message.resp_callback = iotx_response_handler;
message.msg_type = IOTX_MESSAGE_CON;
message.content_type = IOTX_CONTENT_TYPE_JSON;
iotx_coap_context_t *p_ctx = (iotx_coap_context_t *)param;
iotx_get_devinfo(&devinfo);
snprintf(path, IOTX_URI_MAX_LEN, "/topic/%s/%s/update/", (char *)devinfo.product_key,
(char *)devinfo.device_name);
IOT_CoAP_SendMessage(p_ctx, path, &message);
}
void show_usage()
{
HAL_Printf("\r\nusage: coap-example [OPTION]...\r\n");
HAL_Printf("\t-e pre|online|daily\t\tSet the cloud environment.\r\n");
HAL_Printf("\t-s nosec|dtls|psk \t\tSet the security setting.\r\n");
HAL_Printf("\t-l \t\tSet the program run loop.\r\n");
HAL_Printf("\t-r \t\tTesting the DTLS session ticket.\r\n");
HAL_Printf("\t-h \t\tShow this usage.\r\n");
}
int main(int argc, char **argv)
{
int count = 0;
char secur[32] = {0};
char env[32] = {0};
int opt;
iotx_coap_config_t config;
iotx_deviceinfo_t deviceinfo;
/* set device info use HAL function */
HAL_GetProductKey(IOTX_PRODUCT_KEY);
HAL_GetDeviceName(IOTX_DEVICE_NAME);
HAL_GetDeviceSecret(IOTX_DEVICE_SECRET);
IOT_SetLogLevel(IOT_LOG_DEBUG);
#if !defined(_WIN32) && !defined(BUILD_AOS)
while ((opt = getopt(argc, argv, "e:s:lhr")) != -1) {
switch (opt) {
case 's': {
if (strlen(optarg) > 31) {
memcpy(secur, optarg, 31);
} else {
memcpy(secur, optarg, strlen(optarg));
}
}
break;
case 'e': {
if (strlen(optarg) > 31) {
memcpy(env, optarg, 31);
} else {
memcpy(env, optarg, strlen(optarg));
}
}
break;
case 'l':
m_coap_client_running = 1;
break;
case 'r':
m_coap_reconnect = 1;
break;
case 'h':
show_usage();
return 0;
default:
break;
}
}
#else
/* Just use psk security mode, online environment */
(void)argc;
(void)argv;
(void)opt;
memcpy(secur, "psk", 4);
memcpy(env, "online", 7);
m_coap_client_running = 1;
m_coap_reconnect = 1;
#endif
HAL_Printf("[COAP-Client]: Enter Coap Client\r\n");
memset(&config, 0x00, sizeof(iotx_coap_config_t));
if (0 == strncmp(env, "pre", strlen("pre"))) {
if (0 == strncmp(secur, "dtls", strlen("dtls"))) {
config.p_url = IOTX_PRE_DTLS_SERVER_URI;
} else if (0 == strncmp(secur, "psk", strlen("psk"))) {
config.p_url = IOTX_PRE_PSK_SERVER_URI;
} else {
config.p_url = IOTX_PRE_NOSEC_SERVER_URI;
}
} else if (0 == strncmp(env, "online", strlen("online"))) {
if (0 == strncmp(secur, "dtls", strlen("dtls"))) {
char url[256] = {0};
snprintf(url, sizeof(url), IOTX_ONLINE_DTLS_SERVER_URL, IOTX_PRODUCT_KEY);
config.p_url = url;
} else if (0 == strncmp(secur, "psk", strlen("psk"))) {
char url[256] = {0};
snprintf(url, sizeof(url), IOTX_ONLINE_PSK_SERVER_URL, IOTX_PRODUCT_KEY);
config.p_url = url;
} else {
HAL_Printf("Online environment must access with DTLS/PSK\r\n");
IOT_SetLogLevel(IOT_LOG_NONE);
return -1;
}
} else if (0 == strncmp(env, "daily", strlen("daily"))) {
if (0 == strncmp(secur, "dtls", strlen("dtls"))) {
config.p_url = IOTX_DAILY_DTLS_SERVER_URI;
} else if (0 == strncmp(secur, "psk", strlen("psk"))) {
config.p_url = IOTX_DAILY_PSK_SERVER_URI;
}
}
iotx_get_devinfo(&deviceinfo);
config.p_devinfo = (iotx_device_info_t *)&deviceinfo;
config.wait_time_ms = 3000;
iotx_coap_context_t *p_ctx = NULL;
reconnect:
p_ctx = IOT_CoAP_Init(&config);
if (NULL != p_ctx) {
IOT_CoAP_DeviceNameAuth(p_ctx);
do {
if (count == 11 || 0 == count) {
iotx_post_data_to_server((void *)p_ctx);
count = 1;
}
count ++;
IOT_CoAP_Yield(p_ctx);
} while (m_coap_client_running);
IOT_CoAP_Deinit(&p_ctx);
} else {
HAL_Printf("IoTx CoAP init failed\r\n");
}
if (m_coap_reconnect) {
m_coap_reconnect = 0;
goto reconnect;
}
IOT_DumpMemoryStats(IOT_LOG_DEBUG);
IOT_SetLogLevel(IOT_LOG_NONE);
HAL_Printf("[COAP-Client]: Exit Coap Client\r\n");
return 0;
}

View File

@@ -0,0 +1,13 @@
LIBA_TARGET := libiot_coap.a
HDR_REFS := src/infra
LIB_SRCS_PATTERN := *.c
$(call Append_Conditional, LIB_SRCS_PATTERN, client/*.c, COAP_CLIENT)
$(call Append_Conditional, LIB_SRCS_PATTERN, CoAPPacket/*.c, COAP_PACKET)
$(call Append_Conditional, LIB_SRCS_PATTERN, server/*.c, COAP_SERVER)
LDFLAGS += -liot_sdk -liot_hal -liot_tls
$(call Append_Conditional, LIB_SRCS_EXCLUDE, examples/coap_example.c, COAP_CLIENT)
$(call Append_Conditional, SRCS_coap-example, examples/coap_example.c, COAP_CLIENT)
$(call Append_Conditional, TARGET, coap-example, COAP_CLIENT)

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)
{
char 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,242 @@
/*
* 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 (0 == strncmp((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;
}
int CoAPResource_topicFilterMatch(const char *filter, const char *topic)
{
if (filter == NULL || topic == NULL) {
return -1;
}
if (strncmp(filter, topic, strlen(filter) - 1) == 0) {
if (strlen(topic) > strlen(filter) - 1) {
const char *more = topic + (strlen(filter) - 1);
if (strstr(more, "/") == NULL) {
return 0;
}
}
}
return -1;
}
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;
}
}
list_for_each_entry(node, &ctx->resource.list, reslist, CoAPResource) {
if (node->path_type == PATH_FILTER && strlen(node->filter_path) > 0) {
if (CoAPResource_topicFilterMatch(node->filter_path, path) == 0) {
HAL_MutexUnlock(ctx->resource.list_mutex);
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_topicFilterMatch(const char *filter, const char *topic);
int CoAPResource_deinit(CoAPContext *context);
#ifdef __cplusplus
}
#endif /* __cplusplus */
#endif

View File

@@ -0,0 +1,312 @@
/*
* 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;
}
static void *coap_init_mutex = NULL;
CoAPContext *CoAPServer_init()
{
CoAPInitParam param = {0};
#ifdef COAP_SERV_MULTITHREAD
int stack_used;
hal_os_thread_param_t task_parms = {0};
#endif
if (NULL == coap_init_mutex) {
coap_init_mutex = HAL_MutexCreate();
if (NULL == coap_init_mutex) {
return NULL;
}
}
HAL_MutexLock(coap_init_mutex);
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");
HAL_MutexUnlock(coap_init_mutex);
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;
HAL_MutexUnlock(coap_init_mutex);
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");
HAL_MutexUnlock(coap_init_mutex);
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");
}
HAL_MutexUnlock(coap_init_mutex);
return (CoAPContext *)g_context;
}
void CoAPServer_deinit(CoAPContext *context)
{
if (context != g_context) {
COAP_INFO("Invalid CoAP Server context");
return;
}
if (NULL == coap_init_mutex) {
COAP_ERR("CoAP init mutex is NULL");
return;
}
HAL_MutexLock(coap_init_mutex);
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;
}
HAL_MutexUnlock(coap_init_mutex);
HAL_MutexDestroy(coap_init_mutex);
coap_init_mutex = 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

View File

@@ -0,0 +1,50 @@
# README.md: coap local
## Contents
```shell
.
├── aos.mk
├── CMakeLists.txt
├── CoAPDeserialize.c
├── CoAPDeserialize.h
├── CoAPExport.c
├── CoAPExport.h
├── CoAPInternal.h
├── CoAPMessage.c
├── CoAPMessage.h
├── CoAPNetwork.c
├── CoAPNetwork.h
├── CoAPObserve.c
├── CoAPObserve.h
├── CoAPPlatform.c
├── CoAPPlatform.h
├── CoAPResource.c
├── CoAPResource.h
├── CoAPSerialize.c
├── CoAPSerialize.h
├── CoAPServer.c
├── CoAPServer.h
├── Config.in
├── iot.mk
└── README.md
```
## Introduction
Implementation of coap protocol and special customization for alcs and awss
### Features
### Dependencies
- **hal**. osal and hal to shield different os and hardware
- **infra**. Authentication, net and so on tool set.
## API
none
## Reference
none