Factor resources, fix time

Now there is a generic resource that can generate and parse
application/json as well as text/plain. It can be re-used, only the
from_string and to_string routines have to be written and the resource
properly set up. A new resource format is specified, see
GENERIC_RESOURCE in, e.g., examples/osd/pwm-example. This is now used in
all my examples, namely pwm-example, arduino-sketch, wallclock-time.

There was an off by one error for the month in time formatting (in
gmtime and localtime). And the leap-year computation was broken. Both
fixed now, so we get a correct date. For localtime we are still 2 hours
off because daylight saving isn't implemented yet.

Also renamed gmtime to utc.
ico
Ralf Schlatterbeck 2014-06-27 22:25:51 +02:00
parent 4f20df042f
commit d5284eebe1
12 changed files with 488 additions and 612 deletions

View File

@ -0,0 +1 @@
json-resource_src = generic_resource.c

View File

@ -0,0 +1,209 @@
/*
* Copyright (c) 2014, Ralf Schlatterbeck Open Source Consulting
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name of the Institute nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*/
/**
* \addtogroup Generic CoAP Resource Handler
*
* @{
*/
/**
* \file
* Generic CoAP Resource Handler
* \author
* Ralf Schlatterbeck <rsc@runtux.com>
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "contiki.h"
#include "jsonparse.h"
/* Only coap 13 for now */
#include "er-coap-13.h"
#include "generic_resource.h"
/* Error-handling macro */
# define BYE(_exp, _tag) \
do { \
PRINTF("Expect "_exp": %d\n",_tag); \
return -1; \
} while(0)
#define DEBUG 1
#if DEBUG
#define PRINTF(...) printf(__VA_ARGS__)
#else
#define PRINTF(...)
#endif
int8_t
json_parse_variable
(const uint8_t *bytes, size_t len, char *name, char *buf, size_t buflen)
{
int tag = 0;
struct jsonparse_state state;
struct jsonparse_state *parser = &state;
PRINTF ("PUT: len: %d, %s\n", len, (const char *)bytes);
jsonparse_setup (parser, (const char *)bytes, len);
if ((tag = jsonparse_next (parser)) != JSON_TYPE_OBJECT) {
BYE ("OBJECT", tag);
}
if ((tag = jsonparse_next (parser)) != JSON_TYPE_PAIR_NAME) {
BYE ("PAIR_NAME", tag);
}
while (jsonparse_strcmp_value (parser, name) != 0) {
tag = jsonparse_next (parser);
if (tag != JSON_TYPE_PAIR) {
BYE ("PAIR", tag);
}
tag = jsonparse_next (parser);
tag = jsonparse_next (parser);
if (tag != ',') {
BYE (",", tag);
}
tag = jsonparse_next (parser);
if (tag != JSON_TYPE_PAIR_NAME) {
BYE ("PAIR_NAME", tag);
}
}
tag = jsonparse_next (parser);
if (tag != JSON_TYPE_PAIR) {
BYE ("PAIR", tag);
}
tag = jsonparse_next (parser);
if (tag != JSON_TYPE_STRING) {
BYE ("STRING", tag);
}
jsonparse_copy_value (parser, buf, buflen);
return 0;
}
void generic_handler
( void *request
, void *response
, uint8_t *buffer
, uint16_t preferred_size
, int32_t *offset
, char *name
, void (*from_str)(const char *name, const char *s)
, size_t (*to_str)(const char *name, uint8_t is_json, char *buf, size_t bsize)
)
{
int success = 1;
char temp [100];
int i = 0;
size_t len = 0;
int n_acc = 0;
const uint8_t *bytes = NULL;
const uint16_t *accept = NULL;
uint16_t a_ctype = REST.type.APPLICATION_JSON;
uint16_t c_ctype = REST.get_header_content_type (request);
/* Seems like accepted type is currently unsupported? */
n_acc = REST.get_header_accept (request, &accept);
for (i=0; i<n_acc; i++) {
if ( accept [i] == REST.type.TEXT_PLAIN
|| accept [i] == REST.type.APPLICATION_JSON
)
{
a_ctype = accept [i];
break;
}
}
switch(REST.get_method_type(request)) {
case METHOD_GET:
// TEXT format
if (a_ctype == REST.type.TEXT_PLAIN) {
len += to_str (name, 0, temp + len, sizeof (temp) - len);
if (len > sizeof (temp)) {
success = 0;
break;
}
len += snprintf (temp + len, sizeof (temp) - len, "\n");
if (len > sizeof (temp)) {
success = 0;
break;
}
} else { // jSON Format
len += snprintf
(temp + len, sizeof (temp) - len, "{\n \"%s\" : ", name);
if (len > sizeof (temp)) {
success = 0;
break;
}
len += to_str (name, 1, temp + len, sizeof (temp) - len);
if (len > sizeof (temp)) {
success = 0;
break;
}
len += snprintf (temp + len, sizeof (temp) - len, "\n}\n");
if (len > sizeof (temp)) {
success = 0;
break;
}
}
memcpy (buffer, temp, len);
REST.set_header_content_type (response, a_ctype);
REST.set_response_payload (response, buffer, len);
break;
case METHOD_PUT:
if (from_str && (len = coap_get_payload(request, &bytes))) {
if (c_ctype == REST.type.TEXT_PLAIN) {
temp [sizeof (temp) - 1] = 0;
strncpy (temp, (const char *)bytes, MIN (len, sizeof (temp) - 1));
} else { // jSON Format
if (json_parse_variable (bytes, len, name, temp, sizeof (temp)) < 0) {
success = 0;
break;
}
}
from_str (name, temp);
REST.set_response_status(response, REST.status.CHANGED);
} else {
success = 0;
}
break;
default:
success = 0;
}
if (!success) {
REST.set_response_status(response, REST.status.BAD_REQUEST);
}
}
/*
* VI settings, see coding style
* ex:ts=8:et:sw=2
*/
/** @} */

View File

@ -0,0 +1,132 @@
/*
* Copyright (c) 2014, Ralf Schlatterbeck Open Source Consulting
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name of the Institute nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*/
/**
* \defgroup Generic CoAP Resource Handler
*
* This factors the boilerplate code necessary for defining a resource
* together with the necessary handler. Currently this supports
* text/plain and application/json and outputs the resource with its
* name in json format. This may change in the future as more CoRE
* standards (e.g. see RFC 6690) get defined.
*
* @{
*/
/**
* \file
* Generic CoAP Resource Handler
* \author
* Ralf Schlatterbeck <rsc@runtux.com>
*/
#define STR__(s) #s
#define STR_(s) STR__(s)
/*
* A macro that extends the resource definition and also sets up the
* necessary handler function that calls format/parse routines that
* convert from/to string (fs and ts). The ts function needs to return
* the length written, similar to sprintf.
* The content type definitions ct="0 5" are text/plain and
* application/json, respectively, see rfc7252 Table 9 p. 91.
* Yes, this *is* a hack. But I hate boilerplate code.
*/
#define GENERIC_RESOURCE(name, methods, path, title, unit, fs, ts) \
void name##_handler \
( void *request \
, void *response \
, uint8_t *buffer \
, uint16_t ps \
, int32_t *offset \
) \
{ \
generic_handler \
(request, response, buffer, ps, offset, STR_(name), fs, ts); \
} \
\
RESOURCE ( name, methods, path \
, "title=\"" STR_(title) "\"" \
";rt=UCUM:\"" STR_(unit) "\"" \
";ct=\"0 5\"" \
)
/**
* \brief Parse a resource in json format
* \param bytes: Input string received via coap
* \param len: Length of input string
* \param name: Name to search in json input
* \param buf: Output buffer
* \param buflen: Output buffer length
* \return 0 for success, -1 for error
*
* If compiled with DEBUG also prints the error encountered
*/
extern int8_t json_parse_variable
(const uint8_t *bytes, size_t len, char *name, char *buf, size_t buflen);
/**
* \brief Generic coap resource handler
* \param name: The name of the variable in json
* \param from_str: Application method to parse value from string
* and act on it, may be NULL in which case the resource only
* supports GET not PUT
* \param to_str: Application method to format value for output;
* the function may chose to format differently for coap or text
* The other parameters are the same as a normal resource handler
* This helps avoid boilerplate code for request handlers
*
* The callback functions get the name of the parameter as a first
* argument, this allows to re-use the same function for different
* parameters. The from_str in addition gets the string to parse.
* For the to_str function the is_json flag allows to generate a
* different string depending on the content-type. In addition it gets a
* buffer and the size of the buffer. It needs to return the number of
* bytes output, similar to sprintf.
*/
extern void generic_handler
( void *request
, void *response
, uint8_t *buffer
, uint16_t preferred_size
, int32_t *offset
, char *name
, void (*from_str)(const char *name, const char *s)
, size_t (*to_str)(const char *name, uint8_t is_json, char *buf, size_t bsize)
);
/*
* VI settings, see coding style
* ex:ts=8:et:sw=2
*/
/** @} */

View File

@ -16,111 +16,51 @@
#include "jsonparse.h"
/* Only coap 13 for now */
#include "er-coap-13.h"
#include "generic_resource.h"
RESOURCE \
size_t time_to_string (const char *name, uint8_t is_json, char *buf, size_t bs)
{
struct timeval tv;
struct tm tm;
struct tm *(*method)(const time_t *, struct tm *) = gmtime_r;
if (0 == strcmp (name, "localtime")) {
method = localtime_r;
}
gettimeofday (&tv, NULL);
method (&tv.tv_sec, &tm);
return snprintf
( buf
, bs
, "%s%lu-%02u-%02u %02u:%02u:%02u%s"
, is_json ? "\"" : ""
, 1900 + tm.tm_year
, tm.tm_mon + 1, tm.tm_mday, tm.tm_hour, tm.tm_min, tm.tm_sec
, is_json ? "\"" : ""
);
}
GENERIC_RESOURCE \
( localtime
, METHOD_GET
, "clock/localtime"
, "title=\"Time\";rt=\"localtime\""
, Local time
, formatted time
, NULL
, time_to_string
);
RESOURCE \
( gmtime
GENERIC_RESOURCE \
( utc
, METHOD_GET
, "clock/utc"
, "title=\"Time\";rt=\"utc\""
, UTC
, formatted time
, NULL
, time_to_string
);
void
time_handler
( void* request
, void* response
, uint8_t *buffer
, uint16_t preferred_size
, int32_t *offset
, struct tm *(*method)(const time_t *,struct tm *)
)
{
int success = 1;
/*
* VI settings, see coding style
* ex:ts=8:et:sw=2
*/
char temp[100];
int index = 0;
int length = 0; /* |<-------->| */
struct timeval tv;
struct tm tm;
int i = 0;
int n_acc = 0;
const uint16_t *accept = NULL;
uint16_t a_ctype = REST.type.APPLICATION_JSON; /* for now json is default */
/* Looks like accepted content-type isn't currently supported */
n_acc = REST.get_header_accept (request, &accept);
for (i=0; i<n_acc; i++) {
if ( accept [i] == REST.type.TEXT_PLAIN
|| accept [i] == REST.type.APPLICATION_JSON
)
{
a_ctype = accept [i];
break;
}
}
switch(REST.get_method_type(request)){
case METHOD_GET:
gettimeofday (&tv, NULL);
method (&tv.tv_sec, &tm);
if (a_ctype == REST.type.TEXT_PLAIN) {
index += sprintf
( temp + index
, "%lu-%02u-%02u %02u:%02u:%02u\n"
, 1900 + tm.tm_year
, tm.tm_mon, tm.tm_mday, tm.tm_hour, tm.tm_min, tm.tm_sec
);
} else { // jSON Format
index += sprintf
( temp + index
,"{\n \"localtime\" : \"%lu-%02u-%02u %02u:%02u:%02u\"\n"
, 1900 + tm.tm_year
, tm.tm_mon, tm.tm_mday, tm.tm_hour, tm.tm_min, tm.tm_sec
);
index += sprintf(temp + index,"}\n");
}
length = strlen(temp);
memcpy (buffer, temp, length);
REST.set_header_content_type (response, REST.type.APPLICATION_JSON);
REST.set_response_payload (response, buffer, length);
break;
default:
success = 0;
}
if (!success) {
REST.set_response_status(response, REST.status.BAD_REQUEST);
}
}
void
localtime_handler
( void* request
, void* response
, uint8_t *buffer
, uint16_t preferred_size
, int32_t *offset
)
{
return time_handler
(request, response, buffer, preferred_size, offset, &localtime_r);
}
void
gmtime_handler
( void* request
, void* response
, uint8_t *buffer
, uint16_t preferred_size
, int32_t *offset
)
{
return time_handler
(request, response, buffer, preferred_size, offset, &gmtime_r);
}

View File

@ -20,139 +20,42 @@
#include "jsonparse.h"
/* Only coap 13 for now */
#include "er-coap-13.h"
#include "generic_resource.h"
/* Error-handling macro */
# define BYE(_exp, _tag) \
do { \
PRINTF("Expect "_exp": %d\n",_tag); \
success=0; \
goto bye; \
} while(0)
#define DEBUG 1
#if DEBUG
#define PRINTF(...) printf(__VA_ARGS__)
#else
#define PRINTF(...)
#endif
RESOURCE \
( timestamp, METHOD_GET | METHOD_PUT
, "clock/timestamp"
, "title=\"Time\";rt=\"timestamp\""
);
void
timestamp_handler
( void* request
, void* response
, uint8_t *buffer
, uint16_t preferred_size
, int32_t *offset
)
void timestamp_from_string (const char *name, const char *s)
{
int success = 1;
int i;
char temp[100];
int index = 0;
int length = 0;
int tag = 0;
const uint8_t *bytes = NULL;
size_t len = 0;
struct timeval tv;
int n_acc = 0;
const uint16_t *accept = NULL;
uint16_t a_ctype = REST.type.APPLICATION_JSON;
uint16_t c_ctype = REST.get_header_content_type (request);
/* Seems like accepted type is currently unsupported? */
n_acc = REST.get_header_accept (request, &accept);
for (i=0; i<n_acc; i++) {
if ( accept [i] == REST.type.TEXT_PLAIN
|| accept [i] == REST.type.APPLICATION_JSON
)
{
a_ctype = accept [i];
break;
}
}
switch(REST.get_method_type(request)) {
case METHOD_GET:
gettimeofday (&tv, NULL);
// TEXT format
if (a_ctype == REST.type.TEXT_PLAIN) {
index += sprintf (temp + index, "%ld\n", (long)tv.tv_sec);
} else { // jSON Format
// FIXME: Platform doesn't seem to support long long printing
// We get empty string
index += sprintf
( temp + index
,"{\n \"timestamp\" : \"%ld\"\n}\n"
, (long)tv.tv_sec
);
}
length = strlen(temp);
memcpy (buffer, temp, length);
REST.set_header_content_type (response, a_ctype);
REST.set_response_payload (response, buffer, length);
break;
case METHOD_PUT:
if ((len = coap_get_payload(request, &bytes))) {
if (c_ctype == REST.type.TEXT_PLAIN) {
temp [sizeof (temp) - 1] = 0;
strncpy (temp, (char *)bytes, MIN (len, sizeof (temp) - 1));
} else { // jSON Format
struct jsonparse_state state;
struct jsonparse_state *parser = &state;
PRINTF ("PUT: len: %d, %s\n", len, (char *)bytes);
jsonparse_setup (parser, (char *)bytes, len);
if ((tag = jsonparse_next (parser)) != JSON_TYPE_OBJECT) {
BYE ("OBJECT", tag);
}
if ((tag = jsonparse_next (parser)) != JSON_TYPE_PAIR_NAME) {
BYE ("PAIR_NAME", tag);
}
while (jsonparse_strcmp_value (parser, "timestamp") != 0) {
tag = jsonparse_next (parser);
if (tag != JSON_TYPE_PAIR) {
BYE ("PAIR", tag);
}
tag = jsonparse_next (parser);
tag = jsonparse_next (parser);
if (tag != ',') {
BYE (",", tag);
}
tag = jsonparse_next (parser);
if (tag != JSON_TYPE_PAIR_NAME) {
BYE ("PAIR_NAME", tag);
}
}
tag = jsonparse_next (parser);
if (tag != JSON_TYPE_PAIR) {
BYE ("PAIR", tag);
}
tag = jsonparse_next (parser);
if (tag != JSON_TYPE_STRING) {
BYE ("STRING", tag);
}
jsonparse_copy_value (parser, temp, sizeof (temp));
}
// FIXME: Platform has no strtoll (long long)?
tv.tv_sec = strtol (temp, NULL, 10);
settimeofday (&tv, NULL);
REST.set_response_status(response, REST.status.CHANGED);
} else {
success = 0;
}
bye :
break;
default:
success = 0;
}
if (!success) {
REST.set_response_status(response, REST.status.BAD_REQUEST);
}
// FIXME: Platform has no strtoll (long long)?
tv.tv_sec = strtol (s, NULL, 10);
settimeofday (&tv, NULL);
}
size_t
timestamp_to_string (const char *name, uint8_t is_json, char *buf, size_t bsize)
{
struct timeval tv;
char *fmt = "%ld";
if (is_json) {
fmt = "\"%ld\"";
}
gettimeofday (&tv, NULL);
// FIXME: Platform doesn't seem to support long long printing
// We get empty string
return snprintf (buf, bsize, fmt, (long)tv.tv_sec);
}
GENERIC_RESOURCE
( timestamp
, METHOD_GET | METHOD_PUT
, "clock/timestamp"
, Time
, s
, timestamp_from_string
, timestamp_to_string
);
/*
* VI settings, see coding style
* ex:ts=8:et:sw=2
*/

View File

@ -21,7 +21,7 @@
extern resource_t resource_timestamp;
extern resource_t resource_localtime;
extern resource_t resource_gmtime;
extern resource_t resource_utc;
#endif // time_resource_h
/** @} */

View File

@ -68,7 +68,7 @@ CFLAGS += -DUIP_CONF_TCP=1
APPS += er-http-engine
endif
APPS += erbium time json arduino
APPS += erbium time json arduino json-resource
include $(CONTIKI)/Makefile.include
include $(CONTIKI)/apps/arduino/Makefile.include

View File

@ -6,8 +6,6 @@
*
* \brief get/put pwm and period for LED pin
*
* quick&dirty implementation, this should factor json parsing.
* But json format will probably change, there is a draft rfc.
*/
#include <stdio.h>
@ -17,270 +15,61 @@
#include "jsonparse.h"
/* Only coap 13 for now */
#include "er-coap-13.h"
#include "generic_resource.h"
#include "led_pwm.h"
/* Error-handling macro */
# define BYE(_exp, _tag) \
do { \
PRINTF("Expect "_exp": %d\n",_tag); \
success=0; \
goto bye; \
} while(0)
void pwm_from_string (const char *name, const char *s)
{
uint32_t tmp = strtoul (s, NULL, 10);
if (tmp > 255) {
tmp = 255;
}
pwm = tmp;
}
#define DEBUG 1
#if DEBUG
#define PRINTF(...) printf(__VA_ARGS__)
#else
#define PRINTF(...)
#endif
size_t
pwm_to_string (const char *name, uint8_t is_json, char *buf, size_t bufsize)
{
return snprintf (buf, bufsize, "%d", pwm);
}
RESOURCE \
GENERIC_RESOURCE \
( led_pwm, METHOD_GET | METHOD_PUT
, "led/pwm"
, "title=\"LED PWM\";rt=\"led pwm\""
, LED PWM
, duty-cycle
, pwm_from_string
, pwm_to_string
);
void
led_pwm_handler
( void* request
, void* response
, uint8_t *buffer
, uint16_t preferred_size
, int32_t *offset
)
void period_from_string (const char *name, const char *s)
{
int success = 1;
int i;
char temp[100];
int index = 0;
int length = 0;
int tag = 0;
const uint8_t *bytes = NULL;
size_t len = 0;
int n_acc = 0;
const uint16_t *accept = NULL;
uint16_t a_ctype = REST.type.APPLICATION_JSON;
uint16_t c_ctype = REST.get_header_content_type (request);
uint32_t tmp = 0;
/* Seems like accepted type is currently unsupported? */
n_acc = REST.get_header_accept (request, &accept);
for (i=0; i<n_acc; i++) {
if ( accept [i] == REST.type.TEXT_PLAIN
|| accept [i] == REST.type.APPLICATION_JSON
)
{
a_ctype = accept [i];
break;
uint32_t tmp = (strtoul (s, NULL, 10) + 50) / 100;
if (tmp > 10) {
tmp = 10;
}
}
switch(REST.get_method_type(request)) {
case METHOD_GET:
// TEXT format
if (a_ctype == REST.type.TEXT_PLAIN) {
index += sprintf (temp + index, "%d\n", pwm);
} else { // jSON Format
index += sprintf
( temp + index
,"{\n \"pwm\" : \"%d\"\n}\n"
, pwm
);
}
length = strlen(temp);
memcpy (buffer, temp, length);
REST.set_header_content_type (response, a_ctype);
REST.set_response_payload (response, buffer, length);
break;
case METHOD_PUT:
if ((len = coap_get_payload(request, &bytes))) {
PRINTF ("PUT: len: %d, %s\n", len, (char *)bytes);
if (c_ctype == REST.type.TEXT_PLAIN) {
temp [sizeof (temp) - 1] = 0;
strncpy (temp, (char *)bytes, MIN (len + 1, sizeof (temp) - 1));
} else { // jSON Format
struct jsonparse_state state;
struct jsonparse_state *parser = &state;
jsonparse_setup (parser, (char *)bytes, len);
if ((tag = jsonparse_next (parser)) != JSON_TYPE_OBJECT) {
BYE ("OBJECT", tag);
}
if ((tag = jsonparse_next (parser)) != JSON_TYPE_PAIR_NAME) {
BYE ("PAIR_NAME", tag);
}
while (jsonparse_strcmp_value (parser, "pwm") != 0) {
tag = jsonparse_next (parser);
if (tag != JSON_TYPE_PAIR) {
BYE ("PAIR", tag);
}
tag = jsonparse_next (parser);
tag = jsonparse_next (parser);
if (tag != ',') {
BYE (",", tag);
}
tag = jsonparse_next (parser);
if (tag != JSON_TYPE_PAIR_NAME) {
BYE ("PAIR_NAME", tag);
}
}
tag = jsonparse_next (parser);
if (tag != JSON_TYPE_PAIR) {
BYE ("PAIR", tag);
}
tag = jsonparse_next (parser);
if (tag != JSON_TYPE_STRING) {
BYE ("STRING", tag);
}
jsonparse_copy_value (parser, temp, sizeof (temp));
temp [sizeof (temp) - 1] = 0;
}
PRINTF ("GOT: %s\n", temp);
tmp = strtoul (temp, NULL, 10);
if (tmp > 255) {
tmp = 255;
}
pwm = tmp;
PRINTF ("Setting: %d\n", pwm);
REST.set_response_status(response, REST.status.CHANGED);
} else {
PRINTF ("PUT: len: %d\n", len);
success = 0;
}
bye :
break;
default:
success = 0;
}
if (!success) {
REST.set_response_status(response, REST.status.BAD_REQUEST);
}
if (tmp == 0) {
tmp = 1;
}
period_100ms = tmp;
}
RESOURCE \
size_t
period_to_string (const char *name, uint8_t is_json, char *buf, size_t bufsize)
{
return snprintf (buf, bufsize, "%d", period_100ms * 100);
}
GENERIC_RESOURCE \
( led_period, METHOD_GET | METHOD_PUT
, "led/period"
, "title=\"LED Period\";rt=\"led period\""
, LED Period
, ms
, period_from_string
, period_to_string
);
void
led_period_handler
( void* request
, void* response
, uint8_t *buffer
, uint16_t preferred_size
, int32_t *offset
)
{
int success = 1;
int i;
char temp[100];
int index = 0;
int length = 0;
int tag = 0;
const uint8_t *bytes = NULL;
size_t len = 0;
int n_acc = 0;
const uint16_t *accept = NULL;
uint16_t a_ctype = REST.type.APPLICATION_JSON;
uint16_t c_ctype = REST.get_header_content_type (request);
uint32_t tmp = 0;
/* Seems like accepted type is currently unsupported? */
n_acc = REST.get_header_accept (request, &accept);
for (i=0; i<n_acc; i++) {
if ( accept [i] == REST.type.TEXT_PLAIN
|| accept [i] == REST.type.APPLICATION_JSON
)
{
a_ctype = accept [i];
break;
}
}
switch(REST.get_method_type(request)) {
case METHOD_GET:
// TEXT format
if (a_ctype == REST.type.TEXT_PLAIN) {
index += sprintf (temp + index, "%d\n", period_100ms * 100);
} else { // jSON Format
index += sprintf
( temp + index
,"{\n \"period\" : \"%d\"\n}\n"
, period_100ms * 100
);
}
length = strlen(temp);
memcpy (buffer, temp, length);
REST.set_header_content_type (response, a_ctype);
REST.set_response_payload (response, buffer, length);
break;
case METHOD_PUT:
if ((len = coap_get_payload(request, &bytes))) {
PRINTF ("PUT: len: %d, %s\n", len, (char *)bytes);
if (c_ctype == REST.type.TEXT_PLAIN) {
temp [sizeof (temp) - 1] = 0;
strncpy (temp, (char *)bytes, MIN (len + 1, sizeof (temp) - 1));
} else { // jSON Format
struct jsonparse_state state;
struct jsonparse_state *parser = &state;
jsonparse_setup (parser, (char *)bytes, len);
if ((tag = jsonparse_next (parser)) != JSON_TYPE_OBJECT) {
BYE ("OBJECT", tag);
}
if ((tag = jsonparse_next (parser)) != JSON_TYPE_PAIR_NAME) {
BYE ("PAIR_NAME", tag);
}
while (jsonparse_strcmp_value (parser, "period") != 0) {
tag = jsonparse_next (parser);
if (tag != JSON_TYPE_PAIR) {
BYE ("PAIR", tag);
}
tag = jsonparse_next (parser);
tag = jsonparse_next (parser);
if (tag != ',') {
BYE (",", tag);
}
tag = jsonparse_next (parser);
if (tag != JSON_TYPE_PAIR_NAME) {
BYE ("PAIR_NAME", tag);
}
}
tag = jsonparse_next (parser);
if (tag != JSON_TYPE_PAIR) {
BYE ("PAIR", tag);
}
tag = jsonparse_next (parser);
if (tag != JSON_TYPE_STRING) {
BYE ("STRING", tag);
}
jsonparse_copy_value (parser, temp, sizeof (temp));
temp [sizeof (temp) - 1] = 0;
}
PRINTF ("GOT: %s\n", temp);
tmp = (strtoul (temp, NULL, 10) + 50) / 100;
if (tmp > 10) {
tmp = 10;
}
if (tmp == 0) {
tmp = 1;
}
period_100ms = tmp;
PRINTF ("Setting: %dms\n", period_100ms * 100);
REST.set_response_status(response, REST.status.CHANGED);
} else {
PRINTF ("PUT: len: %d\n", len);
success = 0;
}
bye :
break;
default:
success = 0;
}
if (!success) {
REST.set_response_status(response, REST.status.BAD_REQUEST);
}
}
/*
* VI settings, see coding style
* ex:ts=8:et:sw=2
*/

View File

@ -66,7 +66,7 @@ CFLAGS += -DUIP_CONF_TCP=1
APPS += er-http-engine
endif
APPS += erbium json
APPS += erbium json json-resource
include $(CONTIKI)/Makefile.include

View File

@ -15,6 +15,7 @@
/* Only coap 13 for now */
#include "er-coap-13.h"
#include "hw_timer.h"
#include "generic_resource.h"
/* Error-handling macro */
# define BYE(_exp, _tag) \
@ -44,131 +45,32 @@ void led_pwm_init (void)
DDRE |= (1<<PINE5);
}
RESOURCE \
void pwm_from_string (const char *name, const char *s)
{
pwm = atoi (s);
if (pwm > max_ticks) {
pwm = max_ticks;
}
PRINTF ("Setting: %d (max=%d)\n", pwm, max_ticks);
hwtimer_pwm_inverse (3, HWT_CHANNEL_C);
DDRE |= (1<<PINE5);
hwtimer_set_pwm (3, HWT_CHANNEL_C, pwm);
PRINTF
( "TCNT3: %04X TCCR3A: %04X TCCR3B: %04X TCCR3C: %04X OCR3C: %04X\n"
, TCNT3, TCCR3A, TCCR3B, TCCR3C, OCR3C
);
}
size_t pwm_to_string (const char *n, uint8_t is_json, char *buf, size_t bufsize)
{
return snprintf (buf, bufsize, "%d", pwm);
}
GENERIC_RESOURCE \
( led_pwm, METHOD_GET | METHOD_PUT
, "led/pwm"
, "title=\"LED PWM\";rt=\"led pwm\""
, LED PWM
, duty-cycle
, pwm_from_string
, pwm_to_string
);
void
led_pwm_handler
( void* request
, void* response
, uint8_t *buffer
, uint16_t preferred_size
, int32_t *offset
)
{
int success = 1;
int i;
char temp[100];
int index = 0;
int length = 0;
int tag = 0;
const uint8_t *bytes = NULL;
size_t len = 0;
int n_acc = 0;
const uint16_t *accept = NULL;
uint16_t a_ctype = REST.type.APPLICATION_JSON;
uint16_t c_ctype = REST.get_header_content_type (request);
/* Seems like accepted type is currently unsupported? */
n_acc = REST.get_header_accept (request, &accept);
for (i=0; i<n_acc; i++) {
if ( accept [i] == REST.type.TEXT_PLAIN
|| accept [i] == REST.type.APPLICATION_JSON
)
{
a_ctype = accept [i];
break;
}
}
switch(REST.get_method_type(request)) {
case METHOD_GET:
// TEXT format
if (a_ctype == REST.type.TEXT_PLAIN) {
index += sprintf (temp + index, "%d\n", pwm);
} else { // jSON Format
index += sprintf
( temp + index
,"{\n \"pwm\" : \"%d\"\n}\n"
, pwm
);
}
length = strlen(temp);
memcpy (buffer, temp, length);
REST.set_header_content_type (response, a_ctype);
REST.set_response_payload (response, buffer, length);
break;
case METHOD_PUT:
if ((len = coap_get_payload(request, &bytes))) {
PRINTF ("PUT: len: %d, %s\n", len, (char *)bytes);
if (c_ctype == REST.type.TEXT_PLAIN) {
temp [sizeof (temp) - 1] = 0;
strncpy (temp, (char *)bytes, MIN (len + 1, sizeof (temp) - 1));
} else { // jSON Format
struct jsonparse_state state;
struct jsonparse_state *parser = &state;
jsonparse_setup (parser, (char *)bytes, len);
if ((tag = jsonparse_next (parser)) != JSON_TYPE_OBJECT) {
BYE ("OBJECT", tag);
}
if ((tag = jsonparse_next (parser)) != JSON_TYPE_PAIR_NAME) {
BYE ("PAIR_NAME", tag);
}
while (jsonparse_strcmp_value (parser, "pwm") != 0) {
tag = jsonparse_next (parser);
if (tag != JSON_TYPE_PAIR) {
BYE ("PAIR", tag);
}
tag = jsonparse_next (parser);
tag = jsonparse_next (parser);
if (tag != ',') {
BYE (",", tag);
}
tag = jsonparse_next (parser);
if (tag != JSON_TYPE_PAIR_NAME) {
BYE ("PAIR_NAME", tag);
}
}
tag = jsonparse_next (parser);
if (tag != JSON_TYPE_PAIR) {
BYE ("PAIR", tag);
}
tag = jsonparse_next (parser);
if (tag != JSON_TYPE_STRING) {
BYE ("STRING", tag);
}
jsonparse_copy_value (parser, temp, sizeof (temp));
temp [sizeof (temp) - 1] = 0;
}
PRINTF ("GOT: %s\n", temp);
pwm = atoi (temp);
if (pwm > max_ticks) {
pwm = max_ticks;
}
PRINTF ("Setting: %d (max=%d)\n", pwm, max_ticks);
hwtimer_pwm_inverse (3, HWT_CHANNEL_C);
DDRE |= (1<<PINE5);
hwtimer_set_pwm (3, HWT_CHANNEL_C, pwm);
PRINTF
( "TCNT3: %04X TCCR3A: %04X TCCR3B: %04X TCCR3C: %04X OCR3C: %04X\n"
, TCNT3, TCCR3A, TCCR3B, TCCR3C, OCR3C
);
REST.set_response_status(response, REST.status.CHANGED);
} else {
PRINTF ("PUT: len: %d\n", len);
success = 0;
}
bye :
break;
default:
success = 0;
}
if (!success) {
REST.set_response_status(response, REST.status.BAD_REQUEST);
}
}

View File

@ -66,7 +66,7 @@ CFLAGS += -DUIP_CONF_TCP=1
APPS += er-http-engine
endif
APPS += erbium time json
APPS += erbium time json json-resource
include $(CONTIKI)/Makefile.include

View File

@ -286,7 +286,7 @@ PROCESS_THREAD(rest_server_example, ev, data)
#endif
rest_activate_resource(&resource_timestamp);
rest_activate_resource(&resource_localtime);
rest_activate_resource(&resource_gmtime);
rest_activate_resource(&resource_utc);
/* Define application-specific events here. */
while(1) {