1
0
mirror of https://github.com/RIOT-OS/RIOT.git synced 2024-12-29 04:50:03 +01:00

gcoap: CLI example

This commit is contained in:
Ken Bannister 2016-10-29 15:24:06 -04:00
parent f3431fb49e
commit 1783c9c672
7 changed files with 554 additions and 0 deletions

61
examples/gcoap/Makefile Normal file
View File

@ -0,0 +1,61 @@
# Default Makefile, for host native networking
# name of your application
APPLICATION = gcoap
# If no BOARD is found in the environment, use this default:
BOARD ?= native
# This has to be the absolute path to the RIOT base directory:
RIOTBASE ?= $(CURDIR)/../..
BOARD_INSUFFICIENT_MEMORY := chronos msb-430 msb-430h nucleo-f030 nucleo-f334 \
stm32f0discovery telosb weio wsn430-v1_3b wsn430-v1_4 \
z1
# Must read nordic_softdevice_ble package before nanocoap package. However,
# can't read it explicitly here because it is read later, as a dependency for
# the nrf52dk board.
BOARD_BLACKLIST := nrf52dk
## Uncomment to redefine port, for example use 61616 for RFC 6282 UDP compression.
#GCOAP_PORT = 5683
#CFLAGS += -DGCOAP_PORT=$(GCOAP_PORT)
## Uncomment to redefine request token length, max 8.
#GCOAP_TOKENLEN = 2
#CFLAGS += -DGCOAP_TOKENLEN=$(GCOAP_TOKENLEN)
USEPKG += nanocoap
# Required by nanocoap, but only due to issue #5959.
USEMODULE += posix
# Required by nanocoap to compile nanocoap_sock.
USEMODULE += gnrc_sock_udp
# Include packages that pull up and auto-init the link layer.
# NOTE: 6LoWPAN will be included if IEEE802.15.4 devices are present
USEMODULE += gnrc_netdev_default
USEMODULE += auto_init_gnrc_netif
# Specify the mandatory networking modules
USEMODULE += gnrc_ipv6_default
USEMODULE += gcoap
# Additional networking modules that can be dropped if not needed
USEMODULE += gnrc_icmpv6_echo
# Required by gcoap example
USEMODULE += od
USEMODULE += fmt
# Add also the shell, some shell commands
USEMODULE += shell
USEMODULE += shell_commands
USEMODULE += ps
# Comment this out to disable code in RIOT that does safety checking
# which is not needed in a production environment but helps in the
# development process:
CFLAGS += -DDEVELHELP
# Change this to 0 show compiler invocation lines by default:
QUIET ?= 1
include $(RIOTBASE)/Makefile.include

View File

@ -0,0 +1,84 @@
# Border router Makefile for SLIP based networking
# Assumes use of SAMR21 board
# name of your application
APPLICATION = gcoap
# If no BOARD is found in the environment, use this default:
BOARD ?= samr21-xpro
# This has to be the absolute path to the RIOT base directory:
RIOTBASE ?= $(CURDIR)/../..
BOARD_INSUFFICIENT_MEMORY := chronos msb-430 msb-430h nucleo-f030 nucleo-f334 \
stm32f0discovery telosb weio wsn430-v1_3b wsn430-v1_4 \
z1
# Must read nordic_softdevice_ble package before nanocoap package. However,
# can't read it explicitly here because it is read later, as a dependency for
# the nrf52dk board.
BOARD_BLACKLIST := nrf52dk
# Redefine port, for example use 61616 for RFC 6282 UDP compression.
#GCOAP_PORT = 5683
#CFLAGS += -DGCOAP_PORT=$(GCOAP_PORT)
# Redefine request token length, max 8.
#GCOAP_TOKENLEN = 2
#CFLAGS += -DGCOAP_TOKENLEN=$(GCOAP_TOKENLEN)
# Border router requirements
ifeq (,$(SLIP_UART))
# set default (last available UART)
SLIP_UART="(UART_NUMOF-1)"
endif
ifeq (,$(SLIP_BAUDRATE))
# set default
SLIP_BAUDRATE=115200
endif
GNRC_NETIF_NUMOF := 2
INCLUDES += -I$(CURDIR)
CFLAGS += -DSLIP_UART=$(SLIP_UART)
CFLAGS += -DSLIP_BAUDRATE=$(SLIP_BAUDRATE)
USEPKG += nanocoap
# Required by nanocoap, but only due to issue #5959.
USEMODULE += posix
# Required by nanocoap to compile nanocoap_sock.
USEMODULE += gnrc_sock_udp
# Include packages that pull up and auto-init the link layer.
# NOTE: 6LoWPAN will be included if IEEE802.15.4 devices are present
USEMODULE += gnrc_netdev_default
USEMODULE += auto_init_gnrc_netif
# Specify the mandatory networking modules
USEMODULE += gcoap
# Add a routing protocol
USEMODULE += gnrc_rpl
# Border router requirements
# Include SLIP package for IP over Serial communication
USEMODULE += gnrc_slip
# Specify the mandatory networking modules for 6LoWPAN border router
USEMODULE += gnrc_sixlowpan_border_router_default
# Additional networking modules that can be dropped if not needed
USEMODULE += gnrc_icmpv6_echo
# Required by gcoap example
USEMODULE += od
USEMODULE += fmt
# Add also the shell, some shell commands
USEMODULE += shell
USEMODULE += shell_commands
USEMODULE += ps
# Comment this out to disable code in RIOT that does safety checking
# which is not needed in a production environment but helps in the
# development process:
CFLAGS += -DDEVELHELP
# Change this to 0 show compiler invocation lines by default:
QUIET ?= 1
include $(RIOTBASE)/Makefile.include

View File

@ -0,0 +1,67 @@
`Makefile.slip` assumes use of a SAMR21 Xplained Pro. This file describes how we use the board as a border router. See the [SLIP instructions][1] for the gnrc_border_router example for more background.
## Background -- Building
Build commands, for reference:
make clean BOARD="samr21-xpro"
# Use -f only for border router!
make -f Makefile.slip BOARD="samr21-xpro"
../../dist/tools/usb-serial/list-ttys.sh
# Use -f only for border router!
make -f Makefile.slip flash BOARD="samr21-xpro" SERIAL="???"
make term BOARD="samr21-xpro" PORT="/dev/ttyACM???"
## USB serial port
The USB serial port requires a USB-TTL converter cable with 3.3 V output.
Pin connections for SAMR21 board:
* PA23 (RX) -- TXD wire
* PA22 (TX) -- RXD wire
* GND -- GND wire
## Network configuration
We will define two networks:
1. `bbbb` Between Border Router (BR) and Ubuntu host over TUN
2. `aaaa` Between RIOT router node and BR over 6LoWPAN
We include two approaches to configuration below, automated via RPL, and manual via fib.
First, define a TUN interface on an Ubuntu host with tunslip, in the `dist/tools/tunslip` directory. In the example below, the tun interface is host 1.
cd ../../dist/tools/tunslip/
sudo ./tunslip6 -s ttyUSB0 -t tun0 bbbb::1/64
sudo ip -6 route add aaaa::/64 dev tun0
### RPL-based configuration
Configure the interface to the `bbbb` network on the BR from the RIOT terminal. The example commands below assume SLIP is on interface 8.
# Set address for SLIP interface
ifconfig 8 add unicast bbbb::2/64
# Add the Ubuntu host to the neighbor cache
ncache add 8 bbbb::1
Next configure the interface for the `aaaa` network on the BR. Strictly speaking, it is not necessary to define this address. However, it is convenient for typing, because RIOT automatically creates a more verbose address based on the MAC address for the interface.
ifconfig 7 add unicast aaaa::1/64
rpl init 7
Next, configure the interface on the `aaaa` network on the RIOT router mote.
ifconfig 7 add unicast aaaa::2/64
rpl init 7
Finally, set the BR as the RPL DAG root.
rpl root 1 aaaa::1
Ping the TUN interface from the router mote, via the BR:
ping6 bbbb::1
[1]: https://github.com/RIOT-OS/RIOT/tree/master/examples/gnrc_border_router "SLIP instructions"

69
examples/gcoap/README.md Normal file
View File

@ -0,0 +1,69 @@
# gcoap Example
This application provides command line access to gcoap, a GNRC implementation of CoAP. See the [CoAP spec][1] for background, and the Modules>Networking>GNRC>CoAP topic in the source documentation for the structure of the implementation.
We support two setup options for this example:
### Native networking
Build with the standard `Makefile`. Follow the setup [instructions][2] for the gnrc_networking example.
### SLIP-based border router
Build with `Makefile.slip`. Follow the setup instructions in README-slip.md, which are based on the [SLIP instructions][3] for the gnrc_border_router example. We also plan to provide or reference the ethos/UHCP instructions, but we don't have it working yet.
## Current Status
gcoap includes server and client capability. Available features include:
* Server and Client provide helper functions for writing the response/request. See the CoAP topic in the source documentation for details. See the gcoap example for sample implementations.
* Server allows an application to register a 'listener', which includes an array of endpoint paths and function callbacks used to write a response.
* Server listens on a port at startup; defaults to 5683.
* Client operates asynchronously; sends request and then handles response in a user provided callback. Also executes callback on timeout.
* Client generates token; length defined at compile time.
* Message Type: Supports non-confirmable (NON) messaging.
* Options: Supports Content-Format for response payload.
## Example Use
This example uses gcoap as a server on RIOT native. Then we send a request from a libcoap example client on the Linux host.
### Verify setup from RIOT terminal
> coap info
Expected response:
CoAP server is listening on port 5683
CLI requests sent: 0
CoAP open requests: 0
### Query from libcoap example client
gcoap does not provide any output to the CoAP terminal when it handles a request. We recommend use of Wireshark to see the request and response. You also can add some debug output in the endpoint function callback.
./coap-client -N -m get -p 5683 coap://[fe80::1843:8eff:fe40:4eaa%tap0]/.well-known/core
Example response:
v:1 t:NON c:GET i:0daa {} [ ]
</cli/stats>
The response shows the endpoint registered by the gcoap CLI example.
### Send query to libcoap example server
Start the libcoap example server with the command below.
./coap-server
Enter the query below in the RIOT CLI.
> coap get fe80::d8b8:65ff:feee:121b 5683 /.well-known/core
CLI output:
gcoap_cli: sending msg ID 743, 75 bytes
> gcoap: response Success, code 2.05, 105 bytes
</>;title="General Info";ct=0,</time>;if="clock";rt="Ticks";title="Internal Clock";ct=0;obs,</async>;ct=0
[1]: https://tools.ietf.org/html/rfc7252 "CoAP spec"
[2]: https://github.com/RIOT-OS/RIOT/tree/master/examples/gnrc_networking "instructions"
[3]: https://github.com/RIOT-OS/RIOT/tree/master/examples/gnrc_border_router "SLIP instructions"

181
examples/gcoap/gcoap_cli.c Normal file
View File

@ -0,0 +1,181 @@
/*
* Copyright (c) 2015-2016 Ken Bannister. All rights reserved.
*
* This file is subject to the terms and conditions of the GNU Lesser
* General Public License v2.1. See the file LICENSE in the top level
* directory for more details.
*/
/**
* @ingroup examples
* @{
*
* @file
* @brief gcoap CLI support
*
* @author Ken Bannister <kb2ma@runbox.com>
*
* @}
*/
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "net/gnrc/coap.h"
#include "od.h"
#include "fmt.h"
static void _resp_handler(unsigned req_state, coap_pkt_t* pdu);
static ssize_t _stats_handler(coap_pkt_t* pdu, uint8_t *buf, size_t len);
/* CoAP resources */
static const coap_resource_t _resources[] = {
{ "/cli/stats", COAP_GET, _stats_handler },
};
static gcoap_listener_t _listener = {
(coap_resource_t *)&_resources[0],
sizeof(_resources) / sizeof(_resources[0]),
NULL
};
/* Counts requests sent by CLI. */
static uint16_t req_count = 0;
/*
* Response callback.
*/
static void _resp_handler(unsigned req_state, coap_pkt_t* pdu)
{
if (req_state == GCOAP_MEMO_TIMEOUT) {
printf("gcoap: timeout for msg ID %02u\n", coap_get_id(pdu));
return;
}
else if (req_state == GCOAP_MEMO_ERR) {
printf("gcoap: error in response\n");
return;
}
char *class_str = (coap_get_code_class(pdu) == COAP_CLASS_SUCCESS)
? "Success" : "Error";
printf("gcoap: response %s, code %1u.%02u", class_str,
coap_get_code_class(pdu),
coap_get_code_detail(pdu));
if (pdu->payload_len) {
if (pdu->content_type == COAP_FORMAT_TEXT
|| pdu->content_type == COAP_FORMAT_LINK
|| coap_get_code_class(pdu) == COAP_CLASS_CLIENT_FAILURE
|| coap_get_code_class(pdu) == COAP_CLASS_SERVER_FAILURE) {
/* Expecting diagnostic payload in failure cases */
printf(", %u bytes\n%.*s\n", pdu->payload_len, pdu->payload_len,
(char *)pdu->payload);
}
else {
printf(", %u bytes\n", pdu->payload_len);
od_hex_dump(pdu->payload, pdu->payload_len, OD_WIDTH_DEFAULT);
}
}
else {
printf(", empty payload\n");
}
}
/*
* Server callback for /cli/stats. Returns the count of packets sent by the
* CLI.
*/
static ssize_t _stats_handler(coap_pkt_t* pdu, uint8_t *buf, size_t len)
{
gcoap_resp_init(pdu, buf, len, COAP_CODE_CONTENT);
size_t payload_len = fmt_u16_dec((char *)pdu->payload, req_count);
return gcoap_finish(pdu, payload_len, COAP_FORMAT_TEXT);
}
static size_t _send(uint8_t *buf, size_t len, char *addr_str, char *port_str)
{
ipv6_addr_t addr;
uint16_t port;
size_t bytes_sent;
/* parse destination address */
if (ipv6_addr_from_str(&addr, addr_str) == NULL) {
puts("gcoap_cli: unable to parse destination address");
return 0;
}
/* parse port */
port = (uint16_t)atoi(port_str);
if (port == 0) {
puts("gcoap_cli: unable to parse destination port");
return 0;
}
bytes_sent = gcoap_req_send(buf, len, &addr, port, _resp_handler);
if (bytes_sent > 0) {
req_count++;
}
return bytes_sent;
}
int gcoap_cli_cmd(int argc, char **argv)
{
/* Ordered like the RFC method code numbers, but off by 1. GET is code 0. */
char *method_codes[] = {"get", "post", "put"};
uint8_t buf[GCOAP_PDU_BUF_SIZE];
coap_pkt_t pdu;
size_t len;
if (argc == 1) {
/* show help for main commands */
goto end;
}
for (size_t i = 0; i < sizeof(method_codes) / sizeof(char*); i++) {
if (strcmp(argv[1], method_codes[i]) == 0) {
if (argc == 5 || argc == 6) {
if (argc == 6) {
gcoap_req_init(&pdu, &buf[0], GCOAP_PDU_BUF_SIZE, i+1, argv[4]);
memcpy(pdu.payload, argv[5], strlen(argv[5]));
len = gcoap_finish(&pdu, strlen(argv[5]), COAP_FORMAT_TEXT);
}
else {
len = gcoap_request(&pdu, &buf[0], GCOAP_PDU_BUF_SIZE, i+1,
argv[4]);
}
printf("gcoap_cli: sending msg ID %u, %u bytes\n", coap_get_id(&pdu),
(unsigned) len);
if (!_send(&buf[0], len, argv[2], argv[3])) {
puts("gcoap_cli: msg send failed");
}
return 0;
}
else {
printf("usage: %s <get|post|put> <addr> <port> <path> [data]\n",
argv[0]);
return 1;
}
}
}
if (strcmp(argv[1], "info") == 0) {
if (argc == 2) {
uint8_t open_reqs;
gcoap_op_state(&open_reqs);
printf("CoAP server is listening on port %u\n", GCOAP_PORT);
printf(" CLI requests sent: %u\n", req_count);
printf("CoAP open requests: %u\n", open_reqs);
return 0;
}
}
end:
printf("usage: %s <get|post|put|info>\n", argv[0]);
return 1;
}
void gcoap_cli_init(void)
{
gcoap_register_listener(&_listener);
}

53
examples/gcoap/main.c Normal file
View File

@ -0,0 +1,53 @@
/*
* Copyright (c) 2015-2016 Ken Bannister. All rights reserved.
*
* This file is subject to the terms and conditions of the GNU Lesser
* General Public License v2.1. See the file LICENSE in the top level
* directory for more details.
*/
/**
* @ingroup examples
* @{
*
* @file
* @brief gcoap example
*
* @author Ken Bannister <kb2ma@runbox.com>
*
* @}
*/
#include <stdio.h>
#include "msg.h"
#include "net/gnrc/coap.h"
#include "kernel_types.h"
#include "shell.h"
#define MAIN_QUEUE_SIZE (4)
static msg_t _main_msg_queue[MAIN_QUEUE_SIZE];
extern int gcoap_cli_cmd(int argc, char **argv);
extern void gcoap_cli_init(void);
static const shell_command_t shell_commands[] = {
{ "coap", "CoAP example", gcoap_cli_cmd },
{ NULL, NULL, NULL }
};
int main(void)
{
/* for the thread running the shell */
msg_init_queue(_main_msg_queue, MAIN_QUEUE_SIZE);
gcoap_cli_init();
puts("gcoap example app");
/* start shell */
puts("All up, running the shell now");
char line_buf[SHELL_DEFAULT_BUFSIZE];
shell_run(shell_commands, line_buf, SHELL_DEFAULT_BUFSIZE);
/* should never be reached */
return 0;
}

View File

@ -0,0 +1,39 @@
/*
* Copyright (C) 2015 Martine Lenders <mlenders@inf.fu-berlin.de>
*
* This file is subject to the terms and conditions of the GNU Lesser
* General Public License v2.1. See the file LICENSE in the top level
* directory for more details.
*/
/**
* @ingroup tests
* @{
*
* @file
* @brief slip parameters example, used by auto_init_gnrc_netif
*
* @author Martine Lenders <mlenders@inf.fu-berlin.de>
*/
#ifndef SLIP_PARAMS_H
#define SLIP_PARAMS_H
#include "net/gnrc/slip.h"
#ifdef __cplusplus
extern "C" {
#endif
static gnrc_slip_params_t gnrc_slip_params[] = {
{
.uart = SLIP_UART,
.baudrate = SLIP_BAUDRATE,
},
};
#ifdef __cplusplus
}
#endif
#endif /* SLIP_PARAMS_H */
/** @} */