Merge "Soft Sensor Manager Build Error fix" into connectivity-abstraction
[platform/upstream/iotivity.git] / resource / examples / simpleclientserver.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 ///
22 /// This sample provides steps to define an interface for a resource
23 /// (properties and methods) and host this resource on the server.
24 /// Additionally, it'll have a client example to discover it as well.
25 ///
26 #include <memory>
27 #include <iostream>
28 #include <stdexcept>
29 #include <condition_variable>
30 #include <map>
31 #include <vector>
32 #include "OCPlatform.h"
33 #include "OCApi.h"
34 using namespace OC;
35
36 class ClientWorker
37 {
38 private:
39     bool m_isFoo;
40     int m_barCount;
41     void putResourceInfo(const HeaderOptions& headerOptions,
42             const OCRepresentation rep, const OCRepresentation rep2, const int eCode)
43     {
44        std::cout << "In PutResourceInfo" << std::endl;
45
46        std::cout <<"Clientside Put response to get was: "<<std::endl;
47        std::cout <<"ErrorCode: "<<eCode <<std::endl;
48
49        if(eCode == 0)
50        {
51             std::cout<<"Successful Put.  Attributes sent were: "<<std::endl;
52
53             rep.getValue("isFoo", m_isFoo);
54             rep.getValue("barCount", m_barCount);
55
56             std::cout << "\tisFoo: "<< m_isFoo << std::endl;
57             std::cout << "\tbarCount: "<< m_barCount << std::endl;
58
59             std::cout<<"Actual New values are: "<<std::endl;
60
61             rep.getValue("isFoo", m_isFoo);
62             rep.getValue("barCount", m_barCount);
63
64             std::cout << "\tisFoo: "<< m_isFoo << std::endl;
65             std::cout << "\tbarCount: "<< m_barCount << std::endl;
66
67             m_cv.notify_all();
68        }
69     }
70
71     void getResourceInfo(const HeaderOptions& headerOptions, const OCRepresentation rep,
72                 const int eCode)
73     {
74         std::cout << "In getResourceInfo" << std::endl;
75
76         std::cout<<"Clientside response to get was: "<<std::endl;
77         std::cout<<"Error Code: "<<eCode<<std::endl;
78
79         if(eCode == 0)
80         {
81             std::cout <<"Successful Get.  Attributes are: "<<std::endl;
82
83             rep.getValue("isFoo", m_isFoo);
84             rep.getValue("barCount", m_barCount);
85
86             std::cout << "\tisFoo: "<< m_isFoo << std::endl;
87             std::cout << "\tbarCount: "<< m_barCount << std::endl;
88
89             std::cout << "Doing a put on q/foo" <<std::endl;
90             OCRepresentation rep2(rep);
91             m_isFoo = false;
92             m_barCount = 211;
93
94             rep2.setValue("isFoo", m_isFoo);
95             rep2.setValue("barCount", m_barCount);
96
97             m_resource->put(rep2, QueryParamsMap(),
98                 PutCallback(std::bind(&ClientWorker::putResourceInfo, this, std::placeholders::_1,
99                      rep2, std::placeholders::_2, std::placeholders::_3)));
100         }
101     }
102
103     void foundResource(std::shared_ptr<OCResource> resource)
104     {
105         std::cout << "In foundResource" << std::endl;
106         if(resource && resource->uri() == "/q/foo")
107         {
108             {
109                 std::lock_guard<std::mutex> lock(m_resourceLock);
110                 if(m_resource)
111                 {
112                     return;
113                 }
114
115                 m_resource = resource;
116             }
117
118             std::cout << "Found Resource: "<<std::endl;
119             std::cout << "\tHost: "<< resource->host()<<std::endl;
120             std::cout << "\tURI:  "<< resource->uri()<<std::endl;
121
122             // Get the resource types
123             std::cout << "\tList of resource types: " << std::endl;
124             for(auto &resourceTypes : resource->getResourceTypes())
125             {
126                 std::cout << "\t\t" << resourceTypes << std::endl;
127             }
128
129             // Get the resource interfaces
130             std::cout << "\tList of resource interfaces: " << std::endl;
131             for(auto &resourceInterfaces : resource->getResourceInterfaces())
132             {
133                 std::cout << "\t\t" << resourceInterfaces << std::endl;
134             }
135
136             std::cout<<"Doing a get on q/foo."<<std::endl;
137
138             resource->get(QueryParamsMap(),
139                 GetCallback(std::bind(&ClientWorker::getResourceInfo, this,
140                 std::placeholders::_1, std::placeholders::_2, std::placeholders::_3)));
141         }
142     }
143
144 public:
145     void start()
146     {
147         std::cout<<"Starting Client find:"<<std::endl;
148         FindCallback f (std::bind(&ClientWorker::foundResource, this, std::placeholders::_1));
149 #ifdef CA_INT
150         OCConnectivityType connectivityType = OC_WIFI;
151         std::cout<<"result:" <<
152         OCPlatform::findResource("", "coap://224.0.1.187/oc/core?rt=core.foo", connectivityType, f)
153         << std::endl;
154 #else
155         std::cout<<"result:" <<
156         OCPlatform::findResource("", "coap://224.0.1.187/oc/core?rt=core.foo", f)
157         << std::endl;
158 #endif
159
160         std::cout<<"Finding Resource..."<<std::endl;
161
162         {
163             std::unique_lock<std::mutex> lk(m_mutex);
164             m_cv.wait(lk);
165         }
166     }
167 private:
168     std::mutex m_mutex;
169     std::mutex m_resourceLock;
170     std::condition_variable m_cv;
171     std::shared_ptr<OCResource> m_resource;
172 };
173
174 struct FooResource
175 {
176     bool m_isFoo;
177     int m_barCount;
178     OCResourceHandle m_resourceHandle;
179     OCRepresentation m_rep;
180
181     FooResource(): m_isFoo(true), m_barCount (0)
182     {
183         m_rep.setUri("/q/foo");
184         m_rep.setValue("isFoo", m_isFoo);
185         m_rep.setValue("barCount", m_barCount);
186     }
187
188     bool createResource()
189     {
190         std::string resourceURI = "/q/foo";
191         std::string resourceTypeName = "core.foo";
192         std::string resourceInterface = DEFAULT_INTERFACE;
193
194         uint8_t resourceProperty = OC_DISCOVERABLE;
195
196         EntityHandler eh(std::bind(&FooResource::entityHandler,
197                     this, std::placeholders::_1));
198         OCStackResult result = OCPlatform::registerResource(m_resourceHandle,
199                 resourceURI, resourceTypeName,
200                                     resourceInterface,
201                                     eh, resourceProperty);
202         if(OC_STACK_OK != result)
203         {
204             std::cout<<"Resource creation unsuccessful"<<std::endl;
205             return false;
206         }
207
208         return true;
209     }
210
211     OCRepresentation get()
212     {
213         m_rep.setValue("isFoo", m_isFoo);
214         m_rep.setValue("barCount", m_barCount);
215
216         return m_rep;
217     }
218
219     void put(OCRepresentation& rep)
220     {
221         rep.getValue("isFoo", m_isFoo);
222         rep.getValue("barCount", m_barCount);
223     }
224
225     OCStackResult sendResponse(std::shared_ptr<OCResourceRequest> pRequest)
226     {
227         auto pResponse = std::make_shared<OC::OCResourceResponse>();
228         pResponse->setRequestHandle(pRequest->getRequestHandle());
229         pResponse->setResourceHandle(pRequest->getResourceHandle());
230         pResponse->setResourceRepresentation(get(), "");
231         pResponse->setErrorCode(200);
232         pResponse->setResponseResult(OC_EH_OK);
233
234         return OCPlatform::sendResponse(pResponse);
235     }
236
237     OCEntityHandlerResult entityHandler(std::shared_ptr<OCResourceRequest> request)
238     {
239         std::cout<<"\tConsumer Entity Handler:"<<std::endl;
240         OCEntityHandlerResult ehResult = OC_EH_ERROR;
241
242         if(request)
243         {
244             // Note: Most of the handlers are not here, since this is for
245             // demoing client/server co-process existence.
246             // See simpleserver for a more complete example.
247             if(request->getRequestHandlerFlag()  == RequestHandlerFlag::RequestFlag)
248             {
249                 std::cout << "\t\trequestFlag : Request"<<std::endl;
250
251                 if(request->getRequestType() == "GET")
252                 {
253                     std::cout<<"\t\t\trequestType : GET"<<std::endl;
254                     if(OC_STACK_OK == sendResponse(request))
255                     {
256                         ehResult = OC_EH_OK;
257                     }
258                 }
259                 else if (request->getRequestType() == "PUT")
260                 {
261                     std::cout<<"\t\t\trequestType : PUT"<<std::endl;
262
263                     OCRepresentation rep = request->getResourceRepresentation();
264                     put(rep);
265                     if(OC_STACK_OK == sendResponse(request))
266                     {
267                         ehResult = OC_EH_OK;
268                     }
269                 }
270                 else
271                 {
272                     std::cout<<"\t\t\trequestType : UNSUPPORTED: "<<
273                             request->getRequestType()<<std::endl;
274                 }
275             }
276             else
277             {
278                 std::cout <<"\t\trequestFlag : UNSUPPORTED: ";
279
280                 if(request->getRequestHandlerFlag()==RequestHandlerFlag::InitFlag)
281                 {
282                     std::cout<<"InitFlag"<<std::endl;
283                 }
284                 else if(request->getRequestHandlerFlag()== RequestHandlerFlag::ObserverFlag)
285                 {
286                     std::cout<<"ObserverFlag"<<std::endl;
287                 }
288             }
289         }
290         else
291         {
292             std::cout << "Request Invalid!"<<std::endl;
293         }
294
295         return ehResult;
296     }
297
298 };
299
300 int main()
301 {
302     PlatformConfig cfg {
303         OC::ServiceType::InProc,
304         OC::ModeType::Both,
305         "0.0.0.0", // By setting to "0.0.0.0", it binds to all available interfaces
306         0,         // Uses randomly available port
307         OC::QualityOfService::LowQos
308     };
309
310     OCPlatform::Configure(cfg);
311     FooResource fooRes;
312
313     try
314     {
315
316         if(!fooRes.createResource())
317         {
318             return -1;
319         }
320
321         ClientWorker cw;
322         cw.start();
323     }
324     catch(OCException& e)
325     {
326         std::cout<< "Exception in main: "<<e.what()<<std::endl;
327     }
328
329     return 0;
330 }