Update snapshot(2017-12-14)
[platform/upstream/iotivity.git] / resource / examples / garageclient.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 // garageclient.cpp is the client program for garageserver.cpp, which
22 // uses different representation in OCRepresention.
23
24 #include <string>
25 #include <cstdlib>
26 #include <mutex>
27 #include <condition_variable>
28 #include "OCPlatform.h"
29 #include "OCApi.h"
30
31 using namespace OC;
32
33 std::shared_ptr<OCResource> curResource;
34 std::mutex curResourceLock;
35
36 static void printUsage()
37 {
38     std::cout<<"Usage: garageclient <0|1> \n";
39     std::cout<<"ConnectivityType: Default IP\n";
40     std::cout<<"ConnectivityType 0: IP \n";
41 }
42
43 class Garage
44 {
45 public:
46
47     bool m_state;
48     std::string m_name;
49     std::vector<bool> m_lightStates;
50     std::vector<int> m_lightPowers;
51     OCRepresentation m_lightRep;
52     std::vector<OCRepresentation> m_reps;
53     std::vector<std::vector<int>> m_hingeStates;
54
55     Garage() : m_state(false), m_name("")
56     {
57     }
58 };
59
60 Garage myGarage;
61
62 void printRepresentation(const OCRepresentation& rep)
63 {
64
65         // Check if attribute "name" exists, and then getValue
66         if(rep.hasAttribute("name"))
67         {
68             myGarage.m_name = rep["name"];
69         }
70         std::cout << "\tname: " << myGarage.m_name << std::endl;
71
72         // You can directly try to get the value. this function
73         // return false if there is no attribute "state"
74         if(!rep.getValue("state", myGarage.m_state))
75         {
76             std::cout << "Attribute state doesn't exist in the representation\n";
77         }
78         std::cout << "\tstate: " << myGarage.m_state << std::endl;
79
80         OCRepresentation rep2 = rep;
81
82         std::cout << "Number of attributes in rep2: "
83                   << rep2.numberOfAttributes() << std::endl;
84
85         if(rep2.erase("name"))
86         {
87             std::cout << "attribute: name, was removed successfully from rep2.\n";
88         }
89
90         std::cout << "Number of attributes in rep2: "
91                   << rep2.numberOfAttributes() << std::endl;
92
93
94         if(rep.isNULL("nullAttribute"))
95         {
96             std::cout << "\tnullAttribute is null." << std::endl;
97         }
98         else
99         {
100             std::cout << "\tnullAttribute is not null." << std::endl;
101         }
102
103         myGarage.m_lightRep = rep["light"];
104
105         myGarage.m_lightStates = myGarage.m_lightRep["states"];
106         myGarage.m_lightPowers = myGarage.m_lightRep["powers"];
107
108         std::cout << "\tlightRep: states: ";
109
110         int first = 1;
111         for(auto state: myGarage.m_lightStates)
112         {
113             if(first)
114             {
115                 std::cout << state;
116                 first = 0;
117             }
118             else
119             {
120                 std::cout << "," << state;
121             }
122         }
123
124         std::cout << std::endl;
125         std::cout << "\tlightRep: powers: ";
126         first = 1;
127         for(auto power: myGarage.m_lightPowers)
128         {
129             if(first)
130             {
131                 std::cout << power;
132                 first = 0;
133             }
134             else
135             {
136                 std::cout << "," << power;
137             }
138         }
139         std::cout << std::endl;
140
141         // Get vector of representations
142         myGarage.m_reps = rep["reps"];
143
144         int ct = 0;
145         for(auto& rep : myGarage.m_reps)
146         {
147             for(auto& attribute : rep)
148             {
149                 std::cout<< "\treps["<<ct<<"]."<<attribute.attrname()<<":"
150                     << attribute.type()<<" with value " <<attribute.getValueToString() <<std::endl;
151             }
152             ++ct;
153         }
154
155         std::cout << "\tjson: " << rep["json"] << std::endl;
156         myGarage.m_hingeStates = rep["hinges"];
157
158         std::cout<< "\tHinge parameter is type: " << rep["hinges"].type() << " with depth "<<
159             rep["hinges"].depth() << " and a base type of "<< rep["hinges"].base_type()<<std::endl;
160
161
162 }
163 // callback handler on PUT request
164 void onPut(const HeaderOptions& /*headerOptions*/, const OCRepresentation& rep, const int eCode)
165 {
166     if (eCode == OC_STACK_OK || eCode == OC_STACK_RESOURCE_CHANGED)
167     {
168         std::cout << "PUT request was successful" << std::endl;
169
170         printRepresentation(rep);
171     }
172     else
173     {
174         std::cout << "onPut Response error: " << eCode << std::endl;
175         std::exit(-1);
176     }
177 }
178
179 // Local function to put a different state for this resource
180 void putLightRepresentation(std::shared_ptr<OCResource> resource)
181 {
182     if(resource)
183     {
184         OCRepresentation rep;
185
186         std::cout << "Putting light representation..."<<std::endl;
187
188         myGarage.m_state = true;
189
190         rep["state"] = myGarage.m_state;
191
192         // Create QueryParameters Map and add query params (if any)
193         QueryParamsMap queryParamsMap;
194
195         // Invoke resource's pit API with rep, query map and the callback parameter
196         resource->put(rep, queryParamsMap, &onPut);
197     }
198 }
199
200 // Callback handler on GET request
201 void onGet(const HeaderOptions& /*headerOptions*/, const OCRepresentation& rep, const int eCode)
202 {
203     if (eCode == OC_STACK_OK)
204     {
205         std::cout << "GET request was successful" << std::endl;
206         std::cout << "Resource URI: " << rep.getUri() << std::endl;
207
208         printRepresentation(rep);
209
210         putLightRepresentation(curResource);
211     }
212     else
213     {
214         std::cout << "onGET Response error: " << eCode << std::endl;
215         std::exit(-1);
216     }
217 }
218
219 // Local function to get representation of light resource
220 void getLightRepresentation(std::shared_ptr<OCResource> resource)
221 {
222     if(resource)
223     {
224         std::cout << "Getting Light Representation..."<<std::endl;
225         // Invoke resource's get API with the callback parameter
226
227         QueryParamsMap test;
228         resource->get(test, &onGet);
229     }
230 }
231
232 // Callback to found resources
233 void foundResource(std::shared_ptr<OCResource> resource)
234 {
235     std::lock_guard<std::mutex> lock(curResourceLock);
236     if(curResource)
237     {
238         std::cout << "Found another resource, ignoring"<<std::endl;
239         return;
240     }
241
242     std::string resourceURI;
243     std::string hostAddress;
244     try
245     {
246         // Do some operations with resource object.
247         if(resource)
248         {
249             std::cout<<"DISCOVERED Resource:"<<std::endl;
250             // Get the resource URI
251             resourceURI = resource->uri();
252             std::cout << "\tURI of the resource: " << resourceURI << std::endl;
253
254             // Get the resource host address
255             hostAddress = resource->host();
256             std::cout << "\tHost address of the resource: " << hostAddress << std::endl;
257
258             // Get the resource types
259             std::cout << "\tList of resource types: " << std::endl;
260             for(auto &resourceTypes : resource->getResourceTypes())
261             {
262                 std::cout << "\t\t" << resourceTypes << std::endl;
263             }
264
265             // Get the resource interfaces
266             std::cout << "\tList of resource interfaces: " << std::endl;
267             for(auto &resourceInterfaces : resource->getResourceInterfaces())
268             {
269                 std::cout << "\t\t" << resourceInterfaces << std::endl;
270             }
271
272             if(resourceURI == "/a/garage")
273             {
274                 curResource = resource;
275                 // Call a local function which will internally invoke
276                 // get API on the resource pointer
277                 getLightRepresentation(resource);
278             }
279         }
280         else
281         {
282             // Resource is invalid
283             std::cout << "Resource is invalid" << std::endl;
284         }
285
286     }
287     catch(std::exception& e)
288     {
289         std::cerr << "Exception in foundResource: "<< e.what()<<std::endl;
290     }
291 }
292
293 int main(int argc, char* argv[]) {
294
295     std::ostringstream requestURI;
296
297     OCConnectivityType connectivityType = CT_ADAPTER_IP;
298
299     if(argc == 2)
300     {
301         try
302         {
303             std::size_t inputValLen;
304             int optionSelected = std::stoi(argv[1], &inputValLen);
305
306             if(inputValLen == strlen(argv[1]))
307             {
308                 if(optionSelected == 0)
309                 {
310                     std::cout << "Using IP."<< std::endl;
311                     connectivityType = CT_ADAPTER_IP;
312                 }
313                 else
314                 {
315                     std::cout << "Invalid connectivity type selected. Using default IP"
316                         << std::endl;
317                 }
318             }
319             else
320             {
321                 std::cout << "Invalid connectivity type selected. Using default IP" << std::endl;
322             }
323         }
324         catch(std::exception&)
325         {
326             std::cout << "Invalid input argument. Using IP as connectivity type" << std::endl;
327         }
328     }
329     else
330     {
331         printUsage();
332         std::cout << "Invalid input argument. Using IP as connectivity type" << std::endl;
333     }
334
335     // Create PlatformConfig object
336     PlatformConfig cfg {
337         OC::ServiceType::InProc,
338         OC::ModeType::Client,
339         "0.0.0.0",
340         0,
341         OC::QualityOfService::LowQos
342     };
343
344     OCPlatform::Configure(cfg);
345     try
346     {
347         // Find all resources
348         requestURI << OC_RSRVD_WELL_KNOWN_URI << "?rt=core.garage";
349
350         OCPlatform::findResource("", requestURI.str(),
351                 connectivityType, &foundResource);
352
353         std::cout<< "Finding Resource... " <<std::endl;
354
355         // A condition variable will free the mutex it is given, then do a non-
356         // intensive block until 'notify' is called on it.  In this case, since we
357         // don't ever call cv.notify, this should be a non-processor intensive version
358         // of while(true);
359         std::mutex blocker;
360         std::condition_variable cv;
361         std::unique_lock<std::mutex> lock(blocker);
362         cv.wait(lock);
363     }
364     catch(OCException& e)
365     {
366         std::cerr << "Exception in GarageClient: "<<e.what();
367     }
368
369     return 0;
370 }
371
372