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