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 //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
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 //This function takes the request as an input and returns the response
51 char* constructJsonResponse (OCEntityHandlerRequest *ehRequest)
53 cJSON *json = cJSON_CreateObject();
54 cJSON *putJson = NULL;
56 char *jsonResponse = NULL;
57 LEDResource *currLEDResource = &LED;
59 if (ehRequest->resource == gLedInstance[0].handle)
61 currLEDResource = &gLedInstance[0];
62 gResourceUri = (char *) "a/led/0";
64 else if (ehRequest->resource == gLedInstance[1].handle)
66 currLEDResource = &gLedInstance[1];
67 gResourceUri = (char *) "a/led/1";
70 if(OC_REST_PUT == ehRequest->method)
72 cJSON* jsonObj = NULL;
73 putJson = cJSON_Parse(ehRequest->reqJSONPayload);
76 jsonObj = cJSON_GetObjectItem(putJson,"oic");
79 jsonObj = cJSON_GetArrayItem(jsonObj, 0);
82 jsonObj = cJSON_GetObjectItem(jsonObj, "rep");
88 OC_LOG_V(ERROR, TAG, "Failed to parse JSON: %s", ehRequest->reqJSONPayload);
92 currLEDResource->state = ( !strcmp(cJSON_GetObjectItem(jsonObj,"state")->valuestring ,
94 currLEDResource->power = cJSON_GetObjectItem(jsonObj,"power")->valuedouble;
97 cJSON_AddStringToObject(json,"href",gResourceUri);
98 cJSON_AddItemToObject(json, "rep", format=cJSON_CreateObject());
99 cJSON_AddStringToObject(format, "state", (char *) (currLEDResource->state ? "on":"off"));
100 cJSON_AddNumberToObject(format, "power", currLEDResource->power);
102 jsonResponse = cJSON_Print(json);
105 cJSON_Delete(putJson);
110 OCEntityHandlerResult ProcessGetRequest (OCEntityHandlerRequest *ehRequest,
111 char *payload, size_t maxPayloadSize)
113 OCEntityHandlerResult ehResult;
115 char *getResp = constructJsonResponse(ehRequest);
118 if (maxPayloadSize > strlen (getResp))
120 strcpy(payload, getResp);
125 OC_LOG_V (INFO, TAG, "Response buffer: %d bytes is too small",
127 ehResult = OC_EH_ERROR;
134 ehResult = OC_EH_ERROR;
140 OCEntityHandlerResult ProcessPutRequest (OCEntityHandlerRequest *ehRequest,
141 char *payload, size_t maxPayloadSize)
143 OCEntityHandlerResult ehResult;
145 char *putResp = constructJsonResponse(ehRequest);
149 if (maxPayloadSize > strlen (putResp))
151 strcpy(payload, putResp);
156 OC_LOG_V (INFO, TAG, "Response buffer: %d bytes is too small",
158 ehResult = OC_EH_ERROR;
165 ehResult = OC_EH_ERROR;
171 OCEntityHandlerResult ProcessPostRequest (OCEntityHandlerRequest *ehRequest,
172 char *payload, size_t maxPayloadSize)
174 char *respPLPost_led = NULL;
177 OCEntityHandlerResult ehResult;
180 * The entity handler determines how to process a POST request.
181 * Per the REST paradigm, POST can also be used to update representation of existing
182 * resource or create a new resource.
183 * In the sample below, if the POST is for /a/led then a new instance of the LED
184 * resource is created with default representation (if representation is included in
185 * POST payload it can be used as initial values) as long as the instance is
186 * lesser than max new instance count. Once max instance count is reached, POST on
187 * /a/led updated the representation of /a/led (just like PUT)
190 if (ehRequest->resource == LED.handle)
192 if (gCurrLedInstance < SAMPLE_MAX_NUM_POST_INSTANCE)
194 // Create new LED instance
195 char newLedUri[15] = "/a/led/";
196 int newLedUriLength = strlen(newLedUri);
197 snprintf (newLedUri + newLedUriLength, sizeof(newLedUri)-newLedUriLength, "%d", gCurrLedInstance);
199 json = cJSON_CreateObject();
201 cJSON_AddStringToObject(json,"href",gResourceUri);
202 cJSON_AddItemToObject(json, "rep", format=cJSON_CreateObject());
203 cJSON_AddStringToObject(format, "createduri", (char *) newLedUri);
205 if (0 == createLEDResource (newLedUri, &gLedInstance[gCurrLedInstance], false, 0))
207 OC_LOG (INFO, TAG, "Created new LED instance");
208 gLedInstance[gCurrLedInstance].state = 0;
209 gLedInstance[gCurrLedInstance].power = 0;
211 respPLPost_led = cJSON_Print(json);
218 respPLPost_led = constructJsonResponse(ehRequest);
223 for (int i = 0; i < SAMPLE_MAX_NUM_POST_INSTANCE; i++)
225 if (ehRequest->resource == gLedInstance[i].handle)
229 respPLPost_led = constructJsonResponse(ehRequest);
234 respPLPost_led = constructJsonResponse(ehRequest);
240 if ((respPLPost_led != NULL) && (maxPayloadSize > strlen (respPLPost_led)))
242 strcpy(payload, respPLPost_led);
247 OC_LOG_V (INFO, TAG, "Response buffer: %d bytes is too small",
249 ehResult = OC_EH_ERROR;
252 free(respPLPost_led);
257 OCEntityHandlerResult
258 OCEntityHandlerCb (OCEntityHandlerFlag flag,
259 OCEntityHandlerRequest *entityHandlerRequest,
262 OC_LOG_V (INFO, TAG, "Inside entity handler - flags: 0x%x", flag);
264 OCEntityHandlerResult ehResult = OC_EH_ERROR;
265 OCEntityHandlerResponse response;
266 char payload[MAX_RESPONSE_LENGTH] = {0};
268 if (flag & OC_REQUEST_FLAG)
270 OC_LOG (INFO, TAG, "Flag includes OC_REQUEST_FLAG");
271 if (entityHandlerRequest)
273 if (OC_REST_GET == entityHandlerRequest->method)
275 OC_LOG (INFO, TAG, "Received OC_REST_GET from client");
276 ehResult = ProcessGetRequest (entityHandlerRequest, payload, sizeof(payload));
278 else if (OC_REST_PUT == entityHandlerRequest->method)
280 OC_LOG (INFO, TAG, "Received OC_REST_PUT from client");
281 ehResult = ProcessPutRequest (entityHandlerRequest, payload, sizeof(payload));
283 else if (OC_REST_POST == entityHandlerRequest->method)
285 OC_LOG (INFO, TAG, "Received OC_REST_POST from client");
286 ehResult = ProcessPostRequest (entityHandlerRequest, payload, sizeof(payload));
290 OC_LOG_V (INFO, TAG, "Received unsupported method %d from client",
291 entityHandlerRequest->method);
292 ehResult = OC_EH_ERROR;
295 if (ehResult == OC_EH_OK)
297 // Format the response. Note this requires some info about the request
298 response.requestHandle = entityHandlerRequest->requestHandle;
299 response.resourceHandle = entityHandlerRequest->resource;
300 response.ehResult = ehResult;
301 response.payload = payload;
302 response.payloadSize = strlen(payload);
303 response.numSendVendorSpecificHeaderOptions = 0;
304 memset(response.sendVendorSpecificHeaderOptions, 0, sizeof response.sendVendorSpecificHeaderOptions);
305 memset(response.resourceUri, 0, sizeof(response.resourceUri));
306 // Indicate that response is NOT in a persistent buffer
307 response.persistentBufferFlag = 0;
310 if (OCDoResponse(&response) != OC_STACK_OK)
312 OC_LOG(ERROR, TAG, "Error sending response");
313 ehResult = OC_EH_ERROR;
321 /* SIGINT handler: set gQuitFlag to 1 for graceful termination */
322 void handleSigInt(int signum)
324 if (signum == SIGINT)
330 FILE* server_fopen(const char *path, const char *mode)
333 return fopen(CRED_FILE, mode);
336 int main(int argc, char* argv[])
338 struct timespec timeout;
340 OC_LOG(DEBUG, TAG, "OCServer is starting...");
342 // Initialize Persistent Storage for SVR database
343 OCPersistentStorage ps = {};
344 ps.open = server_fopen;
349 OCRegisterPersistentStorageHandler(&ps);
351 if (OCInit(NULL, 0, OC_SERVER) != OC_STACK_OK)
353 OC_LOG(ERROR, TAG, "OCStack init error");
358 * Declare and create the example resource: LED
360 createLEDResource(gResourceUri, &LED, false, 0);
363 timeout.tv_nsec = 100000000L;
365 // Break from loop with Ctrl-C
366 OC_LOG(INFO, TAG, "Entering ocserver main loop...");
367 signal(SIGINT, handleSigInt);
370 if (OCProcess() != OC_STACK_OK)
372 OC_LOG(ERROR, TAG, "OCStack process error");
375 nanosleep(&timeout, NULL);
378 OC_LOG(INFO, TAG, "Exiting ocserver main loop...");
380 if (OCStop() != OC_STACK_OK)
382 OC_LOG(ERROR, TAG, "OCStack process error");
388 int createLEDResource (char *uri, LEDResource *ledResource, bool resourceState, int resourcePower)
392 OC_LOG(ERROR, TAG, "Resource URI cannot be NULL");
396 ledResource->state = resourceState;
397 ledResource->power= resourcePower;
398 OCStackResult res = OCCreateResource(&(ledResource->handle),
400 OC_RSRVD_INTERFACE_DEFAULT,
404 OC_DISCOVERABLE|OC_OBSERVABLE | OC_SECURE);
405 OC_LOG_V(INFO, TAG, "Created LED resource with result: %s", getResult(res));