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