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 ///////////////////////////////////////////////////////////////////////
34 #include "ocpayload.h"
35 #include "pinoxmcommon.h"
39 /** @todo stop-gap for naming issue. Windows.h does not like us to use ERROR */
43 #endif //HAVE_WINDOWS_H
44 #include "platform_features.h"
47 #define TAG "SAMPLE_RANDOMPIN"
51 /* Structure to represent a LED resource */
52 typedef struct LEDRESOURCE{
53 OCResourceHandle handle;
58 static LEDResource LED;
59 // This variable determines instance number of the LED resource.
60 // Used by POST method to create a new instance of LED resource.
61 static int gCurrLedInstance = 0;
62 #define SAMPLE_MAX_NUM_POST_INSTANCE 2
63 static LEDResource gLedInstance[SAMPLE_MAX_NUM_POST_INSTANCE];
65 char *gResourceUri= (char *)"/a/led";
67 //Secure Virtual Resource database for Iotivity Server
68 //It contains Server's Identity and the PSK credentials
69 //of other devices which the server trusts
70 static char CRED_FILE[] = "oic_svr_db_server_randompin.dat";
72 /* Function that creates a new LED resource by calling the
73 * OCCreateResource() method.
75 int createLEDResource (char *uri, LEDResource *ledResource, bool resourceState, int resourcePower);
77 /* This method converts the payload to JSON format */
78 OCRepPayload* constructResponse (OCEntityHandlerRequest *ehRequest);
80 /* Following methods process the PUT, GET, POST
83 OCEntityHandlerResult ProcessGetRequest (OCEntityHandlerRequest *ehRequest,
84 OCRepPayload **payload);
85 OCEntityHandlerResult ProcessPutRequest (OCEntityHandlerRequest *ehRequest,
86 OCRepPayload **payload);
87 OCEntityHandlerResult ProcessPostRequest (OCEntityHandlerRequest *ehRequest,
88 OCEntityHandlerResponse *response,
89 OCRepPayload **payload);
91 /* Entity Handler callback functions */
93 OCEntityHandlerCb (OCEntityHandlerFlag flag,
94 OCEntityHandlerRequest *entityHandlerRequest,
97 const char *getResult(OCStackResult result) {
100 return "OC_STACK_OK";
101 case OC_STACK_RESOURCE_CREATED:
102 return "OC_STACK_RESOURCE_CREATED";
103 case OC_STACK_RESOURCE_DELETED:
104 return "OC_STACK_RESOURCE_DELETED";
105 case OC_STACK_INVALID_URI:
106 return "OC_STACK_INVALID_URI";
107 case OC_STACK_INVALID_QUERY:
108 return "OC_STACK_INVALID_QUERY";
109 case OC_STACK_INVALID_IP:
110 return "OC_STACK_INVALID_IP";
111 case OC_STACK_INVALID_PORT:
112 return "OC_STACK_INVALID_PORT";
113 case OC_STACK_INVALID_CALLBACK:
114 return "OC_STACK_INVALID_CALLBACK";
115 case OC_STACK_INVALID_METHOD:
116 return "OC_STACK_INVALID_METHOD";
117 case OC_STACK_NO_MEMORY:
118 return "OC_STACK_NO_MEMORY";
119 case OC_STACK_COMM_ERROR:
120 return "OC_STACK_COMM_ERROR";
121 case OC_STACK_INVALID_PARAM:
122 return "OC_STACK_INVALID_PARAM";
123 case OC_STACK_NOTIMPL:
124 return "OC_STACK_NOTIMPL";
125 case OC_STACK_NO_RESOURCE:
126 return "OC_STACK_NO_RESOURCE";
127 case OC_STACK_RESOURCE_ERROR:
128 return "OC_STACK_RESOURCE_ERROR";
129 case OC_STACK_SLOW_RESOURCE:
130 return "OC_STACK_SLOW_RESOURCE";
131 case OC_STACK_NO_OBSERVERS:
132 return "OC_STACK_NO_OBSERVERS";
134 case OC_STACK_PRESENCE_STOPPED:
135 return "OC_STACK_PRESENCE_STOPPED";
138 return "OC_STACK_ERROR";
144 OCRepPayload* getPayload(const char* uri, int64_t power, bool state)
146 OCRepPayload* payload = OCRepPayloadCreate();
149 OIC_LOG(ERROR, TAG, "Failed to allocate Payload");
153 OCRepPayloadSetUri(payload, uri);
154 OCRepPayloadSetPropBool(payload, "state", state);
155 OCRepPayloadSetPropInt(payload, "power", power);
160 //This function takes the request as an input and returns the response
161 OCRepPayload* constructResponse (OCEntityHandlerRequest *ehRequest)
163 if(ehRequest->payload && ehRequest->payload->type != PAYLOAD_TYPE_REPRESENTATION)
165 OIC_LOG(ERROR, TAG, "Incoming payload not a representation");
169 OCRepPayload* input = (OCRepPayload*)(ehRequest->payload);
171 LEDResource *currLEDResource = &LED;
173 if (ehRequest->resource == gLedInstance[0].handle)
175 currLEDResource = &gLedInstance[0];
176 gResourceUri = (char *) "/a/led/0";
178 else if (ehRequest->resource == gLedInstance[1].handle)
180 currLEDResource = &gLedInstance[1];
181 gResourceUri = (char *) "/a/led/1";
184 if(OC_REST_PUT == ehRequest->method)
186 // Get pointer to query
188 if(OCRepPayloadGetPropInt(input, "power", &pow))
190 currLEDResource->power =pow;
194 if(OCRepPayloadGetPropBool(input, "state", &state))
196 currLEDResource->state = state;
200 return getPayload(gResourceUri, currLEDResource->power, currLEDResource->state);
203 OCEntityHandlerResult ProcessGetRequest (OCEntityHandlerRequest *ehRequest,
204 OCRepPayload **payload)
206 OCEntityHandlerResult ehResult;
208 OCRepPayload *getResp = constructResponse(ehRequest);
217 ehResult = OC_EH_ERROR;
223 OCEntityHandlerResult ProcessPutRequest (OCEntityHandlerRequest *ehRequest,
224 OCRepPayload **payload)
226 OCEntityHandlerResult ehResult;
228 OCRepPayload *putResp = constructResponse(ehRequest);
237 ehResult = OC_EH_ERROR;
243 OCEntityHandlerResult ProcessPostRequest (OCEntityHandlerRequest *ehRequest,
244 OCEntityHandlerResponse *response, OCRepPayload **payload)
246 OCRepPayload *respPLPost_led = NULL;
247 OCEntityHandlerResult ehResult = OC_EH_OK;
250 * The entity handler determines how to process a POST request.
251 * Per the REST paradigm, POST can also be used to update representation of existing
252 * resource or create a new resource.
253 * In the sample below, if the POST is for /a/led then a new instance of the LED
254 * resource is created with default representation (if representation is included in
255 * POST payload it can be used as initial values) as long as the instance is
256 * lesser than max new instance count. Once max instance count is reached, POST on
257 * /a/led updated the representation of /a/led (just like PUT)
260 if (ehRequest->resource == LED.handle)
262 if (gCurrLedInstance < SAMPLE_MAX_NUM_POST_INSTANCE)
264 // Create new LED instance
265 char newLedUri[15] = "/a/led/";
266 int newLedUriLength = strlen(newLedUri);
267 snprintf (newLedUri + newLedUriLength, sizeof(newLedUri)-newLedUriLength, "%d", gCurrLedInstance);
269 respPLPost_led = OCRepPayloadCreate();
270 OCRepPayloadSetUri(respPLPost_led, gResourceUri);
271 OCRepPayloadSetPropString(respPLPost_led, "createduri", newLedUri);
273 if (0 == createLEDResource (newLedUri, &gLedInstance[gCurrLedInstance], false, 0))
275 OIC_LOG (INFO, TAG, "Created new LED instance");
276 gLedInstance[gCurrLedInstance].state = 0;
277 gLedInstance[gCurrLedInstance].power = 0;
279 strncpy ((char *)response->resourceUri, newLedUri, MAX_URI_LENGTH);
280 ehResult = OC_EH_RESOURCE_CREATED;
285 respPLPost_led = constructResponse(ehRequest);
290 for (int i = 0; i < SAMPLE_MAX_NUM_POST_INSTANCE; i++)
292 if (ehRequest->resource == gLedInstance[i].handle)
296 respPLPost_led = constructResponse(ehRequest);
301 respPLPost_led = constructResponse(ehRequest);
307 if (respPLPost_led != NULL)
309 *payload = respPLPost_led;
314 OIC_LOG_V (INFO, TAG, "Payload was NULL");
315 ehResult = OC_EH_ERROR;
321 OCEntityHandlerResult
322 OCEntityHandlerCb (OCEntityHandlerFlag flag,
323 OCEntityHandlerRequest *entityHandlerRequest,
326 OIC_LOG_V (INFO, TAG, "Inside entity handler - flags: 0x%x", flag);
328 OCEntityHandlerResult ehResult = OC_EH_ERROR;
330 OCEntityHandlerResponse response;
331 memset(&response, 0, sizeof(response));
334 if (!entityHandlerRequest)
336 OIC_LOG (ERROR, TAG, "Invalid request pointer");
340 OCRepPayload* payload = NULL;
342 if (flag & OC_REQUEST_FLAG)
344 OIC_LOG (INFO, TAG, "Flag includes OC_REQUEST_FLAG");
345 if (entityHandlerRequest)
347 if (OC_REST_GET == entityHandlerRequest->method)
349 OIC_LOG (INFO, TAG, "Received OC_REST_GET from client");
350 ehResult = ProcessGetRequest (entityHandlerRequest, &payload);
352 else if (OC_REST_PUT == entityHandlerRequest->method)
354 OIC_LOG (INFO, TAG, "Received OC_REST_PUT from client");
355 ehResult = ProcessPutRequest (entityHandlerRequest, &payload);
357 else if (OC_REST_POST == entityHandlerRequest->method)
359 OIC_LOG (INFO, TAG, "Received OC_REST_POST from client");
360 ehResult = ProcessPostRequest (entityHandlerRequest, &response, &payload);
364 OIC_LOG_V (INFO, TAG, "Received unsupported method %d from client",
365 entityHandlerRequest->method);
366 ehResult = OC_EH_ERROR;
369 if (ehResult == OC_EH_OK && ehResult != OC_EH_FORBIDDEN)
371 // Format the response. Note this requires some info about the request
372 response.requestHandle = entityHandlerRequest->requestHandle;
373 response.resourceHandle = entityHandlerRequest->resource;
374 response.ehResult = ehResult;
375 response.payload = (OCPayload*)(payload);
376 response.numSendVendorSpecificHeaderOptions = 0;
377 memset(response.sendVendorSpecificHeaderOptions, 0,
378 sizeof(response.sendVendorSpecificHeaderOptions));
379 memset(response.resourceUri, 0, sizeof(response.resourceUri));
380 // Indicate that response is NOT in a persistent buffer
381 response.persistentBufferFlag = 0;
384 if (OCDoResponse(&response) != OC_STACK_OK)
386 OIC_LOG(ERROR, TAG, "Error sending response");
387 ehResult = OC_EH_ERROR;
393 OCPayloadDestroy(response.payload);
397 /* SIGINT handler: set gQuitFlag to 1 for graceful termination */
398 void handleSigInt(int signum)
400 if (signum == SIGINT)
406 FILE* server_fopen(const char *path, const char *mode)
409 return fopen(CRED_FILE, mode);
412 void GeneratePinCB(char* pin, size_t pinSize)
414 if(NULL == pin || pinSize <= 0)
416 OIC_LOG(INFO, TAG, "Invalid PIN");
420 OIC_LOG(INFO, TAG, "============================");
421 OIC_LOG_V(INFO, TAG, " PIN CODE : %s", pin);
422 OIC_LOG(INFO, TAG, "============================");
427 struct timespec timeout;
429 OIC_LOG(DEBUG, TAG, "OCServer is starting...");
431 // Initialize Persistent Storage for SVR database
432 OCPersistentStorage ps = {server_fopen, fread, fwrite, fclose, unlink};
433 OCRegisterPersistentStorageHandler(&ps);
435 if (OCInit(NULL, 0, OC_SERVER) != OC_STACK_OK)
437 OIC_LOG(ERROR, TAG, "OCStack init error");
442 * If server supported random pin based ownership transfer,
443 * callback of print PIN should be registered before runing server.
445 SetGeneratePinCB(&GeneratePinCB);
448 * Declare and create the example resource: LED
450 createLEDResource(gResourceUri, &LED, false, 0);
453 timeout.tv_nsec = 100000000L;
455 // Break from loop with Ctrl-C
456 OIC_LOG(INFO, TAG, "Entering ocserver main loop...");
457 signal(SIGINT, handleSigInt);
460 if (OCProcess() != OC_STACK_OK)
462 OIC_LOG(ERROR, TAG, "OCStack process error");
465 nanosleep(&timeout, NULL);
468 OIC_LOG(INFO, TAG, "Exiting ocserver main loop...");
470 if (OCStop() != OC_STACK_OK)
472 OIC_LOG(ERROR, TAG, "OCStack process error");
478 int createLEDResource (char *uri, LEDResource *ledResource, bool resourceState, int resourcePower)
482 OIC_LOG(ERROR, TAG, "Resource URI cannot be NULL");
486 ledResource->state = resourceState;
487 ledResource->power= resourcePower;
488 OCStackResult res = OCCreateResource(&(ledResource->handle),
490 OC_RSRVD_INTERFACE_DEFAULT,
494 OC_DISCOVERABLE|OC_OBSERVABLE | OC_SECURE);
495 OIC_LOG_V(INFO, TAG, "Created LED resource with result: %s", getResult(res));