Changeset for reviewing RI-CA integration changes.
[platform/upstream/iotivity.git] / resource / examples / simpleserverHQ.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 ///
25
26 #include <functional>
27
28 #include <pthread.h>
29 #include <mutex>
30 #include <condition_variable>
31
32 #include "OCPlatform.h"
33 #include "OCApi.h"
34
35 using namespace OC;
36 using namespace std;
37 namespace PH = std::placeholders;
38
39 int gObservation = 0;
40 void * ChangeLightRepresentation (void *param);
41
42 // Specifies where to notify all observers or list of observers
43 // 0 - notifies all observers
44 // 1 - notifies list of observers
45 int isListOfObservers = 0;
46
47 /// This class represents a single resource named 'lightResource'. This resource has
48 /// two simple properties named 'state' and 'power'
49
50 class LightResource
51 {
52
53 public:
54     /// Access this property from a TB client
55     std::string m_name;
56     bool m_state;
57     int m_power;
58     std::string m_lightUri;
59     OCResourceHandle m_resourceHandle;
60     OCRepresentation m_lightRep;
61     ObservationIds m_interestedObservers;
62
63 public:
64     /// Constructor
65     LightResource(PlatformConfig& cfg)
66         :m_name("John's light"), m_state(false), m_power(0), m_lightUri("/a/light") {
67         // Initialize representation
68         m_lightRep.setUri(m_lightUri);
69
70         m_lightRep.setValue("state", m_state);
71         m_lightRep.setValue("power", m_power);
72         m_lightRep.setValue("name", m_name);
73     }
74
75     /* Note that this does not need to be a member function: for classes you do not have
76     access to, you can accomplish this with a free function: */
77
78     /// This function internally calls registerResource API.
79     void createResource()
80     {
81         std::string resourceURI = m_lightUri; // URI of the resource
82         // resource type name. In this case, it is light
83         std::string resourceTypeName = "core.light";
84         std::string resourceInterface = DEFAULT_INTERFACE; // resource interface.
85
86         // OCResourceProperty is defined ocstack.h
87         uint8_t resourceProperty = OC_DISCOVERABLE | OC_OBSERVABLE;
88
89         EntityHandler cb = std::bind(&LightResource::entityHandler, this,PH::_1);
90
91         // This will internally create and register the resource.
92         OCStackResult result = OCPlatform::registerResource(
93                                     m_resourceHandle, resourceURI, resourceTypeName,
94                                     resourceInterface, cb, resourceProperty);
95
96         if (OC_STACK_OK != result)
97         {
98             cout << "Resource creation was unsuccessful\n";
99         }
100     }
101
102     OCStackResult createResource1()
103     {
104         std::string resourceURI = "/a/light1"; // URI of the resource
105         std::string resourceTypeName = "core.light"; // resource type name. In this case, it is light
106         std::string resourceInterface = DEFAULT_INTERFACE; // resource interface.
107
108         // OCResourceProperty is defined ocstack.h
109         uint8_t resourceProperty = OC_DISCOVERABLE | OC_OBSERVABLE;
110
111         EntityHandler cb = std::bind(&LightResource::entityHandler, this,PH::_1);
112
113         OCResourceHandle resHandle;
114
115         // This will internally create and register the resource.
116         OCStackResult result = OCPlatform::registerResource(
117                                     resHandle, resourceURI, resourceTypeName,
118                                     resourceInterface, cb, resourceProperty);
119
120         if (OC_STACK_OK != result)
121         {
122             cout << "Resource creation was unsuccessful\n";
123         }
124
125         return result;
126     }
127
128     OCResourceHandle getHandle()
129     {
130         return m_resourceHandle;
131     }
132
133     // Puts representation.
134     // Gets values from the representation and
135     // updates the internal state
136     void put(OCRepresentation& rep)
137     {
138         try {
139             if (rep.getValue("state", m_state))
140             {
141                 cout << "\t\t\t\t" << "state: " << m_state << endl;
142             }
143             else
144             {
145                 cout << "\t\t\t\t" << "state not found in the representation" << endl;
146             }
147
148             if (rep.getValue("power", m_power))
149             {
150                 cout << "\t\t\t\t" << "power: " << m_power << endl;
151             }
152             else
153             {
154                 cout << "\t\t\t\t" << "power not found in the representation" << endl;
155             }
156         }
157         catch (exception& e)
158         {
159             cout << e.what() << endl;
160         }
161
162     }
163
164     // Post representation.
165     // Post can create new resource or simply act like put.
166     // Gets values from the representation and
167     // updates the internal state
168     OCRepresentation post(OCRepresentation& rep)
169     {
170         static int first = 1;
171
172         std::cout << "In POST\n";
173
174         // for the first time it tries to create a resource
175         if(first)
176         {
177             std::cout << "In POST/First\n";
178
179             first = 0;
180
181             if(OC_STACK_OK == createResource1())
182             {
183                 std::cout << "Created a new resource\n";
184                 OCRepresentation rep1;
185                 rep1.setValue("createduri", std::string("/a/light1"));
186
187                 return rep1;
188             }
189         }
190
191         // from second time onwards it just puts
192         put(rep);
193         return get();
194     }
195
196
197     // gets the updated representation.
198     // Updates the representation with latest internal state before
199     // sending out.
200     OCRepresentation get()
201     {
202         m_lightRep.setValue("state", m_state);
203         m_lightRep.setValue("power", m_power);
204
205         return m_lightRep;
206     }
207
208     void addType(const std::string& type) const
209     {
210         OCStackResult result = OCPlatform::bindTypeToResource(m_resourceHandle, type);
211         if (OC_STACK_OK != result)
212         {
213             cout << "Binding TypeName to Resource was unsuccessful\n";
214         }
215     }
216
217     void addInterface(const std::string& interface) const
218     {
219         OCStackResult result = OCPlatform::bindInterfaceToResource(m_resourceHandle, interface);
220         if (OC_STACK_OK != result)
221         {
222             cout << "Binding TypeName to Resource was unsuccessful\n";
223         }
224     }
225
226 private:
227
228 OCStackResult sendResponse(std::shared_ptr<OCResourceRequest> pRequest)
229 {
230     auto pResponse = std::make_shared<OC::OCResourceResponse>();
231     pResponse->setRequestHandle(pRequest->getRequestHandle());
232     pResponse->setResourceHandle(pRequest->getResourceHandle());
233     pResponse->setResourceRepresentation(get());
234     pResponse->setErrorCode(200);
235     pResponse->setResponseResult(OC_EH_OK);
236
237     return OCPlatform::sendResponse(pResponse);
238 }
239
240 OCStackResult sendPostResponse(std::shared_ptr<OCResourceRequest> pRequest)
241 {
242     auto pResponse = std::make_shared<OC::OCResourceResponse>();
243     pResponse->setRequestHandle(pRequest->getRequestHandle());
244     pResponse->setResourceHandle(pRequest->getResourceHandle());
245
246     OCRepresentation rep = pRequest->getResourceRepresentation();
247     OCRepresentation rep_post = post(rep);
248
249     pResponse->setResourceRepresentation(rep_post);
250     pResponse->setErrorCode(200);
251     pResponse->setResponseResult(OC_EH_OK);
252
253     return OCPlatform::sendResponse(pResponse);
254 }
255
256 // This is just a sample implementation of entity handler.
257 // Entity handler can be implemented in several ways by the manufacturer
258 OCEntityHandlerResult entityHandler(std::shared_ptr<OCResourceRequest> request)
259 {
260     cout << "\tIn Server CPP entity handler:\n";
261     OCEntityHandlerResult ehResult = OC_EH_ERROR;
262
263     if(request)
264     {
265         // Get the request type and request flag
266         std::string requestType = request->getRequestType();
267         int requestFlag = request->getRequestHandlerFlag();
268
269         if(requestFlag & RequestHandlerFlag::InitFlag)
270         {
271             cout << "\t\trequestFlag : Init\n";
272             // entity handler to perform resource initialization operations
273         }
274         if(requestFlag & RequestHandlerFlag::RequestFlag)
275         {
276             cout << "\t\trequestFlag : Request\n";
277
278             // If the request type is GET
279             if(requestType == "GET")
280             {
281                 cout << "\t\t\trequestType : GET\n";
282                 if(OC_STACK_OK == sendResponse(request))
283                 {
284                     ehResult = OC_EH_OK;
285                 }
286             }
287             else if(requestType == "PUT")
288             {
289                 cout << "\t\t\trequestType : PUT\n";
290
291                 OCRepresentation rep = request->getResourceRepresentation();
292                 // Do related operations related to PUT request
293                 // Update the lightResource
294                 put(rep);
295                 if(OC_STACK_OK == sendResponse(request))
296                 {
297                     ehResult = OC_EH_OK;
298                 }
299             }
300             else if(requestType == "POST")
301             {
302                 cout << "\t\t\trequestType : POST\n";
303                 if(OC_STACK_OK == sendPostResponse(request))
304                 {
305                     ehResult = OC_EH_OK;
306                 }
307             }
308             else if(requestType == "DELETE")
309             {
310                 // DELETE request operations
311             }
312         }
313
314         if(requestFlag & RequestHandlerFlag::ObserverFlag)
315         {
316             ObservationInfo observationInfo = request->getObservationInfo();
317             if(ObserveAction::ObserveRegister == observationInfo.action)
318             {
319                 m_interestedObservers.push_back(observationInfo.obsId);
320             }
321             else if(ObserveAction::ObserveUnregister == observationInfo.action)
322             {
323                 m_interestedObservers.erase(std::remove(
324                                                             m_interestedObservers.begin(),
325                                                             m_interestedObservers.end(),
326                                                             observationInfo.obsId),
327                                                             m_interestedObservers.end());
328             }
329
330             pthread_t threadId;
331
332             cout << "\t\trequestFlag : Observer\n";
333             gObservation = 1;
334             static int startedThread = 0;
335
336             // Observation happens on a different thread in ChangeLightRepresentation function.
337             // If we have not created the thread already, we will create one here.
338             if(!startedThread)
339             {
340                 pthread_create (&threadId, NULL, ChangeLightRepresentation, (void *)this);
341                 startedThread = 1;
342             }
343             ehResult = OC_EH_OK;
344         }
345     }
346     else
347     {
348         std::cout << "Request invalid" << std::endl;
349     }
350
351     return ehResult;
352 }
353
354 };
355
356 // ChangeLightRepresentaion is an observation function,
357 // which notifies any changes to the resource to stack
358 // via notifyObservers
359 void * ChangeLightRepresentation (void *param)
360 {
361     LightResource* lightPtr = (LightResource*) param;
362
363     // This function continuously monitors for the changes
364     while (1)
365     {
366         sleep (5);
367
368         if (gObservation)
369         {
370             // If under observation if there are any changes to the light resource
371             // we call notifyObservors
372             //
373             // For demostration we are changing the power value and notifying.
374             lightPtr->m_power += 10;
375
376             cout << "\nPower updated to : " << lightPtr->m_power << endl;
377             cout << "Notifying observers with resource handle: " << lightPtr->getHandle() << endl;
378
379             OCStackResult result = OC_STACK_OK;
380
381             if(isListOfObservers)
382             {
383                 std::shared_ptr<OCResourceResponse> resourceResponse(new OCResourceResponse());
384
385                 resourceResponse->setErrorCode(200);
386                 resourceResponse->setResourceRepresentation(lightPtr->get(), DEFAULT_INTERFACE);
387
388                 result = OCPlatform::notifyListOfObservers(
389                                                             lightPtr->getHandle(),
390                                                             lightPtr->m_interestedObservers,
391                                                             resourceResponse,
392                                                             OC::QualityOfService::HighQos);
393             }
394             else
395             {
396                 result = OCPlatform::notifyAllObservers(lightPtr->getHandle(),
397                                                             OC::QualityOfService::HighQos);
398             }
399
400             if(OC_STACK_NO_OBSERVERS == result)
401             {
402                 cout << "No More observers, stopping notifications" << endl;
403                 gObservation = 0;
404             }
405         }
406     }
407
408     return NULL;
409 }
410
411 void PrintUsage()
412 {
413     std::cout << std::endl;
414     std::cout << "Usage : simpleserver <isListOfObservers>\n";
415     std::cout << "   ObserveType : 0 - Observe All\n";
416     std::cout << "   ObserveType : 1 - Observe List of observers\n\n";
417 }
418
419
420 int main(int argc, char* argv[])
421 {
422     PrintUsage();
423
424     if (argc == 1)
425     {
426         isListOfObservers = 0;
427     }
428     else if (argc == 2)
429     {
430         int value = atoi(argv[1]);
431         if (value == 1)
432             isListOfObservers = 1;
433         else
434             isListOfObservers = 0;
435     }
436     else
437     {
438         return -1;
439     }
440
441     // Create PlatformConfig object
442     PlatformConfig cfg {
443         OC::ServiceType::InProc,
444         OC::ModeType::Server,
445         "0.0.0.0", // By setting to "0.0.0.0", it binds to all available interfaces
446         0,         // Uses randomly available port
447         OC::QualityOfService::LowQos
448     };
449
450     OCPlatform::Configure(cfg);
451
452     try
453     {
454         // Create the instance of the resource class
455         // (in this case instance of class 'LightResource').
456         LightResource myLight(cfg);
457
458         // Invoke createResource function of class light.
459         myLight.createResource();
460
461         myLight.addType(std::string("core.brightlight"));
462         myLight.addInterface(std::string("oc.mi.ll"));
463
464         // A condition variable will free the mutex it is given, then do a non-
465         // intensive block until 'notify' is called on it.  In this case, since we
466         // don't ever call cv.notify, this should be a non-processor intensive version
467         // of while(true);
468         std::mutex blocker;
469         std::condition_variable cv;
470         std::unique_lock<std::mutex> lock(blocker);
471         cv.wait(lock, []{return false;});
472     }
473     catch(OCException& e)
474     {
475         oclog() << "Exception in main: "<< e.what();
476     }
477
478     // No explicit call to stop the platform.
479     // When OCPlatform destructor is invoked, internally we do platform cleanup
480
481     return 0;
482 }
483