1 //******************************************************************
3 // Copyright 2014 Intel Mobile Communications GmbH All Rights Reserved.
5 //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
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
11 // http://www.apache.org/licenses/LICENSE-2.0
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.
19 //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
22 /// This sample provides steps to define an interface for a resource
23 /// (properties and methods) and host this resource on the server.
30 #include "OCPlatform.h"
35 namespace PH = std::placeholders;
38 void * ChangeLightRepresentation (void *param);
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;
45 // Forward declaring the entityHandler
47 /// This class represents a single resource named 'lightResource'. This resource has
48 /// two simple properties named 'state' and 'power'
54 /// Access this property from a TB client
58 std::string m_lightUri;
59 OCResourceHandle m_resourceHandle;
60 OCRepresentation m_lightRep;
61 ObservationIds m_interestedObservers;
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);
70 m_lightRep.setValue("state", m_state);
71 m_lightRep.setValue("power", m_power);
72 m_lightRep.setValue("name", m_name);
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: */
78 /// This function internally calls registerResource API.
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.
85 // OCResourceProperty is defined ocstack.h
86 uint8_t resourceProperty = OC_DISCOVERABLE | OC_OBSERVABLE;
88 EntityHandler cb = std::bind(&LightResource::entityHandler, this,PH::_1, PH::_2);
90 // This will internally create and register the resource.
91 OCStackResult result = OCPlatform::registerResource(
92 m_resourceHandle, resourceURI, resourceTypeName,
93 resourceInterface, cb, resourceProperty);
95 if (OC_STACK_OK != result)
97 cout << "Resource creation was unsuccessful\n";
101 OCStackResult createResource1()
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.
107 // OCResourceProperty is defined ocstack.h
108 uint8_t resourceProperty = OC_DISCOVERABLE | OC_OBSERVABLE;
110 EntityHandler cb = std::bind(&LightResource::entityHandler, this,PH::_1, PH::_2);
112 OCResourceHandle resHandle;
114 // This will internally create and register the resource.
115 OCStackResult result = OCPlatform::registerResource(
116 resHandle, resourceURI, resourceTypeName,
117 resourceInterface, cb, resourceProperty);
119 if (OC_STACK_OK != result)
121 cout << "Resource creation was unsuccessful\n";
127 OCResourceHandle getHandle()
129 return m_resourceHandle;
132 // Puts representation.
133 // Gets values from the representation and
134 // updates the internal state
135 void put(OCRepresentation& rep)
138 if (rep.getValue("state", m_state))
140 cout << "\t\t\t\t" << "state: " << m_state << endl;
144 cout << "\t\t\t\t" << "state not found in the representation" << endl;
147 if (rep.getValue("power", m_power))
149 cout << "\t\t\t\t" << "power: " << m_power << endl;
153 cout << "\t\t\t\t" << "power not found in the representation" << endl;
158 cout << e.what() << endl;
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)
169 static int first = 1;
171 // for the first time it tries to create a resource
176 if(OC_STACK_OK == createResource1())
178 OCRepresentation rep1;
179 rep1.setValue("createduri", std::string("/a/light1"));
185 // from second time onwards it just puts
191 // gets the updated representation.
192 // Updates the representation with latest internal state before
194 OCRepresentation get()
196 m_lightRep.setValue("state", m_state);
197 m_lightRep.setValue("power", m_power);
202 void addType(const std::string& type) const
204 OCStackResult result = OCPlatform::bindTypeToResource(m_resourceHandle, type);
205 if (OC_STACK_OK != result)
207 cout << "Binding TypeName to Resource was unsuccessful\n";
211 void addInterface(const std::string& interface) const
213 OCStackResult result = OCPlatform::bindInterfaceToResource(m_resourceHandle, interface);
214 if (OC_STACK_OK != result)
216 cout << "Binding TypeName to Resource was unsuccessful\n";
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)
226 OCEntityHandlerResult result = OC_EH_OK;
228 cout << "\tIn Server CPP entity handler:\n";
232 // Get the request type and request flag
233 std::string requestType = request->getRequestType();
234 int requestFlag = request->getRequestHandlerFlag();
236 if(requestFlag & RequestHandlerFlag::InitFlag)
238 cout << "\t\trequestFlag : Init\n";
240 // entity handler to perform resource initialization operations
242 if(requestFlag & RequestHandlerFlag::RequestFlag)
244 cout << "\t\trequestFlag : Request\n";
246 // If the request type is GET
247 if(requestType == "GET")
249 cout << "\t\t\trequestType : GET\n";
254 response->setErrorCode(200);
256 response->setResourceRepresentation(get());
259 else if(requestType == "PUT")
261 cout << "\t\t\trequestType : PUT\n";
263 OCRepresentation rep = request->getResourceRepresentation();
265 // Do related operations related to PUT request
267 // Update the lightResource
273 response->setErrorCode(200);
275 response->setResourceRepresentation(get());
279 else if(requestType == "POST")
281 cout << "\t\t\trequestType : POST\n";
283 OCRepresentation rep = request->getResourceRepresentation();
285 // Do related operations related to POST request
287 OCRepresentation rep_post = post(rep);
292 response->setErrorCode(200);
294 response->setResourceRepresentation(rep_post);
296 if(rep_post.hasAttribute("createduri"))
298 result = OC_EH_RESOURCE_CREATED;
300 response->setNewResourceUri(rep_post.getValue<std::string>("createduri"));
305 // POST request operations
307 else if(requestType == "DELETE")
309 // DELETE request operations
313 if(requestFlag & RequestHandlerFlag::ObserverFlag)
315 ObservationInfo observationInfo = request->getObservationInfo();
316 if(ObserveAction::ObserveRegister == observationInfo.action)
318 m_interestedObservers.push_back(observationInfo.obsId);
320 else if(ObserveAction::ObserveUnregister == observationInfo.action)
322 m_interestedObservers.erase(std::remove(
323 m_interestedObservers.begin(),
324 m_interestedObservers.end(),
325 observationInfo.obsId),
326 m_interestedObservers.end());
331 cout << "\t\trequestFlag : Observer\n";
333 static int startedThread = 0;
335 // Observation happens on a different thread in ChangeLightRepresentation function.
336 // If we have not created the thread already, we will create one here.
339 pthread_create (&threadId, NULL, ChangeLightRepresentation, (void *)this);
346 std::cout << "Request invalid" << std::endl;
354 // ChangeLightRepresentaion is an observation function,
355 // which notifies any changes to the resource to stack
356 // via notifyObservers
357 void * ChangeLightRepresentation (void *param)
359 LightResource* lightPtr = (LightResource*) param;
361 // This function continuously monitors for the changes
368 // If under observation if there are any changes to the light resource
369 // we call notifyObservors
371 // For demostration we are changing the power value and notifying.
372 lightPtr->m_power += 10;
374 cout << "\nPower updated to : " << lightPtr->m_power << endl;
375 cout << "Notifying observers with resource handle: " << lightPtr->getHandle() << endl;
377 OCStackResult result = OC_STACK_OK;
379 if(isListOfObservers)
381 std::shared_ptr<OCResourceResponse> resourceResponse(new OCResourceResponse());
383 resourceResponse->setErrorCode(200);
384 resourceResponse->setResourceRepresentation(lightPtr->get(), DEFAULT_INTERFACE);
386 result = OCPlatform::notifyListOfObservers( lightPtr->getHandle(),
387 lightPtr->m_interestedObservers,
392 result = OCPlatform::notifyAllObservers(lightPtr->getHandle());
395 if(OC_STACK_NO_OBSERVERS == result)
397 cout << "No More observers, stopping notifications" << endl;
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";
415 int main(int argc, char* argv[1])
421 isListOfObservers = 0;
425 int value = atoi(argv[1]);
427 isListOfObservers = 1;
429 isListOfObservers = 0;
436 // Create PlatformConfig object
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
445 OCPlatform::Configure(cfg);
448 // Create the instance of the resource class (in this case instance of class 'LightResource').
449 LightResource myLight;
451 // Invoke createResource function of class light.
452 myLight.createResource();
454 myLight.addType(std::string("core.brightlight"));
455 myLight.addInterface(std::string("oc.mi.ll"));
467 // No explicit call to stop the platform.
468 // When OCPlatform::destructor is invoked, internally we do platform cleanup