Repo Merge: Moving resource API down a directory
[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
30 #include "OCPlatform.h"
31 #include "OCApi.h"
32
33 using namespace OC;
34 using namespace std;
35 namespace PH = std::placeholders;
36
37 int gObservation = 0;
38 void * ChangeLightRepresentation (void *param);
39
40 // Specifies where to notify all observers or list of observers
41 // 0 - notifies all observers
42 // 1 - notifies list of observers
43 int isListOfObservers = 0;
44
45 // Forward declaring the entityHandler
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         std::string resourceTypeName = "core.light"; // resource type name. In this case, it is light
83         std::string resourceInterface = DEFAULT_INTERFACE; // resource interface.
84
85         // OCResourceProperty is defined ocstack.h
86         uint8_t resourceProperty = OC_DISCOVERABLE | OC_OBSERVABLE;
87
88         EntityHandler cb = std::bind(&LightResource::entityHandler, this,PH::_1, PH::_2);
89
90         // This will internally create and register the resource.
91         OCStackResult result = OCPlatform::registerResource(
92                                     m_resourceHandle, resourceURI, resourceTypeName,
93                                     resourceInterface, cb, resourceProperty);
94
95         if (OC_STACK_OK != result)
96         {
97             cout << "Resource creation was unsuccessful\n";
98         }
99     }
100
101     OCStackResult createResource1()
102     {
103         std::string resourceURI = "/a/light1"; // URI of the resource
104         std::string resourceTypeName = "core.light"; // resource type name. In this case, it is light
105         std::string resourceInterface = DEFAULT_INTERFACE; // resource interface.
106
107         // OCResourceProperty is defined ocstack.h
108         uint8_t resourceProperty = OC_DISCOVERABLE | OC_OBSERVABLE;
109
110         EntityHandler cb = std::bind(&LightResource::entityHandler, this,PH::_1, PH::_2);
111
112         OCResourceHandle resHandle;
113
114         // This will internally create and register the resource.
115         OCStackResult result = OCPlatform::registerResource(
116                                     resHandle, resourceURI, resourceTypeName,
117                                     resourceInterface, cb, resourceProperty);
118
119         if (OC_STACK_OK != result)
120         {
121             cout << "Resource creation was unsuccessful\n";
122         }
123
124         return result;
125     }
126
127     OCResourceHandle getHandle()
128     {
129         return m_resourceHandle;
130     }
131
132     // Puts representation.
133     // Gets values from the representation and
134     // updates the internal state
135     void put(OCRepresentation& rep)
136     {
137         try {
138             if (rep.getValue("state", m_state))
139             {
140                 cout << "\t\t\t\t" << "state: " << m_state << endl;
141             }
142             else
143             {
144                 cout << "\t\t\t\t" << "state not found in the representation" << endl;
145             }
146
147             if (rep.getValue("power", m_power))
148             {
149                 cout << "\t\t\t\t" << "power: " << m_power << endl;
150             }
151             else
152             {
153                 cout << "\t\t\t\t" << "power not found in the representation" << endl;
154             }
155         }
156         catch (exception& e)
157         {
158             cout << e.what() << endl;
159         }
160
161     }
162
163     // Post representation.
164     // Post can create new resource or simply act like put.
165     // Gets values from the representation and
166     // updates the internal state
167     OCRepresentation post(OCRepresentation& rep)
168     {
169         static int first = 1;
170
171         std::cout << "In POST\n";
172
173         // for the first time it tries to create a resource
174         if(first)
175         {
176             std::cout << "In POST/First\n";
177
178             first = 0;
179
180             if(OC_STACK_OK == createResource1())
181             {
182                 std::cout << "Created a new resource\n";
183
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 // This is just a sample implementation of entity handler.
228 // Entity handler can be implemented in several ways by the manufacturer
229 OCEntityHandlerResult entityHandler(std::shared_ptr<OCResourceRequest> request, std::shared_ptr<OCResourceResponse> response)
230 {
231     cout << "\tIn Server CPP entity handler:\n";
232
233     if(request)
234     {
235         // Get the request type and request flag
236         std::string requestType = request->getRequestType();
237         int requestFlag = request->getRequestHandlerFlag();
238
239         if(requestFlag & RequestHandlerFlag::InitFlag)
240         {
241             cout << "\t\trequestFlag : Init\n";
242
243             // entity handler to perform resource initialization operations
244         }
245         if(requestFlag & RequestHandlerFlag::RequestFlag)
246         {
247             cout << "\t\trequestFlag : Request\n";
248
249             // If the request type is GET
250             if(requestType == "GET")
251             {
252                 cout << "\t\t\trequestType : GET\n";
253
254                 if(response)
255                 {
256                     // TODO Error Code
257                     response->setErrorCode(200);
258
259                     response->setResourceRepresentation(get());
260                 }
261             }
262             else if(requestType == "PUT")
263             {
264                 cout << "\t\t\trequestType : PUT\n";
265
266                 OCRepresentation rep = request->getResourceRepresentation();
267
268                 // Do related operations related to PUT request
269
270                 // Update the lightResource
271                 put(rep);
272
273                 if(response)
274                 {
275                     // TODO Error Code
276                     response->setErrorCode(200);
277
278                     response->setResourceRepresentation(get());
279                 }
280
281             }
282             else if(requestType == "POST")
283             {
284                 cout << "\t\t\trequestType : POST\n";
285
286                 OCRepresentation rep = request->getResourceRepresentation();
287
288                 // Do related operations related to POST request
289
290                 OCRepresentation rep_post = post(rep);
291
292                 if(response)
293                 {
294                     // TODO Error Code
295                     response->setErrorCode(200);
296
297                     response->setResourceRepresentation(rep_post);
298                 }
299
300                 // POST request operations
301             }
302             else if(requestType == "DELETE")
303             {
304                 // DELETE request operations
305             }
306         }
307
308         if(requestFlag & RequestHandlerFlag::ObserverFlag)
309         {
310             ObservationInfo observationInfo = request->getObservationInfo();
311             if(ObserveAction::ObserveRegister == observationInfo.action)
312             {
313                 m_interestedObservers.push_back(observationInfo.obsId);
314             }
315             else if(ObserveAction::ObserveUnregister == observationInfo.action)
316             {
317                 m_interestedObservers.erase(std::remove(
318                                                             m_interestedObservers.begin(),
319                                                             m_interestedObservers.end(),
320                                                             observationInfo.obsId),
321                                                             m_interestedObservers.end());
322             }
323
324             pthread_t threadId;
325
326             cout << "\t\trequestFlag : Observer\n";
327             gObservation = 1;
328             static int startedThread = 0;
329
330             // Observation happens on a different thread in ChangeLightRepresentation function.
331             // If we have not created the thread already, we will create one here.
332             if(!startedThread)
333             {
334                 pthread_create (&threadId, NULL, ChangeLightRepresentation, (void *)this);
335                 startedThread = 1;
336             }
337         }
338     }
339     else
340     {
341         std::cout << "Request invalid" << std::endl;
342     }
343
344     return OC_EH_OK;
345 }
346
347 };
348
349 // ChangeLightRepresentaion is an observation function,
350 // which notifies any changes to the resource to stack
351 // via notifyObservers
352 void * ChangeLightRepresentation (void *param)
353 {
354     LightResource* lightPtr = (LightResource*) param;
355
356     // This function continuously monitors for the changes
357     while (1)
358     {
359         sleep (5);
360
361         if (gObservation)
362         {
363             // If under observation if there are any changes to the light resource
364             // we call notifyObservors
365             //
366             // For demostration we are changing the power value and notifying.
367             lightPtr->m_power += 10;
368
369             cout << "\nPower updated to : " << lightPtr->m_power << endl;
370             cout << "Notifying observers with resource handle: " << lightPtr->getHandle() << endl;
371
372             OCStackResult result = OC_STACK_OK;
373
374             if(isListOfObservers)
375             {
376                 std::shared_ptr<OCResourceResponse> resourceResponse(new OCResourceResponse());
377
378                 resourceResponse->setErrorCode(200);
379                 resourceResponse->setResourceRepresentation(lightPtr->get(), DEFAULT_INTERFACE);
380
381                 result = OCPlatform::notifyListOfObservers(
382                                                             lightPtr->getHandle(),
383                                                             lightPtr->m_interestedObservers,
384                                                             resourceResponse,
385                                                             OC::QualityOfService::HighQos);
386             }
387             else
388             {
389                 result = OCPlatform::notifyAllObservers(lightPtr->getHandle(),
390                                                             OC::QualityOfService::HighQos);
391             }
392
393             if(OC_STACK_NO_OBSERVERS == result)
394             {
395                 cout << "No More observers, stopping notifications" << endl;
396                 gObservation = 0;
397             }
398         }
399     }
400
401     return NULL;
402 }
403
404 void PrintUsage()
405 {
406     std::cout << std::endl;
407     std::cout << "Usage : simplserver <isListOfObservers>\n";
408     std::cout << "   ObserveType : 0 - Observe All\n";
409     std::cout << "   ObserveType : 1 - Observe List of observers\n\n";
410 }
411
412
413 int main(int argc, char* argv[1])
414 {
415     PrintUsage();
416
417     if (argc == 1)
418     {
419         isListOfObservers = 0;
420     }
421     else if (argc == 2)
422     {
423         int value = atoi(argv[1]);
424         if (value == 1)
425             isListOfObservers = 1;
426         else
427             isListOfObservers = 0;
428     }
429     else
430     {
431         return -1;
432     }
433
434     // Create PlatformConfig object
435     PlatformConfig cfg {
436         OC::ServiceType::InProc,
437         OC::ModeType::Server,
438         "0.0.0.0", // By setting to "0.0.0.0", it binds to all available interfaces
439         0,         // Uses randomly available port
440         OC::QualityOfService::LowQos
441     };
442
443     OCPlatform::Configure(cfg);
444
445     try
446     {
447         // Create the instance of the resource class (in this case instance of class 'LightResource').
448         LightResource myLight(cfg);
449
450         // Invoke createResource function of class light.
451         myLight.createResource();
452
453         myLight.addType(std::string("core.brightlight"));
454         myLight.addInterface(std::string("oc.mi.ll"));
455         // Perform app tasks
456         while(true)
457         {
458             // some tasks
459         }
460     }
461     catch(OCException e)
462     {
463         //log(e.what());
464     }
465
466     // No explicit call to stop the platform.
467     // When OCPlatform destructor is invoked, internally we do platform cleanup
468 }