1 //******************************************************************
3 // Copyright 2014 Samsung Electronics 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"
32 #include "../lib/mosquitto.h"
33 #include "fanserver.h"
40 namespace PH = std::placeholders;
42 time_t timer; // Define the timer
43 struct tm *tblock; // Define a structure for time block
47 void *ChangeFanRepresentation (void *param);
48 void *handleSlowResponse (void *param, std::shared_ptr<OCResourceRequest> pRequest);
50 // Specifies where to notify all observers or list of observers
51 // false: notifies all observers
52 // true: notifies list of observers
53 bool isListOfObservers = false;
55 // Specifies secure or non-secure
56 // false: non-secure resource
57 // true: secure resource
58 bool isSecure = false;
60 /// Specifies whether Entity handler is going to do slow response or not
61 bool isSlowResponse = false;
63 // Forward declaring the entityHandler
64 /// This class represents a single resource named 'fanResource'. This resource has
65 /// two simple properties named 'state' and 'power'
66 typedef struct plugin_data_t plugin_data_t;
71 pthread_t m_thread; // 2
76 struct mosquitto *myMosquitto;
80 /// Access this property from a TB client
86 OCResourceHandle m_resourceHandle;
87 OCRepresentation m_fanRep;
88 ObservationIds m_interestedObservers;
92 FanResource(): m_name("John's fan"), m_state(false), m_power(0), m_fanUri("/a/fan")
94 // Initialize representation
95 m_fanRep.setUri(m_fanUri);
97 m_fanRep.setValue("state", m_state);
98 m_fanRep.setValue("power", m_power);
99 m_fanRep.setValue("name", m_name);
103 /* Note that this does not need to be a member function: for classes you do not have
104 access to, you can accomplish this with a free function: */
106 /// This function internally calls registerResource API.
107 void createResource()
109 std::string resourceURI = m_fanUri; // URI of the resource
110 std::string resourceTypeName = "core.fan"; // resource type name. In this case, it is fan
111 std::string resourceInterface = DEFAULT_INTERFACE; // resource interface.
113 // OCResourceProperty is defined ocstack.h
114 uint8_t resourceProperty = OC_DISCOVERABLE | OC_OBSERVABLE;
116 EntityHandler cb = std::bind(&FanResource::entityHandler, this, PH::_1);
118 // This will internally create and register the resource.
119 OCStackResult result = OCPlatform::registerResource(
120 m_resourceHandle, resourceURI, resourceTypeName,
121 resourceInterface, cb, resourceProperty);
123 if (OC_STACK_OK != result)
125 cout << "Resource creation was unsuccessful\n";
129 OCStackResult createResource1()
131 std::string resourceURI = "/a/fan1"; // URI of the resource
132 std::string resourceTypeName = "core.fan"; // resource type name. In this case, it is fan
133 std::string resourceInterface = DEFAULT_INTERFACE; // resource interface.
135 // OCResourceProperty is defined ocstack.h
136 uint8_t resourceProperty = OC_DISCOVERABLE | OC_OBSERVABLE;
138 EntityHandler cb = std::bind(&FanResource::entityHandler, this, PH::_1);
140 OCResourceHandle resHandle;
142 // This will internally create and register the resource.
143 OCStackResult result = OCPlatform::registerResource(
144 resHandle, resourceURI, resourceTypeName,
145 resourceInterface, cb, resourceProperty);
147 if (OC_STACK_OK != result)
149 cout << "Resource creation was unsuccessful\n";
155 OCResourceHandle getHandle()
157 return m_resourceHandle;
160 // Puts representation.
161 // Gets values from the representation and
162 // updates the internal state
163 void put(OCRepresentation &rep)
167 if (rep.getValue("state", m_state))
169 cout << "\t\t\t\t" << "state: " << m_state << endl;
173 cout << "\t\t\t\t" << "state not found in the representation" << endl;
176 if (rep.getValue("power", m_power))
178 cout << "\t\t\t\t" << "power: " << m_power << endl;
181 mosquitto_publish(myMosquitto, NULL, "actuators/fan", 32, "onfan", 0, true);
185 mosquitto_publish(myMosquitto, NULL, "actuators/fan", 32, "offfan", 0, true);
190 cout << "\t\t\t\t" << "power not found in the representation" << endl;
195 cout << e.what() << endl;
200 // Post representation.
201 // Post can create new resource or simply act like put.
202 // Gets values from the representation and
203 // updates the internal state
204 OCRepresentation post(OCRepresentation &rep)
206 static int first = 1;
208 // for the first time it tries to create a resource
213 if (OC_STACK_OK == createResource1())
215 OCRepresentation rep1;
216 rep1.setValue("createduri", std::string("/a/fan1"));
222 // from second time onwards it just puts
228 // gets the updated representation.
229 // Updates the representation with latest internal state before
231 OCRepresentation get()
233 m_fanRep.setValue("state", m_state);
234 m_fanRep.setValue("power", m_power);
240 void addType(const std::string &type) const
242 OCStackResult result = OCPlatform::bindTypeToResource(m_resourceHandle, type);
243 if (OC_STACK_OK != result)
245 cout << "Binding TypeName to Resource was unsuccessful\n";
249 void addInterface(const std::string &interface) const
251 OCStackResult result = OCPlatform::bindInterfaceToResource(m_resourceHandle, interface);
252 if (OC_STACK_OK != result)
254 cout << "Binding TypeName to Resource was unsuccessful\n";
259 // This is just a sample implementation of entity handler.
260 // Entity handler can be implemented in several ways by the manufacturer
261 OCEntityHandlerResult entityHandler(std::shared_ptr<OCResourceRequest> request)
263 cout << "\tIn Server CPP entity handler:\n";
264 OCEntityHandlerResult ehResult = OC_EH_ERROR;
267 // Get the request type and request flag
268 std::string requestType = request->getRequestType();
269 int requestFlag = request->getRequestHandlerFlag();
271 if (requestFlag & RequestHandlerFlag::RequestFlag)
273 cout << "\t\trequestFlag : Request === Handle by FanServer\n";
274 auto pResponse = std::make_shared<OC::OCResourceResponse>();
275 pResponse->setRequestHandle(request->getRequestHandle());
276 pResponse->setResourceHandle(request->getResourceHandle());
278 // If the request type is GET
279 if (requestType == "GET")
281 cout << "\t\t\trequestType : GET\n";
282 if (isSlowResponse) // Slow response case
284 static int startedThread = 0;
287 std::thread t(handleSlowResponse, (void *)this, request);
291 ehResult = OC_EH_SLOW;
293 else // normal response case.
295 pResponse->setErrorCode(200);
296 pResponse->setResponseResult(OC_EH_OK);
297 pResponse->setResourceRepresentation(get());
298 if (OC_STACK_OK == OCPlatform::sendResponse(pResponse))
304 else if (requestType == "PUT")
306 cout << "\t\t\trequestType : PUT\n";
307 OCRepresentation rep = request->getResourceRepresentation();
309 // Do related operations related to PUT request
310 // Update the fanResource
312 pResponse->setErrorCode(200);
313 pResponse->setResponseResult(OC_EH_OK);
314 pResponse->setResourceRepresentation(get());
315 if (OC_STACK_OK == OCPlatform::sendResponse(pResponse))
320 else if (requestType == "POST")
322 cout << "\t\t\trequestType : POST\n";
324 OCRepresentation rep = request->getResourceRepresentation();
326 // Do related operations related to POST request
327 OCRepresentation rep_post = post(rep);
328 pResponse->setResourceRepresentation(rep_post);
329 pResponse->setErrorCode(200);
330 if (rep_post.hasAttribute("createduri"))
332 pResponse->setResponseResult(OC_EH_RESOURCE_CREATED);
333 pResponse->setNewResourceUri(rep_post.getValue<std::string>("createduri"));
336 if (OC_STACK_OK == OCPlatform::sendResponse(pResponse))
341 else if (requestType == "DELETE")
343 // DELETE request operations
347 if (requestFlag & RequestHandlerFlag::ObserverFlag)
349 ObservationInfo observationInfo = request->getObservationInfo();
350 if (ObserveAction::ObserveRegister == observationInfo.action)
352 m_interestedObservers.push_back(observationInfo.obsId);
354 else if (ObserveAction::ObserveUnregister == observationInfo.action)
356 m_interestedObservers.erase(std::remove(
357 m_interestedObservers.begin(),
358 m_interestedObservers.end(),
359 observationInfo.obsId),
360 m_interestedObservers.end());
365 cout << "\t\trequestFlag : Observer\n";
367 static int startedThread = 0;
369 // Observation happens on a different thread in ChangeFanRepresentation function.
370 // If we have not created the thread already, we will create one here.
373 pthread_create (&threadId, NULL, ChangeFanRepresentation, (void *)this);
381 std::cout << "Request invalid" << std::endl;
388 // Create the instance of the resource class (in this case instance of class 'FanResource').
390 // ChangeFanRepresentaion is an observation function,
391 // which notifies any changes to the resource to stack
392 // via notifyObservers
393 void *ChangeFanRepresentation (void *param)
395 FanResource *fanPtr = (FanResource *) param;
397 // This function continuously monitors for the changes
404 // If under observation if there are any changes to the fan resource
405 // we call notifyObservors
407 // For demostration we are changing the power value and notifying.
408 fanPtr->m_power += 10;
410 cout << "\nPower updated to : " << fanPtr->m_power << endl;
411 cout << "Notifying observers with resource handle: " << fanPtr->getHandle() << endl;
413 OCStackResult result = OC_STACK_OK;
415 if (isListOfObservers)
417 std::shared_ptr<OCResourceResponse> resourceResponse(new OCResourceResponse());
419 resourceResponse->setErrorCode(200);
420 resourceResponse->setResourceRepresentation(fanPtr->get(), DEFAULT_INTERFACE);
422 result = OCPlatform::notifyListOfObservers( fanPtr->getHandle(),
423 fanPtr->m_interestedObservers,
428 result = OCPlatform::notifyAllObservers(fanPtr->getHandle());
431 if (OC_STACK_NO_OBSERVERS == result)
433 cout << "No More observers, stopping notifications" << endl;
442 void *handleSlowResponse (void *param, std::shared_ptr<OCResourceRequest> pRequest)
444 // This function handles slow response case
445 FanResource *fanPtr = (FanResource *) param;
446 // Induce a case for slow response by using sleep
447 std::cout << "SLOW response" << std::endl;
450 auto pResponse = std::make_shared<OC::OCResourceResponse>();
451 pResponse->setRequestHandle(pRequest->getRequestHandle());
452 pResponse->setResourceHandle(pRequest->getResourceHandle());
453 pResponse->setResourceRepresentation(fanPtr->get());
454 pResponse->setErrorCode(200);
455 pResponse->setResponseResult(OC_EH_OK);
457 // Set the slow response flag back to false
458 isSlowResponse = false;
459 OCPlatform::sendResponse(pResponse);
464 //int start_fanserver(void*) // 1
465 void *start_fanserver(void *d) // 2
467 // Create PlatformConfig object
470 OC::ServiceType::InProc,
472 "0.0.0.0", // By setting to "0.0.0.0", it binds to all available interfaces
473 0, // Uses randomly available port
474 OC::QualityOfService::LowQos
477 OCPlatform::Configure(cfg);
479 printf("start_fanserver [mosquitto] Null\n");
482 FanResource myFanResource;
483 mosquitto_lib_init();
484 myMosquitto = mosquitto_new("MQTT plug-in", true, NULL);
487 printf("[mosquitto] Null\n");
488 printf("You need to install mqtt broker\n");
492 printf("Mosquitto is working\n");
495 if (mosquitto_connect(myMosquitto, "127.0.0.1", 1883, 60) != MOSQ_ERR_SUCCESS)
497 printf("Mosquitto Connection is failed.\n");
498 pthread_exit((void *)0);
500 printf("Mosquitto Connection is done.\n");
501 myFanResource.createResource();
504 // Converts date/time to a structure
505 tblock = localtime(&timer);
506 // Output ASCII data/time
507 printf("FanReousrce reigishter time is: %s", asctime(tblock));
514 catch (OCException e)
518 // No explicit call to stop the platform.
519 // When OCPlatform destructor is invoked, internally we do platform cleanup
520 mosquitto_destroy(myMosquitto);
522 mosquitto_lib_cleanup();
523 printf("start_fanserver finish\n");
524 pthread_exit((void *)0);