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