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