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.dat";
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 OIC_LOG(ERROR, TAG, "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 OIC_LOG(ERROR, TAG, "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 OIC_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 OIC_LOG_V (INFO, TAG, "Payload was NULL");
301 ehResult = OC_EH_ERROR;
307 OCEntityHandlerResult
308 OCEntityHandlerCb (OCEntityHandlerFlag flag,
309 OCEntityHandlerRequest *entityHandlerRequest,
312 OIC_LOG_V (INFO, TAG, "Inside entity handler - flags: 0x%x", flag);
314 OCEntityHandlerResult ehResult = OC_EH_ERROR;
316 OCEntityHandlerResponse response;
317 memset(&response, 0, sizeof(response));
320 if (!entityHandlerRequest)
322 OIC_LOG (ERROR, TAG, "Invalid request pointer");
326 OCRepPayload* payload = NULL;
328 if (flag & OC_REQUEST_FLAG)
330 OIC_LOG (INFO, TAG, "Flag includes OC_REQUEST_FLAG");
331 if (entityHandlerRequest)
333 if (OC_REST_GET == entityHandlerRequest->method)
335 OIC_LOG (INFO, TAG, "Received OC_REST_GET from client");
336 ehResult = ProcessGetRequest (entityHandlerRequest, &payload);
338 else if (OC_REST_PUT == entityHandlerRequest->method)
340 OIC_LOG (INFO, TAG, "Received OC_REST_PUT from client");
341 ehResult = ProcessPutRequest (entityHandlerRequest, &payload);
343 else if (OC_REST_POST == entityHandlerRequest->method)
345 OIC_LOG (INFO, TAG, "Received OC_REST_POST from client");
346 ehResult = ProcessPostRequest (entityHandlerRequest, &response, &payload);
350 OIC_LOG_V (INFO, TAG, "Received unsupported method %d from client",
351 entityHandlerRequest->method);
352 ehResult = OC_EH_ERROR;
355 if (ehResult == OC_EH_OK && ehResult != OC_EH_FORBIDDEN)
357 // Format the response. Note this requires some info about the request
358 response.requestHandle = entityHandlerRequest->requestHandle;
359 response.resourceHandle = entityHandlerRequest->resource;
360 response.ehResult = ehResult;
361 response.payload = (OCPayload*)(payload);
362 response.numSendVendorSpecificHeaderOptions = 0;
363 memset(response.sendVendorSpecificHeaderOptions, 0,
364 sizeof(response.sendVendorSpecificHeaderOptions));
365 memset(response.resourceUri, 0, sizeof(response.resourceUri));
366 // Indicate that response is NOT in a persistent buffer
367 response.persistentBufferFlag = 0;
370 if (OCDoResponse(&response) != OC_STACK_OK)
372 OIC_LOG(ERROR, TAG, "Error sending response");
373 ehResult = OC_EH_ERROR;
379 OCPayloadDestroy(response.payload);
383 /* SIGINT handler: set gQuitFlag to 1 for graceful termination */
384 void handleSigInt(int signum)
386 if (signum == SIGINT)
392 FILE* server_fopen(const char *path, const char *mode)
395 return fopen(CRED_FILE, mode);
400 struct timespec timeout;
402 OIC_LOG(DEBUG, TAG, "OCServer is starting...");
404 // Initialize Persistent Storage for SVR database
405 OCPersistentStorage ps = {server_fopen, fread, fwrite, fclose, unlink};
407 OCRegisterPersistentStorageHandler(&ps);
409 if (OCInit(NULL, 0, OC_SERVER) != OC_STACK_OK)
411 OIC_LOG(ERROR, TAG, "OCStack init error");
416 * Declare and create the example resource: LED
418 createLEDResource(gResourceUri, &LED, false, 0);
421 timeout.tv_nsec = 100000000L;
423 // Break from loop with Ctrl-C
424 OIC_LOG(INFO, TAG, "Entering ocserver main loop...");
425 signal(SIGINT, handleSigInt);
428 if (OCProcess() != OC_STACK_OK)
430 OIC_LOG(ERROR, TAG, "OCStack process error");
433 nanosleep(&timeout, NULL);
436 OIC_LOG(INFO, TAG, "Exiting ocserver main loop...");
438 if (OCStop() != OC_STACK_OK)
440 OIC_LOG(ERROR, TAG, "OCStack process error");
446 int createLEDResource (char *uri, LEDResource *ledResource, bool resourceState, int resourcePower)
450 OIC_LOG(ERROR, TAG, "Resource URI cannot be NULL");
454 ledResource->state = resourceState;
455 ledResource->power= resourcePower;
456 OCStackResult res = OCCreateResource(&(ledResource->handle),
458 OC_RSRVD_INTERFACE_DEFAULT,
462 OC_DISCOVERABLE|OC_OBSERVABLE | OC_SECURE);
463 OIC_LOG_V(INFO, TAG, "Created LED resource with result: %s", getResult(res));