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