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