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);
41 void * handleSlowResponse (void *param, std::shared_ptr<OCResourceRequest> pRequest);
43 // Specifies where to notify all observers or list of observers
44 // false: notifies all observers
45 // true: notifies list of observers
46 bool isListOfObservers = false;
48 // Specifies secure or non-secure
49 // false: non-secure resource
50 // true: secure resource
51 bool isSecure = false;
53 /// Specifies whether Entity handler is going to do slow response or not
54 bool isSlowResponse = false;
56 // Forward declaring the entityHandler
58 /// This class represents a single resource named 'lightResource'. This resource has
59 /// two simple properties named 'state' and 'power'
65 /// Access this property from a TB client
69 std::string m_lightUri;
70 OCResourceHandle m_resourceHandle;
71 OCRepresentation m_lightRep;
72 ObservationIds m_interestedObservers;
77 :m_name("John's light"), m_state(false), m_power(0), m_lightUri("/a/light"),
78 m_resourceHandle(nullptr) {
79 // Initialize representation
80 m_lightRep.setUri(m_lightUri);
82 m_lightRep.setValue("state", m_state);
83 m_lightRep.setValue("power", m_power);
84 m_lightRep.setValue("name", m_name);
87 /* Note that this does not need to be a member function: for classes you do not have
88 access to, you can accomplish this with a free function: */
90 /// This function internally calls registerResource API.
94 std::string resourceURI = m_lightUri;
95 //resource type name. In this case, it is light
96 std::string resourceTypeName = "core.light";
97 // resource interface.
98 std::string resourceInterface = DEFAULT_INTERFACE;
100 // OCResourceProperty is defined ocstack.h
101 uint8_t resourceProperty;
104 resourceProperty = OC_DISCOVERABLE | OC_OBSERVABLE | OC_SECURE;
108 resourceProperty = OC_DISCOVERABLE | OC_OBSERVABLE;
110 EntityHandler cb = std::bind(&LightResource::entityHandler, this,PH::_1);
112 // This will internally create and register the resource.
113 OCStackResult result = OCPlatform::registerResource(
114 m_resourceHandle, resourceURI, resourceTypeName,
115 resourceInterface, cb, resourceProperty);
117 if (OC_STACK_OK != result)
119 cout << "Resource creation was unsuccessful\n";
123 OCStackResult createResource1()
125 // URI of the resource
126 std::string resourceURI = "/a/light1";
127 // resource type name. In this case, it is light
128 std::string resourceTypeName = "core.light";
129 // resource interface.
130 std::string resourceInterface = DEFAULT_INTERFACE;
132 // OCResourceProperty is defined ocstack.h
133 uint8_t resourceProperty;
136 resourceProperty = OC_DISCOVERABLE | OC_OBSERVABLE | OC_SECURE;
140 resourceProperty = OC_DISCOVERABLE | OC_OBSERVABLE;
142 EntityHandler cb = std::bind(&LightResource::entityHandler, this,PH::_1);
144 OCResourceHandle resHandle;
146 // This will internally create and register the resource.
147 OCStackResult result = OCPlatform::registerResource(
148 resHandle, resourceURI, resourceTypeName,
149 resourceInterface, cb, resourceProperty);
151 if (OC_STACK_OK != result)
153 cout << "Resource creation was unsuccessful\n";
159 OCResourceHandle getHandle()
161 return m_resourceHandle;
164 // Puts representation.
165 // Gets values from the representation and
166 // updates the internal state
167 void put(OCRepresentation& rep)
170 if (rep.getValue("state", m_state))
172 cout << "\t\t\t\t" << "state: " << m_state << endl;
176 cout << "\t\t\t\t" << "state not found in the representation" << endl;
179 if (rep.getValue("power", m_power))
181 cout << "\t\t\t\t" << "power: " << m_power << endl;
185 cout << "\t\t\t\t" << "power not found in the representation" << endl;
190 cout << e.what() << endl;
195 // Post representation.
196 // Post can create new resource or simply act like put.
197 // Gets values from the representation and
198 // updates the internal state
199 OCRepresentation post(OCRepresentation& rep)
201 static int first = 1;
203 // for the first time it tries to create a resource
208 if(OC_STACK_OK == createResource1())
210 OCRepresentation rep1;
211 rep1.setValue("createduri", std::string("/a/light1"));
217 // from second time onwards it just puts
223 // gets the updated representation.
224 // Updates the representation with latest internal state before
226 OCRepresentation get()
228 m_lightRep.setValue("state", m_state);
229 m_lightRep.setValue("power", m_power);
234 void addType(const std::string& type) const
236 OCStackResult result = OCPlatform::bindTypeToResource(m_resourceHandle, type);
237 if (OC_STACK_OK != result)
239 cout << "Binding TypeName to Resource was unsuccessful\n";
243 void addInterface(const std::string& interface) const
245 OCStackResult result = OCPlatform::bindInterfaceToResource(m_resourceHandle, interface);
246 if (OC_STACK_OK != result)
248 cout << "Binding TypeName to Resource was unsuccessful\n";
253 // This is just a sample implementation of entity handler.
254 // Entity handler can be implemented in several ways by the manufacturer
255 OCEntityHandlerResult entityHandler(std::shared_ptr<OCResourceRequest> request)
257 cout << "\tIn Server CPP entity handler:\n";
258 OCEntityHandlerResult ehResult = OC_EH_ERROR;
261 // Get the request type and request flag
262 std::string requestType = request->getRequestType();
263 int requestFlag = request->getRequestHandlerFlag();
265 if(requestFlag & RequestHandlerFlag::InitFlag)
267 cout << "\t\trequestFlag : Init\n";
268 // entity handler to perform resource initialization operations
270 if(requestFlag & RequestHandlerFlag::RequestFlag)
272 cout << "\t\trequestFlag : Request\n";
273 auto pResponse = std::make_shared<OC::OCResourceResponse>();
274 pResponse->setRequestHandle(request->getRequestHandle());
275 pResponse->setResourceHandle(request->getResourceHandle());
277 // Check for query params (if any)
278 QueryParamsMap queries = request->getQueryParameters();
280 if (!queries.empty())
282 std::cout << "\nQuery processing upto entityHandler" << std::endl;
284 for (auto it : queries)
286 std::cout << "Query key: " << it.first << " value : " << it.second
290 // If the request type is GET
291 if(requestType == "GET")
293 cout << "\t\t\trequestType : GET\n";
294 if(isSlowResponse) // Slow response case
296 static int startedThread = 0;
299 std::thread t(handleSlowResponse, (void *)this, request);
303 ehResult = OC_EH_SLOW;
305 else // normal response case.
307 pResponse->setErrorCode(200);
308 pResponse->setResponseResult(OC_EH_OK);
309 pResponse->setResourceRepresentation(get());
310 if(OC_STACK_OK == OCPlatform::sendResponse(pResponse))
316 else if(requestType == "PUT")
318 cout << "\t\t\trequestType : PUT\n";
319 OCRepresentation rep = request->getResourceRepresentation();
321 // Do related operations related to PUT request
322 // Update the lightResource
324 pResponse->setErrorCode(200);
325 pResponse->setResponseResult(OC_EH_OK);
326 pResponse->setResourceRepresentation(get());
327 if(OC_STACK_OK == OCPlatform::sendResponse(pResponse))
332 else if(requestType == "POST")
334 cout << "\t\t\trequestType : POST\n";
336 OCRepresentation rep = request->getResourceRepresentation();
338 // Do related operations related to POST request
339 OCRepresentation rep_post = post(rep);
340 pResponse->setResourceRepresentation(rep_post);
341 pResponse->setErrorCode(200);
342 if(rep_post.hasAttribute("createduri"))
344 pResponse->setResponseResult(OC_EH_RESOURCE_CREATED);
345 pResponse->setNewResourceUri(rep_post.getValue<std::string>("createduri"));
349 pResponse->setResponseResult(OC_EH_OK);
352 if(OC_STACK_OK == OCPlatform::sendResponse(pResponse))
357 else if(requestType == "DELETE")
359 cout << "Delete request received" << endl;
363 if(requestFlag & RequestHandlerFlag::ObserverFlag)
365 ObservationInfo observationInfo = request->getObservationInfo();
366 if(ObserveAction::ObserveRegister == observationInfo.action)
368 m_interestedObservers.push_back(observationInfo.obsId);
370 else if(ObserveAction::ObserveUnregister == observationInfo.action)
372 m_interestedObservers.erase(std::remove(
373 m_interestedObservers.begin(),
374 m_interestedObservers.end(),
375 observationInfo.obsId),
376 m_interestedObservers.end());
381 cout << "\t\trequestFlag : Observer\n";
383 static int startedThread = 0;
385 // Observation happens on a different thread in ChangeLightRepresentation function.
386 // If we have not created the thread already, we will create one here.
389 pthread_create (&threadId, NULL, ChangeLightRepresentation, (void *)this);
397 std::cout << "Request invalid" << std::endl;
405 // ChangeLightRepresentaion is an observation function,
406 // which notifies any changes to the resource to stack
407 // via notifyObservers
408 void * ChangeLightRepresentation (void *param)
410 LightResource* lightPtr = (LightResource*) param;
412 // This function continuously monitors for the changes
419 // If under observation if there are any changes to the light resource
420 // we call notifyObservors
422 // For demostration we are changing the power value and notifying.
423 lightPtr->m_power += 10;
425 cout << "\nPower updated to : " << lightPtr->m_power << endl;
426 cout << "Notifying observers with resource handle: " << lightPtr->getHandle() << endl;
428 OCStackResult result = OC_STACK_OK;
430 if(isListOfObservers)
432 std::shared_ptr<OCResourceResponse> resourceResponse =
433 {std::make_shared<OCResourceResponse>()};
435 resourceResponse->setErrorCode(200);
436 resourceResponse->setResourceRepresentation(lightPtr->get(), DEFAULT_INTERFACE);
438 result = OCPlatform::notifyListOfObservers( lightPtr->getHandle(),
439 lightPtr->m_interestedObservers,
444 result = OCPlatform::notifyAllObservers(lightPtr->getHandle());
447 if(OC_STACK_NO_OBSERVERS == result)
449 cout << "No More observers, stopping notifications" << endl;
458 void * handleSlowResponse (void *param, std::shared_ptr<OCResourceRequest> pRequest)
460 // This function handles slow response case
461 LightResource* lightPtr = (LightResource*) param;
462 // Induce a case for slow response by using sleep
463 std::cout << "SLOW response" << std::endl;
466 auto pResponse = std::make_shared<OC::OCResourceResponse>();
467 pResponse->setRequestHandle(pRequest->getRequestHandle());
468 pResponse->setResourceHandle(pRequest->getResourceHandle());
469 pResponse->setResourceRepresentation(lightPtr->get());
470 pResponse->setErrorCode(200);
471 pResponse->setResponseResult(OC_EH_OK);
473 // Set the slow response flag back to false
474 isSlowResponse = false;
475 OCPlatform::sendResponse(pResponse);
481 std::cout << std::endl;
482 std::cout << "Usage : simpleserver <value>\n";
483 std::cout << " Default - Non-secure resource and notify all observers\n";
484 std::cout << " 1 - Non-secure resource and notify list of observers\n\n";
485 std::cout << " 2 - Secure resource and notify all observers\n";
486 std::cout << " 3 - Secure resource and notify list of observers\n\n";
487 std::cout << " 4 - Non-secure resource, GET slow response, notify all observers\n";
491 int main(int argc, char* argv[])
497 isListOfObservers = false;
502 int value = atoi(argv[1]);
506 isListOfObservers = true;
510 isListOfObservers = false;
514 isListOfObservers = true;
518 isSlowResponse = true;
529 // Create PlatformConfig object
531 OC::ServiceType::InProc,
532 OC::ModeType::Server,
533 "0.0.0.0", // By setting to "0.0.0.0", it binds to all available interfaces
534 0, // Uses randomly available port
535 OC::QualityOfService::LowQos
538 OCPlatform::Configure(cfg);
541 // Create the instance of the resource class
542 // (in this case instance of class 'LightResource').
543 LightResource myLight;
545 // Invoke createResource function of class light.
546 myLight.createResource();
547 std::cout << "Created resource." << std::endl;
549 myLight.addType(std::string("core.brightlight"));
550 myLight.addInterface(std::string(LINK_INTERFACE));
551 std::cout << "Added Interface and Type" << std::endl;
554 // A condition variable will free the mutex it is given, then do a non-
555 // intensive block until 'notify' is called on it. In this case, since we
556 // don't ever call cv.notify, this should be a non-processor intensive version
559 std::condition_variable cv;
560 std::unique_lock<std::mutex> lock(blocker);
561 std::cout <<"Waiting" << std::endl;
562 cv.wait(lock, []{return false;});
564 catch(OCException &e)
566 std::cout << "OCException in main : " << e.what() << endl;
569 // No explicit call to stop the platform.
570 // When OCPlatform::destructor is invoked, internally we do platform cleanup