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 ///////////////////////////////////////////////////////////////////////
23 #include "iotivity_config.h"
35 #include "ocpayload.h"
36 #include "pinoxmcommon.h"
40 /** @todo stop-gap for naming issue. Windows.h does not like us to use ERROR */
44 #endif //HAVE_WINDOWS_H
45 #include "platform_features.h"
48 #define TAG "SAMPLE_RANDOMPIN"
52 /* Structure to represent a LED resource */
53 typedef struct LEDRESOURCE{
54 OCResourceHandle handle;
59 static LEDResource LED;
60 // This variable determines instance number of the LED resource.
61 // Used by POST method to create a new instance of LED resource.
62 static int gCurrLedInstance = 0;
63 #define SAMPLE_MAX_NUM_POST_INSTANCE 2
64 static LEDResource gLedInstance[SAMPLE_MAX_NUM_POST_INSTANCE];
66 char *gResourceUri= (char *)"/a/led";
68 //Secure Virtual Resource database for Iotivity Server
69 //It contains Server's Identity and the PSK credentials
70 //of other devices which the server trusts
71 static char CRED_FILE[] = "oic_svr_db_server_randompin.dat";
73 /* Function that creates a new LED resource by calling the
74 * OCCreateResource() method.
76 int createLEDResource (char *uri, LEDResource *ledResource, bool resourceState, int resourcePower);
78 /* This method converts the payload to JSON format */
79 OCRepPayload* constructResponse (OCEntityHandlerRequest *ehRequest);
81 /* Following methods process the PUT, GET, POST
84 OCEntityHandlerResult ProcessGetRequest (OCEntityHandlerRequest *ehRequest,
85 OCRepPayload **payload);
86 OCEntityHandlerResult ProcessPutRequest (OCEntityHandlerRequest *ehRequest,
87 OCRepPayload **payload);
88 OCEntityHandlerResult ProcessPostRequest (OCEntityHandlerRequest *ehRequest,
89 OCEntityHandlerResponse *response,
90 OCRepPayload **payload);
92 /* Entity Handler callback functions */
94 OCEntityHandlerCb (OCEntityHandlerFlag flag,
95 OCEntityHandlerRequest *entityHandlerRequest,
98 const char *getResult(OCStackResult result) {
101 return "OC_STACK_OK";
102 case OC_STACK_RESOURCE_CREATED:
103 return "OC_STACK_RESOURCE_CREATED";
104 case OC_STACK_RESOURCE_DELETED:
105 return "OC_STACK_RESOURCE_DELETED";
106 case OC_STACK_INVALID_URI:
107 return "OC_STACK_INVALID_URI";
108 case OC_STACK_INVALID_QUERY:
109 return "OC_STACK_INVALID_QUERY";
110 case OC_STACK_INVALID_IP:
111 return "OC_STACK_INVALID_IP";
112 case OC_STACK_INVALID_PORT:
113 return "OC_STACK_INVALID_PORT";
114 case OC_STACK_INVALID_CALLBACK:
115 return "OC_STACK_INVALID_CALLBACK";
116 case OC_STACK_INVALID_METHOD:
117 return "OC_STACK_INVALID_METHOD";
118 case OC_STACK_NO_MEMORY:
119 return "OC_STACK_NO_MEMORY";
120 case OC_STACK_COMM_ERROR:
121 return "OC_STACK_COMM_ERROR";
122 case OC_STACK_INVALID_PARAM:
123 return "OC_STACK_INVALID_PARAM";
124 case OC_STACK_NOTIMPL:
125 return "OC_STACK_NOTIMPL";
126 case OC_STACK_NO_RESOURCE:
127 return "OC_STACK_NO_RESOURCE";
128 case OC_STACK_RESOURCE_ERROR:
129 return "OC_STACK_RESOURCE_ERROR";
130 case OC_STACK_SLOW_RESOURCE:
131 return "OC_STACK_SLOW_RESOURCE";
132 case OC_STACK_NO_OBSERVERS:
133 return "OC_STACK_NO_OBSERVERS";
135 case OC_STACK_PRESENCE_STOPPED:
136 return "OC_STACK_PRESENCE_STOPPED";
139 return "OC_STACK_ERROR";
145 #ifdef _ENABLE_MULTIPLE_OWNER_
151 static bool volatile g_LoopFlag;
152 static std::thread* oc_process_thread;
154 static void oc_process_loop()
158 if (OCProcess() != OC_STACK_OK)
160 OIC_LOG(ERROR, TAG, "OCStack process error");
164 std::this_thread::sleep_for(std::chrono::milliseconds(100));
168 static void StartOCProcessThread()
171 oc_process_thread = new std::thread(oc_process_loop);
174 static void StopOCProcessThread()
176 assert(oc_process_thread->joinable() == true);
178 oc_process_thread->join();
180 #endif //_ENABLE_MULTIPLE_OWNER_
182 OCRepPayload* getPayload(const char* uri, int64_t power, bool state)
184 OCRepPayload* payload = OCRepPayloadCreate();
187 OIC_LOG(ERROR, TAG, "Failed to allocate Payload");
191 OCRepPayloadSetUri(payload, uri);
192 OCRepPayloadSetPropBool(payload, "state", state);
193 OCRepPayloadSetPropInt(payload, "power", power);
198 //This function takes the request as an input and returns the response
199 OCRepPayload* constructResponse (OCEntityHandlerRequest *ehRequest)
201 if(ehRequest->payload && ehRequest->payload->type != PAYLOAD_TYPE_REPRESENTATION)
203 OIC_LOG(ERROR, TAG, "Incoming payload not a representation");
207 OCRepPayload* input = (OCRepPayload*)(ehRequest->payload);
209 LEDResource *currLEDResource = &LED;
211 if (ehRequest->resource == gLedInstance[0].handle)
213 currLEDResource = &gLedInstance[0];
214 gResourceUri = (char *) "/a/led/0";
216 else if (ehRequest->resource == gLedInstance[1].handle)
218 currLEDResource = &gLedInstance[1];
219 gResourceUri = (char *) "/a/led/1";
222 if(OC_REST_PUT == ehRequest->method)
224 // Get pointer to query
226 if(OCRepPayloadGetPropInt(input, "power", &pow))
228 currLEDResource->power =pow;
232 if(OCRepPayloadGetPropBool(input, "state", &state))
234 currLEDResource->state = state;
238 return getPayload(gResourceUri, currLEDResource->power, currLEDResource->state);
241 OCEntityHandlerResult ProcessGetRequest (OCEntityHandlerRequest *ehRequest,
242 OCRepPayload **payload)
244 OCEntityHandlerResult ehResult;
246 OCRepPayload *getResp = constructResponse(ehRequest);
255 ehResult = OC_EH_ERROR;
261 OCEntityHandlerResult ProcessPutRequest (OCEntityHandlerRequest *ehRequest,
262 OCRepPayload **payload)
264 OCEntityHandlerResult ehResult;
266 OCRepPayload *putResp = constructResponse(ehRequest);
275 ehResult = OC_EH_ERROR;
281 OCEntityHandlerResult ProcessPostRequest (OCEntityHandlerRequest *ehRequest,
282 OCEntityHandlerResponse *response, OCRepPayload **payload)
284 OCRepPayload *respPLPost_led = NULL;
285 OCEntityHandlerResult ehResult = OC_EH_OK;
288 * The entity handler determines how to process a POST request.
289 * Per the REST paradigm, POST can also be used to update representation of existing
290 * resource or create a new resource.
291 * In the sample below, if the POST is for /a/led then a new instance of the LED
292 * resource is created with default representation (if representation is included in
293 * POST payload it can be used as initial values) as long as the instance is
294 * lesser than max new instance count. Once max instance count is reached, POST on
295 * /a/led updated the representation of /a/led (just like PUT)
298 if (ehRequest->resource == LED.handle)
300 if (gCurrLedInstance < SAMPLE_MAX_NUM_POST_INSTANCE)
302 // Create new LED instance
303 char newLedUri[15] = "/a/led/";
304 int newLedUriLength = strlen(newLedUri);
305 snprintf (newLedUri + newLedUriLength, sizeof(newLedUri)-newLedUriLength, "%d", gCurrLedInstance);
307 respPLPost_led = OCRepPayloadCreate();
308 OCRepPayloadSetUri(respPLPost_led, gResourceUri);
309 OCRepPayloadSetPropString(respPLPost_led, "createduri", newLedUri);
311 if (0 == createLEDResource (newLedUri, &gLedInstance[gCurrLedInstance], false, 0))
313 OIC_LOG (INFO, TAG, "Created new LED instance");
314 gLedInstance[gCurrLedInstance].state = 0;
315 gLedInstance[gCurrLedInstance].power = 0;
317 strncpy ((char *)response->resourceUri, newLedUri, sizeof(response->resourceUri));
318 ehResult = OC_EH_RESOURCE_CREATED;
323 respPLPost_led = constructResponse(ehRequest);
328 for (int i = 0; i < SAMPLE_MAX_NUM_POST_INSTANCE; i++)
330 if (ehRequest->resource == gLedInstance[i].handle)
334 respPLPost_led = constructResponse(ehRequest);
339 respPLPost_led = constructResponse(ehRequest);
345 if (respPLPost_led != NULL)
347 *payload = respPLPost_led;
352 OIC_LOG_V (INFO, TAG, "Payload was NULL");
353 ehResult = OC_EH_ERROR;
359 OCEntityHandlerResult
360 OCEntityHandlerCb (OCEntityHandlerFlag flag,
361 OCEntityHandlerRequest *entityHandlerRequest,
364 OIC_LOG_V (INFO, TAG, "Inside entity handler - flags: 0x%x", flag);
366 OCEntityHandlerResult ehResult = OC_EH_ERROR;
368 OCEntityHandlerResponse response;
369 memset(&response, 0, sizeof(response));
372 if (!entityHandlerRequest)
374 OIC_LOG (ERROR, TAG, "Invalid request pointer");
378 OCRepPayload* payload = NULL;
380 if (flag & OC_REQUEST_FLAG)
382 OIC_LOG (INFO, TAG, "Flag includes OC_REQUEST_FLAG");
383 if (entityHandlerRequest)
385 if (OC_REST_GET == entityHandlerRequest->method)
387 OIC_LOG (INFO, TAG, "Received OC_REST_GET from client");
388 ehResult = ProcessGetRequest (entityHandlerRequest, &payload);
390 else if (OC_REST_PUT == entityHandlerRequest->method)
392 OIC_LOG (INFO, TAG, "Received OC_REST_PUT from client");
393 ehResult = ProcessPutRequest (entityHandlerRequest, &payload);
395 else if (OC_REST_POST == entityHandlerRequest->method)
397 OIC_LOG (INFO, TAG, "Received OC_REST_POST from client");
398 ehResult = ProcessPostRequest (entityHandlerRequest, &response, &payload);
402 OIC_LOG_V (INFO, TAG, "Received unsupported method %d from client",
403 entityHandlerRequest->method);
404 ehResult = OC_EH_ERROR;
407 if (ehResult == OC_EH_OK && ehResult != OC_EH_FORBIDDEN)
409 // Format the response. Note this requires some info about the request
410 response.requestHandle = entityHandlerRequest->requestHandle;
411 response.resourceHandle = entityHandlerRequest->resource;
412 response.ehResult = ehResult;
413 response.payload = (OCPayload*)(payload);
414 response.numSendVendorSpecificHeaderOptions = 0;
415 memset(response.sendVendorSpecificHeaderOptions, 0,
416 sizeof(response.sendVendorSpecificHeaderOptions));
417 memset(response.resourceUri, 0, sizeof(response.resourceUri));
418 // Indicate that response is NOT in a persistent buffer
419 response.persistentBufferFlag = 0;
422 if (OCDoResponse(&response) != OC_STACK_OK)
424 OIC_LOG(ERROR, TAG, "Error sending response");
425 ehResult = OC_EH_ERROR;
431 OCPayloadDestroy(response.payload);
435 /* SIGINT handler: set gQuitFlag to 1 for graceful termination */
436 void handleSigInt(int signum)
438 if (signum == SIGINT)
444 FILE* server_fopen(const char *path, const char *mode)
447 return fopen(CRED_FILE, mode);
450 void GeneratePinCB(char* pin, size_t pinSize)
452 if(NULL == pin || pinSize <= 0)
454 OIC_LOG(INFO, TAG, "Invalid PIN");
458 OIC_LOG(INFO, TAG, "============================");
459 OIC_LOG_V(INFO, TAG, " PIN CODE : %s", pin);
460 OIC_LOG(INFO, TAG, "============================");
465 OIC_LOG(DEBUG, TAG, "OCServer is starting...");
467 // Initialize Persistent Storage for SVR database
468 OCPersistentStorage ps = {server_fopen, fread, fwrite, fclose, unlink};
469 OCRegisterPersistentStorageHandler(&ps);
471 if (OCInit(NULL, 0, OC_SERVER) != OC_STACK_OK)
473 OIC_LOG(ERROR, TAG, "OCStack init error");
478 * If server supported random pin based ownership transfer,
479 * callback of print PIN should be registered before runing server.
481 SetGeneratePinCB(GeneratePinCB);
484 * Random PIN generation policy can be changed through SetRandomPinPolicy() API.
485 * first param : byte length of random PIN ( 4 <= first param <= 32)
486 * second param : PIN type (This is bitmask)
488 if(OC_STACK_OK != SetRandomPinPolicy(8, NUM_PIN))
490 OIC_LOG(ERROR, TAG, "Failed to setting PIN policy");
495 * Declare and create the example resource: LED
497 createLEDResource(gResourceUri, &LED, false, 0);
499 // Break from loop with Ctrl-C
500 OIC_LOG(INFO, TAG, "Entering ocserver main loop...");
501 signal(SIGINT, handleSigInt);
503 #ifdef _ENABLE_MULTIPLE_OWNER_
504 StartOCProcessThread();
508 printf("Press 'G' to generate random PIN...\n");
509 printf("Press 'E' to exit...\n");
511 if('G' == in || 'g' == in)
513 char ranPin[OXM_RANDOM_PIN_MAX_SIZE + 1] = {0};
514 GeneratePin(ranPin, sizeof(ranPin));
516 if('E' == in || 'e' == in)
522 StopOCProcessThread();
524 struct timespec timeout;
526 timeout.tv_nsec = 100000000L;
530 if (OCProcess() != OC_STACK_OK)
532 OIC_LOG(ERROR, TAG, "OCStack process error");
535 nanosleep(&timeout, NULL);
537 #endif //_ENABLE_MULTIPLE_OWNER_
539 OIC_LOG(INFO, TAG, "Exiting ocserver main loop...");
541 if (OCStop() != OC_STACK_OK)
543 OIC_LOG(ERROR, TAG, "OCStack process error");
549 int createLEDResource (char *uri, LEDResource *ledResource, bool resourceState, int resourcePower)
553 OIC_LOG(ERROR, TAG, "Resource URI cannot be NULL");
557 ledResource->state = resourceState;
558 ledResource->power= resourcePower;
559 OCStackResult res = OCCreateResource(&(ledResource->handle),
561 OC_RSRVD_INTERFACE_DEFAULT,
565 OC_DISCOVERABLE|OC_OBSERVABLE | OC_SECURE);
566 OIC_LOG_V(INFO, TAG, "Created LED resource with result: %s", getResult(res));