Modifying version number for building on tizen 3.0
[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         std::cout<<"result:" <<
150             OCPlatform::findResource("", "coap://224.0.1.187/oc/core?rt=core.foo", f)
151             << std::endl;
152         std::cout<<"Finding Resource..."<<std::endl;
153
154         {
155             std::unique_lock<std::mutex> lk(m_mutex);
156             m_cv.wait(lk);
157         }
158     }
159 private:
160     std::mutex m_mutex;
161     std::mutex m_resourceLock;
162     std::condition_variable m_cv;
163     std::shared_ptr<OCResource> m_resource;
164 };
165
166 struct FooResource
167 {
168     bool m_isFoo;
169     int m_barCount;
170     OCResourceHandle m_resourceHandle;
171     OCRepresentation m_rep;
172
173     FooResource(): m_isFoo(true), m_barCount (0)
174     {
175         m_rep.setUri("/q/foo");
176         m_rep.setValue("isFoo", m_isFoo);
177         m_rep.setValue("barCount", m_barCount);
178     }
179
180     bool createResource()
181     {
182         std::string resourceURI = "/q/foo";
183         std::string resourceTypeName = "core.foo";
184         std::string resourceInterface = DEFAULT_INTERFACE;
185
186         uint8_t resourceProperty = OC_DISCOVERABLE;
187
188         EntityHandler eh(std::bind(&FooResource::entityHandler,
189                     this, std::placeholders::_1));
190         OCStackResult result = OCPlatform::registerResource(m_resourceHandle,
191                 resourceURI, resourceTypeName,
192                                     resourceInterface,
193                                     eh, resourceProperty);
194         if(OC_STACK_OK != result)
195         {
196             std::cout<<"Resource creation unsuccessful"<<std::endl;
197             return false;
198         }
199
200         return true;
201     }
202
203     OCRepresentation get()
204     {
205         m_rep.setValue("isFoo", m_isFoo);
206         m_rep.setValue("barCount", m_barCount);
207
208         return m_rep;
209     }
210
211     void put(OCRepresentation& rep)
212     {
213         rep.getValue("isFoo", m_isFoo);
214         rep.getValue("barCount", m_barCount);
215     }
216
217     OCStackResult sendResponse(std::shared_ptr<OCResourceRequest> pRequest)
218     {
219         auto pResponse = std::make_shared<OC::OCResourceResponse>();
220         pResponse->setRequestHandle(pRequest->getRequestHandle());
221         pResponse->setResourceHandle(pRequest->getResourceHandle());
222         pResponse->setResourceRepresentation(get(), "");
223         pResponse->setErrorCode(200);
224         pResponse->setResponseResult(OC_EH_OK);
225
226         return OCPlatform::sendResponse(pResponse);
227     }
228
229     OCEntityHandlerResult entityHandler(std::shared_ptr<OCResourceRequest> request)
230     {
231         std::cout<<"\tConsumer Entity Handler:"<<std::endl;
232         OCEntityHandlerResult ehResult = OC_EH_ERROR;
233
234         if(request)
235         {
236             // Note: Most of the handlers are not here, since this is for
237             // demoing client/server co-process existence.
238             // See simpleserver for a more complete example.
239             if(request->getRequestHandlerFlag()  == RequestHandlerFlag::RequestFlag)
240             {
241                 std::cout << "\t\trequestFlag : Request"<<std::endl;
242
243                 if(request->getRequestType() == "GET")
244                 {
245                     std::cout<<"\t\t\trequestType : GET"<<std::endl;
246                     if(OC_STACK_OK == sendResponse(request))
247                     {
248                         ehResult = OC_EH_OK;
249                     }
250                 }
251                 else if (request->getRequestType() == "PUT")
252                 {
253                     std::cout<<"\t\t\trequestType : PUT"<<std::endl;
254
255                     OCRepresentation rep = request->getResourceRepresentation();
256                     put(rep);
257                     if(OC_STACK_OK == sendResponse(request))
258                     {
259                         ehResult = OC_EH_OK;
260                     }
261                 }
262                 else
263                 {
264                     std::cout<<"\t\t\trequestType : UNSUPPORTED: "<<
265                             request->getRequestType()<<std::endl;
266                 }
267             }
268             else
269             {
270                 std::cout <<"\t\trequestFlag : UNSUPPORTED: ";
271
272                 if(request->getRequestHandlerFlag()==RequestHandlerFlag::InitFlag)
273                 {
274                     std::cout<<"InitFlag"<<std::endl;
275                 }
276                 else if(request->getRequestHandlerFlag()== RequestHandlerFlag::ObserverFlag)
277                 {
278                     std::cout<<"ObserverFlag"<<std::endl;
279                 }
280             }
281         }
282         else
283         {
284             std::cout << "Request Invalid!"<<std::endl;
285         }
286
287         return ehResult;
288     }
289
290 };
291
292 int main()
293 {
294     PlatformConfig cfg {
295         OC::ServiceType::InProc,
296         OC::ModeType::Both,
297         "0.0.0.0", // By setting to "0.0.0.0", it binds to all available interfaces
298         0,         // Uses randomly available port
299         OC::QualityOfService::LowQos
300     };
301
302     OCPlatform::Configure(cfg);
303     FooResource fooRes;
304
305     try
306     {
307
308         if(!fooRes.createResource())
309         {
310             return -1;
311         }
312
313         ClientWorker cw;
314         cw.start();
315     }
316     catch(OCException& e)
317     {
318         std::cout<< "Exception in main: "<<e.what()<<std::endl;
319     }
320
321     return 0;
322 }