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
- Bug reports of this article: https://github.com/jollen/blog/issues/2
- Discussion group: https://www.facebook.com/groups/wotcity/
Tags: