1 //******************************************************************
3 // Copyright 2014 Intel Mobile Communications GmbH All Rights Reserved.
5 //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
7 // Licensed under the Apache License, Version 2.0 (the "License");
8 // you may not use this file except in compliance with the License.
9 // You may obtain a copy of the License at
11 // http://www.apache.org/licenses/LICENSE-2.0
13 // Unless required by applicable law or agreed to in writing, software
14 // distributed under the License is distributed on an "AS IS" BASIS,
15 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16 // See the License for the specific language governing permissions and
17 // limitations under the License.
19 //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
30 #include "ocserverbasicops.h"
35 static LEDResource LED;
36 // This variable determines instance number of the LED resource.
37 // Used by POST method to create a new instance of LED resource.
38 static int gCurrLedInstance = 0;
39 #define SAMPLE_MAX_NUM_POST_INSTANCE 2
40 static LEDResource gLedInstance[SAMPLE_MAX_NUM_POST_INSTANCE];
43 char *gResourceUri= (char *)"a/led";
45 char *gResourceUri= (char *)"/a/led";
48 static uint16_t OC_WELL_KNOWN_PORT = 5683;
50 //File containing Server's Identity and the PSK credentials
51 //of other devices which the server trusts
52 //This can be generated using 'gen_sec_bin' application
53 static char CRED_FILE[] = "server_cred.bin";
55 //This function takes the request as an input and returns the response
57 char* constructJsonResponse (OCEntityHandlerRequest *ehRequest)
59 cJSON *json = cJSON_CreateObject();
62 LEDResource *currLEDResource = &LED;
64 if (ehRequest->resource == gLedInstance[0].handle)
66 currLEDResource = &gLedInstance[0];
67 gResourceUri = (char *) "a/led/0";
69 else if (ehRequest->resource == gLedInstance[1].handle)
71 currLEDResource = &gLedInstance[1];
72 gResourceUri = (char *) "a/led/1";
75 if(OC_REST_PUT == ehRequest->method)
77 cJSON *putJson = cJSON_Parse((char *)ehRequest->reqJSONPayload);
78 currLEDResource->state = ( !strcmp(cJSON_GetObjectItem(putJson,"state")->valuestring ,
80 currLEDResource->power = cJSON_GetObjectItem(putJson,"power")->valuedouble;
81 cJSON_Delete(putJson);
84 cJSON_AddStringToObject(json,"href",gResourceUri);
85 cJSON_AddItemToObject(json, "rep", format=cJSON_CreateObject());
86 cJSON_AddStringToObject(format, "state", (char *) (currLEDResource->state ? "on":"off"));
87 cJSON_AddNumberToObject(format, "power", currLEDResource->power);
89 jsonResponse = cJSON_Print(json);
94 OCEntityHandlerResult ProcessGetRequest (OCEntityHandlerRequest *ehRequest,
95 char *payload, size_t maxPayloadSize)
97 OCEntityHandlerResult ehResult;
99 char *getResp = constructJsonResponse(ehRequest);
100 if (maxPayloadSize > strlen (getResp))
102 strcpy(payload, getResp);
107 OC_LOG_V (INFO, TAG, "Response buffer: %d bytes is too small",
109 ehResult = OC_EH_ERROR;
117 OCEntityHandlerResult ProcessPutRequest (OCEntityHandlerRequest *ehRequest,
118 char *payload, size_t maxPayloadSize)
120 OCEntityHandlerResult ehResult;
122 char *putResp = constructJsonResponse(ehRequest);
123 if (maxPayloadSize > strlen (putResp))
125 strcpy(payload, putResp);
130 OC_LOG_V (INFO, TAG, "Response buffer: %d bytes is too small",
132 ehResult = OC_EH_ERROR;
140 OCEntityHandlerResult ProcessPostRequest (OCEntityHandlerRequest *ehRequest,
141 char *payload, size_t maxPayloadSize)
143 char *respPLPost_led = NULL;
146 OCEntityHandlerResult ehResult;
149 * The entity handler determines how to process a POST request.
150 * Per the REST paradigm, POST can also be used to update representation of existing
151 * resource or create a new resource.
152 * In the sample below, if the POST is for /a/led then a new instance of the LED
153 * resource is created with default representation (if representation is included in
154 * POST payload it can be used as initial values) as long as the instance is
155 * lesser than max new instance count. Once max instance count is reached, POST on
156 * /a/led updated the representation of /a/led (just like PUT)
159 if (ehRequest->resource == LED.handle)
161 if (gCurrLedInstance < SAMPLE_MAX_NUM_POST_INSTANCE)
163 // Create new LED instance
164 char newLedUri[15] = "/a/led/";
165 sprintf (newLedUri + strlen(newLedUri), "%d", gCurrLedInstance);
167 json = cJSON_CreateObject();
169 cJSON_AddStringToObject(json,"href",gResourceUri);
170 cJSON_AddItemToObject(json, "rep", format=cJSON_CreateObject());
171 cJSON_AddStringToObject(format, "createduri", (char *) newLedUri);
173 if (0 == createLEDResource (newLedUri, &gLedInstance[gCurrLedInstance], false, 0))
175 OC_LOG (INFO, TAG, "Created new LED instance");
176 gLedInstance[gCurrLedInstance].state = 0;
177 gLedInstance[gCurrLedInstance].power = 0;
179 respPLPost_led = cJSON_Print(json);
186 respPLPost_led = constructJsonResponse(ehRequest);
191 for (int i = 0; i < SAMPLE_MAX_NUM_POST_INSTANCE; i++)
193 if (ehRequest->resource == gLedInstance[i].handle)
197 respPLPost_led = constructJsonResponse(ehRequest);
202 respPLPost_led = constructJsonResponse(ehRequest);
208 if ((respPLPost_led != NULL) && (maxPayloadSize > strlen (respPLPost_led)))
210 strcpy(payload, respPLPost_led);
215 OC_LOG_V (INFO, TAG, "Response buffer: %d bytes is too small",
217 ehResult = OC_EH_ERROR;
220 free(respPLPost_led);
225 OCEntityHandlerResult
226 OCEntityHandlerCb (OCEntityHandlerFlag flag,
227 OCEntityHandlerRequest *entityHandlerRequest)
229 OC_LOG_V (INFO, TAG, "Inside entity handler - flags: 0x%x", flag);
231 OCEntityHandlerResult ehResult = OC_EH_ERROR;
232 OCEntityHandlerResponse response;
233 char payload[MAX_RESPONSE_LENGTH];
235 if (flag & OC_INIT_FLAG)
237 OC_LOG (INFO, TAG, "Flag includes OC_INIT_FLAG");
240 if (flag & OC_REQUEST_FLAG)
242 OC_LOG (INFO, TAG, "Flag includes OC_REQUEST_FLAG");
243 if (entityHandlerRequest)
245 if (OC_REST_GET == entityHandlerRequest->method)
247 OC_LOG (INFO, TAG, "Received OC_REST_GET from client");
248 ehResult = ProcessGetRequest (entityHandlerRequest, payload, sizeof(payload));
250 else if (OC_REST_PUT == entityHandlerRequest->method)
252 OC_LOG (INFO, TAG, "Received OC_REST_PUT from client");
253 ehResult = ProcessPutRequest (entityHandlerRequest, payload, sizeof(payload));
255 else if (OC_REST_POST == entityHandlerRequest->method)
257 OC_LOG (INFO, TAG, "Received OC_REST_POST from client");
258 ehResult = ProcessPostRequest (entityHandlerRequest, payload, sizeof(payload));
262 OC_LOG_V (INFO, TAG, "Received unsupported method %d from client",
263 entityHandlerRequest->method);
266 if (ehResult == OC_EH_OK)
268 // Format the response. Note this requires some info about the request
269 response.requestHandle = entityHandlerRequest->requestHandle;
270 response.resourceHandle = entityHandlerRequest->resource;
271 response.ehResult = ehResult;
272 response.payload = (unsigned char *)payload;
273 response.payloadSize = strlen(payload);
274 response.numSendVendorSpecificHeaderOptions = 0;
275 memset(response.sendVendorSpecificHeaderOptions, 0, sizeof response.sendVendorSpecificHeaderOptions);
276 memset(response.resourceUri, 0, sizeof(response.resourceUri));
277 // Indicate that response is NOT in a persistent buffer
278 response.persistentBufferFlag = 0;
281 if (OCDoResponse(&response) != OC_STACK_OK)
283 OC_LOG(ERROR, TAG, "Error sending response");
284 ehResult = OC_EH_ERROR;
292 /* SIGINT handler: set gQuitFlag to 1 for graceful termination */
293 void handleSigInt(int signum)
295 if (signum == SIGINT)
301 int main(int argc, char* argv[])
303 uint8_t addr[20] = {0};
304 uint8_t* paddr = NULL;
305 uint16_t port = OC_WELL_KNOWN_PORT;
306 uint8_t ifname[] = "eth0";
307 struct timespec timeout;
309 OC_LOG(DEBUG, TAG, "OCServer is starting...");
310 /*Get Ip address on defined interface and initialize coap on it with random port number
311 * this port number will be used as a source port in all coap communications*/
312 if ( OCGetInterfaceAddress(ifname, sizeof(ifname), AF_INET, addr,
313 sizeof(addr)) == ERR_SUCCESS)
315 OC_LOG_V(INFO, TAG, "Starting ocserver on address %s:%d",addr,port);
319 if (OCInit((char *) paddr, port, OC_SERVER) != OC_STACK_OK)
321 OC_LOG(ERROR, TAG, "OCStack init error");
326 * Read DTLS PSK credentials from persistent storage and
327 * set in the OC stack.
329 if (SetCredentials(CRED_FILE) != OC_STACK_OK)
331 OC_LOG(ERROR, TAG, "SetCredentials failed");
335 * Declare and create the example resource: LED
337 createLEDResource(gResourceUri, &LED, false, 0);
340 timeout.tv_nsec = 100000000L;
342 // Break from loop with Ctrl-C
343 OC_LOG(INFO, TAG, "Entering ocserver main loop...");
344 signal(SIGINT, handleSigInt);
347 if (OCProcess() != OC_STACK_OK)
349 OC_LOG(ERROR, TAG, "OCStack process error");
352 nanosleep(&timeout, NULL);
355 OC_LOG(INFO, TAG, "Exiting ocserver main loop...");
357 if (OCStop() != OC_STACK_OK)
359 OC_LOG(ERROR, TAG, "OCStack process error");
365 int createLEDResource (char *uri, LEDResource *ledResource, bool resourceState, int resourcePower)
369 OC_LOG(ERROR, TAG, "Resource URI cannot be NULL");
373 ledResource->state = resourceState;
374 ledResource->power= resourcePower;
375 OCStackResult res = OCCreateResource(&(ledResource->handle),
380 OC_DISCOVERABLE|OC_OBSERVABLE | OC_SECURE);
381 OC_LOG_V(INFO, TAG, "Created LED resource with result: %s", getResult(res));