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"
35 static LEDResource LED;
36 // This variable determines instance number of the LED resource.
37 // Used by POST method to create a new instance of LED resource.
38 static int gCurrLedInstance = 0;
39 #define SAMPLE_MAX_NUM_POST_INSTANCE 2
40 static LEDResource gLedInstance[SAMPLE_MAX_NUM_POST_INSTANCE];
42 char *gResourceUri= (char *)"/a/led";
44 //Secure Virtual Resource database for Iotivity Server
45 //It contains Server's Identity and the PSK credentials
46 //of other devices which the server trusts
47 static char CRED_FILE[] = "oic_svr_db_server.json";
49 OCRepPayload* getPayload(const char* uri, int64_t power, bool state)
51 OCRepPayload* payload = OCRepPayloadCreate();
54 OC_LOG(ERROR, TAG, PCF("Failed to allocate Payload"));
58 OCRepPayloadSetUri(payload, uri);
59 OCRepPayloadSetPropBool(payload, "state", state);
60 OCRepPayloadSetPropInt(payload, "power", power);
65 //This function takes the request as an input and returns the response
66 OCRepPayload* constructResponse (OCEntityHandlerRequest *ehRequest)
68 if(ehRequest->payload && ehRequest->payload->type != PAYLOAD_TYPE_REPRESENTATION)
70 OC_LOG(ERROR, TAG, PCF("Incoming payload not a representation"));
74 OCRepPayload* input = reinterpret_cast<OCRepPayload*>(ehRequest->payload);
76 LEDResource *currLEDResource = &LED;
78 if (ehRequest->resource == gLedInstance[0].handle)
80 currLEDResource = &gLedInstance[0];
81 gResourceUri = (char *) "/a/led/0";
83 else if (ehRequest->resource == gLedInstance[1].handle)
85 currLEDResource = &gLedInstance[1];
86 gResourceUri = (char *) "/a/led/1";
89 if(OC_REST_PUT == ehRequest->method)
91 // Get pointer to query
93 if(OCRepPayloadGetPropInt(input, "power", &pow))
95 currLEDResource->power =pow;
99 if(OCRepPayloadGetPropBool(input, "state", &state))
101 currLEDResource->state = state;
105 return getPayload(gResourceUri, currLEDResource->power, currLEDResource->state);
108 OCEntityHandlerResult ProcessGetRequest (OCEntityHandlerRequest *ehRequest,
109 OCRepPayload **payload)
111 OCEntityHandlerResult ehResult;
113 OCRepPayload *getResp = constructResponse(ehRequest);
122 ehResult = OC_EH_ERROR;
128 OCEntityHandlerResult ProcessPutRequest (OCEntityHandlerRequest *ehRequest,
129 OCRepPayload **payload)
131 OCEntityHandlerResult ehResult;
133 OCRepPayload *putResp = constructResponse(ehRequest);
142 ehResult = OC_EH_ERROR;
148 OCEntityHandlerResult ProcessPostRequest (OCEntityHandlerRequest *ehRequest,
149 OCEntityHandlerResponse *response, OCRepPayload **payload)
151 OCRepPayload *respPLPost_led = nullptr;
152 OCEntityHandlerResult ehResult = OC_EH_OK;
155 * The entity handler determines how to process a POST request.
156 * Per the REST paradigm, POST can also be used to update representation of existing
157 * resource or create a new resource.
158 * In the sample below, if the POST is for /a/led then a new instance of the LED
159 * resource is created with default representation (if representation is included in
160 * POST payload it can be used as initial values) as long as the instance is
161 * lesser than max new instance count. Once max instance count is reached, POST on
162 * /a/led updated the representation of /a/led (just like PUT)
165 if (ehRequest->resource == LED.handle)
167 if (gCurrLedInstance < SAMPLE_MAX_NUM_POST_INSTANCE)
169 // Create new LED instance
170 char newLedUri[15] = "/a/led/";
171 int newLedUriLength = strlen(newLedUri);
172 snprintf (newLedUri + newLedUriLength, sizeof(newLedUri)-newLedUriLength, "%d", gCurrLedInstance);
174 respPLPost_led = OCRepPayloadCreate();
175 OCRepPayloadSetUri(respPLPost_led, gResourceUri);
176 OCRepPayloadSetPropString(respPLPost_led, "createduri", newLedUri);
178 if (0 == createLEDResource (newLedUri, &gLedInstance[gCurrLedInstance], false, 0))
180 OC_LOG (INFO, TAG, "Created new LED instance");
181 gLedInstance[gCurrLedInstance].state = 0;
182 gLedInstance[gCurrLedInstance].power = 0;
184 strncpy ((char *)response->resourceUri, newLedUri, MAX_URI_LENGTH);
185 ehResult = OC_EH_RESOURCE_CREATED;
190 respPLPost_led = constructResponse(ehRequest);
195 for (int i = 0; i < SAMPLE_MAX_NUM_POST_INSTANCE; i++)
197 if (ehRequest->resource == gLedInstance[i].handle)
201 respPLPost_led = constructResponse(ehRequest);
206 respPLPost_led = constructResponse(ehRequest);
212 if (respPLPost_led != NULL)
214 *payload = respPLPost_led;
219 OC_LOG_V (INFO, TAG, "Payload was NULL");
220 ehResult = OC_EH_ERROR;
226 OCEntityHandlerResult
227 OCEntityHandlerCb (OCEntityHandlerFlag flag,
228 OCEntityHandlerRequest *entityHandlerRequest,
231 OC_LOG_V (INFO, TAG, "Inside entity handler - flags: 0x%x", flag);
233 OCEntityHandlerResult ehResult = OC_EH_ERROR;
234 OCEntityHandlerResponse response;
237 if (!entityHandlerRequest)
239 OC_LOG (ERROR, TAG, "Invalid request pointer");
243 OCRepPayload* payload = nullptr;
245 if (flag & OC_REQUEST_FLAG)
247 OC_LOG (INFO, TAG, "Flag includes OC_REQUEST_FLAG");
248 if (entityHandlerRequest)
250 if (OC_REST_GET == entityHandlerRequest->method)
252 OC_LOG (INFO, TAG, "Received OC_REST_GET from client");
253 ehResult = ProcessGetRequest (entityHandlerRequest, &payload);
255 else if (OC_REST_PUT == entityHandlerRequest->method)
257 OC_LOG (INFO, TAG, "Received OC_REST_PUT from client");
258 ehResult = ProcessPutRequest (entityHandlerRequest, &payload);
260 else if (OC_REST_POST == entityHandlerRequest->method)
262 OC_LOG (INFO, TAG, "Received OC_REST_POST from client");
263 ehResult = ProcessPostRequest (entityHandlerRequest, &response, &payload);
267 OC_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 OC_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 OC_LOG(DEBUG, TAG, "OCServer is starting...");
320 // Initialize Persistent Storage for SVR database
321 OCPersistentStorage ps = {};
322 ps.open = server_fopen;
327 OCRegisterPersistentStorageHandler(&ps);
329 if (OCInit(NULL, 0, OC_SERVER) != OC_STACK_OK)
331 OC_LOG(ERROR, TAG, "OCStack init error");
336 * Declare and create the example resource: LED
338 createLEDResource(gResourceUri, &LED, false, 0);
341 timeout.tv_nsec = 100000000L;
343 // Break from loop with Ctrl-C
344 OC_LOG(INFO, TAG, "Entering ocserver main loop...");
345 signal(SIGINT, handleSigInt);
348 if (OCProcess() != OC_STACK_OK)
350 OC_LOG(ERROR, TAG, "OCStack process error");
353 nanosleep(&timeout, NULL);
356 OC_LOG(INFO, TAG, "Exiting ocserver main loop...");
358 if (OCStop() != OC_STACK_OK)
360 OC_LOG(ERROR, TAG, "OCStack process error");
366 int createLEDResource (char *uri, LEDResource *ledResource, bool resourceState, int resourcePower)
370 OC_LOG(ERROR, TAG, "Resource URI cannot be NULL");
374 ledResource->state = resourceState;
375 ledResource->power= resourcePower;
376 OCStackResult res = OCCreateResource(&(ledResource->handle),
378 OC_RSRVD_INTERFACE_DEFAULT,
382 OC_DISCOVERABLE|OC_OBSERVABLE | OC_SECURE);
383 OC_LOG_V(INFO, TAG, "Created LED resource with result: %s", getResult(res));