d7efa96a8c439ab37ff7800712b250d7d17fba65
[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     std::string platformDiscoveryURI = "/oic/p";
245     std::string deviceDiscoveryURI   = "/oic/d";
246
247     try
248     {
249         // Do some operations with resource object.
250         if(resource)
251         {
252             std::cout<<"DISCOVERED Resource:"<<std::endl;
253             // Get the resource URI
254             resourceURI = resource->uri();
255             std::cout << "\tURI of the resource: " << resourceURI << std::endl;
256
257             // Get the resource host address
258             hostAddress = resource->host();
259             std::cout << "\tHost address of the resource: " << hostAddress << std::endl;
260
261             // Get the resource types
262             std::cout << "\tList of resource types: " << std::endl;
263             for(auto &resourceTypes : resource->getResourceTypes())
264             {
265                 std::cout << "\t\t" << resourceTypes << std::endl;
266             }
267
268             // Get the resource interfaces
269             std::cout << "\tList of resource interfaces: " << std::endl;
270             for(auto &resourceInterfaces : resource->getResourceInterfaces())
271             {
272                 std::cout << "\t\t" << resourceInterfaces << std::endl;
273             }
274
275             OCStackResult ret;
276             std::cout << "Querying for platform information... " << std::endl;
277
278             ret = OCPlatform::getPlatformInfo("", platformDiscoveryURI, CT_ADAPTER_IP, NULL);
279
280             if (ret == OC_STACK_OK)
281             {
282                 std::cout << "Get platform information is done." << std::endl;
283             }
284             else
285             {
286                 std::cout << "Get platform information failed." << std::endl;
287             }
288
289             std::cout << "Querying for device information... " << std::endl;
290
291             ret = OCPlatform::getDeviceInfo(resource->host(), deviceDiscoveryURI, CT_ADAPTER_IP,
292                     NULL);
293
294             if (ret == OC_STACK_OK)
295             {
296                 std::cout << "Getting device information is done." << std::endl;
297             }
298             else
299             {
300                 std::cout << "Getting device information failed." << std::endl;
301             }
302   
303             if(resourceURI == "/a/garage")
304             {
305                 curResource = resource;
306                 // Call a local function which will internally invoke
307                 // get API on the resource pointer
308                 getLightRepresentation(resource);
309             }
310         }
311         else
312         {
313             // Resource is invalid
314             std::cout << "Resource is invalid" << std::endl;
315         }
316
317     }
318     catch(std::exception& e)
319     {
320         std::cerr << "Exception in foundResource: "<< e.what()<<std::endl;
321     }
322 }
323
324 int main(int argc, char* argv[]) {
325
326     std::ostringstream requestURI;
327
328     OCConnectivityType connectivityType = CT_ADAPTER_IP;
329
330     if(argc == 2)
331     {
332         try
333         {
334             std::size_t inputValLen;
335             int optionSelected = std::stoi(argv[1], &inputValLen);
336
337             if(inputValLen == strlen(argv[1]))
338             {
339                 if(optionSelected == 0)
340                 {
341                     std::cout << "Using IP."<< std::endl;
342                     connectivityType = CT_ADAPTER_IP;
343                 }
344                 else
345                 {
346                     std::cout << "Invalid connectivity type selected. Using default IP"
347                         << std::endl;
348                 }
349             }
350             else
351             {
352                 std::cout << "Invalid connectivity type selected. Using default IP" << std::endl;
353             }
354         }
355         catch(std::exception&)
356         {
357             std::cout << "Invalid input argument. Using IP as connectivity type" << std::endl;
358         }
359     }
360     else
361     {
362         printUsage();
363         std::cout << "Invalid input argument. Using IP as connectivity type" << std::endl;
364     }
365
366     // Create PlatformConfig object
367     PlatformConfig cfg {
368         OC::ServiceType::InProc,
369         OC::ModeType::Client,
370         "0.0.0.0",
371         0,
372         OC::QualityOfService::LowQos
373     };
374
375     OCPlatform::Configure(cfg);
376     try
377     {
378         // Find all resources
379         requestURI << OC_RSRVD_WELL_KNOWN_URI << "?rt=core.garage";
380
381         OCPlatform::findResource("", requestURI.str(),
382                 connectivityType, &foundResource);
383
384         std::cout<< "Finding Resource... " <<std::endl;
385
386         // A condition variable will free the mutex it is given, then do a non-
387         // intensive block until 'notify' is called on it.  In this case, since we
388         // don't ever call cv.notify, this should be a non-processor intensive version
389         // of while(true);
390         std::mutex blocker;
391         std::condition_variable cv;
392         std::unique_lock<std::mutex> lock(blocker);
393         cv.wait(lock);
394     }
395     catch(OCException& e)
396     {
397         std::cerr << "Exception in GarageClient: "<<e.what();
398     }
399
400     return 0;
401 }
402
403