Selaa lähdekoodia

【增加】coap 支持和 coap 例程
【增加】加密相关 wrapper 实现

Signed-off-by: Murphy <d2014zjt@163.com>

Murphy 6 vuotta sitten
vanhempi
sitoutus
516856f2f1

+ 8 - 0
SConscript

@@ -142,6 +142,9 @@ if GetDepend(['DEVICE_MODEL_ENABLED']):
         src += Glob("iotkit-embedded/src/dev_model/alcs/*.c")
         CPPPATH += [cwd + '/iotkit-embedded/src/dev_model/alcs']
 
+    if GetDepend(['COAP_COMM_ENABLED']):
+        src += Glob("iotkit-embedded/src/dev_model/iotx_cm_coap.c")
+
     CPPPATH += [cwd + '/iotkit-embedded/src/dev_model']
     CPPPATH += [cwd + '/iotkit-embedded/src/dev_model/client']
     CPPPATH += [cwd + '/iotkit-embedded/src/dev_model/server']
@@ -248,6 +251,7 @@ src += Split("""
 ports/rtthread/HAL_OS_rtthread.c
 ports/rtthread/HAL_TCP_rtthread.c
 ports/rtthread/HAL_UDP_rtthread.c
+ports/rtthread/HAL_Crypt_rtthread.c
 ports/wrapper.c
 """)
 
@@ -269,6 +273,10 @@ if GetDepend(['PKG_USING_ALI_IOTKIT_DEV_MODEL_SAMPLE']):
     samples/dev_model/linkkit_example_solo.c
     """)
     CPPPATH += [cwd + '/iotkit-embedded/samples/dev_model']
+if GetDepend(['PKG_USING_ALI_IOTKIT_COAP_SAMPLE']):
+    src += Split("""
+    samples/coap/coap_example.c
+    """)
 #### samples end ####
 
 group = DefineGroup('ali-iotkit', src, depend = ['PKG_USING_ALI_IOTKIT'], CPPPATH = CPPPATH)

+ 146 - 0
ports/rtthread/HAL_Crypt_rtthread.c

@@ -0,0 +1,146 @@
+/*
+ * Copyright (C) 2015-2018 Alibaba Group Holding Limited
+ */
+
+#include "infra_config.h"
+
+#if defined(HAL_CRYPTO)
+
+#include <string.h>
+#include <stdlib.h>
+#include "infra_compat.h"
+#include "mbedtls/aes.h"
+
+#define AES_BLOCK_SIZE 16
+
+typedef struct {
+    mbedtls_aes_context ctx;
+    uint8_t iv[16];
+    uint8_t key[16];
+} platform_aes_t;
+
+p_HAL_Aes128_t HAL_Aes128_Init(
+            const uint8_t *key,
+            const uint8_t *iv,
+            AES_DIR_t dir)
+{
+    int ret = 0;
+    platform_aes_t *p_aes128 = NULL;
+
+    if (!key || !iv) return p_aes128;
+
+    p_aes128 = (platform_aes_t *)calloc(1, sizeof(platform_aes_t));
+    if (!p_aes128) return p_aes128;
+
+    mbedtls_aes_init(&p_aes128->ctx);
+
+    if (dir == HAL_AES_ENCRYPTION) {
+        ret = mbedtls_aes_setkey_enc(&p_aes128->ctx, key, 128);
+    } else {
+        ret = mbedtls_aes_setkey_dec(&p_aes128->ctx, key, 128);
+    }
+
+    if (ret == 0) {
+        memcpy(p_aes128->iv, iv, 16);
+        memcpy(p_aes128->key, key, 16);
+    } else {
+        free(p_aes128);
+        p_aes128 = NULL;
+    }
+
+    return (p_HAL_Aes128_t *)p_aes128;
+}
+
+int HAL_Aes128_Destroy(p_HAL_Aes128_t aes)
+{
+    if (!aes) return -1;
+
+    mbedtls_aes_free(&((platform_aes_t *)aes)->ctx);
+    free(aes);
+
+    return 0;
+}
+
+int HAL_Aes128_Cbc_Encrypt(
+            p_HAL_Aes128_t aes,
+            const void *src,
+            size_t blockNum,
+            void *dst)
+{
+    int i   = 0;
+    int ret = ret;
+    platform_aes_t *p_aes128 = (platform_aes_t *)aes;
+
+    if (!aes || !src || !dst) return -1;
+
+    for (i = 0; i < blockNum; ++i) {
+        ret = mbedtls_aes_crypt_cbc(&p_aes128->ctx, MBEDTLS_AES_ENCRYPT, AES_BLOCK_SIZE,
+                                    p_aes128->iv, src, dst);
+        src += 16;
+        dst += 16;
+    }
+
+    return ret;
+}
+
+int HAL_Aes128_Cbc_Decrypt(
+            p_HAL_Aes128_t aes,
+            const void *src,
+            size_t blockNum,
+            void *dst)
+{
+    int i   = 0;
+    int ret = -1;
+    platform_aes_t *p_aes128 = (platform_aes_t *)aes;
+
+    if (!aes || !src || !dst) return ret;
+
+    for (i = 0; i < blockNum; ++i) {
+        ret = mbedtls_aes_crypt_cbc(&p_aes128->ctx, MBEDTLS_AES_DECRYPT, AES_BLOCK_SIZE,
+                                    p_aes128->iv, src, dst);
+        src += 16;
+        dst += 16;
+    }
+
+    return ret;
+}
+#if defined(MBEDTLS_CIPHER_MODE_CFB)
+int HAL_Aes128_Cfb_Encrypt(
+            p_HAL_Aes128_t aes,
+            const void *src,
+            size_t length,
+            void *dst)
+{
+    size_t offset = 0;
+    int ret = -1;
+    platform_aes_t *p_aes128 = (platform_aes_t *)aes;
+
+    if (!aes || !src || !dst) return ret;
+
+    ret = mbedtls_aes_crypt_cfb128(&p_aes128->ctx, MBEDTLS_AES_ENCRYPT, length,
+                                   &offset, p_aes128->iv, src, dst);
+    return ret;
+}
+#endif
+
+#if defined(MBEDTLS_CIPHER_MODE_CFB)
+int HAL_Aes128_Cfb_Decrypt(
+            p_HAL_Aes128_t aes,
+            const void *src,
+            size_t length,
+            void *dst)
+{
+    size_t offset = 0;
+    int ret = -1;
+    platform_aes_t *p_aes128 = (platform_aes_t *)aes;
+
+    if (!aes || !src || !dst) return ret;
+
+    ret = mbedtls_aes_setkey_enc(&p_aes128->ctx, p_aes128->key, 128);
+    ret = mbedtls_aes_crypt_cfb128(&p_aes128->ctx, MBEDTLS_AES_DECRYPT, length,
+                                   &offset, p_aes128->iv, src, dst);
+    return ret;
+}
+#endif
+
+#endif  /* #if defined(HAL_CRYPTO) */

+ 0 - 2
ports/rtthread/HAL_UDP_rtthread.c

@@ -331,8 +331,6 @@ int HAL_UDP_recvfrom(intptr_t sockfd,
     return -1;
 }
 
-
-
 int HAL_UDP_sendto(intptr_t sockfd,
                    const NetworkAddr *p_remote,
                    const unsigned char *p_data,

+ 43 - 41
ports/tls/mbedtls/HAL_DTLS_mbedtls.c

@@ -20,8 +20,10 @@
 #include <stdlib.h>
 #include <string.h>
 #include <stdint.h>
-#include "iot_import_dtls.h"
+#include "infra_config.h"
+
 #ifdef COAP_DTLS_SUPPORT
+#include "wrappers_defs.h"
 #include "mbedtls/ssl.h"
 #include "mbedtls/platform.h"
 #include "mbedtls/sha256.h"
@@ -32,6 +34,10 @@
 #include "mbedtls/ssl_cookie.h"
 #include "mbedtls/net_sockets.h"
 
+#define DBG_TAG                        "ali.udp"
+#define DBG_LVL                        DBG_LOG
+#include <rtdbg.h>
+
 typedef struct {
     mbedtls_ssl_context          context;
     mbedtls_ssl_config           conf;
@@ -45,24 +51,20 @@ typedef struct {
     mbedtls_ssl_cookie_ctx       cookie_ctx;
 } dtls_session_t;
 
-
-static  void *_DTLSCalloc_wrapper(size_t n, size_t s)
+/**
+ * HAL_DTLSHooks_set
+ * Is not used in rt-thread implemented version.
+*/
+int HAL_DTLSHooks_set(dtls_hooks_t *hooks)
 {
-    void *ptr = NULL;
-    size_t len = n * s;
-    ptr = coap_malloc(len);
-    if (NULL != ptr) {
-        memset(ptr, 0x00, len);
-    }
-    return ptr;
-}
+    // if (hooks == NULL || hooks->malloc == NULL || hooks->free == NULL) {
+    //     return DTLS_INVALID_PARAM;
+    // }
 
-static  void _DTLSFree_wrapper(void *ptr)
-{
-    if (NULL != ptr) {
-        coap_free(ptr);
-        ptr = NULL;
-    }
+    // g_dtls_hooks.malloc = hooks->malloc;
+    // g_dtls_hooks.free = hooks->free;
+
+    return DTLS_SUCCESS;
 }
 
 static unsigned int _DTLSVerifyOptions_set(dtls_session_t *p_dtls_session,
@@ -78,14 +80,14 @@ static unsigned int _DTLSVerifyOptions_set(dtls_session_t *p_dtls_session,
 #else
         mbedtls_ssl_conf_authmode(&p_dtls_session->conf, MBEDTLS_SSL_VERIFY_OPTIONAL);
 #endif
-        DTLS_TRC("Call mbedtls_ssl_conf_authmode\r\n");
+        LOG_D("Call mbedtls_ssl_conf_authmode");
 
-        DTLS_TRC("x509 ca cert pem len %d\r\n%s\r\n", (int)strlen((char *)p_ca_cert_pem) + 1, p_ca_cert_pem);
+        LOG_D("x509 ca cert pem len %d\r\n%s", (int)strlen((char *)p_ca_cert_pem) + 1, p_ca_cert_pem);
         result = mbedtls_x509_crt_parse(&p_dtls_session->cacert,
                                         p_ca_cert_pem,
                                         strlen((const char *)p_ca_cert_pem) + 1);
 
-        DTLS_TRC("mbedtls_x509_crt_parse result 0x%04x\r\n", result);
+        LOG_D("mbedtls_x509_crt_parse result 0x%04x", result);
         if (0 != result) {
             err_code = DTLS_INVALID_CA_CERTIFICATE;
         } else {
@@ -103,7 +105,7 @@ static unsigned int _DTLSVerifyOptions_set(dtls_session_t *p_dtls_session,
 static void _DTLSLog_wrapper(void        *p_ctx, int level,
                              const char *p_file, int line,   const char *p_str)
 {
-    DTLS_INFO("[mbedTLS]:[%s]:[%d]: %s\r\n", p_file, line, p_str);
+    LOG_I("[mbedTLS]:[%s]:[%d]: %s", p_file, line, p_str);
 }
 
 static unsigned int _DTLSContext_setup(dtls_session_t *p_dtls_session, coap_dtls_options_t  *p_options)
@@ -113,7 +115,7 @@ static unsigned int _DTLSContext_setup(dtls_session_t *p_dtls_session, coap_dtls
     mbedtls_ssl_init(&p_dtls_session->context);
 
     result = mbedtls_ssl_setup(&p_dtls_session->context, &p_dtls_session->conf);
-    DTLS_TRC("mbedtls_ssl_setup result 0x%04x\r\n", result);
+    LOG_D("mbedtls_ssl_setup result 0x%04x", result);
 
     if (result == 0) {
         if (p_dtls_session->conf.transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM) {
@@ -124,7 +126,7 @@ static unsigned int _DTLSContext_setup(dtls_session_t *p_dtls_session, coap_dtls
         }
 
 #ifdef MBEDTLS_X509_CRT_PARSE_C
-        DTLS_TRC("mbedtls_ssl_set_hostname %s\r\n", p_options->p_host);
+        LOG_D("mbedtls_ssl_set_hostname %s", p_options->p_host);
         mbedtls_ssl_set_hostname(&p_dtls_session->context, p_options->p_host);
 #endif
         mbedtls_ssl_set_bio(&p_dtls_session->context,
@@ -132,13 +134,13 @@ static unsigned int _DTLSContext_setup(dtls_session_t *p_dtls_session, coap_dtls
                             mbedtls_net_send,
                             mbedtls_net_recv,
                             mbedtls_net_recv_timeout);
-        DTLS_TRC("mbedtls_ssl_set_bio result 0x%04x\r\n", result);
+        LOG_D("mbedtls_ssl_set_bio result 0x%04x", result);
 
         do {
             result = mbedtls_ssl_handshake(&p_dtls_session->context);
         } while (result == MBEDTLS_ERR_SSL_WANT_READ ||
                  result == MBEDTLS_ERR_SSL_WANT_WRITE);
-        DTLS_TRC("mbedtls_ssl_handshake result 0x%04x\r\n", result);
+        LOG_D("mbedtls_ssl_handshake result 0x%04x", result);
     }
 
     return (result ? DTLS_HANDSHAKE_FAILED : DTLS_SUCCESS);
@@ -147,12 +149,13 @@ static unsigned int _DTLSContext_setup(dtls_session_t *p_dtls_session, coap_dtls
 dtls_session_t *_DTLSSession_init()
 {
     dtls_session_t *p_dtls_session = NULL;
-    p_dtls_session = coap_malloc(sizeof(dtls_session_t));
+    p_dtls_session = malloc(sizeof(dtls_session_t));
 
 #if defined(MBEDTLS_DEBUG_C)
     mbedtls_debug_set_threshold(0);
 #endif
 
+    /* Is not used in rt-thread implemented version */
     // mbedtls_platform_set_calloc_free(_DTLSCalloc_wrapper, _DTLSFree_wrapper);
     if (NULL != p_dtls_session) {
         mbedtls_net_init(&p_dtls_session->fd);
@@ -167,7 +170,7 @@ dtls_session_t *_DTLSSession_init()
 #endif
         mbedtls_ctr_drbg_init(&p_dtls_session->ctr_drbg);
         mbedtls_entropy_init(&p_dtls_session->entropy);
-        DTLS_INFO("HAL_DTLSSession_init success\r\n");
+        LOG_I("HAL_DTLSSession_init success");
 
     }
 
@@ -193,7 +196,7 @@ unsigned int _DTLSSession_deinit(dtls_session_t *p_dtls_session)
 
         mbedtls_ctr_drbg_free(&p_dtls_session->ctr_drbg);
         mbedtls_entropy_free(&p_dtls_session->entropy);
-        coap_free(p_dtls_session);
+        free(p_dtls_session);
     }
 
     return DTLS_SUCCESS;
@@ -212,7 +215,7 @@ DTLSContext *HAL_DTLSSession_create(coap_dtls_options_t            *p_options)
                                        (const unsigned char *)"IoTx",
                                        strlen("IoTx"));
         if (0 !=  result) {
-            DTLS_ERR("mbedtls_ctr_drbg_seed result 0x%04x\r\n", result);
+            LOG_E("mbedtls_ctr_drbg_seed result 0x%04x", result);
             goto error;
         }
         result = mbedtls_ssl_config_defaults(&p_dtls_session->conf,
@@ -220,7 +223,7 @@ DTLSContext *HAL_DTLSSession_create(coap_dtls_options_t            *p_options)
                                              MBEDTLS_SSL_TRANSPORT_DATAGRAM,
                                              MBEDTLS_SSL_PRESET_DEFAULT);
         if (0 != result) {
-            DTLS_ERR("mbedtls_ssl_config_defaults result 0x%04x\r\n", result);
+            LOG_E("mbedtls_ssl_config_defaults result 0x%04x", result);
             goto error;
         }
         mbedtls_ssl_conf_rng(&p_dtls_session->conf, mbedtls_ctr_drbg_random, &p_dtls_session->ctr_drbg);
@@ -229,7 +232,7 @@ DTLSContext *HAL_DTLSSession_create(coap_dtls_options_t            *p_options)
         result = mbedtls_ssl_cookie_setup(&p_dtls_session->cookie_ctx,
                                           mbedtls_ctr_drbg_random, &p_dtls_session->ctr_drbg);
         if (0 != result) {
-            DTLS_ERR("mbedtls_ssl_cookie_setup result 0x%04x\r\n", result);
+            LOG_E("mbedtls_ssl_cookie_setup result 0x%04x", result);
             goto error;
         }
 #if defined(MBEDTLS_SSL_DTLS_HELLO_VERIFY) && defined(MBEDTLS_SSL_SRV_C)
@@ -240,14 +243,14 @@ DTLSContext *HAL_DTLSSession_create(coap_dtls_options_t            *p_options)
         result = _DTLSVerifyOptions_set(p_dtls_session, p_options->p_ca_cert_pem);
 
         if (DTLS_SUCCESS != result) {
-            DTLS_ERR("DTLSVerifyOptions_set result 0x%04x\r\n", result);
+            LOG_E("DTLSVerifyOptions_set result 0x%04x", result);
             goto error;
         }
         sprintf(port, "%u", p_options->port);
         result = mbedtls_net_connect(&p_dtls_session->fd, p_options->p_host,
                                      port, MBEDTLS_NET_PROTO_UDP);
         if (0 != result) {
-            DTLS_ERR("mbedtls_net_connect result 0x%04x\r\n", result);
+            LOG_E("mbedtls_net_connect result 0x%04x", result);
             goto error;
         }
 
@@ -268,7 +271,7 @@ DTLSContext *HAL_DTLSSession_create(coap_dtls_options_t            *p_options)
 #endif
         result = _DTLSContext_setup(p_dtls_session, p_options);
         if (DTLS_SUCCESS != result) {
-            DTLS_ERR("DTLSVerifyOptions_set result 0x%04x\r\n", result);
+            LOG_E("DTLSVerifyOptions_set result 0x%04x", result);
             goto error;
         }
 
@@ -325,20 +328,20 @@ unsigned int HAL_DTLSSession_read(DTLSContext *context,
         if (0  <  len) {
             *p_datalen = len;
             err_code = DTLS_SUCCESS;
-            DTLS_TRC("mbedtls_ssl_read len %d bytes\r\n", len);
+            LOG_D("mbedtls_ssl_read len %d bytes", len);
         } else {
             *p_datalen = 0;
             if (MBEDTLS_ERR_SSL_FATAL_ALERT_MESSAGE == len) {
                 err_code = DTLS_FATAL_ALERT_MESSAGE;
-                DTLS_INFO("Recv peer fatal alert message\r\n");
+                LOG_I("Recv peer fatal alert message");
             } else if (MBEDTLS_ERR_SSL_PEER_CLOSE_NOTIFY == len) {
                 err_code = DTLS_PEER_CLOSE_NOTIFY;
-                DTLS_INFO("The DTLS session was closed by peer\r\n");
+                LOG_I("The DTLS session was closed by peer");
             } else if (MBEDTLS_ERR_SSL_TIMEOUT == len) {
                 err_code = DTLS_SUCCESS;
-                DTLS_TRC("DTLS recv timeout\r\n");
+                LOG_D("DTLS recv timeout");
             } else {
-                DTLS_TRC("mbedtls_ssl_read error result (-0x%04x)\r\n", len);
+                LOG_E("mbedtls_ssl_read error result (-0x%04x)", len);
             }
         }
     }
@@ -356,5 +359,4 @@ unsigned int HAL_DTLSSession_free(DTLSContext *context)
     return DTLS_INVALID_PARAM;
 }
 
-
-#endif
+#endif /* COAP_DTLS_SUPPORT */

+ 232 - 0
samples/coap/coap_example.c

@@ -0,0 +1,232 @@
+/*
+ * 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"
+
+#include "rtthread.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");
+}
+
+static int coap_example_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;
+}
+#ifdef FINSH_USING_MSH
+MSH_CMD_EXPORT_ALIAS(coap_example_main, ali_coap_sample, ali coap sample);
+#endif