Updated Makefiles and CMakeLists.txt to point to resource, not oic-resource
[platform/upstream/iotivity.git] / examples / simpleserver.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()
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         // for the first time it tries to create a resource
172         if(first)
173         {
174             first = 0;
175
176             if(OC_STACK_OK == createResource1())
177             {
178                 OCRepresentation rep1;
179                 rep1.setValue("createduri", std::string("/a/light1"));
180
181                 return rep1;
182             }
183         }
184
185         // from second time onwards it just puts
186         put(rep);
187         return get();
188     }
189
190
191     // gets the updated representation.
192     // Updates the representation with latest internal state before
193     // sending out.
194     OCRepresentation get()
195     {
196         m_lightRep.setValue("state", m_state);
197         m_lightRep.setValue("power", m_power);
198
199         return m_lightRep;
200     }
201
202     void addType(const std::string& type) const
203     {
204         OCStackResult result = OCPlatform::bindTypeToResource(m_resourceHandle, type);
205         if (OC_STACK_OK != result)
206         {
207             cout << "Binding TypeName to Resource was unsuccessful\n";
208         }
209     }
210
211     void addInterface(const std::string& interface) const
212     {
213         OCStackResult result = OCPlatform::bindInterfaceToResource(m_resourceHandle, interface);
214         if (OC_STACK_OK != result)
215         {
216             cout << "Binding TypeName to Resource was unsuccessful\n";
217         }
218     }
219
220 private:
221 // This is just a sample implementation of entity handler.
222 // Entity handler can be implemented in several ways by the manufacturer
223 OCEntityHandlerResult entityHandler(std::shared_ptr<OCResourceRequest> request,
224                                     std::shared_ptr<OCResourceResponse> response)
225 {
226     OCEntityHandlerResult result = OC_EH_OK;
227
228     cout << "\tIn Server CPP entity handler:\n";
229
230     if(request)
231     {
232         // Get the request type and request flag
233         std::string requestType = request->getRequestType();
234         int requestFlag = request->getRequestHandlerFlag();
235
236         if(requestFlag & RequestHandlerFlag::InitFlag)
237         {
238             cout << "\t\trequestFlag : Init\n";
239
240             // entity handler to perform resource initialization operations
241         }
242         if(requestFlag & RequestHandlerFlag::RequestFlag)
243         {
244             cout << "\t\trequestFlag : Request\n";
245
246             // If the request type is GET
247             if(requestType == "GET")
248             {
249                 cout << "\t\t\trequestType : GET\n";
250
251                 if(response)
252                 {
253                     // TODO Error Code
254                     response->setErrorCode(200);
255
256                     response->setResourceRepresentation(get());
257                 }
258             }
259             else if(requestType == "PUT")
260             {
261                 cout << "\t\t\trequestType : PUT\n";
262
263                 OCRepresentation rep = request->getResourceRepresentation();
264
265                 // Do related operations related to PUT request
266
267                 // Update the lightResource
268                 put(rep);
269
270                 if(response)
271                 {
272                     // TODO Error Code
273                     response->setErrorCode(200);
274
275                     response->setResourceRepresentation(get());
276                 }
277
278             }
279             else if(requestType == "POST")
280             {
281                 cout << "\t\t\trequestType : POST\n";
282
283                 OCRepresentation rep = request->getResourceRepresentation();
284
285                 // Do related operations related to POST request
286
287                 OCRepresentation rep_post = post(rep);
288
289                 if(response)
290                 {
291                     // TODO Error Code
292                     response->setErrorCode(200);
293
294                     response->setResourceRepresentation(rep_post);
295
296                     if(rep_post.hasAttribute("createduri"))
297                     {
298                         result = OC_EH_RESOURCE_CREATED;
299
300                         response->setNewResourceUri(rep_post.getValue<std::string>("createduri"));
301                     }
302
303                 }
304
305                 // POST request operations
306             }
307             else if(requestType == "DELETE")
308             {
309                 // DELETE request operations
310             }
311         }
312
313         if(requestFlag & RequestHandlerFlag::ObserverFlag)
314         {
315             ObservationInfo observationInfo = request->getObservationInfo();
316             if(ObserveAction::ObserveRegister == observationInfo.action)
317             {
318                 m_interestedObservers.push_back(observationInfo.obsId);
319             }
320             else if(ObserveAction::ObserveUnregister == observationInfo.action)
321             {
322                 m_interestedObservers.erase(std::remove(
323                                                             m_interestedObservers.begin(),
324                                                             m_interestedObservers.end(),
325                                                             observationInfo.obsId),
326                                                             m_interestedObservers.end());
327             }
328
329             pthread_t threadId;
330
331             cout << "\t\trequestFlag : Observer\n";
332             gObservation = 1;
333             static int startedThread = 0;
334
335             // Observation happens on a different thread in ChangeLightRepresentation function.
336             // If we have not created the thread already, we will create one here.
337             if(!startedThread)
338             {
339                 pthread_create (&threadId, NULL, ChangeLightRepresentation, (void *)this);
340                 startedThread = 1;
341             }
342         }
343     }
344     else
345     {
346         std::cout << "Request invalid" << std::endl;
347     }
348
349     return result;
350 }
351
352 };
353
354 // ChangeLightRepresentaion is an observation function,
355 // which notifies any changes to the resource to stack
356 // via notifyObservers
357 void * ChangeLightRepresentation (void *param)
358 {
359     LightResource* lightPtr = (LightResource*) param;
360
361     // This function continuously monitors for the changes
362     while (1)
363     {
364         sleep (5);
365
366         if (gObservation)
367         {
368             // If under observation if there are any changes to the light resource
369             // we call notifyObservors
370             //
371             // For demostration we are changing the power value and notifying.
372             lightPtr->m_power += 10;
373
374             cout << "\nPower updated to : " << lightPtr->m_power << endl;
375             cout << "Notifying observers with resource handle: " << lightPtr->getHandle() << endl;
376
377             OCStackResult result = OC_STACK_OK;
378
379             if(isListOfObservers)
380             {
381                 std::shared_ptr<OCResourceResponse> resourceResponse(new OCResourceResponse());
382
383                 resourceResponse->setErrorCode(200);
384                 resourceResponse->setResourceRepresentation(lightPtr->get(), DEFAULT_INTERFACE);
385
386                 result = OCPlatform::notifyListOfObservers(  lightPtr->getHandle(),
387                                                              lightPtr->m_interestedObservers,
388                                                              resourceResponse);
389             }
390             else
391             {
392                 result = OCPlatform::notifyAllObservers(lightPtr->getHandle());
393             }
394
395             if(OC_STACK_NO_OBSERVERS == result)
396             {
397                 cout << "No More observers, stopping notifications" << endl;
398                 gObservation = 0;
399             }
400         }
401     }
402
403     return NULL;
404 }
405
406 void PrintUsage()
407 {
408     std::cout << std::endl;
409     std::cout << "Usage : simplserver <isListOfObservers>\n";
410     std::cout << "   ObserveType : 0 - Observe All\n";
411     std::cout << "   ObserveType : 1 - Observe List of observers\n\n";
412 }
413
414
415 int main(int argc, char* argv[1])
416 {
417     PrintUsage();
418
419     if (argc == 1)
420     {
421         isListOfObservers = 0;
422     }
423     else if (argc == 2)
424     {
425         int value = atoi(argv[1]);
426         if (value == 1)
427             isListOfObservers = 1;
428         else
429             isListOfObservers = 0;
430     }
431     else
432     {
433         return -1;
434     }
435
436     // Create PlatformConfig object
437     PlatformConfig cfg {
438         OC::ServiceType::InProc,
439         OC::ModeType::Server,
440         "0.0.0.0", // By setting to "0.0.0.0", it binds to all available interfaces
441         0,         // Uses randomly available port
442         OC::QualityOfService::LowQos
443     };
444
445     OCPlatform::Configure(cfg);
446     try
447     {
448         // Create the instance of the resource class (in this case instance of class 'LightResource').
449         LightResource myLight;
450
451         // Invoke createResource function of class light.
452         myLight.createResource();
453
454         myLight.addType(std::string("core.brightlight"));
455         myLight.addInterface(std::string("oc.mi.ll"));
456         // Perform app tasks
457         while(true)
458         {
459             // some tasks
460         }
461     }
462     catch(OCException e)
463     {
464         //log(e.what());
465     }
466
467     // No explicit call to stop the platform.
468     // When OCPlatform::destructor is invoked, internally we do platform cleanup
469 }