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 //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
29 #include "ocpayload.h"
30 #include "ocserverbasicops.h"
36 static LEDResource LED;
37 // This variable determines instance number of the LED resource.
38 // Used by POST method to create a new instance of LED resource.
39 static int gCurrLedInstance = 0;
40 #define SAMPLE_MAX_NUM_POST_INSTANCE 2
41 static LEDResource gLedInstance[SAMPLE_MAX_NUM_POST_INSTANCE];
43 char *gResourceUri= (char *)"/a/led";
45 //Secure Virtual Resource database for Iotivity Server
46 //It contains Server's Identity and the PSK credentials
47 //of other devices which the server trusts
48 static char CRED_FILE[] = "oic_svr_db_server.dat";
50 OCRepPayload* getPayload(const char* uri, int64_t power, bool state)
52 OCRepPayload* payload = OCRepPayloadCreate();
55 OIC_LOG(ERROR, TAG, PCF("Failed to allocate Payload"));
59 OCRepPayloadSetUri(payload, uri);
60 OCRepPayloadSetPropBool(payload, "state", state);
61 OCRepPayloadSetPropInt(payload, "power", power);
66 //This function takes the request as an input and returns the response
67 OCRepPayload* constructResponse (OCEntityHandlerRequest *ehRequest)
69 if(ehRequest->payload && ehRequest->payload->type != PAYLOAD_TYPE_REPRESENTATION)
71 OIC_LOG(ERROR, TAG, PCF("Incoming payload not a representation"));
75 OCRepPayload* input = reinterpret_cast<OCRepPayload*>(ehRequest->payload);
77 LEDResource *currLEDResource = &LED;
79 if (ehRequest->resource == gLedInstance[0].handle)
81 currLEDResource = &gLedInstance[0];
82 gResourceUri = (char *) "/a/led/0";
84 else if (ehRequest->resource == gLedInstance[1].handle)
86 currLEDResource = &gLedInstance[1];
87 gResourceUri = (char *) "/a/led/1";
90 if(OC_REST_PUT == ehRequest->method)
92 // Get pointer to query
94 if(OCRepPayloadGetPropInt(input, "power", &pow))
96 currLEDResource->power =pow;
100 if(OCRepPayloadGetPropBool(input, "state", &state))
102 currLEDResource->state = state;
106 return getPayload(gResourceUri, currLEDResource->power, currLEDResource->state);
109 OCEntityHandlerResult ProcessGetRequest (OCEntityHandlerRequest *ehRequest,
110 OCRepPayload **payload)
112 OCEntityHandlerResult ehResult;
114 OCRepPayload *getResp = constructResponse(ehRequest);
123 ehResult = OC_EH_ERROR;
129 OCEntityHandlerResult ProcessPutRequest (OCEntityHandlerRequest *ehRequest,
130 OCRepPayload **payload)
132 OCEntityHandlerResult ehResult;
134 OCRepPayload *putResp = constructResponse(ehRequest);
143 ehResult = OC_EH_ERROR;
149 OCEntityHandlerResult ProcessPostRequest (OCEntityHandlerRequest *ehRequest,
150 OCEntityHandlerResponse *response, OCRepPayload **payload)
152 OCRepPayload *respPLPost_led = nullptr;
153 OCEntityHandlerResult ehResult = OC_EH_OK;
156 * The entity handler determines how to process a POST request.
157 * Per the REST paradigm, POST can also be used to update representation of existing
158 * resource or create a new resource.
159 * In the sample below, if the POST is for /a/led then a new instance of the LED
160 * resource is created with default representation (if representation is included in
161 * POST payload it can be used as initial values) as long as the instance is
162 * lesser than max new instance count. Once max instance count is reached, POST on
163 * /a/led updated the representation of /a/led (just like PUT)
166 if (ehRequest->resource == LED.handle)
168 if (gCurrLedInstance < SAMPLE_MAX_NUM_POST_INSTANCE)
170 // Create new LED instance
171 char newLedUri[15] = "/a/led/";
172 int newLedUriLength = strlen(newLedUri);
173 snprintf (newLedUri + newLedUriLength, sizeof(newLedUri)-newLedUriLength, "%d", gCurrLedInstance);
175 respPLPost_led = OCRepPayloadCreate();
176 OCRepPayloadSetUri(respPLPost_led, gResourceUri);
177 OCRepPayloadSetPropString(respPLPost_led, "createduri", newLedUri);
179 if (0 == createLEDResource (newLedUri, &gLedInstance[gCurrLedInstance], false, 0))
181 OIC_LOG (INFO, TAG, "Created new LED instance");
182 gLedInstance[gCurrLedInstance].state = 0;
183 gLedInstance[gCurrLedInstance].power = 0;
185 strncpy ((char *)response->resourceUri, newLedUri, MAX_URI_LENGTH);
186 ehResult = OC_EH_RESOURCE_CREATED;
191 respPLPost_led = constructResponse(ehRequest);
196 for (int i = 0; i < SAMPLE_MAX_NUM_POST_INSTANCE; i++)
198 if (ehRequest->resource == gLedInstance[i].handle)
202 respPLPost_led = constructResponse(ehRequest);
207 respPLPost_led = constructResponse(ehRequest);
213 if (respPLPost_led != NULL)
215 *payload = respPLPost_led;
220 OIC_LOG_V (INFO, TAG, "Payload was NULL");
221 ehResult = OC_EH_ERROR;
227 OCEntityHandlerResult
228 OCEntityHandlerCb (OCEntityHandlerFlag flag,
229 OCEntityHandlerRequest *entityHandlerRequest,
230 void* /*callbackParam*/)
232 OIC_LOG_V (INFO, TAG, "Inside entity handler - flags: 0x%x", flag);
234 OCEntityHandlerResult ehResult = OC_EH_ERROR;
235 OCEntityHandlerResponse response = { 0, 0, OC_EH_ERROR, 0, 0, { },{ 0 }, false };
237 if (!entityHandlerRequest)
239 OIC_LOG (ERROR, TAG, "Invalid request pointer");
243 OCRepPayload* payload = nullptr;
245 if (flag & OC_REQUEST_FLAG)
247 OIC_LOG (INFO, TAG, "Flag includes OC_REQUEST_FLAG");
248 if (entityHandlerRequest)
250 if (OC_REST_GET == entityHandlerRequest->method)
252 OIC_LOG (INFO, TAG, "Received OC_REST_GET from client");
253 ehResult = ProcessGetRequest (entityHandlerRequest, &payload);
255 else if (OC_REST_PUT == entityHandlerRequest->method)
257 OIC_LOG (INFO, TAG, "Received OC_REST_PUT from client");
258 ehResult = ProcessPutRequest (entityHandlerRequest, &payload);
260 else if (OC_REST_POST == entityHandlerRequest->method)
262 OIC_LOG (INFO, TAG, "Received OC_REST_POST from client");
263 ehResult = ProcessPostRequest (entityHandlerRequest, &response, &payload);
267 OIC_LOG_V (INFO, TAG, "Received unsupported method %d from client",
268 entityHandlerRequest->method);
269 ehResult = OC_EH_ERROR;
272 if (ehResult == OC_EH_OK && ehResult != OC_EH_FORBIDDEN)
274 // Format the response. Note this requires some info about the request
275 response.requestHandle = entityHandlerRequest->requestHandle;
276 response.resourceHandle = entityHandlerRequest->resource;
277 response.ehResult = ehResult;
278 response.payload = reinterpret_cast<OCPayload*>(payload);
279 response.numSendVendorSpecificHeaderOptions = 0;
280 memset(response.sendVendorSpecificHeaderOptions, 0, sizeof response.sendVendorSpecificHeaderOptions);
281 memset(response.resourceUri, 0, sizeof(response.resourceUri));
282 // Indicate that response is NOT in a persistent buffer
283 response.persistentBufferFlag = 0;
286 if (OCDoResponse(&response) != OC_STACK_OK)
288 OIC_LOG(ERROR, TAG, "Error sending response");
289 ehResult = OC_EH_ERROR;
295 OCPayloadDestroy(response.payload);
299 /* SIGINT handler: set gQuitFlag to 1 for graceful termination */
300 void handleSigInt(int signum)
302 if (signum == SIGINT)
308 FILE* server_fopen(const char *path, const char *mode)
311 return fopen(CRED_FILE, mode);
314 int main(int /*argc*/, char* /*argv*/[])
316 struct timespec timeout;
318 OIC_LOG(DEBUG, TAG, "OCServer is starting...");
320 // Initialize Persistent Storage for SVR database
321 OCPersistentStorage ps = { server_fopen, fread, fwrite, fclose, unlink };
322 OCRegisterPersistentStorageHandler(&ps);
324 if (OCInit(NULL, 0, OC_SERVER) != OC_STACK_OK)
326 OIC_LOG(ERROR, TAG, "OCStack init error");
331 * Declare and create the example resource: LED
333 createLEDResource(gResourceUri, &LED, false, 0);
336 timeout.tv_nsec = 100000000L;
338 // Break from loop with Ctrl-C
339 OIC_LOG(INFO, TAG, "Entering ocserver main loop...");
340 signal(SIGINT, handleSigInt);
343 if (OCProcess() != OC_STACK_OK)
345 OIC_LOG(ERROR, TAG, "OCStack process error");
348 nanosleep(&timeout, NULL);
351 OIC_LOG(INFO, TAG, "Exiting ocserver main loop...");
353 if (OCStop() != OC_STACK_OK)
355 OIC_LOG(ERROR, TAG, "OCStack process error");
361 int createLEDResource (char *uri, LEDResource *ledResource, bool resourceState, int resourcePower)
365 OIC_LOG(ERROR, TAG, "Resource URI cannot be NULL");
369 ledResource->state = resourceState;
370 ledResource->power= resourcePower;
371 OCStackResult res = OCCreateResource(&(ledResource->handle),
373 OC_RSRVD_INTERFACE_DEFAULT,
377 OC_DISCOVERABLE|OC_OBSERVABLE | OC_SECURE);
378 OIC_LOG_V(INFO, TAG, "Created LED resource with result: %s", getResult(res));