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