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