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