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 OCRepPayload* getPayload(const char* uri, int64_t power, bool state)
147 OCRepPayload* payload = OCRepPayloadCreate();
150 OIC_LOG(ERROR, TAG, "Failed to allocate Payload");
154 OCRepPayloadSetUri(payload, uri);
155 OCRepPayloadSetPropBool(payload, "state", state);
156 OCRepPayloadSetPropInt(payload, "power", power);
161 //This function takes the request as an input and returns the response
162 OCRepPayload* constructResponse (OCEntityHandlerRequest *ehRequest)
164 if(ehRequest->payload && ehRequest->payload->type != PAYLOAD_TYPE_REPRESENTATION)
166 OIC_LOG(ERROR, TAG, "Incoming payload not a representation");
170 OCRepPayload* input = (OCRepPayload*)(ehRequest->payload);
172 LEDResource *currLEDResource = &LED;
174 if (ehRequest->resource == gLedInstance[0].handle)
176 currLEDResource = &gLedInstance[0];
177 gResourceUri = (char *) "/a/led/0";
179 else if (ehRequest->resource == gLedInstance[1].handle)
181 currLEDResource = &gLedInstance[1];
182 gResourceUri = (char *) "/a/led/1";
185 if(OC_REST_PUT == ehRequest->method)
187 // Get pointer to query
189 if(OCRepPayloadGetPropInt(input, "power", &pow))
191 currLEDResource->power =pow;
195 if(OCRepPayloadGetPropBool(input, "state", &state))
197 currLEDResource->state = state;
201 return getPayload(gResourceUri, currLEDResource->power, currLEDResource->state);
204 OCEntityHandlerResult ProcessGetRequest (OCEntityHandlerRequest *ehRequest,
205 OCRepPayload **payload)
207 OCEntityHandlerResult ehResult;
209 OCRepPayload *getResp = constructResponse(ehRequest);
218 ehResult = OC_EH_ERROR;
224 OCEntityHandlerResult ProcessPutRequest (OCEntityHandlerRequest *ehRequest,
225 OCRepPayload **payload)
227 OCEntityHandlerResult ehResult;
229 OCRepPayload *putResp = constructResponse(ehRequest);
238 ehResult = OC_EH_ERROR;
244 OCEntityHandlerResult ProcessPostRequest (OCEntityHandlerRequest *ehRequest,
245 OCEntityHandlerResponse *response, OCRepPayload **payload)
247 OCRepPayload *respPLPost_led = NULL;
248 OCEntityHandlerResult ehResult = OC_EH_OK;
251 * The entity handler determines how to process a POST request.
252 * Per the REST paradigm, POST can also be used to update representation of existing
253 * resource or create a new resource.
254 * In the sample below, if the POST is for /a/led then a new instance of the LED
255 * resource is created with default representation (if representation is included in
256 * POST payload it can be used as initial values) as long as the instance is
257 * lesser than max new instance count. Once max instance count is reached, POST on
258 * /a/led updated the representation of /a/led (just like PUT)
261 if (ehRequest->resource == LED.handle)
263 if (gCurrLedInstance < SAMPLE_MAX_NUM_POST_INSTANCE)
265 // Create new LED instance
266 char newLedUri[15] = "/a/led/";
267 int newLedUriLength = strlen(newLedUri);
268 snprintf (newLedUri + newLedUriLength, sizeof(newLedUri)-newLedUriLength, "%d", gCurrLedInstance);
270 respPLPost_led = OCRepPayloadCreate();
271 OCRepPayloadSetUri(respPLPost_led, gResourceUri);
272 OCRepPayloadSetPropString(respPLPost_led, "createduri", newLedUri);
274 if (0 == createLEDResource (newLedUri, &gLedInstance[gCurrLedInstance], false, 0))
276 OIC_LOG (INFO, TAG, "Created new LED instance");
277 gLedInstance[gCurrLedInstance].state = 0;
278 gLedInstance[gCurrLedInstance].power = 0;
280 strncpy ((char *)response->resourceUri, newLedUri, MAX_URI_LENGTH);
281 ehResult = OC_EH_RESOURCE_CREATED;
286 respPLPost_led = constructResponse(ehRequest);
291 for (int i = 0; i < SAMPLE_MAX_NUM_POST_INSTANCE; i++)
293 if (ehRequest->resource == gLedInstance[i].handle)
297 respPLPost_led = constructResponse(ehRequest);
302 respPLPost_led = constructResponse(ehRequest);
308 if (respPLPost_led != NULL)
310 *payload = respPLPost_led;
315 OIC_LOG_V (INFO, TAG, "Payload was NULL");
316 ehResult = OC_EH_ERROR;
322 OCEntityHandlerResult
323 OCEntityHandlerCb (OCEntityHandlerFlag flag,
324 OCEntityHandlerRequest *entityHandlerRequest,
327 OIC_LOG_V (INFO, TAG, "Inside entity handler - flags: 0x%x", flag);
329 OCEntityHandlerResult ehResult = OC_EH_ERROR;
331 OCEntityHandlerResponse response;
332 memset(&response, 0, sizeof(response));
335 if (!entityHandlerRequest)
337 OIC_LOG (ERROR, TAG, "Invalid request pointer");
341 OCRepPayload* payload = NULL;
343 if (flag & OC_REQUEST_FLAG)
345 OIC_LOG (INFO, TAG, "Flag includes OC_REQUEST_FLAG");
346 if (entityHandlerRequest)
348 if (OC_REST_GET == entityHandlerRequest->method)
350 OIC_LOG (INFO, TAG, "Received OC_REST_GET from client");
351 ehResult = ProcessGetRequest (entityHandlerRequest, &payload);
353 else if (OC_REST_PUT == entityHandlerRequest->method)
355 OIC_LOG (INFO, TAG, "Received OC_REST_PUT from client");
356 ehResult = ProcessPutRequest (entityHandlerRequest, &payload);
358 else if (OC_REST_POST == entityHandlerRequest->method)
360 OIC_LOG (INFO, TAG, "Received OC_REST_POST from client");
361 ehResult = ProcessPostRequest (entityHandlerRequest, &response, &payload);
365 OIC_LOG_V (INFO, TAG, "Received unsupported method %d from client",
366 entityHandlerRequest->method);
367 ehResult = OC_EH_ERROR;
370 if (ehResult == OC_EH_OK && ehResult != OC_EH_FORBIDDEN)
372 // Format the response. Note this requires some info about the request
373 response.requestHandle = entityHandlerRequest->requestHandle;
374 response.resourceHandle = entityHandlerRequest->resource;
375 response.ehResult = ehResult;
376 response.payload = (OCPayload*)(payload);
377 response.numSendVendorSpecificHeaderOptions = 0;
378 memset(response.sendVendorSpecificHeaderOptions, 0,
379 sizeof(response.sendVendorSpecificHeaderOptions));
380 memset(response.resourceUri, 0, sizeof(response.resourceUri));
381 // Indicate that response is NOT in a persistent buffer
382 response.persistentBufferFlag = 0;
385 if (OCDoResponse(&response) != OC_STACK_OK)
387 OIC_LOG(ERROR, TAG, "Error sending response");
388 ehResult = OC_EH_ERROR;
394 OCPayloadDestroy(response.payload);
398 /* SIGINT handler: set gQuitFlag to 1 for graceful termination */
399 void handleSigInt(int signum)
401 if (signum == SIGINT)
407 FILE* server_fopen(const char *path, const char *mode)
410 return fopen(CRED_FILE, mode);
413 void GeneratePinCB(char* pin, size_t pinSize)
415 if(NULL == pin || pinSize <= 0)
417 OIC_LOG(INFO, TAG, "Invalid PIN");
421 OIC_LOG(INFO, TAG, "============================");
422 OIC_LOG_V(INFO, TAG, " PIN CODE : %s", pin);
423 OIC_LOG(INFO, TAG, "============================");
428 struct timespec timeout;
430 OIC_LOG(DEBUG, TAG, "OCServer is starting...");
432 // Initialize Persistent Storage for SVR database
433 OCPersistentStorage ps = {server_fopen, fread, fwrite, fclose, unlink};
434 OCRegisterPersistentStorageHandler(&ps);
436 if (OCInit(NULL, 0, OC_SERVER) != OC_STACK_OK)
438 OIC_LOG(ERROR, TAG, "OCStack init error");
443 * If server supported random pin based ownership transfer,
444 * callback of print PIN should be registered before runing server.
446 SetGeneratePinCB(&GeneratePinCB);
449 * Declare and create the example resource: LED
451 createLEDResource(gResourceUri, &LED, false, 0);
454 timeout.tv_nsec = 100000000L;
456 // Break from loop with Ctrl-C
457 OIC_LOG(INFO, TAG, "Entering ocserver main loop...");
458 signal(SIGINT, handleSigInt);
461 if (OCProcess() != OC_STACK_OK)
463 OIC_LOG(ERROR, TAG, "OCStack process error");
466 nanosleep(&timeout, NULL);
469 OIC_LOG(INFO, TAG, "Exiting ocserver main loop...");
471 if (OCStop() != OC_STACK_OK)
473 OIC_LOG(ERROR, TAG, "OCStack process error");
479 int createLEDResource (char *uri, LEDResource *ledResource, bool resourceState, int resourcePower)
483 OIC_LOG(ERROR, TAG, "Resource URI cannot be NULL");
487 ledResource->state = resourceState;
488 ledResource->power= resourcePower;
489 OCStackResult res = OCCreateResource(&(ledResource->handle),
491 OC_RSRVD_INTERFACE_DEFAULT,
495 OC_DISCOVERABLE|OC_OBSERVABLE | OC_SECURE);
496 OIC_LOG_V(INFO, TAG, "Created LED resource with result: %s", getResult(res));