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