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;
316 OCEntityHandlerResponse response = {};
319 if (!entityHandlerRequest)
321 OC_LOG (ERROR, TAG, "Invalid request pointer");
325 OCRepPayload* payload = NULL;
327 if (flag & OC_REQUEST_FLAG)
329 OC_LOG (INFO, TAG, "Flag includes OC_REQUEST_FLAG");
330 if (entityHandlerRequest)
332 if (OC_REST_GET == entityHandlerRequest->method)
334 OC_LOG (INFO, TAG, "Received OC_REST_GET from client");
335 ehResult = ProcessGetRequest (entityHandlerRequest, &payload);
337 else if (OC_REST_PUT == entityHandlerRequest->method)
339 OC_LOG (INFO, TAG, "Received OC_REST_PUT from client");
340 ehResult = ProcessPutRequest (entityHandlerRequest, &payload);
342 else if (OC_REST_POST == entityHandlerRequest->method)
344 OC_LOG (INFO, TAG, "Received OC_REST_POST from client");
345 ehResult = ProcessPostRequest (entityHandlerRequest, &response, &payload);
349 OC_LOG_V (INFO, TAG, "Received unsupported method %d from client",
350 entityHandlerRequest->method);
351 ehResult = OC_EH_ERROR;
354 if (ehResult == OC_EH_OK && ehResult != OC_EH_FORBIDDEN)
356 // Format the response. Note this requires some info about the request
357 response.requestHandle = entityHandlerRequest->requestHandle;
358 response.resourceHandle = entityHandlerRequest->resource;
359 response.ehResult = ehResult;
360 response.payload = (OCPayload*)(payload);
361 response.numSendVendorSpecificHeaderOptions = 0;
362 memset(response.sendVendorSpecificHeaderOptions, 0,
363 sizeof(response.sendVendorSpecificHeaderOptions));
364 memset(response.resourceUri, 0, sizeof(response.resourceUri));
365 // Indicate that response is NOT in a persistent buffer
366 response.persistentBufferFlag = 0;
369 if (OCDoResponse(&response) != OC_STACK_OK)
371 OC_LOG(ERROR, TAG, "Error sending response");
372 ehResult = OC_EH_ERROR;
378 OCPayloadDestroy(response.payload);
382 /* SIGINT handler: set gQuitFlag to 1 for graceful termination */
383 void handleSigInt(int signum)
385 if (signum == SIGINT)
391 FILE* server_fopen(const char *path, const char *mode)
394 return fopen(CRED_FILE, mode);
397 void GeneratePinCB(char* pin, size_t pinSize)
399 if(NULL == pin || pinSize <= 0)
401 OC_LOG(INFO, TAG, "Invalid PIN");
405 OC_LOG(INFO, TAG, "============================");
406 OC_LOG_V(INFO, TAG, " PIN CODE : %s", pin);
407 OC_LOG(INFO, TAG, "============================");
410 int main(int argc, char* argv[])
412 struct timespec timeout;
414 OC_LOG(DEBUG, TAG, "OCServer is starting...");
416 // Initialize Persistent Storage for SVR database
417 OCPersistentStorage ps = {};
418 ps.open = server_fopen;
423 OCRegisterPersistentStorageHandler(&ps);
425 if (OCInit(NULL, 0, OC_SERVER) != OC_STACK_OK)
427 OC_LOG(ERROR, TAG, "OCStack init error");
432 * If server supported random pin based ownership transfer,
433 * callback of print PIN should be registered before runing server.
435 SetGeneratePinCB(&GeneratePinCB);
438 * Declare and create the example resource: LED
440 createLEDResource(gResourceUri, &LED, false, 0);
443 timeout.tv_nsec = 100000000L;
445 // Break from loop with Ctrl-C
446 OC_LOG(INFO, TAG, "Entering ocserver main loop...");
447 signal(SIGINT, handleSigInt);
450 if (OCProcess() != OC_STACK_OK)
452 OC_LOG(ERROR, TAG, "OCStack process error");
455 nanosleep(&timeout, NULL);
458 OC_LOG(INFO, TAG, "Exiting ocserver main loop...");
460 if (OCStop() != OC_STACK_OK)
462 OC_LOG(ERROR, TAG, "OCStack process error");
468 int createLEDResource (char *uri, LEDResource *ledResource, bool resourceState, int resourcePower)
472 OC_LOG(ERROR, TAG, "Resource URI cannot be NULL");
476 ledResource->state = resourceState;
477 ledResource->power= resourcePower;
478 OCStackResult res = OCCreateResource(&(ledResource->handle),
480 OC_RSRVD_INTERFACE_DEFAULT,
484 OC_DISCOVERABLE|OC_OBSERVABLE | OC_SECURE);
485 OC_LOG_V(INFO, TAG, "Created LED resource with result: %s", getResult(res));