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 //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
21 /// The purpose of this server is to simulate a refrigerator that contains a device resource for
22 /// its description, a light resource for the internal light, and 2 door resources for the purpose
23 /// of representing the doors attached to this fridge. This is used by the fridgeclient to
24 /// demonstrate using std::bind to attach to instances of a class as well as using
25 /// constructResourceObject
32 #include "OCPlatform.h"
34 #include "ocpayload.h"
37 namespace PH = std::placeholders;
39 // Option ID for API version and client token
40 const uint16_t API_VERSION = 2048;
41 const uint16_t TOKEN = 3000;
43 // Setting API version and token (shared out of band with client)
44 // This assumes the fact that this server responds
45 // only with a server with below version and token
46 const std::string FRIDGE_CLIENT_API_VERSION = "v.1.0";
47 const std::string FRIDGE_CLIENT_TOKEN = "21ae43gf";
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 Fridge 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;
73 OCResourceHandle m_resourceHandle;
74 OCRepresentation m_rep;
75 virtual OCEntityHandlerResult entityHandler(std::shared_ptr<OCResourceRequest> request)=0;
78 class DeviceResource : public Resource
82 DeviceResource():m_modelName{}
84 std::string resourceURI = "/device";
85 std::string resourceTypeName = "intel.fridge";
86 std::string resourceInterface = DEFAULT_INTERFACE;
87 EntityHandler cb = std::bind(&DeviceResource::entityHandler, this,PH::_1);
89 EntityHandler defaultEH = std::bind(&DeviceResource::defaultEntityHandler
92 std::cout << "Setting device default entity handler\n";
93 OCPlatform::setDefaultDeviceEntityHandler(defaultEH);
95 uint8_t resourceProperty = OC_DISCOVERABLE;
96 OCStackResult result = OCPlatform::registerResource(m_resourceHandle,
103 if(OC_STACK_OK != result)
105 throw std::runtime_error(
106 std::string("Device Resource failed to start")+std::to_string(result));
110 OCRepresentation get()
112 m_rep.setValue("device_name", std::string("Intel Powered 2 door, 1 light refrigerator"));
116 OCStackResult deleteDeviceResource()
118 OCStackResult result = OCPlatform::unregisterResource(m_resourceHandle);
119 if(OC_STACK_OK != result)
121 throw std::runtime_error(
122 std::string("Device Resource failed to unregister/delete") + std::to_string(result));
127 std::string m_modelName;
129 virtual OCEntityHandlerResult entityHandler(std::shared_ptr<OCResourceRequest> request)
131 OCEntityHandlerResult ehResult = OC_EH_ERROR;
134 // Get the header options from the request
135 HeaderOptions headerOptions = request->getHeaderOptions();
136 std::string clientAPIVersion;
137 std::string clientToken;
139 // Get the message ID from the request
140 std::cout << " MessageID: " << request->getMessageID() << std::endl;
142 // Search the header options map and look for API version and Client token
143 for (auto it = headerOptions.begin(); it != headerOptions.end(); ++it)
145 uint16_t optionID = it->getOptionID();
146 if(optionID == API_VERSION)
148 clientAPIVersion = it->getOptionData();
149 std::cout << " Client API version: " << clientAPIVersion << std::endl;
151 else if(optionID == TOKEN)
153 clientToken = it->getOptionData();
154 std::cout << " Client token: " << clientToken << std::endl;
158 std::cout << " Invalid header option " << std::endl;
162 // In this case Server entity handler verifies API version
163 // and client token. If they are valid, client requests are handled.
164 if(clientAPIVersion == FRIDGE_CLIENT_API_VERSION && clientToken == FRIDGE_CLIENT_TOKEN)
166 HeaderOptions serverHeaderOptions;
169 // Set API version from server side
170 HeaderOption::OCHeaderOption apiVersion(API_VERSION, FRIDGE_CLIENT_API_VERSION);
171 serverHeaderOptions.push_back(apiVersion);
173 catch(OCException& e)
175 std::cout << "Error creating HeaderOption in server: " << e.what() << std::endl;
178 if(request->getRequestHandlerFlag() == RequestHandlerFlag::RequestFlag)
180 auto pResponse = std::make_shared<OC::OCResourceResponse>();
181 pResponse->setRequestHandle(request->getRequestHandle());
182 pResponse->setResourceHandle(request->getResourceHandle());
183 pResponse->setHeaderOptions(serverHeaderOptions);
185 if(request->getRequestType() == "GET")
187 std::cout<<"DeviceResource Get Request"<<std::endl;
189 pResponse->setResponseResult(OC_EH_OK);
190 pResponse->setResourceRepresentation(get(), "");
191 if(OC_STACK_OK == OCPlatform::sendResponse(pResponse))
196 else if(request->getRequestType() == "DELETE")
198 std::cout<<"DeviceResource Delete Request"<<std::endl;
199 if(deleteDeviceResource() == OC_STACK_OK)
202 pResponse->setResponseResult(OC_EH_RESOURCE_DELETED);
207 pResponse->setResponseResult(OC_EH_ERROR);
208 ehResult = OC_EH_ERROR;
210 OCPlatform::sendResponse(pResponse);
214 std::cout <<"DeviceResource unsupported request type "
215 << request->getRequestType() << std::endl;
216 pResponse->setResponseResult(OC_EH_ERROR);
217 OCPlatform::sendResponse(pResponse);
218 ehResult = OC_EH_ERROR;
223 std::cout << "DeviceResource unsupported request flag" <<std::endl;
228 std::cout << "Unsupported/invalid header options/values" << std::endl;
235 virtual OCEntityHandlerResult defaultEntityHandler(std::shared_ptr<OCResourceRequest> request)
237 OCEntityHandlerResult ehResult = OC_EH_ERROR;
240 std::cout << "In Default Entity Handler, uri received: "
241 << request->getResourceUri() << std::endl;
243 if(request->getRequestHandlerFlag() == RequestHandlerFlag::RequestFlag)
245 auto pResponse = std::make_shared<OC::OCResourceResponse>();
246 pResponse->setRequestHandle(request->getRequestHandle());
247 pResponse->setResourceHandle(request->getResourceHandle());
249 if(request->getRequestType() == "GET")
251 std::cout<<"Default Entity Handler: Get Request"<<std::endl;
253 pResponse->setResourceRepresentation(get(), "");
254 if(OC_STACK_OK == OCPlatform::sendResponse(pResponse))
261 std::cout <<"Default Entity Handler: unsupported request type "
262 << request->getRequestType() << std::endl;
263 pResponse->setResponseResult(OC_EH_ERROR);
264 OCPlatform::sendResponse(pResponse);
265 ehResult = OC_EH_ERROR;
270 std::cout << "Default Entity Handler: unsupported request flag" <<std::endl;
279 class LightResource : public Resource
282 LightResource() : m_isOn(false)
284 std::string resourceURI = "/light";
285 std::string resourceTypeName = "intel.fridge.light";
286 std::string resourceInterface = DEFAULT_INTERFACE;
287 EntityHandler cb = std::bind(&LightResource::entityHandler, this,PH::_1);
288 uint8_t resourceProperty = 0;
289 OCStackResult result = OCPlatform::registerResource(m_resourceHandle,
296 if(OC_STACK_OK != result)
298 throw std::runtime_error(
299 std::string("Light Resource failed to start")+std::to_string(result));
303 OCRepresentation get()
305 m_rep.setValue("on", m_isOn);
309 void put(const OCRepresentation& rep)
311 rep.getValue("on", m_isOn);
316 virtual OCEntityHandlerResult entityHandler(std::shared_ptr<OCResourceRequest> request)
318 OCEntityHandlerResult ehResult = OC_EH_ERROR;
321 std::cout << "In entity handler for Light, URI is : "
322 << request->getResourceUri() << std::endl;
324 if(request->getRequestHandlerFlag() == RequestHandlerFlag::RequestFlag)
326 auto pResponse = std::make_shared<OC::OCResourceResponse>();
327 pResponse->setRequestHandle(request->getRequestHandle());
328 pResponse->setResourceHandle(request->getResourceHandle());
330 if(request->getRequestType() == "GET")
332 std::cout<<"Light Get Request"<<std::endl;
334 pResponse->setResourceRepresentation(get(), "");
335 if(OC_STACK_OK == OCPlatform::sendResponse(pResponse))
340 else if(request->getRequestType() == "PUT")
342 std::cout <<"Light Put Request"<<std::endl;
343 put(request->getResourceRepresentation());
345 pResponse->setResourceRepresentation(get(), "");
346 if(OC_STACK_OK == OCPlatform::sendResponse(pResponse))
353 std::cout << "Light unsupported request type"
354 << request->getRequestType() << std::endl;
355 pResponse->setResponseResult(OC_EH_ERROR);
356 OCPlatform::sendResponse(pResponse);
357 ehResult = OC_EH_ERROR;
362 std::cout << "Light unsupported request flag" <<std::endl;
370 class DoorResource : public Resource
373 DoorResource(const std::string& side):m_isOpen{false}, m_side(side)
376 std::string resourceURI = "/door/"+ side;
377 std::string resourceTypeName = "intel.fridge.door";
378 std::string resourceInterface = DEFAULT_INTERFACE;
379 EntityHandler cb = std::bind(&DoorResource::entityHandler, this,PH::_1);
381 uint8_t resourceProperty = 0;
382 OCStackResult result = OCPlatform::registerResource(m_resourceHandle,
389 if(OC_STACK_OK != result)
391 throw std::runtime_error(
392 std::string("Door Resource failed to start")+std::to_string(result));
397 OCRepresentation get()
399 m_rep.setValue("open", m_isOpen);
400 m_rep.setValue("side", m_side);
404 void put(const OCRepresentation& rep)
406 rep.getValue("open", m_isOpen);
407 // Note, we won't let the user change the door side!
412 virtual OCEntityHandlerResult entityHandler(std::shared_ptr<OCResourceRequest> request)
414 std::cout << "EH of door invoked " << std::endl;
415 OCEntityHandlerResult ehResult = OC_EH_ERROR;
419 std::cout << "In entity handler for Door, URI is : "
420 << request->getResourceUri() << std::endl;
422 if(request->getRequestHandlerFlag() == RequestHandlerFlag::RequestFlag)
424 auto pResponse = std::make_shared<OC::OCResourceResponse>();
425 pResponse->setRequestHandle(request->getRequestHandle());
426 pResponse->setResourceHandle(request->getResourceHandle());
428 if(request->getRequestType() == "GET")
430 // note that we know the side because std::bind gives us the
431 // appropriate object
432 std::cout<< m_side << " Door Get Request"<<std::endl;
434 pResponse->setResourceRepresentation(get(), "");
435 if(OC_STACK_OK == OCPlatform::sendResponse(pResponse))
440 else if(request->getRequestType() == "PUT")
442 std::cout << m_side <<" Door Put Request"<<std::endl;
443 put(request->getResourceRepresentation());
445 pResponse->setResourceRepresentation(get(),"");
446 if(OC_STACK_OK == OCPlatform::sendResponse(pResponse))
453 std::cout <<m_side<<" Door unsupported request type "
454 << request->getRequestType() << std::endl;
455 pResponse->setResponseResult(OC_EH_ERROR);
456 OCPlatform::sendResponse(pResponse);
457 ehResult = OC_EH_ERROR;
462 std::cout << "Door unsupported request flag" <<std::endl;
483 LightResource m_light;
484 DeviceResource m_device;
485 DoorResource m_leftdoor;
486 DoorResource m_rightdoor;
489 void DeletePlatformInfo()
491 delete[] platformInfo.platformID;
492 delete[] platformInfo.manufacturerName;
493 delete[] platformInfo.manufacturerUrl;
494 delete[] platformInfo.modelNumber;
495 delete[] platformInfo.dateOfManufacture;
496 delete[] platformInfo.platformVersion;
497 delete[] platformInfo.operatingSystemVersion;
498 delete[] platformInfo.hardwareVersion;
499 delete[] platformInfo.firmwareVersion;
500 delete[] platformInfo.supportUrl;
501 delete[] platformInfo.systemTime;
504 void DuplicateString(char ** targetString, std::string sourceString)
506 *targetString = new char[sourceString.length() + 1];
507 strncpy(*targetString, sourceString.c_str(), (sourceString.length() + 1));
510 OCStackResult SetPlatformInfo(std::string platformID, std::string manufacturerName,
511 std::string manufacturerUrl, std::string modelNumber, std::string dateOfManufacture,
512 std::string platformVersion, std::string operatingSystemVersion, std::string hardwareVersion,
513 std::string firmwareVersion, std::string supportUrl, std::string systemTime)
515 DuplicateString(&platformInfo.platformID, platformID);
516 DuplicateString(&platformInfo.manufacturerName, manufacturerName);
517 DuplicateString(&platformInfo.manufacturerUrl, manufacturerUrl);
518 DuplicateString(&platformInfo.modelNumber, modelNumber);
519 DuplicateString(&platformInfo.dateOfManufacture, dateOfManufacture);
520 DuplicateString(&platformInfo.platformVersion, platformVersion);
521 DuplicateString(&platformInfo.operatingSystemVersion, operatingSystemVersion);
522 DuplicateString(&platformInfo.hardwareVersion, hardwareVersion);
523 DuplicateString(&platformInfo.firmwareVersion, firmwareVersion);
524 DuplicateString(&platformInfo.supportUrl, supportUrl);
525 DuplicateString(&platformInfo.systemTime, systemTime);
530 OCStackResult SetDeviceInfo()
532 OCStackResult result = OCPlatform::setPropertyValue(PAYLOAD_TYPE_DEVICE, OC_RSRVD_DEVICE_NAME,
534 if (result != OC_STACK_OK)
536 std::cout << "Failed to set device name" << std::endl;
540 result = OCPlatform::setPropertyValue(PAYLOAD_TYPE_DEVICE, OC_RSRVD_DATA_MODEL_VERSION,
542 if (result != OC_STACK_OK)
544 std::cout << "Failed to set data model versions" << std::endl;
548 result = OCPlatform::setPropertyValue(PAYLOAD_TYPE_DEVICE, OC_RSRVD_SPEC_VERSION, specVersion);
549 if (result != OC_STACK_OK)
551 std::cout << "Failed to set spec version" << std::endl;
564 "0.0.0.0", // By setting to "0.0.0.0", it binds to all available interfaces
565 0, // Uses randomly available port
566 QualityOfService::LowQos
569 OCPlatform::Configure(cfg);
572 std::cout << "Starting server & setting platform info\n";
574 OCStackResult result = SetPlatformInfo(platformId, manufacturerName, manufacturerLink,
575 modelNumber, dateOfManufacture, platformVersion, operatingSystemVersion,
576 hardwareVersion, firmwareVersion, supportLink, systemTime);
578 result = OCPlatform::registerPlatformInfo(platformInfo);
580 if (result != OC_STACK_OK)
582 std::cout << "Platform Registration failed\n";
586 result = SetDeviceInfo();
588 if (result != OC_STACK_OK)
590 std::cout << "Device Registration failed\n";
594 DeletePlatformInfo();
595 // we will keep the server alive for at most 30 minutes
596 std::this_thread::sleep_for(std::chrono::minutes(30));