jollen / blog

Jollen's Blog
http://www.jollen.org/blog
66 stars 4 forks source link

How to build a CoAP message and send it to Internet on ESP8266 #2

Closed jollen closed 8 years ago

jollen commented 8 years ago

延續 在 NodeMCU 上使用 er-coap-13 的介紹,使用 er-coap-13 來建立 CoAP 封包的完整寫法如下:

// 引入 er-coap-13 APIs
#include "er-coap-13.h"
#include "er-coap-13-transactions.h"

int main()
{
// 宣告 CoAP packet
coap_packet_t request[1];

// 將 CoAP packet 初始化為 COAP_TYPE_CON 類型,並使用 HTTP POST
coap_init_message(request, COAP_TYPE_CON, COAP_POST, 0);

// 初始化 CoAP headers,填寫 CoAP header 的 Uri Path 與 Uri Host
coap_set_header_uri_path(request, 'object/123456/send');
coap_set_header_uri_host(request, 'wot.city');

// 加入 payload(本文)
const char *payload = "{}";
coap_set_payload(request, (uint8_t *)payload, strlen(payload));
}

Message ID

CoAP 封包必須指定 Message ID(MID),MID 有許多用途,例如:用來做 Duplicate Rejection1。取得 MID 的方式是呼叫 er-coap-13 的 _coap_getmid 函數:

request->mid = coap_get_mid();

參考文件

jollen commented 8 years ago

Introducing rtos-wot

rtos-wot is an open source FreeRTOS distribution for ESP8266 WiFi module. It aims to conform the W3C web of things framework and is heavily based on esp-open-rtos.

The development is still in progress.

CoAP Library

libcoap of Contiki was fully ported to rtos-wot project. The following steps explains how to construct a CoAP message and transmit it to Internet with lwip.

1. Include necessary header files.

#include "er-coap-13.h"
#include "er-coap-13-transactions.h"

2. Prepare and initialize a CoAP packet.

coap_packet_t request[1];
coap_init_message(request, COAP_TYPE_CON, COAP_POST, 0);

In the example, the packet is initialized to _COAP_TYPECON type and POST method.

3. Fill CoAP headers.

coap_set_header_uri_path(request, '/object/123456/send');
coap_set_header_uri_host(request, 'wot.city');

In the example, the packet headers was filled with both server URI path and server host.

4. Set the payload.

const char *payload = "{}";
coap_set_payload(request, (uint8_t *)payload, strlen(payload));

The payload is the message context. In the example, the payload is an empty JSON object.

5. Get message ID

request->mid = coap_get_mid();

6. Serialize CoAP message

coap_transaction_t *transaction = coap_new_transaction(request->mid, &ipaddr, uri->port);
transaction->packet_len = coap_serialize_message(request, transaction->packet);

7. Final step

After serializing the CoAP message, the final CoAP packet is sotred at transaction->packet. The final step is to call lwip APIs to create a UDP socket and send out the serialized message. For example, assume that the server was connected via local socket s.

write(s, transaction->packet, transaction->packet_len);

CoAP is basis of web of things framework. For push pattern of WoT, the TD (thing description) can be serialized in CoAP binary format.

Put together

Please refer to coap_send for how to put all things together.