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 "lightserver.h"
39 namespace PH = std::placeholders;
41 time_t timer; // Define the timer
42 struct tm *tblock; // Define a structure for time block
45 void *ChangeLightRepresentation (void *param);
47 // Specifies where to notify all observers or list of observers
48 // 0 - notifies all observers
49 // 1 - notifies list of observers
50 int isListOfObservers = 0;
52 // Forward declaring the entityHandler
54 /// This class represents a single resource named 'lightResource'. This resource has
55 /// two simple properties named 'state' and 'power'
59 // Forward declaring the entityHandler
60 // void entityHandler(std::shared_ptr<OCResourceRequest> request,
61 // std::shared_ptr<OCResourceResponse> response);
63 /// This class represents a single resource named 'lightResource'. This resource has
64 /// two simple properties named 'state' and 'power'
65 typedef struct plugin_data_t plugin_data_t;
70 pthread_t m_thread; // 2
79 /// Access this property from a TB client
84 std::string m_lightUri;
85 OCResourceHandle m_resourceHandle;
86 OCRepresentation m_lightRep;
87 ObservationIds m_interestedObservers;
91 LightResource(): m_name("John's light"), m_state(false), m_power(0), m_lightUri("/a/light")
93 // Initialize representation
94 m_lightRep.setUri(m_lightUri);
96 m_lightRep.setValue("state", m_state);
97 m_lightRep.setValue("power", m_power);
98 m_lightRep.setValue("name", m_name);
102 /* Note that this does not need to be a member function: for classes you do not have
103 access to, you can accomplish this with a free function: */
105 /// This function internally calls registerResource API.
106 void createResource()
108 std::string resourceURI = m_lightUri; // URI of the resource
109 std::string resourceTypeName = "core.light"; // resource type name. In this case, it is light
110 std::string resourceInterface = DEFAULT_INTERFACE; // resource interface.
112 // OCResourceProperty is defined ocstack.h
113 uint8_t resourceProperty = OC_DISCOVERABLE | OC_OBSERVABLE;
115 EntityHandler cb = std::bind(&LightResource::entityHandler, this, PH::_1, PH::_2);
117 // This will internally create and register the resource.
118 OCStackResult result = OCPlatform::registerResource(
119 m_resourceHandle, resourceURI, resourceTypeName,
120 resourceInterface, cb, resourceProperty);
122 if (OC_STACK_OK != result)
124 cout << "Resource creation was unsuccessful\n";
128 OCStackResult createResource1()
130 std::string resourceURI = "/a/light1"; // URI of the resource
131 std::string resourceTypeName = "core.light"; // resource type name. In this case, it is light
132 std::string resourceInterface = DEFAULT_INTERFACE; // resource interface.
134 // OCResourceProperty is defined ocstack.h
135 uint8_t resourceProperty = OC_DISCOVERABLE | OC_OBSERVABLE;
137 EntityHandler cb = std::bind(&LightResource::entityHandler, this, PH::_1, PH::_2);
139 OCResourceHandle resHandle;
141 // This will internally create and register the resource.
142 OCStackResult result = OCPlatform::registerResource(
143 resHandle, resourceURI, resourceTypeName,
144 resourceInterface, cb, resourceProperty);
146 if (OC_STACK_OK != result)
148 cout << "Resource creation was unsuccessful\n";
154 OCResourceHandle getHandle()
156 return m_resourceHandle;
159 // Puts representation.
160 // Gets values from the representation and
161 // updates the internal state
162 void put(OCRepresentation &rep)
166 if (rep.getValue("state", m_state))
168 cout << "\t\t\t\t" << "state: " << m_state << endl;
172 cout << "\t\t\t\t" << "state not found in the representation" << endl;
175 if (rep.getValue("power", m_power))
177 cout << "\t\t\t\t" << "power: " << m_power << endl;
181 cout << "\t\t\t\t" << "power not found in the representation" << endl;
186 cout << e.what() << endl;
191 // Post representation.
192 // Post can create new resource or simply act like put.
193 // Gets values from the representation and
194 // updates the internal state
195 OCRepresentation post(OCRepresentation &rep)
197 static int first = 1;
199 // for the first time it tries to create a resource
204 if (OC_STACK_OK == createResource1())
206 OCRepresentation rep1;
207 rep1.setValue("createduri", std::string("/a/light1"));
213 // from second time onwards it just puts
219 // gets the updated representation.
220 // Updates the representation with latest internal state before
222 OCRepresentation get()
224 m_lightRep.setValue("state", m_state);
225 m_lightRep.setValue("power", m_power);
231 void addType(const std::string &type) const
233 OCStackResult result = OCPlatform::bindTypeToResource(m_resourceHandle, type);
234 if (OC_STACK_OK != result)
236 cout << "Binding TypeName to Resource was unsuccessful\n";
240 void addInterface(const std::string &interface) const
242 OCStackResult result = OCPlatform::bindInterfaceToResource(m_resourceHandle, interface);
243 if (OC_STACK_OK != result)
245 cout << "Binding TypeName to Resource was unsuccessful\n";
250 // This is just a sample implementation of entity handler.
251 // Entity handler can be implemented in several ways by the manufacturer
252 OCEntityHandlerResult entityHandler(std::shared_ptr<OCResourceRequest> request,
253 std::shared_ptr<OCResourceResponse> response)
255 OCEntityHandlerResult result = OC_EH_OK;
257 cout << "\tIn Server CPP entity handler:\n";
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";
269 // entity handler to perform resource initialization operations
271 if (requestFlag & RequestHandlerFlag::RequestFlag)
273 cout << "\t\trequestFlag : Request === Handle by LightServer\n";
275 // If the request type is GET
276 if (requestType == "GET")
278 cout << "\t\t\trequestType : GET\n";
283 response->setErrorCode(200);
285 response->setResourceRepresentation(get());
288 else if (requestType == "PUT")
290 cout << "\t\t\trequestType : PUT\n";
292 OCRepresentation rep = request->getResourceRepresentation();
294 // Do related operations related to PUT request
296 // Update the lightResource
302 response->setErrorCode(200);
304 response->setResourceRepresentation(get());
308 else if (requestType == "POST")
310 cout << "\t\t\trequestType : POST\n";
312 OCRepresentation rep = request->getResourceRepresentation();
314 // Do related operations related to POST request
316 OCRepresentation rep_post = post(rep);
321 response->setErrorCode(200);
323 response->setResourceRepresentation(rep_post);
325 if (rep_post.hasAttribute("createduri"))
327 result = OC_EH_RESOURCE_CREATED;
329 response->setNewResourceUri(rep_post.getValue<std::string>("createduri"));
334 // POST request operations
336 else if (requestType == "DELETE")
338 // DELETE request operations
342 if (requestFlag & RequestHandlerFlag::ObserverFlag)
344 ObservationInfo observationInfo = request->getObservationInfo();
345 if (ObserveAction::ObserveRegister == observationInfo.action)
347 m_interestedObservers.push_back(observationInfo.obsId);
349 else if (ObserveAction::ObserveUnregister == observationInfo.action)
351 m_interestedObservers.erase(std::remove(
352 m_interestedObservers.begin(),
353 m_interestedObservers.end(),
354 observationInfo.obsId),
355 m_interestedObservers.end());
360 cout << "\t\trequestFlag : Observer\n";
362 static int startedThread = 0;
364 // Observation happens on a different thread in ChangeLightRepresentation function.
365 // If we have not created the thread already, we will create one here.
368 pthread_create (&threadId, NULL, ChangeLightRepresentation, (void *)this);
375 std::cout << "Request invalid" << std::endl;
382 // Create the instance of the resource class (in this case instance of class 'LightResource').
383 struct mosquitto *myMosquitto;
385 // ChangeLightRepresentaion is an observation function,
386 // which notifies any changes to the resource to stack
387 // via notifyObservers
388 void *ChangeLightRepresentation (void *param)
390 LightResource *lightPtr = (LightResource *) param;
392 // This function continuously monitors for the changes
399 // If under observation if there are any changes to the light resource
400 // we call notifyObservors
402 // For demostration we are changing the power value and notifying.
403 lightPtr->m_power += 10;
405 cout << "\nPower updated to : " << lightPtr->m_power << endl;
406 cout << "Notifying observers with resource handle: " << lightPtr->getHandle() << endl;
408 OCStackResult result = OC_STACK_OK;
410 if (isListOfObservers)
412 std::shared_ptr<OCResourceResponse> resourceResponse(new OCResourceResponse());
414 resourceResponse->setErrorCode(200);
415 resourceResponse->setResourceRepresentation(lightPtr->get(), DEFAULT_INTERFACE);
417 result = OCPlatform::notifyListOfObservers( lightPtr->getHandle(),
418 lightPtr->m_interestedObservers,
423 result = OCPlatform::notifyAllObservers(lightPtr->getHandle());
426 if (OC_STACK_NO_OBSERVERS == result)
428 cout << "No More observers, stopping notifications" << endl;
440 //int start_lightserver(void*) // 1
441 void *start_lightserver(void *d) // 2
443 /*PlatformConfig cfg;
444 cfg.ipAddress = "192.168.2.5";
446 cfg.mode = ModeType::Server;
447 cfg.serviceType = ServiceType::InProc;*/
448 // PlatformConfig cfg
450 // OC::ServiceType::InProc,
451 // OC::ModeType::Server,
454 // OC::QualityOfService::NonConfirmable
457 // Create PlatformConfig object
459 // Create a OCPlatform instance.
460 // Note: Platform creation is synchronous call.
462 // Create PlatformConfig object
465 OC::ServiceType::InProc,
466 OC::ModeType::Server,
467 "0.0.0.0", // By setting to "0.0.0.0", it binds to all available interfaces
468 0, // Uses randomly available port
469 OC::QualityOfService::LowQos
472 OCPlatform::Configure(cfg);
474 printf("start_fanserver [mosquitto] Null\n");
477 LightResource myLightResource;
478 mosquitto_lib_init();
479 myMosquitto = mosquitto_new("MQTT plug-in", true, NULL);
482 printf("[mosquitto] Null\n");
483 printf("You need to install mqtt broker\n");
487 printf("Mosquitto is working\n");
490 //plugin_data_t *data = (plugin_data_t *)d;
491 //OCPlatform *platform = (OCPlatform*)data->str;
492 //myLightResource.m_platform = (OCPlatform*)data->str;
493 //OCPlatform platform(cfg);
494 // Invoke createResource function of class light.
496 //mosquitto_connect(myMosquitto, "192.168.2.5", 1883, 60);
497 mosquitto_connect(myMosquitto, "127.0.0.1", 1883, 60);
498 printf("Mosquitto Connection is done\n");
499 myLightResource.createResource();
500 //myLightResource.addType(std::string("core.light"));
501 //myLightResource.addInterface(std::string("oc.mi.ll"));
504 // Converts date/time to a structure
505 tblock = localtime(&timer);
506 // Output ASCII data/time
507 printf("LightReousrce 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_lightserver finish\n");
524 pthread_exit((void *)0);