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 //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
21 #include "iotivity_config.h"
37 #include "ocpayload.h"
38 #include "ocserverbasicops.h"
44 static LEDResource LED;
45 // This variable determines instance number of the LED resource.
46 // Used by POST method to create a new instance of LED resource.
47 static int gCurrLedInstance = 0;
48 #define SAMPLE_MAX_NUM_POST_INSTANCE 2
49 static LEDResource gLedInstance[SAMPLE_MAX_NUM_POST_INSTANCE];
51 char *gResourceUri= (char *)"/a/led";
53 //Secure Virtual Resource database for Iotivity Server
54 //It contains Server's Identity and the PSK credentials
55 //of other devices which the server trusts
56 static char CRED_FILE[] = "oic_svr_db_server.dat";
58 OCRepPayload* getPayload(const char* uri, int64_t power, bool state)
60 OCRepPayload* payload = OCRepPayloadCreate();
63 OIC_LOG(ERROR, TAG, PCF("Failed to allocate Payload"));
67 OCRepPayloadSetUri(payload, uri);
68 OCRepPayloadSetPropBool(payload, "state", state);
69 OCRepPayloadSetPropInt(payload, "power", power);
74 //This function takes the request as an input and returns the response
75 OCRepPayload* constructResponse (OCEntityHandlerRequest *ehRequest)
77 if(ehRequest->payload && ehRequest->payload->type != PAYLOAD_TYPE_REPRESENTATION)
79 OIC_LOG(ERROR, TAG, PCF("Incoming payload not a representation"));
83 OCRepPayload* input = reinterpret_cast<OCRepPayload*>(ehRequest->payload);
85 LEDResource *currLEDResource = &LED;
87 if (ehRequest->resource == gLedInstance[0].handle)
89 currLEDResource = &gLedInstance[0];
90 gResourceUri = (char *) "/a/led/0";
92 else if (ehRequest->resource == gLedInstance[1].handle)
94 currLEDResource = &gLedInstance[1];
95 gResourceUri = (char *) "/a/led/1";
98 if(OC_REST_PUT == ehRequest->method
99 || OC_REST_POST == ehRequest->method)
101 // Get pointer to query
103 if(OCRepPayloadGetPropInt(input, "power", &pow))
105 currLEDResource->power =pow;
109 if(OCRepPayloadGetPropBool(input, "state", &state))
111 currLEDResource->state = state;
115 return getPayload(gResourceUri, currLEDResource->power, currLEDResource->state);
118 OCEntityHandlerResult ProcessGetRequest (OCEntityHandlerRequest *ehRequest,
119 OCRepPayload **payload)
121 OCEntityHandlerResult ehResult;
123 OCRepPayload *getResp = constructResponse(ehRequest);
132 ehResult = OC_EH_ERROR;
138 OCEntityHandlerResult ProcessPutRequest (OCEntityHandlerRequest *ehRequest,
139 OCRepPayload **payload)
141 OCEntityHandlerResult ehResult;
143 OCRepPayload *putResp = constructResponse(ehRequest);
152 ehResult = OC_EH_ERROR;
158 OCEntityHandlerResult ProcessPostRequest (OCEntityHandlerRequest *ehRequest,
159 OCEntityHandlerResponse *response, OCRepPayload **payload)
161 OCRepPayload *respPLPost_led = nullptr;
162 OCEntityHandlerResult ehResult = OC_EH_OK;
165 * The entity handler determines how to process a POST request.
166 * Per the REST paradigm, POST can also be used to update representation of existing
167 * resource or create a new resource.
168 * In the sample below, if the POST is for /a/led then a new instance of the LED
169 * resource is created with default representation (if representation is included in
170 * POST payload it can be used as initial values) as long as the instance is
171 * lesser than max new instance count. Once max instance count is reached, POST on
172 * /a/led updated the representation of /a/led.
175 if (ehRequest->resource == LED.handle)
177 if (gCurrLedInstance < SAMPLE_MAX_NUM_POST_INSTANCE)
179 // Create new LED instance
180 char newLedUri[15] = "/a/led/";
181 int newLedUriLength = strlen(newLedUri);
182 snprintf (newLedUri + newLedUriLength, sizeof(newLedUri)-newLedUriLength, "%d", gCurrLedInstance);
184 respPLPost_led = OCRepPayloadCreate();
185 OCRepPayloadSetUri(respPLPost_led, gResourceUri);
186 OCRepPayloadSetPropString(respPLPost_led, "createduri", newLedUri);
188 if (0 == createLEDResource (newLedUri, &gLedInstance[gCurrLedInstance], false, 0))
190 OIC_LOG (INFO, TAG, "Created new LED instance");
191 gLedInstance[gCurrLedInstance].state = 0;
192 gLedInstance[gCurrLedInstance].power = 0;
194 strncpy ((char *)response->resourceUri, newLedUri, MAX_URI_LENGTH);
195 ehResult = OC_EH_RESOURCE_CREATED;
200 respPLPost_led = constructResponse(ehRequest);
205 for (int i = 0; i < SAMPLE_MAX_NUM_POST_INSTANCE; i++)
207 if (ehRequest->resource == gLedInstance[i].handle)
211 respPLPost_led = constructResponse(ehRequest);
216 respPLPost_led = constructResponse(ehRequest);
222 if (respPLPost_led != NULL)
224 *payload = respPLPost_led;
229 OIC_LOG_V (INFO, TAG, "Payload was NULL");
230 ehResult = OC_EH_ERROR;
236 OCEntityHandlerResult
237 OCEntityHandlerCb (OCEntityHandlerFlag flag,
238 OCEntityHandlerRequest *entityHandlerRequest,
239 void* /*callbackParam*/)
241 OIC_LOG_V (INFO, TAG, "Inside entity handler - flags: 0x%x", flag);
243 OCEntityHandlerResult ehResult = OC_EH_ERROR;
244 OCEntityHandlerResponse response = { 0, 0, OC_EH_ERROR, 0, 0, { },{ 0 }, false };
246 if (!entityHandlerRequest)
248 OIC_LOG (ERROR, TAG, "Invalid request pointer");
252 OCRepPayload* payload = nullptr;
254 if (flag & OC_REQUEST_FLAG)
256 OIC_LOG (INFO, TAG, "Flag includes OC_REQUEST_FLAG");
257 if (entityHandlerRequest)
259 if (OC_REST_GET == entityHandlerRequest->method)
261 OIC_LOG (INFO, TAG, "Received OC_REST_GET from client");
262 ehResult = ProcessGetRequest (entityHandlerRequest, &payload);
264 else if (OC_REST_PUT == entityHandlerRequest->method)
266 OIC_LOG (INFO, TAG, "Received OC_REST_PUT from client");
267 ehResult = ProcessPutRequest (entityHandlerRequest, &payload);
269 else if (OC_REST_POST == entityHandlerRequest->method)
271 OIC_LOG (INFO, TAG, "Received OC_REST_POST from client");
272 ehResult = ProcessPostRequest (entityHandlerRequest, &response, &payload);
276 OIC_LOG_V (INFO, TAG, "Received unsupported method %d from client",
277 entityHandlerRequest->method);
278 ehResult = OC_EH_ERROR;
281 if (ehResult == OC_EH_OK && ehResult != OC_EH_FORBIDDEN)
283 // Format the response. Note this requires some info about the request
284 response.requestHandle = entityHandlerRequest->requestHandle;
285 response.resourceHandle = entityHandlerRequest->resource;
286 response.ehResult = ehResult;
287 response.payload = reinterpret_cast<OCPayload*>(payload);
288 response.numSendVendorSpecificHeaderOptions = 0;
289 memset(response.sendVendorSpecificHeaderOptions, 0, sizeof response.sendVendorSpecificHeaderOptions);
290 memset(response.resourceUri, 0, sizeof(response.resourceUri));
291 // Indicate that response is NOT in a persistent buffer
292 response.persistentBufferFlag = 0;
295 if (OCDoResponse(&response) != OC_STACK_OK)
297 OIC_LOG(ERROR, TAG, "Error sending response");
298 ehResult = OC_EH_ERROR;
304 OCPayloadDestroy(response.payload);
308 /* SIGINT handler: set gQuitFlag to 1 for graceful termination */
309 void handleSigInt(int signum)
311 if (signum == SIGINT)
317 FILE* server_fopen(const char *path, const char *mode)
320 return fopen(CRED_FILE, mode);
323 int main(int /*argc*/, char* /*argv*/[])
325 struct timespec timeout;
327 OIC_LOG(DEBUG, TAG, "OCServer is starting...");
329 // Initialize Persistent Storage for SVR database
330 OCPersistentStorage ps = { server_fopen, fread, fwrite, fclose, unlink };
331 OCRegisterPersistentStorageHandler(&ps);
333 if (OCInit(NULL, 0, OC_SERVER) != OC_STACK_OK)
335 OIC_LOG(ERROR, TAG, "OCStack init error");
340 * Declare and create the example resource: LED
342 createLEDResource(gResourceUri, &LED, false, 0);
345 timeout.tv_nsec = 100000000L;
347 // Break from loop with Ctrl-C
348 OIC_LOG(INFO, TAG, "Entering ocserver main loop...");
349 signal(SIGINT, handleSigInt);
352 if (OCProcess() != OC_STACK_OK)
354 OIC_LOG(ERROR, TAG, "OCStack process error");
357 nanosleep(&timeout, NULL);
360 OIC_LOG(INFO, TAG, "Exiting ocserver main loop...");
362 if (OCStop() != OC_STACK_OK)
364 OIC_LOG(ERROR, TAG, "OCStack process error");
370 int createLEDResource (char *uri, LEDResource *ledResource, bool resourceState, int resourcePower)
374 OIC_LOG(ERROR, TAG, "Resource URI cannot be NULL");
378 ledResource->state = resourceState;
379 ledResource->power= resourcePower;
380 OCStackResult res = OCCreateResource(&(ledResource->handle),
382 OC_RSRVD_INTERFACE_DEFAULT,
386 OC_DISCOVERABLE|OC_OBSERVABLE | OC_SECURE);
387 OIC_LOG_V(INFO, TAG, "Created LED resource with result: %s", getResult(res));