1 /******************************************************************
3 * Copyright 2015 Samsung Electronics All Rights Reserved.
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 ******************************************************************/
20 ///////////////////////////////////////////////////////////////////////
21 //NOTE : This sample server is generated based on ocserverbasicops.cpp
22 ///////////////////////////////////////////////////////////////////////
31 #include "ocpayload.h"
33 #define TAG "SAMPLE_JUSTWORKS"
37 /* Structure to represent a LED resource */
38 typedef struct LEDRESOURCE{
39 OCResourceHandle handle;
44 static LEDResource LED;
45 // This variable determines instance number of the LED resource.
46 // Used by POST method to create a new instance of LED resource.
47 static int gCurrLedInstance = 0;
48 #define SAMPLE_MAX_NUM_POST_INSTANCE 2
49 static LEDResource gLedInstance[SAMPLE_MAX_NUM_POST_INSTANCE];
51 char *gResourceUri= (char *)"/a/led";
53 //Secure Virtual Resource database for Iotivity Server
54 //It contains Server's Identity and the PSK credentials
55 //of other devices which the server trusts
56 static char CRED_FILE[] = "oic_svr_db_server_justworks.json";
58 /* Function that creates a new LED resource by calling the
59 * OCCreateResource() method.
61 int createLEDResource (char *uri, LEDResource *ledResource, bool resourceState, int resourcePower);
63 /* This method converts the payload to JSON format */
64 OCRepPayload* constructResponse (OCEntityHandlerRequest *ehRequest);
66 /* Following methods process the PUT, GET, POST
69 OCEntityHandlerResult ProcessGetRequest (OCEntityHandlerRequest *ehRequest,
70 OCRepPayload **payload);
71 OCEntityHandlerResult ProcessPutRequest (OCEntityHandlerRequest *ehRequest,
72 OCRepPayload **payload);
73 OCEntityHandlerResult ProcessPostRequest (OCEntityHandlerRequest *ehRequest,
74 OCEntityHandlerResponse *response,
75 OCRepPayload **payload);
77 /* Entity Handler callback functions */
79 OCEntityHandlerCb (OCEntityHandlerFlag flag,
80 OCEntityHandlerRequest *entityHandlerRequest,
83 const char *getResult(OCStackResult result) {
87 case OC_STACK_RESOURCE_CREATED:
88 return "OC_STACK_RESOURCE_CREATED";
89 case OC_STACK_RESOURCE_DELETED:
90 return "OC_STACK_RESOURCE_DELETED";
91 case OC_STACK_INVALID_URI:
92 return "OC_STACK_INVALID_URI";
93 case OC_STACK_INVALID_QUERY:
94 return "OC_STACK_INVALID_QUERY";
95 case OC_STACK_INVALID_IP:
96 return "OC_STACK_INVALID_IP";
97 case OC_STACK_INVALID_PORT:
98 return "OC_STACK_INVALID_PORT";
99 case OC_STACK_INVALID_CALLBACK:
100 return "OC_STACK_INVALID_CALLBACK";
101 case OC_STACK_INVALID_METHOD:
102 return "OC_STACK_INVALID_METHOD";
103 case OC_STACK_NO_MEMORY:
104 return "OC_STACK_NO_MEMORY";
105 case OC_STACK_COMM_ERROR:
106 return "OC_STACK_COMM_ERROR";
107 case OC_STACK_INVALID_PARAM:
108 return "OC_STACK_INVALID_PARAM";
109 case OC_STACK_NOTIMPL:
110 return "OC_STACK_NOTIMPL";
111 case OC_STACK_NO_RESOURCE:
112 return "OC_STACK_NO_RESOURCE";
113 case OC_STACK_RESOURCE_ERROR:
114 return "OC_STACK_RESOURCE_ERROR";
115 case OC_STACK_SLOW_RESOURCE:
116 return "OC_STACK_SLOW_RESOURCE";
117 case OC_STACK_NO_OBSERVERS:
118 return "OC_STACK_NO_OBSERVERS";
120 case OC_STACK_PRESENCE_STOPPED:
121 return "OC_STACK_PRESENCE_STOPPED";
124 return "OC_STACK_ERROR";
130 OCRepPayload* getPayload(const char* uri, int64_t power, bool state)
132 OCRepPayload* payload = OCRepPayloadCreate();
135 OC_LOG(ERROR, TAG, PCF("Failed to allocate Payload"));
139 OCRepPayloadSetUri(payload, uri);
140 OCRepPayloadSetPropBool(payload, "state", state);
141 OCRepPayloadSetPropInt(payload, "power", power);
146 //This function takes the request as an input and returns the response
147 OCRepPayload* constructResponse (OCEntityHandlerRequest *ehRequest)
149 if(ehRequest->payload && ehRequest->payload->type != PAYLOAD_TYPE_REPRESENTATION)
151 OC_LOG(ERROR, TAG, PCF("Incoming payload not a representation"));
155 OCRepPayload* input = (OCRepPayload*)(ehRequest->payload);
157 LEDResource *currLEDResource = &LED;
159 if (ehRequest->resource == gLedInstance[0].handle)
161 currLEDResource = &gLedInstance[0];
162 gResourceUri = (char *) "/a/led/0";
164 else if (ehRequest->resource == gLedInstance[1].handle)
166 currLEDResource = &gLedInstance[1];
167 gResourceUri = (char *) "/a/led/1";
170 if(OC_REST_PUT == ehRequest->method)
172 // Get pointer to query
174 if(OCRepPayloadGetPropInt(input, "power", &pow))
176 currLEDResource->power =pow;
180 if(OCRepPayloadGetPropBool(input, "state", &state))
182 currLEDResource->state = state;
186 return getPayload(gResourceUri, currLEDResource->power, currLEDResource->state);
189 OCEntityHandlerResult ProcessGetRequest (OCEntityHandlerRequest *ehRequest,
190 OCRepPayload **payload)
192 OCEntityHandlerResult ehResult;
194 OCRepPayload *getResp = constructResponse(ehRequest);
203 ehResult = OC_EH_ERROR;
209 OCEntityHandlerResult ProcessPutRequest (OCEntityHandlerRequest *ehRequest,
210 OCRepPayload **payload)
212 OCEntityHandlerResult ehResult;
214 OCRepPayload *putResp = constructResponse(ehRequest);
223 ehResult = OC_EH_ERROR;
229 OCEntityHandlerResult ProcessPostRequest (OCEntityHandlerRequest *ehRequest,
230 OCEntityHandlerResponse *response, OCRepPayload **payload)
232 OCRepPayload *respPLPost_led = NULL;
233 OCEntityHandlerResult ehResult = OC_EH_OK;
236 * The entity handler determines how to process a POST request.
237 * Per the REST paradigm, POST can also be used to update representation of existing
238 * resource or create a new resource.
239 * In the sample below, if the POST is for /a/led then a new instance of the LED
240 * resource is created with default representation (if representation is included in
241 * POST payload it can be used as initial values) as long as the instance is
242 * lesser than max new instance count. Once max instance count is reached, POST on
243 * /a/led updated the representation of /a/led (just like PUT)
246 if (ehRequest->resource == LED.handle)
248 if (gCurrLedInstance < SAMPLE_MAX_NUM_POST_INSTANCE)
250 // Create new LED instance
251 char newLedUri[15] = "/a/led/";
252 int newLedUriLength = strlen(newLedUri);
253 snprintf (newLedUri + newLedUriLength, sizeof(newLedUri)-newLedUriLength, "%d", gCurrLedInstance);
255 respPLPost_led = OCRepPayloadCreate();
256 OCRepPayloadSetUri(respPLPost_led, gResourceUri);
257 OCRepPayloadSetPropString(respPLPost_led, "createduri", newLedUri);
259 if (0 == createLEDResource (newLedUri, &gLedInstance[gCurrLedInstance], false, 0))
261 OC_LOG (INFO, TAG, "Created new LED instance");
262 gLedInstance[gCurrLedInstance].state = 0;
263 gLedInstance[gCurrLedInstance].power = 0;
265 strncpy ((char *)response->resourceUri, newLedUri, MAX_URI_LENGTH);
266 ehResult = OC_EH_RESOURCE_CREATED;
271 respPLPost_led = constructResponse(ehRequest);
276 for (int i = 0; i < SAMPLE_MAX_NUM_POST_INSTANCE; i++)
278 if (ehRequest->resource == gLedInstance[i].handle)
282 respPLPost_led = constructResponse(ehRequest);
287 respPLPost_led = constructResponse(ehRequest);
293 if (respPLPost_led != NULL)
295 *payload = respPLPost_led;
300 OC_LOG_V (INFO, TAG, "Payload was NULL");
301 ehResult = OC_EH_ERROR;
307 OCEntityHandlerResult
308 OCEntityHandlerCb (OCEntityHandlerFlag flag,
309 OCEntityHandlerRequest *entityHandlerRequest,
312 OC_LOG_V (INFO, TAG, "Inside entity handler - flags: 0x%x", flag);
314 OCEntityHandlerResult ehResult = OC_EH_ERROR;
315 OCEntityHandlerResponse response = {};
318 if (!entityHandlerRequest)
320 OC_LOG (ERROR, TAG, "Invalid request pointer");
324 OCRepPayload* payload = NULL;
326 if (flag & OC_REQUEST_FLAG)
328 OC_LOG (INFO, TAG, "Flag includes OC_REQUEST_FLAG");
329 if (entityHandlerRequest)
331 if (OC_REST_GET == entityHandlerRequest->method)
333 OC_LOG (INFO, TAG, "Received OC_REST_GET from client");
334 ehResult = ProcessGetRequest (entityHandlerRequest, &payload);
336 else if (OC_REST_PUT == entityHandlerRequest->method)
338 OC_LOG (INFO, TAG, "Received OC_REST_PUT from client");
339 ehResult = ProcessPutRequest (entityHandlerRequest, &payload);
341 else if (OC_REST_POST == entityHandlerRequest->method)
343 OC_LOG (INFO, TAG, "Received OC_REST_POST from client");
344 ehResult = ProcessPostRequest (entityHandlerRequest, &response, &payload);
348 OC_LOG_V (INFO, TAG, "Received unsupported method %d from client",
349 entityHandlerRequest->method);
350 ehResult = OC_EH_ERROR;
353 if (ehResult == OC_EH_OK && ehResult != OC_EH_FORBIDDEN)
355 // Format the response. Note this requires some info about the request
356 response.requestHandle = entityHandlerRequest->requestHandle;
357 response.resourceHandle = entityHandlerRequest->resource;
358 response.ehResult = ehResult;
359 response.payload = (OCPayload*)(payload);
360 response.numSendVendorSpecificHeaderOptions = 0;
361 memset(response.sendVendorSpecificHeaderOptions, 0,
362 sizeof(response.sendVendorSpecificHeaderOptions));
363 memset(response.resourceUri, 0, sizeof(response.resourceUri));
364 // Indicate that response is NOT in a persistent buffer
365 response.persistentBufferFlag = 0;
368 if (OCDoResponse(&response) != OC_STACK_OK)
370 OC_LOG(ERROR, TAG, "Error sending response");
371 ehResult = OC_EH_ERROR;
377 OCPayloadDestroy(response.payload);
381 /* SIGINT handler: set gQuitFlag to 1 for graceful termination */
382 void handleSigInt(int signum)
384 if (signum == SIGINT)
390 FILE* server_fopen(const char *path, const char *mode)
393 return fopen(CRED_FILE, mode);
398 struct timespec timeout;
400 OC_LOG(DEBUG, TAG, "OCServer is starting...");
402 // Initialize Persistent Storage for SVR database
403 OCPersistentStorage ps = {};
404 ps.open = server_fopen;
409 OCRegisterPersistentStorageHandler(&ps);
411 if (OCInit(NULL, 0, OC_SERVER) != OC_STACK_OK)
413 OC_LOG(ERROR, TAG, "OCStack init error");
418 * Declare and create the example resource: LED
420 createLEDResource(gResourceUri, &LED, false, 0);
423 timeout.tv_nsec = 100000000L;
425 // Break from loop with Ctrl-C
426 OC_LOG(INFO, TAG, "Entering ocserver main loop...");
427 signal(SIGINT, handleSigInt);
430 if (OCProcess() != OC_STACK_OK)
432 OC_LOG(ERROR, TAG, "OCStack process error");
435 nanosleep(&timeout, NULL);
438 OC_LOG(INFO, TAG, "Exiting ocserver main loop...");
440 if (OCStop() != OC_STACK_OK)
442 OC_LOG(ERROR, TAG, "OCStack process error");
448 int createLEDResource (char *uri, LEDResource *ledResource, bool resourceState, int resourcePower)
452 OC_LOG(ERROR, TAG, "Resource URI cannot be NULL");
456 ledResource->state = resourceState;
457 ledResource->power= resourcePower;
458 OCStackResult res = OCCreateResource(&(ledResource->handle),
460 OC_RSRVD_INTERFACE_DEFAULT,
464 OC_DISCOVERABLE|OC_OBSERVABLE | OC_SECURE);
465 OC_LOG_V(INFO, TAG, "Created LED resource with result: %s", getResult(res));