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 //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
34 #include "platform_features.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)
100 // Get pointer to query
102 if(OCRepPayloadGetPropInt(input, "power", &pow))
104 currLEDResource->power =pow;
108 if(OCRepPayloadGetPropBool(input, "state", &state))
110 currLEDResource->state = state;
114 return getPayload(gResourceUri, currLEDResource->power, currLEDResource->state);
117 OCEntityHandlerResult ProcessGetRequest (OCEntityHandlerRequest *ehRequest,
118 OCRepPayload **payload)
120 OCEntityHandlerResult ehResult;
122 OCRepPayload *getResp = constructResponse(ehRequest);
131 ehResult = OC_EH_ERROR;
137 OCEntityHandlerResult ProcessPutRequest (OCEntityHandlerRequest *ehRequest,
138 OCRepPayload **payload)
140 OCEntityHandlerResult ehResult;
142 OCRepPayload *putResp = constructResponse(ehRequest);
151 ehResult = OC_EH_ERROR;
157 OCEntityHandlerResult ProcessPostRequest (OCEntityHandlerRequest *ehRequest,
158 OCEntityHandlerResponse *response, OCRepPayload **payload)
160 OCRepPayload *respPLPost_led = nullptr;
161 OCEntityHandlerResult ehResult = OC_EH_OK;
164 * The entity handler determines how to process a POST request.
165 * Per the REST paradigm, POST can also be used to update representation of existing
166 * resource or create a new resource.
167 * In the sample below, if the POST is for /a/led then a new instance of the LED
168 * resource is created with default representation (if representation is included in
169 * POST payload it can be used as initial values) as long as the instance is
170 * lesser than max new instance count. Once max instance count is reached, POST on
171 * /a/led updated the representation of /a/led (just like PUT)
174 if (ehRequest->resource == LED.handle)
176 if (gCurrLedInstance < SAMPLE_MAX_NUM_POST_INSTANCE)
178 // Create new LED instance
179 char newLedUri[15] = "/a/led/";
180 int newLedUriLength = strlen(newLedUri);
181 snprintf (newLedUri + newLedUriLength, sizeof(newLedUri)-newLedUriLength, "%d", gCurrLedInstance);
183 respPLPost_led = OCRepPayloadCreate();
184 OCRepPayloadSetUri(respPLPost_led, gResourceUri);
185 OCRepPayloadSetPropString(respPLPost_led, "createduri", newLedUri);
187 if (0 == createLEDResource (newLedUri, &gLedInstance[gCurrLedInstance], false, 0))
189 OIC_LOG (INFO, TAG, "Created new LED instance");
190 gLedInstance[gCurrLedInstance].state = 0;
191 gLedInstance[gCurrLedInstance].power = 0;
193 strncpy ((char *)response->resourceUri, newLedUri, MAX_URI_LENGTH);
194 ehResult = OC_EH_RESOURCE_CREATED;
199 respPLPost_led = constructResponse(ehRequest);
204 for (int i = 0; i < SAMPLE_MAX_NUM_POST_INSTANCE; i++)
206 if (ehRequest->resource == gLedInstance[i].handle)
210 respPLPost_led = constructResponse(ehRequest);
215 respPLPost_led = constructResponse(ehRequest);
221 if (respPLPost_led != NULL)
223 *payload = respPLPost_led;
228 OIC_LOG_V (INFO, TAG, "Payload was NULL");
229 ehResult = OC_EH_ERROR;
235 OCEntityHandlerResult
236 OCEntityHandlerCb (OCEntityHandlerFlag flag,
237 OCEntityHandlerRequest *entityHandlerRequest,
238 void* /*callbackParam*/)
240 OIC_LOG_V (INFO, TAG, "Inside entity handler - flags: 0x%x", flag);
242 OCEntityHandlerResult ehResult = OC_EH_ERROR;
243 OCEntityHandlerResponse response = { 0, 0, OC_EH_ERROR, 0, 0, { },{ 0 }, false };
245 if (!entityHandlerRequest)
247 OIC_LOG (ERROR, TAG, "Invalid request pointer");
251 OCRepPayload* payload = nullptr;
253 if (flag & OC_REQUEST_FLAG)
255 OIC_LOG (INFO, TAG, "Flag includes OC_REQUEST_FLAG");
256 if (entityHandlerRequest)
258 if (OC_REST_GET == entityHandlerRequest->method)
260 OIC_LOG (INFO, TAG, "Received OC_REST_GET from client");
261 ehResult = ProcessGetRequest (entityHandlerRequest, &payload);
263 else if (OC_REST_PUT == entityHandlerRequest->method)
265 OIC_LOG (INFO, TAG, "Received OC_REST_PUT from client");
266 ehResult = ProcessPutRequest (entityHandlerRequest, &payload);
268 else if (OC_REST_POST == entityHandlerRequest->method)
270 OIC_LOG (INFO, TAG, "Received OC_REST_POST from client");
271 ehResult = ProcessPostRequest (entityHandlerRequest, &response, &payload);
275 OIC_LOG_V (INFO, TAG, "Received unsupported method %d from client",
276 entityHandlerRequest->method);
277 ehResult = OC_EH_ERROR;
280 if (ehResult == OC_EH_OK && ehResult != OC_EH_FORBIDDEN)
282 // Format the response. Note this requires some info about the request
283 response.requestHandle = entityHandlerRequest->requestHandle;
284 response.resourceHandle = entityHandlerRequest->resource;
285 response.ehResult = ehResult;
286 response.payload = reinterpret_cast<OCPayload*>(payload);
287 response.numSendVendorSpecificHeaderOptions = 0;
288 memset(response.sendVendorSpecificHeaderOptions, 0, sizeof response.sendVendorSpecificHeaderOptions);
289 memset(response.resourceUri, 0, sizeof(response.resourceUri));
290 // Indicate that response is NOT in a persistent buffer
291 response.persistentBufferFlag = 0;
294 if (OCDoResponse(&response) != OC_STACK_OK)
296 OIC_LOG(ERROR, TAG, "Error sending response");
297 ehResult = OC_EH_ERROR;
303 OCPayloadDestroy(response.payload);
307 /* SIGINT handler: set gQuitFlag to 1 for graceful termination */
308 void handleSigInt(int signum)
310 if (signum == SIGINT)
316 FILE* server_fopen(const char *path, const char *mode)
319 return fopen(CRED_FILE, mode);
322 int main(int /*argc*/, char* /*argv*/[])
324 struct timespec timeout;
326 OIC_LOG(DEBUG, TAG, "OCServer is starting...");
328 // Initialize Persistent Storage for SVR database
329 OCPersistentStorage ps = { server_fopen, fread, fwrite, fclose, unlink };
330 OCRegisterPersistentStorageHandler(&ps);
332 if (OCInit(NULL, 0, OC_SERVER) != OC_STACK_OK)
334 OIC_LOG(ERROR, TAG, "OCStack init error");
339 * Declare and create the example resource: LED
341 createLEDResource(gResourceUri, &LED, false, 0);
344 timeout.tv_nsec = 100000000L;
346 // Break from loop with Ctrl-C
347 OIC_LOG(INFO, TAG, "Entering ocserver main loop...");
348 signal(SIGINT, handleSigInt);
351 if (OCProcess() != OC_STACK_OK)
353 OIC_LOG(ERROR, TAG, "OCStack process error");
356 nanosleep(&timeout, NULL);
359 OIC_LOG(INFO, TAG, "Exiting ocserver main loop...");
361 if (OCStop() != OC_STACK_OK)
363 OIC_LOG(ERROR, TAG, "OCStack process error");
369 int createLEDResource (char *uri, LEDResource *ledResource, bool resourceState, int resourcePower)
373 OIC_LOG(ERROR, TAG, "Resource URI cannot be NULL");
377 ledResource->state = resourceState;
378 ledResource->power= resourcePower;
379 OCStackResult res = OCCreateResource(&(ledResource->handle),
381 OC_RSRVD_INTERFACE_DEFAULT,
385 OC_DISCOVERABLE|OC_OBSERVABLE | OC_SECURE);
386 OIC_LOG_V(INFO, TAG, "Created LED resource with result: %s", getResult(res));