43b913f11cb08c010a03e15a52e1b1df35760093
[platform/upstream/iotivity.git] / resource / csdk / stack / samples / linux / SimpleClientServer / ocserverbasicops.cpp
1 //******************************************************************
2 //
3 // Copyright 2014 Intel Mobile Communications GmbH All Rights Reserved.
4 //
5 //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
6 //
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
10 //
11 //      http://www.apache.org/licenses/LICENSE-2.0
12 //
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.
18 //
19 //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
20
21 #include <stdio.h>
22 #include <string.h>
23 #include <stdlib.h>
24 #include <unistd.h>
25 #include <signal.h>
26 #include <pthread.h>
27 #include "ocstack.h"
28 #include "logger.h"
29 #include "cJSON.h"
30 #include "ocserverbasicops.h"
31
32 //string length of "/a/led/" + std::numeric_limits<int>::digits10 + '\0'"
33 // 7 + 9 + 1 = 17
34 const int URI_MAXSIZE = 17;
35
36 volatile sig_atomic_t gQuitFlag = 0;
37
38 static LEDResource LED;
39 // This variable determines instance number of the LED resource.
40 // Used by POST method to create a new instance of LED resource.
41 static int gCurrLedInstance = 0;
42 #define SAMPLE_MAX_NUM_POST_INSTANCE 2
43 static LEDResource gLedInstance[SAMPLE_MAX_NUM_POST_INSTANCE];
44
45 char *gResourceUri= (char *)"/a/led";
46
47 //This function takes the request as an input and returns the response
48 //in JSON format.
49 char* constructJsonResponse (OCEntityHandlerRequest *ehRequest)
50 {
51     cJSON *json = cJSON_CreateObject();
52
53     if(!json)
54     {
55         OC_LOG (ERROR, TAG, "json object not created properly");
56         return NULL;
57     }
58
59     cJSON *format;
60     char *jsonResponse;
61     LEDResource *currLEDResource = &LED;
62
63     if (ehRequest->resource == gLedInstance[0].handle)
64     {
65         currLEDResource = &gLedInstance[0];
66         gResourceUri = (char *) "a/led/0";
67     }
68     else if (ehRequest->resource == gLedInstance[1].handle)
69     {
70         currLEDResource = &gLedInstance[1];
71         gResourceUri = (char *) "a/led/1";
72     }
73
74     if(OC_REST_PUT == ehRequest->method)
75     {
76         cJSON *putJson = cJSON_Parse((char *)ehRequest->reqJSONPayload);
77
78         if(!putJson)
79         {
80             OC_LOG (ERROR, TAG, "putJson object not created properly");
81             cJSON_Delete(json);
82             return NULL;
83         }
84         currLEDResource->state = ( !strcmp(cJSON_GetObjectItem(putJson,"state")->valuestring ,
85                 "on") ? true:false);
86         currLEDResource->power = cJSON_GetObjectItem(putJson,"power")->valuedouble;
87         cJSON_Delete(putJson);
88     }
89
90     cJSON_AddStringToObject(json,"href",gResourceUri);
91     format = cJSON_CreateObject();
92
93     if(!format)
94     {
95         OC_LOG (ERROR, TAG, "format object not created properly");
96         cJSON_Delete(json);
97         return NULL;
98     }
99
100     cJSON_AddItemToObject(json, "rep", format);
101     cJSON_AddStringToObject(format, "state", (char *) (currLEDResource->state ? "on":"off"));
102     cJSON_AddNumberToObject(format, "power", currLEDResource->power);
103
104     jsonResponse = cJSON_Print(json);
105     cJSON_Delete(json);
106     return jsonResponse;
107 }
108
109 OCEntityHandlerResult ProcessGetRequest (OCEntityHandlerRequest *ehRequest, char *payload,
110         uint16_t maxPayloadSize)
111 {
112     OCEntityHandlerResult ehResult;
113     char *getResp = constructJsonResponse(ehRequest);
114
115     if(getResp)
116     {
117         if (maxPayloadSize > strlen ((char *)getResp))
118         {
119             strncpy(payload, getResp, strlen((char *)getResp));
120             ehResult = OC_EH_OK;
121         }
122         else
123         {
124             OC_LOG_V (INFO, TAG, "Response buffer: %d bytes is too small",
125                     maxPayloadSize);
126             ehResult = OC_EH_ERROR;
127         }
128
129         free(getResp);
130     }
131     else
132     {
133         ehResult = OC_EH_ERROR;
134     }
135
136     return ehResult;
137 }
138
139 OCEntityHandlerResult ProcessPutRequest (OCEntityHandlerRequest *ehRequest, char *payload,
140         uint16_t maxPayloadSize)
141 {
142     OCEntityHandlerResult ehResult;
143     char *putResp = constructJsonResponse(ehRequest);
144
145     if(putResp)
146     {
147         if (maxPayloadSize > strlen ((char *)putResp))
148         {
149             strncpy(payload, putResp, strlen((char *)putResp));
150             ehResult = OC_EH_OK;
151         }
152         else
153         {
154             OC_LOG_V (INFO, TAG, "Response buffer: %d bytes is too small",
155                     maxPayloadSize);
156             ehResult = OC_EH_ERROR;
157         }
158
159         free(putResp);
160     }
161     else
162     {
163         ehResult = OC_EH_ERROR;
164     }
165
166     return ehResult;
167 }
168
169 OCEntityHandlerResult ProcessPostRequest (OCEntityHandlerRequest *ehRequest, char *payload,
170         uint16_t maxPayloadSize)
171 {
172     char *respPLPost_led = NULL;
173     cJSON *json;
174     cJSON *format;
175     OCEntityHandlerResult ehResult;
176
177     /*
178      * The entity handler determines how to process a POST request.
179      * Per the REST paradigm, POST can also be used to update representation of existing
180      * resource or create a new resource.
181      * In the sample below, if the POST is for /a/led then a new instance of the LED
182      * resource is created with default representation (if representation is included in
183      * POST payload it can be used as initial values) as long as the instance is
184      * lesser than max new instance count. Once max instance count is reached, POST on
185      * /a/led updated the representation of /a/led (just like PUT)
186      */
187
188     if (ehRequest->resource == LED.handle)
189     {
190         if (gCurrLedInstance < SAMPLE_MAX_NUM_POST_INSTANCE)
191         {
192             // Create new LED instance
193             char newLedUri[URI_MAXSIZE ];
194             snprintf(newLedUri, URI_MAXSIZE, "/a/led/%d", gCurrLedInstance);
195
196             json = cJSON_CreateObject();
197             if(!json)
198             {
199                 return OC_EH_ERROR;
200             }
201
202             cJSON_AddStringToObject(json,"href",gResourceUri);
203             format = cJSON_CreateObject();
204
205             if(!format)
206             {
207                 return OC_EH_ERROR;
208             }
209
210             cJSON_AddItemToObject(json, "rep", format);
211             cJSON_AddStringToObject(format, "createduri", (char *) newLedUri);
212
213             if (0 == createLEDResource (newLedUri, &gLedInstance[gCurrLedInstance], false, 0))
214             {
215                 OC_LOG (INFO, TAG, "Created new LED instance");
216                 gLedInstance[gCurrLedInstance].state = 0;
217                 gLedInstance[gCurrLedInstance].power = 0;
218                 gCurrLedInstance++;
219                 respPLPost_led = cJSON_Print(json);
220             }
221
222             cJSON_Delete(json);
223         }
224         else
225         {
226             respPLPost_led = constructJsonResponse(ehRequest);
227         }
228     }
229     else
230     {
231         for (int i = 0; i < SAMPLE_MAX_NUM_POST_INSTANCE; i++)
232         {
233             if (ehRequest->resource == gLedInstance[i].handle)
234             {
235                 if (i == 0)
236                 {
237                     respPLPost_led = constructJsonResponse(ehRequest);
238                     break;
239                 }
240                 else if (i == 1)
241                 {
242                     respPLPost_led = constructJsonResponse(ehRequest);
243                 }
244             }
245         }
246     }
247
248     if ((respPLPost_led != NULL) && (maxPayloadSize > strlen ((char *)respPLPost_led)))
249     {
250         strncpy(payload, respPLPost_led, strlen((char *)respPLPost_led));
251         ehResult = OC_EH_OK;
252     }
253     else
254     {
255         OC_LOG_V (INFO, TAG, "Response buffer: %d bytes is too small",
256                 maxPayloadSize);
257         ehResult = OC_EH_ERROR;
258     }
259
260     free(respPLPost_led);
261
262     return ehResult;
263 }
264
265 OCEntityHandlerResult
266 OCEntityHandlerCb (OCEntityHandlerFlag flag,
267         OCEntityHandlerRequest *entityHandlerRequest)
268 {
269     OC_LOG_V (INFO, TAG, "Inside entity handler - flags: 0x%x", flag);
270
271     OCEntityHandlerResult ehResult = OC_EH_ERROR;
272     OCEntityHandlerResponse response;
273     char payload[MAX_RESPONSE_LENGTH] = {0};
274
275     if (flag & OC_REQUEST_FLAG)
276     {
277         OC_LOG (INFO, TAG, "Flag includes OC_REQUEST_FLAG");
278         if (entityHandlerRequest)
279         {
280             if (OC_REST_GET == entityHandlerRequest->method)
281             {
282                 OC_LOG (INFO, TAG, "Received OC_REST_GET from client");
283                 ehResult = ProcessGetRequest (entityHandlerRequest, payload, sizeof(payload) - 1);
284             }
285             else if (OC_REST_PUT == entityHandlerRequest->method)
286             {
287                 OC_LOG (INFO, TAG, "Received OC_REST_PUT from client");
288                 ehResult = ProcessPutRequest (entityHandlerRequest, payload, sizeof(payload) - 1);
289             }
290             else if (OC_REST_POST == entityHandlerRequest->method)
291             {
292                 OC_LOG (INFO, TAG, "Received OC_REST_POST from client");
293                 ehResult = ProcessPostRequest (entityHandlerRequest, payload, sizeof(payload) - 1);
294             }
295             else
296             {
297                 OC_LOG_V (INFO, TAG, "Received unsupported method %d from client",
298                         entityHandlerRequest->method);
299             }
300
301             if (ehResult == OC_EH_OK)
302             {
303                 // Format the response.  Note this requires some info about the request
304                 response.requestHandle = entityHandlerRequest->requestHandle;
305                 response.resourceHandle = entityHandlerRequest->resource;
306                 response.ehResult = ehResult;
307                 response.payload = payload;
308                 response.payloadSize = strlen(payload);
309                 response.numSendVendorSpecificHeaderOptions = 0;
310                 memset(response.sendVendorSpecificHeaderOptions, 0, sizeof response.sendVendorSpecificHeaderOptions);
311                 memset(response.resourceUri, 0, sizeof(response.resourceUri));
312                 // Indicate that response is NOT in a persistent buffer
313                 response.persistentBufferFlag = 0;
314
315                 // Send the response
316                 if (OCDoResponse(&response) != OC_STACK_OK)
317                 {
318                     OC_LOG(ERROR, TAG, "Error sending response");
319                     ehResult = OC_EH_ERROR;
320                 }
321             }
322         }
323     }
324     return ehResult;
325 }
326
327 /* SIGINT handler: set gQuitFlag to 1 for graceful termination */
328 void handleSigInt(int signum)
329 {
330     if (signum == SIGINT)
331     {
332         gQuitFlag = 1;
333     }
334 }
335
336 int main(int argc, char* argv[])
337 {
338     OC_LOG(DEBUG, TAG, "OCServer is starting...");
339     if (OCInit(NULL, 0, OC_SERVER) != OC_STACK_OK)
340     {
341         OC_LOG(ERROR, TAG, "OCStack init error");
342         return 0;
343     }
344
345     /*
346      * Declare and create the example resource: LED
347      */
348     createLEDResource(gResourceUri, &LED, false, 0);
349
350     // Break from loop with Ctrl-C
351     OC_LOG(INFO, TAG, "Entering ocserver main loop...");
352     signal(SIGINT, handleSigInt);
353     while (!gQuitFlag)
354     {
355         if (OCProcess() != OC_STACK_OK)
356         {
357             OC_LOG(ERROR, TAG, "OCStack process error");
358             return 0;
359         }
360
361         sleep(2);
362     }
363
364     OC_LOG(INFO, TAG, "Exiting ocserver main loop...");
365
366     if (OCStop() != OC_STACK_OK)
367     {
368         OC_LOG(ERROR, TAG, "OCStack process error");
369     }
370
371     return 0;
372 }
373
374 int createLEDResource (char *uri, LEDResource *ledResource, bool resourceState, int resourcePower)
375 {
376     if (!uri)
377     {
378         OC_LOG(ERROR, TAG, "Resource URI cannot be NULL");
379         return -1;
380     }
381
382     ledResource->state = resourceState;
383     ledResource->power= resourcePower;
384     OCStackResult res = OCCreateResource(&(ledResource->handle),
385             "core.led",
386             OC_RSRVD_INTERFACE_DEFAULT,
387             uri,
388             OCEntityHandlerCb,
389             OC_DISCOVERABLE|OC_OBSERVABLE);
390     OC_LOG_V(INFO, TAG, "Created LED resource with result: %s", getResult(res));
391
392     return 0;
393 }
394