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");
61 LEDResource *currLEDResource = &LED;
63 if (ehRequest->resource == gLedInstance[0].handle)
65 currLEDResource = &gLedInstance[0];
66 gResourceUri = (char *) "a/led/0";
68 else if (ehRequest->resource == gLedInstance[1].handle)
70 currLEDResource = &gLedInstance[1];
71 gResourceUri = (char *) "a/led/1";
74 if(OC_REST_PUT == ehRequest->method)
76 cJSON *putJson = cJSON_Parse((char *)ehRequest->reqJSONPayload);
80 OC_LOG (ERROR, TAG, "putJson object not created properly");
84 currLEDResource->state = ( !strcmp(cJSON_GetObjectItem(putJson,"state")->valuestring ,
86 currLEDResource->power = cJSON_GetObjectItem(putJson,"power")->valuedouble;
87 cJSON_Delete(putJson);
90 cJSON_AddStringToObject(json,"href",gResourceUri);
91 format = cJSON_CreateObject();
95 OC_LOG (ERROR, TAG, "format object not created properly");
100 cJSON_AddItemToObject(json, "rep", format);
101 cJSON_AddStringToObject(format, "state", (char *) (currLEDResource->state ? "on":"off"));
102 cJSON_AddNumberToObject(format, "power", currLEDResource->power);
104 jsonResponse = cJSON_Print(json);
109 OCEntityHandlerResult ProcessGetRequest (OCEntityHandlerRequest *ehRequest, char *payload,
110 uint16_t maxPayloadSize)
112 OCEntityHandlerResult ehResult;
113 char *getResp = constructJsonResponse(ehRequest);
117 if (maxPayloadSize > strlen ((char *)getResp))
119 strncpy(payload, getResp, strlen((char *)getResp));
124 OC_LOG_V (INFO, TAG, "Response buffer: %d bytes is too small",
126 ehResult = OC_EH_ERROR;
133 ehResult = OC_EH_ERROR;
139 OCEntityHandlerResult ProcessPutRequest (OCEntityHandlerRequest *ehRequest, char *payload,
140 uint16_t maxPayloadSize)
142 OCEntityHandlerResult ehResult;
143 char *putResp = constructJsonResponse(ehRequest);
147 if (maxPayloadSize > strlen ((char *)putResp))
149 strncpy(payload, putResp, strlen((char *)putResp));
154 OC_LOG_V (INFO, TAG, "Response buffer: %d bytes is too small",
156 ehResult = OC_EH_ERROR;
163 ehResult = OC_EH_ERROR;
169 OCEntityHandlerResult ProcessPostRequest (OCEntityHandlerRequest *ehRequest, char *payload,
170 uint16_t maxPayloadSize)
172 char *respPLPost_led = NULL;
175 OCEntityHandlerResult ehResult;
178 * The entity handler determines how to process a POST request.
179 * Per the REST paradigm, POST can also be used to update representation of existing
180 * resource or create a new resource.
181 * In the sample below, if the POST is for /a/led then a new instance of the LED
182 * resource is created with default representation (if representation is included in
183 * POST payload it can be used as initial values) as long as the instance is
184 * lesser than max new instance count. Once max instance count is reached, POST on
185 * /a/led updated the representation of /a/led (just like PUT)
188 if (ehRequest->resource == LED.handle)
190 if (gCurrLedInstance < SAMPLE_MAX_NUM_POST_INSTANCE)
192 // Create new LED instance
193 char newLedUri[URI_MAXSIZE ];
194 snprintf(newLedUri, URI_MAXSIZE, "/a/led/%d", gCurrLedInstance);
196 json = cJSON_CreateObject();
202 cJSON_AddStringToObject(json,"href",gResourceUri);
203 format = cJSON_CreateObject();
210 cJSON_AddItemToObject(json, "rep", format);
211 cJSON_AddStringToObject(format, "createduri", (char *) newLedUri);
213 if (0 == createLEDResource (newLedUri, &gLedInstance[gCurrLedInstance], false, 0))
215 OC_LOG (INFO, TAG, "Created new LED instance");
216 gLedInstance[gCurrLedInstance].state = 0;
217 gLedInstance[gCurrLedInstance].power = 0;
219 respPLPost_led = cJSON_Print(json);
226 respPLPost_led = constructJsonResponse(ehRequest);
231 for (int i = 0; i < SAMPLE_MAX_NUM_POST_INSTANCE; i++)
233 if (ehRequest->resource == gLedInstance[i].handle)
237 respPLPost_led = constructJsonResponse(ehRequest);
242 respPLPost_led = constructJsonResponse(ehRequest);
248 if ((respPLPost_led != NULL) && (maxPayloadSize > strlen ((char *)respPLPost_led)))
250 strncpy(payload, respPLPost_led, strlen((char *)respPLPost_led));
255 OC_LOG_V (INFO, TAG, "Response buffer: %d bytes is too small",
257 ehResult = OC_EH_ERROR;
260 free(respPLPost_led);
265 OCEntityHandlerResult
266 OCEntityHandlerCb (OCEntityHandlerFlag flag,
267 OCEntityHandlerRequest *entityHandlerRequest)
269 OC_LOG_V (INFO, TAG, "Inside entity handler - flags: 0x%x", flag);
271 OCEntityHandlerResult ehResult = OC_EH_ERROR;
272 OCEntityHandlerResponse response;
273 char payload[MAX_RESPONSE_LENGTH] = {0};
275 if (flag & OC_REQUEST_FLAG)
277 OC_LOG (INFO, TAG, "Flag includes OC_REQUEST_FLAG");
278 if (entityHandlerRequest)
280 if (OC_REST_GET == entityHandlerRequest->method)
282 OC_LOG (INFO, TAG, "Received OC_REST_GET from client");
283 ehResult = ProcessGetRequest (entityHandlerRequest, payload, sizeof(payload) - 1);
285 else if (OC_REST_PUT == entityHandlerRequest->method)
287 OC_LOG (INFO, TAG, "Received OC_REST_PUT from client");
288 ehResult = ProcessPutRequest (entityHandlerRequest, payload, sizeof(payload) - 1);
290 else if (OC_REST_POST == entityHandlerRequest->method)
292 OC_LOG (INFO, TAG, "Received OC_REST_POST from client");
293 ehResult = ProcessPostRequest (entityHandlerRequest, payload, sizeof(payload) - 1);
297 OC_LOG_V (INFO, TAG, "Received unsupported method %d from client",
298 entityHandlerRequest->method);
301 if (ehResult == OC_EH_OK)
303 // Format the response. Note this requires some info about the request
304 response.requestHandle = entityHandlerRequest->requestHandle;
305 response.resourceHandle = entityHandlerRequest->resource;
306 response.ehResult = ehResult;
307 response.payload = payload;
308 response.payloadSize = strlen(payload);
309 response.numSendVendorSpecificHeaderOptions = 0;
310 memset(response.sendVendorSpecificHeaderOptions, 0, sizeof response.sendVendorSpecificHeaderOptions);
311 memset(response.resourceUri, 0, sizeof(response.resourceUri));
312 // Indicate that response is NOT in a persistent buffer
313 response.persistentBufferFlag = 0;
316 if (OCDoResponse(&response) != OC_STACK_OK)
318 OC_LOG(ERROR, TAG, "Error sending response");
319 ehResult = OC_EH_ERROR;
327 /* SIGINT handler: set gQuitFlag to 1 for graceful termination */
328 void handleSigInt(int signum)
330 if (signum == SIGINT)
336 int main(int argc, char* argv[])
338 OC_LOG(DEBUG, TAG, "OCServer is starting...");
339 if (OCInit(NULL, 0, OC_SERVER) != OC_STACK_OK)
341 OC_LOG(ERROR, TAG, "OCStack init error");
346 * Declare and create the example resource: LED
348 createLEDResource(gResourceUri, &LED, false, 0);
350 // Break from loop with Ctrl-C
351 OC_LOG(INFO, TAG, "Entering ocserver main loop...");
352 signal(SIGINT, handleSigInt);
355 if (OCProcess() != OC_STACK_OK)
357 OC_LOG(ERROR, TAG, "OCStack process error");
364 OC_LOG(INFO, TAG, "Exiting ocserver main loop...");
366 if (OCStop() != OC_STACK_OK)
368 OC_LOG(ERROR, TAG, "OCStack process error");
374 int createLEDResource (char *uri, LEDResource *ledResource, bool resourceState, int resourcePower)
378 OC_LOG(ERROR, TAG, "Resource URI cannot be NULL");
382 ledResource->state = resourceState;
383 ledResource->power= resourcePower;
384 OCStackResult res = OCCreateResource(&(ledResource->handle),
386 OC_RSRVD_INTERFACE_DEFAULT,
389 OC_DISCOVERABLE|OC_OBSERVABLE);
390 OC_LOG_V(INFO, TAG, "Created LED resource with result: %s", getResult(res));