Imported Upstream version 0.9.2
[platform/upstream/iotivity.git] / service / resource-encapsulation / src / resourceContainer / examples / ContainerSampleClient.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 // OCClient.cpp : Defines the entry point for the console application.
22 //
23 #include <string>
24 #include <map>
25 #include <cstdlib>
26 #include <pthread.h>
27 #include <mutex>
28 #include <condition_variable>
29 #include "OCPlatform.h"
30 #include "OCApi.h"
31
32 using namespace OC;
33
34 typedef std::map<OCResourceIdentifier, std::shared_ptr<OCResource>> DiscoveredResourceMap;
35
36 DiscoveredResourceMap discoveredResources;
37 std::shared_ptr<OCResource> curResource;
38 std::shared_ptr<OCResource> DISensorResource;
39 static ObserveType OBSERVE_TYPE_TO_USE = ObserveType::Observe;
40 std::mutex curResourceLock;
41
42 class Light
43 {
44     public:
45
46         bool m_on_off;
47         int m_color;
48         int m_dim;
49         std::string m_name;
50
51
52         Light() : m_on_off(false), m_color(0), m_dim(0), m_name("")
53         {
54         }
55 };
56
57 Light mylight;
58
59 int observe_count()
60 {
61     static int oc = 0;
62     return ++oc;
63 }
64
65 void onObserve(const HeaderOptions headerOptions, const OCRepresentation &rep,
66                const int &eCode, const int &sequenceNumber)
67 {
68     try
69     {
70         if (eCode == OC_STACK_OK)
71         {
72             std::cout << "OBSERVE RESULT:" << std::endl;
73             std::cout << "\tSequenceNumber: " << sequenceNumber << std::endl;
74             rep.getValue("on-off", mylight.m_on_off);
75             rep.getValue("color", mylight.m_color);
76             rep.getValue("dim", mylight.m_dim);
77             rep.getValue("name", mylight.m_name);
78
79             std::cout << "\ton-off: " << mylight.m_on_off << std::endl;
80             std::cout << "\tcolor: " << mylight.m_color << std::endl;
81             std::cout << "\tdim: " << mylight.m_dim << std::endl;
82
83             if (observe_count() > 10)
84             {
85                 std::cout << "Cancelling Observe..." << std::endl;
86                 OCStackResult result = curResource->cancelObserve();
87
88                 std::cout << "Cancel result: " << result << std::endl;
89                 sleep(10);
90                 std::cout << "DONE" << std::endl;
91                 std::exit(0);
92             }
93         }
94         else
95         {
96             std::cout << "onObserve Response error: " << eCode << std::endl;
97         }
98     }
99     catch (std::exception &e)
100     {
101         std::cout << "Exception: " << e.what() << " in onObserve" << std::endl;
102     }
103
104 }
105
106 void onPost2(const HeaderOptions &headerOptions, const OCRepresentation &rep, const int eCode)
107 {
108     try
109     {
110         if (eCode == OC_STACK_OK || eCode == OC_STACK_RESOURCE_CREATED)
111         {
112             std::cout << "POST request was successful" << std::endl;
113
114             if (rep.hasAttribute("createduri"))
115             {
116                 std::cout << "\tUri of the created resource: "
117                           << rep.getValue<std::string>("createduri") << std::endl;
118             }
119             else
120             {
121                 rep.getValue("on-off", mylight.m_on_off);
122                 rep.getValue("color", mylight.m_color);
123                 rep.getValue("dim", mylight.m_dim);
124
125                 std::cout << "\ton-off: " << mylight.m_on_off << std::endl;
126                 std::cout << "\tcolor: " << mylight.m_color << std::endl;
127                 std::cout << "\tdim: " << mylight.m_dim << std::endl;
128             }
129
130             if (OBSERVE_TYPE_TO_USE == ObserveType::Observe)
131                 std::cout << std::endl << "Observe is used." << std::endl << std::endl;
132             else if (OBSERVE_TYPE_TO_USE == ObserveType::ObserveAll)
133                 std::cout << std::endl << "ObserveAll is used." << std::endl << std::endl;
134
135             curResource->observe(OBSERVE_TYPE_TO_USE, QueryParamsMap(), &onObserve);
136
137         }
138         else
139         {
140             std::cout << "onPost2 Response error: " << eCode << std::endl;
141         }
142     }
143     catch (std::exception &e)
144     {
145         std::cout << "Exception: " << e.what() << " in onPost2" << std::endl;
146     }
147
148 }
149
150 void onPost(const HeaderOptions &headerOptions, const OCRepresentation &rep, const int eCode)
151 {
152     try
153     {
154         if (eCode == OC_STACK_OK || eCode == OC_STACK_RESOURCE_CREATED)
155         {
156             std::cout << "POST request was successful" << std::endl;
157
158             if (rep.hasAttribute("createduri"))
159             {
160                 std::cout << "\tUri of the created resource: "
161                           << rep.getValue<std::string>("createduri") << std::endl;
162             }
163             else
164             {
165                 rep.getValue("on-off", mylight.m_on_off);
166                 rep.getValue("color", mylight.m_color);
167                 rep.getValue("dim", mylight.m_dim);
168
169                 std::cout << "\ton-off: " << mylight.m_on_off << std::endl;
170                 std::cout << "\tcolor: " << mylight.m_color << std::endl;
171                 std::cout << "\tdim: " << mylight.m_dim << std::endl;
172             }
173
174             OCRepresentation rep2;
175
176             std::cout << "Posting light representation..." << std::endl;
177
178             mylight.m_on_off = true;
179
180             rep2.setValue("on-off", mylight.m_on_off);
181
182             curResource->post(rep2, QueryParamsMap(), &onPost2);
183         }
184         else
185         {
186             std::cout << "onPost Response error: " << eCode << std::endl;
187         }
188     }
189     catch (std::exception &e)
190     {
191         std::cout << "Exception: " << e.what() << " in onPost" << std::endl;
192     }
193 }
194
195 // Local function to put a different state for this resource
196 void postLightRepresentation(std::shared_ptr<OCResource> resource)
197 {
198     if (resource)
199     {
200         OCRepresentation rep;
201
202         std::cout << "Posting light representation..." << std::endl;
203
204         mylight.m_on_off = "false";
205
206         rep.setValue("on-off", mylight.m_on_off);
207
208         // Invoke resource's post API with rep, query map and the callback parameter
209         resource->post(rep, QueryParamsMap(), &onPost);
210     }
211 }
212
213 // callback handler on PUT request
214 void onPut(const HeaderOptions &headerOptions, const OCRepresentation &rep, const int eCode)
215 {
216     try
217     {
218         if (eCode == OC_STACK_OK)
219         {
220             std::cout << "PUT request was successful" << std::endl;
221
222             /*rep.getValue("on-off", mylight.m_on_off);
223             rep.getValue("dim", mylight.m_dim);
224             rep.getValue("color", mylight.m_color);
225
226             std::cout << "\ton-off: " << mylight.m_on_off << std::endl;
227             std::cout << "\tcolor: " << mylight.m_color << std::endl;
228             std::cout << "\tdim: " << mylight.m_dim << std::endl;*/
229
230             //postLightRepresentation(curResource);
231         }
232         else
233         {
234             std::cout << "onPut Response error: " << eCode << std::endl;
235         }
236     }
237     catch (std::exception &e)
238     {
239         std::cout << "Exception: " << e.what() << " in onPut" << std::endl;
240     }
241 }
242
243 void onPutForDISensor(const HeaderOptions &headerOptions, const OCRepresentation &rep,
244                       const int eCode)
245 {
246     void onGetForDISensor(const HeaderOptions & headerOptions, const OCRepresentation & rep,
247                           const int eCode);
248
249     try
250     {
251         if (eCode == OC_STACK_OK)
252         {
253             std::cout << "PUT request was successful" << std::endl;
254
255             QueryParamsMap test;
256             std::cout << "Sending request to: " << DISensorResource->uri() << std::endl;
257             DISensorResource->get(test, &onGetForDISensor);
258         }
259         else
260         {
261             std::cout << "onPut Response error: " << eCode << std::endl;
262         }
263     }
264     catch (std::exception &e)
265     {
266         std::cout << "Exception: " << e.what() << " in onPut" << std::endl;
267     }
268 }
269
270 // Local function to put a different state for this resource
271 void putLightRepresentation(std::shared_ptr<OCResource> resource)
272 {
273     if (resource)
274     {
275         OCRepresentation rep;
276
277         std::cout << "Putting light representation..." << std::endl;
278
279         mylight.m_on_off = true;
280
281         std::cout << "Sending request to: " << resource->uri() << std::endl;
282         rep.setValue("on-off", mylight.m_on_off);
283
284         // Invoke resource's put API with rep, query map and the callback parameter
285
286         resource->put(rep, QueryParamsMap(), &onPut);
287     }
288 }
289
290 // Callback handler on GET request
291 void onGet(const HeaderOptions &headerOptions, const OCRepresentation &rep, const int eCode)
292 {
293     try
294     {
295         if (eCode == OC_STACK_OK)
296         {
297             std::cout << "GET request was successful" << std::endl;
298             std::cout << "Resource URI: " << rep.getUri() << std::endl;
299
300             std::cout << "Payload: " << rep.getPayload() << std::endl;
301
302             rep.getValue("on-off", mylight.m_on_off);
303             rep.getValue("dim", mylight.m_dim);
304             rep.getValue("color", mylight.m_color);
305
306             std::cout << "\ton-off: " << mylight.m_on_off << std::endl;
307             std::cout << "\tcolor: " << mylight.m_color << std::endl;
308             std::cout << "\tdim: " << mylight.m_dim << std::endl;
309
310             putLightRepresentation(curResource);
311         }
312         else
313         {
314             std::cout << "onGET Response error: " << eCode << std::endl;
315         }
316     }
317     catch (std::exception &e)
318     {
319         std::cout << "Exception: " << e.what() << " in onGet" << std::endl;
320     }
321 }
322
323 void onGetForDISensor(const HeaderOptions &headerOptions, const OCRepresentation &rep,
324                       const int eCode)
325 {
326     try
327     {
328         if (eCode == OC_STACK_OK)
329         {
330             std::cout << "GET request was successful" << std::endl;
331             std::cout << "Resource URI: " << DISensorResource->uri() << std::endl;
332
333             std::cout << "Payload: " << rep.getPayload() << std::endl;
334
335             std::cout << "\tdiscomfortIndex: " << rep.getValue<std::string>("discomfortIndex") << std::endl;
336         }
337         else
338         {
339             std::cout << "onGET Response error: " << eCode << std::endl;
340         }
341     }
342     catch (std::exception &e)
343     {
344         std::cout << "Exception: " << e.what() << " in onPut" << std::endl;
345     }
346 }
347
348 // Local function to get representation of light resource
349 void getLightRepresentation(std::shared_ptr<OCResource> resource)
350 {
351     if (resource)
352     {
353         std::cout << "Getting Light Representation..." << std::endl;
354         // Invoke resource's get API with the callback parameter
355
356         QueryParamsMap test;
357         std::cout << "Sending request to: " << resource->uri() << std::endl;
358         resource->get(test, &onGet);
359     }
360 }
361
362 // Callback to found resources
363 void foundResource(std::shared_ptr<OCResource> resource)
364 {
365     std::cout << "In foundResource\n";
366     std::string resourceURI = resource->uri();
367     std::string hostAddress;
368     try
369     {
370         {
371             std::lock_guard<std::mutex> lock(curResourceLock);
372             if (discoveredResources.find(resource->uniqueIdentifier()) == discoveredResources.end())
373             {
374                 std::cout << "Found resource " << resource->uniqueIdentifier() <<
375                           " for the first time on server with ID: " << resource->sid() << std::endl;
376                 discoveredResources[resource->uniqueIdentifier()] = resource;
377
378                 if (resourceURI.find("/discomfortIndex") != std::string::npos)
379                 {
380                     std::cout << "discomfortIndex found !!! " << std::endl;
381
382                     DISensorResource = resource;
383
384                     OCRepresentation rep;
385
386                     rep.setValue("humidity", std::string("30"));
387                     rep.setValue("temperature", std::string("27"));
388
389                     resource->put(rep, QueryParamsMap(), &onPutForDISensor);
390                 }
391             }
392             else
393             {
394                 std::cout << "Found resource " << resource->uniqueIdentifier() << " again!" << std::endl;
395             }
396
397             if (curResource)
398             {
399                 std::cout << "Found another resource, ignoring" << std::endl;
400                 return;
401             }
402         }
403
404         // Do some operations with resource object.
405         if (resource)
406         {
407             std::cout << "DISCOVERED Resource:" << std::endl;
408             // Get the resource URI
409             resourceURI = resource->uri();
410             std::cout << "\tURI of the resource: " << resourceURI << std::endl;
411
412             // Get the resource host address
413             hostAddress = resource->host();
414             std::cout << "\tHost address of the resource: " << hostAddress << std::endl;
415
416             // Get the resource types
417             std::cout << "\tList of resource types: " << std::endl;
418             for (auto &resourceTypes : resource->getResourceTypes())
419             {
420                 std::cout << "\t\t" << resourceTypes << std::endl;
421
422                 if (resourceTypes == "oic.light.control")
423                 {
424                     curResource = resource;
425                     // Call a local function which will internally invoke get API on the resource pointer
426                     getLightRepresentation(resource);
427                 }
428             }
429
430             // Get the resource interfaces
431             std::cout << "\tList of resource interfaces: " << std::endl;
432             for (auto &resourceInterfaces : resource->getResourceInterfaces())
433             {
434                 std::cout << "\t\t" << resourceInterfaces << std::endl;
435             }
436         }
437         else
438         {
439             // Resource is invalid
440             std::cout << "Resource is invalid" << std::endl;
441         }
442
443     }
444     catch (std::exception &e)
445     {
446         std::cerr << "Exception in foundResource: " << e.what() << std::endl;
447     }
448 }
449
450 void printUsage()
451 {
452     std::cout << std::endl;
453     std::cout << "---------------------------------------------------------------------\n";
454     std::cout << "Usage : ContainerSampleClient <ObserveType>" << std::endl;
455     std::cout << "   ObserveType : 1 - Observe" << std::endl;
456     std::cout << "   ObserveType : 2 - ObserveAll" << std::endl;
457     std::cout << "---------------------------------------------------------------------\n\n";
458 }
459
460 void checkObserverValue(int value)
461 {
462     if (value == 1)
463     {
464         OBSERVE_TYPE_TO_USE = ObserveType::Observe;
465         std::cout << "<===Setting ObserveType to Observe===>\n\n";
466     }
467     else if (value == 2)
468     {
469         OBSERVE_TYPE_TO_USE = ObserveType::ObserveAll;
470         std::cout << "<===Setting ObserveType to ObserveAll===>\n\n";
471     }
472     else
473     {
474         std::cout << "<===Invalid ObserveType selected."
475                   << " Setting ObserveType to Observe===>\n\n";
476     }
477 }
478
479 static FILE *client_open(const char *path, const char *mode)
480 {
481     return fopen("./oic_svr_db_client.json", mode);
482 }
483
484 int main(int argc, char *argv[])
485 {
486
487     std::ostringstream requestURI;
488     OCPersistentStorage ps {client_open, fread, fwrite, fclose, unlink };
489     try
490     {
491         printUsage();
492         if (argc == 1)
493         {
494             std::cout << "<===Setting ObserveType to Observe and ConnectivityType to IP===>\n\n";
495         }
496         else if (argc == 2)
497         {
498             checkObserverValue(std::stoi(argv[1]));
499         }
500         else
501         {
502             std::cout << "<===Invalid number of command line arguments===>\n\n";
503             return -1;
504         }
505     }
506     catch (std::exception &)
507     {
508         std::cout << "<===Invalid input arguments===>\n\n";
509         return -1;
510     }
511
512     // Create PlatformConfig object
513     PlatformConfig cfg
514     {
515         OC::ServiceType::InProc,
516         OC::ModeType::Both,
517         "0.0.0.0",
518         0,
519         OC::QualityOfService::LowQos,
520         &ps
521     };
522
523     OCPlatform::Configure(cfg);
524     try
525     {
526         // makes it so that all boolean values are printed as 'true/false' in this stream
527         std::cout.setf(std::ios::boolalpha);
528         // Find all resources
529         requestURI << OC_RSRVD_WELL_KNOWN_URI;// << "?rt=core.light";
530
531         OCPlatform::findResource("", requestURI.str(),
532                                  CT_DEFAULT, &foundResource);
533         std::cout << "Finding Resource... " << std::endl;
534
535         // Find resource is done twice so that we discover the original resources a second time.
536         // These resources will have the same uniqueidentifier (yet be different objects), so that
537         // we can verify/show the duplicate-checking code in foundResource(above);
538         OCPlatform::findResource("", requestURI.str(),
539                                  CT_DEFAULT, &foundResource);
540         std::cout << "Finding Resource for second time..." << std::endl;
541
542         // A condition variable will free the mutex it is given, then do a non-
543         // intensive block until 'notify' is called on it.  In this case, since we
544         // don't ever call cv.notify, this should be a non-processor intensive version
545         // of while(true);
546         std::mutex blocker;
547         std::condition_variable cv;
548         std::unique_lock<std::mutex> lock(blocker);
549         cv.wait(lock);
550
551     }
552     catch (OCException &e)
553     {
554         oclog() << "Exception in main: " << e.what();
555     }
556
557     return 0;
558 }
559
560