Contiki 3.x
res_date.c
Go to the documentation of this file.
1 /**
2  * \file res_date.c
3  * date resource
4  * GET RTC date-time
5  * POST RTC date-time to set the rtc
6  * only for feshie nodes
7  * Arthur Fabre 2015
8  */
9 #include "er-server.h"
10 #include <stdlib.h>
11 #include <stdio.h>
12 #include <string.h>
13 #include "rest-engine.h"
14 #include <errno.h>
15 #include <inttypes.h>
16 #include "ms-io.h"
17 
18 #define DEBUG_ON
19 #include "debug.h"
20 
21 static void res_get_handler(void* request, void* response, uint8_t *buffer, uint16_t preferred_size, int32_t *offset) {
22  uint32_t time;
23 
24  if (!ms_get_time(&time)) {
25  REST.set_response_status(response, REST.status.SERVICE_UNAVAILABLE);
26  return;
27  }
28 
29  int length = snprintf((char *)buffer, preferred_size, "%" PRIu32, time);
30 
31  REST.set_header_content_type(response, REST.type.TEXT_PLAIN);
32  REST.set_response_payload(response, buffer, length);
33 }
34 
35 static void res_post_put_handler(void *request, void *response, uint8_t *buffer, uint16_t preferred_size, int32_t *offset) {
36  uint8_t *incoming;
37  uint8_t incoming_len;
38  char *end_ptr;
39  char *start_ptr;
40  uint32_t seconds;
41 
42  DEBUG("Attempting to set time!\n");
43 
44  if (!(incoming_len = REST.get_request_payload(request, (const uint8_t **)&incoming))) {
45  DEBUG("Failed to get payload\n");
46  REST.set_response_status(response, REST.status.BAD_REQUEST);
47  return;
48  }
49 
50  start_ptr = (char *) incoming;
51 
52  // Convert the string to an int
53  errno = 0;
54  seconds = strtol(start_ptr, &end_ptr, 0);
55  // Errno being set indicates an error occured.
56  // The enptr checks that the entire payload we got was succesfully decoded, and not just the start of it.
57  if (errno != 0 || ((char *) incoming) + incoming_len > end_ptr) {
58  DEBUG("Failed to parse epoch\n");
59  REST.set_response_status(response, REST.status.BAD_REQUEST);
60  return;
61  }
62 
63  DEBUG("Requested time is %" PRIu32 "\n", seconds);
64 
65  if (!ms_set_time(seconds)) {
66  DEBUG("Failed to set epoch\n");
67  REST.set_response_status(response, REST.status.SERVICE_UNAVAILABLE);
68  return;
69  }
70 
71  REST.set_response_status(response, REST.status.CHANGED);
72 }
73 
74 RESOURCE(res_date, "title=\"date: ?len=0..\";rt=\"Text\"", res_get_handler, res_post_put_handler, NULL, NULL);
75 
An abstraction layer for RESTful Web services (Erbium).
#define NULL
The null pointer.
RESOURCE(res_routes,"Routes", res_get_handler, NULL, NULL, NULL)
Route resource.