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