1 //******************************************************************
3 // Copyright 2014 Intel Mobile Communications GmbH All Rights Reserved.
4 // Copyright 2014 Samsung Electronics All Rights Reserved.
6 //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
8 // Licensed under the Apache License, Version 2.0 (the "License");
9 // you may not use this file except in compliance with the License.
10 // You may obtain a copy of the License at
12 // http://www.apache.org/licenses/LICENSE-2.0
14 // Unless required by applicable law or agreed to in writing, software
15 // distributed under the License is distributed on an "AS IS" BASIS,
16 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17 // See the License for the specific language governing permissions and
18 // limitations under the License.
20 //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
23 /// This sample provides steps to define an interface for a resource
24 /// (properties and methods) and host this resource on the server.
26 #include "iotivity_config.h"
35 #include <condition_variable>
37 #include "OCPlatform.h"
39 #include "ocpayload.h"
43 namespace PH = std::placeholders;
46 void * ChangeLightRepresentation (void *param);
47 void * handleSlowResponse (void *param, std::shared_ptr<OCResourceRequest> pRequest);
49 // Set of strings for each of platform Info fields
50 std::string platformId = "0A3E0D6F-DBF5-404E-8719-D6880042463A";
51 std::string manufacturerName = "OCF";
52 std::string manufacturerLink = "https://www.iotivity.org";
53 std::string modelNumber = "myModelNumber";
54 std::string dateOfManufacture = "2016-01-15";
55 std::string platformVersion = "myPlatformVersion";
56 std::string operatingSystemVersion = "myOS";
57 std::string hardwareVersion = "myHardwareVersion";
58 std::string firmwareVersion = "1.0";
59 std::string supportLink = "https://www.iotivity.org";
60 std::string systemTime = "2016-01-15T11.01";
62 // Set of strings for each of device info fields
63 std::string deviceName = "IoTivity Light Server";
64 std::string specVersion = "core.1.1.0";
65 std::vector<std::string> dataModelVersions = {"res.1.1.0"};
67 // OCPlatformInfo Contains all the platform info to be stored
68 OCPlatformInfo platformInfo;
70 // Specifies secure or non-secure
71 // false: non-secure resource
72 // true: secure resource
73 bool isSecure = false;
75 /// Specifies whether Entity handler is going to do slow response or not
76 bool isSlowResponse = false;
78 // Forward declaring the entityHandler
80 /// This class represents a single resource named 'lightResource'. This resource has
81 /// one simple attribute, power
87 /// Access this property from a TB client
89 std::string m_lightUri;
90 OCResourceHandle m_resourceHandle;
91 OCRepresentation m_lightRep;
96 :m_power(""), m_lightUri("/a/light") {
97 // Initialize representation
98 m_lightRep.setUri(m_lightUri);
100 m_lightRep.setValue("power", m_power);
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_lightUri; //URI of the resource
110 std::string resourceTypeName = "core.light"; //resource type name. In this case, it is light
111 std::string resourceInterface = DEFAULT_INTERFACE; // resource interface.
113 EntityHandler cb = std::bind(&LightResource::entityHandler, this,PH::_1);
115 // This will internally create and register the resource.
116 OCStackResult result = OCPlatform::registerResource(
117 m_resourceHandle, resourceURI, resourceTypeName,
118 resourceInterface, cb, OC_DISCOVERABLE | OC_OBSERVABLE);
120 if (OC_STACK_OK != result)
122 cout << "Resource creation was unsuccessful\n";
126 OCResourceHandle getHandle()
128 return m_resourceHandle;
131 // Puts representation.
132 // Gets values from the representation and
133 // updates the internal state
134 void put(OCRepresentation& rep)
137 if (rep.getValue("power", m_power))
139 cout << "\t\t\t\t" << "power: " << m_power << endl;
143 cout << "\t\t\t\t" << "power not found in the representation" << endl;
148 cout << e.what() << endl;
153 // Post representation.
154 // Post can create new resource or simply act like put.
155 // Gets values from the representation and
156 // updates the internal state
157 OCRepresentation post(OCRepresentation& rep)
164 // gets the updated representation.
165 // Updates the representation with latest internal state before
167 OCRepresentation get()
169 m_lightRep.setValue("power", m_power);
174 void addType(const std::string& type) const
176 OCStackResult result = OCPlatform::bindTypeToResource(m_resourceHandle, type);
177 if (OC_STACK_OK != result)
179 cout << "Binding TypeName to Resource was unsuccessful\n";
183 void addInterface(const std::string& interface) const
185 OCStackResult result = OCPlatform::bindInterfaceToResource(m_resourceHandle, interface);
186 if (OC_STACK_OK != result)
188 cout << "Binding TypeName to Resource was unsuccessful\n";
193 // This is just a sample implementation of entity handler.
194 // Entity handler can be implemented in several ways by the manufacturer
195 OCEntityHandlerResult entityHandler(std::shared_ptr<OCResourceRequest> request)
197 cout << "\tIn Server CPP entity handler:\n";
198 OCEntityHandlerResult ehResult = OC_EH_ERROR;
201 // Get the request type and request flag
202 std::string requestType = request->getRequestType();
203 int requestFlag = request->getRequestHandlerFlag();
205 if(requestFlag & RequestHandlerFlag::RequestFlag)
207 cout << "\t\trequestFlag : Request\n";
208 auto pResponse = std::make_shared<OC::OCResourceResponse>();
209 pResponse->setRequestHandle(request->getRequestHandle());
210 pResponse->setResourceHandle(request->getResourceHandle());
212 // If the request type is GET
213 if(requestType == "GET")
215 cout << "\t\t\trequestType : GET\n";
216 if(isSlowResponse) // Slow response case
218 static int startedThread = 0;
221 std::thread t(handleSlowResponse, (void *)this, request);
225 ehResult = OC_EH_SLOW;
227 else // normal response case.
230 pResponse->setResponseResult(OC_EH_OK);
231 pResponse->setResourceRepresentation(get());
232 if(OC_STACK_OK == OCPlatform::sendResponse(pResponse))
238 else if(requestType == "PUT")
240 cout << "\t\t\trequestType : PUT\n";
241 OCRepresentation rep = request->getResourceRepresentation();
243 // Do related operations related to PUT request
244 // Update the lightResource
247 pResponse->setResponseResult(OC_EH_OK);
248 pResponse->setResourceRepresentation(get());
249 if(OC_STACK_OK == OCPlatform::sendResponse(pResponse))
254 else if(requestType == "POST")
256 cout << "\t\t\trequestType : POST\n";
258 OCRepresentation rep = request->getResourceRepresentation();
260 // Do related operations related to POST request
261 OCRepresentation rep_post = post(rep);
262 pResponse->setResourceRepresentation(rep_post);
264 if(rep_post.hasAttribute("createduri"))
266 pResponse->setResponseResult(OC_EH_RESOURCE_CREATED);
267 pResponse->setNewResourceUri(rep_post.getValue<std::string>("createduri"));
270 if(OC_STACK_OK == OCPlatform::sendResponse(pResponse))
275 else if(requestType == "DELETE")
277 // DELETE request operations
283 std::cout << "Request invalid" << std::endl;
290 void * handleSlowResponse (void *param, std::shared_ptr<OCResourceRequest> pRequest)
292 // This function handles slow response case
293 LightResource* lightPtr = (LightResource*) param;
294 // Induce a case for slow response by using sleep
295 std::cout << "SLOW response" << std::endl;
298 auto pResponse = std::make_shared<OC::OCResourceResponse>();
299 pResponse->setRequestHandle(pRequest->getRequestHandle());
300 pResponse->setResourceHandle(pRequest->getResourceHandle());
301 pResponse->setResourceRepresentation(lightPtr->get());
303 pResponse->setResponseResult(OC_EH_OK);
305 // Set the slow response flag back to false
306 isSlowResponse = false;
307 OCPlatform::sendResponse(pResponse);
311 void DeletePlatformInfo()
313 delete[] platformInfo.platformID;
314 delete[] platformInfo.manufacturerName;
315 delete[] platformInfo.manufacturerUrl;
316 delete[] platformInfo.modelNumber;
317 delete[] platformInfo.dateOfManufacture;
318 delete[] platformInfo.platformVersion;
319 delete[] platformInfo.operatingSystemVersion;
320 delete[] platformInfo.hardwareVersion;
321 delete[] platformInfo.firmwareVersion;
322 delete[] platformInfo.supportUrl;
323 delete[] platformInfo.systemTime;
326 void DuplicateString(char ** targetString, std::string sourceString)
328 *targetString = new char[sourceString.length() + 1];
329 strncpy(*targetString, sourceString.c_str(), (sourceString.length() + 1));
332 OCStackResult SetPlatformInfo(std::string platformID, std::string manufacturerName,
333 std::string manufacturerUrl, std::string modelNumber, std::string dateOfManufacture,
334 std::string platformVersion, std::string operatingSystemVersion,
335 std::string hardwareVersion, std::string firmwareVersion, std::string supportUrl,
336 std::string systemTime)
338 DuplicateString(&platformInfo.platformID, platformID);
339 DuplicateString(&platformInfo.manufacturerName, manufacturerName);
340 DuplicateString(&platformInfo.manufacturerUrl, manufacturerUrl);
341 DuplicateString(&platformInfo.modelNumber, modelNumber);
342 DuplicateString(&platformInfo.dateOfManufacture, dateOfManufacture);
343 DuplicateString(&platformInfo.platformVersion, platformVersion);
344 DuplicateString(&platformInfo.operatingSystemVersion, operatingSystemVersion);
345 DuplicateString(&platformInfo.hardwareVersion, hardwareVersion);
346 DuplicateString(&platformInfo.firmwareVersion, firmwareVersion);
347 DuplicateString(&platformInfo.supportUrl, supportUrl);
348 DuplicateString(&platformInfo.systemTime, systemTime);
353 OCStackResult SetDeviceInfo()
355 OCStackResult result = OCPlatform::setPropertyValue(PAYLOAD_TYPE_DEVICE, OC_RSRVD_DEVICE_NAME,
357 if (result != OC_STACK_OK)
359 cout << "Failed to set device name" << endl;
363 result = OCPlatform::setPropertyValue(PAYLOAD_TYPE_DEVICE, OC_RSRVD_DATA_MODEL_VERSION,
365 if (result != OC_STACK_OK)
367 cout << "Failed to set data model versions" << endl;
371 result = OCPlatform::setPropertyValue(PAYLOAD_TYPE_DEVICE, OC_RSRVD_SPEC_VERSION, specVersion);
372 if (result != OC_STACK_OK)
374 cout << "Failed to set spec version" << endl;
381 int main(int /*argc*/, char** /*argv[]*/)
383 // Create PlatformConfig object
385 OC::ServiceType::InProc,
386 OC::ModeType::Server,
387 "0.0.0.0", // By setting to "0.0.0.0", it binds to all available interfaces
388 0, // Uses randomly available port
389 OC::QualityOfService::LowQos
392 OCPlatform::Configure(cfg);
393 std::cout << "Starting server & setting platform info\n";
395 OCStackResult result = SetPlatformInfo(platformId, manufacturerName, manufacturerLink,
396 modelNumber, dateOfManufacture, platformVersion, operatingSystemVersion,
397 hardwareVersion, firmwareVersion, supportLink, systemTime);
399 result = OCPlatform::registerPlatformInfo(platformInfo);
401 if (result != OC_STACK_OK)
403 std::cout << "Platform Registration failed\n";
407 result = SetDeviceInfo();
409 if (result != OC_STACK_OK)
411 std::cout << "Device Registration failed\n";
417 // Create the instance of the resource class
418 // (in this case instance of class 'LightResource').
419 LightResource myLight;
421 // Invoke createResource function of class light.
422 myLight.createResource();
424 myLight.addType(std::string("core.brightlight"));
425 myLight.addInterface(std::string(LINK_INTERFACE));
427 DeletePlatformInfo();
429 // A condition variable will free the mutex it is given, then do a non-
430 // intensive block until 'notify' is called on it. In this case, since we
431 // don't ever call cv.notify, this should be a non-processor intensive version
434 std::condition_variable cv;
435 std::unique_lock<std::mutex> lock(blocker);
438 catch(OCException& e)
440 oclog() << "Exception in main: "<< e.what();
443 // No explicit call to stop the platform.
444 // When OCPlatform::destructor is invoked, internally we do platform cleanup