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