jollen.org

Jollen 的 Blog
Jollen's email: jollen # jollen.org
more:  Jollen's Training

How to build a CoAP message and send it to Internet using FreeRTOS on ESP8266.

.作者:jollen/
.日期:January 27, 2016 11:58 PM


How to build a CoAP message and send it to Internet using FreeRTOS on ESP8266.

Please follow this link if you are unable to read this article.

Abstraction

This article describes how to build a CoAP message by er-coap-13 APIs. er-coap-13 is a high-level CoAP library of Contiki operating system. This article will introduce rtos-wot project which is based on esp-open-rtos from SuperHouse.

With rtos-wot, you are able to build CoAP messages with FreeRTOS and send them over ESP8266 WiFi module.

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 has already been ported to rtos-wot project. The following steps explains how to build a CoAP message and send it to Internet over ESP8266 wifi module.

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_TYPE_CON 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 stored at transaction->packet field. 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.

Reports and Discussion

Tags:

純手工打造說明:技術專欄文章為 Jollen 原創,內容皆為人工撰寫,無 AI 生成。轉載請註明出處與作者,並全文引用。轉載時請在文章開頭或結尾明顯處註明「本文出處:https://www.jollen.org,已取得原作者同意並授權使用。」
訂閱電子報:不定期 Jollen's Blog 精選文章隨 Moko365 電子報寄送;請透過 Moko365 電子報訂閱(可隨時取消)。

Copyright(c) 2001–2016 www.jollen.org. All rights reserved.
Last update: 2026-07-22