Used Uncrustify and fixed Travis build errors.

This commit is contained in:
Lars Schmertmann 2014-04-22 10:31:43 +02:00 committed by Matthias Kovatsch
parent 3dd5bd7a37
commit bb737f85ae
50 changed files with 7115 additions and 7071 deletions

148
apps/er-coap/er-coap-conf.h Executable file → Normal file
View file

@ -1,74 +1,74 @@
/*
* Copyright (c) 2013, Institute for Pervasive Computing, ETH Zurich
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name of the Institute nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*
* This file is part of the Contiki operating system.
*/
/**
* \file
* Collection of default configuration values.
* \author
* Matthias Kovatsch <kovatsch@inf.ethz.ch>
*/
#ifndef ER_COAP_CONF_H_
#define ER_COAP_CONF_H_
/* Features that can be disabled to achieve smaller memory footprint */
#define COAP_LINK_FORMAT_FILTERING 0
#define COAP_PROXY_OPTION_PROCESSING 0
/* Listening port for the CoAP REST Engine */
#ifndef COAP_SERVER_PORT
#define COAP_SERVER_PORT COAP_DEFAULT_PORT
#endif
/* The number of concurrent messages that can be stored for retransmission in the transaction layer. */
#ifndef COAP_MAX_OPEN_TRANSACTIONS
#define COAP_MAX_OPEN_TRANSACTIONS 4
#endif /* COAP_MAX_OPEN_TRANSACTIONS */
/* Maximum number of failed request attempts before action */
#ifndef COAP_MAX_ATTEMPTS
#define COAP_MAX_ATTEMPTS 4
#endif /* COAP_MAX_ATTEMPTS */
/* Conservative size limit, as not all options have to be set at the same time. Check when Proxy-Uri option is used */
#ifndef COAP_MAX_HEADER_SIZE /* Hdr CoF If-Match Obs Blo strings */
#define COAP_MAX_HEADER_SIZE (4 + COAP_TOKEN_LEN + 3 + 1+COAP_ETAG_LEN + 4 + 4 + 30) /* 65 */
#endif /* COAP_MAX_HEADER_SIZE */
/* Number of observer slots (each takes abot xxx bytes) */
#ifndef COAP_MAX_OBSERVERS
#define COAP_MAX_OBSERVERS COAP_MAX_OPEN_TRANSACTIONS-1
#endif /* COAP_MAX_OBSERVERS */
/* Interval in seconds in which NON notifies are changed to CON notifies to check client. */
#define COAP_OBSERVE_REFRESH_INTERVAL 60
#endif /* ER_COAP_CONF_H_ */
/*
* Copyright (c) 2013, Institute for Pervasive Computing, ETH Zurich
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name of the Institute nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*
* This file is part of the Contiki operating system.
*/
/**
* \file
* Collection of default configuration values.
* \author
* Matthias Kovatsch <kovatsch@inf.ethz.ch>
*/
#ifndef ER_COAP_CONF_H_
#define ER_COAP_CONF_H_
/* Features that can be disabled to achieve smaller memory footprint */
#define COAP_LINK_FORMAT_FILTERING 0
#define COAP_PROXY_OPTION_PROCESSING 0
/* Listening port for the CoAP REST Engine */
#ifndef COAP_SERVER_PORT
#define COAP_SERVER_PORT COAP_DEFAULT_PORT
#endif
/* The number of concurrent messages that can be stored for retransmission in the transaction layer. */
#ifndef COAP_MAX_OPEN_TRANSACTIONS
#define COAP_MAX_OPEN_TRANSACTIONS 4
#endif /* COAP_MAX_OPEN_TRANSACTIONS */
/* Maximum number of failed request attempts before action */
#ifndef COAP_MAX_ATTEMPTS
#define COAP_MAX_ATTEMPTS 4
#endif /* COAP_MAX_ATTEMPTS */
/* Conservative size limit, as not all options have to be set at the same time. Check when Proxy-Uri option is used */
#ifndef COAP_MAX_HEADER_SIZE /* Hdr CoF If-Match Obs Blo strings */
#define COAP_MAX_HEADER_SIZE (4 + COAP_TOKEN_LEN + 3 + 1 + COAP_ETAG_LEN + 4 + 4 + 30) /* 65 */
#endif /* COAP_MAX_HEADER_SIZE */
/* Number of observer slots (each takes abot xxx bytes) */
#ifndef COAP_MAX_OBSERVERS
#define COAP_MAX_OBSERVERS COAP_MAX_OPEN_TRANSACTIONS - 1
#endif /* COAP_MAX_OBSERVERS */
/* Interval in seconds in which NON notifies are changed to CON notifies to check client. */
#define COAP_OBSERVE_REFRESH_INTERVAL 60
#endif /* ER_COAP_CONF_H_ */

330
apps/er-coap/er-coap-constants.h Executable file → Normal file
View file

@ -1,165 +1,165 @@
/*
* Copyright (c) 2013, Institute for Pervasive Computing, ETH Zurich
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name of the Institute nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*
* This file is part of the Contiki operating system.
*/
/**
* \file
* Collection of constants specified in the CoAP standard.
* \author
* Matthias Kovatsch <kovatsch@inf.ethz.ch>
*/
#ifndef ER_COAP_CONSTANTS_H_
#define ER_COAP_CONSTANTS_H_
#define COAP_DEFAULT_PORT 5683
#define COAP_DEFAULT_MAX_AGE 60
#define COAP_RESPONSE_TIMEOUT 3
#define COAP_RESPONSE_RANDOM_FACTOR 1.5
#define COAP_MAX_RETRANSMIT 4
#define COAP_HEADER_LEN 4 /* | version:0x03 type:0x0C tkl:0xF0 | code | mid:0x00FF | mid:0xFF00 | */
#define COAP_TOKEN_LEN 8 /* The maximum number of bytes for the Token */
#define COAP_ETAG_LEN 8 /* The maximum number of bytes for the ETag */
#define COAP_HEADER_VERSION_MASK 0xC0
#define COAP_HEADER_VERSION_POSITION 6
#define COAP_HEADER_TYPE_MASK 0x30
#define COAP_HEADER_TYPE_POSITION 4
#define COAP_HEADER_TOKEN_LEN_MASK 0x0F
#define COAP_HEADER_TOKEN_LEN_POSITION 0
#define COAP_HEADER_OPTION_DELTA_MASK 0xF0
#define COAP_HEADER_OPTION_SHORT_LENGTH_MASK 0x0F
/* CoAP message types */
typedef enum {
COAP_TYPE_CON, /* confirmables */
COAP_TYPE_NON, /* non-confirmables */
COAP_TYPE_ACK, /* acknowledgements */
COAP_TYPE_RST /* reset */
} coap_message_type_t;
/* CoAP request method codes */
typedef enum {
COAP_GET = 1,
COAP_POST,
COAP_PUT,
COAP_DELETE
} coap_method_t;
/* CoAP response codes */
typedef enum {
NO_ERROR = 0,
CREATED_2_01 = 65, /* CREATED */
DELETED_2_02 = 66, /* DELETED */
VALID_2_03 = 67, /* NOT_MODIFIED */
CHANGED_2_04 = 68, /* CHANGED */
CONTENT_2_05 = 69, /* OK */
BAD_REQUEST_4_00 = 128, /* BAD_REQUEST */
UNAUTHORIZED_4_01 = 129, /* UNAUTHORIZED */
BAD_OPTION_4_02 = 130, /* BAD_OPTION */
FORBIDDEN_4_03 = 131, /* FORBIDDEN */
NOT_FOUND_4_04 = 132, /* NOT_FOUND */
METHOD_NOT_ALLOWED_4_05 = 133, /* METHOD_NOT_ALLOWED */
NOT_ACCEPTABLE_4_06 = 134, /* NOT_ACCEPTABLE */
PRECONDITION_FAILED_4_12 = 140, /* BAD_REQUEST */
REQUEST_ENTITY_TOO_LARGE_4_13 = 141, /* REQUEST_ENTITY_TOO_LARGE */
UNSUPPORTED_MEDIA_TYPE_4_15 = 143, /* UNSUPPORTED_MEDIA_TYPE */
INTERNAL_SERVER_ERROR_5_00 = 160, /* INTERNAL_SERVER_ERROR */
NOT_IMPLEMENTED_5_01 = 161, /* NOT_IMPLEMENTED */
BAD_GATEWAY_5_02 = 162, /* BAD_GATEWAY */
SERVICE_UNAVAILABLE_5_03 = 163, /* SERVICE_UNAVAILABLE */
GATEWAY_TIMEOUT_5_04 = 164, /* GATEWAY_TIMEOUT */
PROXYING_NOT_SUPPORTED_5_05 = 165, /* PROXYING_NOT_SUPPORTED */
/* Erbium errors */
MEMORY_ALLOCATION_ERROR = 192,
PACKET_SERIALIZATION_ERROR,
/* Erbium hooks */
MANUAL_RESPONSE,
PING_RESPONSE
} coap_status_t;
/* CoAP header option numbers */
typedef enum {
COAP_OPTION_IF_MATCH = 1, /* 0-8 B */
COAP_OPTION_URI_HOST = 3, /* 1-255 B */
COAP_OPTION_ETAG = 4, /* 1-8 B */
COAP_OPTION_IF_NONE_MATCH = 5, /* 0 B */
COAP_OPTION_OBSERVE = 6, /* 0-3 B */
COAP_OPTION_URI_PORT = 7, /* 0-2 B */
COAP_OPTION_LOCATION_PATH = 8, /* 0-255 B */
COAP_OPTION_URI_PATH = 11, /* 0-255 B */
COAP_OPTION_CONTENT_FORMAT = 12, /* 0-2 B */
COAP_OPTION_MAX_AGE = 14, /* 0-4 B */
COAP_OPTION_URI_QUERY = 15, /* 0-255 B */
COAP_OPTION_ACCEPT = 17, /* 0-2 B */
COAP_OPTION_LOCATION_QUERY = 20, /* 0-255 B */
COAP_OPTION_BLOCK2 = 23, /* 1-3 B */
COAP_OPTION_BLOCK1 = 27, /* 1-3 B */
COAP_OPTION_SIZE2 = 28, /* 0-4 B */
COAP_OPTION_PROXY_URI = 35, /* 1-1034 B */
COAP_OPTION_PROXY_SCHEME = 39, /* 1-255 B */
COAP_OPTION_SIZE1 = 60, /* 0-4 B */
} coap_option_t;
/* CoAP Content-Formats */
typedef enum {
TEXT_PLAIN = 0,
TEXT_XML = 1,
TEXT_CSV = 2,
TEXT_HTML = 3,
IMAGE_GIF = 21,
IMAGE_JPEG = 22,
IMAGE_PNG = 23,
IMAGE_TIFF = 24,
AUDIO_RAW = 25,
VIDEO_RAW = 26,
APPLICATION_LINK_FORMAT = 40,
APPLICATION_XML = 41,
APPLICATION_OCTET_STREAM = 42,
APPLICATION_RDF_XML = 43,
APPLICATION_SOAP_XML = 44,
APPLICATION_ATOM_XML = 45,
APPLICATION_XMPP_XML = 46,
APPLICATION_EXI = 47,
APPLICATION_FASTINFOSET = 48,
APPLICATION_SOAP_FASTINFOSET = 49,
APPLICATION_JSON = 50,
APPLICATION_X_OBIX_BINARY = 51
} coap_content_format_t;
#endif /* ER_COAP_CONSTANTS_H_ */
/*
* Copyright (c) 2013, Institute for Pervasive Computing, ETH Zurich
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name of the Institute nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*
* This file is part of the Contiki operating system.
*/
/**
* \file
* Collection of constants specified in the CoAP standard.
* \author
* Matthias Kovatsch <kovatsch@inf.ethz.ch>
*/
#ifndef ER_COAP_CONSTANTS_H_
#define ER_COAP_CONSTANTS_H_
#define COAP_DEFAULT_PORT 5683
#define COAP_DEFAULT_MAX_AGE 60
#define COAP_RESPONSE_TIMEOUT 3
#define COAP_RESPONSE_RANDOM_FACTOR 1.5
#define COAP_MAX_RETRANSMIT 4
#define COAP_HEADER_LEN 4 /* | version:0x03 type:0x0C tkl:0xF0 | code | mid:0x00FF | mid:0xFF00 | */
#define COAP_TOKEN_LEN 8 /* The maximum number of bytes for the Token */
#define COAP_ETAG_LEN 8 /* The maximum number of bytes for the ETag */
#define COAP_HEADER_VERSION_MASK 0xC0
#define COAP_HEADER_VERSION_POSITION 6
#define COAP_HEADER_TYPE_MASK 0x30
#define COAP_HEADER_TYPE_POSITION 4
#define COAP_HEADER_TOKEN_LEN_MASK 0x0F
#define COAP_HEADER_TOKEN_LEN_POSITION 0
#define COAP_HEADER_OPTION_DELTA_MASK 0xF0
#define COAP_HEADER_OPTION_SHORT_LENGTH_MASK 0x0F
/* CoAP message types */
typedef enum {
COAP_TYPE_CON, /* confirmables */
COAP_TYPE_NON, /* non-confirmables */
COAP_TYPE_ACK, /* acknowledgements */
COAP_TYPE_RST /* reset */
} coap_message_type_t;
/* CoAP request method codes */
typedef enum {
COAP_GET = 1,
COAP_POST,
COAP_PUT,
COAP_DELETE
} coap_method_t;
/* CoAP response codes */
typedef enum {
NO_ERROR = 0,
CREATED_2_01 = 65, /* CREATED */
DELETED_2_02 = 66, /* DELETED */
VALID_2_03 = 67, /* NOT_MODIFIED */
CHANGED_2_04 = 68, /* CHANGED */
CONTENT_2_05 = 69, /* OK */
BAD_REQUEST_4_00 = 128, /* BAD_REQUEST */
UNAUTHORIZED_4_01 = 129, /* UNAUTHORIZED */
BAD_OPTION_4_02 = 130, /* BAD_OPTION */
FORBIDDEN_4_03 = 131, /* FORBIDDEN */
NOT_FOUND_4_04 = 132, /* NOT_FOUND */
METHOD_NOT_ALLOWED_4_05 = 133, /* METHOD_NOT_ALLOWED */
NOT_ACCEPTABLE_4_06 = 134, /* NOT_ACCEPTABLE */
PRECONDITION_FAILED_4_12 = 140, /* BAD_REQUEST */
REQUEST_ENTITY_TOO_LARGE_4_13 = 141, /* REQUEST_ENTITY_TOO_LARGE */
UNSUPPORTED_MEDIA_TYPE_4_15 = 143, /* UNSUPPORTED_MEDIA_TYPE */
INTERNAL_SERVER_ERROR_5_00 = 160, /* INTERNAL_SERVER_ERROR */
NOT_IMPLEMENTED_5_01 = 161, /* NOT_IMPLEMENTED */
BAD_GATEWAY_5_02 = 162, /* BAD_GATEWAY */
SERVICE_UNAVAILABLE_5_03 = 163, /* SERVICE_UNAVAILABLE */
GATEWAY_TIMEOUT_5_04 = 164, /* GATEWAY_TIMEOUT */
PROXYING_NOT_SUPPORTED_5_05 = 165, /* PROXYING_NOT_SUPPORTED */
/* Erbium errors */
MEMORY_ALLOCATION_ERROR = 192,
PACKET_SERIALIZATION_ERROR,
/* Erbium hooks */
MANUAL_RESPONSE,
PING_RESPONSE
} coap_status_t;
/* CoAP header option numbers */
typedef enum {
COAP_OPTION_IF_MATCH = 1, /* 0-8 B */
COAP_OPTION_URI_HOST = 3, /* 1-255 B */
COAP_OPTION_ETAG = 4, /* 1-8 B */
COAP_OPTION_IF_NONE_MATCH = 5, /* 0 B */
COAP_OPTION_OBSERVE = 6, /* 0-3 B */
COAP_OPTION_URI_PORT = 7, /* 0-2 B */
COAP_OPTION_LOCATION_PATH = 8, /* 0-255 B */
COAP_OPTION_URI_PATH = 11, /* 0-255 B */
COAP_OPTION_CONTENT_FORMAT = 12, /* 0-2 B */
COAP_OPTION_MAX_AGE = 14, /* 0-4 B */
COAP_OPTION_URI_QUERY = 15, /* 0-255 B */
COAP_OPTION_ACCEPT = 17, /* 0-2 B */
COAP_OPTION_LOCATION_QUERY = 20, /* 0-255 B */
COAP_OPTION_BLOCK2 = 23, /* 1-3 B */
COAP_OPTION_BLOCK1 = 27, /* 1-3 B */
COAP_OPTION_SIZE2 = 28, /* 0-4 B */
COAP_OPTION_PROXY_URI = 35, /* 1-1034 B */
COAP_OPTION_PROXY_SCHEME = 39, /* 1-255 B */
COAP_OPTION_SIZE1 = 60, /* 0-4 B */
} coap_option_t;
/* CoAP Content-Formats */
typedef enum {
TEXT_PLAIN = 0,
TEXT_XML = 1,
TEXT_CSV = 2,
TEXT_HTML = 3,
IMAGE_GIF = 21,
IMAGE_JPEG = 22,
IMAGE_PNG = 23,
IMAGE_TIFF = 24,
AUDIO_RAW = 25,
VIDEO_RAW = 26,
APPLICATION_LINK_FORMAT = 40,
APPLICATION_XML = 41,
APPLICATION_OCTET_STREAM = 42,
APPLICATION_RDF_XML = 43,
APPLICATION_SOAP_XML = 44,
APPLICATION_ATOM_XML = 45,
APPLICATION_XMPP_XML = 46,
APPLICATION_EXI = 47,
APPLICATION_FASTINFOSET = 48,
APPLICATION_SOAP_FASTINFOSET = 49,
APPLICATION_JSON = 50,
APPLICATION_X_OBIX_BINARY = 51
} coap_content_format_t;
#endif /* ER_COAP_CONSTANTS_H_ */

1009
apps/er-coap/er-coap-engine.c Executable file → Normal file

File diff suppressed because it is too large Load diff

170
apps/er-coap/er-coap-engine.h Executable file → Normal file
View file

@ -1,85 +1,85 @@
/*
* Copyright (c) 2013, Institute for Pervasive Computing, ETH Zurich
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name of the Institute nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*
* This file is part of the Contiki operating system.
*/
/**
* \file
* CoAP implementation for the REST Engine.
* \author
* Matthias Kovatsch <kovatsch@inf.ethz.ch>
*/
#ifndef ER_COAP_ENGINE_H_
#define ER_COAP_ENGINE_H_
#include "pt.h"
#include "er-coap.h"
#include "er-coap-transactions.h"
#include "er-coap-observe.h"
#include "er-coap-separate.h"
#define SERVER_LISTEN_PORT UIP_HTONS(COAP_SERVER_PORT)
typedef coap_packet_t rest_request_t;
typedef coap_packet_t rest_response_t;
void coap_init_engine(void);
/*---------------------------------------------------------------------------*/
/*- Client Part -------------------------------------------------------------*/
/*---------------------------------------------------------------------------*/
struct request_state_t {
struct pt pt;
struct process *process;
coap_transaction_t *transaction;
coap_packet_t *response;
uint32_t block_num;
};
typedef void (*blocking_response_handler) (void *response);
PT_THREAD(coap_blocking_request
(struct request_state_t *state, process_event_t ev,
uip_ipaddr_t * remote_ipaddr, uint16_t remote_port,
coap_packet_t * request,
blocking_response_handler request_callback));
#define COAP_BLOCKING_REQUEST(server_addr, server_port, request, chunk_handler) \
{ \
static struct request_state_t request_state; \
PT_SPAWN(process_pt, &request_state.pt, \
coap_blocking_request(&request_state, ev, \
server_addr, server_port, \
request, chunk_handler) \
); \
}
/*---------------------------------------------------------------------------*/
#endif /* ER_COAP_ENGINE_H_ */
/*
* Copyright (c) 2013, Institute for Pervasive Computing, ETH Zurich
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name of the Institute nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*
* This file is part of the Contiki operating system.
*/
/**
* \file
* CoAP implementation for the REST Engine.
* \author
* Matthias Kovatsch <kovatsch@inf.ethz.ch>
*/
#ifndef ER_COAP_ENGINE_H_
#define ER_COAP_ENGINE_H_
#include "pt.h"
#include "er-coap.h"
#include "er-coap-transactions.h"
#include "er-coap-observe.h"
#include "er-coap-separate.h"
#define SERVER_LISTEN_PORT UIP_HTONS(COAP_SERVER_PORT)
typedef coap_packet_t rest_request_t;
typedef coap_packet_t rest_response_t;
void coap_init_engine(void);
/*---------------------------------------------------------------------------*/
/*- Client Part -------------------------------------------------------------*/
/*---------------------------------------------------------------------------*/
struct request_state_t {
struct pt pt;
struct process *process;
coap_transaction_t *transaction;
coap_packet_t *response;
uint32_t block_num;
};
typedef void (*blocking_response_handler)(void *response);
PT_THREAD(coap_blocking_request
(struct request_state_t *state, process_event_t ev,
uip_ipaddr_t *remote_ipaddr, uint16_t remote_port,
coap_packet_t *request,
blocking_response_handler request_callback));
#define COAP_BLOCKING_REQUEST(server_addr, server_port, request, chunk_handler) \
{ \
static struct request_state_t request_state; \
PT_SPAWN(process_pt, &request_state.pt, \
coap_blocking_request(&request_state, ev, \
server_addr, server_port, \
request, chunk_handler) \
); \
}
/*---------------------------------------------------------------------------*/
#endif /* ER_COAP_ENGINE_H_ */

519
apps/er-coap/er-coap-observe.c Executable file → Normal file
View file

@ -1,254 +1,265 @@
/*
* Copyright (c) 2013, Institute for Pervasive Computing, ETH Zurich
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name of the Institute nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*
* This file is part of the Contiki operating system.
*/
/**
* \file
* CoAP module for observing resources (draft-ietf-core-observe-11).
* \author
* Matthias Kovatsch <kovatsch@inf.ethz.ch>
*/
#include <stdio.h>
#include <string.h>
#include "er-coap-observe.h"
#define DEBUG DEBUG_NONE
#include "net/uip-debug.h"
/*---------------------------------------------------------------------------*/
MEMB(observers_memb, coap_observer_t, COAP_MAX_OBSERVERS);
LIST(observers_list);
/*---------------------------------------------------------------------------*/
/*- Internal API ------------------------------------------------------------*/
/*---------------------------------------------------------------------------*/
coap_observer_t *
coap_add_observer(uip_ipaddr_t * addr, uint16_t port, const uint8_t * token,
size_t token_len, const char *uri)
{
/* Remove existing observe relationship, if any. */
coap_remove_observer_by_uri(addr, port, uri);
coap_observer_t *o = memb_alloc(&observers_memb);
if(o) {
o->url = uri;
uip_ipaddr_copy(&o->addr, addr);
o->port = port;
o->token_len = token_len;
memcpy(o->token, token, token_len);
o->last_mid = 0;
PRINTF("Adding observer for /%s [0x%02X%02X]\n", o->url, o->token[0],
o->token[1]);
list_add(observers_list, o);
}
return o;
}
/*---------------------------------------------------------------------------*/
/*- Removal -----------------------------------------------------------------*/
/*---------------------------------------------------------------------------*/
void
coap_remove_observer(coap_observer_t * o)
{
PRINTF("Removing observer for /%s [0x%02X%02X]\n", o->url, o->token[0],
o->token[1]);
memb_free(&observers_memb, o);
list_remove(observers_list, o);
}
/*---------------------------------------------------------------------------*/
int
coap_remove_observer_by_client(uip_ipaddr_t * addr, uint16_t port)
{
int removed = 0;
coap_observer_t *obs = NULL;
for(obs = (coap_observer_t *) list_head(observers_list); obs;
obs = obs->next) {
PRINTF("Remove check client ");
PRINT6ADDR(addr);
PRINTF(":%u\n", port);
if(uip_ipaddr_cmp(&obs->addr, addr) && obs->port == port) {
coap_remove_observer(obs);
removed++;
}
}
return removed;
}
/*---------------------------------------------------------------------------*/
int
coap_remove_observer_by_token(uip_ipaddr_t * addr, uint16_t port,
uint8_t * token, size_t token_len)
{
int removed = 0;
coap_observer_t *obs = NULL;
for(obs = (coap_observer_t *) list_head(observers_list); obs;
obs = obs->next) {
PRINTF("Remove check Token 0x%02X%02X\n", token[0], token[1]);
if(uip_ipaddr_cmp(&obs->addr, addr) && obs->port == port
&& obs->token_len == token_len
&& memcmp(obs->token, token, token_len) == 0) {
coap_remove_observer(obs);
removed++;
}
}
return removed;
}
/*---------------------------------------------------------------------------*/
int
coap_remove_observer_by_uri(uip_ipaddr_t * addr, uint16_t port,
const char *uri)
{
int removed = 0;
coap_observer_t *obs = NULL;
for(obs = (coap_observer_t *) list_head(observers_list); obs;
obs = obs->next) {
PRINTF("Remove check URL %p\n", uri);
if((addr == NULL
|| (uip_ipaddr_cmp(&obs->addr, addr) && obs->port == port))
&& (obs->url == uri || memcmp(obs->url, uri, strlen(obs->url)) == 0)) {
coap_remove_observer(obs);
removed++;
}
}
return removed;
}
/*---------------------------------------------------------------------------*/
int
coap_remove_observer_by_mid(uip_ipaddr_t * addr, uint16_t port, uint16_t mid)
{
int removed = 0;
coap_observer_t *obs = NULL;
for(obs = (coap_observer_t *) list_head(observers_list); obs;
obs = obs->next) {
PRINTF("Remove check MID %u\n", mid);
if(uip_ipaddr_cmp(&obs->addr, addr) && obs->port == port
&& obs->last_mid == mid) {
coap_remove_observer(obs);
removed++;
}
}
return removed;
}
/*---------------------------------------------------------------------------*/
/*- Notification ------------------------------------------------------------*/
/*---------------------------------------------------------------------------*/
void
coap_notify_observers(resource_t * resource)
{
/* build notification */
coap_packet_t notification[1]; /* this way the packet can be treated as pointer as usual */
coap_init_message(notification, COAP_TYPE_NON, CONTENT_2_05, 0);
coap_observer_t *obs = NULL;
PRINTF("Observe: Notification from %s\n", resource->url);
/* iterate over observers */
for(obs = (coap_observer_t *) list_head(observers_list); obs;
obs = obs->next) {
if(obs->url == resource->url) { /* using RESOURCE url pointer as handle */
coap_transaction_t *transaction = NULL;
/*TODO implement special transaction for CON, sharing the same buffer to allow for more observers */
if((transaction =
coap_new_transaction(coap_get_mid(), &obs->addr, obs->port))) {
PRINTF(" Observer ");
PRINT6ADDR(&obs->addr);
PRINTF(":%u\n", obs->port);
/* update last MID for RST matching */
obs->last_mid = transaction->mid;
/* prepare response */
notification->mid = transaction->mid;
resource->get_handler(NULL, notification,
transaction->packet + COAP_MAX_HEADER_SIZE,
REST_MAX_CHUNK_SIZE, NULL);
if(notification->code < BAD_REQUEST_4_00)
coap_set_header_observe(notification, (obs->obs_counter)++);
coap_set_token(notification, obs->token, obs->token_len);
/* TODO use resource-specific COAP_OBSERVE_REFRESH_INTERVAL for CON to check client interest */
transaction->packet_len =
coap_serialize_message(notification, transaction->packet);
coap_send_transaction(transaction);
}
}
}
}
/*---------------------------------------------------------------------------*/
void
coap_observe_handler(resource_t * resource, void *request, void *response)
{
coap_packet_t *const coap_req = (coap_packet_t *) request;
coap_packet_t *const coap_res = (coap_packet_t *) response;
static char content[16];
if(coap_req->code == COAP_GET && coap_res->code < 128) { /* GET request and response without error code */
if(IS_OPTION(coap_req, COAP_OPTION_OBSERVE)) {
if(coap_add_observer(&UIP_IP_BUF->srcipaddr, UIP_UDP_BUF->srcport,
coap_req->token, coap_req->token_len,
resource->url)) {
coap_set_header_observe(coap_res, 0);
/*
* for demonstration purposes only. A subscription should return the same representation as a normal GET
* FIXME comment the following command for any real application
*/
coap_set_payload(coap_res,
content,
snprintf(content, sizeof(content), "Added %u/%u",
list_length(observers_list),
COAP_MAX_OBSERVERS));
} else {
coap_res->code = SERVICE_UNAVAILABLE_5_03;
coap_set_payload(coap_res, "TooManyObservers", 16);
} /* if(added observer) */
} else { /* if (observe) */
/* remove client if it is currently observe */
coap_remove_observer_by_token(&UIP_IP_BUF->srcipaddr,
UIP_UDP_BUF->srcport, coap_req->token,
coap_req->token_len);
} /* if(observe) */
}
}
/*---------------------------------------------------------------------------*/
/*
* Copyright (c) 2013, Institute for Pervasive Computing, ETH Zurich
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name of the Institute nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*
* This file is part of the Contiki operating system.
*/
/**
* \file
* CoAP module for observing resources (draft-ietf-core-observe-11).
* \author
* Matthias Kovatsch <kovatsch@inf.ethz.ch>
*/
#include <stdio.h>
#include <string.h>
#include "er-coap-observe.h"
#define DEBUG 0
#if DEBUG
#include <stdio.h>
#define PRINTF(...) printf(__VA_ARGS__)
#define PRINT6ADDR(addr) PRINTF("[%02x%02x:%02x%02x:%02x%02x:%02x%02x:%02x%02x:%02x%02x:%02x%02x:%02x%02x]", ((uint8_t *)addr)[0], ((uint8_t *)addr)[1], ((uint8_t *)addr)[2], ((uint8_t *)addr)[3], ((uint8_t *)addr)[4], ((uint8_t *)addr)[5], ((uint8_t *)addr)[6], ((uint8_t *)addr)[7], ((uint8_t *)addr)[8], ((uint8_t *)addr)[9], ((uint8_t *)addr)[10], ((uint8_t *)addr)[11], ((uint8_t *)addr)[12], ((uint8_t *)addr)[13], ((uint8_t *)addr)[14], ((uint8_t *)addr)[15])
#define PRINTLLADDR(lladdr) PRINTF("[%02x:%02x:%02x:%02x:%02x:%02x]", (lladdr)->addr[0], (lladdr)->addr[1], (lladdr)->addr[2], (lladdr)->addr[3], (lladdr)->addr[4], (lladdr)->addr[5])
#else
#define PRINTF(...)
#define PRINT6ADDR(addr)
#define PRINTLLADDR(addr)
#endif
/*---------------------------------------------------------------------------*/
MEMB(observers_memb, coap_observer_t, COAP_MAX_OBSERVERS);
LIST(observers_list);
/*---------------------------------------------------------------------------*/
/*- Internal API ------------------------------------------------------------*/
/*---------------------------------------------------------------------------*/
coap_observer_t *
coap_add_observer(uip_ipaddr_t *addr, uint16_t port, const uint8_t *token,
size_t token_len, const char *uri)
{
/* Remove existing observe relationship, if any. */
coap_remove_observer_by_uri(addr, port, uri);
coap_observer_t *o = memb_alloc(&observers_memb);
if(o) {
o->url = uri;
uip_ipaddr_copy(&o->addr, addr);
o->port = port;
o->token_len = token_len;
memcpy(o->token, token, token_len);
o->last_mid = 0;
PRINTF("Adding observer for /%s [0x%02X%02X]\n", o->url, o->token[0],
o->token[1]);
list_add(observers_list, o);
}
return o;
}
/*---------------------------------------------------------------------------*/
/*- Removal -----------------------------------------------------------------*/
/*---------------------------------------------------------------------------*/
void
coap_remove_observer(coap_observer_t *o)
{
PRINTF("Removing observer for /%s [0x%02X%02X]\n", o->url, o->token[0],
o->token[1]);
memb_free(&observers_memb, o);
list_remove(observers_list, o);
}
/*---------------------------------------------------------------------------*/
int
coap_remove_observer_by_client(uip_ipaddr_t *addr, uint16_t port)
{
int removed = 0;
coap_observer_t *obs = NULL;
for(obs = (coap_observer_t *)list_head(observers_list); obs;
obs = obs->next) {
PRINTF("Remove check client ");
PRINT6ADDR(addr);
PRINTF(":%u\n", port);
if(uip_ipaddr_cmp(&obs->addr, addr) && obs->port == port) {
coap_remove_observer(obs);
removed++;
}
}
return removed;
}
/*---------------------------------------------------------------------------*/
int
coap_remove_observer_by_token(uip_ipaddr_t *addr, uint16_t port,
uint8_t *token, size_t token_len)
{
int removed = 0;
coap_observer_t *obs = NULL;
for(obs = (coap_observer_t *)list_head(observers_list); obs;
obs = obs->next) {
PRINTF("Remove check Token 0x%02X%02X\n", token[0], token[1]);
if(uip_ipaddr_cmp(&obs->addr, addr) && obs->port == port
&& obs->token_len == token_len
&& memcmp(obs->token, token, token_len) == 0) {
coap_remove_observer(obs);
removed++;
}
}
return removed;
}
/*---------------------------------------------------------------------------*/
int
coap_remove_observer_by_uri(uip_ipaddr_t *addr, uint16_t port,
const char *uri)
{
int removed = 0;
coap_observer_t *obs = NULL;
for(obs = (coap_observer_t *)list_head(observers_list); obs;
obs = obs->next) {
PRINTF("Remove check URL %p\n", uri);
if((addr == NULL
|| (uip_ipaddr_cmp(&obs->addr, addr) && obs->port == port))
&& (obs->url == uri || memcmp(obs->url, uri, strlen(obs->url)) == 0)) {
coap_remove_observer(obs);
removed++;
}
}
return removed;
}
/*---------------------------------------------------------------------------*/
int
coap_remove_observer_by_mid(uip_ipaddr_t *addr, uint16_t port, uint16_t mid)
{
int removed = 0;
coap_observer_t *obs = NULL;
for(obs = (coap_observer_t *)list_head(observers_list); obs;
obs = obs->next) {
PRINTF("Remove check MID %u\n", mid);
if(uip_ipaddr_cmp(&obs->addr, addr) && obs->port == port
&& obs->last_mid == mid) {
coap_remove_observer(obs);
removed++;
}
}
return removed;
}
/*---------------------------------------------------------------------------*/
/*- Notification ------------------------------------------------------------*/
/*---------------------------------------------------------------------------*/
void
coap_notify_observers(resource_t *resource)
{
/* build notification */
coap_packet_t notification[1]; /* this way the packet can be treated as pointer as usual */
coap_init_message(notification, COAP_TYPE_NON, CONTENT_2_05, 0);
coap_observer_t *obs = NULL;
PRINTF("Observe: Notification from %s\n", resource->url);
/* iterate over observers */
for(obs = (coap_observer_t *)list_head(observers_list); obs;
obs = obs->next) {
if(obs->url == resource->url) { /* using RESOURCE url pointer as handle */
coap_transaction_t *transaction = NULL;
/*TODO implement special transaction for CON, sharing the same buffer to allow for more observers */
if((transaction =
coap_new_transaction(coap_get_mid(), &obs->addr, obs->port))) {
PRINTF(" Observer ");
PRINT6ADDR(&obs->addr);
PRINTF(":%u\n", obs->port);
/* update last MID for RST matching */
obs->last_mid = transaction->mid;
/* prepare response */
notification->mid = transaction->mid;
resource->get_handler(NULL, notification,
transaction->packet + COAP_MAX_HEADER_SIZE,
REST_MAX_CHUNK_SIZE, NULL);
if(notification->code < BAD_REQUEST_4_00) {
coap_set_header_observe(notification, (obs->obs_counter)++);
}
coap_set_token(notification, obs->token, obs->token_len);
/* TODO use resource-specific COAP_OBSERVE_REFRESH_INTERVAL for CON to check client interest */
transaction->packet_len =
coap_serialize_message(notification, transaction->packet);
coap_send_transaction(transaction);
}
}
}
}
/*---------------------------------------------------------------------------*/
void
coap_observe_handler(resource_t *resource, void *request, void *response)
{
coap_packet_t *const coap_req = (coap_packet_t *)request;
coap_packet_t *const coap_res = (coap_packet_t *)response;
static char content[16];
if(coap_req->code == COAP_GET && coap_res->code < 128) { /* GET request and response without error code */
if(IS_OPTION(coap_req, COAP_OPTION_OBSERVE)) {
if(coap_add_observer(&UIP_IP_BUF->srcipaddr, UIP_UDP_BUF->srcport,
coap_req->token, coap_req->token_len,
resource->url)) {
coap_set_header_observe(coap_res, 0);
/*
* for demonstration purposes only. A subscription should return the same representation as a normal GET
* FIXME comment the following command for any real application
*/
coap_set_payload(coap_res,
content,
snprintf(content, sizeof(content), "Added %u/%u",
list_length(observers_list),
COAP_MAX_OBSERVERS));
} else {
coap_res->code = SERVICE_UNAVAILABLE_5_03;
coap_set_payload(coap_res, "TooManyObservers", 16);
} /* if(added observer) */
} else { /* if (observe) */
/* remove client if it is currently observe */
coap_remove_observer_by_token(&UIP_IP_BUF->srcipaddr,
UIP_UDP_BUF->srcport, coap_req->token,
coap_req->token_len);
/* if(observe) */
}
}
}
/*---------------------------------------------------------------------------*/

180
apps/er-coap/er-coap-observe.h Executable file → Normal file
View file

@ -1,90 +1,90 @@
/*
* Copyright (c) 2013, Institute for Pervasive Computing, ETH Zurich
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name of the Institute nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*
* This file is part of the Contiki operating system.
*/
/**
* \file
* CoAP module for observing resources (draft-ietf-core-observe-11).
* \author
* Matthias Kovatsch <kovatsch@inf.ethz.ch>
*/
#ifndef COAP_OBSERVE_H_
#define COAP_OBSERVE_H_
#include "er-coap.h"
#include "er-coap-transactions.h"
#include "stimer.h"
typedef struct coap_observable {
uint32_t observe_clock;
struct stimer orphan_timer;
list_t observers;
coap_packet_t notification;
uint8_t buffer[COAP_MAX_PACKET_SIZE + 1];
} coap_observable_t;
typedef struct coap_observer {
struct coap_observer *next; /* for LIST */
const char *url;
uip_ipaddr_t addr;
uint16_t port;
uint8_t token_len;
uint8_t token[COAP_TOKEN_LEN];
uint16_t last_mid;
int32_t obs_counter;
struct etimer retrans_timer;
uint8_t retrans_counter;
} coap_observer_t;
list_t coap_get_observers(void);
coap_observer_t *coap_add_observer(uip_ipaddr_t * addr, uint16_t port,
const uint8_t * token, size_t token_len,
const char *url);
void coap_remove_observer(coap_observer_t * o);
int coap_remove_observer_by_client(uip_ipaddr_t * addr, uint16_t port);
int coap_remove_observer_by_token(uip_ipaddr_t * addr, uint16_t port,
uint8_t * token, size_t token_len);
int coap_remove_observer_by_uri(uip_ipaddr_t * addr, uint16_t port,
const char *uri);
int coap_remove_observer_by_mid(uip_ipaddr_t * addr, uint16_t port,
uint16_t mid);
void coap_notify_observers(resource_t * resource);
void coap_observe_handler(resource_t * resource, void *request,
void *response);
#endif /* COAP_OBSERVE_H_ */
/*
* Copyright (c) 2013, Institute for Pervasive Computing, ETH Zurich
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name of the Institute nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*
* This file is part of the Contiki operating system.
*/
/**
* \file
* CoAP module for observing resources (draft-ietf-core-observe-11).
* \author
* Matthias Kovatsch <kovatsch@inf.ethz.ch>
*/
#ifndef COAP_OBSERVE_H_
#define COAP_OBSERVE_H_
#include "er-coap.h"
#include "er-coap-transactions.h"
#include "stimer.h"
typedef struct coap_observable {
uint32_t observe_clock;
struct stimer orphan_timer;
list_t observers;
coap_packet_t notification;
uint8_t buffer[COAP_MAX_PACKET_SIZE + 1];
} coap_observable_t;
typedef struct coap_observer {
struct coap_observer *next; /* for LIST */
const char *url;
uip_ipaddr_t addr;
uint16_t port;
uint8_t token_len;
uint8_t token[COAP_TOKEN_LEN];
uint16_t last_mid;
int32_t obs_counter;
struct etimer retrans_timer;
uint8_t retrans_counter;
} coap_observer_t;
list_t coap_get_observers(void);
coap_observer_t *coap_add_observer(uip_ipaddr_t *addr, uint16_t port,
const uint8_t *token, size_t token_len,
const char *url);
void coap_remove_observer(coap_observer_t *o);
int coap_remove_observer_by_client(uip_ipaddr_t *addr, uint16_t port);
int coap_remove_observer_by_token(uip_ipaddr_t *addr, uint16_t port,
uint8_t *token, size_t token_len);
int coap_remove_observer_by_uri(uip_ipaddr_t *addr, uint16_t port,
const char *uri);
int coap_remove_observer_by_mid(uip_ipaddr_t *addr, uint16_t port,
uint16_t mid);
void coap_notify_observers(resource_t *resource);
void coap_observe_handler(resource_t *resource, void *request,
void *response);
#endif /* COAP_OBSERVE_H_ */

452
apps/er-coap/er-coap-res-well-known-core.c Executable file → Normal file
View file

@ -1,220 +1,232 @@
/*
* Copyright (c) 2013, Institute for Pervasive Computing, ETH Zurich
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name of the Institute nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*
* This file is part of the Contiki operating system.
*/
/**
* \file
* /.well-known/core resource implementation.
* \author
* Matthias Kovatsch <kovatsch@inf.ethz.ch>
*/
#include <string.h>
#include "er-coap-engine.h"
#define DEBUG DEBUG_NONE
#include "net/uip-debug.h"
/*---------------------------------------------------------------------------*/
/*- Resource Handlers -------------------------------------------------------*/
/*---------------------------------------------------------------------------*/
void
well_known_core_get_handler(void *request, void *response, uint8_t * buffer,
uint16_t preferred_size, int32_t * offset)
{
size_t strpos = 0; /* position in overall string (which is larger than the buffer) */
size_t bufpos = 0; /* position within buffer (bytes written) */
size_t tmplen = 0;
resource_t *resource = NULL;
#if COAP_LINK_FORMAT_FILTERING
/* For filtering. */
const char *filter = NULL;
const char *attrib = NULL;
const char *found = NULL;
const char *end = NULL;
char *value = NULL;
char lastchar = '\0';
int len = coap_get_header_uri_query(request, &filter);
if(len) {
value = strchr(filter, '=');
value[0] = '\0';
++value;
len -= strlen(filter) + 1;
PRINTF("Filter %s = %.*s\n", filter, len, value);
if(strcmp(filter, "href") == 0 && value[0] == '/') {
++value;
--len;
}
lastchar = value[len - 1];
value[len - 1] = '\0';
}
#endif
for(resource = (resource_t *) list_head(rest_get_resources()); resource;
resource = resource->next) {
#if COAP_LINK_FORMAT_FILTERING
/* Filtering */
if(len) {
if(strcmp(filter, "href") == 0) {
attrib = strstr(resource->url, value);
if(attrib == NULL || (value[-1] == '/' && attrib != resource->url))
continue;
end = attrib + strlen(attrib);
} else {
attrib = strstr(resource->attributes, filter);
if(attrib == NULL
|| (attrib[strlen(filter)] != '='
&& attrib[strlen(filter)] != '"'))
continue;
attrib += strlen(filter) + 2;
end = strchr(attrib, '"');
}
PRINTF("Filter: res has attrib %s (%s)\n", attrib, value);
found = attrib;
while((found = strstr(found, value)) != NULL) {
if(found > end) {
found = NULL;
break;
}
if(lastchar == found[len - 1] || lastchar == '*') {
break;
}
++found;
}
if(found == NULL) {
continue;
}
PRINTF("Filter: res has prefix %s\n", found);
if(lastchar != '*'
&& (found[len] != '"' && found[len] != ' ' && found[len] != '\0'))
continue;
PRINTF("Filter: res has match\n");
}
#endif
PRINTF("res: /%s (%p)\npos: s%d, o%ld, b%d\n", resource->url, resource,
strpos, *offset, bufpos);
if(strpos > 0) {
if(strpos >= *offset && bufpos < preferred_size) {
buffer[bufpos++] = ',';
}
++strpos;
}
if(strpos >= *offset && bufpos < preferred_size) {
buffer[bufpos++] = '<';
}
++strpos;
if(strpos >= *offset && bufpos < preferred_size) {
buffer[bufpos++] = '/';
}
++strpos;
tmplen = strlen(resource->url);
if(strpos + tmplen > *offset) {
bufpos += snprintf((char *)buffer + bufpos,
preferred_size - bufpos + 1,
"%s",
resource->url +
((*offset - (int32_t) strpos >
0) ? (*offset - (int32_t) strpos) : 0));
/* native requires these casts */
if(bufpos >= preferred_size) {
PRINTF("res: BREAK at %s (%p)\n", resource->url, resource);
break;
}
}
strpos += tmplen;
if(strpos >= *offset && bufpos < preferred_size) {
buffer[bufpos++] = '>';
}
++strpos;
if(resource->attributes[0]) {
if(strpos >= *offset && bufpos < preferred_size) {
buffer[bufpos++] = ';';
}
++strpos;
tmplen = strlen(resource->attributes);
if(strpos + tmplen > *offset) {
bufpos += snprintf((char *)buffer + bufpos,
preferred_size - bufpos + 1,
resource->attributes
+ (*offset - (int32_t) strpos > 0 ?
*offset - (int32_t) strpos : 0));
if(bufpos > preferred_size) {
PRINTF("res: BREAK at %s (%p)\n", resource->url, resource);
break;
}
}
strpos += tmplen;
}
/* buffer full, but resource not completed yet; or: do not break if resource exactly fills buffer. */
if(bufpos > preferred_size && strpos - bufpos > *offset) {
PRINTF("res: BREAK at %s (%p)\n", resource->url, resource);
break;
}
}
if(bufpos > 0) {
PRINTF("BUF %d: %.*s\n", bufpos, bufpos, (char *)buffer);
coap_set_payload(response, buffer, bufpos);
coap_set_header_content_format(response, APPLICATION_LINK_FORMAT);
} else if(strpos > 0) {
PRINTF("well_known_core_handler(): bufpos<=0\n");
coap_set_status_code(response, BAD_OPTION_4_02);
coap_set_payload(response, "BlockOutOfScope", 15);
}
if(resource == NULL) {
PRINTF("res: DONE\n");
*offset = -1;
} else {
PRINTF("res: MORE at %s (%p)\n", resource->url, resource);
*offset += preferred_size;
}
}
/*---------------------------------------------------------------------------*/
RESOURCE(res_well_known_core, "ct=40", well_known_core_get_handler, NULL,
NULL, NULL);
/*---------------------------------------------------------------------------*/
/*
* Copyright (c) 2013, Institute for Pervasive Computing, ETH Zurich
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name of the Institute nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*
* This file is part of the Contiki operating system.
*/
/**
* \file
* /.well-known/core resource implementation.
* \author
* Matthias Kovatsch <kovatsch@inf.ethz.ch>
*/
#include <string.h>
#include "er-coap-engine.h"
#define DEBUG 0
#if DEBUG
#include <stdio.h>
#define PRINTF(...) printf(__VA_ARGS__)
#define PRINT6ADDR(addr) PRINTF("[%02x%02x:%02x%02x:%02x%02x:%02x%02x:%02x%02x:%02x%02x:%02x%02x:%02x%02x]", ((uint8_t *)addr)[0], ((uint8_t *)addr)[1], ((uint8_t *)addr)[2], ((uint8_t *)addr)[3], ((uint8_t *)addr)[4], ((uint8_t *)addr)[5], ((uint8_t *)addr)[6], ((uint8_t *)addr)[7], ((uint8_t *)addr)[8], ((uint8_t *)addr)[9], ((uint8_t *)addr)[10], ((uint8_t *)addr)[11], ((uint8_t *)addr)[12], ((uint8_t *)addr)[13], ((uint8_t *)addr)[14], ((uint8_t *)addr)[15])
#define PRINTLLADDR(lladdr) PRINTF("[%02x:%02x:%02x:%02x:%02x:%02x]", (lladdr)->addr[0], (lladdr)->addr[1], (lladdr)->addr[2], (lladdr)->addr[3], (lladdr)->addr[4], (lladdr)->addr[5])
#else
#define PRINTF(...)
#define PRINT6ADDR(addr)
#define PRINTLLADDR(addr)
#endif
/*---------------------------------------------------------------------------*/
/*- Resource Handlers -------------------------------------------------------*/
/*---------------------------------------------------------------------------*/
void
well_known_core_get_handler(void *request, void *response, uint8_t *buffer,
uint16_t preferred_size, int32_t *offset)
{
size_t strpos = 0; /* position in overall string (which is larger than the buffer) */
size_t bufpos = 0; /* position within buffer (bytes written) */
size_t tmplen = 0;
resource_t *resource = NULL;
#if COAP_LINK_FORMAT_FILTERING
/* For filtering. */
const char *filter = NULL;
const char *attrib = NULL;
const char *found = NULL;
const char *end = NULL;
char *value = NULL;
char lastchar = '\0';
int len = coap_get_header_uri_query(request, &filter);
if(len) {
value = strchr(filter, '=');
value[0] = '\0';
++value;
len -= strlen(filter) + 1;
PRINTF("Filter %s = %.*s\n", filter, len, value);
if(strcmp(filter, "href") == 0 && value[0] == '/') {
++value;
--len;
}
lastchar = value[len - 1];
value[len - 1] = '\0';
}
#endif
for(resource = (resource_t *)list_head(rest_get_resources()); resource;
resource = resource->next) {
#if COAP_LINK_FORMAT_FILTERING
/* Filtering */
if(len) {
if(strcmp(filter, "href") == 0) {
attrib = strstr(resource->url, value);
if(attrib == NULL || (value[-1] == '/' && attrib != resource->url)) {
continue;
}
end = attrib + strlen(attrib);
} else {
attrib = strstr(resource->attributes, filter);
if(attrib == NULL
|| (attrib[strlen(filter)] != '='
&& attrib[strlen(filter)] != '"')) {
continue;
}
attrib += strlen(filter) + 2;
end = strchr(attrib, '"');
}
PRINTF("Filter: res has attrib %s (%s)\n", attrib, value);
found = attrib;
while((found = strstr(found, value)) != NULL) {
if(found > end) {
found = NULL;
break;
}
if(lastchar == found[len - 1] || lastchar == '*') {
break;
}
++found;
}
if(found == NULL) {
continue;
}
PRINTF("Filter: res has prefix %s\n", found);
if(lastchar != '*'
&& (found[len] != '"' && found[len] != ' ' && found[len] != '\0')) {
continue;
}
PRINTF("Filter: res has match\n");
}
#endif
PRINTF("res: /%s (%p)\npos: s%d, o%ld, b%d\n", resource->url, resource,
strpos, *offset, bufpos);
if(strpos > 0) {
if(strpos >= *offset && bufpos < preferred_size) {
buffer[bufpos++] = ',';
}
++strpos;
}
if(strpos >= *offset && bufpos < preferred_size) {
buffer[bufpos++] = '<';
}
++strpos;
if(strpos >= *offset && bufpos < preferred_size) {
buffer[bufpos++] = '/';
}
++strpos;
tmplen = strlen(resource->url);
if(strpos + tmplen > *offset) {
bufpos += snprintf((char *)buffer + bufpos,
preferred_size - bufpos + 1,
"%s",
resource->url +
((*offset - (int32_t)strpos >
0) ? (*offset - (int32_t)strpos) : 0));
/* native requires these casts */
if(bufpos >= preferred_size) {
PRINTF("res: BREAK at %s (%p)\n", resource->url, resource);
break;
}
}
strpos += tmplen;
if(strpos >= *offset && bufpos < preferred_size) {
buffer[bufpos++] = '>';
}
++strpos;
if(resource->attributes[0]) {
if(strpos >= *offset && bufpos < preferred_size) {
buffer[bufpos++] = ';';
}
++strpos;
tmplen = strlen(resource->attributes);
if(strpos + tmplen > *offset) {
bufpos += snprintf((char *)buffer + bufpos,
preferred_size - bufpos + 1,
resource->attributes
+ (*offset - (int32_t)strpos > 0 ?
*offset - (int32_t)strpos : 0));
if(bufpos > preferred_size) {
PRINTF("res: BREAK at %s (%p)\n", resource->url, resource);
break;
}
}
strpos += tmplen;
}
/* buffer full, but resource not completed yet; or: do not break if resource exactly fills buffer. */
if(bufpos > preferred_size && strpos - bufpos > *offset) {
PRINTF("res: BREAK at %s (%p)\n", resource->url, resource);
break;
}
}
if(bufpos > 0) {
PRINTF("BUF %d: %.*s\n", bufpos, bufpos, (char *)buffer);
coap_set_payload(response, buffer, bufpos);
coap_set_header_content_format(response, APPLICATION_LINK_FORMAT);
} else if(strpos > 0) {
PRINTF("well_known_core_handler(): bufpos<=0\n");
coap_set_status_code(response, BAD_OPTION_4_02);
coap_set_payload(response, "BlockOutOfScope", 15);
}
if(resource == NULL) {
PRINTF("res: DONE\n");
*offset = -1;
} else {
PRINTF("res: MORE at %s (%p)\n", resource->url, resource);
*offset += preferred_size;
}
}
/*---------------------------------------------------------------------------*/
RESOURCE(res_well_known_core, "ct=40", well_known_core_get_handler, NULL,
NULL, NULL);
/*---------------------------------------------------------------------------*/

274
apps/er-coap/er-coap-separate.c Executable file → Normal file
View file

@ -1,133 +1,141 @@
/*
* Copyright (c) 2013, Institute for Pervasive Computing, ETH Zurich
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name of the Institute nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*
* This file is part of the Contiki operating system.
*/
/**
* \file
* CoAP module for separate responses.
* \author
* Matthias Kovatsch <kovatsch@inf.ethz.ch>
*/
#include <stdio.h>
#include <string.h>
#include "er-coap-separate.h"
#include "er-coap-transactions.h"
#define DEBUG DEBUG_NONE
#include "net/uip-debug.h"
/*---------------------------------------------------------------------------*/
/*- Separate Response API ---------------------------------------------------*/
/*---------------------------------------------------------------------------*/
/**
* \brief Reject a request that would require a separate response with an error message
*
* When the server does not have enough resources left to store the information
* for a separate response or otherwise cannot execute the resource handler,
* this function will respond with 5.03 Service Unavailable. The client can
* then retry later.
*/
void
coap_separate_reject()
{
// TODO: Accept string pointer for custom error message
erbium_status_code = SERVICE_UNAVAILABLE_5_03;
coap_error_message = "AlreadyInUse";
}
/*----------------------------------------------------------------------------*/
/**
* \brief Initiate a separate response with an empty ACK
* \param request The request to accept
* \param separate_store A pointer to the data structure that will store the
* relevant information for the response
*
* When the server does not have enough resources left to store the information
* for a separate response or otherwise cannot execute the resource handler,
* this function will respond with 5.03 Service Unavailable. The client can
* then retry later.
*/
void
coap_separate_accept(void *request, coap_separate_t * separate_store)
{
coap_packet_t *const coap_req = (coap_packet_t *) request;
coap_transaction_t *const t = coap_get_transaction_by_mid(coap_req->mid);
PRINTF("Separate ACCEPT: /%.*s MID %u\n", coap_req->uri_path_len,
coap_req->uri_path, coap_req->mid);
if(t) {
/* send separate ACK for CON */
if(coap_req->type == COAP_TYPE_CON) {
coap_packet_t ack[1];
/* ACK with empty code (0) */
coap_init_message(ack, COAP_TYPE_ACK, 0, coap_req->mid);
/* serializing into IPBUF: Only overwrites header parts that are already parsed into the request struct */
coap_send_message(&UIP_IP_BUF->srcipaddr, UIP_UDP_BUF->srcport,
(uip_appdata), coap_serialize_message(ack,
uip_appdata));
}
/* store remote address */
uip_ipaddr_copy(&separate_store->addr, &t->addr);
separate_store->port = t->port;
/* store correct response type */
separate_store->type =
coap_req->type == COAP_TYPE_CON ? COAP_TYPE_CON : COAP_TYPE_NON;
separate_store->mid = coap_get_mid(); /* if it was a NON, we burned one MID in the engine... */
memcpy(separate_store->token, coap_req->token, coap_req->token_len);
separate_store->token_len = coap_req->token_len;
separate_store->block2_num = coap_req->block2_num;
separate_store->block2_size = coap_req->block2_size;
/* signal the engine to skip automatic response and clear transaction by engine */
erbium_status_code = MANUAL_RESPONSE;
} else {
PRINTF("ERROR: Response transaction for separate request not found!\n");
erbium_status_code = INTERNAL_SERVER_ERROR_5_00;
}
}
/*----------------------------------------------------------------------------*/
void
coap_separate_resume(void *response, coap_separate_t * separate_store,
uint8_t code)
{
coap_init_message(response, separate_store->type, code,
separate_store->mid);
if(separate_store->token_len) {
coap_set_token(response, separate_store->token,
separate_store->token_len);
}
}
/*---------------------------------------------------------------------------*/
/*
* Copyright (c) 2013, Institute for Pervasive Computing, ETH Zurich
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name of the Institute nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*
* This file is part of the Contiki operating system.
*/
/**
* \file
* CoAP module for separate responses.
* \author
* Matthias Kovatsch <kovatsch@inf.ethz.ch>
*/
#include <stdio.h>
#include <string.h>
#include "er-coap-separate.h"
#include "er-coap-transactions.h"
#define DEBUG 0
#if DEBUG
#include <stdio.h>
#define PRINTF(...) printf(__VA_ARGS__)
#define PRINT6ADDR(addr) PRINTF("[%02x%02x:%02x%02x:%02x%02x:%02x%02x:%02x%02x:%02x%02x:%02x%02x:%02x%02x]", ((uint8_t *)addr)[0], ((uint8_t *)addr)[1], ((uint8_t *)addr)[2], ((uint8_t *)addr)[3], ((uint8_t *)addr)[4], ((uint8_t *)addr)[5], ((uint8_t *)addr)[6], ((uint8_t *)addr)[7], ((uint8_t *)addr)[8], ((uint8_t *)addr)[9], ((uint8_t *)addr)[10], ((uint8_t *)addr)[11], ((uint8_t *)addr)[12], ((uint8_t *)addr)[13], ((uint8_t *)addr)[14], ((uint8_t *)addr)[15])
#define PRINTLLADDR(lladdr) PRINTF("[%02x:%02x:%02x:%02x:%02x:%02x]", (lladdr)->addr[0], (lladdr)->addr[1], (lladdr)->addr[2], (lladdr)->addr[3], (lladdr)->addr[4], (lladdr)->addr[5])
#else
#define PRINTF(...)
#define PRINT6ADDR(addr)
#define PRINTLLADDR(addr)
#endif
/*---------------------------------------------------------------------------*/
/*- Separate Response API ---------------------------------------------------*/
/*---------------------------------------------------------------------------*/
/**
* \brief Reject a request that would require a separate response with an error message
*
* When the server does not have enough resources left to store the information
* for a separate response or otherwise cannot execute the resource handler,
* this function will respond with 5.03 Service Unavailable. The client can
* then retry later.
*/
void
coap_separate_reject()
{
/* TODO: Accept string pointer for custom error message */
erbium_status_code = SERVICE_UNAVAILABLE_5_03;
coap_error_message = "AlreadyInUse";
}
/*----------------------------------------------------------------------------*/
/**
* \brief Initiate a separate response with an empty ACK
* \param request The request to accept
* \param separate_store A pointer to the data structure that will store the
* relevant information for the response
*
* When the server does not have enough resources left to store the information
* for a separate response or otherwise cannot execute the resource handler,
* this function will respond with 5.03 Service Unavailable. The client can
* then retry later.
*/
void
coap_separate_accept(void *request, coap_separate_t *separate_store)
{
coap_packet_t *const coap_req = (coap_packet_t *)request;
coap_transaction_t *const t = coap_get_transaction_by_mid(coap_req->mid);
PRINTF("Separate ACCEPT: /%.*s MID %u\n", coap_req->uri_path_len,
coap_req->uri_path, coap_req->mid);
if(t) {
/* send separate ACK for CON */
if(coap_req->type == COAP_TYPE_CON) {
coap_packet_t ack[1];
/* ACK with empty code (0) */
coap_init_message(ack, COAP_TYPE_ACK, 0, coap_req->mid);
/* serializing into IPBUF: Only overwrites header parts that are already parsed into the request struct */
coap_send_message(&UIP_IP_BUF->srcipaddr, UIP_UDP_BUF->srcport,
(uip_appdata), coap_serialize_message(ack,
uip_appdata));
}
/* store remote address */
uip_ipaddr_copy(&separate_store->addr, &t->addr);
separate_store->port = t->port;
/* store correct response type */
separate_store->type =
coap_req->type == COAP_TYPE_CON ? COAP_TYPE_CON : COAP_TYPE_NON;
separate_store->mid = coap_get_mid(); /* if it was a NON, we burned one MID in the engine... */
memcpy(separate_store->token, coap_req->token, coap_req->token_len);
separate_store->token_len = coap_req->token_len;
separate_store->block2_num = coap_req->block2_num;
separate_store->block2_size = coap_req->block2_size;
/* signal the engine to skip automatic response and clear transaction by engine */
erbium_status_code = MANUAL_RESPONSE;
} else {
PRINTF("ERROR: Response transaction for separate request not found!\n");
erbium_status_code = INTERNAL_SERVER_ERROR_5_00;
}
}
/*----------------------------------------------------------------------------*/
void
coap_separate_resume(void *response, coap_separate_t *separate_store,
uint8_t code)
{
coap_init_message(response, separate_store->type, code,
separate_store->mid);
if(separate_store->token_len) {
coap_set_token(response, separate_store->token,
separate_store->token_len);
}
}
/*---------------------------------------------------------------------------*/

135
apps/er-coap/er-coap-separate.h Executable file → Normal file
View file

@ -1,68 +1,67 @@
/*
* Copyright (c) 2013, Institute for Pervasive Computing, ETH Zurich
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name of the Institute nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*
* This file is part of the Contiki operating system.
*/
/**
* \file
* CoAP module for separate responses.
* \author
* Matthias Kovatsch <kovatsch@inf.ethz.ch>
*/
#ifndef COAP_SEPARATE_H_
#define COAP_SEPARATE_H_
#include "er-coap.h"
typedef struct coap_separate {
uip_ipaddr_t addr;
uint16_t port;
coap_message_type_t type;
uint16_t mid;
uint8_t token_len;
uint8_t token[COAP_TOKEN_LEN];
/* separate + blockwise is untested! */
uint32_t block2_num;
uint16_t block2_size;
} coap_separate_t;
int coap_separate_handler(resource_t * resource, void *request,
void *response);
void coap_separate_reject();
void coap_separate_accept(void *request, coap_separate_t * separate_store);
void coap_separate_resume(void *response, coap_separate_t * separate_store,
uint8_t code);
#endif /* COAP_SEPARATE_H_ */
/*
* Copyright (c) 2013, Institute for Pervasive Computing, ETH Zurich
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name of the Institute nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*
* This file is part of the Contiki operating system.
*/
/**
* \file
* CoAP module for separate responses.
* \author
* Matthias Kovatsch <kovatsch@inf.ethz.ch>
*/
#ifndef COAP_SEPARATE_H_
#define COAP_SEPARATE_H_
#include "er-coap.h"
typedef struct coap_separate {
uip_ipaddr_t addr;
uint16_t port;
coap_message_type_t type;
uint16_t mid;
uint8_t token_len;
uint8_t token[COAP_TOKEN_LEN];
/* separate + blockwise is untested! */
uint32_t block2_num;
uint16_t block2_size;
} coap_separate_t;
int coap_separate_handler(resource_t *resource, void *request,
void *response);
void coap_separate_reject();
void coap_separate_accept(void *request, coap_separate_t *separate_store);
void coap_separate_resume(void *response, coap_separate_t *separate_store,
uint8_t code);
#endif /* COAP_SEPARATE_H_ */

363
apps/er-coap/er-coap-transactions.c Executable file → Normal file
View file

@ -1,178 +1,185 @@
/*
* Copyright (c) 2013, Institute for Pervasive Computing, ETH Zurich
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name of the Institute nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*
* This file is part of the Contiki operating system.
*/
/**
* \file
* CoAP module for reliable transport
* \author
* Matthias Kovatsch <kovatsch@inf.ethz.ch>
*/
#include "contiki.h"
#include "contiki-net.h"
#include "er-coap-transactions.h"
#include "er-coap-observe.h"
#define DEBUG DEBUG_NONE
#include "net/uip-debug.h"
/*---------------------------------------------------------------------------*/
MEMB(transactions_memb, coap_transaction_t, COAP_MAX_OPEN_TRANSACTIONS);
LIST(transactions_list);
static struct process *transaction_handler_process = NULL;
/*---------------------------------------------------------------------------*/
/*- Internal API ------------------------------------------------------------*/
/*---------------------------------------------------------------------------*/
void
coap_register_as_transaction_handler()
{
transaction_handler_process = PROCESS_CURRENT();
}
coap_transaction_t *
coap_new_transaction(uint16_t mid, uip_ipaddr_t * addr, uint16_t port)
{
coap_transaction_t *t = memb_alloc(&transactions_memb);
if(t) {
t->mid = mid;
t->retrans_counter = 0;
/* save client address */
uip_ipaddr_copy(&t->addr, addr);
t->port = port;
list_add(transactions_list, t); /* list itself makes sure same element is not added twice */
}
return t;
}
/*---------------------------------------------------------------------------*/
void
coap_send_transaction(coap_transaction_t * t)
{
PRINTF("Sending transaction %u\n", t->mid);
coap_send_message(&t->addr, t->port, t->packet, t->packet_len);
if(COAP_TYPE_CON ==
((COAP_HEADER_TYPE_MASK & t->packet[0]) >> COAP_HEADER_TYPE_POSITION)) {
if(t->retrans_counter < COAP_MAX_RETRANSMIT) {
/* not timed out yet */
PRINTF("Keeping transaction %u\n", t->mid);
if(t->retrans_counter == 0) {
t->retrans_timer.timer.interval =
COAP_RESPONSE_TIMEOUT_TICKS + (random_rand()
%
(clock_time_t)
COAP_RESPONSE_TIMEOUT_BACKOFF_MASK);
PRINTF("Initial interval %f\n",
(float)t->retrans_timer.timer.interval / CLOCK_SECOND);
} else {
t->retrans_timer.timer.interval <<= 1; /* double */
PRINTF("Doubled (%u) interval %f\n", t->retrans_counter,
(float)t->retrans_timer.timer.interval / CLOCK_SECOND);
}
/*FIXME
* Hack: Setting timer for responsible process.
* Maybe there is a better way, but avoid posting everything to the process.
*/
struct process *process_actual = PROCESS_CURRENT();
process_current = transaction_handler_process;
etimer_restart(&t->retrans_timer); /* interval updated above */
process_current = process_actual;
t = NULL;
} else {
/* timed out */
PRINTF("Timeout\n");
restful_response_handler callback = t->callback;
void *callback_data = t->callback_data;
/* handle observers */
coap_remove_observer_by_client(&t->addr, t->port);
coap_clear_transaction(t);
if(callback) {
callback(callback_data, NULL);
}
}
} else {
coap_clear_transaction(t);
}
}
/*---------------------------------------------------------------------------*/
void
coap_clear_transaction(coap_transaction_t * t)
{
if(t) {
PRINTF("Freeing transaction %u: %p\n", t->mid, t);
etimer_stop(&t->retrans_timer);
list_remove(transactions_list, t);
memb_free(&transactions_memb, t);
}
}
coap_transaction_t *
coap_get_transaction_by_mid(uint16_t mid)
{
coap_transaction_t *t = NULL;
for(t = (coap_transaction_t *) list_head(transactions_list); t; t = t->next) {
if(t->mid == mid) {
PRINTF("Found transaction for MID %u: %p\n", t->mid, t);
return t;
}
}
return NULL;
}
/*---------------------------------------------------------------------------*/
void
coap_check_transactions()
{
coap_transaction_t *t = NULL;
for(t = (coap_transaction_t *) list_head(transactions_list); t; t = t->next) {
if(etimer_expired(&t->retrans_timer)) {
++(t->retrans_counter);
PRINTF("Retransmitting %u (%u)\n", t->mid, t->retrans_counter);
coap_send_transaction(t);
}
}
}
/*---------------------------------------------------------------------------*/
/*
* Copyright (c) 2013, Institute for Pervasive Computing, ETH Zurich
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name of the Institute nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*
* This file is part of the Contiki operating system.
*/
/**
* \file
* CoAP module for reliable transport
* \author
* Matthias Kovatsch <kovatsch@inf.ethz.ch>
*/
#include "contiki.h"
#include "contiki-net.h"
#include "er-coap-transactions.h"
#include "er-coap-observe.h"
#define DEBUG 0
#if DEBUG
#include <stdio.h>
#define PRINTF(...) printf(__VA_ARGS__)
#define PRINT6ADDR(addr) PRINTF("[%02x%02x:%02x%02x:%02x%02x:%02x%02x:%02x%02x:%02x%02x:%02x%02x:%02x%02x]", ((uint8_t *)addr)[0], ((uint8_t *)addr)[1], ((uint8_t *)addr)[2], ((uint8_t *)addr)[3], ((uint8_t *)addr)[4], ((uint8_t *)addr)[5], ((uint8_t *)addr)[6], ((uint8_t *)addr)[7], ((uint8_t *)addr)[8], ((uint8_t *)addr)[9], ((uint8_t *)addr)[10], ((uint8_t *)addr)[11], ((uint8_t *)addr)[12], ((uint8_t *)addr)[13], ((uint8_t *)addr)[14], ((uint8_t *)addr)[15])
#define PRINTLLADDR(lladdr) PRINTF("[%02x:%02x:%02x:%02x:%02x:%02x]", (lladdr)->addr[0], (lladdr)->addr[1], (lladdr)->addr[2], (lladdr)->addr[3], (lladdr)->addr[4], (lladdr)->addr[5])
#else
#define PRINTF(...)
#define PRINT6ADDR(addr)
#define PRINTLLADDR(addr)
#endif
/*---------------------------------------------------------------------------*/
MEMB(transactions_memb, coap_transaction_t, COAP_MAX_OPEN_TRANSACTIONS);
LIST(transactions_list);
static struct process *transaction_handler_process = NULL;
/*---------------------------------------------------------------------------*/
/*- Internal API ------------------------------------------------------------*/
/*---------------------------------------------------------------------------*/
void
coap_register_as_transaction_handler()
{
transaction_handler_process = PROCESS_CURRENT();
}
coap_transaction_t *
coap_new_transaction(uint16_t mid, uip_ipaddr_t *addr, uint16_t port)
{
coap_transaction_t *t = memb_alloc(&transactions_memb);
if(t) {
t->mid = mid;
t->retrans_counter = 0;
/* save client address */
uip_ipaddr_copy(&t->addr, addr);
t->port = port;
list_add(transactions_list, t); /* list itself makes sure same element is not added twice */
}
return t;
}
/*---------------------------------------------------------------------------*/
void
coap_send_transaction(coap_transaction_t *t)
{
PRINTF("Sending transaction %u\n", t->mid);
coap_send_message(&t->addr, t->port, t->packet, t->packet_len);
if(COAP_TYPE_CON ==
((COAP_HEADER_TYPE_MASK & t->packet[0]) >> COAP_HEADER_TYPE_POSITION)) {
if(t->retrans_counter < COAP_MAX_RETRANSMIT) {
/* not timed out yet */
PRINTF("Keeping transaction %u\n", t->mid);
if(t->retrans_counter == 0) {
t->retrans_timer.timer.interval =
COAP_RESPONSE_TIMEOUT_TICKS + (random_rand()
%
(clock_time_t)
COAP_RESPONSE_TIMEOUT_BACKOFF_MASK);
PRINTF("Initial interval %f\n",
(float)t->retrans_timer.timer.interval / CLOCK_SECOND);
} else {
t->retrans_timer.timer.interval <<= 1; /* double */
PRINTF("Doubled (%u) interval %f\n", t->retrans_counter,
(float)t->retrans_timer.timer.interval / CLOCK_SECOND);
}
/*FIXME
* Hack: Setting timer for responsible process.
* Maybe there is a better way, but avoid posting everything to the process.
*/
struct process *process_actual = PROCESS_CURRENT();
process_current = transaction_handler_process;
etimer_restart(&t->retrans_timer); /* interval updated above */
process_current = process_actual;
t = NULL;
} else {
/* timed out */
PRINTF("Timeout\n");
restful_response_handler callback = t->callback;
void *callback_data = t->callback_data;
/* handle observers */
coap_remove_observer_by_client(&t->addr, t->port);
coap_clear_transaction(t);
if(callback) {
callback(callback_data, NULL);
}
}
} else {
coap_clear_transaction(t);
}
}
/*---------------------------------------------------------------------------*/
void
coap_clear_transaction(coap_transaction_t *t)
{
if(t) {
PRINTF("Freeing transaction %u: %p\n", t->mid, t);
etimer_stop(&t->retrans_timer);
list_remove(transactions_list, t);
memb_free(&transactions_memb, t);
}
}
coap_transaction_t *
coap_get_transaction_by_mid(uint16_t mid)
{
coap_transaction_t *t = NULL;
for(t = (coap_transaction_t *)list_head(transactions_list); t; t = t->next) {
if(t->mid == mid) {
PRINTF("Found transaction for MID %u: %p\n", t->mid, t);
return t;
}
}
return NULL;
}
/*---------------------------------------------------------------------------*/
void
coap_check_transactions()
{
coap_transaction_t *t = NULL;
for(t = (coap_transaction_t *)list_head(transactions_list); t; t = t->next) {
if(etimer_expired(&t->retrans_timer)) {
++(t->retrans_counter);
PRINTF("Retransmitting %u (%u)\n", t->mid, t->retrans_counter);
coap_send_transaction(t);
}
}
}
/*---------------------------------------------------------------------------*/

160
apps/er-coap/er-coap-transactions.h Executable file → Normal file
View file

@ -1,80 +1,80 @@
/*
* Copyright (c) 2013, Institute for Pervasive Computing, ETH Zurich
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name of the Institute nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*
* This file is part of the Contiki operating system.
*/
/**
* \file
* CoAP module for reliable transport
* \author
* Matthias Kovatsch <kovatsch@inf.ethz.ch>
*/
#ifndef COAP_TRANSACTIONS_H_
#define COAP_TRANSACTIONS_H_
#include "er-coap.h"
/*
* Modulo mask (thus +1) for a random number to get the tick number for the random
* retransmission time between COAP_RESPONSE_TIMEOUT and COAP_RESPONSE_TIMEOUT*COAP_RESPONSE_RANDOM_FACTOR.
*/
#define COAP_RESPONSE_TIMEOUT_TICKS (CLOCK_SECOND * COAP_RESPONSE_TIMEOUT)
#define COAP_RESPONSE_TIMEOUT_BACKOFF_MASK (long)((CLOCK_SECOND * COAP_RESPONSE_TIMEOUT * ((float)COAP_RESPONSE_RANDOM_FACTOR - 1.0)) + 0.5) + 1
/* container for transactions with message buffer and retransmission info */
typedef struct coap_transaction {
struct coap_transaction *next; /* for LIST */
uint16_t mid;
struct etimer retrans_timer;
uint8_t retrans_counter;
uip_ipaddr_t addr;
uint16_t port;
restful_response_handler callback;
void *callback_data;
uint16_t packet_len;
uint8_t packet[COAP_MAX_PACKET_SIZE + 1]; /* +1 for the terminating '\0' which will not be sent
* Use snprintf(buf, len+1, "", ...) to completely fill payload */
} coap_transaction_t;
void coap_register_as_transaction_handler();
coap_transaction_t *coap_new_transaction(uint16_t mid, uip_ipaddr_t * addr,
uint16_t port);
void coap_send_transaction(coap_transaction_t * t);
void coap_clear_transaction(coap_transaction_t * t);
coap_transaction_t *coap_get_transaction_by_mid(uint16_t mid);
void coap_check_transactions();
#endif /* COAP_TRANSACTIONS_H_ */
/*
* Copyright (c) 2013, Institute for Pervasive Computing, ETH Zurich
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name of the Institute nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*
* This file is part of the Contiki operating system.
*/
/**
* \file
* CoAP module for reliable transport
* \author
* Matthias Kovatsch <kovatsch@inf.ethz.ch>
*/
#ifndef COAP_TRANSACTIONS_H_
#define COAP_TRANSACTIONS_H_
#include "er-coap.h"
/*
* Modulo mask (thus +1) for a random number to get the tick number for the random
* retransmission time between COAP_RESPONSE_TIMEOUT and COAP_RESPONSE_TIMEOUT*COAP_RESPONSE_RANDOM_FACTOR.
*/
#define COAP_RESPONSE_TIMEOUT_TICKS (CLOCK_SECOND * COAP_RESPONSE_TIMEOUT)
#define COAP_RESPONSE_TIMEOUT_BACKOFF_MASK (long)((CLOCK_SECOND * COAP_RESPONSE_TIMEOUT * ((float)COAP_RESPONSE_RANDOM_FACTOR - 1.0)) + 0.5) + 1
/* container for transactions with message buffer and retransmission info */
typedef struct coap_transaction {
struct coap_transaction *next; /* for LIST */
uint16_t mid;
struct etimer retrans_timer;
uint8_t retrans_counter;
uip_ipaddr_t addr;
uint16_t port;
restful_response_handler callback;
void *callback_data;
uint16_t packet_len;
uint8_t packet[COAP_MAX_PACKET_SIZE + 1]; /* +1 for the terminating '\0' which will not be sent
* Use snprintf(buf, len+1, "", ...) to completely fill payload */
} coap_transaction_t;
void coap_register_as_transaction_handler();
coap_transaction_t *coap_new_transaction(uint16_t mid, uip_ipaddr_t *addr,
uint16_t port);
void coap_send_transaction(coap_transaction_t *t);
void coap_clear_transaction(coap_transaction_t *t);
coap_transaction_t *coap_get_transaction_by_mid(uint16_t mid);
void coap_check_transactions();
#endif /* COAP_TRANSACTIONS_H_ */

2370
apps/er-coap/er-coap.c Executable file → Normal file

File diff suppressed because it is too large Load diff

513
apps/er-coap/er-coap.h Executable file → Normal file
View file

@ -1,257 +1,256 @@
/*
* Copyright (c) 2013, Institute for Pervasive Computing, ETH Zurich
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name of the Institute nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*
* This file is part of the Contiki operating system.
*/
/**
* \file
* An implementation of the Constrained Application Protocol (RFC).
* \author
* Matthias Kovatsch <kovatsch@inf.ethz.ch>
*/
#ifndef ER_COAP_H_
#define ER_COAP_H_
#include <stddef.h> /* for size_t */
#include "net/uip.h"
#include "er-coap-constants.h"
#include "er-coap-conf.h"
/* sanity check for configured values */
#define COAP_MAX_PACKET_SIZE (COAP_MAX_HEADER_SIZE + REST_MAX_CHUNK_SIZE)
#if COAP_MAX_PACKET_SIZE > (UIP_BUFSIZE - UIP_IPH_LEN - UIP_UDPH_LEN)
#error "UIP_CONF_BUFFER_SIZE too small for REST_MAX_CHUNK_SIZE"
#endif
/* use Erbium CoAP for the REST Engine. Must come before include of rest-engine.h. */
#define REST coap_rest_implementation
#include "rest-engine.h"
/* direct access into the buffer */
#define UIP_IP_BUF ((struct uip_ip_hdr *)&uip_buf[UIP_LLH_LEN])
#if UIP_CONF_IPV6
#define UIP_UDP_BUF ((struct uip_udp_hdr *)&uip_buf[uip_l2_l3_hdr_len])
#else
#define UIP_UDP_BUF ((struct uip_udp_hdr *)&uip_buf[UIP_LLH_LEN + UIP_IPH_LEN])
#endif
/* bitmap for set options */
enum { OPTION_MAP_SIZE = sizeof(uint8_t) * 8 };
#define SET_OPTION(packet, opt) ((packet)->options[opt / OPTION_MAP_SIZE] |= 1 << (opt % OPTION_MAP_SIZE))
#define IS_OPTION(packet, opt) ((packet)->options[opt / OPTION_MAP_SIZE] & (1 << (opt % OPTION_MAP_SIZE)))
#ifndef MIN
#define MIN(a, b) ((a) < (b)? (a) : (b))
#endif /* MIN */
/* parsed message struct */
typedef struct {
uint8_t *buffer; /* pointer to CoAP header / incoming packet buffer / memory to serialize packet */
uint8_t version;
coap_message_type_t type;
uint8_t code;
uint16_t mid;
uint8_t token_len;
uint8_t token[COAP_TOKEN_LEN];
uint8_t options[COAP_OPTION_SIZE1 / OPTION_MAP_SIZE + 1]; /* bitmap to check if option is set */
coap_content_format_t content_format; /* parse options once and store; allows setting options in random order */
uint32_t max_age;
uint8_t etag_len;
uint8_t etag[COAP_ETAG_LEN];
size_t proxy_uri_len;
const char *proxy_uri;
size_t proxy_scheme_len;
const char *proxy_scheme;
size_t uri_host_len;
const char *uri_host;
size_t location_path_len;
const char *location_path;
uint16_t uri_port;
size_t location_query_len;
const char *location_query;
size_t uri_path_len;
const char *uri_path;
int32_t observe;
coap_content_format_t accept;
uint8_t if_match_len;
uint8_t if_match[COAP_ETAG_LEN];
uint32_t block2_num;
uint8_t block2_more;
uint16_t block2_size;
uint32_t block2_offset;
uint32_t block1_num;
uint8_t block1_more;
uint16_t block1_size;
uint32_t block1_offset;
uint32_t size2;
uint32_t size1;
size_t uri_query_len;
const char *uri_query;
uint8_t if_none_match;
uint16_t payload_len;
uint8_t *payload;
} coap_packet_t;
/* option format serialization */
#define COAP_SERIALIZE_INT_OPTION(number, field, text) \
if (IS_OPTION(coap_pkt, number)) { \
PRINTF(text" [%u]\n", coap_pkt->field); \
option += coap_serialize_int_option(number, current_number, option, coap_pkt->field); \
current_number = number; \
}
#define COAP_SERIALIZE_BYTE_OPTION(number, field, text) \
if (IS_OPTION(coap_pkt, number)) { \
PRINTF(text" %u [0x%02X%02X%02X%02X%02X%02X%02X%02X]\n", coap_pkt->field##_len, \
coap_pkt->field[0], \
coap_pkt->field[1], \
coap_pkt->field[2], \
coap_pkt->field[3], \
coap_pkt->field[4], \
coap_pkt->field[5], \
coap_pkt->field[6], \
coap_pkt->field[7] \
); /* FIXME always prints 8 bytes */ \
option += coap_serialize_array_option(number, current_number, option, coap_pkt->field, coap_pkt->field##_len, '\0'); \
current_number = number; \
}
#define COAP_SERIALIZE_STRING_OPTION(number, field, splitter, text) \
if (IS_OPTION(coap_pkt, number)) { \
PRINTF(text" [%.*s]\n", coap_pkt->field##_len, coap_pkt->field); \
option += coap_serialize_array_option(number, current_number, option, (uint8_t *) coap_pkt->field, coap_pkt->field##_len, splitter); \
current_number = number; \
}
#define COAP_SERIALIZE_BLOCK_OPTION(number, field, text) \
if (IS_OPTION(coap_pkt, number)) \
{ \
PRINTF(text" [%lu%s (%u B/blk)]\n", coap_pkt->field##_num, coap_pkt->field##_more ? "+" : "", coap_pkt->field##_size); \
uint32_t block = coap_pkt->field##_num << 4; \
if (coap_pkt->field##_more) block |= 0x8; \
block |= 0xF & coap_log_2(coap_pkt->field##_size/16); \
PRINTF(text" encoded: 0x%lX\n", block); \
option += coap_serialize_int_option(number, current_number, option, block); \
current_number = number; \
}
/* to store error code and human-readable payload */
extern coap_status_t erbium_status_code;
extern char *coap_error_message;
void coap_init_connection(uint16_t port);
uint16_t coap_get_mid(void);
void coap_init_message(void *packet, coap_message_type_t type, uint8_t code,
uint16_t mid);
size_t coap_serialize_message(void *packet, uint8_t * buffer);
void coap_send_message(uip_ipaddr_t * addr, uint16_t port, uint8_t * data,
uint16_t length);
coap_status_t coap_parse_message(void *request, uint8_t * data,
uint16_t data_len);
int coap_get_query_variable(void *packet, const char *name,
const char **output);
int coap_get_post_variable(void *packet, const char *name,
const char **output);
/*---------------------------------------------------------------------------*/
int coap_set_status_code(void *packet, unsigned int code);
int coap_set_token(void *packet, const uint8_t * token, size_t token_len);
int coap_get_header_content_format(void *packet, unsigned int *format);
int coap_set_header_content_format(void *packet, unsigned int format);
int coap_get_header_accept(void *packet, unsigned int *accept);
int coap_set_header_accept(void *packet, unsigned int accept);
int coap_get_header_max_age(void *packet, uint32_t * age);
int coap_set_header_max_age(void *packet, uint32_t age);
int coap_get_header_etag(void *packet, const uint8_t ** etag);
int coap_set_header_etag(void *packet, const uint8_t * etag, size_t etag_len);
int coap_get_header_if_match(void *packet, const uint8_t ** etag);
int coap_set_header_if_match(void *packet, const uint8_t * etag,
size_t etag_len);
int coap_get_header_if_none_match(void *packet);
int coap_set_header_if_none_match(void *packet);
int coap_get_header_proxy_uri(void *packet, const char **uri); /* in-place string might not be 0-terminated. */
int coap_set_header_proxy_uri(void *packet, const char *uri);
int coap_get_header_proxy_scheme(void *packet, const char **scheme); /* in-place string might not be 0-terminated. */
int coap_set_header_proxy_scheme(void *packet, const char *scheme);
int coap_get_header_uri_host(void *packet, const char **host); /* in-place string might not be 0-terminated. */
int coap_set_header_uri_host(void *packet, const char *host);
int coap_get_header_uri_path(void *packet, const char **path); /* in-place string might not be 0-terminated. */
int coap_set_header_uri_path(void *packet, const char *path);
int coap_get_header_uri_query(void *packet, const char **query); /* in-place string might not be 0-terminated. */
int coap_set_header_uri_query(void *packet, const char *query);
int coap_get_header_location_path(void *packet, const char **path); /* in-place string might not be 0-terminated. */
int coap_set_header_location_path(void *packet, const char *path); /* also splits optional query into Location-Query option. */
int coap_get_header_location_query(void *packet, const char **query); /* in-place string might not be 0-terminated. */
int coap_set_header_location_query(void *packet, const char *query);
int coap_get_header_observe(void *packet, uint32_t * observe);
int coap_set_header_observe(void *packet, uint32_t observe);
int coap_get_header_block2(void *packet, uint32_t * num, uint8_t * more,
uint16_t * size, uint32_t * offset);
int coap_set_header_block2(void *packet, uint32_t num, uint8_t more,
uint16_t size);
int coap_get_header_block1(void *packet, uint32_t * num, uint8_t * more,
uint16_t * size, uint32_t * offset);
int coap_set_header_block1(void *packet, uint32_t num, uint8_t more,
uint16_t size);
int coap_get_header_size2(void *packet, uint32_t * size);
int coap_set_header_size2(void *packet, uint32_t size);
int coap_get_header_size1(void *packet, uint32_t * size);
int coap_set_header_size1(void *packet, uint32_t size);
int coap_get_payload(void *packet, const uint8_t ** payload);
int coap_set_payload(void *packet, const void *payload, size_t length);
#endif /* ER_COAP_H_ */
/*
* Copyright (c) 2013, Institute for Pervasive Computing, ETH Zurich
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name of the Institute nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*
* This file is part of the Contiki operating system.
*/
/**
* \file
* An implementation of the Constrained Application Protocol (RFC).
* \author
* Matthias Kovatsch <kovatsch@inf.ethz.ch>
*/
#ifndef ER_COAP_H_
#define ER_COAP_H_
#include <stddef.h> /* for size_t */
#include "contiki-net.h"
#include "er-coap-constants.h"
#include "er-coap-conf.h"
/* sanity check for configured values */
#define COAP_MAX_PACKET_SIZE (COAP_MAX_HEADER_SIZE + REST_MAX_CHUNK_SIZE)
#if COAP_MAX_PACKET_SIZE > (UIP_BUFSIZE - UIP_IPH_LEN - UIP_UDPH_LEN)
#error "UIP_CONF_BUFFER_SIZE too small for REST_MAX_CHUNK_SIZE"
#endif
/* use Erbium CoAP for the REST Engine. Must come before include of rest-engine.h. */
#define REST coap_rest_implementation
#include "rest-engine.h"
/* direct access into the buffer */
#define UIP_IP_BUF ((struct uip_ip_hdr *)&uip_buf[UIP_LLH_LEN])
#if UIP_CONF_IPV6
#define UIP_UDP_BUF ((struct uip_udp_hdr *)&uip_buf[uip_l2_l3_hdr_len])
#else
#define UIP_UDP_BUF ((struct uip_udp_hdr *)&uip_buf[UIP_LLH_LEN + UIP_IPH_LEN])
#endif
/* bitmap for set options */
enum { OPTION_MAP_SIZE = sizeof(uint8_t) * 8 };
#define SET_OPTION(packet, opt) ((packet)->options[opt / OPTION_MAP_SIZE] |= 1 << (opt % OPTION_MAP_SIZE))
#define IS_OPTION(packet, opt) ((packet)->options[opt / OPTION_MAP_SIZE] & (1 << (opt % OPTION_MAP_SIZE)))
#ifndef MIN
#define MIN(a, b) ((a) < (b) ? (a) : (b))
#endif /* MIN */
/* parsed message struct */
typedef struct {
uint8_t *buffer; /* pointer to CoAP header / incoming packet buffer / memory to serialize packet */
uint8_t version;
coap_message_type_t type;
uint8_t code;
uint16_t mid;
uint8_t token_len;
uint8_t token[COAP_TOKEN_LEN];
uint8_t options[COAP_OPTION_SIZE1 / OPTION_MAP_SIZE + 1]; /* bitmap to check if option is set */
coap_content_format_t content_format; /* parse options once and store; allows setting options in random order */
uint32_t max_age;
uint8_t etag_len;
uint8_t etag[COAP_ETAG_LEN];
size_t proxy_uri_len;
const char *proxy_uri;
size_t proxy_scheme_len;
const char *proxy_scheme;
size_t uri_host_len;
const char *uri_host;
size_t location_path_len;
const char *location_path;
uint16_t uri_port;
size_t location_query_len;
const char *location_query;
size_t uri_path_len;
const char *uri_path;
int32_t observe;
coap_content_format_t accept;
uint8_t if_match_len;
uint8_t if_match[COAP_ETAG_LEN];
uint32_t block2_num;
uint8_t block2_more;
uint16_t block2_size;
uint32_t block2_offset;
uint32_t block1_num;
uint8_t block1_more;
uint16_t block1_size;
uint32_t block1_offset;
uint32_t size2;
uint32_t size1;
size_t uri_query_len;
const char *uri_query;
uint8_t if_none_match;
uint16_t payload_len;
uint8_t *payload;
} coap_packet_t;
/* option format serialization */
#define COAP_SERIALIZE_INT_OPTION(number, field, text) \
if(IS_OPTION(coap_pkt, number)) { \
PRINTF(text " [%u]\n", coap_pkt->field); \
option += coap_serialize_int_option(number, current_number, option, coap_pkt->field); \
current_number = number; \
}
#define COAP_SERIALIZE_BYTE_OPTION(number, field, text) \
if(IS_OPTION(coap_pkt, number)) { \
PRINTF(text " %u [0x%02X%02X%02X%02X%02X%02X%02X%02X]\n", coap_pkt->field##_len, \
coap_pkt->field[0], \
coap_pkt->field[1], \
coap_pkt->field[2], \
coap_pkt->field[3], \
coap_pkt->field[4], \
coap_pkt->field[5], \
coap_pkt->field[6], \
coap_pkt->field[7] \
); /* FIXME always prints 8 bytes */ \
option += coap_serialize_array_option(number, current_number, option, coap_pkt->field, coap_pkt->field##_len, '\0'); \
current_number = number; \
}
#define COAP_SERIALIZE_STRING_OPTION(number, field, splitter, text) \
if(IS_OPTION(coap_pkt, number)) { \
PRINTF(text " [%.*s]\n", coap_pkt->field##_len, coap_pkt->field); \
option += coap_serialize_array_option(number, current_number, option, (uint8_t *)coap_pkt->field, coap_pkt->field##_len, splitter); \
current_number = number; \
}
#define COAP_SERIALIZE_BLOCK_OPTION(number, field, text) \
if(IS_OPTION(coap_pkt, number)) \
{ \
PRINTF(text " [%lu%s (%u B/blk)]\n", coap_pkt->field##_num, coap_pkt->field##_more ? "+" : "", coap_pkt->field##_size); \
uint32_t block = coap_pkt->field##_num << 4; \
if(coap_pkt->field##_more) { block |= 0x8; } \
block |= 0xF & coap_log_2(coap_pkt->field##_size / 16); \
PRINTF(text " encoded: 0x%lX\n", block); \
option += coap_serialize_int_option(number, current_number, option, block); \
current_number = number; \
}
/* to store error code and human-readable payload */
extern coap_status_t erbium_status_code;
extern char *coap_error_message;
void coap_init_connection(uint16_t port);
uint16_t coap_get_mid(void);
void coap_init_message(void *packet, coap_message_type_t type, uint8_t code,
uint16_t mid);
size_t coap_serialize_message(void *packet, uint8_t *buffer);
void coap_send_message(uip_ipaddr_t *addr, uint16_t port, uint8_t *data,
uint16_t length);
coap_status_t coap_parse_message(void *request, uint8_t *data,
uint16_t data_len);
int coap_get_query_variable(void *packet, const char *name,
const char **output);
int coap_get_post_variable(void *packet, const char *name,
const char **output);
/*---------------------------------------------------------------------------*/
int coap_set_status_code(void *packet, unsigned int code);
int coap_set_token(void *packet, const uint8_t *token, size_t token_len);
int coap_get_header_content_format(void *packet, unsigned int *format);
int coap_set_header_content_format(void *packet, unsigned int format);
int coap_get_header_accept(void *packet, unsigned int *accept);
int coap_set_header_accept(void *packet, unsigned int accept);
int coap_get_header_max_age(void *packet, uint32_t *age);
int coap_set_header_max_age(void *packet, uint32_t age);
int coap_get_header_etag(void *packet, const uint8_t **etag);
int coap_set_header_etag(void *packet, const uint8_t *etag, size_t etag_len);
int coap_get_header_if_match(void *packet, const uint8_t **etag);
int coap_set_header_if_match(void *packet, const uint8_t *etag,
size_t etag_len);
int coap_get_header_if_none_match(void *packet);
int coap_set_header_if_none_match(void *packet);
int coap_get_header_proxy_uri(void *packet, const char **uri); /* in-place string might not be 0-terminated. */
int coap_set_header_proxy_uri(void *packet, const char *uri);
int coap_get_header_proxy_scheme(void *packet, const char **scheme); /* in-place string might not be 0-terminated. */
int coap_set_header_proxy_scheme(void *packet, const char *scheme);
int coap_get_header_uri_host(void *packet, const char **host); /* in-place string might not be 0-terminated. */
int coap_set_header_uri_host(void *packet, const char *host);
int coap_get_header_uri_path(void *packet, const char **path); /* in-place string might not be 0-terminated. */
int coap_set_header_uri_path(void *packet, const char *path);
int coap_get_header_uri_query(void *packet, const char **query); /* in-place string might not be 0-terminated. */
int coap_set_header_uri_query(void *packet, const char *query);
int coap_get_header_location_path(void *packet, const char **path); /* in-place string might not be 0-terminated. */
int coap_set_header_location_path(void *packet, const char *path); /* also splits optional query into Location-Query option. */
int coap_get_header_location_query(void *packet, const char **query); /* in-place string might not be 0-terminated. */
int coap_set_header_location_query(void *packet, const char *query);
int coap_get_header_observe(void *packet, uint32_t *observe);
int coap_set_header_observe(void *packet, uint32_t observe);
int coap_get_header_block2(void *packet, uint32_t *num, uint8_t *more,
uint16_t *size, uint32_t *offset);
int coap_set_header_block2(void *packet, uint32_t num, uint8_t more,
uint16_t size);
int coap_get_header_block1(void *packet, uint32_t *num, uint8_t *more,
uint16_t *size, uint32_t *offset);
int coap_set_header_block1(void *packet, uint32_t num, uint8_t more,
uint16_t size);
int coap_get_header_size2(void *packet, uint32_t *size);
int coap_set_header_size2(void *packet, uint32_t size);
int coap_get_header_size1(void *packet, uint32_t *size);
int coap_set_header_size1(void *packet, uint32_t size);
int coap_get_payload(void *packet, const uint8_t **payload);
int coap_set_payload(void *packet, const void *payload, size_t length);
#endif /* ER_COAP_H_ */

236
apps/rest-engine/rest-constants.h Executable file → Normal file
View file

@ -1,118 +1,118 @@
/*
* Copyright (c) 2013, Institute for Pervasive Computing, ETH Zurich
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name of the Institute nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*
* This file is part of the Contiki operating system.
*/
/**
* \file
* Constants for the REST Engine (Erbium).
* \author
* Matthias Kovatsch <kovatsch@inf.ethz.ch>
*/
#ifndef REST_CONSTANTS_H_
#define REST_CONSTANTS_H_
/**
* Generic status codes that are mapped to either HTTP or CoAP codes.
*/
struct rest_implementation_status {
const unsigned int OK; /* CONTENT_2_05, OK_200 */
const unsigned int CREATED; /* CREATED_2_01, CREATED_201 */
const unsigned int CHANGED; /* CHANGED_2_04, NO_CONTENT_204 */
const unsigned int DELETED; /* DELETED_2_02, NO_CONTENT_204 */
const unsigned int NOT_MODIFIED; /* VALID_2_03, NOT_MODIFIED_304 */
const unsigned int BAD_REQUEST; /* BAD_REQUEST_4_00, BAD_REQUEST_400 */
const unsigned int UNAUTHORIZED; /* UNAUTHORIZED_4_01, UNAUTHORIZED_401 */
const unsigned int BAD_OPTION; /* BAD_OPTION_4_02, BAD_REQUEST_400 */
const unsigned int FORBIDDEN; /* FORBIDDEN_4_03, FORBIDDEN_403 */
const unsigned int NOT_FOUND; /* NOT_FOUND_4_04, NOT_FOUND_404 */
const unsigned int METHOD_NOT_ALLOWED; /* METHOD_NOT_ALLOWED_4_05, METHOD_NOT_ALLOWED_405 */
const unsigned int NOT_ACCEPTABLE; /* NOT_ACCEPTABLE_4_06, NOT_ACCEPTABLE_406 */
const unsigned int REQUEST_ENTITY_TOO_LARGE; /* REQUEST_ENTITY_TOO_LARGE_4_13, REQUEST_ENTITY_TOO_LARGE_413 */
const unsigned int UNSUPPORTED_MEDIA_TYPE; /* UNSUPPORTED_MEDIA_TYPE_4_15, UNSUPPORTED_MEDIA_TYPE_415 */
const unsigned int INTERNAL_SERVER_ERROR; /* INTERNAL_SERVER_ERROR_5_00, INTERNAL_SERVER_ERROR_500 */
const unsigned int NOT_IMPLEMENTED; /* NOT_IMPLEMENTED_5_01, NOT_IMPLEMENTED_501 */
const unsigned int BAD_GATEWAY; /* BAD_GATEWAY_5_02, BAD_GATEWAY_502 */
const unsigned int SERVICE_UNAVAILABLE; /* SERVICE_UNAVAILABLE_5_03, SERVICE_UNAVAILABLE_503 */
const unsigned int GATEWAY_TIMEOUT; /* GATEWAY_TIMEOUT_5_04, GATEWAY_TIMEOUT_504 */
const unsigned int PROXYING_NOT_SUPPORTED; /* PROXYING_NOT_SUPPORTED_5_05, INTERNAL_SERVER_ERROR_500 */
};
/**
* List of Content-Formats which are Internet Media Types plus encoding.
* TODO This should be a constant enum taken from CoAP for both CoAP and HTTP.
*/
struct rest_implementation_type {
unsigned int TEXT_PLAIN;
unsigned int TEXT_XML;
unsigned int TEXT_CSV;
unsigned int TEXT_HTML;
unsigned int IMAGE_GIF;
unsigned int IMAGE_JPEG;
unsigned int IMAGE_PNG;
unsigned int IMAGE_TIFF;
unsigned int AUDIO_RAW;
unsigned int VIDEO_RAW;
unsigned int APPLICATION_LINK_FORMAT;
unsigned int APPLICATION_XML;
unsigned int APPLICATION_OCTET_STREAM;
unsigned int APPLICATION_RDF_XML;
unsigned int APPLICATION_SOAP_XML;
unsigned int APPLICATION_ATOM_XML;
unsigned int APPLICATION_XMPP_XML;
unsigned int APPLICATION_EXI;
unsigned int APPLICATION_FASTINFOSET;
unsigned int APPLICATION_SOAP_FASTINFOSET;
unsigned int APPLICATION_JSON;
unsigned int APPLICATION_X_OBIX_BINARY;
};
/**
* Resource flags for allowed methods and special functionalities.
*/
typedef enum {
NO_FLAGS = 0,
/* methods to handle */
METHOD_GET = (1 << 0),
METHOD_POST = (1 << 1),
METHOD_PUT = (1 << 2),
METHOD_DELETE = (1 << 3),
/* special flags */
HAS_SUB_RESOURCES = (1 << 4),
IS_SEPARATE = (1 << 5),
IS_OBSERVABLE = (1 << 6),
IS_PERIODIC = (1 << 7)
} rest_resource_flags_t;
#endif /* REST_CONSTANTS_H_ */
/*
* Copyright (c) 2013, Institute for Pervasive Computing, ETH Zurich
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name of the Institute nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*
* This file is part of the Contiki operating system.
*/
/**
* \file
* Constants for the REST Engine (Erbium).
* \author
* Matthias Kovatsch <kovatsch@inf.ethz.ch>
*/
#ifndef REST_CONSTANTS_H_
#define REST_CONSTANTS_H_
/**
* Generic status codes that are mapped to either HTTP or CoAP codes.
*/
struct rest_implementation_status {
const unsigned int OK; /* CONTENT_2_05, OK_200 */
const unsigned int CREATED; /* CREATED_2_01, CREATED_201 */
const unsigned int CHANGED; /* CHANGED_2_04, NO_CONTENT_204 */
const unsigned int DELETED; /* DELETED_2_02, NO_CONTENT_204 */
const unsigned int NOT_MODIFIED; /* VALID_2_03, NOT_MODIFIED_304 */
const unsigned int BAD_REQUEST; /* BAD_REQUEST_4_00, BAD_REQUEST_400 */
const unsigned int UNAUTHORIZED; /* UNAUTHORIZED_4_01, UNAUTHORIZED_401 */
const unsigned int BAD_OPTION; /* BAD_OPTION_4_02, BAD_REQUEST_400 */
const unsigned int FORBIDDEN; /* FORBIDDEN_4_03, FORBIDDEN_403 */
const unsigned int NOT_FOUND; /* NOT_FOUND_4_04, NOT_FOUND_404 */
const unsigned int METHOD_NOT_ALLOWED; /* METHOD_NOT_ALLOWED_4_05, METHOD_NOT_ALLOWED_405 */
const unsigned int NOT_ACCEPTABLE; /* NOT_ACCEPTABLE_4_06, NOT_ACCEPTABLE_406 */
const unsigned int REQUEST_ENTITY_TOO_LARGE; /* REQUEST_ENTITY_TOO_LARGE_4_13, REQUEST_ENTITY_TOO_LARGE_413 */
const unsigned int UNSUPPORTED_MEDIA_TYPE; /* UNSUPPORTED_MEDIA_TYPE_4_15, UNSUPPORTED_MEDIA_TYPE_415 */
const unsigned int INTERNAL_SERVER_ERROR; /* INTERNAL_SERVER_ERROR_5_00, INTERNAL_SERVER_ERROR_500 */
const unsigned int NOT_IMPLEMENTED; /* NOT_IMPLEMENTED_5_01, NOT_IMPLEMENTED_501 */
const unsigned int BAD_GATEWAY; /* BAD_GATEWAY_5_02, BAD_GATEWAY_502 */
const unsigned int SERVICE_UNAVAILABLE; /* SERVICE_UNAVAILABLE_5_03, SERVICE_UNAVAILABLE_503 */
const unsigned int GATEWAY_TIMEOUT; /* GATEWAY_TIMEOUT_5_04, GATEWAY_TIMEOUT_504 */
const unsigned int PROXYING_NOT_SUPPORTED; /* PROXYING_NOT_SUPPORTED_5_05, INTERNAL_SERVER_ERROR_500 */
};
/**
* List of Content-Formats which are Internet Media Types plus encoding.
* TODO This should be a constant enum taken from CoAP for both CoAP and HTTP.
*/
struct rest_implementation_type {
unsigned int TEXT_PLAIN;
unsigned int TEXT_XML;
unsigned int TEXT_CSV;
unsigned int TEXT_HTML;
unsigned int IMAGE_GIF;
unsigned int IMAGE_JPEG;
unsigned int IMAGE_PNG;
unsigned int IMAGE_TIFF;
unsigned int AUDIO_RAW;
unsigned int VIDEO_RAW;
unsigned int APPLICATION_LINK_FORMAT;
unsigned int APPLICATION_XML;
unsigned int APPLICATION_OCTET_STREAM;
unsigned int APPLICATION_RDF_XML;
unsigned int APPLICATION_SOAP_XML;
unsigned int APPLICATION_ATOM_XML;
unsigned int APPLICATION_XMPP_XML;
unsigned int APPLICATION_EXI;
unsigned int APPLICATION_FASTINFOSET;
unsigned int APPLICATION_SOAP_FASTINFOSET;
unsigned int APPLICATION_JSON;
unsigned int APPLICATION_X_OBIX_BINARY;
};
/**
* Resource flags for allowed methods and special functionalities.
*/
typedef enum {
NO_FLAGS = 0,
/* methods to handle */
METHOD_GET = (1 << 0),
METHOD_POST = (1 << 1),
METHOD_PUT = (1 << 2),
METHOD_DELETE = (1 << 3),
/* special flags */
HAS_SUB_RESOURCES = (1 << 4),
IS_SEPARATE = (1 << 5),
IS_OBSERVABLE = (1 << 6),
IS_PERIODIC = (1 << 7)
} rest_resource_flags_t;
#endif /* REST_CONSTANTS_H_ */

430
apps/rest-engine/rest-engine.c Executable file → Normal file
View file

@ -1,212 +1,218 @@
/*
* Copyright (c) 2013, Institute for Pervasive Computing, ETH Zurich
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name of the Institute nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*
* This file is part of the Contiki operating system.
*/
/**
* \file
* An abstraction layer for RESTful Web services (Erbium).
* Inspired by RESTful Contiki by Dogan Yazar.
* \author
* Matthias Kovatsch <kovatsch@inf.ethz.ch>
*/
#include <string.h>
#include <stdio.h>
#include "contiki.h"
#include "rest-engine.h"
#define DEBUG DEBUG_NONE
#include "net/uip-debug.h"
PROCESS(rest_engine_process, "REST Engine");
/*---------------------------------------------------------------------------*/
LIST(restful_services);
LIST(restful_periodic_services);
/*---------------------------------------------------------------------------*/
/*- REST Engine API ---------------------------------------------------------*/
/*---------------------------------------------------------------------------*/
/**
* \brief Initializes and starts the REST Engine process
*
* This function must be called by server processes before any resources are
* registered through rest_activate_resource().
*/
void
rest_init_engine(void)
{
list_init(restful_services);
REST.set_service_callback(rest_invoke_restful_service);
/* Start the RESTful server implementation. */
REST.init();
/*Start REST engine process */
process_start(&rest_engine_process, NULL);
}
/*---------------------------------------------------------------------------*/
/**
* \brief Makes a resource available under the given URI path
* \param resource A pointer to a resource implementation
* \param path The URI path string for this resource
*
* The resource implementation must be imported first using the
* extern keyword. The build system takes care of compiling every
* *.c file in the ./resources/ sub-directory (see example Makefile).
*/
void
rest_activate_resource(resource_t * resource, char *path)
{
resource->url = path;
list_add(restful_services, resource);
PRINTF("Activating: %s\n", resource->url);
/* Only add periodic resources with a periodic_handler and a period > 0. */
if(resource->flags & IS_PERIODIC && resource->periodic->periodic_handler
&& resource->periodic->period) {
PRINTF("Periodic resource: %p (%s)\n", resource->periodic,
resource->periodic->resource->url);
list_add(restful_periodic_services, resource->periodic);
}
}
/*---------------------------------------------------------------------------*/
/*- Internal API ------------------------------------------------------------*/
/*---------------------------------------------------------------------------*/
list_t
rest_get_resources(void)
{
return restful_services;
}
/*---------------------------------------------------------------------------*/
int
rest_invoke_restful_service(void *request, void *response, uint8_t * buffer,
uint16_t buffer_size, int32_t * offset)
{
uint8_t found = 0;
uint8_t allowed = 1;
resource_t *resource = NULL;
const char *url = NULL;
for(resource = (resource_t *) list_head(restful_services);
resource; resource = resource->next) {
/* if the web service handles that kind of requests and urls matches */
if((REST.get_url(request, &url) == strlen(resource->url)
|| (REST.get_url(request, &url) > strlen(resource->url)
&& (resource->flags & HAS_SUB_RESOURCES)))
&& strncmp(resource->url, url, strlen(resource->url)) == 0) {
found = 1;
rest_resource_flags_t method = REST.get_method_type(request);
PRINTF("/%s, method %u, resource->flags %u\n", resource->url,
(uint16_t) method, resource->flags);
if((method & METHOD_GET) && resource->get_handler != NULL) {
/* call handler function */
resource->get_handler(request, response, buffer, buffer_size, offset);
} else if((method & METHOD_POST) && resource->post_handler != NULL) {
/* call handler function */
resource->post_handler(request, response, buffer, buffer_size,
offset);
} else if((method & METHOD_PUT) && resource->put_handler != NULL) {
/* call handler function */
resource->put_handler(request, response, buffer, buffer_size, offset);
} else if((method & METHOD_DELETE) && resource->delete_handler != NULL) {
/* call handler function */
resource->delete_handler(request, response, buffer, buffer_size,
offset);
} else {
allowed = 0;
REST.set_response_status(response, REST.status.METHOD_NOT_ALLOWED);
}
break;
}
}
if(!found) {
REST.set_response_status(response, REST.status.NOT_FOUND);
} else if(allowed) {
/* final handler for special flags */
if(resource->flags & IS_OBSERVABLE) {
REST.subscription_handler(resource, request, response);
}
}
return found & allowed;
}
/*-----------------------------------------------------------------------------------*/
PROCESS_THREAD(rest_engine_process, ev, data)
{
PROCESS_BEGIN();
/* pause to let REST server finish adding resources. */
PROCESS_PAUSE();
/* initialize the PERIODIC_RESOURCE timers, which will be handled by this process. */
periodic_resource_t *periodic_resource = NULL;
for(periodic_resource =
(periodic_resource_t *) list_head(restful_periodic_services);
periodic_resource; periodic_resource = periodic_resource->next) {
if(periodic_resource->periodic_handler && periodic_resource->period) {
PRINTF("Periodic: Set timer for /%s to %lu\n",
periodic_resource->resource->url, periodic_resource->period);
etimer_set(&periodic_resource->periodic_timer,
periodic_resource->period);
}
}
while(1) {
PROCESS_WAIT_EVENT();
if(ev == PROCESS_EVENT_TIMER) {
for(periodic_resource =
(periodic_resource_t *) list_head(restful_periodic_services);
periodic_resource; periodic_resource = periodic_resource->next) {
if(periodic_resource->period
&& etimer_expired(&periodic_resource->periodic_timer)) {
PRINTF("Periodic: etimer expired for /%s (period: %lu)\n",
periodic_resource->resource->url, periodic_resource->period);
/* Call the periodic_handler function, which was checked during adding to list. */
(periodic_resource->periodic_handler) ();
etimer_reset(&periodic_resource->periodic_timer);
}
}
}
}
PROCESS_END();
}
/*---------------------------------------------------------------------------*/
/*
* Copyright (c) 2013, Institute for Pervasive Computing, ETH Zurich
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name of the Institute nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*
* This file is part of the Contiki operating system.
*/
/**
* \file
* An abstraction layer for RESTful Web services (Erbium).
* Inspired by RESTful Contiki by Dogan Yazar.
* \author
* Matthias Kovatsch <kovatsch@inf.ethz.ch>
*/
#include <string.h>
#include <stdio.h>
#include "contiki.h"
#include "rest-engine.h"
#define DEBUG 0
#if DEBUG
#include <stdio.h>
#define PRINTF(...) printf(__VA_ARGS__)
#define PRINT6ADDR(addr) PRINTF("[%02x%02x:%02x%02x:%02x%02x:%02x%02x:%02x%02x:%02x%02x:%02x%02x:%02x%02x]", ((uint8_t *)addr)[0], ((uint8_t *)addr)[1], ((uint8_t *)addr)[2], ((uint8_t *)addr)[3], ((uint8_t *)addr)[4], ((uint8_t *)addr)[5], ((uint8_t *)addr)[6], ((uint8_t *)addr)[7], ((uint8_t *)addr)[8], ((uint8_t *)addr)[9], ((uint8_t *)addr)[10], ((uint8_t *)addr)[11], ((uint8_t *)addr)[12], ((uint8_t *)addr)[13], ((uint8_t *)addr)[14], ((uint8_t *)addr)[15])
#define PRINTLLADDR(lladdr) PRINTF("[%02x:%02x:%02x:%02x:%02x:%02x]", (lladdr)->addr[0], (lladdr)->addr[1], (lladdr)->addr[2], (lladdr)->addr[3], (lladdr)->addr[4], (lladdr)->addr[5])
#else
#define PRINTF(...)
#define PRINT6ADDR(addr)
#define PRINTLLADDR(addr)
#endif
PROCESS(rest_engine_process, "REST Engine");
/*---------------------------------------------------------------------------*/
LIST(restful_services);
LIST(restful_periodic_services);
/*---------------------------------------------------------------------------*/
/*- REST Engine API ---------------------------------------------------------*/
/*---------------------------------------------------------------------------*/
/**
* \brief Initializes and starts the REST Engine process
*
* This function must be called by server processes before any resources are
* registered through rest_activate_resource().
*/
void
rest_init_engine(void)
{
list_init(restful_services);
REST.set_service_callback(rest_invoke_restful_service);
/* Start the RESTful server implementation. */
REST.init();
/*Start REST engine process */
process_start(&rest_engine_process, NULL);
}
/*---------------------------------------------------------------------------*/
/**
* \brief Makes a resource available under the given URI path
* \param resource A pointer to a resource implementation
* \param path The URI path string for this resource
*
* The resource implementation must be imported first using the
* extern keyword. The build system takes care of compiling every
* *.c file in the ./resources/ sub-directory (see example Makefile).
*/
void
rest_activate_resource(resource_t *resource, char *path)
{
resource->url = path;
list_add(restful_services, resource);
PRINTF("Activating: %s\n", resource->url);
/* Only add periodic resources with a periodic_handler and a period > 0. */
if(resource->flags & IS_PERIODIC && resource->periodic->periodic_handler
&& resource->periodic->period) {
PRINTF("Periodic resource: %p (%s)\n", resource->periodic,
resource->periodic->resource->url);
list_add(restful_periodic_services, resource->periodic);
}
}
/*---------------------------------------------------------------------------*/
/*- Internal API ------------------------------------------------------------*/
/*---------------------------------------------------------------------------*/
list_t
rest_get_resources(void)
{
return restful_services;
}
/*---------------------------------------------------------------------------*/
int
rest_invoke_restful_service(void *request, void *response, uint8_t *buffer,
uint16_t buffer_size, int32_t *offset)
{
uint8_t found = 0;
uint8_t allowed = 1;
resource_t *resource = NULL;
const char *url = NULL;
for(resource = (resource_t *)list_head(restful_services);
resource; resource = resource->next) {
/* if the web service handles that kind of requests and urls matches */
if((REST.get_url(request, &url) == strlen(resource->url)
|| (REST.get_url(request, &url) > strlen(resource->url)
&& (resource->flags & HAS_SUB_RESOURCES)))
&& strncmp(resource->url, url, strlen(resource->url)) == 0) {
found = 1;
rest_resource_flags_t method = REST.get_method_type(request);
PRINTF("/%s, method %u, resource->flags %u\n", resource->url,
(uint16_t)method, resource->flags);
if((method & METHOD_GET) && resource->get_handler != NULL) {
/* call handler function */
resource->get_handler(request, response, buffer, buffer_size, offset);
} else if((method & METHOD_POST) && resource->post_handler != NULL) {
/* call handler function */
resource->post_handler(request, response, buffer, buffer_size,
offset);
} else if((method & METHOD_PUT) && resource->put_handler != NULL) {
/* call handler function */
resource->put_handler(request, response, buffer, buffer_size, offset);
} else if((method & METHOD_DELETE) && resource->delete_handler != NULL) {
/* call handler function */
resource->delete_handler(request, response, buffer, buffer_size,
offset);
} else {
allowed = 0;
REST.set_response_status(response, REST.status.METHOD_NOT_ALLOWED);
}
break;
}
}
if(!found) {
REST.set_response_status(response, REST.status.NOT_FOUND);
} else if(allowed) {
/* final handler for special flags */
if(resource->flags & IS_OBSERVABLE) {
REST.subscription_handler(resource, request, response);
}
}
return found & allowed;
}
/*-----------------------------------------------------------------------------------*/
PROCESS_THREAD(rest_engine_process, ev, data)
{
PROCESS_BEGIN();
/* pause to let REST server finish adding resources. */
PROCESS_PAUSE();
/* initialize the PERIODIC_RESOURCE timers, which will be handled by this process. */
periodic_resource_t *periodic_resource = NULL;
for(periodic_resource =
(periodic_resource_t *)list_head(restful_periodic_services);
periodic_resource; periodic_resource = periodic_resource->next) {
if(periodic_resource->periodic_handler && periodic_resource->period) {
PRINTF("Periodic: Set timer for /%s to %lu\n",
periodic_resource->resource->url, periodic_resource->period);
etimer_set(&periodic_resource->periodic_timer,
periodic_resource->period);
}
}
while(1) {
PROCESS_WAIT_EVENT();
if(ev == PROCESS_EVENT_TIMER) {
for(periodic_resource =
(periodic_resource_t *)list_head(restful_periodic_services);
periodic_resource; periodic_resource = periodic_resource->next) {
if(periodic_resource->period
&& etimer_expired(&periodic_resource->periodic_timer)) {
PRINTF("Periodic: etimer expired for /%s (period: %lu)\n",
periodic_resource->resource->url, periodic_resource->period);
/* Call the periodic_handler function, which was checked during adding to list. */
(periodic_resource->periodic_handler)();
etimer_reset(&periodic_resource->periodic_timer);
}
}
}
}
PROCESS_END();
}
/*---------------------------------------------------------------------------*/

525
apps/rest-engine/rest-engine.h Executable file → Normal file
View file

@ -1,263 +1,262 @@
/*
* Copyright (c) 2013, Institute for Pervasive Computing, ETH Zurich
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name of the Institute nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*
* This file is part of the Contiki operating system.
*/
/**
* \file
* An abstraction layer for RESTful Web services (Erbium).
* Inspired by RESTful Contiki by Dogan Yazar.
* \author
* Matthias Kovatsch <kovatsch@inf.ethz.ch>
*/
#ifndef REST_ENGINE_H_
#define REST_ENGINE_H_
#include <stdio.h>
#include "contiki.h"
#include "contiki-lib.h"
#include "rest-constants.h"
/* list of valid REST Enigne implementations */
#define REGISTERED_ENGINE_ERBIUM coap_rest_implementation
#define REGISTERED_ENGINE_HELIUM http_rest_implementation
/* sanity check for configured implementation */
#if !defined(REST) || (REST!=REGISTERED_ENGINE_ERBIUM && REST!=REGISTERED_ENGINE_HELIUM)
#error "Define a valid REST Engine implementation (REST define)!"
#endif
/*
* The maximum buffer size that is provided for resource responses and must be respected due to the limited IP buffer.
* Larger data must be handled by the resource and will be sent chunk-wise through a TCP stream or CoAP blocks.
*/
#ifndef REST_MAX_CHUNK_SIZE
#define REST_MAX_CHUNK_SIZE 64
#endif
#ifndef MIN
#define MIN(a, b) ((a) < (b)? (a) : (b))
#endif /* MIN */
struct resource_s;
struct periodic_resource_s;
/* signatures of handler functions */
typedef void (*restful_handler) (void *request, void *response,
uint8_t * buffer, uint16_t preferred_size,
int32_t * offset);
typedef void (*restful_final_handler) (struct resource_s * resource,
void *request, void *response);
typedef void (*restful_periodic_handler) (void);
typedef void (*restful_response_handler) (void *data, void *response);
typedef void (*restful_trigger_handler) (void);
/* signature of the rest-engine service function */
typedef int (*service_callback_t) (void *request, void *response,
uint8_t * buffer, uint16_t preferred_size,
int32_t * offset);
/* data structure representing a resource in REST */
struct resource_s {
struct resource_s *next; /* for LIST, points to next resource defined */
const char *url; /*handled URL */
rest_resource_flags_t flags; /* handled RESTful methods */
const char *attributes; /* link-format attributes */
restful_handler get_handler; /* handler function */
restful_handler post_handler; /* handler function */
restful_handler put_handler; /* handler function */
restful_handler delete_handler; /* handler function */
union {
struct periodic_resource_s *periodic; /* special data depending on flags */
restful_trigger_handler trigger;
restful_trigger_handler resume;
};
};
typedef struct resource_s resource_t;
struct periodic_resource_s {
struct periodic_resource_s *next; /* for LIST, points to next resource defined */
const resource_t *resource;
uint32_t period;
struct etimer periodic_timer;
const restful_periodic_handler periodic_handler;
};
typedef struct periodic_resource_s periodic_resource_t;
/*
* Macro to define a RESTful resource.
* Resources are statically defined for the sake of efficiency and better memory management.
*/
#define RESOURCE(name, attributes, get_handler, post_handler, put_handler, delete_handler) \
resource_t name = {NULL, NULL, NO_FLAGS, attributes, get_handler, post_handler, put_handler, delete_handler, {NULL}}
#define PARENT_RESOURCE(name, attributes, get_handler, post_handler, put_handler, delete_handler) \
resource_t name = {NULL, NULL, HAS_SUB_RESOURCES, attributes, get_handler, post_handler, put_handler, delete_handler, {NULL}}
#define SEPARATE_RESOURCE(name, attributes, get_handler, post_handler, put_handler, delete_handler, resume_handler) \
resource_t name = {NULL, NULL, IS_SEPARATE, attributes, get_handler, post_handler, put_handler, delete_handler, { .resume = resume_handler }}
#define EVENT_RESOURCE(name, attributes, get_handler, post_handler, put_handler, delete_handler, event_handler) \
resource_t name = {NULL, NULL, IS_OBSERVABLE, attributes, get_handler, post_handler, put_handler, delete_handler, { .trigger = event_handler }}
/*
* Macro to define a periodic resource.
* The corresponding [name]_periodic_handler() function will be called every period.
* For instance polling a sensor and publishing a changed value to subscribed clients would be done there.
* The subscriber list will be maintained by the final_handler rest_subscription_handler() (see rest-mapping header file).
*/
#define PERIODIC_RESOURCE(name, attributes, get_handler, post_handler, put_handler, delete_handler, period, periodic_handler) \
periodic_resource_t periodic_##name; \
resource_t name = {NULL, NULL, IS_OBSERVABLE | IS_PERIODIC, attributes, get_handler, post_handler, put_handler, delete_handler, { .periodic = &periodic_##name }}; \
periodic_resource_t periodic_##name = {NULL, &name, period, {{0}}, periodic_handler};
struct rest_implementation {
char *name;
/** Initialize the REST implementation. */
void (*init) (void);
/** Register the RESTful service callback at implementation. */
void (*set_service_callback) (service_callback_t callback);
/** Get request URI path. */
int (*get_url) (void *request, const char **url);
/** Get the method of a request. */
rest_resource_flags_t (*get_method_type) (void *request);
/** Set the status code of a response. */
int (*set_response_status) (void *response, unsigned int code);
/** Get the content-type of a request. */
int (*get_header_content_type) (void *request,
unsigned int *content_format);
/** Set the Content-Type of a response. */
int (*set_header_content_type) (void *response,
unsigned int content_format);
/** Get the Accept types of a request. */
int (*get_header_accept) (void *request, unsigned int *accept);
/** Get the Length option of a request. */
int (*get_header_length) (void *request, uint32_t * size);
/** Set the Length option of a response. */
int (*set_header_length) (void *response, uint32_t size);
/** Get the Max-Age option of a request. */
int (*get_header_max_age) (void *request, uint32_t * age);
/** Set the Max-Age option of a response. */
int (*set_header_max_age) (void *response, uint32_t age);
/** Set the ETag option of a response. */
int (*set_header_etag) (void *response, const uint8_t * etag,
size_t length);
/** Get the If-Match option of a request. */
int (*get_header_if_match) (void *request, const uint8_t ** etag);
/** Get the If-Match option of a request. */
int (*get_header_if_none_match) (void *request);
/** Get the Host option of a request. */
int (*get_header_host) (void *request, const char **host);
/** Set the location option of a response. */
int (*set_header_location) (void *response, const char *location);
/** Get the payload option of a request. */
int (*get_request_payload) (void *request, const uint8_t ** payload);
/** Set the payload option of a response. */
int (*set_response_payload) (void *response, const void *payload,
size_t length);
/** Get the query string of a request. */
int (*get_query) (void *request, const char **value);
/** Get the value of a request query key-value pair. */
int (*get_query_variable) (void *request, const char *name,
const char **value);
/** Get the value of a request POST key-value pair. */
int (*get_post_variable) (void *request, const char *name,
const char **value);
/** Send the payload to all subscribers of the resource at url. */
void (*notify_subscribers) (resource_t * resource);
/** The handler for resource subscriptions. */
restful_final_handler subscription_handler;
/* REST status codes. */
const struct rest_implementation_status status;
/* REST content-types. */
const struct rest_implementation_type type;
};
/* instance of REST implementation */
extern const struct rest_implementation REST;
/*
* To be called by HTTP/COAP server as a callback function when a new service request appears.
* This function dispatches the corresponding RESTful service.
*/
int rest_invoke_restful_service(void *request, void *response,
uint8_t * buffer, uint16_t buffer_size,
int32_t * offset);
/*---------------------------------------------------------------------------*/
/**
* \brief Initializes REST framework and starts the HTTP or CoAP process.
*/
void rest_init_engine(void);
/*---------------------------------------------------------------------------*/
/**
*
* \brief Resources wanted to be accessible should be activated with the following code.
* \param resource
* A RESTful resource defined through the RESOURCE macros.
* \param path
* The local URI path where to provide the resource.
*/
void rest_activate_resource(resource_t * resource, char *path);
/*---------------------------------------------------------------------------*/
/**
* \brief Returns the list of registered RESTful resources.
* \return The resource list.
*/
list_t rest_get_resources(void);
/*---------------------------------------------------------------------------*/
#endif /*REST_ENGINE_H_ */
/*
* Copyright (c) 2013, Institute for Pervasive Computing, ETH Zurich
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name of the Institute nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*
* This file is part of the Contiki operating system.
*/
/**
* \file
* An abstraction layer for RESTful Web services (Erbium).
* Inspired by RESTful Contiki by Dogan Yazar.
* \author
* Matthias Kovatsch <kovatsch@inf.ethz.ch>
*/
#ifndef REST_ENGINE_H_
#define REST_ENGINE_H_
#include <stdio.h>
#include "contiki.h"
#include "contiki-lib.h"
#include "rest-constants.h"
/* list of valid REST Enigne implementations */
#define REGISTERED_ENGINE_ERBIUM coap_rest_implementation
#define REGISTERED_ENGINE_HELIUM http_rest_implementation
/* sanity check for configured implementation */
#if !defined(REST) || (REST != REGISTERED_ENGINE_ERBIUM && REST != REGISTERED_ENGINE_HELIUM)
#error "Define a valid REST Engine implementation (REST define)!"
#endif
/*
* The maximum buffer size that is provided for resource responses and must be respected due to the limited IP buffer.
* Larger data must be handled by the resource and will be sent chunk-wise through a TCP stream or CoAP blocks.
*/
#ifndef REST_MAX_CHUNK_SIZE
#define REST_MAX_CHUNK_SIZE 64
#endif
#ifndef MIN
#define MIN(a, b) ((a) < (b) ? (a) : (b))
#endif /* MIN */
struct resource_s;
struct periodic_resource_s;
/* signatures of handler functions */
typedef void (*restful_handler)(void *request, void *response,
uint8_t *buffer, uint16_t preferred_size,
int32_t *offset);
typedef void (*restful_final_handler)(struct resource_s *resource,
void *request, void *response);
typedef void (*restful_periodic_handler)(void);
typedef void (*restful_response_handler)(void *data, void *response);
typedef void (*restful_trigger_handler)(void);
/* signature of the rest-engine service function */
typedef int (*service_callback_t)(void *request, void *response,
uint8_t *buffer, uint16_t preferred_size,
int32_t *offset);
/* data structure representing a resource in REST */
struct resource_s {
struct resource_s *next; /* for LIST, points to next resource defined */
const char *url; /*handled URL */
rest_resource_flags_t flags; /* handled RESTful methods */
const char *attributes; /* link-format attributes */
restful_handler get_handler; /* handler function */
restful_handler post_handler; /* handler function */
restful_handler put_handler; /* handler function */
restful_handler delete_handler; /* handler function */
union {
struct periodic_resource_s *periodic; /* special data depending on flags */
restful_trigger_handler trigger;
restful_trigger_handler resume;
};
};
typedef struct resource_s resource_t;
struct periodic_resource_s {
struct periodic_resource_s *next; /* for LIST, points to next resource defined */
const resource_t *resource;
uint32_t period;
struct etimer periodic_timer;
const restful_periodic_handler periodic_handler;
};
typedef struct periodic_resource_s periodic_resource_t;
/*
* Macro to define a RESTful resource.
* Resources are statically defined for the sake of efficiency and better memory management.
*/
#define RESOURCE(name, attributes, get_handler, post_handler, put_handler, delete_handler) \
resource_t name = { NULL, NULL, NO_FLAGS, attributes, get_handler, post_handler, put_handler, delete_handler, { NULL } }
#define PARENT_RESOURCE(name, attributes, get_handler, post_handler, put_handler, delete_handler) \
resource_t name = { NULL, NULL, HAS_SUB_RESOURCES, attributes, get_handler, post_handler, put_handler, delete_handler, { NULL } }
#define SEPARATE_RESOURCE(name, attributes, get_handler, post_handler, put_handler, delete_handler, resume_handler) \
resource_t name = { NULL, NULL, IS_SEPARATE, attributes, get_handler, post_handler, put_handler, delete_handler, { .resume = resume_handler } }
#define EVENT_RESOURCE(name, attributes, get_handler, post_handler, put_handler, delete_handler, event_handler) \
resource_t name = { NULL, NULL, IS_OBSERVABLE, attributes, get_handler, post_handler, put_handler, delete_handler, { .trigger = event_handler } }
/*
* Macro to define a periodic resource.
* The corresponding [name]_periodic_handler() function will be called every period.
* For instance polling a sensor and publishing a changed value to subscribed clients would be done there.
* The subscriber list will be maintained by the final_handler rest_subscription_handler() (see rest-mapping header file).
*/
#define PERIODIC_RESOURCE(name, attributes, get_handler, post_handler, put_handler, delete_handler, period, periodic_handler) \
periodic_resource_t periodic_##name; \
resource_t name = { NULL, NULL, IS_OBSERVABLE | IS_PERIODIC, attributes, get_handler, post_handler, put_handler, delete_handler, { .periodic = &periodic_##name } }; \
periodic_resource_t periodic_##name = { NULL, &name, period, { { 0 } }, periodic_handler };
struct rest_implementation {
char *name;
/** Initialize the REST implementation. */
void (*init)(void);
/** Register the RESTful service callback at implementation. */
void (*set_service_callback)(service_callback_t callback);
/** Get request URI path. */
int (*get_url)(void *request, const char **url);
/** Get the method of a request. */
rest_resource_flags_t (*get_method_type)(void *request);
/** Set the status code of a response. */
int (*set_response_status)(void *response, unsigned int code);
/** Get the content-type of a request. */
int (*get_header_content_type)(void *request,
unsigned int *content_format);
/** Set the Content-Type of a response. */
int (*set_header_content_type)(void *response,
unsigned int content_format);
/** Get the Accept types of a request. */
int (*get_header_accept)(void *request, unsigned int *accept);
/** Get the Length option of a request. */
int (*get_header_length)(void *request, uint32_t *size);
/** Set the Length option of a response. */
int (*set_header_length)(void *response, uint32_t size);
/** Get the Max-Age option of a request. */
int (*get_header_max_age)(void *request, uint32_t *age);
/** Set the Max-Age option of a response. */
int (*set_header_max_age)(void *response, uint32_t age);
/** Set the ETag option of a response. */
int (*set_header_etag)(void *response, const uint8_t *etag,
size_t length);
/** Get the If-Match option of a request. */
int (*get_header_if_match)(void *request, const uint8_t **etag);
/** Get the If-Match option of a request. */
int (*get_header_if_none_match)(void *request);
/** Get the Host option of a request. */
int (*get_header_host)(void *request, const char **host);
/** Set the location option of a response. */
int (*set_header_location)(void *response, const char *location);
/** Get the payload option of a request. */
int (*get_request_payload)(void *request, const uint8_t **payload);
/** Set the payload option of a response. */
int (*set_response_payload)(void *response, const void *payload,
size_t length);
/** Get the query string of a request. */
int (*get_query)(void *request, const char **value);
/** Get the value of a request query key-value pair. */
int (*get_query_variable)(void *request, const char *name,
const char **value);
/** Get the value of a request POST key-value pair. */
int (*get_post_variable)(void *request, const char *name,
const char **value);
/** Send the payload to all subscribers of the resource at url. */
void (*notify_subscribers)(resource_t *resource);
/** The handler for resource subscriptions. */
restful_final_handler subscription_handler;
/* REST status codes. */
const struct rest_implementation_status status;
/* REST content-types. */
const struct rest_implementation_type type;
};
/* instance of REST implementation */
extern const struct rest_implementation REST;
/*
* To be called by HTTP/COAP server as a callback function when a new service request appears.
* This function dispatches the corresponding RESTful service.
*/
int rest_invoke_restful_service(void *request, void *response,
uint8_t *buffer, uint16_t buffer_size,
int32_t *offset);
/*---------------------------------------------------------------------------*/
/**
* \brief Initializes REST framework and starts the HTTP or CoAP process.
*/
void rest_init_engine(void);
/*---------------------------------------------------------------------------*/
/**
*
* \brief Resources wanted to be accessible should be activated with the following code.
* \param resource
* A RESTful resource defined through the RESOURCE macros.
* \param path
* The local URI path where to provide the resource.
*/
void rest_activate_resource(resource_t *resource, char *path);
/*---------------------------------------------------------------------------*/
/**
* \brief Returns the list of registered RESTful resources.
* \return The resource list.
*/
list_t rest_get_resources(void);
/*---------------------------------------------------------------------------*/
#endif /*REST_ENGINE_H_ */