Imported Upstream version 0.9.2
[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 std::mutex curResourceLock;
40
41 class Light
42 {
43 public:
44
45     bool m_state;
46     int m_power;
47     std::string m_name;
48
49     Light() : m_state(false), m_power(0), m_name("")
50     {
51     }
52 };
53
54 Light mylight;
55
56 int observe_count()
57 {
58     static int oc = 0;
59     return ++oc;
60 }
61
62 void onObserve(const HeaderOptions headerOptions, const OCRepresentation& rep,
63                     const int& eCode, const int& sequenceNumber)
64 {
65     try
66     {
67         if(eCode == OC_STACK_OK)
68         {
69             std::cout << "OBSERVE RESULT:"<<std::endl;
70             std::cout << "\tSequenceNumber: "<< sequenceNumber << std::endl;
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() > 10)
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 << std::endl << "Observe is used." << std::endl << std::endl;
129             else if (OBSERVE_TYPE_TO_USE == ObserveType::ObserveAll)
130                 std::cout << std::endl << "ObserveAll is used." << std::endl << std::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::cout << "In foundResource\n";
316     std::string resourceURI;
317     std::string hostAddress;
318     try
319     {
320         {
321             std::lock_guard<std::mutex> lock(curResourceLock);
322             if(discoveredResources.find(resource->uniqueIdentifier()) == discoveredResources.end())
323             {
324                 std::cout << "Found resource " << resource->uniqueIdentifier() <<
325                     " for the first time on server with ID: "<< resource->sid()<<std::endl;
326                 discoveredResources[resource->uniqueIdentifier()] = resource;
327             }
328             else
329             {
330                 std::cout<<"Found resource "<< resource->uniqueIdentifier() << " again!"<<std::endl;
331             }
332
333             if(curResource)
334             {
335                 std::cout << "Found another resource, ignoring"<<std::endl;
336                 return;
337             }
338         }
339
340         // Do some operations with resource object.
341         if(resource)
342         {
343             std::cout<<"DISCOVERED Resource:"<<std::endl;
344             // Get the resource URI
345             resourceURI = resource->uri();
346             std::cout << "\tURI of the resource: " << resourceURI << std::endl;
347
348             // Get the resource host address
349             hostAddress = resource->host();
350             std::cout << "\tHost address of the resource: " << hostAddress << std::endl;
351
352             // Get the resource types
353             std::cout << "\tList of resource types: " << std::endl;
354             for(auto &resourceTypes : resource->getResourceTypes())
355             {
356                 std::cout << "\t\t" << resourceTypes << std::endl;
357             }
358
359             // Get the resource interfaces
360             std::cout << "\tList of resource interfaces: " << std::endl;
361             for(auto &resourceInterfaces : resource->getResourceInterfaces())
362             {
363                 std::cout << "\t\t" << resourceInterfaces << std::endl;
364             }
365
366             if(resourceURI == "/a/light")
367             {
368                 curResource = resource;
369                 // Call a local function which will internally invoke get API on the resource pointer
370                 getLightRepresentation(resource);
371             }
372         }
373         else
374         {
375             // Resource is invalid
376             std::cout << "Resource is invalid" << std::endl;
377         }
378
379     }
380     catch(std::exception& e)
381     {
382         std::cerr << "Exception in foundResource: "<< e.what() << std::endl;
383     }
384 }
385
386 void printUsage()
387 {
388     std::cout << std::endl;
389     std::cout << "---------------------------------------------------------------------\n";
390     std::cout << "Usage : simpleclient <ObserveType>" << std::endl;
391     std::cout << "   ObserveType : 1 - Observe" << std::endl;
392     std::cout << "   ObserveType : 2 - ObserveAll" << std::endl;
393     std::cout << "---------------------------------------------------------------------\n\n";
394 }
395
396 void checkObserverValue(int value)
397 {
398     if (value == 1)
399     {
400         OBSERVE_TYPE_TO_USE = ObserveType::Observe;
401         std::cout << "<===Setting ObserveType to Observe===>\n\n";
402     }
403     else if (value == 2)
404     {
405         OBSERVE_TYPE_TO_USE = ObserveType::ObserveAll;
406         std::cout << "<===Setting ObserveType to ObserveAll===>\n\n";
407     }
408     else
409     {
410         std::cout << "<===Invalid ObserveType selected."
411                   <<" Setting ObserveType to Observe===>\n\n";
412     }
413 }
414
415 static FILE* client_open(const char *path, const char *mode)
416 {
417     return fopen("./oic_svr_db_client.json", mode);
418 }
419
420 int main(int argc, char* argv[]) {
421
422     std::ostringstream requestURI;
423     OCPersistentStorage ps {client_open, fread, fwrite, fclose, unlink };
424     try
425     {
426         printUsage();
427         if (argc == 1)
428         {
429             std::cout << "<===Setting ObserveType to Observe and ConnectivityType to IP===>\n\n";
430         }
431         else if (argc == 2)
432         {
433             checkObserverValue(std::stoi(argv[1]));
434         }
435         else
436         {
437             std::cout << "<===Invalid number of command line arguments===>\n\n";
438             return -1;
439         }
440     }
441     catch(std::exception& )
442     {
443         std::cout << "<===Invalid input arguments===>\n\n";
444         return -1;
445     }
446
447     // Create PlatformConfig object
448     PlatformConfig cfg {
449         OC::ServiceType::InProc,
450         OC::ModeType::Both,
451         "0.0.0.0",
452         0,
453         OC::QualityOfService::LowQos,
454         &ps
455     };
456
457     OCPlatform::Configure(cfg);
458     try
459     {
460         // makes it so that all boolean values are printed as 'true/false' in this stream
461         std::cout.setf(std::ios::boolalpha);
462         // Find all resources
463         requestURI << OC_RSRVD_WELL_KNOWN_URI;// << "?rt=core.light";
464
465         OCPlatform::findResource("", requestURI.str(),
466                 CT_DEFAULT, &foundResource);
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                 CT_DEFAULT, &foundResource);
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     }catch(OCException& e)
486     {
487         oclog() << "Exception in main: "<<e.what();
488     }
489
490     return 0;
491 }
492
493