Imported Upstream version 1.1.1
[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() == 11)
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 || eCode == OC_STACK_RESOURCE_CHANGED)
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*/,
154         const OCRepresentation& rep, const int eCode)
155 {
156     if(eCode == SUCCESS_RESPONSE || eCode == OC_STACK_RESOURCE_CHANGED)
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("state", mylight.m_state);
168             rep.getValue("power", mylight.m_power);
169             rep.getValue("name", mylight.m_name);
170
171             std::cout << "\tstate: " << mylight.m_state << std::endl;
172             std::cout << "\tpower: " << mylight.m_power << std::endl;
173             std::cout << "\tname: " << mylight.m_name << std::endl;
174         }
175
176         OCRepresentation rep2;
177
178         std::cout << "Posting light representation..."<<std::endl;
179
180         mylight.m_state = true;
181         mylight.m_power = 55;
182
183         rep2.setValue("state", mylight.m_state);
184         rep2.setValue("power", mylight.m_power);
185         sleep(1);
186         curResource->post(rep2, QueryParamsMap(), &onPost2, OC::QualityOfService::HighQos);
187     }
188     else
189     {
190         std::cout << "onPost Response error: " << eCode << std::endl;
191         std::exit(-1);
192     }
193 }
194
195 // Local function to put a different state for this resource
196 void postLightRepresentation(std::shared_ptr<OCResource> resource)
197 {
198     if(resource)
199     {
200         OCRepresentation rep;
201
202         std::cout << "Posting light representation..."<<std::endl;
203
204         mylight.m_state = false;
205         mylight.m_power = 105;
206
207         rep.setValue("state", mylight.m_state);
208         rep.setValue("power", mylight.m_power);
209
210         // Invoke resource's post API with rep, query map and the callback parameter
211         resource->post(rep, QueryParamsMap(), &onPost, OC::QualityOfService::HighQos);
212     }
213 }
214
215 // callback handler on PUT request
216 void onPut(const HeaderOptions& /*headerOptions*/, const OCRepresentation& rep, const int eCode)
217 {
218     if(eCode == SUCCESS_RESPONSE)
219     {
220         std::cout << "PUT request was successful" << std::endl;
221
222         rep.getValue("state", mylight.m_state);
223         rep.getValue("power", mylight.m_power);
224         rep.getValue("name", mylight.m_name);
225
226         std::cout << "\tstate: " << mylight.m_state << std::endl;
227         std::cout << "\tpower: " << mylight.m_power << std::endl;
228         std::cout << "\tname: " << mylight.m_name << std::endl;
229         sleep(1);
230         postLightRepresentation(curResource);
231     }
232     else
233     {
234         std::cout << "onPut Response error: " << eCode << std::endl;
235         std::exit(-1);
236     }
237 }
238
239 // Local function to put a different state for this resource
240 void putLightRepresentation(std::shared_ptr<OCResource> resource)
241 {
242     if(resource)
243     {
244         OCRepresentation rep;
245
246         std::cout << "Putting light representation..."<<std::endl;
247
248         mylight.m_state = true;
249         mylight.m_power = 15;
250
251         rep.setValue("state", mylight.m_state);
252         rep.setValue("power", mylight.m_power);
253
254         // Invoke resource's put API with rep, query map and the callback parameter
255         resource->put(rep, QueryParamsMap(), &onPut, OC::QualityOfService::HighQos);
256     }
257 }
258
259 // Callback handler on GET request
260 void onGet(const HeaderOptions& /*headerOptions*/, const OCRepresentation& rep, const int eCode)
261 {
262     if(eCode == SUCCESS_RESPONSE)
263     {
264         std::cout << "GET request was successful" << std::endl;
265         std::cout << "Resource URI: " << rep.getUri() << std::endl;
266
267         rep.getValue("state", mylight.m_state);
268         rep.getValue("power", mylight.m_power);
269         rep.getValue("name", mylight.m_name);
270
271         std::cout << "\tstate: " << mylight.m_state << std::endl;
272         std::cout << "\tpower: " << mylight.m_power << std::endl;
273         std::cout << "\tname: " << mylight.m_name << std::endl;
274         sleep(1);
275         putLightRepresentation(curResource);
276     }
277     else
278     {
279         std::cout << "onGET Response error: " << eCode << std::endl;
280         std::exit(-1);
281     }
282 }
283
284 // Local function to get representation of light resource
285 void getLightRepresentation(std::shared_ptr<OCResource> resource)
286 {
287     if(resource)
288     {
289         std::cout << "Getting Light Representation..."<<std::endl;
290         // Invoke resource's get API with the callback parameter
291
292         QueryParamsMap test;
293         resource->get(test, &onGet,OC::QualityOfService::HighQos);
294     }
295 }
296
297 // Callback to found resources
298 void foundResource(std::shared_ptr<OCResource> resource)
299 {
300     std::string resourceURI;
301     std::string hostAddress;
302     try
303     {
304         // Do some operations with resource object.
305         if(resource)
306         {
307             std::lock_guard<std::mutex> lk(resourceLock);
308
309             if(discoveredResources.find(resource) == discoveredResources.end())
310             {
311                 std::cout << "Found resource " << resource->uniqueIdentifier() <<
312                     " for the first time on server with ID: "<< resource->sid()<<std::endl;
313                 discoveredResources.insert(resource);
314             }
315             else
316             {
317                 std::cout<<"Found resource "<< resource->uniqueIdentifier() << " again!"<<std::endl;
318             }
319
320             if(curResource)
321             {
322                 std::cout << "Found another resource, ignoring"<<std::endl;
323                 return;
324             }
325
326             std::cout<<"DISCOVERED Resource:"<<std::endl;
327             // Get the resource URI
328             resourceURI = resource->uri();
329             std::cout << "\tURI of the resource: " << resourceURI << std::endl;
330
331             // Get the resource host address
332             hostAddress = resource->host();
333             std::cout << "\tHost address of the resource: " << hostAddress << std::endl;
334
335             // Get the resource types
336             std::cout << "\tList of resource types: " << std::endl;
337             for(auto &resourceTypes : resource->getResourceTypes())
338             {
339                 std::cout << "\t\t" << resourceTypes << std::endl;
340             }
341
342             // Get the resource interfaces
343             std::cout << "\tList of resource interfaces: " << std::endl;
344             for(auto &resourceInterfaces : resource->getResourceInterfaces())
345             {
346                 std::cout << "\t\t" << resourceInterfaces << std::endl;
347             }
348
349             if(resourceURI == "/a/light")
350             {
351                 curResource = resource;
352                 sleep(1);
353                 // Call a local function which will internally invoke get
354                 // API on the resource pointer
355                 getLightRepresentation(resource);
356             }
357         }
358         else
359         {
360             // Resource is invalid
361             std::cout << "Resource is invalid" << std::endl;
362         }
363
364     }
365     catch(std::exception& e)
366     {
367         std::cerr << "Exception in foundResource: "<< e.what() <<std::endl;
368     }
369 }
370
371 void PrintUsage()
372 {
373     std::cout << std::endl;
374     std::cout << "Usage : simpleclientHQ <ObserveType> <ConnectivityType>" << std::endl;
375     std::cout << "   ObserveType : 1 - Observe" << std::endl;
376     std::cout << "   ObserveType : 2 - ObserveAll" << std::endl;
377     std::cout << "   ConnectivityType: Default IP" << std::endl;
378     std::cout << "   ConnectivityType : 0 - IP"<< std::endl;
379 }
380
381 int main(int argc, char* argv[]) {
382
383     std::ostringstream requestURI;
384
385     OCConnectivityType connectivityType = CT_ADAPTER_IP;
386     try
387     {
388         if (argc == 1)
389         {
390             OBSERVE_TYPE_TO_USE = ObserveType::Observe;
391         }
392         else if (argc ==2 || argc==3)
393         {
394             int value = std::stoi(argv[1]);
395             if (value == 1)
396                 OBSERVE_TYPE_TO_USE = ObserveType::Observe;
397             else if (value == 2)
398                 OBSERVE_TYPE_TO_USE = ObserveType::ObserveAll;
399             else
400                 OBSERVE_TYPE_TO_USE = ObserveType::Observe;
401
402             if(argc == 3)
403             {
404                 std::size_t inputValLen;
405                 int optionSelected = std::stoi(argv[2], &inputValLen);
406
407                 if(inputValLen == strlen(argv[2]))
408                 {
409                     if(optionSelected == 0)
410                     {
411                         std::cout << "Using IP."<< std::endl;
412                         connectivityType = CT_ADAPTER_IP;
413                     }
414                     else
415                     {
416                         std::cout << "Invalid connectivity type selected. Using default IP"
417                             << std::endl;
418                     }
419                 }
420                 else
421                 {
422                     std::cout << "Invalid connectivity type selected. Using default IP"
423                             << std::endl;
424                 }
425             }
426         }
427         else
428         {
429             PrintUsage();
430             return -1;
431         }
432     }
433     catch(std::exception&)
434     {
435         std::cout << "Invalid input argument." << std::endl;
436         PrintUsage();
437         return -1;
438     }
439
440
441     // Create PlatformConfig object
442     PlatformConfig cfg {
443         OC::ServiceType::InProc,
444         OC::ModeType::Client,
445         "0.0.0.0",
446         0,
447         OC::QualityOfService::HighQos
448     };
449
450     OCPlatform::Configure(cfg);
451
452     try
453     {
454         // Find all resources
455         requestURI << OC_RSRVD_WELL_KNOWN_URI << "?rt=core.light";
456
457         OCPlatform::findResource("", requestURI.str(),
458                 connectivityType, &foundResource, OC::QualityOfService::LowQos);
459         std::cout<< "Finding Resource... " <<std::endl;
460
461         // Find resource is done twice so that we discover the original resources a second time.
462         // These resources will have the same uniqueidentifier (yet be different objects), so that
463         // we can verify/show the duplicate-checking code in foundResource(above);
464         OCPlatform::findResource("", requestURI.str(),
465                 connectivityType, &foundResource, OC::QualityOfService::LowQos);
466         std::cout<< "Finding Resource for second time... " <<std::endl;
467
468         // A condition variable will free the mutex it is given, then do a non-
469         // intensive block until 'notify' is called on it.  In this case, since we
470         // don't ever call cv.notify, this should be a non-processor intensive version
471         // of while(true);
472         std::mutex blocker;
473         std::condition_variable cv;
474         std::unique_lock<std::mutex> lock(blocker);
475         cv.wait(lock);
476
477     }
478     catch(OCException& e)
479     {
480         oclog() << "Exception in main: "<<e.what();
481     }
482
483     return 0;
484 }
485
486