iotivity 0.9.0
[platform/upstream/iotivity.git] / resource / csdk / stack / samples / linux / SimpleClientServer / ocservercoll.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
22 #include <stdio.h>
23 #include <string.h>
24 #include <string>
25 #include <stdlib.h>
26 #include <unistd.h>
27 #include <signal.h>
28 #include <pthread.h>
29 #include <ocstack.h>
30 #include <logger.h>
31
32 const char *getResult(OCStackResult result);
33
34 #define TAG PCF("ocservercontainer")
35
36 volatile sig_atomic_t gQuitFlag = 0;
37 int gLightUnderObservation = 0;
38 void createResources();
39 typedef struct LIGHTRESOURCE{
40     OCResourceHandle handle;
41     bool state;
42     int power;
43 } LightResource;
44
45 static LightResource light;
46
47 // TODO : hard coded for now, change after Sprint10
48 const char rspGetRoomDefault[] = "{\"href\":\"/a/room\",\"rep\":{\"name\":\"John's Room\"}}";
49 const char rspGetRoomCollection[] = "{\"href\":\"/a/room\"}";
50 // TODO : Needs to be changed to retrieve current status of room and return that in response
51 const char rspPutRoomDefault[] = "{\"href\":\"/a/room\",\"rep\":{\"name\":\"John's Room\"}}";
52 const char rspPutRoomCollection[] = "{\"href\":\"/a/room\"}";
53 const char rspFailureRoom[] = "{\"href\":\"/a/room\",\"rep\":{\"error\":\"ROOM_OP_FAIL\"}}";
54
55 // TODO : hard coded for now, change after Sprint4
56 const char rspGetLightDefault[] = "{\"href\":\"/a/light\",\"rep\":{\"state\":\"false\",\"color\":\"0\"}}";
57 const char rspGetLightCollection[] = "{\"href\":\"/a/light\"}";
58 // TODO : Needs to be changed to retrieve current status of light and return that in response
59 const char rspPutLightDefault[] = "{\"href\":\"/a/light\",\"rep\":{\"state\":\"true\",\"color\":\"0\"}}";
60 const char rspPutLightCollection[] = "{\"href\":\"/a/light\"}";
61 const char rspFailureLight[] = "{\"href\":\"/a/light\",\"rep\":{\"error\":\"LIGHT_OP_FAIL\"}}";
62
63
64 // TODO : hard coded for now, change after Sprint4
65 const char rspGetFanDefault[] = "{\"href\":\"/a/fan\",\"rep\":{\"state\":\"true\",\"speed\":10}}";
66 const char rspGetFanCollection[] = "{\"href\":\"/a/fan\"}";
67 // TODO : Needs to be changed to retrieve current status of fan and return that in response
68 const char rspPutFanDefault[] = "{\"href\":\"/a/fan\",\"rep\":{\"state\":\"false\",\"speed\":0}}";
69 const char rspPutFanCollection[] = "{\"href\":\"/a/fan\"}";
70 const char rspFailureFan[] = "{\"href\":\"/a/fan\",\"rep\":{\"error\":\"FAN_OP_FAIL\"}}";
71
72 typedef enum {
73     TEST_INVALID = 0,
74     TEST_DEFAULT_COLL_EH,
75     TEST_APP_COLL_EH,
76     MAX_TESTS
77 } SERVER_TEST;
78
79 void PrintUsage()
80 {
81     OC_LOG(INFO, TAG, "Usage : ocservercoll -t <Test Case>");
82     OC_LOG(INFO, TAG, "Test Case 1 : Create room resource with default collection entity handler.");
83     OC_LOG(INFO, TAG, "Test Case 2 : Create room resource with application collection entity handler.");
84 }
85
86 unsigned static int TEST = TEST_INVALID;
87
88 static OCEntityHandlerResult
89 HandleCallback(OCEntityHandlerRequest * ehRequest,
90                const char* opStr,
91                const char* errStr,
92                char *payload,
93                uint16_t maxPayloadSize)
94 {
95     OCEntityHandlerResult ret = OC_EH_OK;
96
97     // Append opStr or errStr, after making sure there is
98     // enough room in the payload
99     if (strlen(opStr) < (maxPayloadSize - strlen(payload)))
100     {
101         strncat((char*)payload, opStr, strlen(opStr));
102     }
103     else if (strlen(errStr) < (maxPayloadSize - strlen(payload)))
104     {
105         strncat((char*)payload, errStr, strlen(errStr));
106         ret = OC_EH_ERROR;
107     }
108     else
109     {
110         ret = OC_EH_ERROR;
111     }
112
113     return ret;
114 }
115
116 static void
117 PrintReceivedMsgInfo(OCEntityHandlerFlag flag, OCEntityHandlerRequest * ehRequest)
118 {
119     const char* typeOfMessage;
120
121     switch (flag) {
122         case OC_INIT_FLAG:
123             typeOfMessage = "OC_INIT_FLAG";
124             break;
125         case OC_REQUEST_FLAG:
126             typeOfMessage = "OC_REQUEST_FLAG";
127             break;
128         case OC_OBSERVE_FLAG:
129             typeOfMessage = "OC_OBSERVE_FLAG";
130             break;
131         default:
132             typeOfMessage = "UNKNOWN";
133     }
134
135     OC_LOG_V(INFO, TAG, "Receiving message type: %s, method %s",
136              typeOfMessage,
137              (ehRequest->method == OC_REST_GET) ? "OC_REST_GET" : "OC_REST_PUT" );
138 }
139
140 OCEntityHandlerResult OCEntityHandlerRoomCb(OCEntityHandlerFlag flag,
141                                             OCEntityHandlerRequest * ehRequest)
142 {
143     OCEntityHandlerResult ret = OC_EH_OK;
144     OCEntityHandlerResponse response;
145     char payload[MAX_RESPONSE_LENGTH] = {0};
146
147     OC_LOG_V(INFO, TAG, "Callback for Room");
148     PrintReceivedMsgInfo(flag, ehRequest );
149
150     if(ehRequest && flag == OC_REQUEST_FLAG )
151     {
152         std::string query = (const char*)ehRequest->query;
153
154         if(OC_REST_GET == ehRequest->method)
155         {
156             if(query.find("oc.mi.def") != std::string::npos)
157             {
158                 ret = HandleCallback(ehRequest, rspGetRoomDefault, rspFailureRoom, payload, sizeof(payload));
159                 if(ret != OC_EH_ERROR)
160                 {
161                     ret = HandleCallback(ehRequest, ",", ",", payload, sizeof(payload));
162                     ret = HandleCallback(ehRequest, rspGetLightCollection, rspFailureLight, payload, sizeof(payload));
163                 }
164                 if(ret != OC_EH_ERROR)
165                 {
166                     ret = HandleCallback(ehRequest, ",", ",", payload, sizeof(payload));
167                     ret = HandleCallback(ehRequest, rspGetFanCollection, rspFailureFan, payload, sizeof(payload));
168                 }
169             }
170             else if(query.find("oc.mi.ll") != std::string::npos)
171             {
172                 ret = HandleCallback(ehRequest, rspGetRoomCollection, rspFailureRoom, payload, sizeof(payload));
173                 if(ret != OC_EH_ERROR)
174                 {
175                     ret = HandleCallback(ehRequest, ",", ",", payload, sizeof(payload));
176                     ret = HandleCallback(ehRequest, rspGetLightCollection, rspFailureLight, payload, sizeof(payload));
177                 }
178                 if(ret != OC_EH_ERROR)
179                 {
180                     ret = HandleCallback(ehRequest, ",", ",", payload, sizeof(payload));
181                     ret = HandleCallback(ehRequest, rspGetFanCollection, rspFailureFan, payload, sizeof(payload));
182                 }
183             }
184             else if(query.find("oc.mi.b") != std::string::npos)
185             {
186                 ret = HandleCallback(ehRequest, rspGetRoomCollection, rspFailureRoom, payload, sizeof(payload));
187                 if(ret != OC_EH_ERROR)
188                 {
189                     ret = HandleCallback(ehRequest, ",", ",", payload, sizeof(payload));
190                     ret = HandleCallback(ehRequest, rspGetLightDefault, rspFailureLight, payload, sizeof(payload));
191                 }
192                 if(ret != OC_EH_ERROR)
193                 {
194                     ret = HandleCallback(ehRequest, ",", ",", payload, sizeof(payload));
195                     ret = HandleCallback(ehRequest, rspGetFanDefault, rspFailureFan, payload, sizeof(payload));
196                 }
197             }
198             if (ret == OC_EH_OK)
199             {
200                 // Format the response.  Note this requires some info about the request
201                 response.requestHandle = ehRequest->requestHandle;
202                 response.resourceHandle = ehRequest->resource;
203                 response.ehResult = ret;
204                 response.payload = (unsigned char *)payload;
205                 response.payloadSize = strlen(payload);
206                 response.numSendVendorSpecificHeaderOptions = 0;
207                 memset(response.sendVendorSpecificHeaderOptions, 0, sizeof response.sendVendorSpecificHeaderOptions);
208                 memset(response.resourceUri, 0, sizeof response.resourceUri);
209                 // Indicate that response is NOT in a persistent buffer
210                 response.persistentBufferFlag = 0;
211                 // Send the response
212                 if (OCDoResponse(&response) != OC_STACK_OK)
213                 {
214                     OC_LOG(ERROR, TAG, "Error sending response");
215                     ret = OC_EH_ERROR;
216                 }
217             }
218         }
219         else if(OC_REST_PUT == ehRequest->method)
220         {
221             if(query.find("oc.mi.def") != std::string::npos)
222             {
223                 if(ret != OC_EH_ERROR)
224                 {
225                     ret = HandleCallback(ehRequest, rspPutRoomDefault, rspFailureRoom, payload, sizeof(payload));
226                 }
227             }
228             if(query.find("oc.mi.ll") != std::string::npos)
229             {
230                 if(ret != OC_EH_ERROR)
231                 {
232                     ret = HandleCallback(ehRequest, rspPutRoomCollection, rspFailureRoom, payload, sizeof(payload));
233                 }
234                 if(ret != OC_EH_ERROR)
235                 {
236                     ret = HandleCallback(ehRequest, ",", ",", payload, sizeof(payload));
237                     ret = HandleCallback(ehRequest, rspPutLightCollection, rspFailureLight, payload, sizeof(payload));
238                 }
239                 if(ret != OC_EH_ERROR)
240                 {
241                     ret = HandleCallback(ehRequest, ",", ",", payload, sizeof(payload));
242                     ret = HandleCallback(ehRequest, rspPutFanCollection, rspFailureFan, payload, sizeof(payload));
243                 }
244             }
245             if(query.find("oc.mi.b") != std::string::npos)
246             {
247                 if(ret != OC_EH_ERROR)
248                 {
249                     ret = HandleCallback(ehRequest, rspPutRoomCollection, rspFailureRoom, payload, sizeof(payload));
250                 }
251                 if(ret != OC_EH_ERROR)
252                 {
253                     ret = HandleCallback(ehRequest, ",", ",", payload, sizeof(payload));
254                     ret = HandleCallback(ehRequest, rspPutLightDefault, rspFailureLight, payload, sizeof(payload));
255                 }
256                 if(ret != OC_EH_ERROR)
257                 {
258                     ret = HandleCallback(ehRequest, ",", ",", payload, sizeof(payload));
259                     ret = HandleCallback(ehRequest, rspPutFanDefault, rspFailureFan, payload, sizeof(payload));
260                 }
261             }
262             if (ret == OC_EH_OK)
263             {
264                 // Format the response.  Note this requires some info about the request
265                 response.requestHandle = ehRequest->requestHandle;
266                 response.resourceHandle = ehRequest->resource;
267                 response.ehResult = ret;
268                 response.payload = (unsigned char *)payload;
269                 response.payloadSize = strlen(payload);
270                 response.numSendVendorSpecificHeaderOptions = 0;
271                 memset(response.sendVendorSpecificHeaderOptions, 0, sizeof response.sendVendorSpecificHeaderOptions);
272                 memset(response.resourceUri, 0, sizeof response.resourceUri);
273                 // Indicate that response is NOT in a persistent buffer
274                 response.persistentBufferFlag = 0;
275                 // Send the response
276                 if (OCDoResponse(&response) != OC_STACK_OK)
277                 {
278                     OC_LOG(ERROR, TAG, "Error sending response");
279                     ret = OC_EH_ERROR;
280                 }
281             }
282         }
283         else
284         {
285             OC_LOG_V (INFO, TAG, "Received unsupported method %d from client",
286                     ehRequest->method);
287             ret = OC_EH_ERROR;
288         }
289     }
290     else if (ehRequest && flag == OC_OBSERVE_FLAG)
291     {
292         gLightUnderObservation = 1;
293     }
294     return ret;
295 }
296
297 OCEntityHandlerResult OCEntityHandlerLightCb(OCEntityHandlerFlag flag, OCEntityHandlerRequest * ehRequest)
298 {
299     OCEntityHandlerResult ret = OC_EH_OK;
300     OCEntityHandlerResponse response;
301     char payload[MAX_RESPONSE_LENGTH] = {0};
302
303     OC_LOG_V(INFO, TAG, "Callback for Light");
304     PrintReceivedMsgInfo(flag, ehRequest );
305
306     if(ehRequest && flag == OC_REQUEST_FLAG)
307     {
308         if(OC_REST_GET == ehRequest->method)
309         {
310             ret = HandleCallback(ehRequest, rspGetLightDefault, rspFailureLight, payload, sizeof(payload));
311         }
312         else if(OC_REST_PUT == ehRequest->method)
313         {
314             ret = HandleCallback(ehRequest, rspPutLightDefault, rspFailureLight, payload, sizeof(payload));
315         }
316         else
317         {
318             OC_LOG_V (INFO, TAG, "Received unsupported method %d from client",
319                     ehRequest->method);
320             ret = OC_EH_ERROR;
321         }
322
323         if (ret == OC_EH_OK)
324         {
325             // Format the response.  Note this requires some info about the request
326             response.requestHandle = ehRequest->requestHandle;
327             response.resourceHandle = ehRequest->resource;
328             response.ehResult = ret;
329             response.payload = (unsigned char *)payload;
330             response.payloadSize = strlen(payload);
331             response.numSendVendorSpecificHeaderOptions = 0;
332             memset(response.sendVendorSpecificHeaderOptions, 0, sizeof response.sendVendorSpecificHeaderOptions);
333             memset(response.resourceUri, 0, sizeof response.resourceUri);
334             // Indicate that response is NOT in a persistent buffer
335             response.persistentBufferFlag = 0;
336
337             // Send the response
338             if (OCDoResponse(&response) != OC_STACK_OK)
339             {
340                 OC_LOG(ERROR, TAG, "Error sending response");
341                 ret = OC_EH_ERROR;
342             }
343         }
344     }
345     else if (ehRequest && flag == OC_OBSERVE_FLAG)
346     {
347         gLightUnderObservation = 1;
348     }
349
350     return ret;
351 }
352
353 OCEntityHandlerResult OCEntityHandlerFanCb(OCEntityHandlerFlag flag, OCEntityHandlerRequest * ehRequest)
354 {
355     OCEntityHandlerResult ret = OC_EH_OK;
356     OCEntityHandlerResponse response;
357     char payload[MAX_RESPONSE_LENGTH] = {0};
358
359     OC_LOG_V(INFO, TAG, "Callback for Fan");
360     PrintReceivedMsgInfo(flag, ehRequest );
361
362     if(ehRequest && flag == OC_REQUEST_FLAG)
363     {
364         if(OC_REST_GET == ehRequest->method)
365         {
366             ret = HandleCallback(ehRequest, rspGetFanDefault, rspFailureFan, payload, sizeof(payload));
367         }
368         else if(OC_REST_PUT == ehRequest->method)
369         {
370             ret = HandleCallback(ehRequest, rspPutFanDefault, rspFailureFan, payload, sizeof(payload));
371         }
372         else
373         {
374             OC_LOG_V (INFO, TAG, "Received unsupported method %d from client",
375                     ehRequest->method);
376             ret = OC_EH_ERROR;
377         }
378
379         if (ret == OC_EH_OK)
380         {
381             // Format the response.  Note this requires some info about the request
382             response.requestHandle = ehRequest->requestHandle;
383             response.resourceHandle = ehRequest->resource;
384             response.ehResult = ret;
385             response.payload = (unsigned char *)payload;
386             response.payloadSize = strlen(payload);
387             response.numSendVendorSpecificHeaderOptions = 0;
388             memset(response.sendVendorSpecificHeaderOptions, 0, sizeof response.sendVendorSpecificHeaderOptions);
389             memset(response.resourceUri, 0, sizeof response.resourceUri);
390             // Indicate that response is NOT in a persistent buffer
391             response.persistentBufferFlag = 0;
392
393             // Send the response
394             if (OCDoResponse(&response) != OC_STACK_OK)
395             {
396                 OC_LOG(ERROR, TAG, "Error sending response");
397                 ret = OC_EH_ERROR;
398             }
399         }
400
401     }
402     else if (ehRequest && flag == OC_OBSERVE_FLAG)
403     {
404         gLightUnderObservation = 1;
405     }
406
407     return ret;
408 }
409
410 /* SIGINT handler: set gQuitFlag to 1 for graceful termination */
411 void handleSigInt(int signum)
412 {
413     if (signum == SIGINT)
414     {
415         gQuitFlag = 1;
416     }
417 }
418
419 void *ChangeLightRepresentation (void *param)
420 {
421     (void)param;
422     OCStackResult result = OC_STACK_ERROR;
423
424     while (!gQuitFlag)
425     {
426         sleep(10);
427         light.power += 5;
428         if (gLightUnderObservation)
429         {
430             OC_LOG_V(INFO, TAG,
431                 " =====> Notifying stack of new power level %d\n", light.power);
432             result = OCNotifyAllObservers (light.handle, OC_NA_QOS);
433             if (OC_STACK_NO_OBSERVERS == result)
434             {
435                 gLightUnderObservation = 0;
436             }
437         }
438     }
439     return NULL;
440 }
441
442 int main(int argc, char* argv[])
443 {
444     uint8_t addr[20] = {0};
445     uint8_t* paddr = NULL;
446     uint16_t port = 0;
447     uint8_t ifname[] = "eth0";
448     pthread_t threadId;
449     int opt;
450
451     while ((opt = getopt(argc, argv, "t:")) != -1)
452     {
453         switch(opt)
454         {
455         case 't':
456             TEST = atoi(optarg);
457             break;
458         default:
459             PrintUsage();
460             return -1;
461         }
462     }
463     if(TEST <= TEST_INVALID || TEST >= MAX_TESTS){
464         PrintUsage();
465         return -1;
466     }
467
468     OC_LOG(DEBUG, TAG, "OCServer is starting...");
469     /*Get Ip address on defined interface and initialize coap on it with random port number
470      * this port number will be used as a source port in all coap communications*/
471     if (OCGetInterfaceAddress(ifname, sizeof(ifname), AF_INET, addr,
472                                sizeof(addr)) == ERR_SUCCESS)
473     {
474         OC_LOG_V(INFO, TAG, "Starting ocserver on address %s:%d",addr,port);
475         paddr = addr;
476     }
477
478     if (OCInit((char *) paddr, port, OC_SERVER) != OC_STACK_OK) {
479         OC_LOG(ERROR, TAG, "OCStack init error");
480         return 0;
481     }
482
483     /*
484      * Declare and create the example resource: light
485      */
486     createResources();
487
488     /*
489      * Create a thread for changing the representation of the light
490      */
491     pthread_create (&threadId, NULL, ChangeLightRepresentation, (void *)NULL);
492
493     // Break from loop with Ctrl-C
494     OC_LOG(INFO, TAG, "Entering ocserver main loop...");
495     signal(SIGINT, handleSigInt);
496     while (!gQuitFlag)
497     {
498         if (OCProcess() != OC_STACK_OK)
499         {
500             OC_LOG(ERROR, TAG, "OCStack process error");
501             return 0;
502         }
503         sleep(2);
504     }
505
506     /*
507      * Cancel the light thread and wait for it to terminate
508      */
509     pthread_cancel(threadId);
510     pthread_join(threadId, NULL);
511
512     OC_LOG(INFO, TAG, "Exiting ocserver main loop...");
513
514     if (OCStop() != OC_STACK_OK)
515     {
516         OC_LOG(ERROR, TAG, "OCStack process error");
517     }
518
519     return 0;
520 }
521 void createResources()
522 {
523     light.state = false;
524
525     OCResourceHandle fan;
526     OCStackResult res = OCCreateResource(&fan,
527             "core.fan",
528             "oc.mi.def",
529             "/a/fan",
530             OCEntityHandlerFanCb,
531             OC_DISCOVERABLE|OC_OBSERVABLE);
532     OC_LOG_V(INFO, TAG, "Created fan resource with result: %s", getResult(res));
533
534     OCResourceHandle light;
535     res = OCCreateResource(&light,
536             "core.light",
537             "oc.mi.def",
538             "/a/light",
539             OCEntityHandlerLightCb,
540             OC_DISCOVERABLE|OC_OBSERVABLE);
541     OC_LOG_V(INFO, TAG, "Created light resource with result: %s", getResult(res));
542
543     OCResourceHandle room;
544
545     if(TEST == TEST_APP_COLL_EH)
546     {
547         res = OCCreateResource(&room,
548                 "core.room",
549                 "oc.mi.b",
550                 "/a/room",
551                 OCEntityHandlerRoomCb,
552                 OC_DISCOVERABLE);
553     }
554     else
555     {
556         res = OCCreateResource(&room,
557                 "core.room",
558                 "oc.mi.b",
559                 "/a/room",
560                 NULL,
561                 OC_DISCOVERABLE);
562     }
563
564     OC_LOG_V(INFO, TAG, "Created room resource with result: %s", getResult(res));
565     OCBindResourceInterfaceToResource(room, "oc.mi.ll");
566     OCBindResourceInterfaceToResource(room, "oc.mi.def");
567
568     res = OCBindResource(room, light);
569     OC_LOG_V(INFO, TAG, "OC Bind Contained Resource to resource: %s", getResult(res));
570
571     res = OCBindResource(room, fan);
572     OC_LOG_V(INFO, TAG, "OC Bind Contained Resource to resource: %s", getResult(res));
573 }