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"};
66 std::string protocolIndependentID = "b0ed9259-ec95-4ac6-8f62-241d0da02683";
68 // OCPlatformInfo Contains all the platform info to be stored
69 OCPlatformInfo platformInfo;
71 // Specifies secure or non-secure
72 // false: non-secure resource
73 // true: secure resource
74 bool isSecure = false;
76 /// Specifies whether Entity handler is going to do slow response or not
77 bool isSlowResponse = false;
79 // Forward declaring the entityHandler
81 /// This class represents a single resource named 'lightResource'. This resource has
82 /// one simple attribute, power
88 /// Access this property from a TB client
90 std::string m_lightUri;
91 OCResourceHandle m_resourceHandle;
92 OCRepresentation m_lightRep;
97 :m_power(""), m_lightUri("/a/light") {
98 // Initialize representation
99 m_lightRep.setUri(m_lightUri);
101 m_lightRep.setValue("power", m_power);
104 /* Note that this does not need to be a member function: for classes you do not have
105 access to, you can accomplish this with a free function: */
107 /// This function internally calls registerResource API.
108 void createResource()
110 std::string resourceURI = m_lightUri; //URI of the resource
111 std::string resourceTypeName = "core.light"; //resource type name. In this case, it is light
112 std::string resourceInterface = DEFAULT_INTERFACE; // resource interface.
114 EntityHandler cb = std::bind(&LightResource::entityHandler, this,PH::_1);
116 // This will internally create and register the resource.
117 OCStackResult result = OCPlatform::registerResource(
118 m_resourceHandle, resourceURI, resourceTypeName,
119 resourceInterface, cb, OC_DISCOVERABLE | OC_OBSERVABLE);
121 if (OC_STACK_OK != result)
123 cout << "Resource creation was unsuccessful\n";
127 OCResourceHandle getHandle()
129 return m_resourceHandle;
132 // Puts representation.
133 // Gets values from the representation and
134 // updates the internal state
135 void put(OCRepresentation& rep)
138 if (rep.getValue("power", m_power))
140 cout << "\t\t\t\t" << "power: " << m_power << endl;
144 cout << "\t\t\t\t" << "power not found in the representation" << endl;
149 cout << e.what() << endl;
154 // Post representation.
155 // Post can create new resource or simply act like put.
156 // Gets values from the representation and
157 // updates the internal state
158 OCRepresentation post(OCRepresentation& rep)
165 // gets the updated representation.
166 // Updates the representation with latest internal state before
168 OCRepresentation get()
170 m_lightRep.setValue("power", m_power);
175 void addType(const std::string& type) const
177 OCStackResult result = OCPlatform::bindTypeToResource(m_resourceHandle, type);
178 if (OC_STACK_OK != result)
180 cout << "Binding TypeName to Resource was unsuccessful\n";
184 void addInterface(const std::string& interface) const
186 OCStackResult result = OCPlatform::bindInterfaceToResource(m_resourceHandle, interface);
187 if (OC_STACK_OK != result)
189 cout << "Binding TypeName to Resource was unsuccessful\n";
194 // This is just a sample implementation of entity handler.
195 // Entity handler can be implemented in several ways by the manufacturer
196 OCEntityHandlerResult entityHandler(std::shared_ptr<OCResourceRequest> request)
198 cout << "\tIn Server CPP entity handler:\n";
199 OCEntityHandlerResult ehResult = OC_EH_ERROR;
202 // Get the request type and request flag
203 std::string requestType = request->getRequestType();
204 int requestFlag = request->getRequestHandlerFlag();
206 if(requestFlag & RequestHandlerFlag::RequestFlag)
208 cout << "\t\trequestFlag : Request\n";
209 auto pResponse = std::make_shared<OC::OCResourceResponse>();
210 pResponse->setRequestHandle(request->getRequestHandle());
211 pResponse->setResourceHandle(request->getResourceHandle());
213 // If the request type is GET
214 if(requestType == "GET")
216 cout << "\t\t\trequestType : GET\n";
217 if(isSlowResponse) // Slow response case
219 static int startedThread = 0;
222 std::thread t(handleSlowResponse, (void *)this, request);
226 ehResult = OC_EH_SLOW;
228 else // normal response case.
231 pResponse->setResponseResult(OC_EH_OK);
232 pResponse->setResourceRepresentation(get());
233 if(OC_STACK_OK == OCPlatform::sendResponse(pResponse))
239 else if(requestType == "PUT")
241 cout << "\t\t\trequestType : PUT\n";
242 OCRepresentation rep = request->getResourceRepresentation();
244 // Do related operations related to PUT request
245 // Update the lightResource
248 pResponse->setResponseResult(OC_EH_OK);
249 pResponse->setResourceRepresentation(get());
250 if(OC_STACK_OK == OCPlatform::sendResponse(pResponse))
255 else if(requestType == "POST")
257 cout << "\t\t\trequestType : POST\n";
259 OCRepresentation rep = request->getResourceRepresentation();
261 // Do related operations related to POST request
262 OCRepresentation rep_post = post(rep);
263 pResponse->setResourceRepresentation(rep_post);
265 if(rep_post.hasAttribute("createduri"))
267 pResponse->setResponseResult(OC_EH_RESOURCE_CREATED);
268 pResponse->setNewResourceUri(rep_post.getValue<std::string>("createduri"));
271 if(OC_STACK_OK == OCPlatform::sendResponse(pResponse))
276 else if(requestType == "DELETE")
278 // DELETE request operations
284 std::cout << "Request invalid" << std::endl;
291 void * handleSlowResponse (void *param, std::shared_ptr<OCResourceRequest> pRequest)
293 // This function handles slow response case
294 LightResource* lightPtr = (LightResource*) param;
295 // Induce a case for slow response by using sleep
296 std::cout << "SLOW response" << std::endl;
299 auto pResponse = std::make_shared<OC::OCResourceResponse>();
300 pResponse->setRequestHandle(pRequest->getRequestHandle());
301 pResponse->setResourceHandle(pRequest->getResourceHandle());
302 pResponse->setResourceRepresentation(lightPtr->get());
304 pResponse->setResponseResult(OC_EH_OK);
306 // Set the slow response flag back to false
307 isSlowResponse = false;
308 OCPlatform::sendResponse(pResponse);
312 void DeletePlatformInfo()
314 delete[] platformInfo.platformID;
315 delete[] platformInfo.manufacturerName;
316 delete[] platformInfo.manufacturerUrl;
317 delete[] platformInfo.modelNumber;
318 delete[] platformInfo.dateOfManufacture;
319 delete[] platformInfo.platformVersion;
320 delete[] platformInfo.operatingSystemVersion;
321 delete[] platformInfo.hardwareVersion;
322 delete[] platformInfo.firmwareVersion;
323 delete[] platformInfo.supportUrl;
324 delete[] platformInfo.systemTime;
327 void DuplicateString(char ** targetString, std::string sourceString)
329 *targetString = new char[sourceString.length() + 1];
330 strncpy(*targetString, sourceString.c_str(), (sourceString.length() + 1));
333 OCStackResult SetPlatformInfo(std::string platformID, std::string manufacturerName,
334 std::string manufacturerUrl, std::string modelNumber, std::string dateOfManufacture,
335 std::string platformVersion, std::string operatingSystemVersion,
336 std::string hardwareVersion, std::string firmwareVersion, std::string supportUrl,
337 std::string systemTime)
339 DuplicateString(&platformInfo.platformID, platformID);
340 DuplicateString(&platformInfo.manufacturerName, manufacturerName);
341 DuplicateString(&platformInfo.manufacturerUrl, manufacturerUrl);
342 DuplicateString(&platformInfo.modelNumber, modelNumber);
343 DuplicateString(&platformInfo.dateOfManufacture, dateOfManufacture);
344 DuplicateString(&platformInfo.platformVersion, platformVersion);
345 DuplicateString(&platformInfo.operatingSystemVersion, operatingSystemVersion);
346 DuplicateString(&platformInfo.hardwareVersion, hardwareVersion);
347 DuplicateString(&platformInfo.firmwareVersion, firmwareVersion);
348 DuplicateString(&platformInfo.supportUrl, supportUrl);
349 DuplicateString(&platformInfo.systemTime, systemTime);
354 OCStackResult SetDeviceInfo()
356 OCStackResult result = OCPlatform::setPropertyValue(PAYLOAD_TYPE_DEVICE, OC_RSRVD_DEVICE_NAME,
358 if (result != OC_STACK_OK)
360 cout << "Failed to set device name" << endl;
364 result = OCPlatform::setPropertyValue(PAYLOAD_TYPE_DEVICE, OC_RSRVD_DATA_MODEL_VERSION,
366 if (result != OC_STACK_OK)
368 cout << "Failed to set data model versions" << endl;
372 result = OCPlatform::setPropertyValue(PAYLOAD_TYPE_DEVICE, OC_RSRVD_SPEC_VERSION, specVersion);
373 if (result != OC_STACK_OK)
375 cout << "Failed to set spec version" << endl;
379 result = OCPlatform::setPropertyValue(PAYLOAD_TYPE_DEVICE, OC_RSRVD_PROTOCOL_INDEPENDENT_ID,
380 protocolIndependentID);
381 if (result != OC_STACK_OK)
383 cout << "Failed to set piid" << endl;
390 int main(int /*argc*/, char** /*argv[]*/)
392 // Create PlatformConfig object
394 OC::ServiceType::InProc,
395 OC::ModeType::Server,
396 "0.0.0.0", // By setting to "0.0.0.0", it binds to all available interfaces
397 0, // Uses randomly available port
398 OC::QualityOfService::LowQos
401 OCPlatform::Configure(cfg);
402 std::cout << "Starting server & setting platform info\n";
404 OCStackResult result = SetPlatformInfo(platformId, manufacturerName, manufacturerLink,
405 modelNumber, dateOfManufacture, platformVersion, operatingSystemVersion,
406 hardwareVersion, firmwareVersion, supportLink, systemTime);
408 result = OCPlatform::registerPlatformInfo(platformInfo);
410 if (result != OC_STACK_OK)
412 std::cout << "Platform Registration failed\n";
416 result = SetDeviceInfo();
418 if (result != OC_STACK_OK)
420 std::cout << "Device Registration failed\n";
426 // Create the instance of the resource class
427 // (in this case instance of class 'LightResource').
428 LightResource myLight;
430 // Invoke createResource function of class light.
431 myLight.createResource();
433 myLight.addType(std::string("core.brightlight"));
434 myLight.addInterface(std::string(LINK_INTERFACE));
436 DeletePlatformInfo();
438 // A condition variable will free the mutex it is given, then do a non-
439 // intensive block until 'notify' is called on it. In this case, since we
440 // don't ever call cv.notify, this should be a non-processor intensive version
443 std::condition_variable cv;
444 std::unique_lock<std::mutex> lock(blocker);
447 catch(OCException& e)
449 oclog() << "Exception in main: "<< e.what();
452 // No explicit call to stop the platform.
453 // When OCPlatform::destructor is invoked, internally we do platform cleanup