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"
37 #include "oxmverifycommon.h"
41 /** @todo stop-gap for naming issue. Windows.h does not like us to use ERROR */
45 #endif //HAVE_WINDOWS_H
46 #include "platform_features.h"
50 #define TAG "SAMPLE_MV_JUSTWORKS"
54 /* Structure to represent a LED resource */
55 typedef struct LEDRESOURCE{
56 OCResourceHandle handle;
61 static LEDResource LED;
62 // This variable determines instance number of the LED resource.
63 // Used by POST method to create a new instance of LED resource.
64 static int gCurrLedInstance = 0;
65 #define SAMPLE_MAX_NUM_POST_INSTANCE 2
66 static LEDResource gLedInstance[SAMPLE_MAX_NUM_POST_INSTANCE];
68 char *gResourceUri= (char *)"/a/led";
70 //Secure Virtual Resource database for Iotivity Server
71 //It contains Server's Identity and the PSK credentials
72 //of other devices which the server trusts
73 static char CRED_FILE[] = "oic_svr_db_server_mvjustworks.dat";
75 /* Function that creates a new LED resource by calling the
76 * OCCreateResource() method.
78 int createLEDResource (char *uri, LEDResource *ledResource, bool resourceState, int resourcePower);
80 /* This method converts the payload to JSON format */
81 OCRepPayload* constructResponse (OCEntityHandlerRequest *ehRequest);
83 /* Following methods process the PUT, GET, POST
86 OCEntityHandlerResult ProcessGetRequest (OCEntityHandlerRequest *ehRequest,
87 OCRepPayload **payload);
88 OCEntityHandlerResult ProcessPutRequest (OCEntityHandlerRequest *ehRequest,
89 OCRepPayload **payload);
90 OCEntityHandlerResult ProcessPostRequest (OCEntityHandlerRequest *ehRequest,
91 OCEntityHandlerResponse *response,
92 OCRepPayload **payload);
94 /* Entity Handler callback functions */
96 OCEntityHandlerCb (OCEntityHandlerFlag flag,
97 OCEntityHandlerRequest *entityHandlerRequest,
100 const char *getResult(OCStackResult result) {
103 return "OC_STACK_OK";
104 case OC_STACK_RESOURCE_CREATED:
105 return "OC_STACK_RESOURCE_CREATED";
106 case OC_STACK_RESOURCE_DELETED:
107 return "OC_STACK_RESOURCE_DELETED";
108 case OC_STACK_INVALID_URI:
109 return "OC_STACK_INVALID_URI";
110 case OC_STACK_INVALID_QUERY:
111 return "OC_STACK_INVALID_QUERY";
112 case OC_STACK_INVALID_IP:
113 return "OC_STACK_INVALID_IP";
114 case OC_STACK_INVALID_PORT:
115 return "OC_STACK_INVALID_PORT";
116 case OC_STACK_INVALID_CALLBACK:
117 return "OC_STACK_INVALID_CALLBACK";
118 case OC_STACK_INVALID_METHOD:
119 return "OC_STACK_INVALID_METHOD";
120 case OC_STACK_NO_MEMORY:
121 return "OC_STACK_NO_MEMORY";
122 case OC_STACK_COMM_ERROR:
123 return "OC_STACK_COMM_ERROR";
124 case OC_STACK_INVALID_PARAM:
125 return "OC_STACK_INVALID_PARAM";
126 case OC_STACK_NOTIMPL:
127 return "OC_STACK_NOTIMPL";
128 case OC_STACK_NO_RESOURCE:
129 return "OC_STACK_NO_RESOURCE";
130 case OC_STACK_RESOURCE_ERROR:
131 return "OC_STACK_RESOURCE_ERROR";
132 case OC_STACK_SLOW_RESOURCE:
133 return "OC_STACK_SLOW_RESOURCE";
134 case OC_STACK_NO_OBSERVERS:
135 return "OC_STACK_NO_OBSERVERS";
137 case OC_STACK_PRESENCE_STOPPED:
138 return "OC_STACK_PRESENCE_STOPPED";
141 return "OC_STACK_ERROR";
147 OCRepPayload* getPayload(const char* uri, int64_t power, bool state)
149 OCRepPayload* payload = OCRepPayloadCreate();
152 OIC_LOG(ERROR, TAG, "Failed to allocate Payload");
156 OCRepPayloadSetUri(payload, uri);
157 OCRepPayloadSetPropBool(payload, "state", state);
158 OCRepPayloadSetPropInt(payload, "power", power);
163 //This function takes the request as an input and returns the response
164 OCRepPayload* constructResponse (OCEntityHandlerRequest *ehRequest)
166 if(ehRequest->payload && ehRequest->payload->type != PAYLOAD_TYPE_REPRESENTATION)
168 OIC_LOG(ERROR, TAG, "Incoming payload not a representation");
172 OCRepPayload* input = (OCRepPayload*)(ehRequest->payload);
174 LEDResource *currLEDResource = &LED;
176 if (ehRequest->resource == gLedInstance[0].handle)
178 currLEDResource = &gLedInstance[0];
179 gResourceUri = (char *) "/a/led/0";
181 else if (ehRequest->resource == gLedInstance[1].handle)
183 currLEDResource = &gLedInstance[1];
184 gResourceUri = (char *) "/a/led/1";
187 if(OC_REST_PUT == ehRequest->method)
189 // Get pointer to query
191 if(OCRepPayloadGetPropInt(input, "power", &pow))
193 currLEDResource->power =pow;
197 if(OCRepPayloadGetPropBool(input, "state", &state))
199 currLEDResource->state = state;
203 return getPayload(gResourceUri, currLEDResource->power, currLEDResource->state);
206 OCEntityHandlerResult ProcessGetRequest (OCEntityHandlerRequest *ehRequest,
207 OCRepPayload **payload)
209 OCEntityHandlerResult ehResult;
211 OCRepPayload *getResp = constructResponse(ehRequest);
220 ehResult = OC_EH_ERROR;
226 OCEntityHandlerResult ProcessPutRequest (OCEntityHandlerRequest *ehRequest,
227 OCRepPayload **payload)
229 OCEntityHandlerResult ehResult;
231 OCRepPayload *putResp = constructResponse(ehRequest);
240 ehResult = OC_EH_ERROR;
246 OCEntityHandlerResult ProcessPostRequest (OCEntityHandlerRequest *ehRequest,
247 OCEntityHandlerResponse *response, OCRepPayload **payload)
249 OCRepPayload *respPLPost_led = NULL;
250 OCEntityHandlerResult ehResult = OC_EH_OK;
253 * The entity handler determines how to process a POST request.
254 * Per the REST paradigm, POST can also be used to update representation of existing
255 * resource or create a new resource.
256 * In the sample below, if the POST is for /a/led then a new instance of the LED
257 * resource is created with default representation (if representation is included in
258 * POST payload it can be used as initial values) as long as the instance is
259 * lesser than max new instance count. Once max instance count is reached, POST on
260 * /a/led updated the representation of /a/led (just like PUT)
263 if (ehRequest->resource == LED.handle)
265 if (gCurrLedInstance < SAMPLE_MAX_NUM_POST_INSTANCE)
267 // Create new LED instance
268 char newLedUri[15] = "/a/led/";
269 int newLedUriLength = strlen(newLedUri);
270 snprintf (newLedUri + newLedUriLength, sizeof(newLedUri)-newLedUriLength, "%d", gCurrLedInstance);
272 respPLPost_led = OCRepPayloadCreate();
273 OCRepPayloadSetUri(respPLPost_led, gResourceUri);
274 OCRepPayloadSetPropString(respPLPost_led, "createduri", newLedUri);
276 if (0 == createLEDResource (newLedUri, &gLedInstance[gCurrLedInstance], false, 0))
278 OIC_LOG (INFO, TAG, "Created new LED instance");
279 gLedInstance[gCurrLedInstance].state = 0;
280 gLedInstance[gCurrLedInstance].power = 0;
282 strncpy ((char *)response->resourceUri, newLedUri, MAX_URI_LENGTH);
283 ehResult = OC_EH_RESOURCE_CREATED;
288 respPLPost_led = constructResponse(ehRequest);
293 for (int i = 0; i < SAMPLE_MAX_NUM_POST_INSTANCE; i++)
295 if (ehRequest->resource == gLedInstance[i].handle)
299 respPLPost_led = constructResponse(ehRequest);
304 respPLPost_led = constructResponse(ehRequest);
310 if (respPLPost_led != NULL)
312 *payload = respPLPost_led;
317 OIC_LOG_V (INFO, TAG, "Payload was NULL");
318 ehResult = OC_EH_ERROR;
324 OCEntityHandlerResult
325 OCEntityHandlerCb (OCEntityHandlerFlag flag,
326 OCEntityHandlerRequest *entityHandlerRequest,
329 OIC_LOG_V (INFO, TAG, "Inside entity handler - flags: 0x%x", flag);
331 OCEntityHandlerResult ehResult = OC_EH_ERROR;
333 OCEntityHandlerResponse response;
334 memset(&response, 0, sizeof(response));
337 if (!entityHandlerRequest)
339 OIC_LOG (ERROR, TAG, "Invalid request pointer");
343 OCRepPayload* payload = NULL;
345 if (flag & OC_REQUEST_FLAG)
347 OIC_LOG (INFO, TAG, "Flag includes OC_REQUEST_FLAG");
348 if (entityHandlerRequest)
350 if (OC_REST_GET == entityHandlerRequest->method)
352 OIC_LOG (INFO, TAG, "Received OC_REST_GET from client");
353 ehResult = ProcessGetRequest (entityHandlerRequest, &payload);
355 else if (OC_REST_PUT == entityHandlerRequest->method)
357 OIC_LOG (INFO, TAG, "Received OC_REST_PUT from client");
358 ehResult = ProcessPutRequest (entityHandlerRequest, &payload);
360 else if (OC_REST_POST == entityHandlerRequest->method)
362 OIC_LOG (INFO, TAG, "Received OC_REST_POST from client");
363 ehResult = ProcessPostRequest (entityHandlerRequest, &response, &payload);
367 OIC_LOG_V (INFO, TAG, "Received unsupported method %d from client",
368 entityHandlerRequest->method);
369 ehResult = OC_EH_ERROR;
372 if (ehResult == OC_EH_OK && ehResult != OC_EH_FORBIDDEN)
374 // Format the response. Note this requires some info about the request
375 response.requestHandle = entityHandlerRequest->requestHandle;
376 response.resourceHandle = entityHandlerRequest->resource;
377 response.ehResult = ehResult;
378 response.payload = (OCPayload*)(payload);
379 response.numSendVendorSpecificHeaderOptions = 0;
380 memset(response.sendVendorSpecificHeaderOptions, 0,
381 sizeof(response.sendVendorSpecificHeaderOptions));
382 memset(response.resourceUri, 0, sizeof(response.resourceUri));
383 // Indicate that response is NOT in a persistent buffer
384 response.persistentBufferFlag = 0;
387 if (OCDoResponse(&response) != OC_STACK_OK)
389 OIC_LOG(ERROR, TAG, "Error sending response");
390 ehResult = OC_EH_ERROR;
396 OCPayloadDestroy(response.payload);
400 OCStackResult displayNumCB(void * ctx, uint8_t mutualVerifNum[MUTUAL_VERIF_NUM_LEN])
403 OIC_LOG(INFO, TAG, "IN displayNumCB");
404 OIC_LOG(INFO, TAG, "############ mutualVerifNum ############");
405 OIC_LOG_BUFFER(INFO, TAG, mutualVerifNum, MUTUAL_VERIF_NUM_LEN);
406 OIC_LOG(INFO, TAG, "############ mutualVerifNum ############");
407 OIC_LOG(INFO, TAG, "OUT displayNumCB");
411 OCStackResult confirmNumCB(void * ctx)
418 printf(" > Press 1 for confirmation\n");
419 printf(" > Press 0 otherwise\n");
421 for (int ret=0; 1!=ret; )
423 ret = scanf("%d", &userConfirm);
424 for (; 0x20<=getchar(); ); // for removing overflow garbage
425 // '0x20<=code' is character region
427 if (1 == userConfirm)
431 else if (0 == userConfirm)
433 return OC_STACK_ERROR;
435 printf(" Entered Wrong Number. Please Enter Again\n");
440 /* SIGINT handler: set gQuitFlag to 1 for graceful termination */
441 void handleSigInt(int signum)
443 if (signum == SIGINT)
449 FILE* server_fopen(const char *path, const char *mode)
452 return fopen(CRED_FILE, mode);
457 struct timespec timeout;
459 OIC_LOG(DEBUG, TAG, "OCServer is starting...");
461 // Set callbacks for verification
462 SetDisplayNumCB(NULL, displayNumCB);
463 SetUserConfirmCB(NULL, confirmNumCB);
465 // Set Verification Option for ownership transfer
466 // Currently, BOTH display AND confirm
467 SetVerifyOption((VerifyOptionBitmask_t)(DISPLAY_NUM | USER_CONFIRM));
469 // Initialize Persistent Storage for SVR database
470 OCPersistentStorage ps = {server_fopen, fread, fwrite, fclose, unlink, NULL, NULL};
472 OCRegisterPersistentStorageHandler(&ps);
474 if (OCInit(NULL, 0, OC_SERVER) != OC_STACK_OK)
476 OIC_LOG(ERROR, TAG, "OCStack init error");
481 * Declare and create the example resource: LED
483 createLEDResource(gResourceUri, &LED, false, 0);
486 timeout.tv_nsec = 100000000L;
488 // Break from loop with Ctrl-C
489 OIC_LOG(INFO, TAG, "Entering ocserver main loop...");
490 signal(SIGINT, handleSigInt);
493 if (OCProcess() != OC_STACK_OK)
495 OIC_LOG(ERROR, TAG, "OCStack process error");
498 nanosleep(&timeout, NULL);
501 OIC_LOG(INFO, TAG, "Exiting ocserver main loop...");
503 if (OCStop() != OC_STACK_OK)
505 OIC_LOG(ERROR, TAG, "OCStack process error");
511 int createLEDResource (char *uri, LEDResource *ledResource, bool resourceState, int resourcePower)
515 OIC_LOG(ERROR, TAG, "Resource URI cannot be NULL");
519 ledResource->state = resourceState;
520 ledResource->power= resourcePower;
521 OCStackResult res = OCCreateResource(&(ledResource->handle),
523 OC_RSRVD_INTERFACE_DEFAULT,
527 OC_DISCOVERABLE|OC_OBSERVABLE | OC_SECURE);
528 OIC_LOG_V(INFO, TAG, "Created LED resource with result: %s", getResult(res));