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"
32 //string length of "/a/led/" + std::numeric_limits<int>::digits10 + '\0'"
34 const int URI_MAXSIZE = 17;
36 volatile sig_atomic_t gQuitFlag = 0;
38 static LEDResource LED;
39 // This variable determines instance number of the LED resource.
40 // Used by POST method to create a new instance of LED resource.
41 static int gCurrLedInstance = 0;
42 #define SAMPLE_MAX_NUM_POST_INSTANCE 2
43 static LEDResource gLedInstance[SAMPLE_MAX_NUM_POST_INSTANCE];
45 char *gResourceUri= (char *)"/a/led";
47 //This function takes the request as an input and returns the response
49 char* constructJsonResponse (OCEntityHandlerRequest *ehRequest)
51 cJSON *json = cJSON_CreateObject();
55 OC_LOG (ERROR, TAG, "json object not created properly");
60 cJSON *putJson = NULL;
61 char *jsonResponse = NULL;
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* jsonObj = NULL;
78 putJson = cJSON_Parse(ehRequest->reqJSONPayload);
81 jsonObj = cJSON_GetObjectItem(putJson,"oic");
84 jsonObj = cJSON_GetArrayItem(jsonObj, 0);
87 jsonObj = cJSON_GetObjectItem(jsonObj, "rep");
93 OC_LOG_V(ERROR, TAG, "Failed to parse JSON: %s", ehRequest->reqJSONPayload);
97 cJSON* prop = cJSON_GetObjectItem(jsonObj,"power");
100 currLEDResource->power =prop->valueint;
103 prop = cJSON_GetObjectItem(jsonObj,"state");
106 currLEDResource->state = prop->valueint;
110 cJSON_AddStringToObject(json,"href",gResourceUri);
111 format = cJSON_CreateObject();
115 OC_LOG (ERROR, TAG, "format object not created properly");
119 cJSON_AddItemToObject(json, "rep", format);
120 cJSON_AddStringToObject(format, "state", (char *) (currLEDResource->state ? "on":"off"));
121 cJSON_AddNumberToObject(format, "power", currLEDResource->power);
123 jsonResponse = cJSON_Print(json);
126 cJSON_Delete(putJson);
131 OCEntityHandlerResult ProcessGetRequest (OCEntityHandlerRequest *ehRequest, char *payload,
132 uint16_t maxPayloadSize)
134 OCEntityHandlerResult ehResult;
135 char *getResp = constructJsonResponse(ehRequest);
139 if (maxPayloadSize > strlen ((char *)getResp))
141 strncpy(payload, getResp, strlen((char *)getResp));
146 OC_LOG_V (INFO, TAG, "Response buffer: %d bytes is too small",
148 ehResult = OC_EH_ERROR;
155 ehResult = OC_EH_ERROR;
161 OCEntityHandlerResult ProcessPutRequest (OCEntityHandlerRequest *ehRequest, char *payload,
162 uint16_t maxPayloadSize)
164 OCEntityHandlerResult ehResult;
165 char *putResp = constructJsonResponse(ehRequest);
169 if (maxPayloadSize > strlen ((char *)putResp))
171 strncpy(payload, putResp, strlen((char *)putResp));
176 OC_LOG_V (INFO, TAG, "Response buffer: %d bytes is too small",
178 ehResult = OC_EH_ERROR;
185 ehResult = OC_EH_ERROR;
191 OCEntityHandlerResult ProcessPostRequest (OCEntityHandlerRequest *ehRequest, char *payload,
192 uint16_t maxPayloadSize)
194 char *respPLPost_led = NULL;
197 OCEntityHandlerResult ehResult;
200 * The entity handler determines how to process a POST request.
201 * Per the REST paradigm, POST can also be used to update representation of existing
202 * resource or create a new resource.
203 * In the sample below, if the POST is for /a/led then a new instance of the LED
204 * resource is created with default representation (if representation is included in
205 * POST payload it can be used as initial values) as long as the instance is
206 * lesser than max new instance count. Once max instance count is reached, POST on
207 * /a/led updated the representation of /a/led (just like PUT)
210 if (ehRequest->resource == LED.handle)
212 if (gCurrLedInstance < SAMPLE_MAX_NUM_POST_INSTANCE)
214 // Create new LED instance
215 char newLedUri[URI_MAXSIZE ];
216 snprintf(newLedUri, URI_MAXSIZE, "/a/led/%d", gCurrLedInstance);
218 json = cJSON_CreateObject();
224 cJSON_AddStringToObject(json,"href",gResourceUri);
225 format = cJSON_CreateObject();
232 cJSON_AddItemToObject(json, "rep", format);
233 cJSON_AddStringToObject(format, "createduri", (char *) newLedUri);
235 if (0 == createLEDResource (newLedUri, &gLedInstance[gCurrLedInstance], false, 0))
237 OC_LOG (INFO, TAG, "Created new LED instance");
238 gLedInstance[gCurrLedInstance].state = 0;
239 gLedInstance[gCurrLedInstance].power = 0;
241 respPLPost_led = cJSON_Print(json);
248 respPLPost_led = constructJsonResponse(ehRequest);
253 for (int i = 0; i < SAMPLE_MAX_NUM_POST_INSTANCE; i++)
255 if (ehRequest->resource == gLedInstance[i].handle)
259 respPLPost_led = constructJsonResponse(ehRequest);
264 respPLPost_led = constructJsonResponse(ehRequest);
270 if ((respPLPost_led != NULL) && (maxPayloadSize > strlen ((char *)respPLPost_led)))
272 strncpy(payload, respPLPost_led, strlen((char *)respPLPost_led));
277 OC_LOG_V (INFO, TAG, "Response buffer: %d bytes is too small",
279 ehResult = OC_EH_ERROR;
282 free(respPLPost_led);
287 OCEntityHandlerResult
288 OCEntityHandlerCb (OCEntityHandlerFlag flag,
289 OCEntityHandlerRequest *entityHandlerRequest,void* callbackParam)
291 OC_LOG_V (INFO, TAG, "Inside entity handler - flags: 0x%x", flag);
293 OCEntityHandlerResult ehResult = OC_EH_ERROR;
294 OCEntityHandlerResponse response;
295 char payload[MAX_RESPONSE_LENGTH] = {0};
297 if (flag & OC_REQUEST_FLAG)
299 OC_LOG (INFO, TAG, "Flag includes OC_REQUEST_FLAG");
300 if (entityHandlerRequest)
302 if (OC_REST_GET == entityHandlerRequest->method)
304 OC_LOG (INFO, TAG, "Received OC_REST_GET from client");
305 ehResult = ProcessGetRequest (entityHandlerRequest, payload, sizeof(payload) - 1);
307 else if (OC_REST_PUT == entityHandlerRequest->method)
309 OC_LOG (INFO, TAG, "Received OC_REST_PUT from client");
310 ehResult = ProcessPutRequest (entityHandlerRequest, payload, sizeof(payload) - 1);
312 else if (OC_REST_POST == entityHandlerRequest->method)
314 OC_LOG (INFO, TAG, "Received OC_REST_POST from client");
315 ehResult = ProcessPostRequest (entityHandlerRequest, payload, sizeof(payload) - 1);
319 OC_LOG_V (INFO, TAG, "Received unsupported method %d from client",
320 entityHandlerRequest->method);
323 if (ehResult == OC_EH_OK)
325 // Format the response. Note this requires some info about the request
326 response.requestHandle = entityHandlerRequest->requestHandle;
327 response.resourceHandle = entityHandlerRequest->resource;
328 response.ehResult = ehResult;
329 response.payload = payload;
330 response.payloadSize = strlen(payload);
331 response.numSendVendorSpecificHeaderOptions = 0;
332 memset(response.sendVendorSpecificHeaderOptions, 0, sizeof response.sendVendorSpecificHeaderOptions);
333 memset(response.resourceUri, 0, sizeof(response.resourceUri));
334 // Indicate that response is NOT in a persistent buffer
335 response.persistentBufferFlag = 0;
338 if (OCDoResponse(&response) != OC_STACK_OK)
340 OC_LOG(ERROR, TAG, "Error sending response");
341 ehResult = OC_EH_ERROR;
349 /* SIGINT handler: set gQuitFlag to 1 for graceful termination */
350 void handleSigInt(int signum)
352 if (signum == SIGINT)
358 int main(int argc, char* argv[])
360 OC_LOG(DEBUG, TAG, "OCServer is starting...");
361 if (OCInit(NULL, 0, OC_SERVER) != OC_STACK_OK)
363 OC_LOG(ERROR, TAG, "OCStack init error");
368 * Declare and create the example resource: LED
370 createLEDResource(gResourceUri, &LED, false, 0);
372 // Break from loop with Ctrl-C
373 OC_LOG(INFO, TAG, "Entering ocserver main loop...");
374 signal(SIGINT, handleSigInt);
377 if (OCProcess() != OC_STACK_OK)
379 OC_LOG(ERROR, TAG, "OCStack process error");
386 OC_LOG(INFO, TAG, "Exiting ocserver main loop...");
388 if (OCStop() != OC_STACK_OK)
390 OC_LOG(ERROR, TAG, "OCStack process error");
396 int createLEDResource (char *uri, LEDResource *ledResource, bool resourceState, int resourcePower)
400 OC_LOG(ERROR, TAG, "Resource URI cannot be NULL");
404 ledResource->state = resourceState;
405 ledResource->power= resourcePower;
406 OCStackResult res = OCCreateResource(&(ledResource->handle),
408 OC_RSRVD_INTERFACE_DEFAULT,
412 OC_DISCOVERABLE|OC_OBSERVABLE);
413 OC_LOG_V(INFO, TAG, "Created LED resource with result: %s", getResult(res));