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 <condition_variable>
32 #include "OCPlatform.h"
37 namespace PH = std::placeholders;
40 void * ChangeLightRepresentation (void *param);
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;
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;
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);
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 // resource type name. In this case, it is light
83 std::string resourceTypeName = "core.light";
84 std::string resourceInterface = DEFAULT_INTERFACE; // resource interface.
86 // OCResourceProperty is defined ocstack.h
87 uint8_t resourceProperty = OC_DISCOVERABLE | OC_OBSERVABLE;
89 EntityHandler cb = std::bind(&LightResource::entityHandler, this,PH::_1);
91 // This will internally create and register the resource.
92 OCStackResult result = OCPlatform::registerResource(
93 m_resourceHandle, resourceURI, resourceTypeName,
94 resourceInterface, cb, resourceProperty);
96 if (OC_STACK_OK != result)
98 cout << "Resource creation was unsuccessful\n";
102 OCStackResult createResource1()
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.
108 // OCResourceProperty is defined ocstack.h
109 uint8_t resourceProperty = OC_DISCOVERABLE | OC_OBSERVABLE;
111 EntityHandler cb = std::bind(&LightResource::entityHandler, this,PH::_1);
113 OCResourceHandle resHandle;
115 // This will internally create and register the resource.
116 OCStackResult result = OCPlatform::registerResource(
117 resHandle, resourceURI, resourceTypeName,
118 resourceInterface, cb, resourceProperty);
120 if (OC_STACK_OK != result)
122 cout << "Resource creation was unsuccessful\n";
128 OCResourceHandle getHandle()
130 return m_resourceHandle;
133 // Puts representation.
134 // Gets values from the representation and
135 // updates the internal state
136 void put(OCRepresentation& rep)
139 if (rep.getValue("state", m_state))
141 cout << "\t\t\t\t" << "state: " << m_state << endl;
145 cout << "\t\t\t\t" << "state not found in the representation" << endl;
148 if (rep.getValue("power", m_power))
150 cout << "\t\t\t\t" << "power: " << m_power << endl;
154 cout << "\t\t\t\t" << "power not found in the representation" << endl;
159 cout << e.what() << endl;
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)
170 static int first = 1;
172 std::cout << "In POST\n";
174 // for the first time it tries to create a resource
177 std::cout << "In POST/First\n";
181 if(OC_STACK_OK == createResource1())
183 std::cout << "Created a new resource\n";
184 OCRepresentation rep1;
185 rep1.setValue("createduri", std::string("/a/light1"));
191 // from second time onwards it just puts
197 // gets the updated representation.
198 // Updates the representation with latest internal state before
200 OCRepresentation get()
202 m_lightRep.setValue("state", m_state);
203 m_lightRep.setValue("power", m_power);
208 void addType(const std::string& type) const
210 OCStackResult result = OCPlatform::bindTypeToResource(m_resourceHandle, type);
211 if (OC_STACK_OK != result)
213 cout << "Binding TypeName to Resource was unsuccessful\n";
217 void addInterface(const std::string& interface) const
219 OCStackResult result = OCPlatform::bindInterfaceToResource(m_resourceHandle, interface);
220 if (OC_STACK_OK != result)
222 cout << "Binding TypeName to Resource was unsuccessful\n";
228 OCStackResult sendResponse(std::shared_ptr<OCResourceRequest> pRequest)
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);
237 return OCPlatform::sendResponse(pResponse);
240 OCStackResult sendPostResponse(std::shared_ptr<OCResourceRequest> pRequest)
242 auto pResponse = std::make_shared<OC::OCResourceResponse>();
243 pResponse->setRequestHandle(pRequest->getRequestHandle());
244 pResponse->setResourceHandle(pRequest->getResourceHandle());
246 OCRepresentation rep = pRequest->getResourceRepresentation();
247 OCRepresentation rep_post = post(rep);
249 pResponse->setResourceRepresentation(rep_post);
250 pResponse->setErrorCode(200);
251 pResponse->setResponseResult(OC_EH_OK);
253 return OCPlatform::sendResponse(pResponse);
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)
260 cout << "\tIn Server CPP entity handler:\n";
261 OCEntityHandlerResult ehResult = OC_EH_ERROR;
265 // Get the request type and request flag
266 std::string requestType = request->getRequestType();
267 int requestFlag = request->getRequestHandlerFlag();
269 if(requestFlag & RequestHandlerFlag::InitFlag)
271 cout << "\t\trequestFlag : Init\n";
272 // entity handler to perform resource initialization operations
274 if(requestFlag & RequestHandlerFlag::RequestFlag)
276 cout << "\t\trequestFlag : Request\n";
278 // If the request type is GET
279 if(requestType == "GET")
281 cout << "\t\t\trequestType : GET\n";
282 if(OC_STACK_OK == sendResponse(request))
287 else if(requestType == "PUT")
289 cout << "\t\t\trequestType : PUT\n";
291 OCRepresentation rep = request->getResourceRepresentation();
292 // Do related operations related to PUT request
293 // Update the lightResource
295 if(OC_STACK_OK == sendResponse(request))
300 else if(requestType == "POST")
302 cout << "\t\t\trequestType : POST\n";
303 if(OC_STACK_OK == sendPostResponse(request))
308 else if(requestType == "DELETE")
310 // DELETE request operations
314 if(requestFlag & RequestHandlerFlag::ObserverFlag)
316 ObservationInfo observationInfo = request->getObservationInfo();
317 if(ObserveAction::ObserveRegister == observationInfo.action)
319 m_interestedObservers.push_back(observationInfo.obsId);
321 else if(ObserveAction::ObserveUnregister == observationInfo.action)
323 m_interestedObservers.erase(std::remove(
324 m_interestedObservers.begin(),
325 m_interestedObservers.end(),
326 observationInfo.obsId),
327 m_interestedObservers.end());
332 cout << "\t\trequestFlag : Observer\n";
334 static int startedThread = 0;
336 // Observation happens on a different thread in ChangeLightRepresentation function.
337 // If we have not created the thread already, we will create one here.
340 pthread_create (&threadId, NULL, ChangeLightRepresentation, (void *)this);
348 std::cout << "Request invalid" << std::endl;
356 // ChangeLightRepresentaion is an observation function,
357 // which notifies any changes to the resource to stack
358 // via notifyObservers
359 void * ChangeLightRepresentation (void *param)
361 LightResource* lightPtr = (LightResource*) param;
363 // This function continuously monitors for the changes
370 // If under observation if there are any changes to the light resource
371 // we call notifyObservors
373 // For demostration we are changing the power value and notifying.
374 lightPtr->m_power += 10;
376 cout << "\nPower updated to : " << lightPtr->m_power << endl;
377 cout << "Notifying observers with resource handle: " << lightPtr->getHandle() << endl;
379 OCStackResult result = OC_STACK_OK;
381 if(isListOfObservers)
383 std::shared_ptr<OCResourceResponse> resourceResponse(new OCResourceResponse());
385 resourceResponse->setErrorCode(200);
386 resourceResponse->setResourceRepresentation(lightPtr->get(), DEFAULT_INTERFACE);
388 result = OCPlatform::notifyListOfObservers(
389 lightPtr->getHandle(),
390 lightPtr->m_interestedObservers,
392 OC::QualityOfService::HighQos);
396 result = OCPlatform::notifyAllObservers(lightPtr->getHandle(),
397 OC::QualityOfService::HighQos);
400 if(OC_STACK_NO_OBSERVERS == result)
402 cout << "No More observers, stopping notifications" << endl;
413 std::cout << std::endl;
414 std::cout << "Usage : simpleserverHQ <ObserveType>\n";
415 std::cout << " ObserveType : 0 - Observe All\n";
416 std::cout << " ObserveType : 1 - Observe List of observers\n\n";
420 int main(int argc, char* argv[])
426 isListOfObservers = 0;
430 int value = atoi(argv[1]);
432 isListOfObservers = 1;
434 isListOfObservers = 0;
441 // Create PlatformConfig object
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
450 OCPlatform::Configure(cfg);
454 // Create the instance of the resource class
455 // (in this case instance of class 'LightResource').
456 LightResource myLight(cfg);
458 // Invoke createResource function of class light.
459 myLight.createResource();
461 myLight.addType(std::string("core.brightlight"));
462 myLight.addInterface(std::string("oc.mi.ll"));
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
469 std::condition_variable cv;
470 std::unique_lock<std::mutex> lock(blocker);
471 cv.wait(lock, []{return false;});
473 catch(OCException& e)
475 oclog() << "Exception in main: "<< e.what();
478 // No explicit call to stop the platform.
479 // When OCPlatform destructor is invoked, internally we do platform cleanup