1 //******************************************************************
3 // Copyright 2014 Intel Mobile Communications GmbH All Rights Reserved.
5 //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
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 //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
36 #include "ocpayload.h"
37 #include "ocserverbasicops.h"
43 static LEDResource LED;
44 // This variable determines instance number of the LED resource.
45 // Used by POST method to create a new instance of LED resource.
46 static int gCurrLedInstance = 0;
47 #define SAMPLE_MAX_NUM_POST_INSTANCE 2
48 static LEDResource gLedInstance[SAMPLE_MAX_NUM_POST_INSTANCE];
50 char *gResourceUri= (char *)"/a/led";
52 //Secure Virtual Resource database for Iotivity Server
53 //It contains Server's Identity and the PSK credentials
54 //of other devices which the server trusts
55 static char CRED_FILE[] = "oic_svr_db_server.dat";
57 OCRepPayload* getPayload(const char* uri, int64_t power, bool state)
59 OCRepPayload* payload = OCRepPayloadCreate();
62 OIC_LOG(ERROR, TAG, PCF("Failed to allocate Payload"));
66 OCRepPayloadSetUri(payload, uri);
67 OCRepPayloadSetPropBool(payload, "state", state);
68 OCRepPayloadSetPropInt(payload, "power", power);
73 //This function takes the request as an input and returns the response
74 OCRepPayload* constructResponse (OCEntityHandlerRequest *ehRequest)
76 if(ehRequest->payload && ehRequest->payload->type != PAYLOAD_TYPE_REPRESENTATION)
78 OIC_LOG(ERROR, TAG, PCF("Incoming payload not a representation"));
82 OCRepPayload* input = reinterpret_cast<OCRepPayload*>(ehRequest->payload);
84 LEDResource *currLEDResource = &LED;
86 if (ehRequest->resource == gLedInstance[0].handle)
88 currLEDResource = &gLedInstance[0];
89 gResourceUri = (char *) "/a/led/0";
91 else if (ehRequest->resource == gLedInstance[1].handle)
93 currLEDResource = &gLedInstance[1];
94 gResourceUri = (char *) "/a/led/1";
97 if(OC_REST_PUT == ehRequest->method)
99 // Get pointer to query
101 if(OCRepPayloadGetPropInt(input, "power", &pow))
103 currLEDResource->power =pow;
107 if(OCRepPayloadGetPropBool(input, "state", &state))
109 currLEDResource->state = state;
113 return getPayload(gResourceUri, currLEDResource->power, currLEDResource->state);
116 OCEntityHandlerResult ProcessGetRequest (OCEntityHandlerRequest *ehRequest,
117 OCRepPayload **payload)
119 OCEntityHandlerResult ehResult;
121 OCRepPayload *getResp = constructResponse(ehRequest);
130 ehResult = OC_EH_ERROR;
136 OCEntityHandlerResult ProcessPutRequest (OCEntityHandlerRequest *ehRequest,
137 OCRepPayload **payload)
139 OCEntityHandlerResult ehResult;
141 OCRepPayload *putResp = constructResponse(ehRequest);
150 ehResult = OC_EH_ERROR;
156 OCEntityHandlerResult ProcessPostRequest (OCEntityHandlerRequest *ehRequest,
157 OCEntityHandlerResponse *response, OCRepPayload **payload)
159 OCRepPayload *respPLPost_led = nullptr;
160 OCEntityHandlerResult ehResult = OC_EH_OK;
163 * The entity handler determines how to process a POST request.
164 * Per the REST paradigm, POST can also be used to update representation of existing
165 * resource or create a new resource.
166 * In the sample below, if the POST is for /a/led then a new instance of the LED
167 * resource is created with default representation (if representation is included in
168 * POST payload it can be used as initial values) as long as the instance is
169 * lesser than max new instance count. Once max instance count is reached, POST on
170 * /a/led updated the representation of /a/led (just like PUT)
173 if (ehRequest->resource == LED.handle)
175 if (gCurrLedInstance < SAMPLE_MAX_NUM_POST_INSTANCE)
177 // Create new LED instance
178 char newLedUri[15] = "/a/led/";
179 int newLedUriLength = strlen(newLedUri);
180 snprintf (newLedUri + newLedUriLength, sizeof(newLedUri)-newLedUriLength, "%d", gCurrLedInstance);
182 respPLPost_led = OCRepPayloadCreate();
183 OCRepPayloadSetUri(respPLPost_led, gResourceUri);
184 OCRepPayloadSetPropString(respPLPost_led, "createduri", newLedUri);
186 if (0 == createLEDResource (newLedUri, &gLedInstance[gCurrLedInstance], false, 0))
188 OIC_LOG (INFO, TAG, "Created new LED instance");
189 gLedInstance[gCurrLedInstance].state = 0;
190 gLedInstance[gCurrLedInstance].power = 0;
192 strncpy ((char *)response->resourceUri, newLedUri, MAX_URI_LENGTH);
193 ehResult = OC_EH_RESOURCE_CREATED;
198 respPLPost_led = constructResponse(ehRequest);
203 for (int i = 0; i < SAMPLE_MAX_NUM_POST_INSTANCE; i++)
205 if (ehRequest->resource == gLedInstance[i].handle)
209 respPLPost_led = constructResponse(ehRequest);
214 respPLPost_led = constructResponse(ehRequest);
220 if (respPLPost_led != NULL)
222 *payload = respPLPost_led;
227 OIC_LOG_V (INFO, TAG, "Payload was NULL");
228 ehResult = OC_EH_ERROR;
234 OCEntityHandlerResult
235 OCEntityHandlerCb (OCEntityHandlerFlag flag,
236 OCEntityHandlerRequest *entityHandlerRequest,
237 void* /*callbackParam*/)
239 OIC_LOG_V (INFO, TAG, "Inside entity handler - flags: 0x%x", flag);
241 OCEntityHandlerResult ehResult = OC_EH_ERROR;
242 OCEntityHandlerResponse response = { 0, 0, OC_EH_ERROR, 0, 0, { },{ 0 }, false };
244 if (!entityHandlerRequest)
246 OIC_LOG (ERROR, TAG, "Invalid request pointer");
250 OCRepPayload* payload = nullptr;
252 if (flag & OC_REQUEST_FLAG)
254 OIC_LOG (INFO, TAG, "Flag includes OC_REQUEST_FLAG");
255 if (entityHandlerRequest)
257 if (OC_REST_GET == entityHandlerRequest->method)
259 OIC_LOG (INFO, TAG, "Received OC_REST_GET from client");
260 ehResult = ProcessGetRequest (entityHandlerRequest, &payload);
262 else if (OC_REST_PUT == entityHandlerRequest->method)
264 OIC_LOG (INFO, TAG, "Received OC_REST_PUT from client");
265 ehResult = ProcessPutRequest (entityHandlerRequest, &payload);
267 else if (OC_REST_POST == entityHandlerRequest->method)
269 OIC_LOG (INFO, TAG, "Received OC_REST_POST from client");
270 ehResult = ProcessPostRequest (entityHandlerRequest, &response, &payload);
274 OIC_LOG_V (INFO, TAG, "Received unsupported method %d from client",
275 entityHandlerRequest->method);
276 ehResult = OC_EH_ERROR;
279 if (ehResult == OC_EH_OK && ehResult != OC_EH_FORBIDDEN)
281 // Format the response. Note this requires some info about the request
282 response.requestHandle = entityHandlerRequest->requestHandle;
283 response.resourceHandle = entityHandlerRequest->resource;
284 response.ehResult = ehResult;
285 response.payload = reinterpret_cast<OCPayload*>(payload);
286 response.numSendVendorSpecificHeaderOptions = 0;
287 memset(response.sendVendorSpecificHeaderOptions, 0, sizeof response.sendVendorSpecificHeaderOptions);
288 memset(response.resourceUri, 0, sizeof(response.resourceUri));
289 // Indicate that response is NOT in a persistent buffer
290 response.persistentBufferFlag = 0;
293 if (OCDoResponse(&response) != OC_STACK_OK)
295 OIC_LOG(ERROR, TAG, "Error sending response");
296 ehResult = OC_EH_ERROR;
302 OCPayloadDestroy(response.payload);
306 /* SIGINT handler: set gQuitFlag to 1 for graceful termination */
307 void handleSigInt(int signum)
309 if (signum == SIGINT)
315 FILE* server_fopen(const char *path, const char *mode)
318 return fopen(CRED_FILE, mode);
321 int main(int /*argc*/, char* /*argv*/[])
323 struct timespec timeout;
325 OIC_LOG(DEBUG, TAG, "OCServer is starting...");
327 // Initialize Persistent Storage for SVR database
328 OCPersistentStorage ps = { server_fopen, fread, fwrite, fclose, unlink };
329 OCRegisterPersistentStorageHandler(&ps);
331 if (OCInit(NULL, 0, OC_SERVER) != OC_STACK_OK)
333 OIC_LOG(ERROR, TAG, "OCStack init error");
338 * Declare and create the example resource: LED
340 createLEDResource(gResourceUri, &LED, false, 0);
343 timeout.tv_nsec = 100000000L;
345 // Break from loop with Ctrl-C
346 OIC_LOG(INFO, TAG, "Entering ocserver main loop...");
347 signal(SIGINT, handleSigInt);
350 if (OCProcess() != OC_STACK_OK)
352 OIC_LOG(ERROR, TAG, "OCStack process error");
358 nanosleep(&timeout, NULL);
359 #endif //defined(_WIN32)
362 OIC_LOG(INFO, TAG, "Exiting ocserver main loop...");
364 if (OCStop() != OC_STACK_OK)
366 OIC_LOG(ERROR, TAG, "OCStack process error");
372 int createLEDResource (char *uri, LEDResource *ledResource, bool resourceState, int resourcePower)
376 OIC_LOG(ERROR, TAG, "Resource URI cannot be NULL");
380 ledResource->state = resourceState;
381 ledResource->power= resourcePower;
382 OCStackResult res = OCCreateResource(&(ledResource->handle),
384 OC_RSRVD_INTERFACE_DEFAULT,
388 OC_DISCOVERABLE|OC_OBSERVABLE | OC_SECURE);
389 OIC_LOG_V(INFO, TAG, "Created LED resource with result: %s", getResult(res));