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 * Copyright (c) 2013, Institute for Pervasive Computing, ETH Zurich
* All rights reserved. * All rights reserved.
* *
* Redistribution and use in source and binary forms, with or without * Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions * modification, are permitted provided that the following conditions
* are met: * are met:
* 1. Redistributions of source code must retain the above copyright * 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer. * notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright * 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the * notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution. * documentation and/or other materials provided with the distribution.
* 3. Neither the name of the Institute nor the names of its contributors * 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 * may be used to endorse or promote products derived from this software
* without specific prior written permission. * without specific prior written permission.
* *
* THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * 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 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE. * SUCH DAMAGE.
* *
* This file is part of the Contiki operating system. * This file is part of the Contiki operating system.
*/ */
/** /**
* \file * \file
* Collection of default configuration values. * Collection of default configuration values.
* \author * \author
* Matthias Kovatsch <kovatsch@inf.ethz.ch> * Matthias Kovatsch <kovatsch@inf.ethz.ch>
*/ */
#ifndef ER_COAP_CONF_H_ #ifndef ER_COAP_CONF_H_
#define ER_COAP_CONF_H_ #define ER_COAP_CONF_H_
/* Features that can be disabled to achieve smaller memory footprint */ /* Features that can be disabled to achieve smaller memory footprint */
#define COAP_LINK_FORMAT_FILTERING 0 #define COAP_LINK_FORMAT_FILTERING 0
#define COAP_PROXY_OPTION_PROCESSING 0 #define COAP_PROXY_OPTION_PROCESSING 0
/* Listening port for the CoAP REST Engine */ /* Listening port for the CoAP REST Engine */
#ifndef COAP_SERVER_PORT #ifndef COAP_SERVER_PORT
#define COAP_SERVER_PORT COAP_DEFAULT_PORT #define COAP_SERVER_PORT COAP_DEFAULT_PORT
#endif #endif
/* The number of concurrent messages that can be stored for retransmission in the transaction layer. */ /* The number of concurrent messages that can be stored for retransmission in the transaction layer. */
#ifndef COAP_MAX_OPEN_TRANSACTIONS #ifndef COAP_MAX_OPEN_TRANSACTIONS
#define COAP_MAX_OPEN_TRANSACTIONS 4 #define COAP_MAX_OPEN_TRANSACTIONS 4
#endif /* COAP_MAX_OPEN_TRANSACTIONS */ #endif /* COAP_MAX_OPEN_TRANSACTIONS */
/* Maximum number of failed request attempts before action */ /* Maximum number of failed request attempts before action */
#ifndef COAP_MAX_ATTEMPTS #ifndef COAP_MAX_ATTEMPTS
#define COAP_MAX_ATTEMPTS 4 #define COAP_MAX_ATTEMPTS 4
#endif /* COAP_MAX_ATTEMPTS */ #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 */ /* 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 */ #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 */ #define COAP_MAX_HEADER_SIZE (4 + COAP_TOKEN_LEN + 3 + 1 + COAP_ETAG_LEN + 4 + 4 + 30) /* 65 */
#endif /* COAP_MAX_HEADER_SIZE */ #endif /* COAP_MAX_HEADER_SIZE */
/* Number of observer slots (each takes abot xxx bytes) */ /* Number of observer slots (each takes abot xxx bytes) */
#ifndef COAP_MAX_OBSERVERS #ifndef COAP_MAX_OBSERVERS
#define COAP_MAX_OBSERVERS COAP_MAX_OPEN_TRANSACTIONS-1 #define COAP_MAX_OBSERVERS COAP_MAX_OPEN_TRANSACTIONS - 1
#endif /* COAP_MAX_OBSERVERS */ #endif /* COAP_MAX_OBSERVERS */
/* Interval in seconds in which NON notifies are changed to CON notifies to check client. */ /* Interval in seconds in which NON notifies are changed to CON notifies to check client. */
#define COAP_OBSERVE_REFRESH_INTERVAL 60 #define COAP_OBSERVE_REFRESH_INTERVAL 60
#endif /* ER_COAP_CONF_H_ */ #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 * Copyright (c) 2013, Institute for Pervasive Computing, ETH Zurich
* All rights reserved. * All rights reserved.
* *
* Redistribution and use in source and binary forms, with or without * Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions * modification, are permitted provided that the following conditions
* are met: * are met:
* 1. Redistributions of source code must retain the above copyright * 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer. * notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright * 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the * notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution. * documentation and/or other materials provided with the distribution.
* 3. Neither the name of the Institute nor the names of its contributors * 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 * may be used to endorse or promote products derived from this software
* without specific prior written permission. * without specific prior written permission.
* *
* THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * 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 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE. * SUCH DAMAGE.
* *
* This file is part of the Contiki operating system. * This file is part of the Contiki operating system.
*/ */
/** /**
* \file * \file
* Collection of constants specified in the CoAP standard. * Collection of constants specified in the CoAP standard.
* \author * \author
* Matthias Kovatsch <kovatsch@inf.ethz.ch> * Matthias Kovatsch <kovatsch@inf.ethz.ch>
*/ */
#ifndef ER_COAP_CONSTANTS_H_ #ifndef ER_COAP_CONSTANTS_H_
#define ER_COAP_CONSTANTS_H_ #define ER_COAP_CONSTANTS_H_
#define COAP_DEFAULT_PORT 5683 #define COAP_DEFAULT_PORT 5683
#define COAP_DEFAULT_MAX_AGE 60 #define COAP_DEFAULT_MAX_AGE 60
#define COAP_RESPONSE_TIMEOUT 3 #define COAP_RESPONSE_TIMEOUT 3
#define COAP_RESPONSE_RANDOM_FACTOR 1.5 #define COAP_RESPONSE_RANDOM_FACTOR 1.5
#define COAP_MAX_RETRANSMIT 4 #define COAP_MAX_RETRANSMIT 4
#define COAP_HEADER_LEN 4 /* | version:0x03 type:0x0C tkl:0xF0 | code | mid:0x00FF | mid:0xFF00 | */ #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_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_ETAG_LEN 8 /* The maximum number of bytes for the ETag */
#define COAP_HEADER_VERSION_MASK 0xC0 #define COAP_HEADER_VERSION_MASK 0xC0
#define COAP_HEADER_VERSION_POSITION 6 #define COAP_HEADER_VERSION_POSITION 6
#define COAP_HEADER_TYPE_MASK 0x30 #define COAP_HEADER_TYPE_MASK 0x30
#define COAP_HEADER_TYPE_POSITION 4 #define COAP_HEADER_TYPE_POSITION 4
#define COAP_HEADER_TOKEN_LEN_MASK 0x0F #define COAP_HEADER_TOKEN_LEN_MASK 0x0F
#define COAP_HEADER_TOKEN_LEN_POSITION 0 #define COAP_HEADER_TOKEN_LEN_POSITION 0
#define COAP_HEADER_OPTION_DELTA_MASK 0xF0 #define COAP_HEADER_OPTION_DELTA_MASK 0xF0
#define COAP_HEADER_OPTION_SHORT_LENGTH_MASK 0x0F #define COAP_HEADER_OPTION_SHORT_LENGTH_MASK 0x0F
/* CoAP message types */ /* CoAP message types */
typedef enum { typedef enum {
COAP_TYPE_CON, /* confirmables */ COAP_TYPE_CON, /* confirmables */
COAP_TYPE_NON, /* non-confirmables */ COAP_TYPE_NON, /* non-confirmables */
COAP_TYPE_ACK, /* acknowledgements */ COAP_TYPE_ACK, /* acknowledgements */
COAP_TYPE_RST /* reset */ COAP_TYPE_RST /* reset */
} coap_message_type_t; } coap_message_type_t;
/* CoAP request method codes */ /* CoAP request method codes */
typedef enum { typedef enum {
COAP_GET = 1, COAP_GET = 1,
COAP_POST, COAP_POST,
COAP_PUT, COAP_PUT,
COAP_DELETE COAP_DELETE
} coap_method_t; } coap_method_t;
/* CoAP response codes */ /* CoAP response codes */
typedef enum { typedef enum {
NO_ERROR = 0, NO_ERROR = 0,
CREATED_2_01 = 65, /* CREATED */ CREATED_2_01 = 65, /* CREATED */
DELETED_2_02 = 66, /* DELETED */ DELETED_2_02 = 66, /* DELETED */
VALID_2_03 = 67, /* NOT_MODIFIED */ VALID_2_03 = 67, /* NOT_MODIFIED */
CHANGED_2_04 = 68, /* CHANGED */ CHANGED_2_04 = 68, /* CHANGED */
CONTENT_2_05 = 69, /* OK */ CONTENT_2_05 = 69, /* OK */
BAD_REQUEST_4_00 = 128, /* BAD_REQUEST */ BAD_REQUEST_4_00 = 128, /* BAD_REQUEST */
UNAUTHORIZED_4_01 = 129, /* UNAUTHORIZED */ UNAUTHORIZED_4_01 = 129, /* UNAUTHORIZED */
BAD_OPTION_4_02 = 130, /* BAD_OPTION */ BAD_OPTION_4_02 = 130, /* BAD_OPTION */
FORBIDDEN_4_03 = 131, /* FORBIDDEN */ FORBIDDEN_4_03 = 131, /* FORBIDDEN */
NOT_FOUND_4_04 = 132, /* NOT_FOUND */ NOT_FOUND_4_04 = 132, /* NOT_FOUND */
METHOD_NOT_ALLOWED_4_05 = 133, /* METHOD_NOT_ALLOWED */ METHOD_NOT_ALLOWED_4_05 = 133, /* METHOD_NOT_ALLOWED */
NOT_ACCEPTABLE_4_06 = 134, /* NOT_ACCEPTABLE */ NOT_ACCEPTABLE_4_06 = 134, /* NOT_ACCEPTABLE */
PRECONDITION_FAILED_4_12 = 140, /* BAD_REQUEST */ PRECONDITION_FAILED_4_12 = 140, /* BAD_REQUEST */
REQUEST_ENTITY_TOO_LARGE_4_13 = 141, /* REQUEST_ENTITY_TOO_LARGE */ REQUEST_ENTITY_TOO_LARGE_4_13 = 141, /* REQUEST_ENTITY_TOO_LARGE */
UNSUPPORTED_MEDIA_TYPE_4_15 = 143, /* UNSUPPORTED_MEDIA_TYPE */ UNSUPPORTED_MEDIA_TYPE_4_15 = 143, /* UNSUPPORTED_MEDIA_TYPE */
INTERNAL_SERVER_ERROR_5_00 = 160, /* INTERNAL_SERVER_ERROR */ INTERNAL_SERVER_ERROR_5_00 = 160, /* INTERNAL_SERVER_ERROR */
NOT_IMPLEMENTED_5_01 = 161, /* NOT_IMPLEMENTED */ NOT_IMPLEMENTED_5_01 = 161, /* NOT_IMPLEMENTED */
BAD_GATEWAY_5_02 = 162, /* BAD_GATEWAY */ BAD_GATEWAY_5_02 = 162, /* BAD_GATEWAY */
SERVICE_UNAVAILABLE_5_03 = 163, /* SERVICE_UNAVAILABLE */ SERVICE_UNAVAILABLE_5_03 = 163, /* SERVICE_UNAVAILABLE */
GATEWAY_TIMEOUT_5_04 = 164, /* GATEWAY_TIMEOUT */ GATEWAY_TIMEOUT_5_04 = 164, /* GATEWAY_TIMEOUT */
PROXYING_NOT_SUPPORTED_5_05 = 165, /* PROXYING_NOT_SUPPORTED */ PROXYING_NOT_SUPPORTED_5_05 = 165, /* PROXYING_NOT_SUPPORTED */
/* Erbium errors */ /* Erbium errors */
MEMORY_ALLOCATION_ERROR = 192, MEMORY_ALLOCATION_ERROR = 192,
PACKET_SERIALIZATION_ERROR, PACKET_SERIALIZATION_ERROR,
/* Erbium hooks */ /* Erbium hooks */
MANUAL_RESPONSE, MANUAL_RESPONSE,
PING_RESPONSE PING_RESPONSE
} coap_status_t; } coap_status_t;
/* CoAP header option numbers */ /* CoAP header option numbers */
typedef enum { typedef enum {
COAP_OPTION_IF_MATCH = 1, /* 0-8 B */ COAP_OPTION_IF_MATCH = 1, /* 0-8 B */
COAP_OPTION_URI_HOST = 3, /* 1-255 B */ COAP_OPTION_URI_HOST = 3, /* 1-255 B */
COAP_OPTION_ETAG = 4, /* 1-8 B */ COAP_OPTION_ETAG = 4, /* 1-8 B */
COAP_OPTION_IF_NONE_MATCH = 5, /* 0 B */ COAP_OPTION_IF_NONE_MATCH = 5, /* 0 B */
COAP_OPTION_OBSERVE = 6, /* 0-3 B */ COAP_OPTION_OBSERVE = 6, /* 0-3 B */
COAP_OPTION_URI_PORT = 7, /* 0-2 B */ COAP_OPTION_URI_PORT = 7, /* 0-2 B */
COAP_OPTION_LOCATION_PATH = 8, /* 0-255 B */ COAP_OPTION_LOCATION_PATH = 8, /* 0-255 B */
COAP_OPTION_URI_PATH = 11, /* 0-255 B */ COAP_OPTION_URI_PATH = 11, /* 0-255 B */
COAP_OPTION_CONTENT_FORMAT = 12, /* 0-2 B */ COAP_OPTION_CONTENT_FORMAT = 12, /* 0-2 B */
COAP_OPTION_MAX_AGE = 14, /* 0-4 B */ COAP_OPTION_MAX_AGE = 14, /* 0-4 B */
COAP_OPTION_URI_QUERY = 15, /* 0-255 B */ COAP_OPTION_URI_QUERY = 15, /* 0-255 B */
COAP_OPTION_ACCEPT = 17, /* 0-2 B */ COAP_OPTION_ACCEPT = 17, /* 0-2 B */
COAP_OPTION_LOCATION_QUERY = 20, /* 0-255 B */ COAP_OPTION_LOCATION_QUERY = 20, /* 0-255 B */
COAP_OPTION_BLOCK2 = 23, /* 1-3 B */ COAP_OPTION_BLOCK2 = 23, /* 1-3 B */
COAP_OPTION_BLOCK1 = 27, /* 1-3 B */ COAP_OPTION_BLOCK1 = 27, /* 1-3 B */
COAP_OPTION_SIZE2 = 28, /* 0-4 B */ COAP_OPTION_SIZE2 = 28, /* 0-4 B */
COAP_OPTION_PROXY_URI = 35, /* 1-1034 B */ COAP_OPTION_PROXY_URI = 35, /* 1-1034 B */
COAP_OPTION_PROXY_SCHEME = 39, /* 1-255 B */ COAP_OPTION_PROXY_SCHEME = 39, /* 1-255 B */
COAP_OPTION_SIZE1 = 60, /* 0-4 B */ COAP_OPTION_SIZE1 = 60, /* 0-4 B */
} coap_option_t; } coap_option_t;
/* CoAP Content-Formats */ /* CoAP Content-Formats */
typedef enum { typedef enum {
TEXT_PLAIN = 0, TEXT_PLAIN = 0,
TEXT_XML = 1, TEXT_XML = 1,
TEXT_CSV = 2, TEXT_CSV = 2,
TEXT_HTML = 3, TEXT_HTML = 3,
IMAGE_GIF = 21, IMAGE_GIF = 21,
IMAGE_JPEG = 22, IMAGE_JPEG = 22,
IMAGE_PNG = 23, IMAGE_PNG = 23,
IMAGE_TIFF = 24, IMAGE_TIFF = 24,
AUDIO_RAW = 25, AUDIO_RAW = 25,
VIDEO_RAW = 26, VIDEO_RAW = 26,
APPLICATION_LINK_FORMAT = 40, APPLICATION_LINK_FORMAT = 40,
APPLICATION_XML = 41, APPLICATION_XML = 41,
APPLICATION_OCTET_STREAM = 42, APPLICATION_OCTET_STREAM = 42,
APPLICATION_RDF_XML = 43, APPLICATION_RDF_XML = 43,
APPLICATION_SOAP_XML = 44, APPLICATION_SOAP_XML = 44,
APPLICATION_ATOM_XML = 45, APPLICATION_ATOM_XML = 45,
APPLICATION_XMPP_XML = 46, APPLICATION_XMPP_XML = 46,
APPLICATION_EXI = 47, APPLICATION_EXI = 47,
APPLICATION_FASTINFOSET = 48, APPLICATION_FASTINFOSET = 48,
APPLICATION_SOAP_FASTINFOSET = 49, APPLICATION_SOAP_FASTINFOSET = 49,
APPLICATION_JSON = 50, APPLICATION_JSON = 50,
APPLICATION_X_OBIX_BINARY = 51 APPLICATION_X_OBIX_BINARY = 51
} coap_content_format_t; } coap_content_format_t;
#endif /* ER_COAP_CONSTANTS_H_ */ #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 * Copyright (c) 2013, Institute for Pervasive Computing, ETH Zurich
* All rights reserved. * All rights reserved.
* *
* Redistribution and use in source and binary forms, with or without * Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions * modification, are permitted provided that the following conditions
* are met: * are met:
* 1. Redistributions of source code must retain the above copyright * 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer. * notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright * 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the * notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution. * documentation and/or other materials provided with the distribution.
* 3. Neither the name of the Institute nor the names of its contributors * 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 * may be used to endorse or promote products derived from this software
* without specific prior written permission. * without specific prior written permission.
* *
* THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * 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 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE. * SUCH DAMAGE.
* *
* This file is part of the Contiki operating system. * This file is part of the Contiki operating system.
*/ */
/** /**
* \file * \file
* CoAP implementation for the REST Engine. * CoAP implementation for the REST Engine.
* \author * \author
* Matthias Kovatsch <kovatsch@inf.ethz.ch> * Matthias Kovatsch <kovatsch@inf.ethz.ch>
*/ */
#ifndef ER_COAP_ENGINE_H_ #ifndef ER_COAP_ENGINE_H_
#define ER_COAP_ENGINE_H_ #define ER_COAP_ENGINE_H_
#include "pt.h" #include "pt.h"
#include "er-coap.h" #include "er-coap.h"
#include "er-coap-transactions.h" #include "er-coap-transactions.h"
#include "er-coap-observe.h" #include "er-coap-observe.h"
#include "er-coap-separate.h" #include "er-coap-separate.h"
#define SERVER_LISTEN_PORT UIP_HTONS(COAP_SERVER_PORT) #define SERVER_LISTEN_PORT UIP_HTONS(COAP_SERVER_PORT)
typedef coap_packet_t rest_request_t; typedef coap_packet_t rest_request_t;
typedef coap_packet_t rest_response_t; typedef coap_packet_t rest_response_t;
void coap_init_engine(void); void coap_init_engine(void);
/*---------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------*/
/*- Client Part -------------------------------------------------------------*/ /*- Client Part -------------------------------------------------------------*/
/*---------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------*/
struct request_state_t { struct request_state_t {
struct pt pt; struct pt pt;
struct process *process; struct process *process;
coap_transaction_t *transaction; coap_transaction_t *transaction;
coap_packet_t *response; coap_packet_t *response;
uint32_t block_num; uint32_t block_num;
}; };
typedef void (*blocking_response_handler) (void *response); typedef void (*blocking_response_handler)(void *response);
PT_THREAD(coap_blocking_request PT_THREAD(coap_blocking_request
(struct request_state_t *state, process_event_t ev, (struct request_state_t *state, process_event_t ev,
uip_ipaddr_t * remote_ipaddr, uint16_t remote_port, uip_ipaddr_t *remote_ipaddr, uint16_t remote_port,
coap_packet_t * request, coap_packet_t *request,
blocking_response_handler request_callback)); blocking_response_handler request_callback));
#define COAP_BLOCKING_REQUEST(server_addr, server_port, request, chunk_handler) \ #define COAP_BLOCKING_REQUEST(server_addr, server_port, request, chunk_handler) \
{ \ { \
static struct request_state_t request_state; \ static struct request_state_t request_state; \
PT_SPAWN(process_pt, &request_state.pt, \ PT_SPAWN(process_pt, &request_state.pt, \
coap_blocking_request(&request_state, ev, \ coap_blocking_request(&request_state, ev, \
server_addr, server_port, \ server_addr, server_port, \
request, chunk_handler) \ request, chunk_handler) \
); \ ); \
} }
/*---------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------*/
#endif /* ER_COAP_ENGINE_H_ */ #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 * Copyright (c) 2013, Institute for Pervasive Computing, ETH Zurich
* All rights reserved. * All rights reserved.
* *
* Redistribution and use in source and binary forms, with or without * Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions * modification, are permitted provided that the following conditions
* are met: * are met:
* 1. Redistributions of source code must retain the above copyright * 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer. * notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright * 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the * notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution. * documentation and/or other materials provided with the distribution.
* 3. Neither the name of the Institute nor the names of its contributors * 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 * may be used to endorse or promote products derived from this software
* without specific prior written permission. * without specific prior written permission.
* *
* THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * 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 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE. * SUCH DAMAGE.
* *
* This file is part of the Contiki operating system. * This file is part of the Contiki operating system.
*/ */
/** /**
* \file * \file
* CoAP module for observing resources (draft-ietf-core-observe-11). * CoAP module for observing resources (draft-ietf-core-observe-11).
* \author * \author
* Matthias Kovatsch <kovatsch@inf.ethz.ch> * Matthias Kovatsch <kovatsch@inf.ethz.ch>
*/ */
#include <stdio.h> #include <stdio.h>
#include <string.h> #include <string.h>
#include "er-coap-observe.h" #include "er-coap-observe.h"
#define DEBUG DEBUG_NONE #define DEBUG 0
#include "net/uip-debug.h" #if DEBUG
#include <stdio.h>
/*---------------------------------------------------------------------------*/ #define PRINTF(...) printf(__VA_ARGS__)
MEMB(observers_memb, coap_observer_t, COAP_MAX_OBSERVERS); #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])
LIST(observers_list); #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
/*- Internal API ------------------------------------------------------------*/ #define PRINTF(...)
/*---------------------------------------------------------------------------*/ #define PRINT6ADDR(addr)
coap_observer_t * #define PRINTLLADDR(addr)
coap_add_observer(uip_ipaddr_t * addr, uint16_t port, const uint8_t * token, #endif
size_t token_len, const char *uri)
{ /*---------------------------------------------------------------------------*/
/* Remove existing observe relationship, if any. */ MEMB(observers_memb, coap_observer_t, COAP_MAX_OBSERVERS);
coap_remove_observer_by_uri(addr, port, uri); LIST(observers_list);
/*---------------------------------------------------------------------------*/
coap_observer_t *o = memb_alloc(&observers_memb); /*- Internal API ------------------------------------------------------------*/
/*---------------------------------------------------------------------------*/
if(o) { coap_observer_t *
o->url = uri; coap_add_observer(uip_ipaddr_t *addr, uint16_t port, const uint8_t *token,
uip_ipaddr_copy(&o->addr, addr); size_t token_len, const char *uri)
o->port = port; {
o->token_len = token_len; /* Remove existing observe relationship, if any. */
memcpy(o->token, token, token_len); coap_remove_observer_by_uri(addr, port, uri);
o->last_mid = 0;
coap_observer_t *o = memb_alloc(&observers_memb);
PRINTF("Adding observer for /%s [0x%02X%02X]\n", o->url, o->token[0],
o->token[1]); if(o) {
list_add(observers_list, o); o->url = uri;
} uip_ipaddr_copy(&o->addr, addr);
o->port = port;
return o; o->token_len = token_len;
} memcpy(o->token, token, token_len);
/*---------------------------------------------------------------------------*/ o->last_mid = 0;
/*- Removal -----------------------------------------------------------------*/
/*---------------------------------------------------------------------------*/ PRINTF("Adding observer for /%s [0x%02X%02X]\n", o->url, o->token[0],
void o->token[1]);
coap_remove_observer(coap_observer_t * o) list_add(observers_list, o);
{ }
PRINTF("Removing observer for /%s [0x%02X%02X]\n", o->url, o->token[0],
o->token[1]); return o;
}
memb_free(&observers_memb, o); /*---------------------------------------------------------------------------*/
list_remove(observers_list, o); /*- Removal -----------------------------------------------------------------*/
} /*---------------------------------------------------------------------------*/
/*---------------------------------------------------------------------------*/ void
int coap_remove_observer(coap_observer_t *o)
coap_remove_observer_by_client(uip_ipaddr_t * addr, uint16_t port) {
{ PRINTF("Removing observer for /%s [0x%02X%02X]\n", o->url, o->token[0],
int removed = 0; o->token[1]);
coap_observer_t *obs = NULL;
memb_free(&observers_memb, o);
for(obs = (coap_observer_t *) list_head(observers_list); obs; list_remove(observers_list, o);
obs = obs->next) { }
PRINTF("Remove check client "); /*---------------------------------------------------------------------------*/
PRINT6ADDR(addr); int
PRINTF(":%u\n", port); coap_remove_observer_by_client(uip_ipaddr_t *addr, uint16_t port)
if(uip_ipaddr_cmp(&obs->addr, addr) && obs->port == port) { {
coap_remove_observer(obs); int removed = 0;
removed++; coap_observer_t *obs = NULL;
}
} for(obs = (coap_observer_t *)list_head(observers_list); obs;
return removed; obs = obs->next) {
} PRINTF("Remove check client ");
/*---------------------------------------------------------------------------*/ PRINT6ADDR(addr);
int PRINTF(":%u\n", port);
coap_remove_observer_by_token(uip_ipaddr_t * addr, uint16_t port, if(uip_ipaddr_cmp(&obs->addr, addr) && obs->port == port) {
uint8_t * token, size_t token_len) coap_remove_observer(obs);
{ removed++;
int removed = 0; }
coap_observer_t *obs = NULL; }
return removed;
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]); int
if(uip_ipaddr_cmp(&obs->addr, addr) && obs->port == port coap_remove_observer_by_token(uip_ipaddr_t *addr, uint16_t port,
&& obs->token_len == token_len uint8_t *token, size_t token_len)
&& memcmp(obs->token, token, token_len) == 0) { {
coap_remove_observer(obs); int removed = 0;
removed++; coap_observer_t *obs = NULL;
}
} for(obs = (coap_observer_t *)list_head(observers_list); obs;
return removed; 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
int && obs->token_len == token_len
coap_remove_observer_by_uri(uip_ipaddr_t * addr, uint16_t port, && memcmp(obs->token, token, token_len) == 0) {
const char *uri) coap_remove_observer(obs);
{ removed++;
int removed = 0; }
coap_observer_t *obs = NULL; }
return removed;
for(obs = (coap_observer_t *) list_head(observers_list); obs; }
obs = obs->next) { /*---------------------------------------------------------------------------*/
PRINTF("Remove check URL %p\n", uri); int
if((addr == NULL coap_remove_observer_by_uri(uip_ipaddr_t *addr, uint16_t port,
|| (uip_ipaddr_cmp(&obs->addr, addr) && obs->port == port)) const char *uri)
&& (obs->url == uri || memcmp(obs->url, uri, strlen(obs->url)) == 0)) { {
coap_remove_observer(obs); int removed = 0;
removed++; coap_observer_t *obs = NULL;
}
} for(obs = (coap_observer_t *)list_head(observers_list); obs;
return removed; obs = obs->next) {
} PRINTF("Remove check URL %p\n", uri);
/*---------------------------------------------------------------------------*/ if((addr == NULL
int || (uip_ipaddr_cmp(&obs->addr, addr) && obs->port == port))
coap_remove_observer_by_mid(uip_ipaddr_t * addr, uint16_t port, uint16_t mid) && (obs->url == uri || memcmp(obs->url, uri, strlen(obs->url)) == 0)) {
{ coap_remove_observer(obs);
int removed = 0; removed++;
coap_observer_t *obs = NULL; }
}
for(obs = (coap_observer_t *) list_head(observers_list); obs; return removed;
obs = obs->next) { }
PRINTF("Remove check MID %u\n", mid); /*---------------------------------------------------------------------------*/
if(uip_ipaddr_cmp(&obs->addr, addr) && obs->port == port int
&& obs->last_mid == mid) { coap_remove_observer_by_mid(uip_ipaddr_t *addr, uint16_t port, uint16_t mid)
coap_remove_observer(obs); {
removed++; int removed = 0;
} coap_observer_t *obs = NULL;
}
return removed; for(obs = (coap_observer_t *)list_head(observers_list); obs;
} obs = obs->next) {
/*---------------------------------------------------------------------------*/ PRINTF("Remove check MID %u\n", mid);
/*- Notification ------------------------------------------------------------*/ if(uip_ipaddr_cmp(&obs->addr, addr) && obs->port == port
/*---------------------------------------------------------------------------*/ && obs->last_mid == mid) {
void coap_remove_observer(obs);
coap_notify_observers(resource_t * resource) removed++;
{ }
/* build notification */ }
coap_packet_t notification[1]; /* this way the packet can be treated as pointer as usual */ return removed;
coap_init_message(notification, COAP_TYPE_NON, CONTENT_2_05, 0); }
coap_observer_t *obs = NULL; /*---------------------------------------------------------------------------*/
/*- Notification ------------------------------------------------------------*/
PRINTF("Observe: Notification from %s\n", resource->url); /*---------------------------------------------------------------------------*/
void
/* iterate over observers */ coap_notify_observers(resource_t *resource)
for(obs = (coap_observer_t *) list_head(observers_list); obs; {
obs = obs->next) { /* build notification */
if(obs->url == resource->url) { /* using RESOURCE url pointer as handle */ coap_packet_t notification[1]; /* this way the packet can be treated as pointer as usual */
coap_transaction_t *transaction = NULL; coap_init_message(notification, COAP_TYPE_NON, CONTENT_2_05, 0);
coap_observer_t *obs = NULL;
/*TODO implement special transaction for CON, sharing the same buffer to allow for more observers */
PRINTF("Observe: Notification from %s\n", resource->url);
if((transaction =
coap_new_transaction(coap_get_mid(), &obs->addr, obs->port))) { /* iterate over observers */
PRINTF(" Observer "); for(obs = (coap_observer_t *)list_head(observers_list); obs;
PRINT6ADDR(&obs->addr); obs = obs->next) {
PRINTF(":%u\n", obs->port); if(obs->url == resource->url) { /* using RESOURCE url pointer as handle */
coap_transaction_t *transaction = NULL;
/* update last MID for RST matching */
obs->last_mid = transaction->mid; /*TODO implement special transaction for CON, sharing the same buffer to allow for more observers */
/* prepare response */ if((transaction =
notification->mid = transaction->mid; coap_new_transaction(coap_get_mid(), &obs->addr, obs->port))) {
PRINTF(" Observer ");
resource->get_handler(NULL, notification, PRINT6ADDR(&obs->addr);
transaction->packet + COAP_MAX_HEADER_SIZE, PRINTF(":%u\n", obs->port);
REST_MAX_CHUNK_SIZE, NULL);
/* update last MID for RST matching */
if(notification->code < BAD_REQUEST_4_00) obs->last_mid = transaction->mid;
coap_set_header_observe(notification, (obs->obs_counter)++);
coap_set_token(notification, obs->token, obs->token_len); /* prepare response */
notification->mid = transaction->mid;
/* TODO use resource-specific COAP_OBSERVE_REFRESH_INTERVAL for CON to check client interest */
resource->get_handler(NULL, notification,
transaction->packet_len = transaction->packet + COAP_MAX_HEADER_SIZE,
coap_serialize_message(notification, transaction->packet); REST_MAX_CHUNK_SIZE, NULL);
coap_send_transaction(transaction); 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 */
void
coap_observe_handler(resource_t * resource, void *request, void *response) transaction->packet_len =
{ coap_serialize_message(notification, transaction->packet);
coap_packet_t *const coap_req = (coap_packet_t *) request;
coap_packet_t *const coap_res = (coap_packet_t *) response; coap_send_transaction(transaction);
}
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)) { /*---------------------------------------------------------------------------*/
void
if(coap_add_observer(&UIP_IP_BUF->srcipaddr, UIP_UDP_BUF->srcport, coap_observe_handler(resource_t *resource, void *request, void *response)
coap_req->token, coap_req->token_len, {
resource->url)) { coap_packet_t *const coap_req = (coap_packet_t *)request;
coap_set_header_observe(coap_res, 0); coap_packet_t *const coap_res = (coap_packet_t *)response;
/*
* for demonstration purposes only. A subscription should return the same representation as a normal GET static char content[16];
* FIXME comment the following command for any real application
*/ if(coap_req->code == COAP_GET && coap_res->code < 128) { /* GET request and response without error code */
coap_set_payload(coap_res, if(IS_OPTION(coap_req, COAP_OPTION_OBSERVE)) {
content,
snprintf(content, sizeof(content), "Added %u/%u", if(coap_add_observer(&UIP_IP_BUF->srcipaddr, UIP_UDP_BUF->srcport,
list_length(observers_list), coap_req->token, coap_req->token_len,
COAP_MAX_OBSERVERS)); resource->url)) {
} else { coap_set_header_observe(coap_res, 0);
coap_res->code = SERVICE_UNAVAILABLE_5_03; /*
coap_set_payload(coap_res, "TooManyObservers", 16); * for demonstration purposes only. A subscription should return the same representation as a normal GET
} /* if(added observer) */ * FIXME comment the following command for any real application
} else { /* if (observe) */ */
coap_set_payload(coap_res,
/* remove client if it is currently observe */ content,
coap_remove_observer_by_token(&UIP_IP_BUF->srcipaddr, snprintf(content, sizeof(content), "Added %u/%u",
UIP_UDP_BUF->srcport, coap_req->token, list_length(observers_list),
coap_req->token_len); COAP_MAX_OBSERVERS));
} /* if(observe) */ } 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 * Copyright (c) 2013, Institute for Pervasive Computing, ETH Zurich
* All rights reserved. * All rights reserved.
* *
* Redistribution and use in source and binary forms, with or without * Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions * modification, are permitted provided that the following conditions
* are met: * are met:
* 1. Redistributions of source code must retain the above copyright * 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer. * notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright * 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the * notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution. * documentation and/or other materials provided with the distribution.
* 3. Neither the name of the Institute nor the names of its contributors * 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 * may be used to endorse or promote products derived from this software
* without specific prior written permission. * without specific prior written permission.
* *
* THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * 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 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE. * SUCH DAMAGE.
* *
* This file is part of the Contiki operating system. * This file is part of the Contiki operating system.
*/ */
/** /**
* \file * \file
* CoAP module for observing resources (draft-ietf-core-observe-11). * CoAP module for observing resources (draft-ietf-core-observe-11).
* \author * \author
* Matthias Kovatsch <kovatsch@inf.ethz.ch> * Matthias Kovatsch <kovatsch@inf.ethz.ch>
*/ */
#ifndef COAP_OBSERVE_H_ #ifndef COAP_OBSERVE_H_
#define COAP_OBSERVE_H_ #define COAP_OBSERVE_H_
#include "er-coap.h" #include "er-coap.h"
#include "er-coap-transactions.h" #include "er-coap-transactions.h"
#include "stimer.h" #include "stimer.h"
typedef struct coap_observable { typedef struct coap_observable {
uint32_t observe_clock; uint32_t observe_clock;
struct stimer orphan_timer; struct stimer orphan_timer;
list_t observers; list_t observers;
coap_packet_t notification; coap_packet_t notification;
uint8_t buffer[COAP_MAX_PACKET_SIZE + 1]; uint8_t buffer[COAP_MAX_PACKET_SIZE + 1];
} coap_observable_t; } coap_observable_t;
typedef struct coap_observer { typedef struct coap_observer {
struct coap_observer *next; /* for LIST */ struct coap_observer *next; /* for LIST */
const char *url; const char *url;
uip_ipaddr_t addr; uip_ipaddr_t addr;
uint16_t port; uint16_t port;
uint8_t token_len; uint8_t token_len;
uint8_t token[COAP_TOKEN_LEN]; uint8_t token[COAP_TOKEN_LEN];
uint16_t last_mid; uint16_t last_mid;
int32_t obs_counter; int32_t obs_counter;
struct etimer retrans_timer; struct etimer retrans_timer;
uint8_t retrans_counter; uint8_t retrans_counter;
} coap_observer_t; } coap_observer_t;
list_t coap_get_observers(void); list_t coap_get_observers(void);
coap_observer_t *coap_add_observer(uip_ipaddr_t * addr, uint16_t port, coap_observer_t *coap_add_observer(uip_ipaddr_t *addr, uint16_t port,
const uint8_t * token, size_t token_len, const uint8_t *token, size_t token_len,
const char *url); const char *url);
void coap_remove_observer(coap_observer_t * o); 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_client(uip_ipaddr_t *addr, uint16_t port);
int coap_remove_observer_by_token(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); uint8_t *token, size_t token_len);
int coap_remove_observer_by_uri(uip_ipaddr_t * addr, uint16_t port, int coap_remove_observer_by_uri(uip_ipaddr_t *addr, uint16_t port,
const char *uri); const char *uri);
int coap_remove_observer_by_mid(uip_ipaddr_t * addr, uint16_t port, int coap_remove_observer_by_mid(uip_ipaddr_t *addr, uint16_t port,
uint16_t mid); uint16_t mid);
void coap_notify_observers(resource_t * resource); void coap_notify_observers(resource_t *resource);
void coap_observe_handler(resource_t * resource, void *request, void coap_observe_handler(resource_t *resource, void *request,
void *response); void *response);
#endif /* COAP_OBSERVE_H_ */ #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 * Copyright (c) 2013, Institute for Pervasive Computing, ETH Zurich
* All rights reserved. * All rights reserved.
* *
* Redistribution and use in source and binary forms, with or without * Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions * modification, are permitted provided that the following conditions
* are met: * are met:
* 1. Redistributions of source code must retain the above copyright * 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer. * notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright * 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the * notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution. * documentation and/or other materials provided with the distribution.
* 3. Neither the name of the Institute nor the names of its contributors * 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 * may be used to endorse or promote products derived from this software
* without specific prior written permission. * without specific prior written permission.
* *
* THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * 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 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE. * SUCH DAMAGE.
* *
* This file is part of the Contiki operating system. * This file is part of the Contiki operating system.
*/ */
/** /**
* \file * \file
* /.well-known/core resource implementation. * /.well-known/core resource implementation.
* \author * \author
* Matthias Kovatsch <kovatsch@inf.ethz.ch> * Matthias Kovatsch <kovatsch@inf.ethz.ch>
*/ */
#include <string.h> #include <string.h>
#include "er-coap-engine.h" #include "er-coap-engine.h"
#define DEBUG DEBUG_NONE #define DEBUG 0
#include "net/uip-debug.h" #if DEBUG
#include <stdio.h>
/*---------------------------------------------------------------------------*/ #define PRINTF(...) printf(__VA_ARGS__)
/*- Resource Handlers -------------------------------------------------------*/ #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])
void #else
well_known_core_get_handler(void *request, void *response, uint8_t * buffer, #define PRINTF(...)
uint16_t preferred_size, int32_t * offset) #define PRINT6ADDR(addr)
{ #define PRINTLLADDR(addr)
size_t strpos = 0; /* position in overall string (which is larger than the buffer) */ #endif
size_t bufpos = 0; /* position within buffer (bytes written) */
size_t tmplen = 0; /*---------------------------------------------------------------------------*/
resource_t *resource = NULL; /*- Resource Handlers -------------------------------------------------------*/
/*---------------------------------------------------------------------------*/
#if COAP_LINK_FORMAT_FILTERING void
/* For filtering. */ well_known_core_get_handler(void *request, void *response, uint8_t *buffer,
const char *filter = NULL; uint16_t preferred_size, int32_t *offset)
const char *attrib = NULL; {
const char *found = NULL; size_t strpos = 0; /* position in overall string (which is larger than the buffer) */
const char *end = NULL; size_t bufpos = 0; /* position within buffer (bytes written) */
char *value = NULL; size_t tmplen = 0;
char lastchar = '\0'; resource_t *resource = NULL;
int len = coap_get_header_uri_query(request, &filter);
#if COAP_LINK_FORMAT_FILTERING
if(len) { /* For filtering. */
value = strchr(filter, '='); const char *filter = NULL;
value[0] = '\0'; const char *attrib = NULL;
++value; const char *found = NULL;
len -= strlen(filter) + 1; const char *end = NULL;
char *value = NULL;
PRINTF("Filter %s = %.*s\n", filter, len, value); char lastchar = '\0';
int len = coap_get_header_uri_query(request, &filter);
if(strcmp(filter, "href") == 0 && value[0] == '/') {
++value; if(len) {
--len; value = strchr(filter, '=');
} value[0] = '\0';
++value;
lastchar = value[len - 1]; len -= strlen(filter) + 1;
value[len - 1] = '\0';
} PRINTF("Filter %s = %.*s\n", filter, len, value);
#endif
if(strcmp(filter, "href") == 0 && value[0] == '/') {
for(resource = (resource_t *) list_head(rest_get_resources()); resource; ++value;
resource = resource->next) { --len;
#if COAP_LINK_FORMAT_FILTERING }
/* Filtering */
if(len) { lastchar = value[len - 1];
if(strcmp(filter, "href") == 0) { value[len - 1] = '\0';
attrib = strstr(resource->url, value); }
if(attrib == NULL || (value[-1] == '/' && attrib != resource->url)) #endif
continue;
end = attrib + strlen(attrib); for(resource = (resource_t *)list_head(rest_get_resources()); resource;
} else { resource = resource->next) {
attrib = strstr(resource->attributes, filter); #if COAP_LINK_FORMAT_FILTERING
if(attrib == NULL /* Filtering */
|| (attrib[strlen(filter)] != '=' if(len) {
&& attrib[strlen(filter)] != '"')) if(strcmp(filter, "href") == 0) {
continue; attrib = strstr(resource->url, value);
attrib += strlen(filter) + 2; if(attrib == NULL || (value[-1] == '/' && attrib != resource->url)) {
end = strchr(attrib, '"'); continue;
} }
end = attrib + strlen(attrib);
PRINTF("Filter: res has attrib %s (%s)\n", attrib, value); } else {
found = attrib; attrib = strstr(resource->attributes, filter);
while((found = strstr(found, value)) != NULL) { if(attrib == NULL
if(found > end) { || (attrib[strlen(filter)] != '='
found = NULL; && attrib[strlen(filter)] != '"')) {
break; continue;
} }
if(lastchar == found[len - 1] || lastchar == '*') { attrib += strlen(filter) + 2;
break; end = strchr(attrib, '"');
} }
++found;
} PRINTF("Filter: res has attrib %s (%s)\n", attrib, value);
if(found == NULL) { found = attrib;
continue; while((found = strstr(found, value)) != NULL) {
} if(found > end) {
PRINTF("Filter: res has prefix %s\n", found); found = NULL;
if(lastchar != '*' break;
&& (found[len] != '"' && found[len] != ' ' && found[len] != '\0')) }
continue; if(lastchar == found[len - 1] || lastchar == '*') {
PRINTF("Filter: res has match\n"); break;
} }
#endif ++found;
}
PRINTF("res: /%s (%p)\npos: s%d, o%ld, b%d\n", resource->url, resource, if(found == NULL) {
strpos, *offset, bufpos); continue;
}
if(strpos > 0) { PRINTF("Filter: res has prefix %s\n", found);
if(strpos >= *offset && bufpos < preferred_size) { if(lastchar != '*'
buffer[bufpos++] = ','; && (found[len] != '"' && found[len] != ' ' && found[len] != '\0')) {
} continue;
++strpos; }
} PRINTF("Filter: res has match\n");
}
if(strpos >= *offset && bufpos < preferred_size) { #endif
buffer[bufpos++] = '<';
} PRINTF("res: /%s (%p)\npos: s%d, o%ld, b%d\n", resource->url, resource,
++strpos; strpos, *offset, bufpos);
if(strpos >= *offset && bufpos < preferred_size) { if(strpos > 0) {
buffer[bufpos++] = '/'; if(strpos >= *offset && bufpos < preferred_size) {
} buffer[bufpos++] = ',';
++strpos; }
++strpos;
tmplen = strlen(resource->url); }
if(strpos + tmplen > *offset) {
bufpos += snprintf((char *)buffer + bufpos, if(strpos >= *offset && bufpos < preferred_size) {
preferred_size - bufpos + 1, buffer[bufpos++] = '<';
"%s", }
resource->url + ++strpos;
((*offset - (int32_t) strpos >
0) ? (*offset - (int32_t) strpos) : 0)); if(strpos >= *offset && bufpos < preferred_size) {
/* native requires these casts */ buffer[bufpos++] = '/';
if(bufpos >= preferred_size) { }
PRINTF("res: BREAK at %s (%p)\n", resource->url, resource); ++strpos;
break;
} tmplen = strlen(resource->url);
} if(strpos + tmplen > *offset) {
strpos += tmplen; bufpos += snprintf((char *)buffer + bufpos,
preferred_size - bufpos + 1,
if(strpos >= *offset && bufpos < preferred_size) { "%s",
buffer[bufpos++] = '>'; resource->url +
} ((*offset - (int32_t)strpos >
++strpos; 0) ? (*offset - (int32_t)strpos) : 0));
/* native requires these casts */
if(resource->attributes[0]) { if(bufpos >= preferred_size) {
if(strpos >= *offset && bufpos < preferred_size) { PRINTF("res: BREAK at %s (%p)\n", resource->url, resource);
buffer[bufpos++] = ';'; break;
} }
++strpos; }
strpos += tmplen;
tmplen = strlen(resource->attributes);
if(strpos + tmplen > *offset) { if(strpos >= *offset && bufpos < preferred_size) {
bufpos += snprintf((char *)buffer + bufpos, buffer[bufpos++] = '>';
preferred_size - bufpos + 1, }
resource->attributes ++strpos;
+ (*offset - (int32_t) strpos > 0 ?
*offset - (int32_t) strpos : 0)); if(resource->attributes[0]) {
if(bufpos > preferred_size) { if(strpos >= *offset && bufpos < preferred_size) {
PRINTF("res: BREAK at %s (%p)\n", resource->url, resource); buffer[bufpos++] = ';';
break; }
} ++strpos;
}
strpos += tmplen; tmplen = strlen(resource->attributes);
} if(strpos + tmplen > *offset) {
bufpos += snprintf((char *)buffer + bufpos,
/* buffer full, but resource not completed yet; or: do not break if resource exactly fills buffer. */ preferred_size - bufpos + 1,
if(bufpos > preferred_size && strpos - bufpos > *offset) { resource->attributes
PRINTF("res: BREAK at %s (%p)\n", resource->url, resource); + (*offset - (int32_t)strpos > 0 ?
break; *offset - (int32_t)strpos : 0));
} if(bufpos > preferred_size) {
} PRINTF("res: BREAK at %s (%p)\n", resource->url, resource);
break;
if(bufpos > 0) { }
PRINTF("BUF %d: %.*s\n", bufpos, bufpos, (char *)buffer); }
strpos += tmplen;
coap_set_payload(response, buffer, bufpos); }
coap_set_header_content_format(response, APPLICATION_LINK_FORMAT);
} else if(strpos > 0) { /* buffer full, but resource not completed yet; or: do not break if resource exactly fills buffer. */
PRINTF("well_known_core_handler(): bufpos<=0\n"); if(bufpos > preferred_size && strpos - bufpos > *offset) {
PRINTF("res: BREAK at %s (%p)\n", resource->url, resource);
coap_set_status_code(response, BAD_OPTION_4_02); break;
coap_set_payload(response, "BlockOutOfScope", 15); }
} }
if(resource == NULL) { if(bufpos > 0) {
PRINTF("res: DONE\n"); PRINTF("BUF %d: %.*s\n", bufpos, bufpos, (char *)buffer);
*offset = -1;
} else { coap_set_payload(response, buffer, bufpos);
PRINTF("res: MORE at %s (%p)\n", resource->url, resource); coap_set_header_content_format(response, APPLICATION_LINK_FORMAT);
*offset += preferred_size; } else if(strpos > 0) {
} PRINTF("well_known_core_handler(): bufpos<=0\n");
}
/*---------------------------------------------------------------------------*/ coap_set_status_code(response, BAD_OPTION_4_02);
RESOURCE(res_well_known_core, "ct=40", well_known_core_get_handler, NULL, coap_set_payload(response, "BlockOutOfScope", 15);
NULL, NULL); }
/*---------------------------------------------------------------------------*/
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 * Copyright (c) 2013, Institute for Pervasive Computing, ETH Zurich
* All rights reserved. * All rights reserved.
* *
* Redistribution and use in source and binary forms, with or without * Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions * modification, are permitted provided that the following conditions
* are met: * are met:
* 1. Redistributions of source code must retain the above copyright * 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer. * notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright * 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the * notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution. * documentation and/or other materials provided with the distribution.
* 3. Neither the name of the Institute nor the names of its contributors * 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 * may be used to endorse or promote products derived from this software
* without specific prior written permission. * without specific prior written permission.
* *
* THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * 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 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE. * SUCH DAMAGE.
* *
* This file is part of the Contiki operating system. * This file is part of the Contiki operating system.
*/ */
/** /**
* \file * \file
* CoAP module for separate responses. * CoAP module for separate responses.
* \author * \author
* Matthias Kovatsch <kovatsch@inf.ethz.ch> * Matthias Kovatsch <kovatsch@inf.ethz.ch>
*/ */
#include <stdio.h> #include <stdio.h>
#include <string.h> #include <string.h>
#include "er-coap-separate.h" #include "er-coap-separate.h"
#include "er-coap-transactions.h" #include "er-coap-transactions.h"
#define DEBUG DEBUG_NONE #define DEBUG 0
#include "net/uip-debug.h" #if DEBUG
#include <stdio.h>
/*---------------------------------------------------------------------------*/ #define PRINTF(...) printf(__VA_ARGS__)
/*- Separate Response API ---------------------------------------------------*/ #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
* \brief Reject a request that would require a separate response with an error message #define PRINTF(...)
* #define PRINT6ADDR(addr)
* When the server does not have enough resources left to store the information #define PRINTLLADDR(addr)
* for a separate response or otherwise cannot execute the resource handler, #endif
* this function will respond with 5.03 Service Unavailable. The client can
* then retry later. /*---------------------------------------------------------------------------*/
*/ /*- Separate Response API ---------------------------------------------------*/
void /*---------------------------------------------------------------------------*/
coap_separate_reject() /**
{ * \brief Reject a request that would require a separate response with an error message
// TODO: Accept string pointer for custom error message *
erbium_status_code = SERVICE_UNAVAILABLE_5_03; * When the server does not have enough resources left to store the information
coap_error_message = "AlreadyInUse"; * 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.
/** */
* \brief Initiate a separate response with an empty ACK void
* \param request The request to accept coap_separate_reject()
* \param separate_store A pointer to the data structure that will store the {
* relevant information for the response /* TODO: Accept string pointer for custom error message */
* erbium_status_code = SERVICE_UNAVAILABLE_5_03;
* When the server does not have enough resources left to store the information coap_error_message = "AlreadyInUse";
* 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. /**
*/ * \brief Initiate a separate response with an empty ACK
void * \param request The request to accept
coap_separate_accept(void *request, coap_separate_t * separate_store) * \param separate_store A pointer to the data structure that will store the
{ * relevant information for the response
coap_packet_t *const coap_req = (coap_packet_t *) request; *
coap_transaction_t *const t = coap_get_transaction_by_mid(coap_req->mid); * When the server does not have enough resources left to store the information
* for a separate response or otherwise cannot execute the resource handler,
PRINTF("Separate ACCEPT: /%.*s MID %u\n", coap_req->uri_path_len, * this function will respond with 5.03 Service Unavailable. The client can
coap_req->uri_path, coap_req->mid); * then retry later.
if(t) { */
/* send separate ACK for CON */ void
if(coap_req->type == COAP_TYPE_CON) { coap_separate_accept(void *request, coap_separate_t *separate_store)
coap_packet_t ack[1]; {
coap_packet_t *const coap_req = (coap_packet_t *)request;
/* ACK with empty code (0) */ coap_transaction_t *const t = coap_get_transaction_by_mid(coap_req->mid);
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 */ PRINTF("Separate ACCEPT: /%.*s MID %u\n", coap_req->uri_path_len,
coap_send_message(&UIP_IP_BUF->srcipaddr, UIP_UDP_BUF->srcport, coap_req->uri_path, coap_req->mid);
(uip_appdata), coap_serialize_message(ack, if(t) {
uip_appdata)); /* send separate ACK for CON */
} if(coap_req->type == COAP_TYPE_CON) {
coap_packet_t ack[1];
/* store remote address */
uip_ipaddr_copy(&separate_store->addr, &t->addr); /* ACK with empty code (0) */
separate_store->port = t->port; 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 */
/* store correct response type */ coap_send_message(&UIP_IP_BUF->srcipaddr, UIP_UDP_BUF->srcport,
separate_store->type = (uip_appdata), coap_serialize_message(ack,
coap_req->type == COAP_TYPE_CON ? COAP_TYPE_CON : COAP_TYPE_NON; uip_appdata));
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); /* store remote address */
separate_store->token_len = coap_req->token_len; uip_ipaddr_copy(&separate_store->addr, &t->addr);
separate_store->port = t->port;
separate_store->block2_num = coap_req->block2_num;
separate_store->block2_size = coap_req->block2_size; /* store correct response type */
separate_store->type =
/* signal the engine to skip automatic response and clear transaction by engine */ coap_req->type == COAP_TYPE_CON ? COAP_TYPE_CON : COAP_TYPE_NON;
erbium_status_code = MANUAL_RESPONSE; separate_store->mid = coap_get_mid(); /* if it was a NON, we burned one MID in the engine... */
} else { memcpy(separate_store->token, coap_req->token, coap_req->token_len);
PRINTF("ERROR: Response transaction for separate request not found!\n"); separate_store->token_len = coap_req->token_len;
erbium_status_code = INTERNAL_SERVER_ERROR_5_00;
} separate_store->block2_num = coap_req->block2_num;
} separate_store->block2_size = coap_req->block2_size;
/*----------------------------------------------------------------------------*/
void /* signal the engine to skip automatic response and clear transaction by engine */
coap_separate_resume(void *response, coap_separate_t * separate_store, erbium_status_code = MANUAL_RESPONSE;
uint8_t code) } else {
{ PRINTF("ERROR: Response transaction for separate request not found!\n");
coap_init_message(response, separate_store->type, code, erbium_status_code = INTERNAL_SERVER_ERROR_5_00;
separate_store->mid); }
if(separate_store->token_len) { }
coap_set_token(response, separate_store->token, /*----------------------------------------------------------------------------*/
separate_store->token_len); 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 * Copyright (c) 2013, Institute for Pervasive Computing, ETH Zurich
* All rights reserved. * All rights reserved.
* *
* Redistribution and use in source and binary forms, with or without * Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions * modification, are permitted provided that the following conditions
* are met: * are met:
* 1. Redistributions of source code must retain the above copyright * 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer. * notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright * 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the * notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution. * documentation and/or other materials provided with the distribution.
* 3. Neither the name of the Institute nor the names of its contributors * 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 * may be used to endorse or promote products derived from this software
* without specific prior written permission. * without specific prior written permission.
* *
* THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * 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 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE. * SUCH DAMAGE.
* *
* This file is part of the Contiki operating system. * This file is part of the Contiki operating system.
*/ */
/** /**
* \file * \file
* CoAP module for separate responses. * CoAP module for separate responses.
* \author * \author
* Matthias Kovatsch <kovatsch@inf.ethz.ch> * Matthias Kovatsch <kovatsch@inf.ethz.ch>
*/ */
#ifndef COAP_SEPARATE_H_ #ifndef COAP_SEPARATE_H_
#define COAP_SEPARATE_H_ #define COAP_SEPARATE_H_
#include "er-coap.h" #include "er-coap.h"
typedef struct coap_separate { typedef struct coap_separate {
uip_ipaddr_t addr; uip_ipaddr_t addr;
uint16_t port; uint16_t port;
coap_message_type_t type; coap_message_type_t type;
uint16_t mid; uint16_t mid;
uint8_t token_len; uint8_t token_len;
uint8_t token[COAP_TOKEN_LEN]; uint8_t token[COAP_TOKEN_LEN];
/* separate + blockwise is untested! */ /* separate + blockwise is untested! */
uint32_t block2_num; uint32_t block2_num;
uint16_t block2_size; uint16_t block2_size;
} coap_separate_t;
} coap_separate_t;
int coap_separate_handler(resource_t *resource, void *request,
int coap_separate_handler(resource_t * resource, void *request, void *response);
void *response); void coap_separate_reject();
void coap_separate_reject(); void coap_separate_accept(void *request, coap_separate_t *separate_store);
void coap_separate_accept(void *request, coap_separate_t * separate_store); void coap_separate_resume(void *response, coap_separate_t *separate_store,
void coap_separate_resume(void *response, coap_separate_t * separate_store, uint8_t code);
uint8_t code);
#endif /* COAP_SEPARATE_H_ */
#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 * Copyright (c) 2013, Institute for Pervasive Computing, ETH Zurich
* All rights reserved. * All rights reserved.
* *
* Redistribution and use in source and binary forms, with or without * Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions * modification, are permitted provided that the following conditions
* are met: * are met:
* 1. Redistributions of source code must retain the above copyright * 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer. * notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright * 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the * notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution. * documentation and/or other materials provided with the distribution.
* 3. Neither the name of the Institute nor the names of its contributors * 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 * may be used to endorse or promote products derived from this software
* without specific prior written permission. * without specific prior written permission.
* *
* THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * 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 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE. * SUCH DAMAGE.
* *
* This file is part of the Contiki operating system. * This file is part of the Contiki operating system.
*/ */
/** /**
* \file * \file
* CoAP module for reliable transport * CoAP module for reliable transport
* \author * \author
* Matthias Kovatsch <kovatsch@inf.ethz.ch> * Matthias Kovatsch <kovatsch@inf.ethz.ch>
*/ */
#include "contiki.h" #include "contiki.h"
#include "contiki-net.h" #include "contiki-net.h"
#include "er-coap-transactions.h" #include "er-coap-transactions.h"
#include "er-coap-observe.h" #include "er-coap-observe.h"
#define DEBUG DEBUG_NONE #define DEBUG 0
#include "net/uip-debug.h" #if DEBUG
#include <stdio.h>
/*---------------------------------------------------------------------------*/ #define PRINTF(...) printf(__VA_ARGS__)
MEMB(transactions_memb, coap_transaction_t, COAP_MAX_OPEN_TRANSACTIONS); #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])
LIST(transactions_list); #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
static struct process *transaction_handler_process = NULL; #define PRINTF(...)
#define PRINT6ADDR(addr)
/*---------------------------------------------------------------------------*/ #define PRINTLLADDR(addr)
/*- Internal API ------------------------------------------------------------*/ #endif
/*---------------------------------------------------------------------------*/
void /*---------------------------------------------------------------------------*/
coap_register_as_transaction_handler() MEMB(transactions_memb, coap_transaction_t, COAP_MAX_OPEN_TRANSACTIONS);
{ LIST(transactions_list);
transaction_handler_process = PROCESS_CURRENT();
} static struct process *transaction_handler_process = NULL;
coap_transaction_t * /*---------------------------------------------------------------------------*/
coap_new_transaction(uint16_t mid, uip_ipaddr_t * addr, uint16_t port) /*- Internal API ------------------------------------------------------------*/
{ /*---------------------------------------------------------------------------*/
coap_transaction_t *t = memb_alloc(&transactions_memb); void
coap_register_as_transaction_handler()
if(t) { {
t->mid = mid; transaction_handler_process = PROCESS_CURRENT();
t->retrans_counter = 0; }
coap_transaction_t *
/* save client address */ coap_new_transaction(uint16_t mid, uip_ipaddr_t *addr, uint16_t port)
uip_ipaddr_copy(&t->addr, addr); {
t->port = port; coap_transaction_t *t = memb_alloc(&transactions_memb);
list_add(transactions_list, t); /* list itself makes sure same element is not added twice */ if(t) {
} t->mid = mid;
t->retrans_counter = 0;
return t;
} /* save client address */
/*---------------------------------------------------------------------------*/ uip_ipaddr_copy(&t->addr, addr);
void t->port = port;
coap_send_transaction(coap_transaction_t * t)
{ list_add(transactions_list, t); /* list itself makes sure same element is not added twice */
PRINTF("Sending transaction %u\n", t->mid); }
coap_send_message(&t->addr, t->port, t->packet, t->packet_len); return t;
}
if(COAP_TYPE_CON == /*---------------------------------------------------------------------------*/
((COAP_HEADER_TYPE_MASK & t->packet[0]) >> COAP_HEADER_TYPE_POSITION)) { void
if(t->retrans_counter < COAP_MAX_RETRANSMIT) { coap_send_transaction(coap_transaction_t *t)
/* not timed out yet */ {
PRINTF("Keeping transaction %u\n", t->mid); PRINTF("Sending transaction %u\n", t->mid);
if(t->retrans_counter == 0) { coap_send_message(&t->addr, t->port, t->packet, t->packet_len);
t->retrans_timer.timer.interval =
COAP_RESPONSE_TIMEOUT_TICKS + (random_rand() if(COAP_TYPE_CON ==
% ((COAP_HEADER_TYPE_MASK & t->packet[0]) >> COAP_HEADER_TYPE_POSITION)) {
(clock_time_t) if(t->retrans_counter < COAP_MAX_RETRANSMIT) {
COAP_RESPONSE_TIMEOUT_BACKOFF_MASK); /* not timed out yet */
PRINTF("Initial interval %f\n", PRINTF("Keeping transaction %u\n", t->mid);
(float)t->retrans_timer.timer.interval / CLOCK_SECOND);
} else { if(t->retrans_counter == 0) {
t->retrans_timer.timer.interval <<= 1; /* double */ t->retrans_timer.timer.interval =
PRINTF("Doubled (%u) interval %f\n", t->retrans_counter, COAP_RESPONSE_TIMEOUT_TICKS + (random_rand()
(float)t->retrans_timer.timer.interval / CLOCK_SECOND); %
} (clock_time_t)
COAP_RESPONSE_TIMEOUT_BACKOFF_MASK);
/*FIXME PRINTF("Initial interval %f\n",
* Hack: Setting timer for responsible process. (float)t->retrans_timer.timer.interval / CLOCK_SECOND);
* Maybe there is a better way, but avoid posting everything to the process. } else {
*/ t->retrans_timer.timer.interval <<= 1; /* double */
struct process *process_actual = PROCESS_CURRENT(); PRINTF("Doubled (%u) interval %f\n", t->retrans_counter,
(float)t->retrans_timer.timer.interval / CLOCK_SECOND);
process_current = transaction_handler_process; }
etimer_restart(&t->retrans_timer); /* interval updated above */
process_current = process_actual; /*FIXME
* Hack: Setting timer for responsible process.
t = NULL; * Maybe there is a better way, but avoid posting everything to the process.
} else { */
/* timed out */ struct process *process_actual = PROCESS_CURRENT();
PRINTF("Timeout\n");
restful_response_handler callback = t->callback; process_current = transaction_handler_process;
void *callback_data = t->callback_data; etimer_restart(&t->retrans_timer); /* interval updated above */
process_current = process_actual;
/* handle observers */
coap_remove_observer_by_client(&t->addr, t->port); t = NULL;
} else {
coap_clear_transaction(t); /* timed out */
PRINTF("Timeout\n");
if(callback) { restful_response_handler callback = t->callback;
callback(callback_data, NULL); void *callback_data = t->callback_data;
}
} /* handle observers */
} else { coap_remove_observer_by_client(&t->addr, t->port);
coap_clear_transaction(t);
} coap_clear_transaction(t);
}
/*---------------------------------------------------------------------------*/ if(callback) {
void callback(callback_data, NULL);
coap_clear_transaction(coap_transaction_t * t) }
{ }
if(t) { } else {
PRINTF("Freeing transaction %u: %p\n", t->mid, t); coap_clear_transaction(t);
}
etimer_stop(&t->retrans_timer); }
list_remove(transactions_list, t); /*---------------------------------------------------------------------------*/
memb_free(&transactions_memb, t); void
} coap_clear_transaction(coap_transaction_t *t)
} {
if(t) {
coap_transaction_t * PRINTF("Freeing transaction %u: %p\n", t->mid, t);
coap_get_transaction_by_mid(uint16_t mid)
{ etimer_stop(&t->retrans_timer);
coap_transaction_t *t = NULL; list_remove(transactions_list, t);
memb_free(&transactions_memb, t);
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); coap_transaction_t *
return t; coap_get_transaction_by_mid(uint16_t mid)
} {
} coap_transaction_t *t = NULL;
return NULL;
} for(t = (coap_transaction_t *)list_head(transactions_list); t; t = t->next) {
/*---------------------------------------------------------------------------*/ if(t->mid == mid) {
void PRINTF("Found transaction for MID %u: %p\n", t->mid, t);
coap_check_transactions() return t;
{ }
coap_transaction_t *t = NULL; }
return NULL;
for(t = (coap_transaction_t *) list_head(transactions_list); t; t = t->next) { }
if(etimer_expired(&t->retrans_timer)) { /*---------------------------------------------------------------------------*/
++(t->retrans_counter); void
PRINTF("Retransmitting %u (%u)\n", t->mid, t->retrans_counter); coap_check_transactions()
coap_send_transaction(t); {
} 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 * Copyright (c) 2013, Institute for Pervasive Computing, ETH Zurich
* All rights reserved. * All rights reserved.
* *
* Redistribution and use in source and binary forms, with or without * Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions * modification, are permitted provided that the following conditions
* are met: * are met:
* 1. Redistributions of source code must retain the above copyright * 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer. * notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright * 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the * notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution. * documentation and/or other materials provided with the distribution.
* 3. Neither the name of the Institute nor the names of its contributors * 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 * may be used to endorse or promote products derived from this software
* without specific prior written permission. * without specific prior written permission.
* *
* THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * 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 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE. * SUCH DAMAGE.
* *
* This file is part of the Contiki operating system. * This file is part of the Contiki operating system.
*/ */
/** /**
* \file * \file
* CoAP module for reliable transport * CoAP module for reliable transport
* \author * \author
* Matthias Kovatsch <kovatsch@inf.ethz.ch> * Matthias Kovatsch <kovatsch@inf.ethz.ch>
*/ */
#ifndef COAP_TRANSACTIONS_H_ #ifndef COAP_TRANSACTIONS_H_
#define COAP_TRANSACTIONS_H_ #define COAP_TRANSACTIONS_H_
#include "er-coap.h" #include "er-coap.h"
/* /*
* Modulo mask (thus +1) for a random number to get the tick number for the random * 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. * 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_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 #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 */ /* container for transactions with message buffer and retransmission info */
typedef struct coap_transaction { typedef struct coap_transaction {
struct coap_transaction *next; /* for LIST */ struct coap_transaction *next; /* for LIST */
uint16_t mid; uint16_t mid;
struct etimer retrans_timer; struct etimer retrans_timer;
uint8_t retrans_counter; uint8_t retrans_counter;
uip_ipaddr_t addr; uip_ipaddr_t addr;
uint16_t port; uint16_t port;
restful_response_handler callback; restful_response_handler callback;
void *callback_data; void *callback_data;
uint16_t packet_len; uint16_t packet_len;
uint8_t packet[COAP_MAX_PACKET_SIZE + 1]; /* +1 for the terminating '\0' which will not be sent 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 */ * Use snprintf(buf, len+1, "", ...) to completely fill payload */
} coap_transaction_t; } coap_transaction_t;
void coap_register_as_transaction_handler(); void coap_register_as_transaction_handler();
coap_transaction_t *coap_new_transaction(uint16_t mid, uip_ipaddr_t * addr, coap_transaction_t *coap_new_transaction(uint16_t mid, uip_ipaddr_t *addr,
uint16_t port); uint16_t port);
void coap_send_transaction(coap_transaction_t * t); void coap_send_transaction(coap_transaction_t *t);
void coap_clear_transaction(coap_transaction_t * t); void coap_clear_transaction(coap_transaction_t *t);
coap_transaction_t *coap_get_transaction_by_mid(uint16_t mid); coap_transaction_t *coap_get_transaction_by_mid(uint16_t mid);
void coap_check_transactions(); void coap_check_transactions();
#endif /* COAP_TRANSACTIONS_H_ */ #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 * Copyright (c) 2013, Institute for Pervasive Computing, ETH Zurich
* All rights reserved. * All rights reserved.
* *
* Redistribution and use in source and binary forms, with or without * Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions * modification, are permitted provided that the following conditions
* are met: * are met:
* 1. Redistributions of source code must retain the above copyright * 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer. * notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright * 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the * notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution. * documentation and/or other materials provided with the distribution.
* 3. Neither the name of the Institute nor the names of its contributors * 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 * may be used to endorse or promote products derived from this software
* without specific prior written permission. * without specific prior written permission.
* *
* THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * 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 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE. * SUCH DAMAGE.
* *
* This file is part of the Contiki operating system. * This file is part of the Contiki operating system.
*/ */
/** /**
* \file * \file
* An implementation of the Constrained Application Protocol (RFC). * An implementation of the Constrained Application Protocol (RFC).
* \author * \author
* Matthias Kovatsch <kovatsch@inf.ethz.ch> * Matthias Kovatsch <kovatsch@inf.ethz.ch>
*/ */
#ifndef ER_COAP_H_ #ifndef ER_COAP_H_
#define ER_COAP_H_ #define ER_COAP_H_
#include <stddef.h> /* for size_t */ #include <stddef.h> /* for size_t */
#include "net/uip.h" #include "contiki-net.h"
#include "er-coap-constants.h" #include "er-coap-constants.h"
#include "er-coap-conf.h" #include "er-coap-conf.h"
/* sanity check for configured values */ /* sanity check for configured values */
#define COAP_MAX_PACKET_SIZE (COAP_MAX_HEADER_SIZE + REST_MAX_CHUNK_SIZE) #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) #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" #error "UIP_CONF_BUFFER_SIZE too small for REST_MAX_CHUNK_SIZE"
#endif #endif
/* use Erbium CoAP for the REST Engine. Must come before include of rest-engine.h. */ /* use Erbium CoAP for the REST Engine. Must come before include of rest-engine.h. */
#define REST coap_rest_implementation #define REST coap_rest_implementation
#include "rest-engine.h" #include "rest-engine.h"
/* direct access into the buffer */ /* direct access into the buffer */
#define UIP_IP_BUF ((struct uip_ip_hdr *)&uip_buf[UIP_LLH_LEN]) #define UIP_IP_BUF ((struct uip_ip_hdr *)&uip_buf[UIP_LLH_LEN])
#if UIP_CONF_IPV6 #if UIP_CONF_IPV6
#define UIP_UDP_BUF ((struct uip_udp_hdr *)&uip_buf[uip_l2_l3_hdr_len]) #define UIP_UDP_BUF ((struct uip_udp_hdr *)&uip_buf[uip_l2_l3_hdr_len])
#else #else
#define UIP_UDP_BUF ((struct uip_udp_hdr *)&uip_buf[UIP_LLH_LEN + UIP_IPH_LEN]) #define UIP_UDP_BUF ((struct uip_udp_hdr *)&uip_buf[UIP_LLH_LEN + UIP_IPH_LEN])
#endif #endif
/* bitmap for set options */ /* bitmap for set options */
enum { OPTION_MAP_SIZE = sizeof(uint8_t) * 8 }; 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 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))) #define IS_OPTION(packet, opt) ((packet)->options[opt / OPTION_MAP_SIZE] & (1 << (opt % OPTION_MAP_SIZE)))
#ifndef MIN #ifndef MIN
#define MIN(a, b) ((a) < (b)? (a) : (b)) #define MIN(a, b) ((a) < (b) ? (a) : (b))
#endif /* MIN */ #endif /* MIN */
/* parsed message struct */ /* parsed message struct */
typedef struct { typedef struct {
uint8_t *buffer; /* pointer to CoAP header / incoming packet buffer / memory to serialize packet */ uint8_t *buffer; /* pointer to CoAP header / incoming packet buffer / memory to serialize packet */
uint8_t version; uint8_t version;
coap_message_type_t type; coap_message_type_t type;
uint8_t code; uint8_t code;
uint16_t mid; uint16_t mid;
uint8_t token_len; uint8_t token_len;
uint8_t token[COAP_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 */ 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 */ coap_content_format_t content_format; /* parse options once and store; allows setting options in random order */
uint32_t max_age; uint32_t max_age;
uint8_t etag_len; uint8_t etag_len;
uint8_t etag[COAP_ETAG_LEN]; uint8_t etag[COAP_ETAG_LEN];
size_t proxy_uri_len; size_t proxy_uri_len;
const char *proxy_uri; const char *proxy_uri;
size_t proxy_scheme_len; size_t proxy_scheme_len;
const char *proxy_scheme; const char *proxy_scheme;
size_t uri_host_len; size_t uri_host_len;
const char *uri_host; const char *uri_host;
size_t location_path_len; size_t location_path_len;
const char *location_path; const char *location_path;
uint16_t uri_port; uint16_t uri_port;
size_t location_query_len; size_t location_query_len;
const char *location_query; const char *location_query;
size_t uri_path_len; size_t uri_path_len;
const char *uri_path; const char *uri_path;
int32_t observe; int32_t observe;
coap_content_format_t accept; coap_content_format_t accept;
uint8_t if_match_len; uint8_t if_match_len;
uint8_t if_match[COAP_ETAG_LEN]; uint8_t if_match[COAP_ETAG_LEN];
uint32_t block2_num; uint32_t block2_num;
uint8_t block2_more; uint8_t block2_more;
uint16_t block2_size; uint16_t block2_size;
uint32_t block2_offset; uint32_t block2_offset;
uint32_t block1_num; uint32_t block1_num;
uint8_t block1_more; uint8_t block1_more;
uint16_t block1_size; uint16_t block1_size;
uint32_t block1_offset; uint32_t block1_offset;
uint32_t size2; uint32_t size2;
uint32_t size1; uint32_t size1;
size_t uri_query_len; size_t uri_query_len;
const char *uri_query; const char *uri_query;
uint8_t if_none_match; uint8_t if_none_match;
uint16_t payload_len; uint16_t payload_len;
uint8_t *payload; uint8_t *payload;
} coap_packet_t;
} coap_packet_t;
/* option format serialization */
/* option format serialization */ #define COAP_SERIALIZE_INT_OPTION(number, field, text) \
#define COAP_SERIALIZE_INT_OPTION(number, field, text) \ if(IS_OPTION(coap_pkt, number)) { \
if (IS_OPTION(coap_pkt, number)) { \ PRINTF(text " [%u]\n", coap_pkt->field); \
PRINTF(text" [%u]\n", coap_pkt->field); \ option += coap_serialize_int_option(number, current_number, option, coap_pkt->field); \
option += coap_serialize_int_option(number, current_number, option, coap_pkt->field); \ current_number = number; \
current_number = number; \ }
} #define COAP_SERIALIZE_BYTE_OPTION(number, field, text) \
#define COAP_SERIALIZE_BYTE_OPTION(number, field, text) \ if(IS_OPTION(coap_pkt, number)) { \
if (IS_OPTION(coap_pkt, number)) { \ PRINTF(text " %u [0x%02X%02X%02X%02X%02X%02X%02X%02X]\n", coap_pkt->field##_len, \
PRINTF(text" %u [0x%02X%02X%02X%02X%02X%02X%02X%02X]\n", coap_pkt->field##_len, \ coap_pkt->field[0], \
coap_pkt->field[0], \ coap_pkt->field[1], \
coap_pkt->field[1], \ coap_pkt->field[2], \
coap_pkt->field[2], \ coap_pkt->field[3], \
coap_pkt->field[3], \ coap_pkt->field[4], \
coap_pkt->field[4], \ coap_pkt->field[5], \
coap_pkt->field[5], \ coap_pkt->field[6], \
coap_pkt->field[6], \ coap_pkt->field[7] \
coap_pkt->field[7] \ ); /* FIXME always prints 8 bytes */ \
); /* FIXME always prints 8 bytes */ \ option += coap_serialize_array_option(number, current_number, option, coap_pkt->field, coap_pkt->field##_len, '\0'); \
option += coap_serialize_array_option(number, current_number, option, coap_pkt->field, coap_pkt->field##_len, '\0'); \ current_number = number; \
current_number = number; \ }
} #define COAP_SERIALIZE_STRING_OPTION(number, field, splitter, text) \
#define COAP_SERIALIZE_STRING_OPTION(number, field, splitter, text) \ if(IS_OPTION(coap_pkt, number)) { \
if (IS_OPTION(coap_pkt, number)) { \ PRINTF(text " [%.*s]\n", coap_pkt->field##_len, coap_pkt->field); \
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); \
option += coap_serialize_array_option(number, current_number, option, (uint8_t *) coap_pkt->field, coap_pkt->field##_len, splitter); \ current_number = number; \
current_number = number; \ }
} #define COAP_SERIALIZE_BLOCK_OPTION(number, field, text) \
#define COAP_SERIALIZE_BLOCK_OPTION(number, field, text) \ if(IS_OPTION(coap_pkt, number)) \
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); \
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; \
uint32_t block = coap_pkt->field##_num << 4; \ if(coap_pkt->field##_more) { block |= 0x8; } \
if (coap_pkt->field##_more) block |= 0x8; \ block |= 0xF & coap_log_2(coap_pkt->field##_size / 16); \
block |= 0xF & coap_log_2(coap_pkt->field##_size/16); \ PRINTF(text " encoded: 0x%lX\n", block); \
PRINTF(text" encoded: 0x%lX\n", block); \ option += coap_serialize_int_option(number, current_number, option, block); \
option += coap_serialize_int_option(number, current_number, option, block); \ current_number = number; \
current_number = number; \ }
}
/* to store error code and human-readable payload */
/* to store error code and human-readable payload */ extern coap_status_t erbium_status_code;
extern coap_status_t erbium_status_code; extern char *coap_error_message;
extern char *coap_error_message;
void coap_init_connection(uint16_t port);
void coap_init_connection(uint16_t port); uint16_t coap_get_mid(void);
uint16_t coap_get_mid(void);
void coap_init_message(void *packet, coap_message_type_t type, uint8_t code,
void coap_init_message(void *packet, coap_message_type_t type, uint8_t code, uint16_t mid);
uint16_t mid); size_t coap_serialize_message(void *packet, uint8_t *buffer);
size_t coap_serialize_message(void *packet, uint8_t * buffer); void coap_send_message(uip_ipaddr_t *addr, uint16_t port, uint8_t *data,
void coap_send_message(uip_ipaddr_t * addr, uint16_t port, uint8_t * data, uint16_t length);
uint16_t length); coap_status_t coap_parse_message(void *request, uint8_t *data,
coap_status_t coap_parse_message(void *request, uint8_t * data, uint16_t data_len);
uint16_t data_len);
int coap_get_query_variable(void *packet, const char *name,
int coap_get_query_variable(void *packet, const char *name, const char **output);
const char **output); int coap_get_post_variable(void *packet, const char *name,
int coap_get_post_variable(void *packet, const char *name, const char **output);
const char **output);
/*---------------------------------------------------------------------------*/
/*---------------------------------------------------------------------------*/
int coap_set_status_code(void *packet, unsigned int code);
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_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_get_header_content_format(void *packet, unsigned int *format); int coap_set_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_get_header_accept(void *packet, unsigned int *accept); int coap_set_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_get_header_max_age(void *packet, uint32_t * age); int coap_set_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_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_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_get_header_if_match(void *packet, const uint8_t ** etag); int coap_set_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);
size_t etag_len);
int coap_get_header_if_none_match(void *packet);
int coap_get_header_if_none_match(void *packet); int coap_set_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_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_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_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_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_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_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_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_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_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_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_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_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_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_set_header_location_query(void *packet, const char *query);
int coap_get_header_observe(void *packet, uint32_t *observe);
int coap_get_header_observe(void *packet, uint32_t * observe); int coap_set_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,
int coap_get_header_block2(void *packet, uint32_t * num, uint8_t * more, uint16_t *size, uint32_t *offset);
uint16_t * size, uint32_t * offset); int coap_set_header_block2(void *packet, uint32_t num, uint8_t more,
int coap_set_header_block2(void *packet, uint32_t num, uint8_t more, uint16_t size);
uint16_t size);
int coap_get_header_block1(void *packet, uint32_t *num, uint8_t *more,
int coap_get_header_block1(void *packet, uint32_t * num, uint8_t * more, uint16_t *size, uint32_t *offset);
uint16_t * size, uint32_t * offset); int coap_set_header_block1(void *packet, uint32_t num, uint8_t more,
int coap_set_header_block1(void *packet, uint32_t num, uint8_t more, uint16_t size);
uint16_t size);
int coap_get_header_size2(void *packet, uint32_t *size);
int coap_get_header_size2(void *packet, uint32_t * size); int coap_set_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_get_header_size1(void *packet, uint32_t * size); int coap_set_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_get_payload(void *packet, const uint8_t ** payload); int coap_set_payload(void *packet, const void *payload, size_t length);
int coap_set_payload(void *packet, const void *payload, size_t length);
#endif /* ER_COAP_H_ */
#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 * Copyright (c) 2013, Institute for Pervasive Computing, ETH Zurich
* All rights reserved. * All rights reserved.
* *
* Redistribution and use in source and binary forms, with or without * Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions * modification, are permitted provided that the following conditions
* are met: * are met:
* 1. Redistributions of source code must retain the above copyright * 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer. * notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright * 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the * notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution. * documentation and/or other materials provided with the distribution.
* 3. Neither the name of the Institute nor the names of its contributors * 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 * may be used to endorse or promote products derived from this software
* without specific prior written permission. * without specific prior written permission.
* *
* THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * 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 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE. * SUCH DAMAGE.
* *
* This file is part of the Contiki operating system. * This file is part of the Contiki operating system.
*/ */
/** /**
* \file * \file
* Constants for the REST Engine (Erbium). * Constants for the REST Engine (Erbium).
* \author * \author
* Matthias Kovatsch <kovatsch@inf.ethz.ch> * Matthias Kovatsch <kovatsch@inf.ethz.ch>
*/ */
#ifndef REST_CONSTANTS_H_ #ifndef REST_CONSTANTS_H_
#define REST_CONSTANTS_H_ #define REST_CONSTANTS_H_
/** /**
* Generic status codes that are mapped to either HTTP or CoAP codes. * Generic status codes that are mapped to either HTTP or CoAP codes.
*/ */
struct rest_implementation_status { struct rest_implementation_status {
const unsigned int OK; /* CONTENT_2_05, OK_200 */ const unsigned int OK; /* CONTENT_2_05, OK_200 */
const unsigned int CREATED; /* CREATED_2_01, CREATED_201 */ const unsigned int CREATED; /* CREATED_2_01, CREATED_201 */
const unsigned int CHANGED; /* CHANGED_2_04, NO_CONTENT_204 */ const unsigned int CHANGED; /* CHANGED_2_04, NO_CONTENT_204 */
const unsigned int DELETED; /* DELETED_2_02, 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 NOT_MODIFIED; /* VALID_2_03, NOT_MODIFIED_304 */
const unsigned int BAD_REQUEST; /* BAD_REQUEST_4_00, BAD_REQUEST_400 */ const unsigned int BAD_REQUEST; /* BAD_REQUEST_4_00, BAD_REQUEST_400 */
const unsigned int UNAUTHORIZED; /* UNAUTHORIZED_4_01, UNAUTHORIZED_401 */ const unsigned int UNAUTHORIZED; /* UNAUTHORIZED_4_01, UNAUTHORIZED_401 */
const unsigned int BAD_OPTION; /* BAD_OPTION_4_02, BAD_REQUEST_400 */ const unsigned int BAD_OPTION; /* BAD_OPTION_4_02, BAD_REQUEST_400 */
const unsigned int FORBIDDEN; /* FORBIDDEN_4_03, FORBIDDEN_403 */ const unsigned int FORBIDDEN; /* FORBIDDEN_4_03, FORBIDDEN_403 */
const unsigned int NOT_FOUND; /* NOT_FOUND_4_04, NOT_FOUND_404 */ 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 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 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 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 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 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 NOT_IMPLEMENTED; /* NOT_IMPLEMENTED_5_01, NOT_IMPLEMENTED_501 */
const unsigned int BAD_GATEWAY; /* BAD_GATEWAY_5_02, BAD_GATEWAY_502 */ 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 SERVICE_UNAVAILABLE; /* SERVICE_UNAVAILABLE_5_03, SERVICE_UNAVAILABLE_503 */
const unsigned int GATEWAY_TIMEOUT; /* GATEWAY_TIMEOUT_5_04, GATEWAY_TIMEOUT_504 */ 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 */ 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. * 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. * TODO This should be a constant enum taken from CoAP for both CoAP and HTTP.
*/ */
struct rest_implementation_type { struct rest_implementation_type {
unsigned int TEXT_PLAIN; unsigned int TEXT_PLAIN;
unsigned int TEXT_XML; unsigned int TEXT_XML;
unsigned int TEXT_CSV; unsigned int TEXT_CSV;
unsigned int TEXT_HTML; unsigned int TEXT_HTML;
unsigned int IMAGE_GIF; unsigned int IMAGE_GIF;
unsigned int IMAGE_JPEG; unsigned int IMAGE_JPEG;
unsigned int IMAGE_PNG; unsigned int IMAGE_PNG;
unsigned int IMAGE_TIFF; unsigned int IMAGE_TIFF;
unsigned int AUDIO_RAW; unsigned int AUDIO_RAW;
unsigned int VIDEO_RAW; unsigned int VIDEO_RAW;
unsigned int APPLICATION_LINK_FORMAT; unsigned int APPLICATION_LINK_FORMAT;
unsigned int APPLICATION_XML; unsigned int APPLICATION_XML;
unsigned int APPLICATION_OCTET_STREAM; unsigned int APPLICATION_OCTET_STREAM;
unsigned int APPLICATION_RDF_XML; unsigned int APPLICATION_RDF_XML;
unsigned int APPLICATION_SOAP_XML; unsigned int APPLICATION_SOAP_XML;
unsigned int APPLICATION_ATOM_XML; unsigned int APPLICATION_ATOM_XML;
unsigned int APPLICATION_XMPP_XML; unsigned int APPLICATION_XMPP_XML;
unsigned int APPLICATION_EXI; unsigned int APPLICATION_EXI;
unsigned int APPLICATION_FASTINFOSET; unsigned int APPLICATION_FASTINFOSET;
unsigned int APPLICATION_SOAP_FASTINFOSET; unsigned int APPLICATION_SOAP_FASTINFOSET;
unsigned int APPLICATION_JSON; unsigned int APPLICATION_JSON;
unsigned int APPLICATION_X_OBIX_BINARY; unsigned int APPLICATION_X_OBIX_BINARY;
}; };
/** /**
* Resource flags for allowed methods and special functionalities. * Resource flags for allowed methods and special functionalities.
*/ */
typedef enum { typedef enum {
NO_FLAGS = 0, NO_FLAGS = 0,
/* methods to handle */ /* methods to handle */
METHOD_GET = (1 << 0), METHOD_GET = (1 << 0),
METHOD_POST = (1 << 1), METHOD_POST = (1 << 1),
METHOD_PUT = (1 << 2), METHOD_PUT = (1 << 2),
METHOD_DELETE = (1 << 3), METHOD_DELETE = (1 << 3),
/* special flags */ /* special flags */
HAS_SUB_RESOURCES = (1 << 4), HAS_SUB_RESOURCES = (1 << 4),
IS_SEPARATE = (1 << 5), IS_SEPARATE = (1 << 5),
IS_OBSERVABLE = (1 << 6), IS_OBSERVABLE = (1 << 6),
IS_PERIODIC = (1 << 7) IS_PERIODIC = (1 << 7)
} rest_resource_flags_t; } rest_resource_flags_t;
#endif /* REST_CONSTANTS_H_ */ #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 * Copyright (c) 2013, Institute for Pervasive Computing, ETH Zurich
* All rights reserved. * All rights reserved.
* *
* Redistribution and use in source and binary forms, with or without * Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions * modification, are permitted provided that the following conditions
* are met: * are met:
* 1. Redistributions of source code must retain the above copyright * 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer. * notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright * 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the * notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution. * documentation and/or other materials provided with the distribution.
* 3. Neither the name of the Institute nor the names of its contributors * 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 * may be used to endorse or promote products derived from this software
* without specific prior written permission. * without specific prior written permission.
* *
* THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * 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 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE. * SUCH DAMAGE.
* *
* This file is part of the Contiki operating system. * This file is part of the Contiki operating system.
*/ */
/** /**
* \file * \file
* An abstraction layer for RESTful Web services (Erbium). * An abstraction layer for RESTful Web services (Erbium).
* Inspired by RESTful Contiki by Dogan Yazar. * Inspired by RESTful Contiki by Dogan Yazar.
* \author * \author
* Matthias Kovatsch <kovatsch@inf.ethz.ch> * Matthias Kovatsch <kovatsch@inf.ethz.ch>
*/ */
#include <string.h> #include <string.h>
#include <stdio.h> #include <stdio.h>
#include "contiki.h" #include "contiki.h"
#include "rest-engine.h" #include "rest-engine.h"
#define DEBUG DEBUG_NONE #define DEBUG 0
#include "net/uip-debug.h" #if DEBUG
#include <stdio.h>
PROCESS(rest_engine_process, "REST Engine"); #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])
LIST(restful_services); #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])
LIST(restful_periodic_services); #else
/*---------------------------------------------------------------------------*/ #define PRINTF(...)
/*- REST Engine API ---------------------------------------------------------*/ #define PRINT6ADDR(addr)
/*---------------------------------------------------------------------------*/ #define PRINTLLADDR(addr)
/** #endif
* \brief Initializes and starts the REST Engine process
* PROCESS(rest_engine_process, "REST Engine");
* This function must be called by server processes before any resources are /*---------------------------------------------------------------------------*/
* registered through rest_activate_resource(). LIST(restful_services);
*/ LIST(restful_periodic_services);
void /*---------------------------------------------------------------------------*/
rest_init_engine(void) /*- REST Engine API ---------------------------------------------------------*/
{ /*---------------------------------------------------------------------------*/
list_init(restful_services); /**
* \brief Initializes and starts the REST Engine process
REST.set_service_callback(rest_invoke_restful_service); *
* This function must be called by server processes before any resources are
/* Start the RESTful server implementation. */ * registered through rest_activate_resource().
REST.init(); */
void
/*Start REST engine process */ rest_init_engine(void)
process_start(&rest_engine_process, NULL); {
} list_init(restful_services);
/*---------------------------------------------------------------------------*/
/** REST.set_service_callback(rest_invoke_restful_service);
* \brief Makes a resource available under the given URI path
* \param resource A pointer to a resource implementation /* Start the RESTful server implementation. */
* \param path The URI path string for this resource REST.init();
*
* The resource implementation must be imported first using the /*Start REST engine process */
* extern keyword. The build system takes care of compiling every process_start(&rest_engine_process, NULL);
* *.c file in the ./resources/ sub-directory (see example Makefile). }
*/ /*---------------------------------------------------------------------------*/
void /**
rest_activate_resource(resource_t * resource, char *path) * \brief Makes a resource available under the given URI path
{ * \param resource A pointer to a resource implementation
resource->url = path; * \param path The URI path string for this resource
list_add(restful_services, resource); *
* The resource implementation must be imported first using the
PRINTF("Activating: %s\n", resource->url); * extern keyword. The build system takes care of compiling every
* *.c file in the ./resources/ sub-directory (see example Makefile).
/* Only add periodic resources with a periodic_handler and a period > 0. */ */
if(resource->flags & IS_PERIODIC && resource->periodic->periodic_handler void
&& resource->periodic->period) { rest_activate_resource(resource_t *resource, char *path)
PRINTF("Periodic resource: %p (%s)\n", resource->periodic, {
resource->periodic->resource->url); resource->url = path;
list_add(restful_periodic_services, resource->periodic); list_add(restful_services, resource);
}
} PRINTF("Activating: %s\n", resource->url);
/*---------------------------------------------------------------------------*/
/*- Internal API ------------------------------------------------------------*/ /* Only add periodic resources with a periodic_handler and a period > 0. */
/*---------------------------------------------------------------------------*/ if(resource->flags & IS_PERIODIC && resource->periodic->periodic_handler
list_t && resource->periodic->period) {
rest_get_resources(void) PRINTF("Periodic resource: %p (%s)\n", resource->periodic,
{ resource->periodic->resource->url);
return restful_services; list_add(restful_periodic_services, resource->periodic);
} }
/*---------------------------------------------------------------------------*/ }
int /*---------------------------------------------------------------------------*/
rest_invoke_restful_service(void *request, void *response, uint8_t * buffer, /*- Internal API ------------------------------------------------------------*/
uint16_t buffer_size, int32_t * offset) /*---------------------------------------------------------------------------*/
{ list_t
uint8_t found = 0; rest_get_resources(void)
uint8_t allowed = 1; {
return restful_services;
resource_t *resource = NULL; }
const char *url = NULL; /*---------------------------------------------------------------------------*/
int
for(resource = (resource_t *) list_head(restful_services); rest_invoke_restful_service(void *request, void *response, uint8_t *buffer,
resource; resource = resource->next) { uint16_t buffer_size, int32_t *offset)
{
/* if the web service handles that kind of requests and urls matches */ uint8_t found = 0;
if((REST.get_url(request, &url) == strlen(resource->url) uint8_t allowed = 1;
|| (REST.get_url(request, &url) > strlen(resource->url)
&& (resource->flags & HAS_SUB_RESOURCES))) resource_t *resource = NULL;
&& strncmp(resource->url, url, strlen(resource->url)) == 0) { const char *url = NULL;
found = 1;
rest_resource_flags_t method = REST.get_method_type(request); for(resource = (resource_t *)list_head(restful_services);
resource; resource = resource->next) {
PRINTF("/%s, method %u, resource->flags %u\n", resource->url,
(uint16_t) method, resource->flags); /* if the web service handles that kind of requests and urls matches */
if((REST.get_url(request, &url) == strlen(resource->url)
if((method & METHOD_GET) && resource->get_handler != NULL) { || (REST.get_url(request, &url) > strlen(resource->url)
/* call handler function */ && (resource->flags & HAS_SUB_RESOURCES)))
resource->get_handler(request, response, buffer, buffer_size, offset); && strncmp(resource->url, url, strlen(resource->url)) == 0) {
} else if((method & METHOD_POST) && resource->post_handler != NULL) { found = 1;
/* call handler function */ rest_resource_flags_t method = REST.get_method_type(request);
resource->post_handler(request, response, buffer, buffer_size,
offset); PRINTF("/%s, method %u, resource->flags %u\n", resource->url,
} else if((method & METHOD_PUT) && resource->put_handler != NULL) { (uint16_t)method, resource->flags);
/* call handler function */
resource->put_handler(request, response, buffer, buffer_size, offset); if((method & METHOD_GET) && resource->get_handler != NULL) {
} else if((method & METHOD_DELETE) && resource->delete_handler != NULL) { /* call handler function */
/* call handler function */ resource->get_handler(request, response, buffer, buffer_size, offset);
resource->delete_handler(request, response, buffer, buffer_size, } else if((method & METHOD_POST) && resource->post_handler != NULL) {
offset); /* call handler function */
} else { resource->post_handler(request, response, buffer, buffer_size,
allowed = 0; offset);
REST.set_response_status(response, REST.status.METHOD_NOT_ALLOWED); } else if((method & METHOD_PUT) && resource->put_handler != NULL) {
} /* call handler function */
break; 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,
if(!found) { offset);
REST.set_response_status(response, REST.status.NOT_FOUND); } else {
} else if(allowed) { allowed = 0;
/* final handler for special flags */ REST.set_response_status(response, REST.status.METHOD_NOT_ALLOWED);
if(resource->flags & IS_OBSERVABLE) { }
REST.subscription_handler(resource, request, response); break;
} }
} }
if(!found) {
return found & allowed; REST.set_response_status(response, REST.status.NOT_FOUND);
} } else if(allowed) {
/*-----------------------------------------------------------------------------------*/ /* final handler for special flags */
PROCESS_THREAD(rest_engine_process, ev, data) if(resource->flags & IS_OBSERVABLE) {
{ REST.subscription_handler(resource, request, response);
PROCESS_BEGIN(); }
}
/* pause to let REST server finish adding resources. */ return found & allowed;
PROCESS_PAUSE(); }
/*-----------------------------------------------------------------------------------*/
/* initialize the PERIODIC_RESOURCE timers, which will be handled by this process. */ PROCESS_THREAD(rest_engine_process, ev, data)
periodic_resource_t *periodic_resource = NULL; {
PROCESS_BEGIN();
for(periodic_resource =
(periodic_resource_t *) list_head(restful_periodic_services); /* pause to let REST server finish adding resources. */
periodic_resource; periodic_resource = periodic_resource->next) { PROCESS_PAUSE();
if(periodic_resource->periodic_handler && periodic_resource->period) {
PRINTF("Periodic: Set timer for /%s to %lu\n", /* initialize the PERIODIC_RESOURCE timers, which will be handled by this process. */
periodic_resource->resource->url, periodic_resource->period); periodic_resource_t *periodic_resource = NULL;
etimer_set(&periodic_resource->periodic_timer,
periodic_resource->period); 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) {
while(1) { PRINTF("Periodic: Set timer for /%s to %lu\n",
PROCESS_WAIT_EVENT(); periodic_resource->resource->url, periodic_resource->period);
etimer_set(&periodic_resource->periodic_timer,
if(ev == PROCESS_EVENT_TIMER) { periodic_resource->period);
for(periodic_resource = }
(periodic_resource_t *) list_head(restful_periodic_services); }
periodic_resource; periodic_resource = periodic_resource->next) { while(1) {
if(periodic_resource->period PROCESS_WAIT_EVENT();
&& etimer_expired(&periodic_resource->periodic_timer)) {
if(ev == PROCESS_EVENT_TIMER) {
PRINTF("Periodic: etimer expired for /%s (period: %lu)\n", for(periodic_resource =
periodic_resource->resource->url, periodic_resource->period); (periodic_resource_t *)list_head(restful_periodic_services);
periodic_resource; periodic_resource = periodic_resource->next) {
/* Call the periodic_handler function, which was checked during adding to list. */ if(periodic_resource->period
(periodic_resource->periodic_handler) (); && etimer_expired(&periodic_resource->periodic_timer)) {
etimer_reset(&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)();
PROCESS_END(); 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 * Copyright (c) 2013, Institute for Pervasive Computing, ETH Zurich
* All rights reserved. * All rights reserved.
* *
* Redistribution and use in source and binary forms, with or without * Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions * modification, are permitted provided that the following conditions
* are met: * are met:
* 1. Redistributions of source code must retain the above copyright * 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer. * notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright * 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the * notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution. * documentation and/or other materials provided with the distribution.
* 3. Neither the name of the Institute nor the names of its contributors * 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 * may be used to endorse or promote products derived from this software
* without specific prior written permission. * without specific prior written permission.
* *
* THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * 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 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE. * SUCH DAMAGE.
* *
* This file is part of the Contiki operating system. * This file is part of the Contiki operating system.
*/ */
/** /**
* \file * \file
* An abstraction layer for RESTful Web services (Erbium). * An abstraction layer for RESTful Web services (Erbium).
* Inspired by RESTful Contiki by Dogan Yazar. * Inspired by RESTful Contiki by Dogan Yazar.
* \author * \author
* Matthias Kovatsch <kovatsch@inf.ethz.ch> * Matthias Kovatsch <kovatsch@inf.ethz.ch>
*/ */
#ifndef REST_ENGINE_H_ #ifndef REST_ENGINE_H_
#define REST_ENGINE_H_ #define REST_ENGINE_H_
#include <stdio.h> #include <stdio.h>
#include "contiki.h" #include "contiki.h"
#include "contiki-lib.h" #include "contiki-lib.h"
#include "rest-constants.h" #include "rest-constants.h"
/* list of valid REST Enigne implementations */ /* list of valid REST Enigne implementations */
#define REGISTERED_ENGINE_ERBIUM coap_rest_implementation #define REGISTERED_ENGINE_ERBIUM coap_rest_implementation
#define REGISTERED_ENGINE_HELIUM http_rest_implementation #define REGISTERED_ENGINE_HELIUM http_rest_implementation
/* sanity check for configured implementation */ /* sanity check for configured implementation */
#if !defined(REST) || (REST!=REGISTERED_ENGINE_ERBIUM && REST!=REGISTERED_ENGINE_HELIUM) #if !defined(REST) || (REST != REGISTERED_ENGINE_ERBIUM && REST != REGISTERED_ENGINE_HELIUM)
#error "Define a valid REST Engine implementation (REST define)!" #error "Define a valid REST Engine implementation (REST define)!"
#endif #endif
/* /*
* The maximum buffer size that is provided for resource responses and must be respected due to the limited IP buffer. * 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. * 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 #ifndef REST_MAX_CHUNK_SIZE
#define REST_MAX_CHUNK_SIZE 64 #define REST_MAX_CHUNK_SIZE 64
#endif #endif
#ifndef MIN #ifndef MIN
#define MIN(a, b) ((a) < (b)? (a) : (b)) #define MIN(a, b) ((a) < (b) ? (a) : (b))
#endif /* MIN */ #endif /* MIN */
struct resource_s;
struct resource_s; struct periodic_resource_s;
struct periodic_resource_s;
/* signatures of handler functions */
/* signatures of handler functions */ typedef void (*restful_handler)(void *request, void *response,
typedef void (*restful_handler) (void *request, void *response, uint8_t *buffer, uint16_t preferred_size,
uint8_t * buffer, uint16_t preferred_size, int32_t *offset);
int32_t * offset); typedef void (*restful_final_handler)(struct resource_s *resource,
typedef void (*restful_final_handler) (struct resource_s * resource, void *request, void *response);
void *request, void *response); typedef void (*restful_periodic_handler)(void);
typedef void (*restful_periodic_handler) (void); typedef void (*restful_response_handler)(void *data, void *response);
typedef void (*restful_response_handler) (void *data, void *response); typedef void (*restful_trigger_handler)(void);
typedef void (*restful_trigger_handler) (void);
/* signature of the rest-engine service function */
/* signature of the rest-engine service function */ typedef int (*service_callback_t)(void *request, void *response,
typedef int (*service_callback_t) (void *request, void *response, uint8_t *buffer, uint16_t preferred_size,
uint8_t * buffer, uint16_t preferred_size, int32_t *offset);
int32_t * offset);
/* data structure representing a resource in REST */
/* data structure representing a resource in REST */ struct resource_s {
struct resource_s { struct resource_s *next; /* for LIST, points to next resource defined */
struct resource_s *next; /* for LIST, points to next resource defined */ const char *url; /*handled URL */
const char *url; /*handled URL */ rest_resource_flags_t flags; /* handled RESTful methods */
rest_resource_flags_t flags; /* handled RESTful methods */ const char *attributes; /* link-format attributes */
const char *attributes; /* link-format attributes */ restful_handler get_handler; /* handler function */
restful_handler get_handler; /* handler function */ restful_handler post_handler; /* handler function */
restful_handler post_handler; /* handler function */ restful_handler put_handler; /* handler function */
restful_handler put_handler; /* handler function */ restful_handler delete_handler; /* handler function */
restful_handler delete_handler; /* handler function */ union {
union { struct periodic_resource_s *periodic; /* special data depending on flags */
struct periodic_resource_s *periodic; /* special data depending on flags */ restful_trigger_handler trigger;
restful_trigger_handler trigger; restful_trigger_handler resume;
restful_trigger_handler resume; };
}; };
}; typedef struct resource_s resource_t;
typedef struct resource_s resource_t;
struct periodic_resource_s {
struct periodic_resource_s { struct periodic_resource_s *next; /* for LIST, points to next resource defined */
struct periodic_resource_s *next; /* for LIST, points to next resource defined */ const resource_t *resource;
const resource_t *resource; uint32_t period;
uint32_t period; struct etimer periodic_timer;
struct etimer periodic_timer; const restful_periodic_handler periodic_handler;
const restful_periodic_handler periodic_handler; };
}; typedef struct periodic_resource_s periodic_resource_t;
typedef struct periodic_resource_s periodic_resource_t;
/*
/* * Macro to define a RESTful resource.
* Macro to define a RESTful resource. * Resources are statically defined for the sake of efficiency and better memory management.
* 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) \
#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 } }
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) \
#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 } }
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) \
#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 } }
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) \
#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 } }
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.
* Macro to define a periodic resource. * The corresponding [name]_periodic_handler() function will be called every period.
* 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.
* 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).
* 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) \
#define PERIODIC_RESOURCE(name, attributes, get_handler, post_handler, put_handler, delete_handler, period, periodic_handler) \ periodic_resource_t periodic_##name; \
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 } }; \
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 };
periodic_resource_t periodic_##name = {NULL, &name, period, {{0}}, periodic_handler};
struct rest_implementation {
struct rest_implementation { char *name;
char *name;
/** Initialize the REST implementation. */
/** Initialize the REST implementation. */ void (*init)(void);
void (*init) (void);
/** Register the RESTful service callback at implementation. */
/** Register the RESTful service callback at implementation. */ void (*set_service_callback)(service_callback_t callback);
void (*set_service_callback) (service_callback_t callback);
/** Get request URI path. */
/** Get request URI path. */ int (*get_url)(void *request, const char **url);
int (*get_url) (void *request, const char **url);
/** Get the method of a request. */
/** Get the method of a request. */ rest_resource_flags_t (*get_method_type)(void *request);
rest_resource_flags_t (*get_method_type) (void *request);
/** Set the status code of a response. */
/** Set the status code of a response. */ int (*set_response_status)(void *response, unsigned int code);
int (*set_response_status) (void *response, unsigned int code);
/** Get the content-type of a request. */
/** Get the content-type of a request. */ int (*get_header_content_type)(void *request,
int (*get_header_content_type) (void *request, unsigned int *content_format);
unsigned int *content_format);
/** Set the Content-Type of a response. */
/** Set the Content-Type of a response. */ int (*set_header_content_type)(void *response,
int (*set_header_content_type) (void *response, unsigned int content_format);
unsigned int content_format);
/** Get the Accept types of a request. */
/** Get the Accept types of a request. */ int (*get_header_accept)(void *request, unsigned int *accept);
int (*get_header_accept) (void *request, unsigned int *accept);
/** Get the Length option of a request. */
/** Get the Length option of a request. */ int (*get_header_length)(void *request, uint32_t *size);
int (*get_header_length) (void *request, uint32_t * size);
/** Set the Length option of a response. */
/** Set the Length option of a response. */ int (*set_header_length)(void *response, uint32_t size);
int (*set_header_length) (void *response, uint32_t size);
/** Get the Max-Age option of a request. */
/** Get the Max-Age option of a request. */ int (*get_header_max_age)(void *request, uint32_t *age);
int (*get_header_max_age) (void *request, uint32_t * age);
/** Set the Max-Age option of a response. */
/** Set the Max-Age option of a response. */ int (*set_header_max_age)(void *response, uint32_t age);
int (*set_header_max_age) (void *response, uint32_t age);
/** Set the ETag option of a response. */
/** Set the ETag option of a response. */ int (*set_header_etag)(void *response, const uint8_t *etag,
int (*set_header_etag) (void *response, const uint8_t * etag, size_t length);
size_t length);
/** Get the If-Match option of a request. */
/** Get the If-Match option of a request. */ int (*get_header_if_match)(void *request, const uint8_t **etag);
int (*get_header_if_match) (void *request, const uint8_t ** etag);
/** Get the If-Match option of a request. */
/** Get the If-Match option of a request. */ int (*get_header_if_none_match)(void *request);
int (*get_header_if_none_match) (void *request);
/** Get the Host option of a request. */
/** Get the Host option of a request. */ int (*get_header_host)(void *request, const char **host);
int (*get_header_host) (void *request, const char **host);
/** Set the location option of a response. */
/** Set the location option of a response. */ int (*set_header_location)(void *response, const char *location);
int (*set_header_location) (void *response, const char *location);
/** Get the payload option of a request. */
/** Get the payload option of a request. */ int (*get_request_payload)(void *request, const uint8_t **payload);
int (*get_request_payload) (void *request, const uint8_t ** payload);
/** Set the payload option of a response. */
/** Set the payload option of a response. */ int (*set_response_payload)(void *response, const void *payload,
int (*set_response_payload) (void *response, const void *payload, size_t length);
size_t length);
/** Get the query string of a request. */
/** Get the query string of a request. */ int (*get_query)(void *request, const char **value);
int (*get_query) (void *request, const char **value);
/** Get the value of a request query key-value pair. */
/** Get the value of a request query key-value pair. */ int (*get_query_variable)(void *request, const char *name,
int (*get_query_variable) (void *request, const char *name, const char **value);
const char **value);
/** Get the value of a request POST key-value pair. */
/** Get the value of a request POST key-value pair. */ int (*get_post_variable)(void *request, const char *name,
int (*get_post_variable) (void *request, const char *name, const char **value);
const char **value);
/** Send the payload to all subscribers of the resource at url. */
/** Send the payload to all subscribers of the resource at url. */ void (*notify_subscribers)(resource_t *resource);
void (*notify_subscribers) (resource_t * resource);
/** The handler for resource subscriptions. */
/** The handler for resource subscriptions. */ restful_final_handler subscription_handler;
restful_final_handler subscription_handler;
/* REST status codes. */
/* REST status codes. */ const struct rest_implementation_status status;
const struct rest_implementation_status status;
/* REST content-types. */
/* REST content-types. */ const struct rest_implementation_type type;
const struct rest_implementation_type type; };
};
/* instance of REST implementation */
/* instance of REST implementation */ extern const struct rest_implementation REST;
extern const struct rest_implementation REST;
/*
/* * To be called by HTTP/COAP server as a callback function when a new service request appears.
* To be called by HTTP/COAP server as a callback function when a new service request appears. * This function dispatches the corresponding RESTful service.
* This function dispatches the corresponding RESTful service. */
*/ int rest_invoke_restful_service(void *request, void *response,
int rest_invoke_restful_service(void *request, void *response, uint8_t *buffer, uint16_t buffer_size,
uint8_t * buffer, uint16_t buffer_size, int32_t *offset);
int32_t * offset); /*---------------------------------------------------------------------------*/
/*---------------------------------------------------------------------------*/ /**
/** * \brief Initializes REST framework and starts the HTTP or CoAP process.
* \brief Initializes REST framework and starts the HTTP or CoAP process. */
*/ void rest_init_engine(void);
void rest_init_engine(void); /*---------------------------------------------------------------------------*/
/*---------------------------------------------------------------------------*/ /**
/** *
* * \brief Resources wanted to be accessible should be activated with the following code.
* \brief Resources wanted to be accessible should be activated with the following code. * \param resource
* \param resource * A RESTful resource defined through the RESOURCE macros.
* A RESTful resource defined through the RESOURCE macros. * \param path
* \param path * The local URI path where to provide the resource.
* The local URI path where to provide the resource. */
*/ void rest_activate_resource(resource_t *resource, char *path);
void rest_activate_resource(resource_t * resource, char *path); /*---------------------------------------------------------------------------*/
/*---------------------------------------------------------------------------*/ /**
/** * \brief Returns the list of registered RESTful resources.
* \brief Returns the list of registered RESTful resources. * \return The resource list.
* \return The resource list. */
*/ list_t rest_get_resources(void);
list_t rest_get_resources(void); /*---------------------------------------------------------------------------*/
/*---------------------------------------------------------------------------*/
#endif /*REST_ENGINE_H_ */
#endif /*REST_ENGINE_H_ */

View file

@ -13,7 +13,15 @@ CFLAGS += -DPROJECT_CONF_H=\"project-conf.h\"
# automatically build RESTful resources # automatically build RESTful resources
REST_RESOURCES_DIR = ./resources REST_RESOURCES_DIR = ./resources
ifndef TARGET
REST_RESOURCES_FILES = $(notdir $(shell find $(REST_RESOURCES_DIR) -name '*.c')) REST_RESOURCES_FILES = $(notdir $(shell find $(REST_RESOURCES_DIR) -name '*.c'))
else
ifeq ($(TARGET), native)
REST_RESOURCES_FILES = $(notdir $(shell find $(REST_RESOURCES_DIR) -name '*.c'))
else
REST_RESOURCES_FILES = $(notdir $(shell find $(REST_RESOURCES_DIR) -name '*.c' ! -name 'res-plugtest*'))
endif
endif
PROJECTDIRS += $(REST_RESOURCES_DIR) PROJECTDIRS += $(REST_RESOURCES_DIR)
PROJECT_SOURCEFILES += $(REST_RESOURCES_FILES) PROJECT_SOURCEFILES += $(REST_RESOURCES_FILES)

315
examples/er-rest-example/er-example-client.c Executable file → Normal file
View file

@ -1,156 +1,159 @@
/* /*
* Copyright (c) 2013, Institute for Pervasive Computing, ETH Zurich * Copyright (c) 2013, Institute for Pervasive Computing, ETH Zurich
* All rights reserved. * All rights reserved.
* *
* Redistribution and use in source and binary forms, with or without * Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions * modification, are permitted provided that the following conditions
* are met: * are met:
* 1. Redistributions of source code must retain the above copyright * 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer. * notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright * 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the * notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution. * documentation and/or other materials provided with the distribution.
* 3. Neither the name of the Institute nor the names of its contributors * 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 * may be used to endorse or promote products derived from this software
* without specific prior written permission. * without specific prior written permission.
* *
* THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * 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 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE. * SUCH DAMAGE.
* *
* This file is part of the Contiki operating system. * This file is part of the Contiki operating system.
*/ */
/** /**
* \file * \file
* Erbium (Er) CoAP client example. * Erbium (Er) CoAP client example.
* \author * \author
* Matthias Kovatsch <kovatsch@inf.ethz.ch> * Matthias Kovatsch <kovatsch@inf.ethz.ch>
*/ */
#include <stdio.h> #include <stdio.h>
#include <stdlib.h> #include <stdlib.h>
#include <string.h> #include <string.h>
#include "contiki.h" #include "contiki.h"
#include "contiki-net.h" #include "contiki-net.h"
#include "er-coap-engine.h" #include "er-coap-engine.h"
#include "dev/button-sensor.h" #include "dev/button-sensor.h"
#define DEBUG DEBUG_NONE #define DEBUG 0
#include "net/uip-debug.h" #if DEBUG
#include <stdio.h>
#define PRINTF(...) printf(__VA_ARGS__)
/* FIXME: This server address is hard-coded for Cooja and link-local for unconnected border router. */ #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 SERVER_NODE(ipaddr) uip_ip6addr(ipaddr, 0xfe80, 0, 0, 0, 0x0212, 0x7402, 0x0002, 0x0202) /* cooja2 */ #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])
//#define SERVER_NODE(ipaddr) uip_ip6addr(ipaddr, 0xbbbb, 0, 0, 0, 0, 0, 0, 0x1) #else
#define PRINTF(...)
#define LOCAL_PORT UIP_HTONS(COAP_DEFAULT_PORT+1) #define PRINT6ADDR(addr)
#define REMOTE_PORT UIP_HTONS(COAP_DEFAULT_PORT) #define PRINTLLADDR(addr)
#endif
#define TOGGLE_INTERVAL 10
/* FIXME: This server address is hard-coded for Cooja and link-local for unconnected border router. */
PROCESS(er_example_client, "Erbium Example Client"); #define SERVER_NODE(ipaddr) uip_ip6addr(ipaddr, 0xfe80, 0, 0, 0, 0x0212, 0x7402, 0x0002, 0x0202) /* cooja2 */
AUTOSTART_PROCESSES(&er_example_client); /* #define SERVER_NODE(ipaddr) uip_ip6addr(ipaddr, 0xbbbb, 0, 0, 0, 0, 0, 0, 0x1) */
#define LOCAL_PORT UIP_HTONS(COAP_DEFAULT_PORT + 1)
uip_ipaddr_t server_ipaddr; #define REMOTE_PORT UIP_HTONS(COAP_DEFAULT_PORT)
static struct etimer et;
#define TOGGLE_INTERVAL 10
/* Example URIs that can be queried. */
#define NUMBER_OF_URLS 4 PROCESS(er_example_client, "Erbium Example Client");
/* leading and ending slashes only for demo purposes, get cropped automatically when setting the Uri-Path */ AUTOSTART_PROCESSES(&er_example_client);
char *service_urls[NUMBER_OF_URLS] =
{ ".well-known/core", "/actuators/toggle", "battery/", "error/in//path" }; uip_ipaddr_t server_ipaddr;
#if PLATFORM_HAS_BUTTON static struct etimer et;
static int uri_switch = 0;
#endif /* Example URIs that can be queried. */
#define NUMBER_OF_URLS 4
/* This function is will be passed to COAP_BLOCKING_REQUEST() to handle responses. */ /* leading and ending slashes only for demo purposes, get cropped automatically when setting the Uri-Path */
void char *service_urls[NUMBER_OF_URLS] =
client_chunk_handler(void *response) { ".well-known/core", "/actuators/toggle", "battery/", "error/in//path" };
{ #if PLATFORM_HAS_BUTTON
const uint8_t *chunk; static int uri_switch = 0;
#endif
int len = coap_get_payload(response, &chunk);
/* This function is will be passed to COAP_BLOCKING_REQUEST() to handle responses. */
printf("|%.*s", len, (char *)chunk); void
} client_chunk_handler(void *response)
{
const uint8_t *chunk;
PROCESS_THREAD(er_example_client, ev, data)
{ int len = coap_get_payload(response, &chunk);
PROCESS_BEGIN();
printf("|%.*s", len, (char *)chunk);
static coap_packet_t request[1]; /* This way the packet can be treated as pointer as usual. */ }
PROCESS_THREAD(er_example_client, ev, data)
SERVER_NODE(&server_ipaddr); {
PROCESS_BEGIN();
/* receives all CoAP messages */
coap_init_engine(); static coap_packet_t request[1]; /* This way the packet can be treated as pointer as usual. */
etimer_set(&et, TOGGLE_INTERVAL * CLOCK_SECOND); SERVER_NODE(&server_ipaddr);
#if PLATFORM_HAS_BUTTON /* receives all CoAP messages */
SENSORS_ACTIVATE(button_sensor); coap_init_engine();
printf("Press a button to request %s\n", service_urls[uri_switch]);
#endif etimer_set(&et, TOGGLE_INTERVAL * CLOCK_SECOND);
while(1) { #if PLATFORM_HAS_BUTTON
PROCESS_YIELD(); SENSORS_ACTIVATE(button_sensor);
printf("Press a button to request %s\n", service_urls[uri_switch]);
if(etimer_expired(&et)) { #endif
printf("--Toggle timer--\n");
while(1) {
/* prepare request, TID is set by COAP_BLOCKING_REQUEST() */ PROCESS_YIELD();
coap_init_message(request, COAP_TYPE_CON, COAP_POST, 0);
coap_set_header_uri_path(request, service_urls[1]); if(etimer_expired(&et)) {
printf("--Toggle timer--\n");
const char msg[] = "Toggle!";
/* prepare request, TID is set by COAP_BLOCKING_REQUEST() */
coap_set_payload(request, (uint8_t *) msg, sizeof(msg) - 1); coap_init_message(request, COAP_TYPE_CON, COAP_POST, 0);
coap_set_header_uri_path(request, service_urls[1]);
PRINT6ADDR(&server_ipaddr); const char msg[] = "Toggle!";
PRINTF(" : %u\n", UIP_HTONS(REMOTE_PORT));
coap_set_payload(request, (uint8_t *)msg, sizeof(msg) - 1);
COAP_BLOCKING_REQUEST(&server_ipaddr, REMOTE_PORT, request,
client_chunk_handler); PRINT6ADDR(&server_ipaddr);
PRINTF(" : %u\n", UIP_HTONS(REMOTE_PORT));
printf("\n--Done--\n");
COAP_BLOCKING_REQUEST(&server_ipaddr, REMOTE_PORT, request,
etimer_reset(&et); client_chunk_handler);
#if PLATFORM_HAS_BUTTON printf("\n--Done--\n");
} else if(ev == sensors_event && data == &button_sensor) {
etimer_reset(&et);
/* send a request to notify the end of the process */
#if PLATFORM_HAS_BUTTON
coap_init_message(request, COAP_TYPE_CON, COAP_GET, 0); } else if(ev == sensors_event && data == &button_sensor) {
coap_set_header_uri_path(request, service_urls[uri_switch]);
/* send a request to notify the end of the process */
printf("--Requesting %s--\n", service_urls[uri_switch]);
coap_init_message(request, COAP_TYPE_CON, COAP_GET, 0);
PRINT6ADDR(&server_ipaddr); coap_set_header_uri_path(request, service_urls[uri_switch]);
PRINTF(" : %u\n", UIP_HTONS(REMOTE_PORT));
printf("--Requesting %s--\n", service_urls[uri_switch]);
COAP_BLOCKING_REQUEST(&server_ipaddr, REMOTE_PORT, request,
client_chunk_handler); PRINT6ADDR(&server_ipaddr);
PRINTF(" : %u\n", UIP_HTONS(REMOTE_PORT));
printf("\n--Done--\n");
COAP_BLOCKING_REQUEST(&server_ipaddr, REMOTE_PORT, request,
uri_switch = (uri_switch + 1) % NUMBER_OF_URLS; client_chunk_handler);
#endif
printf("\n--Done--\n");
}
} uri_switch = (uri_switch + 1) % NUMBER_OF_URLS;
#endif
PROCESS_END(); }
} }
PROCESS_END();
}

0
examples/er-rest-example/er-example-server.c Executable file → Normal file
View file

257
examples/er-rest-example/er-plugtest-server.c Executable file → Normal file
View file

@ -1,129 +1,128 @@
/* /*
* Copyright (c) 2013, Institute for Pervasive Computing, ETH Zurich * Copyright (c) 2013, Institute for Pervasive Computing, ETH Zurich
* All rights reserved. * All rights reserved.
* *
* Redistribution and use in source and binary forms, with or without * Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions * modification, are permitted provided that the following conditions
* are met: * are met:
* 1. Redistributions of source code must retain the above copyright * 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer. * notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright * 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the * notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution. * documentation and/or other materials provided with the distribution.
* 3. Neither the name of the Institute nor the names of its contributors * 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 * may be used to endorse or promote products derived from this software
* without specific prior written permission. * without specific prior written permission.
* *
* THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * 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 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE. * SUCH DAMAGE.
* *
* This file is part of the Contiki operating system. * This file is part of the Contiki operating system.
*/ */
/** /**
* \file * \file
* Server for the ETSI IoT CoAP Plugtests, Las Vegas, NV, USA, Nov 2013. * Server for the ETSI IoT CoAP Plugtests, Las Vegas, NV, USA, Nov 2013.
* \author * \author
* Matthias Kovatsch <kovatsch@inf.ethz.ch> * Matthias Kovatsch <kovatsch@inf.ethz.ch>
*/ */
#include <stdio.h> #include <stdio.h>
#include <stdlib.h> #include <stdlib.h>
#include <string.h> #include <string.h>
#include "contiki.h" #include "contiki.h"
#include "contiki-net.h" #include "contiki-net.h"
#include "er-coap.h" #include "er-coap.h"
#include "er-coap-transactions.h" #include "er-coap-transactions.h"
#include "er-coap-separate.h" #include "er-coap-separate.h"
#include "rest-engine.h" #include "rest-engine.h"
#include "er-plugtest.h" #include "er-plugtest.h"
/* /*
* Resources to be activated need to be imported through the extern keyword. * Resources to be activated need to be imported through the extern keyword.
* The build system automatically compiles the resources in the corresponding * The build system automatically compiles the resources in the corresponding
* sub-directory. * sub-directory.
*/ */
extern resource_t extern resource_t
res_plugtest_test, res_plugtest_test,
res_plugtest_validate, res_plugtest_validate,
res_plugtest_create1, res_plugtest_create1,
res_plugtest_create2, res_plugtest_create2,
res_plugtest_create3, res_plugtest_create3,
res_plugtest_longpath, res_plugtest_longpath,
res_plugtest_query, res_plugtest_query,
res_plugtest_locquery, res_plugtest_locquery,
res_plugtest_multi, res_plugtest_multi,
res_plugtest_link1, res_plugtest_link1,
res_plugtest_link2, res_plugtest_link2,
res_plugtest_link3, res_plugtest_link3,
res_plugtest_path, res_plugtest_path,
res_plugtest_separate, res_plugtest_separate,
res_plugtest_large, res_plugtest_large,
res_plugtest_large_update, res_plugtest_large_update,
res_plugtest_large_create, res_plugtest_large_create,
res_plugtest_obs, res_plugtest_obs,
res_mirror; res_mirror;
PROCESS(plugtest_server, "PlugtestServer"); PROCESS(plugtest_server, "PlugtestServer");
AUTOSTART_PROCESSES(&plugtest_server); AUTOSTART_PROCESSES(&plugtest_server);
PROCESS_THREAD(plugtest_server, ev, data) PROCESS_THREAD(plugtest_server, ev, data)
{ {
PROCESS_BEGIN(); PROCESS_BEGIN();
PRINTF("ETSI IoT CoAP Plugtests Server\n"); PRINTF("ETSI IoT CoAP Plugtests Server\n");
#ifdef RF_CHANNEL #ifdef RF_CHANNEL
PRINTF("RF channel: %u\n", RF_CHANNEL); PRINTF("RF channel: %u\n", RF_CHANNEL);
#endif #endif
#ifdef IEEE802154_PANID #ifdef IEEE802154_PANID
PRINTF("PAN ID: 0x%04X\n", IEEE802154_PANID); PRINTF("PAN ID: 0x%04X\n", IEEE802154_PANID);
#endif #endif
PRINTF("uIP buffer: %u\n", UIP_BUFSIZE); PRINTF("uIP buffer: %u\n", UIP_BUFSIZE);
PRINTF("LL header: %u\n", UIP_LLH_LEN); PRINTF("LL header: %u\n", UIP_LLH_LEN);
PRINTF("IP+UDP header: %u\n", UIP_IPUDPH_LEN); PRINTF("IP+UDP header: %u\n", UIP_IPUDPH_LEN);
PRINTF("REST max chunk: %u\n", REST_MAX_CHUNK_SIZE); PRINTF("REST max chunk: %u\n", REST_MAX_CHUNK_SIZE);
/* Initialize the REST engine. */ /* Initialize the REST engine. */
rest_init_engine(); rest_init_engine();
/* Activate the application-specific resources. */ /* Activate the application-specific resources. */
rest_activate_resource(&res_plugtest_test, "test"); rest_activate_resource(&res_plugtest_test, "test");
rest_activate_resource(&res_plugtest_validate, "validate"); rest_activate_resource(&res_plugtest_validate, "validate");
rest_activate_resource(&res_plugtest_create1, "create1"); rest_activate_resource(&res_plugtest_create1, "create1");
rest_activate_resource(&res_plugtest_create2, "create2"); rest_activate_resource(&res_plugtest_create2, "create2");
rest_activate_resource(&res_plugtest_create3, "create3"); rest_activate_resource(&res_plugtest_create3, "create3");
rest_activate_resource(&res_plugtest_longpath, "seg1/seg2/seg3"); rest_activate_resource(&res_plugtest_longpath, "seg1/seg2/seg3");
rest_activate_resource(&res_plugtest_query, "query"); rest_activate_resource(&res_plugtest_query, "query");
rest_activate_resource(&res_plugtest_locquery, "location-query"); rest_activate_resource(&res_plugtest_locquery, "location-query");
rest_activate_resource(&res_plugtest_multi, "multi-format"); rest_activate_resource(&res_plugtest_multi, "multi-format");
rest_activate_resource(&res_plugtest_link1, "link1"); rest_activate_resource(&res_plugtest_link1, "link1");
rest_activate_resource(&res_plugtest_link2, "link2"); rest_activate_resource(&res_plugtest_link2, "link2");
rest_activate_resource(&res_plugtest_link3, "link3"); rest_activate_resource(&res_plugtest_link3, "link3");
rest_activate_resource(&res_plugtest_path, "path"); rest_activate_resource(&res_plugtest_path, "path");
rest_activate_resource(&res_plugtest_separate, "separate"); rest_activate_resource(&res_plugtest_separate, "separate");
rest_activate_resource(&res_plugtest_large, "large"); rest_activate_resource(&res_plugtest_large, "large");
rest_activate_resource(&res_plugtest_large_update, "large-update"); rest_activate_resource(&res_plugtest_large_update, "large-update");
rest_activate_resource(&res_plugtest_large_create, "large-create"); rest_activate_resource(&res_plugtest_large_create, "large-create");
rest_activate_resource(&res_plugtest_obs, "obs"); rest_activate_resource(&res_plugtest_obs, "obs");
rest_activate_resource(&res_mirror, "mirror"); rest_activate_resource(&res_mirror, "mirror");
/* Define application-specific events here. */ /* Define application-specific events here. */
while(1) { while(1) {
PROCESS_WAIT_EVENT(); PROCESS_WAIT_EVENT();
} /* while (1) */
} /* while (1) */
PROCESS_END();
PROCESS_END(); }
}

123
examples/er-rest-example/er-plugtest.h Executable file → Normal file
View file

@ -1,57 +1,66 @@
/* /*
* Copyright (c) 2013, Institute for Pervasive Computing, ETH Zurich * Copyright (c) 2013, Institute for Pervasive Computing, ETH Zurich
* All rights reserved. * All rights reserved.
* *
* Redistribution and use in source and binary forms, with or without * Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions * modification, are permitted provided that the following conditions
* are met: * are met:
* 1. Redistributions of source code must retain the above copyright * 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer. * notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright * 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the * notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution. * documentation and/or other materials provided with the distribution.
* 3. Neither the name of the Institute nor the names of its contributors * 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 * may be used to endorse or promote products derived from this software
* without specific prior written permission. * without specific prior written permission.
* *
* THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * 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 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE. * SUCH DAMAGE.
* *
* This file is part of the Contiki operating system. * This file is part of the Contiki operating system.
*/ */
/** /**
* \file * \file
* Erbium (Er) CoAP client example * Erbium (Er) CoAP client example
* \author * \author
* Matthias Kovatsch <kovatsch@inf.ethz.ch> * Matthias Kovatsch <kovatsch@inf.ethz.ch>
*/ */
#ifndef __ER_PLUGTEST_H__ #ifndef __ER_PLUGTEST_H__
#define __ER_PLUGTEST_H__ #define __ER_PLUGTEST_H__
#if !defined (CONTIKI_TARGET_NATIVE) #if !defined(CONTIKI_TARGET_NATIVE)
#warning "Should only be compiled for native!" #warning "Should only be compiled for native!"
#endif #endif
#define DEBUG DEBUG_PRINT #define DEBUG 0
#include "net/uip-debug.h" #if DEBUG
#include <stdio.h>
/* double expansion */ #define PRINTF(...) printf(__VA_ARGS__)
#define TO_STRING2(x) #x #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 TO_STRING(x) TO_STRING2(x) #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 MAX_PLUGFEST_PAYLOAD 64+1 /* +1 for the terminating zero, which is not transmitted */ #define PRINTF(...)
#define MAX_PLUGFEST_BODY 2048 #define PRINT6ADDR(addr)
#define CHUNKS_TOTAL 2012 #define PRINTLLADDR(addr)
#endif
#endif /* __ER_PLUGTEST_H__ */
/* double expansion */
#define TO_STRING2(x) # x
#define TO_STRING(x) TO_STRING2(x)
#define MAX_PLUGFEST_PAYLOAD 64 + 1 /* +1 for the terminating zero, which is not transmitted */
#define MAX_PLUGFEST_BODY 2048
#define CHUNKS_TOTAL 2012
#endif /* __ER_PLUGTEST_H__ */

184
examples/er-rest-example/project-conf.h Executable file → Normal file
View file

@ -1,92 +1,92 @@
/* /*
* Copyright (c) 2013, Institute for Pervasive Computing, ETH Zurich * Copyright (c) 2013, Institute for Pervasive Computing, ETH Zurich
* All rights reserved. * All rights reserved.
* *
* Redistribution and use in source and binary forms, with or without * Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions * modification, are permitted provided that the following conditions
* are met: * are met:
* 1. Redistributions of source code must retain the above copyright * 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer. * notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright * 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the * notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution. * documentation and/or other materials provided with the distribution.
* 3. Neither the name of the Institute nor the names of its contributors * 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 * may be used to endorse or promote products derived from this software
* without specific prior written permission. * without specific prior written permission.
* *
* THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * 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 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE. * SUCH DAMAGE.
* *
* This file is part of the Contiki operating system. * This file is part of the Contiki operating system.
*/ */
/** /**
* \file * \file
* Erbium (Er) example project configuration. * Erbium (Er) example project configuration.
* \author * \author
* Matthias Kovatsch <kovatsch@inf.ethz.ch> * Matthias Kovatsch <kovatsch@inf.ethz.ch>
*/ */
#ifndef __PROJECT_ERBIUM_CONF_H__ #ifndef __PROJECT_ERBIUM_CONF_H__
#define __PROJECT_ERBIUM_CONF_H__ #define __PROJECT_ERBIUM_CONF_H__
/* Custom channel and PAN ID configuration for your project. */ /* Custom channel and PAN ID configuration for your project. */
/* /*
#undef RF_CHANNEL #undef RF_CHANNEL
#define RF_CHANNEL 26 #define RF_CHANNEL 26
#undef IEEE802154_CONF_PANID #undef IEEE802154_CONF_PANID
#define IEEE802154_CONF_PANID 0xABCD #define IEEE802154_CONF_PANID 0xABCD
*/ */
/* IP buffer size must match all other hops, in particular the border router. */ /* IP buffer size must match all other hops, in particular the border router. */
/* /*
#undef UIP_CONF_BUFFER_SIZE #undef UIP_CONF_BUFFER_SIZE
#define UIP_CONF_BUFFER_SIZE 256 #define UIP_CONF_BUFFER_SIZE 256
*/ */
/* Disabling RDC for demo purposes. Core updates often require more memory. */ /* Disabling RDC for demo purposes. Core updates often require more memory. */
/* For projects, optimize memory and enable RDC again. */ /* For projects, optimize memory and enable RDC again. */
#undef NETSTACK_CONF_RDC #undef NETSTACK_CONF_RDC
#define NETSTACK_CONF_RDC nullrdc_driver #define NETSTACK_CONF_RDC nullrdc_driver
/* Disabling TCP on CoAP nodes. */ /* Disabling TCP on CoAP nodes. */
#undef UIP_CONF_TCP #undef UIP_CONF_TCP
#define UIP_CONF_TCP 0 #define UIP_CONF_TCP 0
/* Increase rpl-border-router IP-buffer when using more than 64. */ /* Increase rpl-border-router IP-buffer when using more than 64. */
#undef REST_MAX_CHUNK_SIZE #undef REST_MAX_CHUNK_SIZE
#define REST_MAX_CHUNK_SIZE 64 #define REST_MAX_CHUNK_SIZE 64
/* Estimate your header size, especially when using Proxy-Uri. */ /* Estimate your header size, especially when using Proxy-Uri. */
/* /*
#undef COAP_MAX_HEADER_SIZE #undef COAP_MAX_HEADER_SIZE
#define COAP_MAX_HEADER_SIZE 70 #define COAP_MAX_HEADER_SIZE 70
*/ */
/* Multiplies with chunk size, be aware of memory constraints. */ /* Multiplies with chunk size, be aware of memory constraints. */
#undef COAP_MAX_OPEN_TRANSACTIONS #undef COAP_MAX_OPEN_TRANSACTIONS
#define COAP_MAX_OPEN_TRANSACTIONS 4 #define COAP_MAX_OPEN_TRANSACTIONS 4
/* Must be <= open transactions, default is COAP_MAX_OPEN_TRANSACTIONS-1. */ /* Must be <= open transactions, default is COAP_MAX_OPEN_TRANSACTIONS-1. */
/* /*
#undef COAP_MAX_OBSERVERS #undef COAP_MAX_OBSERVERS
#define COAP_MAX_OBSERVERS 2 #define COAP_MAX_OBSERVERS 2
*/ */
/* Filtering .well-known/core per query can be disabled to save space. */ /* Filtering .well-known/core per query can be disabled to save space. */
#undef COAP_LINK_FORMAT_FILTERING #undef COAP_LINK_FORMAT_FILTERING
#define COAP_LINK_FORMAT_FILTERING 0 #define COAP_LINK_FORMAT_FILTERING 0
#undef COAP_PROXY_OPTION_PROCESSING #undef COAP_PROXY_OPTION_PROCESSING
#define COAP_PROXY_OPTION_PROCESSING 0 #define COAP_PROXY_OPTION_PROCESSING 0
#endif /* __PROJECT_ERBIUM_CONF_H__ */ #endif /* __PROJECT_ERBIUM_CONF_H__ */

163
examples/er-rest-example/resources/res-battery.c Executable file → Normal file
View file

@ -1,82 +1,81 @@
/* /*
* Copyright (c) 2013, Institute for Pervasive Computing, ETH Zurich * Copyright (c) 2013, Institute for Pervasive Computing, ETH Zurich
* All rights reserved. * All rights reserved.
* *
* Redistribution and use in source and binary forms, with or without * Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions * modification, are permitted provided that the following conditions
* are met: * are met:
* 1. Redistributions of source code must retain the above copyright * 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer. * notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright * 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the * notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution. * documentation and/or other materials provided with the distribution.
* 3. Neither the name of the Institute nor the names of its contributors * 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 * may be used to endorse or promote products derived from this software
* without specific prior written permission. * without specific prior written permission.
* *
* THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * 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 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE. * SUCH DAMAGE.
* *
* This file is part of the Contiki operating system. * This file is part of the Contiki operating system.
*/ */
/** /**
* \file * \file
* Example resource * Example resource
* \author * \author
* Matthias Kovatsch <kovatsch@inf.ethz.ch> * Matthias Kovatsch <kovatsch@inf.ethz.ch>
*/ */
#include "contiki.h" #include "contiki.h"
#if PLATFORM_HAS_BATTERY #if PLATFORM_HAS_BATTERY
#include <string.h> #include <string.h>
#include "rest-engine.h" #include "rest-engine.h"
#include "dev/battery-sensor.h" #include "dev/battery-sensor.h"
static void res_get_handler(void* request, void* response, uint8_t *buffer, uint16_t preferred_size, int32_t *offset); static void res_get_handler(void *request, void *response, uint8_t *buffer, uint16_t preferred_size, int32_t *offset);
/* A simple getter example. Returns the reading from light sensor with a simple etag */ /* A simple getter example. Returns the reading from light sensor with a simple etag */
RESOURCE(battery, RESOURCE(battery,
"title=\"Battery status\";rt=\"Battery\"", "title=\"Battery status\";rt=\"Battery\"",
res_get_handler, res_get_handler,
NULL, NULL,
NULL, NULL,
NULL); NULL);
static void static void
res_get_handler(void* request, void* response, uint8_t *buffer, uint16_t preferred_size, int32_t *offset) res_get_handler(void *request, void *response, uint8_t *buffer, uint16_t preferred_size, int32_t *offset)
{ {
int battery = battery_sensor.value(0); int battery = battery_sensor.value(0);
unsigned int accept = -1; unsigned int accept = -1;
REST.get_header_accept(request, &accept); REST.get_header_accept(request, &accept);
if(accept==-1 || accept==REST.type.TEXT_PLAIN) { if(accept == -1 || accept == REST.type.TEXT_PLAIN) {
REST.set_header_content_type(response, REST.type.TEXT_PLAIN); REST.set_header_content_type(response, REST.type.TEXT_PLAIN);
snprintf((char *)buffer, REST_MAX_CHUNK_SIZE, "%d", battery); snprintf((char *)buffer, REST_MAX_CHUNK_SIZE, "%d", battery);
REST.set_response_payload(response, (uint8_t *)buffer, strlen((char *)buffer)); REST.set_response_payload(response, (uint8_t *)buffer, strlen((char *)buffer));
} else if(accept==REST.type.APPLICATION_JSON) { } else if(accept == REST.type.APPLICATION_JSON) {
REST.set_header_content_type(response, REST.type.APPLICATION_JSON); REST.set_header_content_type(response, REST.type.APPLICATION_JSON);
snprintf((char *)buffer, REST_MAX_CHUNK_SIZE, "{'battery':%d}", battery); snprintf((char *)buffer, REST_MAX_CHUNK_SIZE, "{'battery':%d}", battery);
REST.set_response_payload(response, buffer, strlen((char *)buffer)); REST.set_response_payload(response, buffer, strlen((char *)buffer));
} else { } else {
REST.set_response_status(response, REST.status.NOT_ACCEPTABLE); REST.set_response_status(response, REST.status.NOT_ACCEPTABLE);
const char *msg = "Supporting content-types text/plain and application/json"; const char *msg = "Supporting content-types text/plain and application/json";
REST.set_response_payload(response, msg, strlen(msg)); REST.set_response_payload(response, msg, strlen(msg));
} }
} }
#endif /* PLATFORM_HAS_BATTERY */
#endif /* PLATFORM_HAS_BATTERY */

196
examples/er-rest-example/resources/res-chunks.c Executable file → Normal file
View file

@ -1,99 +1,97 @@
/* /*
* Copyright (c) 2013, Institute for Pervasive Computing, ETH Zurich * Copyright (c) 2013, Institute for Pervasive Computing, ETH Zurich
* All rights reserved. * All rights reserved.
* *
* Redistribution and use in source and binary forms, with or without * Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions * modification, are permitted provided that the following conditions
* are met: * are met:
* 1. Redistributions of source code must retain the above copyright * 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer. * notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright * 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the * notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution. * documentation and/or other materials provided with the distribution.
* 3. Neither the name of the Institute nor the names of its contributors * 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 * may be used to endorse or promote products derived from this software
* without specific prior written permission. * without specific prior written permission.
* *
* THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * 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 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE. * SUCH DAMAGE.
* *
* This file is part of the Contiki operating system. * This file is part of the Contiki operating system.
*/ */
/** /**
* \file * \file
* Example resource * Example resource
* \author * \author
* Matthias Kovatsch <kovatsch@inf.ethz.ch> * Matthias Kovatsch <kovatsch@inf.ethz.ch>
*/ */
#include <string.h> #include <string.h>
#include "rest-engine.h" #include "rest-engine.h"
static void res_get_handler(void* request, void* response, uint8_t *buffer, uint16_t preferred_size, int32_t *offset); static void res_get_handler(void *request, void *response, uint8_t *buffer, uint16_t preferred_size, int32_t *offset);
/* /*
* For data larger than REST_MAX_CHUNK_SIZE (e.g., when stored in flash) resources must be aware of the buffer limitation * For data larger than REST_MAX_CHUNK_SIZE (e.g., when stored in flash) resources must be aware of the buffer limitation
* and split their responses by themselves. To transfer the complete resource through a TCP stream or CoAP's blockwise transfer, * and split their responses by themselves. To transfer the complete resource through a TCP stream or CoAP's blockwise transfer,
* the byte offset where to continue is provided to the handler as int32_t pointer. * the byte offset where to continue is provided to the handler as int32_t pointer.
* These chunk-wise resources must set the offset value to its new position or -1 of the end is reached. * These chunk-wise resources must set the offset value to its new position or -1 of the end is reached.
* (The offset for CoAP's blockwise transfer can go up to 2'147'481'600 = ~2047 M for block size 2048 (reduced to 1024 in observe-03.) * (The offset for CoAP's blockwise transfer can go up to 2'147'481'600 = ~2047 M for block size 2048 (reduced to 1024 in observe-03.)
*/ */
RESOURCE(res_chunks, RESOURCE(res_chunks,
"title=\"Blockwise demo\";rt=\"Data\"", "title=\"Blockwise demo\";rt=\"Data\"",
res_get_handler, res_get_handler,
NULL, NULL,
NULL, NULL,
NULL); NULL);
#define CHUNKS_TOTAL 2050 #define CHUNKS_TOTAL 2050
static void static void
res_get_handler(void* request, void* response, uint8_t *buffer, uint16_t preferred_size, int32_t *offset) res_get_handler(void *request, void *response, uint8_t *buffer, uint16_t preferred_size, int32_t *offset)
{ {
int32_t strpos = 0; int32_t strpos = 0;
/* Check the offset for boundaries of the resource data. */ /* Check the offset for boundaries of the resource data. */
if(*offset>=CHUNKS_TOTAL) { if(*offset >= CHUNKS_TOTAL) {
REST.set_response_status(response, REST.status.BAD_OPTION); REST.set_response_status(response, REST.status.BAD_OPTION);
/* A block error message should not exceed the minimum block size (16). */ /* A block error message should not exceed the minimum block size (16). */
const char *error_msg = "BlockOutOfScope"; const char *error_msg = "BlockOutOfScope";
REST.set_response_payload(response, error_msg, strlen(error_msg)); REST.set_response_payload(response, error_msg, strlen(error_msg));
return; return;
} }
/* Generate data until reaching CHUNKS_TOTAL. */ /* Generate data until reaching CHUNKS_TOTAL. */
while (strpos<preferred_size) { while(strpos < preferred_size) {
strpos += snprintf((char *)buffer+strpos, preferred_size-strpos+1, "|%ld|", *offset); strpos += snprintf((char *)buffer + strpos, preferred_size - strpos + 1, "|%ld|", *offset);
} }
/* snprintf() does not adjust return value if truncated by size. */ /* snprintf() does not adjust return value if truncated by size. */
if(strpos > preferred_size) { if(strpos > preferred_size) {
strpos = preferred_size; strpos = preferred_size;
} /* Truncate if above CHUNKS_TOTAL bytes. */
}
/* Truncate if above CHUNKS_TOTAL bytes. */ if(*offset + (int32_t)strpos > CHUNKS_TOTAL) {
if(*offset+(int32_t)strpos > CHUNKS_TOTAL) { strpos = CHUNKS_TOTAL - *offset;
strpos = CHUNKS_TOTAL - *offset; }
} REST.set_response_payload(response, buffer, strpos);
REST.set_response_payload(response, buffer, strpos); /* IMPORTANT for chunk-wise resources: Signal chunk awareness to REST engine. */
*offset += strpos;
/* IMPORTANT for chunk-wise resources: Signal chunk awareness to REST engine. */
*offset += strpos; /* Signal end of resource representation. */
if(*offset >= CHUNKS_TOTAL) {
/* Signal end of resource representation. */ *offset = -1;
if(*offset>=CHUNKS_TOTAL) { }
*offset = -1; }
}
}

194
examples/er-rest-example/resources/res-event.c Executable file → Normal file
View file

@ -1,93 +1,101 @@
/* /*
* Copyright (c) 2013, Institute for Pervasive Computing, ETH Zurich * Copyright (c) 2013, Institute for Pervasive Computing, ETH Zurich
* All rights reserved. * All rights reserved.
* *
* Redistribution and use in source and binary forms, with or without * Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions * modification, are permitted provided that the following conditions
* are met: * are met:
* 1. Redistributions of source code must retain the above copyright * 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer. * notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright * 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the * notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution. * documentation and/or other materials provided with the distribution.
* 3. Neither the name of the Institute nor the names of its contributors * 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 * may be used to endorse or promote products derived from this software
* without specific prior written permission. * without specific prior written permission.
* *
* THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * 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 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE. * SUCH DAMAGE.
* *
* This file is part of the Contiki operating system. * This file is part of the Contiki operating system.
*/ */
/** /**
* \file * \file
* Example resource * Example resource
* \author * \author
* Matthias Kovatsch <kovatsch@inf.ethz.ch> * Matthias Kovatsch <kovatsch@inf.ethz.ch>
*/ */
#include <string.h> #include <string.h>
#include "rest-engine.h" #include "rest-engine.h"
#include "er-coap.h" #include "er-coap.h"
#define DEBUG DEBUG_NONE #define DEBUG 0
#include "net/uip-debug.h" #if DEBUG
#include <stdio.h>
static void res_get_handler(void* request, void* response, uint8_t *buffer, uint16_t preferred_size, int32_t *offset); #define PRINTF(...) printf(__VA_ARGS__)
static void res_event_handler(); #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
* Example for an event resource. #define PRINTF(...)
* Additionally takes a period parameter that defines the interval to call [name]_periodic_handler(). #define PRINT6ADDR(addr)
* A default post_handler takes care of subscriptions and manages a list of subscribers to notify. #define PRINTLLADDR(addr)
*/ #endif
EVENT_RESOURCE(res_event,
"title=\"Event demo\";obs", static void res_get_handler(void *request, void *response, uint8_t *buffer, uint16_t preferred_size, int32_t *offset);
res_get_handler, static void res_event_handler();
NULL,
NULL, /*
NULL, * Example for an event resource.
res_event_handler); * Additionally takes a period parameter that defines the interval to call [name]_periodic_handler().
* A default post_handler takes care of subscriptions and manages a list of subscribers to notify.
/* */
* Use local resource state that is accessed by res_get_handler() and altered by res_event_handler() or PUT or POST. EVENT_RESOURCE(res_event,
*/ "title=\"Event demo\";obs",
static int32_t event_counter = 0; res_get_handler,
NULL,
static void NULL,
res_get_handler(void* request, void* response, uint8_t *buffer, uint16_t preferred_size, int32_t *offset) NULL,
{ res_event_handler);
REST.set_header_content_type(response, REST.type.TEXT_PLAIN);
REST.set_response_payload(response, buffer, snprintf((char *)buffer, preferred_size, "EVENT %lu", event_counter)); /*
* Use local resource state that is accessed by res_get_handler() and altered by res_event_handler() or PUT or POST.
/* A post_handler that handles subscriptions/observing will be called for periodic resources by the framework. */ */
} static int32_t event_counter = 0;
/* static void
* Additionally, res_event_handler must be implemented for each EVENT_RESOURCE. res_get_handler(void *request, void *response, uint8_t *buffer, uint16_t preferred_size, int32_t *offset)
* It is called through <res_name>.trigger(), usually from the server process. {
*/ REST.set_header_content_type(response, REST.type.TEXT_PLAIN);
static void REST.set_response_payload(response, buffer, snprintf((char *)buffer, preferred_size, "EVENT %lu", event_counter));
res_event_handler()
{ /* A post_handler that handles subscriptions/observing will be called for periodic resources by the framework. */
/* Do the update triggered by the event here, e.g., sampling a sensor. */ }
++event_counter; /*
* Additionally, res_event_handler must be implemented for each EVENT_RESOURCE.
/* Usually a condition is defined under with subscribers are notified, e.g., event was above a threshold. */ * It is called through <res_name>.trigger(), usually from the server process.
if (1) { */
PRINTF("TICK %u for /%s\n", event_counter, res_event.url); static void
res_event_handler()
/* Notify the registered observers which will trigger the res_get_handler to create the response. */ {
REST.notify_subscribers(&res_event); /* Do the update triggered by the event here, e.g., sampling a sensor. */
} ++event_counter;
}
/* Usually a condition is defined under with subscribers are notified, e.g., event was above a threshold. */
if(1) {
PRINTF("TICK %u for /%s\n", event_counter, res_event.url);
/* Notify the registered observers which will trigger the res_get_handler to create the response. */
REST.notify_subscribers(&res_event);
}
}

160
examples/er-rest-example/resources/res-hello.c Executable file → Normal file
View file

@ -1,79 +1,81 @@
/* /*
* Copyright (c) 2013, Institute for Pervasive Computing, ETH Zurich * Copyright (c) 2013, Institute for Pervasive Computing, ETH Zurich
* All rights reserved. * All rights reserved.
* *
* Redistribution and use in source and binary forms, with or without * Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions * modification, are permitted provided that the following conditions
* are met: * are met:
* 1. Redistributions of source code must retain the above copyright * 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer. * notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright * 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the * notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution. * documentation and/or other materials provided with the distribution.
* 3. Neither the name of the Institute nor the names of its contributors * 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 * may be used to endorse or promote products derived from this software
* without specific prior written permission. * without specific prior written permission.
* *
* THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * 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 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE. * SUCH DAMAGE.
* *
* This file is part of the Contiki operating system. * This file is part of the Contiki operating system.
*/ */
/** /**
* \file * \file
* Example resource * Example resource
* \author * \author
* Matthias Kovatsch <kovatsch@inf.ethz.ch> * Matthias Kovatsch <kovatsch@inf.ethz.ch>
*/ */
#include <stdlib.h> #include <stdlib.h>
#include <string.h> #include <string.h>
#include "rest-engine.h" #include "rest-engine.h"
static void res_get_handler(void* request, void* response, uint8_t *buffer, uint16_t preferred_size, int32_t *offset); static void res_get_handler(void *request, void *response, uint8_t *buffer, uint16_t preferred_size, int32_t *offset);
/* /*
* A handler function named [resource name]_handler must be implemented for each RESOURCE. * A handler function named [resource name]_handler must be implemented for each RESOURCE.
* A buffer for the response payload is provided through the buffer pointer. Simple resources can ignore * A buffer for the response payload is provided through the buffer pointer. Simple resources can ignore
* preferred_size and offset, but must respect the REST_MAX_CHUNK_SIZE limit for the buffer. * preferred_size and offset, but must respect the REST_MAX_CHUNK_SIZE limit for the buffer.
* If a smaller block size is requested for CoAP, the REST framework automatically splits the data. * If a smaller block size is requested for CoAP, the REST framework automatically splits the data.
*/ */
RESOURCE(res_hello, RESOURCE(res_hello,
"title=\"Hello world: ?len=0..\";rt=\"Text\"", "title=\"Hello world: ?len=0..\";rt=\"Text\"",
res_get_handler, res_get_handler,
NULL, NULL,
NULL, NULL,
NULL); NULL);
static void static void
res_get_handler(void* request, void* response, uint8_t *buffer, uint16_t preferred_size, int32_t *offset) res_get_handler(void *request, void *response, uint8_t *buffer, uint16_t preferred_size, int32_t *offset)
{ {
const char *len = NULL; const char *len = NULL;
/* Some data that has the length up to REST_MAX_CHUNK_SIZE. For more, see the chunk resource. */ /* Some data that has the length up to REST_MAX_CHUNK_SIZE. For more, see the chunk resource. */
char const * const message = "Hello World! ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxy"; char const *const message = "Hello World! ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxy";
int length = 12; /* |<-------->| */ int length = 12; /* |<-------->| */
/* The query string can be retrieved by rest_get_query() or parsed for its key-value pairs. */ /* The query string can be retrieved by rest_get_query() or parsed for its key-value pairs. */
if(REST.get_query_variable(request, "len", &len)) { if(REST.get_query_variable(request, "len", &len)) {
length = atoi(len); length = atoi(len);
if(length<0) length = 0; if(length < 0) {
if(length>REST_MAX_CHUNK_SIZE) length = REST_MAX_CHUNK_SIZE; length = 0;
memcpy(buffer, message, length); }
} else { if(length > REST_MAX_CHUNK_SIZE) {
memcpy(buffer, message, length); length = REST_MAX_CHUNK_SIZE;
} }
memcpy(buffer, message, length);
REST.set_header_content_type(response, REST.type.TEXT_PLAIN); /* text/plain is the default, hence this option could be omitted. */ } else {
REST.set_header_etag(response, (uint8_t *) &length, 1); memcpy(buffer, message, length);
REST.set_response_payload(response, buffer, length); } REST.set_header_content_type(response, REST.type.TEXT_PLAIN); /* text/plain is the default, hence this option could be omitted. */
} REST.set_header_etag(response, (uint8_t *)&length, 1);
REST.set_response_payload(response, buffer, length);
}

212
examples/er-rest-example/resources/res-leds.c Executable file → Normal file
View file

@ -1,104 +1,108 @@
/* /*
* Copyright (c) 2013, Institute for Pervasive Computing, ETH Zurich * Copyright (c) 2013, Institute for Pervasive Computing, ETH Zurich
* All rights reserved. * All rights reserved.
* *
* Redistribution and use in source and binary forms, with or without * Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions * modification, are permitted provided that the following conditions
* are met: * are met:
* 1. Redistributions of source code must retain the above copyright * 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer. * notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright * 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the * notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution. * documentation and/or other materials provided with the distribution.
* 3. Neither the name of the Institute nor the names of its contributors * 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 * may be used to endorse or promote products derived from this software
* without specific prior written permission. * without specific prior written permission.
* *
* THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * 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 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE. * SUCH DAMAGE.
* *
* This file is part of the Contiki operating system. * This file is part of the Contiki operating system.
*/ */
/** /**
* \file * \file
* Example resource * Example resource
* \author * \author
* Matthias Kovatsch <kovatsch@inf.ethz.ch> * Matthias Kovatsch <kovatsch@inf.ethz.ch>
*/ */
#include "contiki.h" #include "contiki.h"
#if PLATFORM_HAS_LEDS #if PLATFORM_HAS_LEDS
#include <string.h> #include <string.h>
#include "rest-engine.h" #include "rest-engine.h"
#include "dev/leds.h" #include "dev/leds.h"
#define DEBUG DEBUG_NONE #define DEBUG 0
#include "net/uip-debug.h" #if DEBUG
#include <stdio.h>
static void res_post_put_handler(void* request, void* response, uint8_t *buffer, uint16_t preferred_size, int32_t *offset); #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])
/*A simple actuator example, depending on the color query parameter and post variable mode, corresponding led is activated or deactivated*/ #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])
RESOURCE(res_leds, #else
"title=\"LEDs: ?color=r|g|b, POST/PUT mode=on|off\";rt=\"Control\"", #define PRINTF(...)
NULL, #define PRINT6ADDR(addr)
res_post_put_handler, #define PRINTLLADDR(addr)
res_post_put_handler, #endif
NULL);
static void res_post_put_handler(void *request, void *response, uint8_t *buffer, uint16_t preferred_size, int32_t *offset);
static void
res_post_put_handler(void* request, void* response, uint8_t *buffer, uint16_t preferred_size, int32_t *offset) /*A simple actuator example, depending on the color query parameter and post variable mode, corresponding led is activated or deactivated*/
{ RESOURCE(res_leds,
size_t len = 0; "title=\"LEDs: ?color=r|g|b, POST/PUT mode=on|off\";rt=\"Control\"",
const char *color = NULL; NULL,
const char *mode = NULL; res_post_put_handler,
uint8_t led = 0; res_post_put_handler,
int success = 1; NULL);
if((len=REST.get_query_variable(request, "color", &color))) { static void
PRINTF("color %.*s\n", len, color); res_post_put_handler(void *request, void *response, uint8_t *buffer, uint16_t preferred_size, int32_t *offset)
{
if(strncmp(color, "r", len)==0) { size_t len = 0;
led = LEDS_RED; const char *color = NULL;
} else if(strncmp(color,"g", len)==0) { const char *mode = NULL;
led = LEDS_GREEN; uint8_t led = 0;
} else if(strncmp(color,"b", len)==0) { int success = 1;
led = LEDS_BLUE;
} else { if((len = REST.get_query_variable(request, "color", &color))) {
success = 0; PRINTF("color %.*s\n", len, color);
}
} else { if(strncmp(color, "r", len) == 0) {
success = 0; led = LEDS_RED;
} } else if(strncmp(color, "g", len) == 0) {
led = LEDS_GREEN;
if(success && (len=REST.get_post_variable(request, "mode", &mode))) { } else if(strncmp(color, "b", len) == 0) {
PRINTF("mode %s\n", mode); led = LEDS_BLUE;
} else {
if(strncmp(mode, "on", len)==0) { success = 0;
leds_on(led); }
} else if(strncmp(mode, "off", len)==0) { } else {
leds_off(led); success = 0;
} else { } if(success && (len = REST.get_post_variable(request, "mode", &mode))) {
success = 0; PRINTF("mode %s\n", mode);
}
} else { if(strncmp(mode, "on", len) == 0) {
success = 0; leds_on(led);
} } else if(strncmp(mode, "off", len) == 0) {
leds_off(led);
if(!success) { } else {
REST.set_response_status(response, REST.status.BAD_REQUEST); success = 0;
} }
} } else {
success = 0;
#endif /* PLATFORM_HAS_LEDS */ } if(!success) {
REST.set_response_status(response, REST.status.BAD_REQUEST);
}
}
#endif /* PLATFORM_HAS_LEDS */

175
examples/er-rest-example/resources/res-light.c Executable file → Normal file
View file

@ -1,88 +1,87 @@
/* /*
* Copyright (c) 2013, Institute for Pervasive Computing, ETH Zurich * Copyright (c) 2013, Institute for Pervasive Computing, ETH Zurich
* All rights reserved. * All rights reserved.
* *
* Redistribution and use in source and binary forms, with or without * Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions * modification, are permitted provided that the following conditions
* are met: * are met:
* 1. Redistributions of source code must retain the above copyright * 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer. * notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright * 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the * notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution. * documentation and/or other materials provided with the distribution.
* 3. Neither the name of the Institute nor the names of its contributors * 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 * may be used to endorse or promote products derived from this software
* without specific prior written permission. * without specific prior written permission.
* *
* THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * 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 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE. * SUCH DAMAGE.
* *
* This file is part of the Contiki operating system. * This file is part of the Contiki operating system.
*/ */
/** /**
* \file * \file
* Example resource * Example resource
* \author * \author
* Matthias Kovatsch <kovatsch@inf.ethz.ch> * Matthias Kovatsch <kovatsch@inf.ethz.ch>
*/ */
#include "contiki.h" #include "contiki.h"
#if PLATFORM_HAS_LIGHT #if PLATFORM_HAS_LIGHT
#include <string.h> #include <string.h>
#include "rest-engine.h" #include "rest-engine.h"
#include "dev/light-sensor.h" #include "dev/light-sensor.h"
static void res_get_handler(void* request, void* response, uint8_t *buffer, uint16_t preferred_size, int32_t *offset); static void res_get_handler(void *request, void *response, uint8_t *buffer, uint16_t preferred_size, int32_t *offset);
/* A simple getter example. Returns the reading from light sensor with a simple etag */ /* A simple getter example. Returns the reading from light sensor with a simple etag */
RESOURCE(res_light, RESOURCE(res_light,
"title=\"Photosynthetic and solar light (supports JSON)\";rt=\"LightSensor\"", "title=\"Photosynthetic and solar light (supports JSON)\";rt=\"LightSensor\"",
res_get_handler, res_get_handler,
NULL, NULL,
NULL, NULL,
NULL); NULL);
static void static void
res_get_handler(void* request, void* response, uint8_t *buffer, uint16_t preferred_size, int32_t *offset) res_get_handler(void *request, void *response, uint8_t *buffer, uint16_t preferred_size, int32_t *offset)
{ {
uint16_t light_photosynthetic = light_sensor.value(LIGHT_SENSOR_PHOTOSYNTHETIC); uint16_t light_photosynthetic = light_sensor.value(LIGHT_SENSOR_PHOTOSYNTHETIC);
uint16_t light_solar = light_sensor.value(LIGHT_SENSOR_TOTAL_SOLAR); uint16_t light_solar = light_sensor.value(LIGHT_SENSOR_TOTAL_SOLAR);
unsigned int accept = -1; unsigned int accept = -1;
REST.get_header_accept(request, &accept); REST.get_header_accept(request, &accept);
if(accept==-1 || accept==REST.type.TEXT_PLAIN) { if(accept == -1 || accept == REST.type.TEXT_PLAIN) {
REST.set_header_content_type(response, REST.type.TEXT_PLAIN); REST.set_header_content_type(response, REST.type.TEXT_PLAIN);
snprintf((char *)buffer, REST_MAX_CHUNK_SIZE, "%u;%u", light_photosynthetic, light_solar); snprintf((char *)buffer, REST_MAX_CHUNK_SIZE, "%u;%u", light_photosynthetic, light_solar);
REST.set_response_payload(response, (uint8_t *)buffer, strlen((char *)buffer)); REST.set_response_payload(response, (uint8_t *)buffer, strlen((char *)buffer));
} else if(accept==REST.type.APPLICATION_XML) { } else if(accept == REST.type.APPLICATION_XML) {
REST.set_header_content_type(response, REST.type.APPLICATION_XML); REST.set_header_content_type(response, REST.type.APPLICATION_XML);
snprintf((char *)buffer, REST_MAX_CHUNK_SIZE, "<light photosynthetic=\"%u\" solar=\"%u\"/>", light_photosynthetic, light_solar); snprintf((char *)buffer, REST_MAX_CHUNK_SIZE, "<light photosynthetic=\"%u\" solar=\"%u\"/>", light_photosynthetic, light_solar);
REST.set_response_payload(response, buffer, strlen((char *)buffer)); REST.set_response_payload(response, buffer, strlen((char *)buffer));
} else if(accept==REST.type.APPLICATION_JSON) { } else if(accept == REST.type.APPLICATION_JSON) {
REST.set_header_content_type(response, REST.type.APPLICATION_JSON); REST.set_header_content_type(response, REST.type.APPLICATION_JSON);
snprintf((char *)buffer, REST_MAX_CHUNK_SIZE, "{'light':{'photosynthetic':%u,'solar':%u}}", light_photosynthetic, light_solar); snprintf((char *)buffer, REST_MAX_CHUNK_SIZE, "{'light':{'photosynthetic':%u,'solar':%u}}", light_photosynthetic, light_solar);
REST.set_response_payload(response, buffer, strlen((char *)buffer)); REST.set_response_payload(response, buffer, strlen((char *)buffer));
} else { } else {
REST.set_response_status(response, REST.status.NOT_ACCEPTABLE); REST.set_response_status(response, REST.status.NOT_ACCEPTABLE);
const char *msg = "Supporting content-types text/plain, application/xml, and application/json"; const char *msg = "Supporting content-types text/plain, application/xml, and application/json";
REST.set_response_payload(response, msg, strlen(msg)); REST.set_response_payload(response, msg, strlen(msg));
} }
} }
#endif /* PLATFORM_HAS_LIGHT */
#endif /* PLATFORM_HAS_LIGHT */

354
examples/er-rest-example/resources/res-mirror.c Executable file → Normal file
View file

@ -1,177 +1,177 @@
/* /*
* Copyright (c) 2013, Institute for Pervasive Computing, ETH Zurich * Copyright (c) 2013, Institute for Pervasive Computing, ETH Zurich
* All rights reserved. * All rights reserved.
* *
* Redistribution and use in source and binary forms, with or without * Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions * modification, are permitted provided that the following conditions
* are met: * are met:
* 1. Redistributions of source code must retain the above copyright * 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer. * notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright * 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the * notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution. * documentation and/or other materials provided with the distribution.
* 3. Neither the name of the Institute nor the names of its contributors * 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 * may be used to endorse or promote products derived from this software
* without specific prior written permission. * without specific prior written permission.
* *
* THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * 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 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE. * SUCH DAMAGE.
* *
* This file is part of the Contiki operating system. * This file is part of the Contiki operating system.
*/ */
/** /**
* \file * \file
* Example resource * Example resource
* \author * \author
* Matthias Kovatsch <kovatsch@inf.ethz.ch> * Matthias Kovatsch <kovatsch@inf.ethz.ch>
*/ */
#include <string.h> #include <string.h>
#include "rest-engine.h" #include "rest-engine.h"
#include "er-coap.h" #include "er-coap.h"
#define DEBUG DEBUG_NONE #define DEBUG 0
#include "net/uip-debug.h" #if DEBUG
#include <stdio.h>
static void res_any_handler(void* request, void* response, uint8_t *buffer, uint16_t preferred_size, int32_t *offset); #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])
/* This resource mirrors the incoming request. It shows how to access the options and how to set them for the response. */ #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])
RESOURCE(res_mirror, #else
"title=\"Returns your decoded message\";rt=\"Debug\"", #define PRINTF(...)
res_any_handler, #define PRINT6ADDR(addr)
res_any_handler, #define PRINTLLADDR(addr)
res_any_handler, #endif
res_any_handler);
static void res_any_handler(void *request, void *response, uint8_t *buffer, uint16_t preferred_size, int32_t *offset);
static void
res_any_handler(void* request, void* response, uint8_t *buffer, uint16_t preferred_size, int32_t *offset) /* This resource mirrors the incoming request. It shows how to access the options and how to set them for the response. */
{ RESOURCE(res_mirror,
/* The ETag and Token is copied to the header. */ "title=\"Returns your decoded message\";rt=\"Debug\"",
uint8_t opaque[] = {0x0A, 0xBC, 0xDE}; res_any_handler,
res_any_handler,
/* Strings are not copied, so use static string buffers or strings in .text memory (char *str = "string in .text";). */ res_any_handler,
static char location[] = {'/','f','/','a','?','k','&','e', 0}; res_any_handler);
/* No default my be assumed for the Content-Format. (Unsigned -1 means all bits set.) */ static void
unsigned int content_format = -1; res_any_handler(void *request, void *response, uint8_t *buffer, uint16_t preferred_size, int32_t *offset)
{
/* The other getters copy the value (or string/array pointer) to the given pointers and return 1 for success or the length of strings/arrays. */ /* The ETag and Token is copied to the header. */
uint32_t longint = 0; uint8_t opaque[] = { 0x0A, 0xBC, 0xDE };
const char *str = NULL;
const uint8_t *bytes = NULL; /* Strings are not copied, so use static string buffers or strings in .text memory (char *str = "string in .text";). */
uint32_t block_num = 0; static char location[] = { '/', 'f', '/', 'a', '?', 'k', '&', 'e', 0 };
uint8_t block_more = 0;
uint16_t block_size = 0; /* No default my be assumed for the Content-Format. (Unsigned -1 means all bits set.) */
int len = 0; unsigned int content_format = -1;
/* Mirror the received header options in the response payload. Unsupported getters (e.g., rest_get_header_observe() with HTTP) will return 0. */ /* The other getters copy the value (or string/array pointer) to the given pointers and return 1 for success or the length of strings/arrays. */
uint32_t longint = 0;
int strpos = 0; const char *str = NULL;
/* snprintf() counts the terminating '\0' to the size parameter. const uint8_t *bytes = NULL;
* The additional byte is taken care of by allocating REST_MAX_CHUNK_SIZE+1 bytes in the REST framework. uint32_t block_num = 0;
* Add +1 to fill the complete buffer, as the payload does not need a terminating '\0'. */ uint8_t block_more = 0;
if(REST.get_header_content_type(request, &content_format)) { uint16_t block_size = 0;
strpos += snprintf((char *)buffer, REST_MAX_CHUNK_SIZE+1, "CF %u\n", content_format); int len = 0;
}
if(strpos<=REST_MAX_CHUNK_SIZE && (len = REST.get_header_accept(request, &content_format))) { /* Mirror the received header options in the response payload. Unsupported getters (e.g., rest_get_header_observe() with HTTP) will return 0. */
strpos += snprintf((char *)buffer+strpos, REST_MAX_CHUNK_SIZE-strpos+1, "Ac %u\n", content_format);
} int strpos = 0;
/* snprintf() counts the terminating '\0' to the size parameter.
/* Some getters such as for ETag or Location are omitted, as these options should not appear in a request. * The additional byte is taken care of by allocating REST_MAX_CHUNK_SIZE+1 bytes in the REST framework.
* Max-Age might appear in HTTP requests or used for special purposes in CoAP. */ * Add +1 to fill the complete buffer, as the payload does not need a terminating '\0'. */
if(strpos<=REST_MAX_CHUNK_SIZE && REST.get_header_max_age(request, &longint)) { if(REST.get_header_content_type(request, &content_format)) {
strpos += snprintf((char *)buffer+strpos, REST_MAX_CHUNK_SIZE-strpos+1, "MA %lu\n", longint); strpos += snprintf((char *)buffer, REST_MAX_CHUNK_SIZE + 1, "CF %u\n", content_format);
} }
/* For HTTP this is the Length option, for CoAP it is the Size option. */ if(strpos <= REST_MAX_CHUNK_SIZE && (len = REST.get_header_accept(request, &content_format))) {
if(strpos<=REST_MAX_CHUNK_SIZE && REST.get_header_length(request, &longint)) { strpos += snprintf((char *)buffer + strpos, REST_MAX_CHUNK_SIZE - strpos + 1, "Ac %u\n", content_format);
strpos += snprintf((char *)buffer+strpos, REST_MAX_CHUNK_SIZE-strpos+1, "SZ %lu\n", longint); /* Some getters such as for ETag or Location are omitted, as these options should not appear in a request.
} * Max-Age might appear in HTTP requests or used for special purposes in CoAP. */
}
if(strpos<=REST_MAX_CHUNK_SIZE && (len = REST.get_header_host(request, &str))) { if(strpos <= REST_MAX_CHUNK_SIZE && REST.get_header_max_age(request, &longint)) {
strpos += snprintf((char *)buffer+strpos, REST_MAX_CHUNK_SIZE-strpos+1, "UH %.*s\n", len, str); strpos += snprintf((char *)buffer + strpos, REST_MAX_CHUNK_SIZE - strpos + 1, "MA %lu\n", longint);
} /* For HTTP this is the Length option, for CoAP it is the Size option. */
if(strpos<=REST_MAX_CHUNK_SIZE && (len = REST.get_url(request, &str))) { }
strpos += snprintf((char *)buffer+strpos, REST_MAX_CHUNK_SIZE-strpos+1, "UP %.*s\n", len, str); if(strpos <= REST_MAX_CHUNK_SIZE && REST.get_header_length(request, &longint)) {
} strpos += snprintf((char *)buffer + strpos, REST_MAX_CHUNK_SIZE - strpos + 1, "SZ %lu\n", longint);
if(strpos<=REST_MAX_CHUNK_SIZE && (len = REST.get_query(request, &str))) { }
strpos += snprintf((char *)buffer+strpos, REST_MAX_CHUNK_SIZE-strpos+1, "UQ %.*s\n", len, str); if(strpos <= REST_MAX_CHUNK_SIZE && (len = REST.get_header_host(request, &str))) {
} strpos += snprintf((char *)buffer + strpos, REST_MAX_CHUNK_SIZE - strpos + 1, "UH %.*s\n", len, str);
}
/* Undefined request options for debugging: actions not required for normal RESTful Web service. */ if(strpos <= REST_MAX_CHUNK_SIZE && (len = REST.get_url(request, &str))) {
if(strpos<=REST_MAX_CHUNK_SIZE && (len = coap_get_header_location_path(request, &str))) { strpos += snprintf((char *)buffer + strpos, REST_MAX_CHUNK_SIZE - strpos + 1, "UP %.*s\n", len, str);
strpos += snprintf((char *)buffer+strpos, REST_MAX_CHUNK_SIZE-strpos+1, "LP %.*s\n", len, str); }
} if(strpos <= REST_MAX_CHUNK_SIZE && (len = REST.get_query(request, &str))) {
if(strpos<=REST_MAX_CHUNK_SIZE && (len = coap_get_header_location_query(request, &str))) { strpos += snprintf((char *)buffer + strpos, REST_MAX_CHUNK_SIZE - strpos + 1, "UQ %.*s\n", len, str);
strpos += snprintf((char *)buffer+strpos, REST_MAX_CHUNK_SIZE-strpos+1, "LQ %.*s\n", len, str); /* Undefined request options for debugging: actions not required for normal RESTful Web service. */
} }
if(strpos <= REST_MAX_CHUNK_SIZE && (len = coap_get_header_location_path(request, &str))) {
/* CoAP-specific example: actions not required for normal RESTful Web service. */ strpos += snprintf((char *)buffer + strpos, REST_MAX_CHUNK_SIZE - strpos + 1, "LP %.*s\n", len, str);
coap_packet_t *const coap_pkt = (coap_packet_t *) request; }
if(strpos <= REST_MAX_CHUNK_SIZE && (len = coap_get_header_location_query(request, &str))) {
if(strpos<=REST_MAX_CHUNK_SIZE && coap_pkt->token_len>0) { strpos += snprintf((char *)buffer + strpos, REST_MAX_CHUNK_SIZE - strpos + 1, "LQ %.*s\n", len, str);
strpos += snprintf((char *)buffer+strpos, REST_MAX_CHUNK_SIZE-strpos+1, "To 0x"); /* CoAP-specific example: actions not required for normal RESTful Web service. */
int index = 0; }
for(index = 0; index<coap_pkt->token_len; ++index) { coap_packet_t *const coap_pkt = (coap_packet_t *)request;
strpos += snprintf((char *)buffer+strpos, REST_MAX_CHUNK_SIZE-strpos+1, "%02X", coap_pkt->token[index]);
} if(strpos <= REST_MAX_CHUNK_SIZE && coap_pkt->token_len > 0) {
strpos += snprintf((char *)buffer+strpos, REST_MAX_CHUNK_SIZE-strpos+1, "\n"); strpos += snprintf((char *)buffer + strpos, REST_MAX_CHUNK_SIZE - strpos + 1, "To 0x");
} int index = 0;
for(index = 0; index < coap_pkt->token_len; ++index) {
if(strpos<=REST_MAX_CHUNK_SIZE && IS_OPTION(coap_pkt, COAP_OPTION_OBSERVE)) { strpos += snprintf((char *)buffer + strpos, REST_MAX_CHUNK_SIZE - strpos + 1, "%02X", coap_pkt->token[index]);
strpos += snprintf((char *)buffer+strpos, REST_MAX_CHUNK_SIZE-strpos+1, "Ob %lu\n", coap_pkt->observe); }
} strpos += snprintf((char *)buffer + strpos, REST_MAX_CHUNK_SIZE - strpos + 1, "\n");
if(strpos<=REST_MAX_CHUNK_SIZE && IS_OPTION(coap_pkt, COAP_OPTION_ETAG)) { }
strpos += snprintf((char *)buffer+strpos, REST_MAX_CHUNK_SIZE-strpos+1, "ET 0x");
int index = 0; if(strpos <= REST_MAX_CHUNK_SIZE && IS_OPTION(coap_pkt, COAP_OPTION_OBSERVE)) {
for(index = 0; index<coap_pkt->etag_len; ++index) { strpos += snprintf((char *)buffer + strpos, REST_MAX_CHUNK_SIZE - strpos + 1, "Ob %lu\n", coap_pkt->observe);
strpos += snprintf((char *)buffer+strpos, REST_MAX_CHUNK_SIZE-strpos+1, "%02X", coap_pkt->etag[index]); }
} if(strpos <= REST_MAX_CHUNK_SIZE && IS_OPTION(coap_pkt, COAP_OPTION_ETAG)) {
strpos += snprintf((char *)buffer+strpos, REST_MAX_CHUNK_SIZE-strpos+1, "\n"); strpos += snprintf((char *)buffer + strpos, REST_MAX_CHUNK_SIZE - strpos + 1, "ET 0x");
} int index = 0;
if(strpos<=REST_MAX_CHUNK_SIZE && coap_get_header_block2(request, &block_num, &block_more, &block_size, NULL)) { /* This getter allows NULL pointers to get only a subset of the block parameters. */ for(index = 0; index < coap_pkt->etag_len; ++index) {
strpos += snprintf((char *)buffer+strpos, REST_MAX_CHUNK_SIZE-strpos+1, "B2 %lu%s (%u)\n", block_num, block_more ? "+" : "", block_size); strpos += snprintf((char *)buffer + strpos, REST_MAX_CHUNK_SIZE - strpos + 1, "%02X", coap_pkt->etag[index]);
} }
if(strpos<=REST_MAX_CHUNK_SIZE && coap_get_header_block1(request, &block_num, &block_more, &block_size, NULL)) { strpos += snprintf((char *)buffer + strpos, REST_MAX_CHUNK_SIZE - strpos + 1, "\n");
strpos += snprintf((char *)buffer+strpos, REST_MAX_CHUNK_SIZE-strpos+1, "B1 %lu%s (%u)\n", block_num, block_more ? "+" : "", block_size); }
} if(strpos <= REST_MAX_CHUNK_SIZE && coap_get_header_block2(request, &block_num, &block_more, &block_size, NULL)) { /* This getter allows NULL pointers to get only a subset of the block parameters. */
strpos += snprintf((char *)buffer + strpos, REST_MAX_CHUNK_SIZE - strpos + 1, "B2 %lu%s (%u)\n", block_num, block_more ? "+" : "", block_size);
}
if(strpos<=REST_MAX_CHUNK_SIZE && (len = REST.get_request_payload(request, &bytes))) { if(strpos <= REST_MAX_CHUNK_SIZE && coap_get_header_block1(request, &block_num, &block_more, &block_size, NULL)) {
strpos += snprintf((char *)buffer+strpos, REST_MAX_CHUNK_SIZE-strpos+1, "%.*s", len, bytes); strpos += snprintf((char *)buffer + strpos, REST_MAX_CHUNK_SIZE - strpos + 1, "B1 %lu%s (%u)\n", block_num, block_more ? "+" : "", block_size);
} }
if(strpos <= REST_MAX_CHUNK_SIZE && (len = REST.get_request_payload(request, &bytes))) {
strpos += snprintf((char *)buffer + strpos, REST_MAX_CHUNK_SIZE - strpos + 1, "%.*s", len, bytes);
if(strpos >= REST_MAX_CHUNK_SIZE) { }
buffer[REST_MAX_CHUNK_SIZE-1] = 0xBB; /* '»' to indicate truncation */ if(strpos >= REST_MAX_CHUNK_SIZE) {
} buffer[REST_MAX_CHUNK_SIZE - 1] = 0xBB; /* '»' to indicate truncation */
}
REST.set_response_payload(response, buffer, strpos); REST.set_response_payload(response, buffer, strpos);
PRINTF("/mirror options received: %s\n", buffer); PRINTF("/mirror options received: %s\n", buffer);
/* Set dummy header options for response. Like getters, some setters are not implemented for HTTP and have no effect. */ /* Set dummy header options for response. Like getters, some setters are not implemented for HTTP and have no effect. */
REST.set_header_content_type(response, REST.type.TEXT_PLAIN); REST.set_header_content_type(response, REST.type.TEXT_PLAIN);
REST.set_header_max_age(response, 17); /* For HTTP, browsers will not re-request the page for 17 seconds. */ REST.set_header_max_age(response, 17); /* For HTTP, browsers will not re-request the page for 17 seconds. */
REST.set_header_etag(response, opaque, 2); REST.set_header_etag(response, opaque, 2);
REST.set_header_location(response, location); /* Initial slash is omitted by framework */ REST.set_header_location(response, location); /* Initial slash is omitted by framework */
REST.set_header_length(response, strpos); /* For HTTP, browsers will not re-request the page for 10 seconds. CoAP action depends on the client. */ REST.set_header_length(response, strpos); /* For HTTP, browsers will not re-request the page for 10 seconds. CoAP action depends on the client. */
/* CoAP-specific example: actions not required for normal RESTful Web service. */ /* CoAP-specific example: actions not required for normal RESTful Web service. */
coap_set_header_uri_host(response, "tiki"); coap_set_header_uri_host(response, "tiki");
coap_set_header_observe(response, 10); coap_set_header_observe(response, 10);
coap_set_header_proxy_uri(response, "ftp://x"); coap_set_header_proxy_uri(response, "ftp://x");
coap_set_header_block2(response, 42, 0, 64); /* The block option might be overwritten by the framework when blockwise transfer is requested. */ coap_set_header_block2(response, 42, 0, 64); /* The block option might be overwritten by the framework when blockwise transfer is requested. */
coap_set_header_block1(response, 23, 0, 16); coap_set_header_block1(response, 23, 0, 16);
coap_set_header_accept(response, TEXT_PLAIN); coap_set_header_accept(response, TEXT_PLAIN);
coap_set_header_if_none_match(response); coap_set_header_if_none_match(response);
} }

161
examples/er-rest-example/resources/res-plugtest-create1.c Executable file → Normal file
View file

@ -1,81 +1,80 @@
/* /*
* Copyright (c) 2013, Institute for Pervasive Computing, ETH Zurich * Copyright (c) 2013, Institute for Pervasive Computing, ETH Zurich
* All rights reserved. * All rights reserved.
* *
* Redistribution and use in source and binary forms, with or without * Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions * modification, are permitted provided that the following conditions
* are met: * are met:
* 1. Redistributions of source code must retain the above copyright * 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer. * notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright * 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the * notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution. * documentation and/or other materials provided with the distribution.
* 3. Neither the name of the Institute nor the names of its contributors * 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 * may be used to endorse or promote products derived from this software
* without specific prior written permission. * without specific prior written permission.
* *
* THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * 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 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE. * SUCH DAMAGE.
* *
* This file is part of the Contiki operating system. * This file is part of the Contiki operating system.
*/ */
/** /**
* \file * \file
* ETSI Plugtest resource * ETSI Plugtest resource
* \author * \author
* Matthias Kovatsch <kovatsch@inf.ethz.ch> * Matthias Kovatsch <kovatsch@inf.ethz.ch>
*/ */
#include <string.h> #include <string.h>
#include "rest-engine.h" #include "rest-engine.h"
#include "er-coap.h" #include "er-coap.h"
#include "er-plugtest.h" #include "er-plugtest.h"
static void res_put_handler(void* request, void* response, uint8_t *buffer, uint16_t preferred_size, int32_t *offset); static void res_put_handler(void *request, void *response, uint8_t *buffer, uint16_t preferred_size, int32_t *offset);
static void res_delete_handler(void* request, void* response, uint8_t *buffer, uint16_t preferred_size, int32_t *offset); static void res_delete_handler(void *request, void *response, uint8_t *buffer, uint16_t preferred_size, int32_t *offset);
RESOURCE(res_plugtest_create1, RESOURCE(res_plugtest_create1,
"title=\"Creates on PUT\"", "title=\"Creates on PUT\"",
NULL, NULL,
NULL, NULL,
res_put_handler, res_put_handler,
res_delete_handler); res_delete_handler);
static uint8_t create1_exists = 0; static uint8_t create1_exists = 0;
static void static void
res_put_handler(void* request, void* response, uint8_t *buffer, uint16_t preferred_size, int32_t *offset) res_put_handler(void *request, void *response, uint8_t *buffer, uint16_t preferred_size, int32_t *offset)
{ {
PRINTF("/create1 PUT"); PRINTF("/create1 PUT");
if(coap_get_header_if_none_match(request)) { if(coap_get_header_if_none_match(request)) {
if(!create1_exists) { if(!create1_exists) {
REST.set_response_status(response, REST.status.CREATED); REST.set_response_status(response, REST.status.CREATED);
create1_exists = 1; create1_exists = 1;
} else { } else {
REST.set_response_status(response, PRECONDITION_FAILED_4_12); REST.set_response_status(response, PRECONDITION_FAILED_4_12);
} }
} else { } else {
REST.set_response_status(response, REST.status.CHANGED); REST.set_response_status(response, REST.status.CHANGED);
} }
} }
static void
static void res_delete_handler(void *request, void *response, uint8_t *buffer, uint16_t preferred_size, int32_t *offset)
res_delete_handler(void* request, void* response, uint8_t *buffer, uint16_t preferred_size, int32_t *offset) {
{ PRINTF("/create1 DELETE ");
PRINTF("/create1 DELETE "); REST.set_response_status(response, REST.status.DELETED);
REST.set_response_status(response, REST.status.DELETED);
create1_exists = 0;
create1_exists = 0; }
}

120
examples/er-rest-example/resources/res-plugtest-create2.c Executable file → Normal file
View file

@ -1,60 +1,60 @@
/* /*
* Copyright (c) 2013, Institute for Pervasive Computing, ETH Zurich * Copyright (c) 2013, Institute for Pervasive Computing, ETH Zurich
* All rights reserved. * All rights reserved.
* *
* Redistribution and use in source and binary forms, with or without * Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions * modification, are permitted provided that the following conditions
* are met: * are met:
* 1. Redistributions of source code must retain the above copyright * 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer. * notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright * 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the * notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution. * documentation and/or other materials provided with the distribution.
* 3. Neither the name of the Institute nor the names of its contributors * 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 * may be used to endorse or promote products derived from this software
* without specific prior written permission. * without specific prior written permission.
* *
* THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * 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 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE. * SUCH DAMAGE.
* *
* This file is part of the Contiki operating system. * This file is part of the Contiki operating system.
*/ */
/** /**
* \file * \file
* ETSI Plugtest resource * ETSI Plugtest resource
* \author * \author
* Matthias Kovatsch <kovatsch@inf.ethz.ch> * Matthias Kovatsch <kovatsch@inf.ethz.ch>
*/ */
#include <string.h> #include <string.h>
#include "rest-engine.h" #include "rest-engine.h"
#include "er-coap.h" #include "er-coap.h"
#include "er-plugtest.h" #include "er-plugtest.h"
static void res_post_handler(void* request, void* response, uint8_t *buffer, uint16_t preferred_size, int32_t *offset); static void res_post_handler(void *request, void *response, uint8_t *buffer, uint16_t preferred_size, int32_t *offset);
RESOURCE(res_plugtest_create2, RESOURCE(res_plugtest_create2,
"title=\"Creates on POST\"", "title=\"Creates on POST\"",
NULL, NULL,
res_post_handler, res_post_handler,
NULL, NULL,
NULL); NULL);
static void static void
res_post_handler(void* request, void* response, uint8_t *buffer, uint16_t preferred_size, int32_t *offset) res_post_handler(void *request, void *response, uint8_t *buffer, uint16_t preferred_size, int32_t *offset)
{ {
PRINTF("/create2 "); PRINTF("/create2 ");
REST.set_response_status(response, REST.status.CREATED); REST.set_response_status(response, REST.status.CREATED);
REST.set_header_location(response, "/location1/location2/location3"); REST.set_header_location(response, "/location1/location2/location3");
} }

161
examples/er-rest-example/resources/res-plugtest-create3.c Executable file → Normal file
View file

@ -1,81 +1,80 @@
/* /*
* Copyright (c) 2013, Institute for Pervasive Computing, ETH Zurich * Copyright (c) 2013, Institute for Pervasive Computing, ETH Zurich
* All rights reserved. * All rights reserved.
* *
* Redistribution and use in source and binary forms, with or without * Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions * modification, are permitted provided that the following conditions
* are met: * are met:
* 1. Redistributions of source code must retain the above copyright * 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer. * notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright * 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the * notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution. * documentation and/or other materials provided with the distribution.
* 3. Neither the name of the Institute nor the names of its contributors * 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 * may be used to endorse or promote products derived from this software
* without specific prior written permission. * without specific prior written permission.
* *
* THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * 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 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE. * SUCH DAMAGE.
* *
* This file is part of the Contiki operating system. * This file is part of the Contiki operating system.
*/ */
/** /**
* \file * \file
* ETSI Plugtest resource * ETSI Plugtest resource
* \author * \author
* Matthias Kovatsch <kovatsch@inf.ethz.ch> * Matthias Kovatsch <kovatsch@inf.ethz.ch>
*/ */
#include <string.h> #include <string.h>
#include "rest-engine.h" #include "rest-engine.h"
#include "er-coap.h" #include "er-coap.h"
#include "er-plugtest.h" #include "er-plugtest.h"
static void res_put_handler(void* request, void* response, uint8_t *buffer, uint16_t preferred_size, int32_t *offset); static void res_put_handler(void *request, void *response, uint8_t *buffer, uint16_t preferred_size, int32_t *offset);
static void res_delete_handler(void* request, void* response, uint8_t *buffer, uint16_t preferred_size, int32_t *offset); static void res_delete_handler(void *request, void *response, uint8_t *buffer, uint16_t preferred_size, int32_t *offset);
RESOURCE(res_plugtest_create3, RESOURCE(res_plugtest_create3,
"title=\"Default test resource\"", "title=\"Default test resource\"",
NULL, NULL,
NULL, NULL,
res_put_handler, res_put_handler,
res_delete_handler); res_delete_handler);
static uint8_t create3_exists = 0; static uint8_t create3_exists = 0;
static void static void
res_put_handler(void* request, void* response, uint8_t *buffer, uint16_t preferred_size, int32_t *offset) res_put_handler(void *request, void *response, uint8_t *buffer, uint16_t preferred_size, int32_t *offset)
{ {
PRINTF("/create3 PUT "); PRINTF("/create3 PUT ");
if(coap_get_header_if_none_match(request)) { if(coap_get_header_if_none_match(request)) {
if(!create3_exists) { if(!create3_exists) {
REST.set_response_status(response, REST.status.CREATED); REST.set_response_status(response, REST.status.CREATED);
create3_exists = 1; create3_exists = 1;
} else { } else {
REST.set_response_status(response, PRECONDITION_FAILED_4_12); REST.set_response_status(response, PRECONDITION_FAILED_4_12);
} }
} else { } else {
REST.set_response_status(response, REST.status.CHANGED); REST.set_response_status(response, REST.status.CHANGED);
} }
} }
static void
static void res_delete_handler(void *request, void *response, uint8_t *buffer, uint16_t preferred_size, int32_t *offset)
res_delete_handler(void* request, void* response, uint8_t *buffer, uint16_t preferred_size, int32_t *offset) {
{ PRINTF("/create3 DELETE ");
PRINTF("/create3 DELETE "); REST.set_response_status(response, REST.status.DELETED);
REST.set_response_status(response, REST.status.DELETED);
create3_exists = 0;
create3_exists = 0; }
}

View file

@ -1,91 +1,91 @@
/* /*
* Copyright (c) 2013, Institute for Pervasive Computing, ETH Zurich * Copyright (c) 2013, Institute for Pervasive Computing, ETH Zurich
* All rights reserved. * All rights reserved.
* *
* Redistribution and use in source and binary forms, with or without * Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions * modification, are permitted provided that the following conditions
* are met: * are met:
* 1. Redistributions of source code must retain the above copyright * 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer. * notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright * 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the * notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution. * documentation and/or other materials provided with the distribution.
* 3. Neither the name of the Institute nor the names of its contributors * 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 * may be used to endorse or promote products derived from this software
* without specific prior written permission. * without specific prior written permission.
* *
* THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * 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 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE. * SUCH DAMAGE.
* *
* This file is part of the Contiki operating system. * This file is part of the Contiki operating system.
*/ */
/** /**
* \file * \file
* ETSI Plugtest resource * ETSI Plugtest resource
* \author * \author
* Matthias Kovatsch <kovatsch@inf.ethz.ch> * Matthias Kovatsch <kovatsch@inf.ethz.ch>
*/ */
#include <string.h> #include <string.h>
#include "rest-engine.h" #include "rest-engine.h"
#include "er-coap.h" #include "er-coap.h"
#include "er-plugtest.h" #include "er-plugtest.h"
static void res_post_handler(void* request, void* response, uint8_t *buffer, uint16_t preferred_size, int32_t *offset); static void res_post_handler(void *request, void *response, uint8_t *buffer, uint16_t preferred_size, int32_t *offset);
/* /*
* Large resource that can be created using POST method * Large resource that can be created using POST method
*/ */
RESOURCE(res_plugtest_large_create, RESOURCE(res_plugtest_large_create,
"title=\"Large resource that can be created using POST method\";rt=\"block\"", "title=\"Large resource that can be created using POST method\";rt=\"block\"",
NULL, NULL,
res_post_handler, res_post_handler,
NULL, NULL,
NULL); NULL);
static void static void
res_post_handler(void* request, void* response, uint8_t *buffer, uint16_t preferred_size, int32_t *offset) res_post_handler(void *request, void *response, uint8_t *buffer, uint16_t preferred_size, int32_t *offset)
{ {
coap_packet_t * const coap_req = (coap_packet_t *) request; coap_packet_t *const coap_req = (coap_packet_t *)request;
uint8_t *incoming = NULL; uint8_t *incoming = NULL;
size_t len = 0; size_t len = 0;
unsigned int ct = -1; unsigned int ct = -1;
if(!REST.get_header_content_type(request, &ct)) { if(!REST.get_header_content_type(request, &ct)) {
REST.set_response_status(response, REST.status.BAD_REQUEST); REST.set_response_status(response, REST.status.BAD_REQUEST);
const char *error_msg = "NoContentType"; const char *error_msg = "NoContentType";
REST.set_response_payload(response, error_msg, strlen(error_msg)); REST.set_response_payload(response, error_msg, strlen(error_msg));
return; return;
} }
if((len = REST.get_request_payload(request, (const uint8_t **) &incoming))) { if((len = REST.get_request_payload(request, (const uint8_t **)&incoming))) {
if(coap_req->block1_num * coap_req->block1_size + len <= 2048) { if(coap_req->block1_num * coap_req->block1_size + len <= 2048) {
REST.set_response_status(response, REST.status.CREATED); REST.set_response_status(response, REST.status.CREATED);
REST.set_header_location(response, "/nirvana"); REST.set_header_location(response, "/nirvana");
coap_set_header_block1(response, coap_req->block1_num, 0, coap_set_header_block1(response, coap_req->block1_num, 0,
coap_req->block1_size); coap_req->block1_size);
} else { } else {
REST.set_response_status(response, REST.status.REQUEST_ENTITY_TOO_LARGE); REST.set_response_status(response, REST.status.REQUEST_ENTITY_TOO_LARGE);
const char *error_msg = "2048B max."; const char *error_msg = "2048B max.";
REST.set_response_payload(response, error_msg, strlen(error_msg)); REST.set_response_payload(response, error_msg, strlen(error_msg));
return; return;
} }
} else { } else {
REST.set_response_status(response, REST.status.BAD_REQUEST); REST.set_response_status(response, REST.status.BAD_REQUEST);
const char *error_msg = "NoPayload"; const char *error_msg = "NoPayload";
REST.set_response_payload(response, error_msg, strlen(error_msg)); REST.set_response_payload(response, error_msg, strlen(error_msg));
return; return;
} }
} }

View file

@ -1,128 +1,127 @@
/* /*
* Copyright (c) 2013, Institute for Pervasive Computing, ETH Zurich * Copyright (c) 2013, Institute for Pervasive Computing, ETH Zurich
* All rights reserved. * All rights reserved.
* *
* Redistribution and use in source and binary forms, with or without * Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions * modification, are permitted provided that the following conditions
* are met: * are met:
* 1. Redistributions of source code must retain the above copyright * 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer. * notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright * 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the * notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution. * documentation and/or other materials provided with the distribution.
* 3. Neither the name of the Institute nor the names of its contributors * 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 * may be used to endorse or promote products derived from this software
* without specific prior written permission. * without specific prior written permission.
* *
* THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * 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 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE. * SUCH DAMAGE.
* *
* This file is part of the Contiki operating system. * This file is part of the Contiki operating system.
*/ */
/** /**
* \file * \file
* ETSI Plugtest resource * ETSI Plugtest resource
* \author * \author
* Matthias Kovatsch <kovatsch@inf.ethz.ch> * Matthias Kovatsch <kovatsch@inf.ethz.ch>
*/ */
#include <string.h> #include <string.h>
#include "rest-engine.h" #include "rest-engine.h"
#include "er-coap.h" #include "er-coap.h"
#include "er-plugtest.h" #include "er-plugtest.h"
static void res_get_handler(void* request, void* response, uint8_t *buffer, uint16_t preferred_size, int32_t *offset); static void res_get_handler(void *request, void *response, uint8_t *buffer, uint16_t preferred_size, int32_t *offset);
static void res_put_handler(void* request, void* response, uint8_t *buffer, uint16_t preferred_size, int32_t *offset); static void res_put_handler(void *request, void *response, uint8_t *buffer, uint16_t preferred_size, int32_t *offset);
RESOURCE( RESOURCE(
res_plugtest_large_update, res_plugtest_large_update,
"title=\"Large resource that can be updated using PUT method\";rt=\"block\";sz=\"" TO_STRING(MAX_PLUGFEST_BODY) "\"", "title=\"Large resource that can be updated using PUT method\";rt=\"block\";sz=\"" TO_STRING(MAX_PLUGFEST_BODY) "\"",
res_get_handler, res_get_handler,
NULL, NULL,
res_put_handler, res_put_handler,
NULL); NULL);
static int32_t large_update_size = 0; static int32_t large_update_size = 0;
static uint8_t large_update_store[MAX_PLUGFEST_BODY] = { 0 }; static uint8_t large_update_store[MAX_PLUGFEST_BODY] = { 0 };
static unsigned int large_update_ct = APPLICATION_OCTET_STREAM; static unsigned int large_update_ct = APPLICATION_OCTET_STREAM;
static void static void
res_get_handler(void* request, void* response, uint8_t *buffer, uint16_t preferred_size, int32_t *offset) res_get_handler(void *request, void *response, uint8_t *buffer, uint16_t preferred_size, int32_t *offset)
{ {
/* Check the offset for boundaries of the resource data. */ /* Check the offset for boundaries of the resource data. */
if(*offset >= large_update_size) { if(*offset >= large_update_size) {
REST.set_response_status(response, REST.status.BAD_OPTION); REST.set_response_status(response, REST.status.BAD_OPTION);
/* A block error message should not exceed the minimum block size (16). */ /* A block error message should not exceed the minimum block size (16). */
const char *error_msg = "BlockOutOfScope"; const char *error_msg = "BlockOutOfScope";
REST.set_response_payload(response, error_msg, strlen(error_msg)); REST.set_response_payload(response, error_msg, strlen(error_msg));
return; return;
} }
REST.set_response_payload(response, large_update_store + *offset, REST.set_response_payload(response, large_update_store + *offset,
MIN(large_update_size - *offset, preferred_size)); MIN(large_update_size - *offset, preferred_size));
REST.set_header_content_type(response, large_update_ct); REST.set_header_content_type(response, large_update_ct);
/* IMPORTANT for chunk-wise resources: Signal chunk awareness to REST engine. */ /* IMPORTANT for chunk-wise resources: Signal chunk awareness to REST engine. */
*offset += preferred_size; *offset += preferred_size;
/* Signal end of resource representation. */ /* Signal end of resource representation. */
if(*offset >= large_update_size) { if(*offset >= large_update_size) {
*offset = -1; *offset = -1;
} }
} }
static void
static void res_put_handler(void *request, void *response, uint8_t *buffer, uint16_t preferred_size, int32_t *offset)
res_put_handler(void* request, void* response, uint8_t *buffer, uint16_t preferred_size, int32_t *offset) {
{ coap_packet_t *const coap_req = (coap_packet_t *)request;
coap_packet_t * const coap_req = (coap_packet_t *) request; uint8_t *incoming = NULL;
uint8_t *incoming = NULL; size_t len = 0;
size_t len = 0;
unsigned int ct = -1;
unsigned int ct = -1;
if(!REST.get_header_content_type(request, &ct)) {
if(!REST.get_header_content_type(request, &ct)) { REST.set_response_status(response, REST.status.BAD_REQUEST);
REST.set_response_status(response, REST.status.BAD_REQUEST); const char *error_msg = "NoContentType";
const char *error_msg = "NoContentType"; REST.set_response_payload(response, error_msg, strlen(error_msg));
REST.set_response_payload(response, error_msg, strlen(error_msg)); return;
return; }
}
if((len = REST.get_request_payload(request, (const uint8_t **)&incoming))) {
if((len = REST.get_request_payload(request, (const uint8_t **) &incoming))) { if(coap_req->block1_num * coap_req->block1_size + len <= sizeof(large_update_store)) {
if(coap_req->block1_num * coap_req->block1_size + len <= sizeof(large_update_store)) { memcpy(
memcpy( large_update_store + coap_req->block1_num * coap_req->block1_size,
large_update_store + coap_req->block1_num * coap_req->block1_size, incoming, len);
incoming, len); large_update_size = coap_req->block1_num * coap_req->block1_size + len;
large_update_size = coap_req->block1_num * coap_req->block1_size + len; large_update_ct = ct;
large_update_ct = ct;
REST.set_response_status(response, REST.status.CHANGED);
REST.set_response_status(response, REST.status.CHANGED); coap_set_header_block1(response, coap_req->block1_num, 0,
coap_set_header_block1(response, coap_req->block1_num, 0, coap_req->block1_size);
coap_req->block1_size); } else {
} else { REST.set_response_status(response,
REST.set_response_status(response, REST.status.REQUEST_ENTITY_TOO_LARGE);
REST.status.REQUEST_ENTITY_TOO_LARGE); REST.set_response_payload(
REST.set_response_payload( response,
response, buffer,
buffer, snprintf((char *)buffer, MAX_PLUGFEST_PAYLOAD, "%uB max.",
snprintf((char *) buffer, MAX_PLUGFEST_PAYLOAD, "%uB max.", sizeof(large_update_store)));
sizeof(large_update_store))); return;
return; }
} } else {
} else { REST.set_response_status(response, REST.status.BAD_REQUEST);
REST.set_response_status(response, REST.status.BAD_REQUEST); const char *error_msg = "NoPayload";
const char *error_msg = "NoPayload"; REST.set_response_payload(response, error_msg, strlen(error_msg));
REST.set_response_payload(response, error_msg, strlen(error_msg)); return;
return; }
} }
}

186
examples/er-rest-example/resources/res-plugtest-large.c Executable file → Normal file
View file

@ -1,94 +1,92 @@
/* /*
* Copyright (c) 2013, Institute for Pervasive Computing, ETH Zurich * Copyright (c) 2013, Institute for Pervasive Computing, ETH Zurich
* All rights reserved. * All rights reserved.
* *
* Redistribution and use in source and binary forms, with or without * Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions * modification, are permitted provided that the following conditions
* are met: * are met:
* 1. Redistributions of source code must retain the above copyright * 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer. * notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright * 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the * notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution. * documentation and/or other materials provided with the distribution.
* 3. Neither the name of the Institute nor the names of its contributors * 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 * may be used to endorse or promote products derived from this software
* without specific prior written permission. * without specific prior written permission.
* *
* THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * 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 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE. * SUCH DAMAGE.
* *
* This file is part of the Contiki operating system. * This file is part of the Contiki operating system.
*/ */
/** /**
* \file * \file
* ETSI Plugtest resource * ETSI Plugtest resource
* \author * \author
* Matthias Kovatsch <kovatsch@inf.ethz.ch> * Matthias Kovatsch <kovatsch@inf.ethz.ch>
*/ */
#include <string.h> #include <string.h>
#include "rest-engine.h" #include "rest-engine.h"
#include "er-coap.h" #include "er-coap.h"
#include "er-plugtest.h" #include "er-plugtest.h"
static void res_get_handler(void* request, void* response, uint8_t *buffer, uint16_t preferred_size, int32_t *offset); static void res_get_handler(void *request, void *response, uint8_t *buffer, uint16_t preferred_size, int32_t *offset);
RESOURCE(res_plugtest_large, RESOURCE(res_plugtest_large,
"title=\"Large resource\";rt=\"block\";sz=\"" TO_STRING(CHUNKS_TOTAL) "\"", "title=\"Large resource\";rt=\"block\";sz=\"" TO_STRING(CHUNKS_TOTAL) "\"",
res_get_handler, res_get_handler,
NULL, NULL,
NULL, NULL,
NULL); NULL);
static void static void
res_get_handler(void* request, void* response, uint8_t *buffer, uint16_t preferred_size, int32_t *offset) res_get_handler(void *request, void *response, uint8_t *buffer, uint16_t preferred_size, int32_t *offset)
{ {
int32_t strpos = 0; int32_t strpos = 0;
/* Check the offset for boundaries of the resource data. */ /* Check the offset for boundaries of the resource data. */
if(*offset >= CHUNKS_TOTAL) { if(*offset >= CHUNKS_TOTAL) {
REST.set_response_status(response, REST.status.BAD_OPTION); REST.set_response_status(response, REST.status.BAD_OPTION);
/* A block error message should not exceed the minimum block size (16). */ /* A block error message should not exceed the minimum block size (16). */
const char *error_msg = "BlockOutOfScope"; const char *error_msg = "BlockOutOfScope";
REST.set_response_payload(response, error_msg, strlen(error_msg)); REST.set_response_payload(response, error_msg, strlen(error_msg));
return; return;
} }
/* Generate data until reaching CHUNKS_TOTAL. */ /* Generate data until reaching CHUNKS_TOTAL. */
while(strpos < preferred_size) { while(strpos < preferred_size) {
strpos += snprintf((char *) buffer + strpos, preferred_size - strpos + 1, strpos += snprintf((char *)buffer + strpos, preferred_size - strpos + 1,
"|%ld|", *offset); "|%ld|", *offset);
} }
/* snprintf() does not adjust return value if truncated by size. */ /* snprintf() does not adjust return value if truncated by size. */
if(strpos > preferred_size) { if(strpos > preferred_size) {
strpos = preferred_size; strpos = preferred_size;
} /* Truncate if above CHUNKS_TOTAL bytes. */
}
/* Truncate if above CHUNKS_TOTAL bytes. */ if(*offset + (int32_t)strpos > CHUNKS_TOTAL) {
if(*offset + (int32_t) strpos > CHUNKS_TOTAL) { strpos = CHUNKS_TOTAL - *offset;
strpos = CHUNKS_TOTAL - *offset; }
} REST.set_response_payload(response, buffer, strpos);
REST.set_header_content_type(response, REST.type.TEXT_PLAIN);
REST.set_response_payload(response, buffer, strpos);
REST.set_header_content_type(response, REST.type.TEXT_PLAIN); /* IMPORTANT for chunk-wise resources: Signal chunk awareness to REST engine. */
*offset += strpos;
/* IMPORTANT for chunk-wise resources: Signal chunk awareness to REST engine. */
*offset += strpos; /* Signal end of resource representation. */
if(*offset >= CHUNKS_TOTAL) {
/* Signal end of resource representation. */ *offset = -1;
if(*offset >= CHUNKS_TOTAL) { }
*offset = -1; }
}
}

142
examples/er-rest-example/resources/res-plugtest-links.c Executable file → Normal file
View file

@ -1,71 +1,71 @@
/* /*
* Copyright (c) 2013, Institute for Pervasive Computing, ETH Zurich * Copyright (c) 2013, Institute for Pervasive Computing, ETH Zurich
* All rights reserved. * All rights reserved.
* *
* Redistribution and use in source and binary forms, with or without * Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions * modification, are permitted provided that the following conditions
* are met: * are met:
* 1. Redistributions of source code must retain the above copyright * 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer. * notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright * 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the * notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution. * documentation and/or other materials provided with the distribution.
* 3. Neither the name of the Institute nor the names of its contributors * 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 * may be used to endorse or promote products derived from this software
* without specific prior written permission. * without specific prior written permission.
* *
* THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * 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 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE. * SUCH DAMAGE.
* *
* This file is part of the Contiki operating system. * This file is part of the Contiki operating system.
*/ */
/** /**
* \file * \file
* ETSI Plugtest resource * ETSI Plugtest resource
* \author * \author
* Matthias Kovatsch <kovatsch@inf.ethz.ch> * Matthias Kovatsch <kovatsch@inf.ethz.ch>
*/ */
#include <string.h> #include <string.h>
#include "rest-engine.h" #include "rest-engine.h"
#include "er-coap.h" #include "er-coap.h"
#include "er-plugtest.h" #include "er-plugtest.h"
static void res_get_handler(void* request, void* response, uint8_t *buffer, uint16_t preferred_size, int32_t *offset); static void res_get_handler(void *request, void *response, uint8_t *buffer, uint16_t preferred_size, int32_t *offset);
RESOURCE(res_plugtest_link1, RESOURCE(res_plugtest_link1,
"rt=\"Type1 Type2\";if=\"If1\"", "rt=\"Type1 Type2\";if=\"If1\"",
res_get_handler, res_get_handler,
NULL, NULL,
NULL, NULL,
NULL); NULL);
RESOURCE(res_plugtest_link2, RESOURCE(res_plugtest_link2,
"rt=\"Type2 Type3\";if=\"If2\"", "rt=\"Type2 Type3\";if=\"If2\"",
res_get_handler, res_get_handler,
NULL, NULL,
NULL, NULL,
NULL); NULL);
RESOURCE(res_plugtest_link3, RESOURCE(res_plugtest_link3,
"rt=\"Type1 Type3\";if=\"foo\"", "rt=\"Type1 Type3\";if=\"foo\"",
res_get_handler, res_get_handler,
NULL, NULL,
NULL, NULL,
NULL); NULL);
static void static void
res_get_handler(void* request, void* response, uint8_t *buffer, uint16_t preferred_size, int32_t *offset) res_get_handler(void *request, void *response, uint8_t *buffer, uint16_t preferred_size, int32_t *offset)
{ {
const char *msg = "Dummy link"; const char *msg = "Dummy link";
REST.set_header_content_type(response, REST.type.TEXT_PLAIN); REST.set_header_content_type(response, REST.type.TEXT_PLAIN);
REST.set_response_payload(response, msg, strlen(msg)); REST.set_response_payload(response, msg, strlen(msg));
} }

View file

@ -1,63 +1,63 @@
/* /*
* Copyright (c) 2013, Institute for Pervasive Computing, ETH Zurich * Copyright (c) 2013, Institute for Pervasive Computing, ETH Zurich
* All rights reserved. * All rights reserved.
* *
* Redistribution and use in source and binary forms, with or without * Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions * modification, are permitted provided that the following conditions
* are met: * are met:
* 1. Redistributions of source code must retain the above copyright * 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer. * notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright * 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the * notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution. * documentation and/or other materials provided with the distribution.
* 3. Neither the name of the Institute nor the names of its contributors * 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 * may be used to endorse or promote products derived from this software
* without specific prior written permission. * without specific prior written permission.
* *
* THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * 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 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE. * SUCH DAMAGE.
* *
* This file is part of the Contiki operating system. * This file is part of the Contiki operating system.
*/ */
/** /**
* \file * \file
* ETSI Plugtest resource * ETSI Plugtest resource
* \author * \author
* Matthias Kovatsch <kovatsch@inf.ethz.ch> * Matthias Kovatsch <kovatsch@inf.ethz.ch>
*/ */
#include <string.h> #include <string.h>
#include "rest-engine.h" #include "rest-engine.h"
#include "er-coap.h" #include "er-coap.h"
#include "er-plugtest.h" #include "er-plugtest.h"
static void res_post_handler(void* request, void* response, uint8_t *buffer, uint16_t preferred_size, int32_t *offset); static void res_post_handler(void *request, void *response, uint8_t *buffer, uint16_t preferred_size, int32_t *offset);
RESOURCE(res_plugtest_locquery, RESOURCE(res_plugtest_locquery,
"title=\"Resource accepting query parameters\"", "title=\"Resource accepting query parameters\"",
NULL, NULL,
res_post_handler, res_post_handler,
NULL, NULL,
NULL); NULL);
static void static void
res_post_handler(void* request, void* response, uint8_t *buffer, uint16_t preferred_size, int32_t *offset) res_post_handler(void *request, void *response, uint8_t *buffer, uint16_t preferred_size, int32_t *offset)
{ {
coap_packet_t * const coap_req = (coap_packet_t *) request; coap_packet_t *const coap_req = (coap_packet_t *)request;
PRINTF( PRINTF(
"/location-query POST (%s %u)\n", coap_req->type==COAP_TYPE_CON?"CON":"NON", coap_req->mid); "/location-query POST (%s %u)\n", coap_req->type == COAP_TYPE_CON ? "CON" : "NON", coap_req->mid);
REST.set_response_status(response, REST.status.CREATED); REST.set_response_status(response, REST.status.CREATED);
REST.set_header_location(response, "?first=1&second=2"); REST.set_header_location(response, "?first=1&second=2");
} }

View file

@ -1,68 +1,68 @@
/* /*
* Copyright (c) 2013, Institute for Pervasive Computing, ETH Zurich * Copyright (c) 2013, Institute for Pervasive Computing, ETH Zurich
* All rights reserved. * All rights reserved.
* *
* Redistribution and use in source and binary forms, with or without * Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions * modification, are permitted provided that the following conditions
* are met: * are met:
* 1. Redistributions of source code must retain the above copyright * 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer. * notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright * 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the * notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution. * documentation and/or other materials provided with the distribution.
* 3. Neither the name of the Institute nor the names of its contributors * 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 * may be used to endorse or promote products derived from this software
* without specific prior written permission. * without specific prior written permission.
* *
* THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * 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 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE. * SUCH DAMAGE.
* *
* This file is part of the Contiki operating system. * This file is part of the Contiki operating system.
*/ */
/** /**
* \file * \file
* ETSI Plugtest resource * ETSI Plugtest resource
* \author * \author
* Matthias Kovatsch <kovatsch@inf.ethz.ch> * Matthias Kovatsch <kovatsch@inf.ethz.ch>
*/ */
#include <string.h> #include <string.h>
#include "rest-engine.h" #include "rest-engine.h"
#include "er-coap.h" #include "er-coap.h"
#include "er-plugtest.h" #include "er-plugtest.h"
static void res_get_handler(void* request, void* response, uint8_t *buffer, uint16_t preferred_size, int32_t *offset); static void res_get_handler(void *request, void *response, uint8_t *buffer, uint16_t preferred_size, int32_t *offset);
RESOURCE(res_plugtest_longpath, RESOURCE(res_plugtest_longpath,
"title=\"Long path resource\"", "title=\"Long path resource\"",
res_get_handler, res_get_handler,
NULL, NULL,
NULL, NULL,
NULL); NULL);
static void static void
res_get_handler(void* request, void* response, uint8_t *buffer, uint16_t preferred_size, int32_t *offset) res_get_handler(void *request, void *response, uint8_t *buffer, uint16_t preferred_size, int32_t *offset)
{ {
coap_packet_t * const coap_req = (coap_packet_t *) request; coap_packet_t *const coap_req = (coap_packet_t *)request;
PRINTF("/seg1/seg2/seg3 GET "); PRINTF("/seg1/seg2/seg3 GET ");
/* Code 2.05 CONTENT is default. */ /* Code 2.05 CONTENT is default. */
REST.set_header_content_type(response, REST.type.TEXT_PLAIN); REST.set_header_content_type(response, REST.type.TEXT_PLAIN);
REST.set_response_payload( REST.set_response_payload(
response, response,
buffer, buffer,
snprintf((char *) buffer, MAX_PLUGFEST_PAYLOAD, snprintf((char *)buffer, MAX_PLUGFEST_PAYLOAD,
"Type: %u\nCode: %u\nMID: %u", coap_req->type, coap_req->code, coap_req->mid)); "Type: %u\nCode: %u\nMID: %u", coap_req->type, coap_req->code, coap_req->mid));
PRINTF("(%s %u)\n", coap_req->type==COAP_TYPE_CON?"CON":"NON", coap_req->mid); PRINTF("(%s %u)\n", coap_req->type == COAP_TYPE_CON ? "CON" : "NON", coap_req->mid);
} }

174
examples/er-rest-example/resources/res-plugtest-multi.c Executable file → Normal file
View file

@ -1,87 +1,87 @@
/* /*
* Copyright (c) 2013, Institute for Pervasive Computing, ETH Zurich * Copyright (c) 2013, Institute for Pervasive Computing, ETH Zurich
* All rights reserved. * All rights reserved.
* *
* Redistribution and use in source and binary forms, with or without * Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions * modification, are permitted provided that the following conditions
* are met: * are met:
* 1. Redistributions of source code must retain the above copyright * 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer. * notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright * 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the * notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution. * documentation and/or other materials provided with the distribution.
* 3. Neither the name of the Institute nor the names of its contributors * 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 * may be used to endorse or promote products derived from this software
* without specific prior written permission. * without specific prior written permission.
* *
* THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * 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 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE. * SUCH DAMAGE.
* *
* This file is part of the Contiki operating system. * This file is part of the Contiki operating system.
*/ */
/** /**
* \file * \file
* ETSI Plugtest resource * ETSI Plugtest resource
* \author * \author
* Matthias Kovatsch <kovatsch@inf.ethz.ch> * Matthias Kovatsch <kovatsch@inf.ethz.ch>
*/ */
#include <string.h> #include <string.h>
#include "rest-engine.h" #include "rest-engine.h"
#include "er-coap.h" #include "er-coap.h"
#include "er-plugtest.h" #include "er-plugtest.h"
static void res_get_handler(void* request, void* response, uint8_t *buffer, uint16_t preferred_size, int32_t *offset); static void res_get_handler(void *request, void *response, uint8_t *buffer, uint16_t preferred_size, int32_t *offset);
RESOURCE(res_plugtest_multi, RESOURCE(res_plugtest_multi,
"title=\"Resource providing text/plain and application/xml\";ct=\"0 41\"", "title=\"Resource providing text/plain and application/xml\";ct=\"0 41\"",
res_get_handler, res_get_handler,
NULL, NULL,
NULL, NULL,
NULL); NULL);
static void static void
res_get_handler(void* request, void* response, uint8_t *buffer, uint16_t preferred_size, int32_t *offset) res_get_handler(void *request, void *response, uint8_t *buffer, uint16_t preferred_size, int32_t *offset)
{ {
coap_packet_t * const coap_req = (coap_packet_t *) request; coap_packet_t *const coap_req = (coap_packet_t *)request;
unsigned int accept = -1; unsigned int accept = -1;
REST.get_header_accept(request, &accept); REST.get_header_accept(request, &accept);
PRINTF("/multi-format GET (%s %u) ", coap_req->type==COAP_TYPE_CON?"CON":"NON", coap_req->mid); PRINTF("/multi-format GET (%s %u) ", coap_req->type == COAP_TYPE_CON ? "CON" : "NON", coap_req->mid);
if(accept == -1 || accept == REST.type.TEXT_PLAIN) { if(accept == -1 || accept == REST.type.TEXT_PLAIN) {
REST.set_header_content_type(response, REST.type.TEXT_PLAIN); REST.set_header_content_type(response, REST.type.TEXT_PLAIN);
REST.set_response_payload( REST.set_response_payload(
response, response,
buffer, buffer,
snprintf((char *) buffer, MAX_PLUGFEST_PAYLOAD, snprintf((char *)buffer, MAX_PLUGFEST_PAYLOAD,
"Type: %u\nCode: %u\nMID: %u%s", coap_req->type, coap_req->code, "Type: %u\nCode: %u\nMID: %u%s", coap_req->type, coap_req->code,
coap_req->mid, accept != -1 ? "\nAccept: 0" : "")); coap_req->mid, accept != -1 ? "\nAccept: 0" : ""));
PRINTF("PLAIN\n"); PRINTF("PLAIN\n");
} else if(accept == REST.type.APPLICATION_XML) { } else if(accept == REST.type.APPLICATION_XML) {
REST.set_header_content_type(response, REST.type.APPLICATION_XML); REST.set_header_content_type(response, REST.type.APPLICATION_XML);
REST.set_response_payload( REST.set_response_payload(
response, response,
buffer, buffer,
snprintf((char *) buffer, MAX_PLUGFEST_PAYLOAD, snprintf((char *)buffer, MAX_PLUGFEST_PAYLOAD,
"<status type=\"%u\" code=\"%u\" mid=\"%u\" accept=\"%u\"/>", "<status type=\"%u\" code=\"%u\" mid=\"%u\" accept=\"%u\"/>",
coap_req->type, coap_req->code, coap_req->mid, accept)); coap_req->type, coap_req->code, coap_req->mid, accept));
PRINTF("XML\n"); PRINTF("XML\n");
} else { } else {
REST.set_response_status(response, REST.status.NOT_ACCEPTABLE); REST.set_response_status(response, REST.status.NOT_ACCEPTABLE);
const char *msg = "Supporting content-types text/plain and application/xml"; const char *msg = "Supporting content-types text/plain and application/xml";
REST.set_response_payload(response, msg, strlen(msg)); REST.set_response_payload(response, msg, strlen(msg));
PRINTF("ERROR\n"); PRINTF("ERROR\n");
} }
} }

316
examples/er-rest-example/resources/res-plugtest-obs.c Executable file → Normal file
View file

@ -1,161 +1,155 @@
/* /*
* Copyright (c) 2013, Institute for Pervasive Computing, ETH Zurich * Copyright (c) 2013, Institute for Pervasive Computing, ETH Zurich
* All rights reserved. * All rights reserved.
* *
* Redistribution and use in source and binary forms, with or without * Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions * modification, are permitted provided that the following conditions
* are met: * are met:
* 1. Redistributions of source code must retain the above copyright * 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer. * notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright * 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the * notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution. * documentation and/or other materials provided with the distribution.
* 3. Neither the name of the Institute nor the names of its contributors * 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 * may be used to endorse or promote products derived from this software
* without specific prior written permission. * without specific prior written permission.
* *
* THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * 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 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE. * SUCH DAMAGE.
* *
* This file is part of the Contiki operating system. * This file is part of the Contiki operating system.
*/ */
/** /**
* \file * \file
* ETSI Plugtest resource * ETSI Plugtest resource
* \author * \author
* Matthias Kovatsch <kovatsch@inf.ethz.ch> * Matthias Kovatsch <kovatsch@inf.ethz.ch>
*/ */
#include <string.h> #include <string.h>
#include "rest-engine.h" #include "rest-engine.h"
#include "er-coap.h" #include "er-coap.h"
#include "er-coap-observe.h" #include "er-coap-observe.h"
#include "er-plugtest.h" #include "er-plugtest.h"
static void res_get_handler(void* request, void* response, uint8_t *buffer, uint16_t preferred_size, int32_t *offset); static void res_get_handler(void *request, void *response, uint8_t *buffer, uint16_t preferred_size, int32_t *offset);
static void res_put_handler(void* request, void* response, uint8_t *buffer, uint16_t preferred_size, int32_t *offset); static void res_put_handler(void *request, void *response, uint8_t *buffer, uint16_t preferred_size, int32_t *offset);
static void res_delete_handler(void* request, void* response, uint8_t *buffer, uint16_t preferred_size, int32_t *offset); static void res_delete_handler(void *request, void *response, uint8_t *buffer, uint16_t preferred_size, int32_t *offset);
static void res_periodic_handler(void); static void res_periodic_handler(void);
PERIODIC_RESOURCE(res_plugtest_obs, PERIODIC_RESOURCE(res_plugtest_obs,
"title=\"Observable resource which changes every 5 seconds\";obs", "title=\"Observable resource which changes every 5 seconds\";obs",
res_get_handler, res_get_handler,
NULL, NULL,
res_put_handler, res_put_handler,
res_delete_handler, res_delete_handler,
5*CLOCK_SECOND, 5 * CLOCK_SECOND,
res_periodic_handler); res_periodic_handler);
static int32_t obs_counter = 0; static int32_t obs_counter = 0;
static char obs_content[MAX_PLUGFEST_BODY]; static char obs_content[MAX_PLUGFEST_BODY];
static size_t obs_content_len = 0; static size_t obs_content_len = 0;
static unsigned int obs_format = 0; static unsigned int obs_format = 0;
static char obs_status = 0; static char obs_status = 0;
static void static void
obs_purge_list() obs_purge_list()
{ {
PRINTF("### SERVER ACTION ### Purging obs list"); PRINTF("### SERVER ACTION ### Purging obs list");
coap_remove_observer_by_uri(NULL, 0, res_plugtest_obs.url); coap_remove_observer_by_uri(NULL, 0, res_plugtest_obs.url);
} }
static void
static void res_get_handler(void *request, void *response, uint8_t *buffer, uint16_t preferred_size, int32_t *offset)
res_get_handler(void* request, void* response, uint8_t *buffer, uint16_t preferred_size, int32_t *offset) {
{ /* Keep server log clean from ticking events */
/* Keep server log clean from ticking events */ if(request != NULL) {
if(request != NULL) { PRINTF("/obs GET\n");
PRINTF("/obs GET\n"); }
} REST.set_header_content_type(response, obs_format);
REST.set_header_max_age(response, 5);
REST.set_header_content_type(response, obs_format);
REST.set_header_max_age(response, 5); if(obs_content_len) {
REST.set_header_content_type(response, obs_format);
if(obs_content_len) { REST.set_response_payload(response, obs_content, obs_content_len);
REST.set_header_content_type(response, obs_format); } else {
REST.set_response_payload(response, obs_content, obs_content_len); REST.set_header_content_type(response, REST.type.TEXT_PLAIN);
} else { REST.set_response_payload(response, obs_content,
REST.set_header_content_type(response, REST.type.TEXT_PLAIN); snprintf(obs_content, MAX_PLUGFEST_PAYLOAD, "TICK %lu", obs_counter));
REST.set_response_payload(response, obs_content, }
snprintf(obs_content, MAX_PLUGFEST_PAYLOAD, "TICK %lu", obs_counter)); /* A post_handler that handles subscriptions will be called for periodic resources by the REST framework. */
} }
/* A post_handler that handles subscriptions will be called for periodic resources by the REST framework. */ static void
} res_put_handler(void *request, void *response, uint8_t *buffer, uint16_t preferred_size, int32_t *offset)
{
static void uint8_t *incoming = NULL;
res_put_handler(void* request, void* response, uint8_t *buffer, uint16_t preferred_size, int32_t *offset) unsigned int ct = -1;
{
uint8_t *incoming = NULL; REST.get_header_content_type(request, &ct);
unsigned int ct = -1;
PRINTF("/obs PUT\n");
REST.get_header_content_type(request, &ct);
if(ct != obs_format) {
PRINTF("/obs PUT\n"); obs_status = 1;
obs_format = ct;
if(ct != obs_format) { } else {
obs_status = 1; obs_content_len = REST.get_request_payload(request,
obs_format = ct; (const uint8_t **)&incoming);
} else { memcpy(obs_content, incoming, obs_content_len);
obs_content_len = REST.get_request_payload(request, res_periodic_handler();
(const uint8_t **) &incoming); }
memcpy(obs_content, incoming, obs_content_len);
res_periodic_handler(); REST.set_response_status(response, REST.status.CHANGED);
} }
static void
REST.set_response_status(response, REST.status.CHANGED); res_delete_handler(void *request, void *response, uint8_t *buffer, uint16_t preferred_size, int32_t *offset)
} {
PRINTF("/obs DELETE\n");
static void
res_delete_handler(void* request, void* response, uint8_t *buffer, uint16_t preferred_size, int32_t *offset) obs_status = 2;
{
PRINTF("/obs DELETE\n"); REST.set_response_status(response, REST.status.DELETED);
}
obs_status = 2; /*
* Additionally, a handler function named [resource name]_handler must be implemented for each PERIODIC_RESOURCE.
REST.set_response_status(response, REST.status.DELETED); * It will be called by the REST manager process with the defined period.
} */
static void
/* res_periodic_handler()
* Additionally, a handler function named [resource name]_handler must be implemented for each PERIODIC_RESOURCE. {
* It will be called by the REST manager process with the defined period. ++obs_counter;
*/
static void /* PRINTF("TICK %u for /%s\n", obs_counter, r->url); */
res_periodic_handler()
{ if(obs_status == 1) {
++obs_counter;
/* Notify the registered observers with the given message type, observe option, and payload. */
//PRINTF("TICK %u for /%s\n", obs_counter, r->url); REST.notify_subscribers(&res_plugtest_obs);
if(obs_status == 1) { PRINTF("######### sending 5.00\n");
/* Notify the registered observers with the given message type, observe option, and payload. */ obs_purge_list();
REST.notify_subscribers(&res_plugtest_obs); } else if(obs_status == 2) {
PRINTF("######### sending 5.00\n"); /* Notify the registered observers with the given message type, observe option, and payload. */
REST.notify_subscribers(&res_plugtest_obs);
obs_purge_list();
} else if(obs_status == 2) { obs_purge_list();
/* Notify the registered observers with the given message type, observe option, and payload. */ obs_counter = 0;
REST.notify_subscribers(&res_plugtest_obs); obs_content_len = 0;
} else {
obs_purge_list(); /* Notify the registered observers with the given message type, observe option, and payload. */
REST.notify_subscribers(&res_plugtest_obs);
obs_counter = 0; } obs_status = 0;
obs_content_len = 0; }
} else {
/* Notify the registered observers with the given message type, observe option, and payload. */
REST.notify_subscribers(&res_plugtest_obs);
}
obs_status = 0;
}

144
examples/er-rest-example/resources/res-plugtest-path.c Executable file → Normal file
View file

@ -1,72 +1,72 @@
/* /*
* Copyright (c) 2013, Institute for Pervasive Computing, ETH Zurich * Copyright (c) 2013, Institute for Pervasive Computing, ETH Zurich
* All rights reserved. * All rights reserved.
* *
* Redistribution and use in source and binary forms, with or without * Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions * modification, are permitted provided that the following conditions
* are met: * are met:
* 1. Redistributions of source code must retain the above copyright * 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer. * notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright * 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the * notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution. * documentation and/or other materials provided with the distribution.
* 3. Neither the name of the Institute nor the names of its contributors * 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 * may be used to endorse or promote products derived from this software
* without specific prior written permission. * without specific prior written permission.
* *
* THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * 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 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE. * SUCH DAMAGE.
* *
* This file is part of the Contiki operating system. * This file is part of the Contiki operating system.
*/ */
/** /**
* \file * \file
* ETSI Plugtest resource * ETSI Plugtest resource
* \author * \author
* Matthias Kovatsch <kovatsch@inf.ethz.ch> * Matthias Kovatsch <kovatsch@inf.ethz.ch>
*/ */
#include <string.h> #include <string.h>
#include "rest-engine.h" #include "rest-engine.h"
#include "er-coap.h" #include "er-coap.h"
#include "er-plugtest.h" #include "er-plugtest.h"
static void res_get_handler(void* request, void* response, uint8_t *buffer, uint16_t preferred_size, int32_t *offset); static void res_get_handler(void *request, void *response, uint8_t *buffer, uint16_t preferred_size, int32_t *offset);
PARENT_RESOURCE(res_plugtest_path, PARENT_RESOURCE(res_plugtest_path,
"title=\"Path test resource\";ct=\"40\"", "title=\"Path test resource\";ct=\"40\"",
res_get_handler, res_get_handler,
NULL, NULL,
NULL, NULL,
NULL); NULL);
static void static void
res_get_handler(void* request, void* response, uint8_t *buffer, res_get_handler(void *request, void *response, uint8_t *buffer,
uint16_t preferred_size, int32_t *offset) uint16_t preferred_size, int32_t *offset)
{ {
const char *uri_path = NULL; const char *uri_path = NULL;
int len = REST.get_url(request, &uri_path); int len = REST.get_url(request, &uri_path);
int base_len = strlen(res_plugtest_path.url); int base_len = strlen(res_plugtest_path.url);
if(len == base_len) { if(len == base_len) {
REST.set_header_content_type(response, REST.type.APPLICATION_LINK_FORMAT); REST.set_header_content_type(response, REST.type.APPLICATION_LINK_FORMAT);
snprintf((char *) buffer, MAX_PLUGFEST_PAYLOAD, snprintf((char *)buffer, MAX_PLUGFEST_PAYLOAD,
"</path/sub1>,</path/sub2>,</path/sub3>"); "</path/sub1>,</path/sub2>,</path/sub3>");
} else { } else {
REST.set_header_content_type(response, REST.type.TEXT_PLAIN); REST.set_header_content_type(response, REST.type.TEXT_PLAIN);
snprintf((char *) buffer, MAX_PLUGFEST_PAYLOAD, "/%.*s", len, uri_path); snprintf((char *)buffer, MAX_PLUGFEST_PAYLOAD, "/%.*s", len, uri_path);
} }
REST.set_response_payload(response, buffer, strlen((char *) buffer)); REST.set_response_payload(response, buffer, strlen((char *)buffer));
} }

149
examples/er-rest-example/resources/res-plugtest-query.c Executable file → Normal file
View file

@ -1,75 +1,74 @@
/* /*
* Copyright (c) 2013, Institute for Pervasive Computing, ETH Zurich * Copyright (c) 2013, Institute for Pervasive Computing, ETH Zurich
* All rights reserved. * All rights reserved.
* *
* Redistribution and use in source and binary forms, with or without * Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions * modification, are permitted provided that the following conditions
* are met: * are met:
* 1. Redistributions of source code must retain the above copyright * 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer. * notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright * 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the * notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution. * documentation and/or other materials provided with the distribution.
* 3. Neither the name of the Institute nor the names of its contributors * 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 * may be used to endorse or promote products derived from this software
* without specific prior written permission. * without specific prior written permission.
* *
* THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * 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 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE. * SUCH DAMAGE.
* *
* This file is part of the Contiki operating system. * This file is part of the Contiki operating system.
*/ */
/** /**
* \file * \file
* ETSI Plugtest resource * ETSI Plugtest resource
* \author * \author
* Matthias Kovatsch <kovatsch@inf.ethz.ch> * Matthias Kovatsch <kovatsch@inf.ethz.ch>
*/ */
#include <string.h> #include <string.h>
#include "rest-engine.h" #include "rest-engine.h"
#include "er-coap.h" #include "er-coap.h"
#include "er-plugtest.h" #include "er-plugtest.h"
static void res_get_handler(void* request, void* response, uint8_t *buffer, uint16_t preferred_size, int32_t *offset); static void res_get_handler(void *request, void *response, uint8_t *buffer, uint16_t preferred_size, int32_t *offset);
RESOURCE(res_plugtest_query, RESOURCE(res_plugtest_query,
"title=\"Resource accepting query parameters\"", "title=\"Resource accepting query parameters\"",
res_get_handler, res_get_handler,
NULL, NULL,
NULL, NULL,
NULL); NULL);
static void static void
res_get_handler(void* request, void* response, uint8_t *buffer, uint16_t preferred_size, int32_t *offset) res_get_handler(void *request, void *response, uint8_t *buffer, uint16_t preferred_size, int32_t *offset)
{ {
coap_packet_t * const coap_req = (coap_packet_t *) request; coap_packet_t *const coap_req = (coap_packet_t *)request;
int len = 0; int len = 0;
const char *query = NULL; const char *query = NULL;
PRINTF( PRINTF(
"/query GET (%s %u)\n", coap_req->type==COAP_TYPE_CON?"CON":"NON", coap_req->mid); "/query GET (%s %u)\n", coap_req->type == COAP_TYPE_CON ? "CON" : "NON", coap_req->mid);
if((len = REST.get_query(request, &query))) { if((len = REST.get_query(request, &query))) {
PRINTF("Query: %.*s\n", len, query); PRINTF("Query: %.*s\n", len, query);
} } /* Code 2.05 CONTENT is default. */
REST.set_header_content_type(response,
/* Code 2.05 CONTENT is default. */REST.set_header_content_type(response, REST.type.TEXT_PLAIN);
REST.type.TEXT_PLAIN); REST.set_response_payload(
REST.set_response_payload( response,
response, buffer,
buffer, snprintf((char *)buffer, MAX_PLUGFEST_PAYLOAD,
snprintf((char *) buffer, MAX_PLUGFEST_PAYLOAD, "Type: %u\nCode: %u\nMID: %u\nQuery: %.*s", coap_req->type,
"Type: %u\nCode: %u\nMID: %u\nQuery: %.*s", coap_req->type, coap_req->code, coap_req->mid, len, query));
coap_req->code, coap_req->mid, len, query)); }
}

View file

@ -1,135 +1,133 @@
/* /*
* Copyright (c) 2013, Institute for Pervasive Computing, ETH Zurich * Copyright (c) 2013, Institute for Pervasive Computing, ETH Zurich
* All rights reserved. * All rights reserved.
* *
* Redistribution and use in source and binary forms, with or without * Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions * modification, are permitted provided that the following conditions
* are met: * are met:
* 1. Redistributions of source code must retain the above copyright * 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer. * notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright * 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the * notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution. * documentation and/or other materials provided with the distribution.
* 3. Neither the name of the Institute nor the names of its contributors * 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 * may be used to endorse or promote products derived from this software
* without specific prior written permission. * without specific prior written permission.
* *
* THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * 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 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE. * SUCH DAMAGE.
* *
* This file is part of the Contiki operating system. * This file is part of the Contiki operating system.
*/ */
/** /**
* \file * \file
* ETSI Plugtest resource * ETSI Plugtest resource
* \author * \author
* Matthias Kovatsch <kovatsch@inf.ethz.ch> * Matthias Kovatsch <kovatsch@inf.ethz.ch>
*/ */
#include <string.h> #include <string.h>
#include "rest-engine.h" #include "rest-engine.h"
#include "er-coap.h" #include "er-coap.h"
#include "er-coap-transactions.h" #include "er-coap-transactions.h"
#include "er-coap-separate.h" #include "er-coap-separate.h"
#include "er-plugtest.h" #include "er-plugtest.h"
static void res_get_handler(void* request, void* response, uint8_t *buffer, uint16_t preferred_size, int32_t *offset); static void res_get_handler(void *request, void *response, uint8_t *buffer, uint16_t preferred_size, int32_t *offset);
static void res_resume_handler(void); static void res_resume_handler(void);
PERIODIC_RESOURCE(res_plugtest_separate, PERIODIC_RESOURCE(res_plugtest_separate,
"title=\"Resource which cannot be served immediately and which cannot be acknowledged in a piggy-backed way\"", "title=\"Resource which cannot be served immediately and which cannot be acknowledged in a piggy-backed way\"",
res_get_handler, res_get_handler,
NULL, NULL,
NULL, NULL,
NULL, NULL,
3*CLOCK_SECOND, 3 * CLOCK_SECOND,
res_resume_handler); res_resume_handler);
/* A structure to store the required information */ /* A structure to store the required information */
typedef struct application_separate_store typedef struct application_separate_store {
{ /* Provided by Erbium to store generic request information such as remote address and token. */
/* Provided by Erbium to store generic request information such as remote address and token. */ coap_separate_t request_metadata;
coap_separate_t request_metadata; /* Add fields for addition information to be stored for finalizing, e.g.: */
/* Add fields for addition information to be stored for finalizing, e.g.: */ char buffer[MAX_PLUGFEST_PAYLOAD];
char buffer[MAX_PLUGFEST_PAYLOAD]; } application_separate_store_t;
} application_separate_store_t;
static uint8_t separate_active = 0;
static uint8_t separate_active = 0; static application_separate_store_t separate_store[1];
static application_separate_store_t separate_store[1];
void
void res_get_handler(void *request, void *response, uint8_t *buffer, uint16_t preferred_size, int32_t *offset)
res_get_handler(void* request, void* response, uint8_t *buffer, uint16_t preferred_size, int32_t *offset) {
{ coap_packet_t *const coap_req = (coap_packet_t *)request;
coap_packet_t * const coap_req = (coap_packet_t *) request;
PRINTF("/separate ");
PRINTF("/separate "); if(separate_active) {
if(separate_active) { PRINTF("REJECTED ");
PRINTF("REJECTED "); coap_separate_reject();
coap_separate_reject(); } else {
} else { PRINTF("STORED ");
PRINTF("STORED "); separate_active = 1;
separate_active = 1;
/* Take over and skip response by engine. */
/* Take over and skip response by engine. */ coap_separate_accept(request, &separate_store->request_metadata);
coap_separate_accept(request, &separate_store->request_metadata); /* Be aware to respect the Block2 option, which is also stored in the coap_separate_t. */
/* Be aware to respect the Block2 option, which is also stored in the coap_separate_t. */
snprintf(separate_store->buffer, MAX_PLUGFEST_PAYLOAD,
snprintf(separate_store->buffer, MAX_PLUGFEST_PAYLOAD, "Type: %u\nCode: %u\nMID: %u", coap_req->type, coap_req->code,
"Type: %u\nCode: %u\nMID: %u", coap_req->type, coap_req->code, coap_req->mid);
coap_req->mid); }
}
PRINTF("(%s %u)\n", coap_req->type == COAP_TYPE_CON ? "CON" : "NON", coap_req->mid);
PRINTF("(%s %u)\n", coap_req->type==COAP_TYPE_CON?"CON":"NON", coap_req->mid); }
} static void
res_resume_handler()
static void {
res_resume_handler() if(separate_active) {
{ PRINTF("/separate ");
if(separate_active) { coap_transaction_t *transaction = NULL;
PRINTF("/separate "); if((transaction = coap_new_transaction(separate_store->request_metadata.mid,
coap_transaction_t *transaction = NULL; &separate_store->request_metadata.addr,
if((transaction = coap_new_transaction(separate_store->request_metadata.mid, separate_store->request_metadata.port))) {
&separate_store->request_metadata.addr, PRINTF(
separate_store->request_metadata.port))) { "RESPONSE (%s %u)\n", separate_store->request_metadata.type == COAP_TYPE_CON ? "CON" : "NON", separate_store->request_metadata.mid);
PRINTF(
"RESPONSE (%s %u)\n", separate_store->request_metadata.type==COAP_TYPE_CON?"CON":"NON", separate_store->request_metadata.mid); coap_packet_t response[1]; /* This way the packet can be treated as pointer as usual. */
coap_packet_t response[1]; /* This way the packet can be treated as pointer as usual. */ /* Restore the request information for the response. */
coap_separate_resume(response, &separate_store->request_metadata, CONTENT_2_05);
/* Restore the request information for the response. */
coap_separate_resume(response, &separate_store->request_metadata, CONTENT_2_05); REST.set_header_content_type(response, REST.type.TEXT_PLAIN);
coap_set_payload(response, separate_store->buffer,
REST.set_header_content_type(response, REST.type.TEXT_PLAIN); strlen(separate_store->buffer));
coap_set_payload(response, separate_store->buffer,
strlen(separate_store->buffer)); /*
* Be aware to respect the Block2 option, which is also stored in the coap_separate_t.
/* * As it is a critical option, this example resource pretends to handle it for compliance.
* Be aware to respect the Block2 option, which is also stored in the coap_separate_t. */
* As it is a critical option, this example resource pretends to handle it for compliance. coap_set_header_block2(response,
*/ separate_store->request_metadata.block2_num, 0,
coap_set_header_block2(response, separate_store->request_metadata.block2_size);
separate_store->request_metadata.block2_num, 0,
separate_store->request_metadata.block2_size); /* Warning: No check for serialization error. */
transaction->packet_len = coap_serialize_message(response,
/* Warning: No check for serialization error. */ transaction->packet);
transaction->packet_len = coap_serialize_message(response, coap_send_transaction(transaction);
transaction->packet); /* The engine will clear the transaction (right after send for NON, after acked for CON). */
coap_send_transaction(transaction);
/* The engine will clear the transaction (right after send for NON, after acked for CON). */ separate_active = 0;
} else {
separate_active = 0; PRINTF("ERROR (transaction)\n");
} else { }
PRINTF("ERROR (transaction)\n"); } /* if (separate_active) */
} }
} /* if (separate_active) */
}

323
examples/er-rest-example/resources/res-plugtest-test.c Executable file → Normal file
View file

@ -1,164 +1,159 @@
/* /*
* Copyright (c) 2013, Institute for Pervasive Computing, ETH Zurich * Copyright (c) 2013, Institute for Pervasive Computing, ETH Zurich
* All rights reserved. * All rights reserved.
* *
* Redistribution and use in source and binary forms, with or without * Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions * modification, are permitted provided that the following conditions
* are met: * are met:
* 1. Redistributions of source code must retain the above copyright * 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer. * notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright * 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the * notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution. * documentation and/or other materials provided with the distribution.
* 3. Neither the name of the Institute nor the names of its contributors * 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 * may be used to endorse or promote products derived from this software
* without specific prior written permission. * without specific prior written permission.
* *
* THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * 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 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE. * SUCH DAMAGE.
* *
* This file is part of the Contiki operating system. * This file is part of the Contiki operating system.
*/ */
/** /**
* \file * \file
* ETSI Plugtest resource * ETSI Plugtest resource
* \author * \author
* Matthias Kovatsch <kovatsch@inf.ethz.ch> * Matthias Kovatsch <kovatsch@inf.ethz.ch>
*/ */
#include <string.h> #include <string.h>
#include "rest-engine.h" #include "rest-engine.h"
#include "er-coap.h" #include "er-coap.h"
#include "er-plugtest.h" #include "er-plugtest.h"
static void res_get_handler(void* request, void* response, uint8_t *buffer, uint16_t preferred_size, int32_t *offset); static void res_get_handler(void *request, void *response, uint8_t *buffer, uint16_t preferred_size, int32_t *offset);
static void res_post_handler(void* request, void* response, uint8_t *buffer, uint16_t preferred_size, int32_t *offset); static void res_post_handler(void *request, void *response, uint8_t *buffer, uint16_t preferred_size, int32_t *offset);
static void res_put_handler(void* request, void* response, uint8_t *buffer, uint16_t preferred_size, int32_t *offset); static void res_put_handler(void *request, void *response, uint8_t *buffer, uint16_t preferred_size, int32_t *offset);
static void res_delete_handler(void* request, void* response, uint8_t *buffer, uint16_t preferred_size, int32_t *offset); static void res_delete_handler(void *request, void *response, uint8_t *buffer, uint16_t preferred_size, int32_t *offset);
RESOURCE(res_plugtest_test, "title=\"Default test resource\"", res_get_handler, res_post_handler, res_put_handler, res_delete_handler); RESOURCE(res_plugtest_test, "title=\"Default test resource\"", res_get_handler, res_post_handler, res_put_handler, res_delete_handler);
static uint8_t test_etag[8] = { 0 }; static uint8_t test_etag[8] = { 0 };
static uint8_t test_etag_len = 1; static uint8_t test_etag_len = 1;
static uint8_t test_change = 1; static uint8_t test_change = 1;
static uint8_t test_none_match_okay = 1; static uint8_t test_none_match_okay = 1;
static const uint8_t *bytes = NULL; static const uint8_t *bytes = NULL;
static size_t len = 0; static size_t len = 0;
static void static void
test_update_etag() test_update_etag()
{ {
int i; int i;
test_etag_len = (random_rand() % 8) + 1; test_etag_len = (random_rand() % 8) + 1;
for(i = 0; i < test_etag_len; ++i) { for(i = 0; i < test_etag_len; ++i) {
test_etag[i] = random_rand(); test_etag[i] = random_rand();
} }
test_change = 0; test_change = 0;
PRINTF("### SERVER ACTION ### Changed ETag %u [0x%02X%02X%02X%02X%02X%02X%02X%02X]\n", test_etag_len, test_etag[0], test_etag[1], test_etag[2], test_etag[3], test_etag[4], test_etag[5], test_etag[6], test_etag[7]); PRINTF("### SERVER ACTION ### Changed ETag %u [0x%02X%02X%02X%02X%02X%02X%02X%02X]\n", test_etag_len, test_etag[0], test_etag[1], test_etag[2], test_etag[3], test_etag[4], test_etag[5], test_etag[6], test_etag[7]);
} }
static void
static void res_get_handler(void *request, void *response, uint8_t *buffer, uint16_t preferred_size, int32_t *offset)
res_get_handler(void* request, void* response, uint8_t *buffer, uint16_t preferred_size, int32_t *offset) {
{ coap_packet_t *const coap_req = (coap_packet_t *)request;
coap_packet_t * const coap_req = (coap_packet_t *) request;
if(test_change) {
if(test_change) { test_update_etag();
test_update_etag(); }
} PRINTF("/test GET (%s %u)\n", coap_req->type == COAP_TYPE_CON ? "CON" : "NON", coap_req->mid);
PRINTF("/test GET (%s %u)\n", coap_req->type==COAP_TYPE_CON?"CON":"NON", coap_req->mid); if((len = coap_get_header_etag(request, &bytes)) > 0
&& len == test_etag_len
if((len = coap_get_header_etag(request, &bytes)) > 0 && memcmp(test_etag, bytes, len) == 0) {
&& len == test_etag_len PRINTF("validate ");
&& memcmp(test_etag, bytes, len) == 0) { REST.set_response_status(response, REST.status.NOT_MODIFIED);
PRINTF("validate "); REST.set_header_etag(response, test_etag, test_etag_len);
REST.set_response_status(response, REST.status.NOT_MODIFIED);
REST.set_header_etag(response, test_etag, test_etag_len); test_change = 1;
PRINTF("### SERVER ACTION ### Resource will change\n");
test_change = 1; } else {
PRINTF("### SERVER ACTION ### Resource will change\n"); /* Code 2.05 CONTENT is default. */
} else { REST.set_header_content_type(response, REST.type.TEXT_PLAIN);
/* Code 2.05 CONTENT is default. */ REST.set_header_etag(response, test_etag, test_etag_len);
REST.set_header_content_type(response, REST.type.TEXT_PLAIN); REST.set_header_max_age(response, 30);
REST.set_header_etag(response, test_etag, test_etag_len); REST.set_response_payload(
REST.set_header_max_age(response, 30); response,
REST.set_response_payload( buffer,
response, snprintf((char *)buffer, MAX_PLUGFEST_PAYLOAD, "Type: %u\nCode: %u\nMID: %u", coap_req->type, coap_req->code, coap_req->mid));
buffer, }
snprintf((char *) buffer, MAX_PLUGFEST_PAYLOAD, "Type: %u\nCode: %u\nMID: %u", coap_req->type, coap_req->code, coap_req->mid)); }
} static void
} res_post_handler(void *request, void *response, uint8_t *buffer, uint16_t preferred_size, int32_t *offset)
{
static void coap_packet_t *const coap_req = (coap_packet_t *)request;
res_post_handler(void* request, void* response, uint8_t *buffer, uint16_t preferred_size, int32_t *offset)
{ PRINTF("/test POST (%s %u)\n", coap_req->type == COAP_TYPE_CON ? "CON" : "NON", coap_req->mid);
coap_packet_t * const coap_req = (coap_packet_t *) request; REST.set_response_status(response, REST.status.CREATED);
REST.set_header_location(response, "/location1/location2/location3");
PRINTF("/test POST (%s %u)\n", coap_req->type==COAP_TYPE_CON?"CON":"NON", coap_req->mid); }
REST.set_response_status(response, REST.status.CREATED); static void
REST.set_header_location(response, "/location1/location2/location3"); res_put_handler(void *request, void *response, uint8_t *buffer, uint16_t preferred_size, int32_t *offset)
} {
coap_packet_t *const coap_req = (coap_packet_t *)request;
static void
res_put_handler(void* request, void* response, uint8_t *buffer, uint16_t preferred_size, int32_t *offset) PRINTF("/test PUT (%s %u)\n", coap_req->type == COAP_TYPE_CON ? "CON" : "NON", coap_req->mid);
{
coap_packet_t * const coap_req = (coap_packet_t *) request; if(coap_get_header_if_none_match(request)) {
if(test_none_match_okay) {
PRINTF("/test PUT (%s %u)\n", coap_req->type==COAP_TYPE_CON?"CON":"NON", coap_req->mid); REST.set_response_status(response, REST.status.CREATED);
if(coap_get_header_if_none_match(request)) { test_none_match_okay = 0;
if(test_none_match_okay) { PRINTF("### SERVER ACTION ### If-None-Match will FAIL\n");
REST.set_response_status(response, REST.status.CREATED); } else {
REST.set_response_status(response, PRECONDITION_FAILED_4_12);
test_none_match_okay = 0;
PRINTF("### SERVER ACTION ### If-None-Match will FAIL\n"); test_none_match_okay = 1;
} else { PRINTF("### SERVER ACTION ### If-None-Match will SUCCEED\n");
REST.set_response_status(response, PRECONDITION_FAILED_4_12); }
} else if(((len = coap_get_header_if_match(request, &bytes)) > 0
test_none_match_okay = 1; && (len == test_etag_len
PRINTF("### SERVER ACTION ### If-None-Match will SUCCEED\n"); && memcmp(test_etag, bytes, len) == 0))
} || len == 0) {
} else if(((len = coap_get_header_if_match(request, &bytes)) > 0 test_update_etag();
&& (len == test_etag_len REST.set_header_etag(response, test_etag, test_etag_len);
&& memcmp(test_etag, bytes, len) == 0))
|| len == 0) { REST.set_response_status(response, REST.status.CHANGED);
test_update_etag();
REST.set_header_etag(response, test_etag, test_etag_len); if(len > 0) {
test_change = 1;
REST.set_response_status(response, REST.status.CHANGED); PRINTF("### SERVER ACTION ### Resource will change\n");
}
if(len > 0) { } else {
test_change = 1; PRINTF("Check %u/%u\n [0x%02X%02X%02X%02X%02X%02X%02X%02X]\n [0x%02X%02X%02X%02X%02X%02X%02X%02X]\n",
PRINTF("### SERVER ACTION ### Resource will change\n"); len,
} test_etag_len,
} else { bytes[0], bytes[1], bytes[2], bytes[3], bytes[4], bytes[5], bytes[6], bytes[7],
PRINTF("Check %u/%u\n [0x%02X%02X%02X%02X%02X%02X%02X%02X]\n [0x%02X%02X%02X%02X%02X%02X%02X%02X]\n", test_etag[0], test_etag[1], test_etag[2], test_etag[3], test_etag[4], test_etag[5], test_etag[6], test_etag[7]);
len,
test_etag_len, REST.set_response_status(response, PRECONDITION_FAILED_4_12);
bytes[0], bytes[1], bytes[2], bytes[3], bytes[4], bytes[5], bytes[6], bytes[7], }
test_etag[0], test_etag[1], test_etag[2], test_etag[3], test_etag[4], test_etag[5], test_etag[6], test_etag[7]); }
static void
REST.set_response_status(response, PRECONDITION_FAILED_4_12); res_delete_handler(void *request, void *response, uint8_t *buffer, uint16_t preferred_size, int32_t *offset)
} {
} coap_packet_t *const coap_req = (coap_packet_t *)request;
static void PRINTF("/test DELETE (%s %u)\n", coap_req->type == COAP_TYPE_CON ? "CON" : "NON", coap_req->mid);
res_delete_handler(void* request, void* response, uint8_t *buffer, uint16_t preferred_size, int32_t *offset) REST.set_response_status(response, REST.status.DELETED);
{ }
coap_packet_t * const coap_req = (coap_packet_t *) request;
PRINTF("/test DELETE (%s %u)\n", coap_req->type==COAP_TYPE_CON?"CON":"NON", coap_req->mid);
REST.set_response_status(response, REST.status.DELETED);
}

View file

@ -1,141 +1,137 @@
/* /*
* Copyright (c) 2013, Institute for Pervasive Computing, ETH Zurich * Copyright (c) 2013, Institute for Pervasive Computing, ETH Zurich
* All rights reserved. * All rights reserved.
* *
* Redistribution and use in source and binary forms, with or without * Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions * modification, are permitted provided that the following conditions
* are met: * are met:
* 1. Redistributions of source code must retain the above copyright * 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer. * notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright * 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the * notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution. * documentation and/or other materials provided with the distribution.
* 3. Neither the name of the Institute nor the names of its contributors * 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 * may be used to endorse or promote products derived from this software
* without specific prior written permission. * without specific prior written permission.
* *
* THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * 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 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE. * SUCH DAMAGE.
* *
* This file is part of the Contiki operating system. * This file is part of the Contiki operating system.
*/ */
/** /**
* \file * \file
* ETSI Plugtest resource * ETSI Plugtest resource
* \author * \author
* Matthias Kovatsch <kovatsch@inf.ethz.ch> * Matthias Kovatsch <kovatsch@inf.ethz.ch>
*/ */
#include <string.h> #include <string.h>
#include "rest-engine.h" #include "rest-engine.h"
#include "er-coap.h" #include "er-coap.h"
#include "er-plugtest.h" #include "er-plugtest.h"
static void res_get_handler(void* request, void* response, uint8_t *buffer, uint16_t preferred_size, int32_t *offset); static void res_get_handler(void *request, void *response, uint8_t *buffer, uint16_t preferred_size, int32_t *offset);
static void res_put_handler(void* request, void* response, uint8_t *buffer, uint16_t preferred_size, int32_t *offset); static void res_put_handler(void *request, void *response, uint8_t *buffer, uint16_t preferred_size, int32_t *offset);
RESOURCE(res_plugtest_validate, RESOURCE(res_plugtest_validate,
"title=\"Validation test resource\"", "title=\"Validation test resource\"",
res_get_handler, res_get_handler,
NULL, NULL,
res_put_handler, res_put_handler,
NULL); NULL);
static uint8_t validate_etag[8] = { 0 }; static uint8_t validate_etag[8] = { 0 };
static uint8_t validate_etag_len = 1; static uint8_t validate_etag_len = 1;
static uint8_t validate_change = 1; static uint8_t validate_change = 1;
static const uint8_t *bytes = NULL;
static const uint8_t *bytes = NULL; static size_t len = 0;
static size_t len = 0;
static void
static void validate_update_etag()
validate_update_etag() {
{ int i;
int i; validate_etag_len = (random_rand() % 8) + 1;
validate_etag_len = (random_rand() % 8) + 1; for(i = 0; i < validate_etag_len; ++i) {
for(i = 0; i < validate_etag_len; ++i) { validate_etag[i] = random_rand();
validate_etag[i] = random_rand(); }
} validate_change = 0;
validate_change = 0;
PRINTF("### SERVER ACTION ### Changed ETag %u [0x%02X%02X%02X%02X%02X%02X%02X%02X]\n",
PRINTF("### SERVER ACTION ### Changed ETag %u [0x%02X%02X%02X%02X%02X%02X%02X%02X]\n", validate_etag_len, validate_etag[0], validate_etag[1], validate_etag[2], validate_etag[3], validate_etag[4], validate_etag[5], validate_etag[6], validate_etag[7]);
validate_etag_len, validate_etag[0], validate_etag[1], validate_etag[2], validate_etag[3], validate_etag[4], validate_etag[5], validate_etag[6], validate_etag[7]); }
} static void
res_get_handler(void *request, void *response, uint8_t *buffer, uint16_t preferred_size, int32_t *offset)
static void {
res_get_handler(void* request, void* response, uint8_t *buffer, uint16_t preferred_size, int32_t *offset) coap_packet_t *const coap_req = (coap_packet_t *)request;
{
coap_packet_t * const coap_req = (coap_packet_t *) request; if(validate_change) {
validate_update_etag();
if(validate_change) { }
validate_update_etag(); PRINTF("/validate GET");
} PRINTF("(%s %u)\n", coap_req->type == COAP_TYPE_CON ? "CON" : "NON", coap_req->mid);
PRINTF("/validate GET"); if((len = coap_get_header_etag(request, &bytes)) > 0
PRINTF("(%s %u)\n", coap_req->type==COAP_TYPE_CON?"CON":"NON", coap_req->mid); && len == validate_etag_len && memcmp(validate_etag, bytes, len) == 0) {
PRINTF("validate ");
if((len = coap_get_header_etag(request, &bytes)) > 0 REST.set_response_status(response, REST.status.NOT_MODIFIED);
&& len == validate_etag_len && memcmp(validate_etag, bytes, len) == 0) { REST.set_header_etag(response, validate_etag, validate_etag_len);
PRINTF("validate ");
REST.set_response_status(response, REST.status.NOT_MODIFIED); validate_change = 1;
REST.set_header_etag(response, validate_etag, validate_etag_len); PRINTF("### SERVER ACTION ### Resouce will change\n");
} else {
validate_change = 1; /* Code 2.05 CONTENT is default. */
PRINTF("### SERVER ACTION ### Resouce will change\n"); REST.set_header_content_type(response, REST.type.TEXT_PLAIN);
} else { REST.set_header_etag(response, validate_etag, validate_etag_len);
/* Code 2.05 CONTENT is default. */ REST.set_header_max_age(response, 30);
REST.set_header_content_type(response, REST.type.TEXT_PLAIN); REST.set_response_payload(
REST.set_header_etag(response, validate_etag, validate_etag_len); response,
REST.set_header_max_age(response, 30); buffer,
REST.set_response_payload( snprintf((char *)buffer, MAX_PLUGFEST_PAYLOAD,
response, "Type: %u\nCode: %u\nMID: %u", coap_req->type, coap_req->code,
buffer, coap_req->mid));
snprintf((char *) buffer, MAX_PLUGFEST_PAYLOAD, }
"Type: %u\nCode: %u\nMID: %u", coap_req->type, coap_req->code, }
coap_req->mid)); static void
} res_put_handler(void *request, void *response, uint8_t *buffer, uint16_t preferred_size, int32_t *offset)
} {
coap_packet_t *const coap_req = (coap_packet_t *)request;
static void
res_put_handler(void* request, void* response, uint8_t *buffer, uint16_t preferred_size, int32_t *offset) PRINTF("/validate PUT ");
{ PRINTF("(%s %u)\n", coap_req->type == COAP_TYPE_CON ? "CON" : "NON", coap_req->mid);
coap_packet_t * const coap_req = (coap_packet_t *) request;
if(((len = coap_get_header_if_match(request, &bytes)) > 0
PRINTF("/validate PUT "); && (len == validate_etag_len
PRINTF("(%s %u)\n", coap_req->type==COAP_TYPE_CON?"CON":"NON", coap_req->mid); && memcmp(validate_etag, bytes, len) == 0))
|| len == 0) {
if(((len = coap_get_header_if_match(request, &bytes)) > 0 validate_update_etag();
&& (len == validate_etag_len REST.set_header_etag(response, validate_etag, validate_etag_len);
&& memcmp(validate_etag, bytes, len) == 0))
|| len == 0) { REST.set_response_status(response, REST.status.CHANGED);
validate_update_etag();
REST.set_header_etag(response, validate_etag, validate_etag_len); if(len > 0) {
validate_change = 1;
REST.set_response_status(response, REST.status.CHANGED); PRINTF("### SERVER ACTION ### Resouce will change\n");
}
if(len > 0) { } else {
validate_change = 1; PRINTF(
PRINTF("### SERVER ACTION ### Resouce will change\n"); "Check %u/%u\n [0x%02X%02X%02X%02X%02X%02X%02X%02X]\n [0x%02X%02X%02X%02X%02X%02X%02X%02X] ",
} len,
} else { validate_etag_len,
PRINTF( bytes[0], bytes[1], bytes[2], bytes[3], bytes[4], bytes[5], bytes[6], bytes[7],
"Check %u/%u\n [0x%02X%02X%02X%02X%02X%02X%02X%02X]\n [0x%02X%02X%02X%02X%02X%02X%02X%02X] ", validate_etag[0], validate_etag[1], validate_etag[2], validate_etag[3], validate_etag[4], validate_etag[5], validate_etag[6], validate_etag[7]);
len,
validate_etag_len, REST.set_response_status(response, PRECONDITION_FAILED_4_12);
bytes[0], bytes[1], bytes[2], bytes[3], bytes[4], bytes[5], bytes[6], bytes[7], }
validate_etag[0], validate_etag[1], validate_etag[2], validate_etag[3], validate_etag[4], validate_etag[5], validate_etag[6], validate_etag[7]); }
REST.set_response_status(response, PRECONDITION_FAILED_4_12);
}
}

179
examples/er-rest-example/resources/res-push.c Executable file → Normal file
View file

@ -1,90 +1,89 @@
/* /*
* Copyright (c) 2013, Institute for Pervasive Computing, ETH Zurich * Copyright (c) 2013, Institute for Pervasive Computing, ETH Zurich
* All rights reserved. * All rights reserved.
* *
* Redistribution and use in source and binary forms, with or without * Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions * modification, are permitted provided that the following conditions
* are met: * are met:
* 1. Redistributions of source code must retain the above copyright * 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer. * notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright * 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the * notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution. * documentation and/or other materials provided with the distribution.
* 3. Neither the name of the Institute nor the names of its contributors * 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 * may be used to endorse or promote products derived from this software
* without specific prior written permission. * without specific prior written permission.
* *
* THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * 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 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE. * SUCH DAMAGE.
* *
* This file is part of the Contiki operating system. * This file is part of the Contiki operating system.
*/ */
/** /**
* \file * \file
* Example resource * Example resource
* \author * \author
* Matthias Kovatsch <kovatsch@inf.ethz.ch> * Matthias Kovatsch <kovatsch@inf.ethz.ch>
*/ */
#include <string.h> #include <string.h>
#include "rest-engine.h" #include "rest-engine.h"
#include "er-coap.h" #include "er-coap.h"
static void res_get_handler(void* request, void* response, uint8_t *buffer, uint16_t preferred_size, int32_t *offset); static void res_get_handler(void *request, void *response, uint8_t *buffer, uint16_t preferred_size, int32_t *offset);
static void res_periodic_handler(void); static void res_periodic_handler(void);
PERIODIC_RESOURCE(res_push, PERIODIC_RESOURCE(res_push,
"title=\"Periodic demo\";obs", "title=\"Periodic demo\";obs",
res_get_handler, res_get_handler,
NULL, NULL,
NULL, NULL,
NULL, NULL,
5*CLOCK_SECOND, 5 * CLOCK_SECOND,
res_periodic_handler); res_periodic_handler);
/* /*
* Use local resource state that is accessed by res_get_handler() and altered by res_periodic_handler() or PUT or POST. * Use local resource state that is accessed by res_get_handler() and altered by res_periodic_handler() or PUT or POST.
*/ */
static int32_t event_counter = 0; static int32_t event_counter = 0;
static void static void
res_get_handler(void* request, void* response, uint8_t *buffer, uint16_t preferred_size, int32_t *offset) res_get_handler(void *request, void *response, uint8_t *buffer, uint16_t preferred_size, int32_t *offset)
{ {
/* /*
* For minimal complexity, request query and options should be ignored for GET on observable resources. * For minimal complexity, request query and options should be ignored for GET on observable resources.
* Otherwise the requests must be stored with the observer list and passed by REST.notify_subscribers(). * Otherwise the requests must be stored with the observer list and passed by REST.notify_subscribers().
* This would be a TODO in the corresponding files in contiki/apps/erbium/! * This would be a TODO in the corresponding files in contiki/apps/erbium/!
*/ */
REST.set_header_content_type(response, REST.type.TEXT_PLAIN); REST.set_header_content_type(response, REST.type.TEXT_PLAIN);
REST.set_header_max_age(response, res_push.periodic->period/CLOCK_SECOND); REST.set_header_max_age(response, res_push.periodic->period / CLOCK_SECOND);
REST.set_response_payload(response, buffer, snprintf((char *)buffer, preferred_size, "VERY LONG EVENT %lu", event_counter)); REST.set_response_payload(response, buffer, snprintf((char *)buffer, preferred_size, "VERY LONG EVENT %lu", event_counter));
/* The REST.subscription_handler() will be called for observable resources by the REST framework. */ /* The REST.subscription_handler() will be called for observable resources by the REST framework. */
} }
/*
/* * Additionally, a handler function named [resource name]_handler must be implemented for each PERIODIC_RESOURCE.
* Additionally, a handler function named [resource name]_handler must be implemented for each PERIODIC_RESOURCE. * It will be called by the REST manager process with the defined period.
* It will be called by the REST manager process with the defined period. */
*/ static void
static void res_periodic_handler()
res_periodic_handler() {
{ /* Do a periodic task here, e.g., sampling a sensor. */
/* Do a periodic task here, e.g., sampling a sensor. */ ++event_counter;
++event_counter;
/* Usually a condition is defined under with subscribers are notified, e.g., large enough delta in sensor reading. */
/* Usually a condition is defined under with subscribers are notified, e.g., large enough delta in sensor reading. */ if(1) {
if(1) { /* Notify the registered observers which will trigger the res_get_handler to create the response. */
/* Notify the registered observers which will trigger the res_get_handler to create the response. */ REST.notify_subscribers(&res_push);
REST.notify_subscribers(&res_push); }
} }
}

208
examples/er-rest-example/resources/res-radio.c Executable file → Normal file
View file

@ -1,106 +1,102 @@
/* /*
* Copyright (c) 2013, Institute for Pervasive Computing, ETH Zurich * Copyright (c) 2013, Institute for Pervasive Computing, ETH Zurich
* All rights reserved. * All rights reserved.
* *
* Redistribution and use in source and binary forms, with or without * Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions * modification, are permitted provided that the following conditions
* are met: * are met:
* 1. Redistributions of source code must retain the above copyright * 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer. * notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright * 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the * notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution. * documentation and/or other materials provided with the distribution.
* 3. Neither the name of the Institute nor the names of its contributors * 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 * may be used to endorse or promote products derived from this software
* without specific prior written permission. * without specific prior written permission.
* *
* THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * 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 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE. * SUCH DAMAGE.
* *
* This file is part of the Contiki operating system. * This file is part of the Contiki operating system.
*/ */
/** /**
* \file * \file
* Example resource * Example resource
* \author * \author
* Matthias Kovatsch <kovatsch@inf.ethz.ch> * Matthias Kovatsch <kovatsch@inf.ethz.ch>
*/ */
#include "contiki.h" #include "contiki.h"
#if PLATFORM_HAS_RADIO #if PLATFORM_HAS_RADIO
#include <string.h> #include <string.h>
#include "rest-engine.h" #include "rest-engine.h"
#include "dev/radio-sensor.h" #include "dev/radio-sensor.h"
static void res_get_handler(void* request, void* response, uint8_t *buffer, uint16_t preferred_size, int32_t *offset); static void res_get_handler(void *request, void *response, uint8_t *buffer, uint16_t preferred_size, int32_t *offset);
/* A simple getter example. Returns the reading of the rssi/lqi from radio sensor */ /* A simple getter example. Returns the reading of the rssi/lqi from radio sensor */
RESOURCE(res_radio, RESOURCE(res_radio,
"title=\"RADIO: ?p=lqi|rssi\";rt=\"RadioSensor\"", "title=\"RADIO: ?p=lqi|rssi\";rt=\"RadioSensor\"",
res_get_handler, res_get_handler,
NULL, NULL,
NULL, NULL,
NULL); NULL);
static void static void
res_get_handler(void* request, void* response, uint8_t *buffer, uint16_t preferred_size, int32_t *offset) res_get_handler(void *request, void *response, uint8_t *buffer, uint16_t preferred_size, int32_t *offset)
{ {
size_t len = 0; size_t len = 0;
const char *p = NULL; const char *p = NULL;
uint8_t param = 0; uint8_t param = 0;
int success = 1; int success = 1;
unsigned int accept = -1; unsigned int accept = -1;
REST.get_header_accept(request, &accept); REST.get_header_accept(request, &accept);
if((len=REST.get_query_variable(request, "p", &p))) { if((len = REST.get_query_variable(request, "p", &p))) {
if(strncmp(p, "lqi", len)==0) { if(strncmp(p, "lqi", len) == 0) {
param = RADIO_SENSOR_LAST_VALUE; param = RADIO_SENSOR_LAST_VALUE;
} else if(strncmp(p,"rssi", len)==0) { } else if(strncmp(p, "rssi", len) == 0) {
param = RADIO_SENSOR_LAST_PACKET; param = RADIO_SENSOR_LAST_PACKET;
} else { } else {
success = 0; success = 0;
} }
} else { } else {
success = 0; success = 0;
} } if(success) {
if(accept == -1 || accept == REST.type.TEXT_PLAIN) {
if(success) { REST.set_header_content_type(response, REST.type.TEXT_PLAIN);
if(accept==-1 || accept==REST.type.TEXT_PLAIN) { snprintf((char *)buffer, REST_MAX_CHUNK_SIZE, "%d", radio_sensor.value(param));
REST.set_header_content_type(response, REST.type.TEXT_PLAIN);
snprintf((char *)buffer, REST_MAX_CHUNK_SIZE, "%d", radio_sensor.value(param)); REST.set_response_payload(response, (uint8_t *)buffer, strlen((char *)buffer));
} else if(accept == REST.type.APPLICATION_JSON) {
REST.set_response_payload(response, (uint8_t *)buffer, strlen((char *)buffer)); REST.set_header_content_type(response, REST.type.APPLICATION_JSON);
} else if(accept==REST.type.APPLICATION_JSON) {
REST.set_header_content_type(response, REST.type.APPLICATION_JSON); if(param == RADIO_SENSOR_LAST_VALUE) {
snprintf((char *)buffer, REST_MAX_CHUNK_SIZE, "{'lqi':%d}", radio_sensor.value(param));
if(param == RADIO_SENSOR_LAST_VALUE) { } else if(param == RADIO_SENSOR_LAST_PACKET) {
snprintf((char *)buffer, REST_MAX_CHUNK_SIZE, "{'lqi':%d}", radio_sensor.value(param)); snprintf((char *)buffer, REST_MAX_CHUNK_SIZE, "{'rssi':%d}", radio_sensor.value(param));
} else if(param == RADIO_SENSOR_LAST_PACKET) { }
snprintf((char *)buffer, REST_MAX_CHUNK_SIZE, "{'rssi':%d}", radio_sensor.value(param)); REST.set_response_payload(response, buffer, strlen((char *)buffer));
} } else {
REST.set_response_status(response, REST.status.NOT_ACCEPTABLE);
REST.set_response_payload(response, buffer, strlen((char *)buffer)); const char *msg = "Supporting content-types text/plain and application/json";
} else { REST.set_response_payload(response, msg, strlen(msg));
REST.set_response_status(response, REST.status.NOT_ACCEPTABLE); }
const char *msg = "Supporting content-types text/plain and application/json"; } else {
REST.set_response_payload(response, msg, strlen(msg)); REST.set_response_status(response, REST.status.BAD_REQUEST);
} }
} else { }
REST.set_response_status(response, REST.status.BAD_REQUEST); #endif /* PLATFORM_HAS_RADIO */
}
}
#endif /* PLATFORM_HAS_RADIO */

256
examples/er-rest-example/resources/res-separate.c Executable file → Normal file
View file

@ -1,129 +1,127 @@
/* /*
* Copyright (c) 2013, Institute for Pervasive Computing, ETH Zurich * Copyright (c) 2013, Institute for Pervasive Computing, ETH Zurich
* All rights reserved. * All rights reserved.
* *
* Redistribution and use in source and binary forms, with or without * Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions * modification, are permitted provided that the following conditions
* are met: * are met:
* 1. Redistributions of source code must retain the above copyright * 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer. * notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright * 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the * notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution. * documentation and/or other materials provided with the distribution.
* 3. Neither the name of the Institute nor the names of its contributors * 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 * may be used to endorse or promote products derived from this software
* without specific prior written permission. * without specific prior written permission.
* *
* THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * 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 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE. * SUCH DAMAGE.
* *
* This file is part of the Contiki operating system. * This file is part of the Contiki operating system.
*/ */
/** /**
* \file * \file
* Example resource * Example resource
* \author * \author
* Matthias Kovatsch <kovatsch@inf.ethz.ch> * Matthias Kovatsch <kovatsch@inf.ethz.ch>
*/ */
#include <string.h> #include <string.h>
#include "rest-engine.h" #include "rest-engine.h"
#include "er-coap-separate.h" #include "er-coap-separate.h"
#include "er-coap-transactions.h" #include "er-coap-transactions.h"
static void res_get_handler(void* request, void* response, uint8_t *buffer, uint16_t preferred_size, int32_t *offset); static void res_get_handler(void *request, void *response, uint8_t *buffer, uint16_t preferred_size, int32_t *offset);
static void res_resume_handler(void); static void res_resume_handler(void);
SEPARATE_RESOURCE(res_separate, SEPARATE_RESOURCE(res_separate,
"title=\"Separate demo\"", "title=\"Separate demo\"",
res_get_handler, res_get_handler,
NULL, NULL,
NULL, NULL,
NULL, NULL,
res_resume_handler); res_resume_handler);
/* A structure to store the information required for the separate handler */ /* A structure to store the information required for the separate handler */
typedef struct application_separate_store { typedef struct application_separate_store {
/* Provided by Erbium to store generic request information such as remote address and token. */ /* Provided by Erbium to store generic request information such as remote address and token. */
coap_separate_t request_metadata; coap_separate_t request_metadata;
/* Add fields for addition information to be stored for finalizing, e.g.: */ /* Add fields for addition information to be stored for finalizing, e.g.: */
char buffer[16]; char buffer[16];
} application_separate_store_t;
} application_separate_store_t;
#define COAP_MAX_OPEN_SEPARATE 2
#define COAP_MAX_OPEN_SEPARATE 2
static uint8_t separate_active = 0;
static uint8_t separate_active = 0; static application_separate_store_t separate_store[COAP_MAX_OPEN_SEPARATE];
static application_separate_store_t separate_store[COAP_MAX_OPEN_SEPARATE];
static void
static void res_get_handler(void *request, void *response, uint8_t *buffer, uint16_t preferred_size, int32_t *offset)
res_get_handler(void* request, void* response, uint8_t *buffer, uint16_t preferred_size, int32_t *offset) {
{ /*
/* * Example allows only one open separate response.
* Example allows only one open separate response. * For multiple, the application must manage the list of stores.
* For multiple, the application must manage the list of stores. */
*/ if(separate_active >= COAP_MAX_OPEN_SEPARATE) {
if (separate_active>=COAP_MAX_OPEN_SEPARATE) { coap_separate_reject();
coap_separate_reject(); } else {
} else { ++separate_active;
++separate_active;
/* Take over and skip response by engine. */
/* Take over and skip response by engine. */ coap_separate_accept(request, &separate_store->request_metadata);
coap_separate_accept(request, &separate_store->request_metadata); /* Be aware to respect the Block2 option, which is also stored in the coap_separate_t. */
/* Be aware to respect the Block2 option, which is also stored in the coap_separate_t. */
/*
/* * At the moment, only the minimal information is stored in the store (client address, port, token, MID, type, and Block2).
* At the moment, only the minimal information is stored in the store (client address, port, token, MID, type, and Block2). * Extend the store, if the application requires additional information from this handler.
* Extend the store, if the application requires additional information from this handler. * buffer is an example field for custom information.
* buffer is an example field for custom information. */
*/ snprintf(separate_store->buffer, sizeof(separate_store->buffer), "StoredInfo");
snprintf(separate_store->buffer, sizeof(separate_store->buffer), "StoredInfo"); }
} }
} static void
res_resume_handler()
static void {
res_resume_handler() if(separate_active) {
{ coap_transaction_t *transaction = NULL;
if(separate_active) { if((transaction = coap_new_transaction(separate_store->request_metadata.mid, &separate_store->request_metadata.addr, separate_store->request_metadata.port))) {
coap_transaction_t *transaction = NULL; coap_packet_t response[1]; /* This way the packet can be treated as pointer as usual. */
if( (transaction = coap_new_transaction(separate_store->request_metadata.mid, &separate_store->request_metadata.addr, separate_store->request_metadata.port)) ) {
coap_packet_t response[1]; /* This way the packet can be treated as pointer as usual. */ /* Restore the request information for the response. */
coap_separate_resume(response, &separate_store->request_metadata, REST.status.OK);
/* Restore the request information for the response. */
coap_separate_resume(response, &separate_store->request_metadata, REST.status.OK); coap_set_payload(response, separate_store->buffer, strlen(separate_store->buffer));
coap_set_payload(response, separate_store->buffer, strlen(separate_store->buffer)); /*
* Be aware to respect the Block2 option, which is also stored in the coap_separate_t.
/* * As it is a critical option, this example resource pretends to handle it for compliance.
* Be aware to respect the Block2 option, which is also stored in the coap_separate_t. */
* As it is a critical option, this example resource pretends to handle it for compliance. coap_set_header_block2(response, separate_store->request_metadata.block2_num, 0, separate_store->request_metadata.block2_size);
*/
coap_set_header_block2(response, separate_store->request_metadata.block2_num, 0, separate_store->request_metadata.block2_size); /* Warning: No check for serialization error. */
transaction->packet_len = coap_serialize_message(response, transaction->packet);
/* Warning: No check for serialization error. */ coap_send_transaction(transaction);
transaction->packet_len = coap_serialize_message(response, transaction->packet); /* The engine will clear the transaction (right after send for NON, after acked for CON). */
coap_send_transaction(transaction);
/* The engine will clear the transaction (right after send for NON, after acked for CON). */ /* FIXME there could me more! */
separate_active = 0;
//FIXME there could me more! } else {
separate_active = 0; /*
} else { * Set timer for retry, send error message, ...
/* * The example simply waits for another button press.
* Set timer for retry, send error message, ... */
* The example simply waits for another button press. }
*/ } /* if (separate_active) */
} }
} /* if (separate_active) */
}

140
examples/er-rest-example/resources/res-sub.c Executable file → Normal file
View file

@ -1,71 +1,69 @@
/* /*
* Copyright (c) 2013, Institute for Pervasive Computing, ETH Zurich * Copyright (c) 2013, Institute for Pervasive Computing, ETH Zurich
* All rights reserved. * All rights reserved.
* *
* Redistribution and use in source and binary forms, with or without * Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions * modification, are permitted provided that the following conditions
* are met: * are met:
* 1. Redistributions of source code must retain the above copyright * 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer. * notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright * 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the * notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution. * documentation and/or other materials provided with the distribution.
* 3. Neither the name of the Institute nor the names of its contributors * 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 * may be used to endorse or promote products derived from this software
* without specific prior written permission. * without specific prior written permission.
* *
* THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * 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 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE. * SUCH DAMAGE.
* *
* This file is part of the Contiki operating system. * This file is part of the Contiki operating system.
*/ */
/** /**
* \file * \file
* Example resource * Example resource
* \author * \author
* Matthias Kovatsch <kovatsch@inf.ethz.ch> * Matthias Kovatsch <kovatsch@inf.ethz.ch>
*/ */
#include <string.h> #include <string.h>
#include "rest-engine.h" #include "rest-engine.h"
static void res_get_handler(void* request, void* response, uint8_t *buffer, uint16_t preferred_size, int32_t *offset); static void res_get_handler(void *request, void *response, uint8_t *buffer, uint16_t preferred_size, int32_t *offset);
/* /*
* Example for a resource that also handles all its sub-resources. * Example for a resource that also handles all its sub-resources.
* Use REST.get_url() to multiplex the handling of the request depending on the Uri-Path. * Use REST.get_url() to multiplex the handling of the request depending on the Uri-Path.
*/ */
PARENT_RESOURCE(res_sub, PARENT_RESOURCE(res_sub,
"title=\"Sub-resource demo\"", "title=\"Sub-resource demo\"",
res_get_handler, res_get_handler,
NULL, NULL,
NULL, NULL,
NULL); NULL);
static void static void
res_get_handler(void* request, void* response, uint8_t *buffer, uint16_t preferred_size, int32_t *offset) res_get_handler(void *request, void *response, uint8_t *buffer, uint16_t preferred_size, int32_t *offset)
{ {
REST.set_header_content_type(response, REST.type.TEXT_PLAIN); REST.set_header_content_type(response, REST.type.TEXT_PLAIN);
const char *uri_path = NULL; const char *uri_path = NULL;
int len = REST.get_url(request, &uri_path); int len = REST.get_url(request, &uri_path);
int base_len = strlen(res_sub.url); int base_len = strlen(res_sub.url);
if(len==base_len) { if(len == base_len) {
snprintf((char *)buffer, REST_MAX_CHUNK_SIZE, "Request any sub-resource of /%s", res_sub.url); snprintf((char *)buffer, REST_MAX_CHUNK_SIZE, "Request any sub-resource of /%s", res_sub.url);
} else { } else {
snprintf((char *)buffer, REST_MAX_CHUNK_SIZE, ".%.*s", len-base_len, uri_path+base_len); snprintf((char *)buffer, REST_MAX_CHUNK_SIZE, ".%.*s", len - base_len, uri_path + base_len);
} } REST.set_response_payload(response, buffer, strlen((char *)buffer));
}
REST.set_response_payload(response, buffer, strlen((char *)buffer));
}

127
examples/er-rest-example/resources/res-toggle.c Executable file → Normal file
View file

@ -1,64 +1,63 @@
/* /*
* Copyright (c) 2013, Institute for Pervasive Computing, ETH Zurich * Copyright (c) 2013, Institute for Pervasive Computing, ETH Zurich
* All rights reserved. * All rights reserved.
* *
* Redistribution and use in source and binary forms, with or without * Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions * modification, are permitted provided that the following conditions
* are met: * are met:
* 1. Redistributions of source code must retain the above copyright * 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer. * notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright * 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the * notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution. * documentation and/or other materials provided with the distribution.
* 3. Neither the name of the Institute nor the names of its contributors * 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 * may be used to endorse or promote products derived from this software
* without specific prior written permission. * without specific prior written permission.
* *
* THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * 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 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE. * SUCH DAMAGE.
* *
* This file is part of the Contiki operating system. * This file is part of the Contiki operating system.
*/ */
/** /**
* \file * \file
* Example resource * Example resource
* \author * \author
* Matthias Kovatsch <kovatsch@inf.ethz.ch> * Matthias Kovatsch <kovatsch@inf.ethz.ch>
*/ */
#include "contiki.h" #include "contiki.h"
#if PLATFORM_HAS_LEDS #if PLATFORM_HAS_LEDS
#include <string.h> #include <string.h>
#include "contiki.h" #include "contiki.h"
#include "rest-engine.h" #include "rest-engine.h"
#include "dev/leds.h" #include "dev/leds.h"
static void res_post_handler(void* request, void* response, uint8_t *buffer, uint16_t preferred_size, int32_t *offset); static void res_post_handler(void *request, void *response, uint8_t *buffer, uint16_t preferred_size, int32_t *offset);
/* A simple actuator example. Toggles the red led */ /* A simple actuator example. Toggles the red led */
RESOURCE(res_toggle, RESOURCE(res_toggle,
"title=\"Red LED\";rt=\"Control\"", "title=\"Red LED\";rt=\"Control\"",
NULL, NULL,
res_post_handler, res_post_handler,
NULL, NULL,
NULL); NULL);
static void static void
res_post_handler(void* request, void* response, uint8_t *buffer, uint16_t preferred_size, int32_t *offset) res_post_handler(void *request, void *response, uint8_t *buffer, uint16_t preferred_size, int32_t *offset)
{ {
leds_invert(LEDS_RED); leds_invert(LEDS_RED);
} }
#endif /* PLATFORM_HAS_LEDS */
#endif /* PLATFORM_HAS_LEDS */