Imported Upstream version 0.9.2
[platform/upstream/iotivity.git] / service / things-manager / sampleapp / linux / configuration / con-server.cpp
1 //******************************************************************
2 //
3 // Copyright 2014 Samsung Electronics 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 shows how one could create a resource (collection) with children.
23 ///
24
25 #include <functional>
26 #include <pthread.h>
27
28 #include "OCPlatform.h"
29 #include "OCApi.h"
30 #include "ThingsManager.h"
31 #include "ConfigurationCollection.h"
32 #include "DiagnosticsCollection.h"
33 #include "FactorySetCollection.h"
34
35 using namespace OC;
36 using namespace OIC;
37
38 const int SUCCESS_RESPONSE = 0;
39 int g_Steps = 0;
40 int isWaiting = 0;
41 pthread_mutex_t mutex_lock = PTHREAD_MUTEX_INITIALIZER;
42
43 // Default system configuration value's variables
44 // The variable's names should be same as the names of "extern" variables defined in
45 // "ConfigurationResource.h"
46 std::string defaultLocation;
47 std::string defaultRegion;
48 std::string defaultSystemTime;
49 std::string defaultCurrency;
50
51 static ThingsManager* g_thingsmanager;
52
53 // Forward declaring the entityHandler (Configuration)
54 bool prepareResponseForResource(std::shared_ptr< OCResourceRequest > request);
55 OCStackResult sendResponseForResource(std::shared_ptr< OCResourceRequest > pRequest);
56 OCEntityHandlerResult entityHandlerForResource(std::shared_ptr< OCResourceRequest > request);
57
58 ConfigurationResource *myConfigurationResource;
59 DiagnosticsResource *myDiagnosticsResource;
60 FactorySetResource *myFactorySetResource;
61
62 typedef std::function< void(OCRepresentation&) > putFunc;
63 typedef std::function< OCRepresentation(void) > getFunc;
64
65 getFunc getGetFunction(std::string uri)
66 {
67     getFunc res = NULL;
68
69     if (uri == myConfigurationResource->getUri())
70     {
71         res = std::bind(&ConfigurationResource::getConfigurationRepresentation,
72                 myConfigurationResource);
73     }
74     else if (uri == myDiagnosticsResource->getUri())
75     {
76         res = std::bind(&DiagnosticsResource::getDiagnosticsRepresentation,
77                 myDiagnosticsResource);
78     }
79
80     return res;
81 }
82
83 putFunc getPutFunction(std::string uri)
84 {
85     putFunc res = NULL;
86
87     if (uri == myConfigurationResource->getUri())
88     {
89         res = std::bind(&ConfigurationResource::setConfigurationRepresentation,
90                 myConfigurationResource, std::placeholders::_1);
91     }
92     else if (uri == myDiagnosticsResource->getUri())
93     {
94         res = std::bind(&DiagnosticsResource::setDiagnosticsRepresentation,
95                 myDiagnosticsResource, std::placeholders::_1);
96     }
97
98     return res;
99 }
100
101 // This function prepares a response for any incoming request to Light resource.
102 bool prepareResponseForResource(std::shared_ptr< OCResourceRequest > request)
103 {
104     std::cout << "\tIn Server CPP prepareResponseForResource:\n";
105     bool result = false;
106     if (request)
107     {
108         // Get the request type and request flag
109         std::string requestType = request->getRequestType();
110         int requestFlag = request->getRequestHandlerFlag();
111
112         if (requestFlag == RequestHandlerFlag::RequestFlag)
113         {
114             std::cout << "\t\trequestFlag : Request\n";
115
116             // If the request type is GET
117             if (requestType == "GET")
118             {
119                 std::cout << "\t\t\trequestType : GET\n";
120                 // GET operations are directly handled while sending the response
121                 // in the sendLightResponse function
122                 result = true;
123             }
124             else if (requestType == "PUT")
125             {
126                 std::cout << "\t\t\trequestType : PUT\n";
127                 putFunc putFunction;
128                 OCRepresentation rep = request->getResourceRepresentation();
129
130                 putFunction = getPutFunction(request->getResourceUri());
131
132                 // Do related operations related to PUT request
133                 putFunction(rep);
134                 result = true;
135             }
136             else if (requestType == "POST")
137             {
138                 // POST request operations
139             }
140             else if (requestType == "DELETE")
141             {
142                 // DELETE request operations
143             }
144         }
145         else if (requestFlag == RequestHandlerFlag::ObserverFlag)
146         {
147             std::cout << "\t\trequestFlag : Observer\n";
148         }
149     }
150     else
151     {
152         std::cout << "Request invalid" << std::endl;
153     }
154
155     return result;
156 }
157
158 OCStackResult sendResponseForResource(std::shared_ptr< OCResourceRequest > pRequest)
159 {
160     auto pResponse = std::make_shared< OC::OCResourceResponse >();
161
162     // Check for query params (if any)
163     QueryParamsMap queryParamsMap = pRequest->getQueryParameters();
164
165     pResponse->setRequestHandle(pRequest->getRequestHandle());
166     pResponse->setResourceHandle(pRequest->getResourceHandle());
167
168     getFunc getFunction;
169     getFunction = getGetFunction(pRequest->getResourceUri());
170
171     OCRepresentation rep;
172     rep = getFunction();
173
174     auto findRes = queryParamsMap.find("if");
175
176     if (findRes != queryParamsMap.end())
177     {
178         pResponse->setResourceRepresentation(rep, findRes->second);
179     }
180     else
181     {
182         pResponse->setResourceRepresentation(rep, DEFAULT_INTERFACE);
183     }
184
185     pResponse->setErrorCode(200);
186     pResponse->setResponseResult(OC_EH_OK);
187
188     return OCPlatform::sendResponse(pResponse);
189 }
190
191 OCEntityHandlerResult entityHandlerForResource(std::shared_ptr< OCResourceRequest > request)
192 {
193     std::cout << "\tIn Server CPP (entityHandlerForResource) entity handler:\n";
194     OCEntityHandlerResult ehResult = OC_EH_ERROR;
195
196     QueryParamsMap test = request->getQueryParameters();
197
198     if (prepareResponseForResource(request))
199     {
200         if (OC_STACK_OK == sendResponseForResource(request))
201         {
202             ehResult = OC_EH_OK;
203         }
204         else
205         {
206             std::cout << "sendResponse failed." << std::endl;
207         }
208     }
209     else
210     {
211         std::cout << "PrepareResponse failed." << std::endl;
212     }
213     return ehResult;
214 }
215
216 // callback handler on GET request
217 void onBootstrap(const HeaderOptions& headerOptions, const OCRepresentation& rep, const int eCode)
218 {
219     pthread_mutex_lock(&mutex_lock);
220     isWaiting = 0;
221     pthread_mutex_unlock(&mutex_lock);
222
223     if (eCode != SUCCESS_RESPONSE)
224     {
225         std::cout << "onGET Response error: " << eCode << std::endl;
226         return ;
227     }
228
229     std::cout << "\n\nGET request was successful" << std::endl;
230     std::cout << "\tResource URI: " << rep.getUri() << std::endl;
231
232     defaultRegion = rep.getValue< std::string >("r");
233     defaultSystemTime = rep.getValue< std::string >("st");
234     defaultCurrency = rep.getValue< std::string >("c");
235     defaultLocation = rep.getValue< std::string >("loc");
236
237     std::cout << "\tLocation : " << defaultLocation << std::endl;
238     std::cout << "\tSystemTime : " << defaultSystemTime << std::endl;
239     std::cout << "\tCurrency : " << defaultCurrency << std::endl;
240     std::cout << "\tRegion : " << defaultRegion << std::endl;
241
242 }
243
244 int main()
245 {
246     //**************************************************************
247     // STEP 0
248     // Create PlatformConfig object
249     PlatformConfig cfg
250     { OC::ServiceType::InProc, OC::ModeType::Both, "0.0.0.0", 0, OC::QualityOfService::LowQos };
251
252     OCPlatform::Configure(cfg);
253     g_thingsmanager = new ThingsManager();
254     //**************************************************************
255
256     if (getuid() != 0)
257     {
258         std::cout << "NOTE: You may gain the root privilege (e.g, reboot)\n";
259         std::cout << "NOTE: Now, you don't have it.\n";
260     }
261
262     try
263     {
264         // Perform app tasks
265         while (true)
266         {
267             pthread_mutex_lock(&mutex_lock);
268             if (isWaiting > 0)
269             {
270                 pthread_mutex_unlock(&mutex_lock);
271                 continue;
272             }
273
274             isWaiting = 0;
275             pthread_mutex_unlock(&mutex_lock);
276
277             std::cout << endl << endl << "(0) Quit" << std::endl;
278             std::cout << "(1) Bootstrap" << std::endl;
279             std::cout << "(2) Create Configuration Resources" << std::endl;
280
281             cin >> g_Steps;
282
283             if (g_Steps == 0)
284             {
285                 break;
286             }
287             else if (g_Steps == 1)
288             {
289                 if( g_thingsmanager->doBootstrap(&onBootstrap) == OC_STACK_OK)
290                 {
291                     pthread_mutex_lock(&mutex_lock);
292                     isWaiting = 1;
293                     pthread_mutex_unlock(&mutex_lock);
294                 }
295                 else
296                 {
297                     std::cout << "A callback pointer of the function is NULL." << std::endl;
298                 }
299             }
300             else if (g_Steps == 2)
301             {
302                 myConfigurationResource = new ConfigurationResource();
303                 myConfigurationResource->createResources(&entityHandlerForResource);
304
305                 myDiagnosticsResource = new DiagnosticsResource();
306                 myDiagnosticsResource->createResources(&entityHandlerForResource);
307
308
309                 myFactorySetResource = new FactorySetResource();
310                 myFactorySetResource->createResources(&entityHandlerForResource);
311                 myDiagnosticsResource->factoryReset = std::function < void()
312                         > (std::bind(&ConfigurationResource::factoryReset,
313                                 myConfigurationResource));
314
315                 pthread_mutex_lock(&mutex_lock);
316                 isWaiting = 1;
317                 pthread_mutex_unlock(&mutex_lock);
318             }
319         }
320     }
321     catch (OCException e)
322     {
323         std::cout << "Exception in main: " << e.what();
324     }
325
326     // No explicit call to stop the platform.
327     // When OCPlatform destructor is invoked, internally we do platform cleanup
328     return 0;
329 }
330