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);
39 void * handleSlowResponse (void *param, std::shared_ptr<OCResourceRequest> pRequest);
41 // Specifies where to notify all observers or list of observers
42 // false: notifies all observers
43 // true: notifies list of observers
44 bool isListOfObservers = false;
46 // Specifies secure or non-secure
47 // false: non-secure resource
48 // true: secure resource
49 bool isSecure = false;
51 /// Specifies whether Entity handler is going to do slow response or not
52 bool isSlowResponse = false;
54 // Forward declaring the entityHandler
56 /// This class represents a single resource named 'lightResource'. This resource has
57 /// two simple properties named 'state' and 'power'
63 /// Access this property from a TB client
67 std::string m_lightUri;
68 OCResourceHandle m_resourceHandle;
69 OCRepresentation m_lightRep;
70 ObservationIds m_interestedObservers;
75 :m_name("John's light"), m_state(false), m_power(0), m_lightUri("/a/light") {
76 // Initialize representation
77 m_lightRep.setUri(m_lightUri);
79 m_lightRep.setValue("state", m_state);
80 m_lightRep.setValue("power", m_power);
81 m_lightRep.setValue("name", m_name);
84 /* Note that this does not need to be a member function: for classes you do not have
85 access to, you can accomplish this with a free function: */
87 /// This function internally calls registerResource API.
90 std::string resourceURI = m_lightUri; //URI of the resource
91 std::string resourceTypeName = "core.light"; //resource type name. In this case, it is light
92 std::string resourceInterface = DEFAULT_INTERFACE; // resource interface.
94 // OCResourceProperty is defined ocstack.h
95 uint8_t resourceProperty;
98 resourceProperty = OC_DISCOVERABLE | OC_OBSERVABLE | OC_SECURE;
102 resourceProperty = OC_DISCOVERABLE | OC_OBSERVABLE;
104 EntityHandler cb = std::bind(&LightResource::entityHandler, this,PH::_1);
106 // This will internally create and register the resource.
107 OCStackResult result = OCPlatform::registerResource(
108 m_resourceHandle, resourceURI, resourceTypeName,
109 resourceInterface, cb, resourceProperty);
111 if (OC_STACK_OK != result)
113 cout << "Resource creation was unsuccessful\n";
117 OCStackResult createResource1()
119 std::string resourceURI = "/a/light1"; // URI of the resource
120 std::string resourceTypeName = "core.light"; // resource type name. In this case, it is light
121 std::string resourceInterface = DEFAULT_INTERFACE; // resource interface.
123 // OCResourceProperty is defined ocstack.h
124 uint8_t resourceProperty;
127 resourceProperty = OC_DISCOVERABLE | OC_OBSERVABLE | OC_SECURE;
131 resourceProperty = OC_DISCOVERABLE | OC_OBSERVABLE;
133 EntityHandler cb = std::bind(&LightResource::entityHandler, this,PH::_1);
135 OCResourceHandle resHandle;
137 // This will internally create and register the resource.
138 OCStackResult result = OCPlatform::registerResource(
139 resHandle, resourceURI, resourceTypeName,
140 resourceInterface, cb, resourceProperty);
142 if (OC_STACK_OK != result)
144 cout << "Resource creation was unsuccessful\n";
150 OCResourceHandle getHandle()
152 return m_resourceHandle;
155 // Puts representation.
156 // Gets values from the representation and
157 // updates the internal state
158 void put(OCRepresentation& rep)
161 if (rep.getValue("state", m_state))
163 cout << "\t\t\t\t" << "state: " << m_state << endl;
167 cout << "\t\t\t\t" << "state not found in the representation" << endl;
170 if (rep.getValue("power", m_power))
172 cout << "\t\t\t\t" << "power: " << m_power << endl;
176 cout << "\t\t\t\t" << "power not found in the representation" << endl;
181 cout << e.what() << endl;
186 // Post representation.
187 // Post can create new resource or simply act like put.
188 // Gets values from the representation and
189 // updates the internal state
190 OCRepresentation post(OCRepresentation& rep)
192 static int first = 1;
194 // for the first time it tries to create a resource
199 if(OC_STACK_OK == createResource1())
201 OCRepresentation rep1;
202 rep1.setValue("createduri", std::string("/a/light1"));
208 // from second time onwards it just puts
214 // gets the updated representation.
215 // Updates the representation with latest internal state before
217 OCRepresentation get()
219 m_lightRep.setValue("state", m_state);
220 m_lightRep.setValue("power", m_power);
225 void addType(const std::string& type) const
227 OCStackResult result = OCPlatform::bindTypeToResource(m_resourceHandle, type);
228 if (OC_STACK_OK != result)
230 cout << "Binding TypeName to Resource was unsuccessful\n";
234 void addInterface(const std::string& interface) const
236 OCStackResult result = OCPlatform::bindInterfaceToResource(m_resourceHandle, interface);
237 if (OC_STACK_OK != result)
239 cout << "Binding TypeName to Resource was unsuccessful\n";
244 // This is just a sample implementation of entity handler.
245 // Entity handler can be implemented in several ways by the manufacturer
246 OCEntityHandlerResult entityHandler(std::shared_ptr<OCResourceRequest> request)
248 cout << "\tIn Server CPP entity handler:\n";
249 OCEntityHandlerResult ehResult = OC_EH_ERROR;
252 // Get the request type and request flag
253 std::string requestType = request->getRequestType();
254 int requestFlag = request->getRequestHandlerFlag();
256 if(requestFlag & RequestHandlerFlag::InitFlag)
258 cout << "\t\trequestFlag : Init\n";
260 // entity handler to perform resource initialization operations
262 if(requestFlag & RequestHandlerFlag::RequestFlag)
264 cout << "\t\trequestFlag : Request\n";
265 auto pResponse = std::make_shared<OC::OCResourceResponse>();
266 pResponse->setRequestHandle(request->getRequestHandle());
267 pResponse->setResourceHandle(request->getResourceHandle());
269 // If the request type is GET
270 if(requestType == "GET")
272 cout << "\t\t\trequestType : GET\n";
273 if(isSlowResponse) // Slow response case
275 static int startedThread = 0;
278 std::thread t(handleSlowResponse, (void *)this, request);
282 ehResult = OC_EH_SLOW;
284 else // normal response case.
286 pResponse->setErrorCode(200);
287 pResponse->setResponseResult(OC_EH_OK);
288 pResponse->setResourceRepresentation(get());
289 if(OC_STACK_OK == OCPlatform::sendResponse(pResponse))
295 else if(requestType == "PUT")
297 cout << "\t\t\trequestType : PUT\n";
298 OCRepresentation rep = request->getResourceRepresentation();
300 // Do related operations related to PUT request
301 // Update the lightResource
303 pResponse->setErrorCode(200);
304 pResponse->setResponseResult(OC_EH_OK);
305 pResponse->setResourceRepresentation(get());
306 if(OC_STACK_OK == OCPlatform::sendResponse(pResponse))
311 else if(requestType == "POST")
313 cout << "\t\t\trequestType : POST\n";
315 OCRepresentation rep = request->getResourceRepresentation();
317 // Do related operations related to POST request
318 OCRepresentation rep_post = post(rep);
319 pResponse->setResourceRepresentation(rep_post);
320 pResponse->setErrorCode(200);
321 if(rep_post.hasAttribute("createduri"))
323 pResponse->setResponseResult(OC_EH_RESOURCE_CREATED);
324 pResponse->setNewResourceUri(rep_post.getValue<std::string>("createduri"));
327 if(OC_STACK_OK == OCPlatform::sendResponse(pResponse))
332 else if(requestType == "DELETE")
334 // DELETE request operations
338 if(requestFlag & RequestHandlerFlag::ObserverFlag)
340 ObservationInfo observationInfo = request->getObservationInfo();
341 if(ObserveAction::ObserveRegister == observationInfo.action)
343 m_interestedObservers.push_back(observationInfo.obsId);
345 else if(ObserveAction::ObserveUnregister == observationInfo.action)
347 m_interestedObservers.erase(std::remove(
348 m_interestedObservers.begin(),
349 m_interestedObservers.end(),
350 observationInfo.obsId),
351 m_interestedObservers.end());
356 cout << "\t\trequestFlag : Observer\n";
358 static int startedThread = 0;
360 // Observation happens on a different thread in ChangeLightRepresentation function.
361 // If we have not created the thread already, we will create one here.
364 pthread_create (&threadId, NULL, ChangeLightRepresentation, (void *)this);
372 std::cout << "Request invalid" << std::endl;
380 // ChangeLightRepresentaion is an observation function,
381 // which notifies any changes to the resource to stack
382 // via notifyObservers
383 void * ChangeLightRepresentation (void *param)
385 LightResource* lightPtr = (LightResource*) param;
387 // This function continuously monitors for the changes
394 // If under observation if there are any changes to the light resource
395 // we call notifyObservors
397 // For demostration we are changing the power value and notifying.
398 lightPtr->m_power += 10;
400 cout << "\nPower updated to : " << lightPtr->m_power << endl;
401 cout << "Notifying observers with resource handle: " << lightPtr->getHandle() << endl;
403 OCStackResult result = OC_STACK_OK;
405 if(isListOfObservers)
407 std::shared_ptr<OCResourceResponse> resourceResponse(new OCResourceResponse());
409 resourceResponse->setErrorCode(200);
410 resourceResponse->setResourceRepresentation(lightPtr->get(), DEFAULT_INTERFACE);
412 result = OCPlatform::notifyListOfObservers( lightPtr->getHandle(),
413 lightPtr->m_interestedObservers,
418 result = OCPlatform::notifyAllObservers(lightPtr->getHandle());
421 if(OC_STACK_NO_OBSERVERS == result)
423 cout << "No More observers, stopping notifications" << endl;
432 void * handleSlowResponse (void *param, std::shared_ptr<OCResourceRequest> pRequest)
434 // This function handles slow response case
435 LightResource* lightPtr = (LightResource*) param;
436 // Induce a case for slow response by using sleep
437 std::cout << "SLOW response" << std::endl;
440 auto pResponse = std::make_shared<OC::OCResourceResponse>();
441 pResponse->setRequestHandle(pRequest->getRequestHandle());
442 pResponse->setResourceHandle(pRequest->getResourceHandle());
443 pResponse->setResourceRepresentation(lightPtr->get());
444 pResponse->setErrorCode(200);
445 pResponse->setResponseResult(OC_EH_OK);
447 // Set the slow response flag back to false
448 isSlowResponse = false;
449 OCPlatform::sendResponse(pResponse);
455 std::cout << std::endl;
456 std::cout << "Usage : simpleserver <value>\n";
457 std::cout << " Default - Non-secure resource and notify all observers\n";
458 std::cout << " 1 - Non-secure resource and notify list of observers\n\n";
459 std::cout << " 2 - Secure resource and notify all observers\n";
460 std::cout << " 3 - Secure resource and notify list of observers\n\n";
461 std::cout << " 4 - Non-secure resource, GET slow response, notify all observers\n";
465 int main(int argc, char* argv[1])
471 isListOfObservers = false;
476 int value = atoi(argv[1]);
480 isListOfObservers = true;
484 isListOfObservers = false;
488 isListOfObservers = true;
492 isSlowResponse = true;
502 // Create PlatformConfig object
504 OC::ServiceType::InProc,
505 OC::ModeType::Server,
506 "0.0.0.0", // By setting to "0.0.0.0", it binds to all available interfaces
507 0, // Uses randomly available port
508 OC::QualityOfService::LowQos
511 OCPlatform::Configure(cfg);
514 // Create the instance of the resource class
515 // (in this case instance of class 'LightResource').
516 LightResource myLight;
518 // Invoke createResource function of class light.
519 myLight.createResource();
521 myLight.addType(std::string("core.brightlight"));
522 myLight.addInterface(std::string("oc.mi.ll"));
534 // No explicit call to stop the platform.
535 // When OCPlatform::destructor is invoked, internally we do platform cleanup