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"
32 #include "pinoxmcommon.h"
34 #define TAG "SAMPLE_RANDOMPIN"
38 /* Structure to represent a LED resource */
39 typedef struct LEDRESOURCE{
40 OCResourceHandle handle;
45 static LEDResource LED;
46 // This variable determines instance number of the LED resource.
47 // Used by POST method to create a new instance of LED resource.
48 static int gCurrLedInstance = 0;
49 #define SAMPLE_MAX_NUM_POST_INSTANCE 2
50 static LEDResource gLedInstance[SAMPLE_MAX_NUM_POST_INSTANCE];
52 char *gResourceUri= (char *)"/a/led";
54 //Secure Virtual Resource database for Iotivity Server
55 //It contains Server's Identity and the PSK credentials
56 //of other devices which the server trusts
57 static char CRED_FILE[] = "oic_svr_db_server_randompin.json";
59 /* Function that creates a new LED resource by calling the
60 * OCCreateResource() method.
62 int createLEDResource (char *uri, LEDResource *ledResource, bool resourceState, int resourcePower);
64 /* This method converts the payload to JSON format */
65 OCRepPayload* constructResponse (OCEntityHandlerRequest *ehRequest);
67 /* Following methods process the PUT, GET, POST
70 OCEntityHandlerResult ProcessGetRequest (OCEntityHandlerRequest *ehRequest,
71 OCRepPayload **payload);
72 OCEntityHandlerResult ProcessPutRequest (OCEntityHandlerRequest *ehRequest,
73 OCRepPayload **payload);
74 OCEntityHandlerResult ProcessPostRequest (OCEntityHandlerRequest *ehRequest,
75 OCEntityHandlerResponse *response,
76 OCRepPayload **payload);
78 /* Entity Handler callback functions */
80 OCEntityHandlerCb (OCEntityHandlerFlag flag,
81 OCEntityHandlerRequest *entityHandlerRequest,
84 const char *getResult(OCStackResult result) {
88 case OC_STACK_RESOURCE_CREATED:
89 return "OC_STACK_RESOURCE_CREATED";
90 case OC_STACK_RESOURCE_DELETED:
91 return "OC_STACK_RESOURCE_DELETED";
92 case OC_STACK_INVALID_URI:
93 return "OC_STACK_INVALID_URI";
94 case OC_STACK_INVALID_QUERY:
95 return "OC_STACK_INVALID_QUERY";
96 case OC_STACK_INVALID_IP:
97 return "OC_STACK_INVALID_IP";
98 case OC_STACK_INVALID_PORT:
99 return "OC_STACK_INVALID_PORT";
100 case OC_STACK_INVALID_CALLBACK:
101 return "OC_STACK_INVALID_CALLBACK";
102 case OC_STACK_INVALID_METHOD:
103 return "OC_STACK_INVALID_METHOD";
104 case OC_STACK_NO_MEMORY:
105 return "OC_STACK_NO_MEMORY";
106 case OC_STACK_COMM_ERROR:
107 return "OC_STACK_COMM_ERROR";
108 case OC_STACK_INVALID_PARAM:
109 return "OC_STACK_INVALID_PARAM";
110 case OC_STACK_NOTIMPL:
111 return "OC_STACK_NOTIMPL";
112 case OC_STACK_NO_RESOURCE:
113 return "OC_STACK_NO_RESOURCE";
114 case OC_STACK_RESOURCE_ERROR:
115 return "OC_STACK_RESOURCE_ERROR";
116 case OC_STACK_SLOW_RESOURCE:
117 return "OC_STACK_SLOW_RESOURCE";
118 case OC_STACK_NO_OBSERVERS:
119 return "OC_STACK_NO_OBSERVERS";
121 case OC_STACK_PRESENCE_STOPPED:
122 return "OC_STACK_PRESENCE_STOPPED";
125 return "OC_STACK_ERROR";
131 OCRepPayload* getPayload(const char* uri, int64_t power, bool state)
133 OCRepPayload* payload = OCRepPayloadCreate();
136 OC_LOG(ERROR, TAG, PCF("Failed to allocate Payload"));
140 OCRepPayloadSetUri(payload, uri);
141 OCRepPayloadSetPropBool(payload, "state", state);
142 OCRepPayloadSetPropInt(payload, "power", power);
147 //This function takes the request as an input and returns the response
148 OCRepPayload* constructResponse (OCEntityHandlerRequest *ehRequest)
150 if(ehRequest->payload && ehRequest->payload->type != PAYLOAD_TYPE_REPRESENTATION)
152 OC_LOG(ERROR, TAG, PCF("Incoming payload not a representation"));
156 OCRepPayload* input = (OCRepPayload*)(ehRequest->payload);
158 LEDResource *currLEDResource = &LED;
160 if (ehRequest->resource == gLedInstance[0].handle)
162 currLEDResource = &gLedInstance[0];
163 gResourceUri = (char *) "/a/led/0";
165 else if (ehRequest->resource == gLedInstance[1].handle)
167 currLEDResource = &gLedInstance[1];
168 gResourceUri = (char *) "/a/led/1";
171 if(OC_REST_PUT == ehRequest->method)
173 // Get pointer to query
175 if(OCRepPayloadGetPropInt(input, "power", &pow))
177 currLEDResource->power =pow;
181 if(OCRepPayloadGetPropBool(input, "state", &state))
183 currLEDResource->state = state;
187 return getPayload(gResourceUri, currLEDResource->power, currLEDResource->state);
190 OCEntityHandlerResult ProcessGetRequest (OCEntityHandlerRequest *ehRequest,
191 OCRepPayload **payload)
193 OCEntityHandlerResult ehResult;
195 OCRepPayload *getResp = constructResponse(ehRequest);
204 ehResult = OC_EH_ERROR;
210 OCEntityHandlerResult ProcessPutRequest (OCEntityHandlerRequest *ehRequest,
211 OCRepPayload **payload)
213 OCEntityHandlerResult ehResult;
215 OCRepPayload *putResp = constructResponse(ehRequest);
224 ehResult = OC_EH_ERROR;
230 OCEntityHandlerResult ProcessPostRequest (OCEntityHandlerRequest *ehRequest,
231 OCEntityHandlerResponse *response, OCRepPayload **payload)
233 OCRepPayload *respPLPost_led = NULL;
234 OCEntityHandlerResult ehResult = OC_EH_OK;
237 * The entity handler determines how to process a POST request.
238 * Per the REST paradigm, POST can also be used to update representation of existing
239 * resource or create a new resource.
240 * In the sample below, if the POST is for /a/led then a new instance of the LED
241 * resource is created with default representation (if representation is included in
242 * POST payload it can be used as initial values) as long as the instance is
243 * lesser than max new instance count. Once max instance count is reached, POST on
244 * /a/led updated the representation of /a/led (just like PUT)
247 if (ehRequest->resource == LED.handle)
249 if (gCurrLedInstance < SAMPLE_MAX_NUM_POST_INSTANCE)
251 // Create new LED instance
252 char newLedUri[15] = "/a/led/";
253 int newLedUriLength = strlen(newLedUri);
254 snprintf (newLedUri + newLedUriLength, sizeof(newLedUri)-newLedUriLength, "%d", gCurrLedInstance);
256 respPLPost_led = OCRepPayloadCreate();
257 OCRepPayloadSetUri(respPLPost_led, gResourceUri);
258 OCRepPayloadSetPropString(respPLPost_led, "createduri", newLedUri);
260 if (0 == createLEDResource (newLedUri, &gLedInstance[gCurrLedInstance], false, 0))
262 OC_LOG (INFO, TAG, "Created new LED instance");
263 gLedInstance[gCurrLedInstance].state = 0;
264 gLedInstance[gCurrLedInstance].power = 0;
266 strncpy ((char *)response->resourceUri, newLedUri, MAX_URI_LENGTH);
267 ehResult = OC_EH_RESOURCE_CREATED;
272 respPLPost_led = constructResponse(ehRequest);
277 for (int i = 0; i < SAMPLE_MAX_NUM_POST_INSTANCE; i++)
279 if (ehRequest->resource == gLedInstance[i].handle)
283 respPLPost_led = constructResponse(ehRequest);
288 respPLPost_led = constructResponse(ehRequest);
294 if (respPLPost_led != NULL)
296 *payload = respPLPost_led;
301 OC_LOG_V (INFO, TAG, "Payload was NULL");
302 ehResult = OC_EH_ERROR;
308 OCEntityHandlerResult
309 OCEntityHandlerCb (OCEntityHandlerFlag flag,
310 OCEntityHandlerRequest *entityHandlerRequest,
313 OC_LOG_V (INFO, TAG, "Inside entity handler - flags: 0x%x", flag);
315 OCEntityHandlerResult ehResult = OC_EH_ERROR;
317 OCEntityHandlerResponse response;
318 memset(&response, 0, sizeof(response));
321 if (!entityHandlerRequest)
323 OC_LOG (ERROR, TAG, "Invalid request pointer");
327 OCRepPayload* payload = NULL;
329 if (flag & OC_REQUEST_FLAG)
331 OC_LOG (INFO, TAG, "Flag includes OC_REQUEST_FLAG");
332 if (entityHandlerRequest)
334 if (OC_REST_GET == entityHandlerRequest->method)
336 OC_LOG (INFO, TAG, "Received OC_REST_GET from client");
337 ehResult = ProcessGetRequest (entityHandlerRequest, &payload);
339 else if (OC_REST_PUT == entityHandlerRequest->method)
341 OC_LOG (INFO, TAG, "Received OC_REST_PUT from client");
342 ehResult = ProcessPutRequest (entityHandlerRequest, &payload);
344 else if (OC_REST_POST == entityHandlerRequest->method)
346 OC_LOG (INFO, TAG, "Received OC_REST_POST from client");
347 ehResult = ProcessPostRequest (entityHandlerRequest, &response, &payload);
351 OC_LOG_V (INFO, TAG, "Received unsupported method %d from client",
352 entityHandlerRequest->method);
353 ehResult = OC_EH_ERROR;
356 if (ehResult == OC_EH_OK && ehResult != OC_EH_FORBIDDEN)
358 // Format the response. Note this requires some info about the request
359 response.requestHandle = entityHandlerRequest->requestHandle;
360 response.resourceHandle = entityHandlerRequest->resource;
361 response.ehResult = ehResult;
362 response.payload = (OCPayload*)(payload);
363 response.numSendVendorSpecificHeaderOptions = 0;
364 memset(response.sendVendorSpecificHeaderOptions, 0,
365 sizeof(response.sendVendorSpecificHeaderOptions));
366 memset(response.resourceUri, 0, sizeof(response.resourceUri));
367 // Indicate that response is NOT in a persistent buffer
368 response.persistentBufferFlag = 0;
371 if (OCDoResponse(&response) != OC_STACK_OK)
373 OC_LOG(ERROR, TAG, "Error sending response");
374 ehResult = OC_EH_ERROR;
380 OCPayloadDestroy(response.payload);
384 /* SIGINT handler: set gQuitFlag to 1 for graceful termination */
385 void handleSigInt(int signum)
387 if (signum == SIGINT)
393 FILE* server_fopen(const char *path, const char *mode)
396 return fopen(CRED_FILE, mode);
399 void GeneratePinCB(char* pin, size_t pinSize)
401 if(NULL == pin || pinSize <= 0)
403 OC_LOG(INFO, TAG, "Invalid PIN");
407 OC_LOG(INFO, TAG, "============================");
408 OC_LOG_V(INFO, TAG, " PIN CODE : %s", pin);
409 OC_LOG(INFO, TAG, "============================");
414 struct timespec timeout;
416 OC_LOG(DEBUG, TAG, "OCServer is starting...");
418 // Initialize Persistent Storage for SVR database
419 OCPersistentStorage ps = {server_fopen, fread, fwrite, fclose, unlink};
420 OCRegisterPersistentStorageHandler(&ps);
422 if (OCInit(NULL, 0, OC_SERVER) != OC_STACK_OK)
424 OC_LOG(ERROR, TAG, "OCStack init error");
429 * If server supported random pin based ownership transfer,
430 * callback of print PIN should be registered before runing server.
432 SetGeneratePinCB(&GeneratePinCB);
435 * Declare and create the example resource: LED
437 createLEDResource(gResourceUri, &LED, false, 0);
440 timeout.tv_nsec = 100000000L;
442 // Break from loop with Ctrl-C
443 OC_LOG(INFO, TAG, "Entering ocserver main loop...");
444 signal(SIGINT, handleSigInt);
447 if (OCProcess() != OC_STACK_OK)
449 OC_LOG(ERROR, TAG, "OCStack process error");
452 nanosleep(&timeout, NULL);
455 OC_LOG(INFO, TAG, "Exiting ocserver main loop...");
457 if (OCStop() != OC_STACK_OK)
459 OC_LOG(ERROR, TAG, "OCStack process error");
465 int createLEDResource (char *uri, LEDResource *ledResource, bool resourceState, int resourcePower)
469 OC_LOG(ERROR, TAG, "Resource URI cannot be NULL");
473 ledResource->state = resourceState;
474 ledResource->power= resourcePower;
475 OCStackResult res = OCCreateResource(&(ledResource->handle),
477 OC_RSRVD_INTERFACE_DEFAULT,
481 OC_DISCOVERABLE|OC_OBSERVABLE | OC_SECURE);
482 OC_LOG_V(INFO, TAG, "Created LED resource with result: %s", getResult(res));