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 //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
22 /// This sample shows how one could create a resource (collection) with children.
28 #include <condition_variable>
30 #include "OCPlatform.h"
32 #include "ocpayload.h"
38 // Forward declaring the entityHandler (room)
39 OCEntityHandlerResult entityHandlerRoom(std::shared_ptr<OCResourceRequest> request);
40 OCEntityHandlerResult entityHandlerLight(std::shared_ptr<OCResourceRequest> request);
41 OCEntityHandlerResult entityHandlerFan(std::shared_ptr<OCResourceRequest> request);
43 /// Specifies whether default collection entity handler is used or not
44 bool useDefaultCollectionEH = false;
46 // Set of strings for each of platform Info fields
47 std::string platformId = "0A3E0D6F-DBF5-404E-8719-D6880042463A";
48 std::string manufacturerName = "OCF";
49 std::string manufacturerLink = "https://www.iotivity.org";
50 std::string modelNumber = "myModelNumber";
51 std::string dateOfManufacture = "2016-01-15";
52 std::string platformVersion = "myPlatformVersion";
53 std::string operatingSystemVersion = "myOS";
54 std::string hardwareVersion = "myHardwareVersion";
55 std::string firmwareVersion = "1.0";
56 std::string supportLink = "https://www.iotivity.org";
57 std::string systemTime = "2016-01-15T11.01";
59 // Set of strings for each of device info fields
60 std::string deviceName = "IoTivity Room Server";
61 std::string specVersion = "core.1.1.0";
62 std::vector<std::string> dataModelVersions = {"res.1.1.0"};
63 std::string protocolIndependentID = "ac1b42a7-0518-448f-9b11-bfe328837bbf";
65 // OCPlatformInfo Contains all the platform info to be stored
66 OCPlatformInfo platformInfo;
73 std::string m_roomUri;
74 std::string m_roomName;
75 std::vector<std::string> m_roomTypes;
76 std::vector<std::string> m_roomInterfaces;
77 OCResourceHandle m_roomHandle;
78 OCRepresentation m_roomRep;
83 std::string m_lightUri;
84 std::vector<std::string> m_lightTypes;
85 std::vector<std::string> m_lightInterfaces;
86 OCResourceHandle m_lightHandle;
87 OCRepresentation m_lightRep;
93 std::vector<std::string> m_fanTypes;
94 std::vector<std::string> m_fanInterfaces;
95 OCResourceHandle m_fanHandle;
96 OCRepresentation m_fanRep;
100 RoomResource(): m_roomName("John's Room"), m_roomHandle(nullptr), m_lightState(false),
101 m_lightColor(0),m_lightHandle(nullptr), m_fanState(false), m_fanSpeed(0),
104 m_lightUri = "/a/light"; // URI of the resource
105 m_lightTypes.push_back("core.light"); // resource type name. In this case, it is light
106 m_lightInterfaces.push_back(DEFAULT_INTERFACE); // resource interface.
108 m_lightRep.setUri(m_lightUri);
109 m_lightRep.setResourceTypes(m_lightTypes);
110 m_lightRep.setResourceInterfaces(m_lightInterfaces);
111 m_lightRep.setValue("state", m_lightState);
112 m_lightRep.setValue("color", m_lightColor);
114 m_fanUri = "/a/fan"; // URI of the resource
115 m_fanTypes.push_back("core.fan"); // resource type name. In this case, it is light
116 m_fanInterfaces.push_back(DEFAULT_INTERFACE); // resource interface.
118 m_fanRep.setUri(m_fanUri);
119 m_fanRep.setResourceTypes(m_fanTypes);
120 m_fanRep.setResourceInterfaces(m_fanInterfaces);
121 m_fanRep.setValue("state", m_fanState);
122 m_fanRep.setValue("speed", m_fanSpeed);
124 m_roomUri = "/a/room"; // URI of the resource
125 m_roomTypes.push_back("core.room"); // resource type name. In this case, it is light
126 m_roomInterfaces.push_back(DEFAULT_INTERFACE); // resource interface.
127 m_roomInterfaces.push_back(BATCH_INTERFACE); // resource interface.
128 m_roomInterfaces.push_back(LINK_INTERFACE); // resource interface.
129 m_roomRep.setValue("name", m_roomName);
130 m_roomRep.setUri(m_roomUri);
131 m_roomRep.setResourceTypes(m_roomTypes);
132 m_roomRep.setResourceInterfaces(m_roomInterfaces);
135 /// This function internally calls registerResource API.
136 void createResources()
138 // This function internally creates and registers the resource.
139 using namespace OC::OCPlatform;
140 OCStackResult result = OC_STACK_ERROR;
142 // Based on the case, we will use default collection EH (by passing NULL in entity handler
143 // parameter) or use application entity handler.
144 if(useDefaultCollectionEH)
146 result = registerResource(
147 m_roomHandle, m_roomUri, m_roomTypes[0],
148 m_roomInterfaces[0], NULL,
149 OC_DISCOVERABLE | OC_OBSERVABLE);
153 result = registerResource(
154 m_roomHandle, m_roomUri, m_roomTypes[0],
155 m_roomInterfaces[0], entityHandlerRoom,
156 OC_DISCOVERABLE | OC_OBSERVABLE);
159 if (OC_STACK_OK != result)
161 cout << "Resource creation (room) was unsuccessful\n";
164 result = bindInterfaceToResource(m_roomHandle, m_roomInterfaces[1]);
165 if (OC_STACK_OK != result)
167 cout << "Binding TypeName to Resource was unsuccessful\n";
170 result = bindInterfaceToResource(m_roomHandle, m_roomInterfaces[2]);
171 if (OC_STACK_OK != result)
173 cout << "Binding TypeName to Resource was unsuccessful\n";
176 result = registerResource(m_lightHandle, m_lightUri, m_lightTypes[0],
177 m_lightInterfaces[0], entityHandlerLight,
178 OC_DISCOVERABLE | OC_OBSERVABLE);
180 if (OC_STACK_OK != result)
182 cout << "Resource creation (light) was unsuccessful\n";
185 result = registerResource(m_fanHandle, m_fanUri, m_fanTypes[0],
186 m_fanInterfaces[0], entityHandlerFan,
187 OC_DISCOVERABLE | OC_OBSERVABLE);
189 if (OC_STACK_OK != result)
191 cout << "Resource creation (fan) was unsuccessful\n";
194 result = bindResource(m_roomHandle, m_lightHandle);
195 if (OC_STACK_OK != result)
197 cout << "Binding fan resource to room was unsuccessful\n";
200 result = bindResource(m_roomHandle, m_fanHandle);
201 if (OC_STACK_OK != result)
203 cout << "Binding light resource to room was unsuccessful\n";
208 void setLightRepresentation(OCRepresentation& rep)
210 bool tempState = false;
213 // If both entries exist
214 if(rep.getValue("state", tempState) && rep.getValue("color", tempColor))
216 m_lightState = tempState;
217 m_lightColor= tempColor;
219 cout << "\t\t\t\t" << "state: " << m_lightState << endl;
220 cout << "\t\t\t\t" << "color: " << m_lightColor << endl;
224 void setFanRepresentation(OCRepresentation& rep)
226 bool tempState = false;
229 // If both entries exist
230 if(rep.getValue("state", tempState) && rep.getValue("speed", tempSpeed))
232 m_fanState = tempState;
233 m_fanSpeed = tempSpeed;
235 cout << "\t\t\t\t" << "state: " << m_fanState << endl;
236 cout << "\t\t\t\t" << "speed: " << m_fanSpeed << endl;
241 OCRepresentation getLightRepresentation()
243 m_lightRep.setValue("state", m_lightState);
244 m_lightRep.setValue("color", m_lightColor);
249 OCRepresentation getFanRepresentation()
251 m_fanRep.setValue("state", m_fanState);
252 m_fanRep.setValue("speed", m_fanSpeed);
256 OCRepresentation getRoomRepresentation(void)
258 m_roomRep.clearChildren();
260 m_roomRep.addChild(getLightRepresentation());
261 m_roomRep.addChild(getFanRepresentation());
267 // Create the instance of the resource class (in this case instance of class 'RoomResource').
268 RoomResource myRoomResource;
270 OCStackResult sendRoomResponse(std::shared_ptr<OCResourceRequest> pRequest)
272 auto pResponse = std::make_shared<OC::OCResourceResponse>();
273 pResponse->setRequestHandle(pRequest->getRequestHandle());
274 pResponse->setResourceHandle(pRequest->getResourceHandle());
276 // Check for query params (if any)
277 QueryParamsMap queryParamsMap = pRequest->getQueryParameters();
279 cout << "\t\t\tquery params: \n";
280 for(auto it = queryParamsMap.begin(); it != queryParamsMap.end(); it++)
282 cout << "\t\t\t\t" << it->first << ":" << it->second << endl;
285 OCRepresentation rep;
286 rep = myRoomResource.getRoomRepresentation();
288 auto findRes = queryParamsMap.find("if");
290 if(findRes != queryParamsMap.end())
292 pResponse->setResourceRepresentation(rep, findRes->second);
296 pResponse->setResourceRepresentation(rep, DEFAULT_INTERFACE);
300 pResponse->setResponseResult(OC_EH_OK);
302 return OCPlatform::sendResponse(pResponse);
305 // This function prepares a response for any incoming request to Light resource.
306 bool prepareLightResponse(std::shared_ptr<OCResourceRequest> request)
308 cout << "\tIn Server CPP (Light) prepareLightResponse:\n";
312 // Get the request type and request flag
313 std::string requestType = request->getRequestType();
314 int requestFlag = request->getRequestHandlerFlag();
316 if(requestFlag == RequestHandlerFlag::RequestFlag)
318 cout << "\t\trequestFlag : Request\n";
320 // If the request type is GET
321 if(requestType == "GET")
323 cout << "\t\t\trequestType : GET\n";
324 // GET operations are directly handled while sending the response
325 // in the sendLightResponse function
328 else if(requestType == "PUT")
330 cout << "\t\t\trequestType : PUT\n";
331 OCRepresentation rep = request->getResourceRepresentation();
333 // Do related operations related to PUT request
334 myRoomResource.setLightRepresentation(rep);
337 else if(requestType == "POST")
339 // POST request operations
341 else if(requestType == "DELETE")
343 // DELETE request operations
346 else if(requestFlag == RequestHandlerFlag::ObserverFlag)
348 cout << "\t\trequestFlag : Observer\n";
353 std::cout << "Request invalid" << std::endl;
359 // This function prepares a response for any incoming request to Fan resource.
360 bool prepareFanResponse(std::shared_ptr<OCResourceRequest> request)
362 cout << "\tIn Server CPP (Fan) prepareFanResponse:\n";
367 // Get the request type and request flag
368 std::string requestType = request->getRequestType();
369 int requestFlag = request->getRequestHandlerFlag();
371 if(requestFlag == RequestHandlerFlag::RequestFlag)
373 cout << "\t\trequestFlag : Request\n";
375 // If the request type is GET
376 if(requestType == "GET")
378 cout << "\t\t\trequestType : GET\n";
379 // GET operations are directly handled while sending the response
380 // in the sendLightResponse function
383 else if(requestType == "PUT")
385 cout << "\t\t\trequestType : PUT\n";
387 OCRepresentation rep = request->getResourceRepresentation();
389 // Do related operations related to PUT request
390 myRoomResource.setFanRepresentation(rep);
393 else if(requestType == "POST")
395 // POST request operations
397 else if(requestType == "DELETE")
399 // DELETE request operations
402 else if(requestFlag == RequestHandlerFlag::ObserverFlag)
404 cout << "\t\trequestFlag : Observer\n";
409 std::cout << "Request invalid" << std::endl;
415 OCEntityHandlerResult entityHandlerRoom(std::shared_ptr<OCResourceRequest> request)
417 cout << "\tIn Server CPP entity handler:\n";
418 OCEntityHandlerResult ehResult = OC_EH_ERROR;
422 // Get the request type and request flag
423 std::string requestType = request->getRequestType();
424 int requestFlag = request->getRequestHandlerFlag();
426 if(requestFlag == RequestHandlerFlag::RequestFlag)
428 cout << "\t\trequestFlag : Request\n";
430 // If the request type is GET
431 if(requestType == "GET")
433 cout << "\t\t\trequestType : GET\n";
434 if(OC_STACK_OK == sendRoomResponse(request))
439 else if(requestType == "PUT")
441 cout << "\t\t\trequestType : PUT\n";
442 // Call these functions to prepare the response for child resources and
443 // then send the final response using sendRoomResponse function
444 prepareLightResponse(request);
445 prepareFanResponse(request);
446 if(OC_STACK_OK == sendRoomResponse(request))
451 else if(requestType == "POST")
453 // POST request operations
455 else if(requestType == "DELETE")
457 // DELETE request operations
460 else if(requestFlag == RequestHandlerFlag::ObserverFlag)
462 cout << "\t\trequestFlag : Observer\n";
467 std::cout << "Request invalid" << std::endl;
473 OCStackResult sendLightResponse(std::shared_ptr<OCResourceRequest> pRequest)
475 auto pResponse = std::make_shared<OC::OCResourceResponse>();
476 pResponse->setRequestHandle(pRequest->getRequestHandle());
477 pResponse->setResourceHandle(pRequest->getResourceHandle());
478 pResponse->setResourceRepresentation(myRoomResource.getLightRepresentation());
480 pResponse->setResponseResult(OC_EH_OK);
482 return OCPlatform::sendResponse(pResponse);
487 OCEntityHandlerResult entityHandlerLight(std::shared_ptr<OCResourceRequest> request)
489 cout << "\tIn Server CPP (Light) entity handler:\n";
490 OCEntityHandlerResult ehResult = OC_EH_ERROR;
492 if(prepareLightResponse(request))
494 if(OC_STACK_OK == sendLightResponse(request))
500 std::cout << "sendLightResponse failed." << std::endl;
505 std::cout << "PrepareLightResponse failed." << std::endl;
510 OCStackResult sendFanResponse(std::shared_ptr<OCResourceRequest> pRequest)
512 auto pResponse = std::make_shared<OC::OCResourceResponse>();
513 pResponse->setRequestHandle(pRequest->getRequestHandle());
514 pResponse->setResourceHandle(pRequest->getResourceHandle());
515 pResponse->setResourceRepresentation(myRoomResource.getFanRepresentation());
517 pResponse->setResponseResult(OC_EH_OK);
519 return OCPlatform::sendResponse(pResponse);
523 OCEntityHandlerResult entityHandlerFan(std::shared_ptr<OCResourceRequest> request)
525 cout << "\tIn Server CPP (Fan) entity handler:\n";
526 OCEntityHandlerResult ehResult = OC_EH_ERROR;
527 if(prepareFanResponse(request))
529 if(OC_STACK_OK == sendFanResponse(request))
535 std::cout << "sendFanResponse failed." << std::endl;
540 std::cout << "PrepareFanResponse failed." << std::endl;
548 std::cout << std::endl;
549 std::cout << "Usage : roomserver <value>\n";
550 std::cout << "1 : Create room resource with default collection entity handler.\n";
551 std::cout << "2 : Create room resource with application collection entity handler.\n";
554 void DeletePlatformInfo()
556 delete[] platformInfo.platformID;
557 delete[] platformInfo.manufacturerName;
558 delete[] platformInfo.manufacturerUrl;
559 delete[] platformInfo.modelNumber;
560 delete[] platformInfo.dateOfManufacture;
561 delete[] platformInfo.platformVersion;
562 delete[] platformInfo.operatingSystemVersion;
563 delete[] platformInfo.hardwareVersion;
564 delete[] platformInfo.firmwareVersion;
565 delete[] platformInfo.supportUrl;
566 delete[] platformInfo.systemTime;
569 void DuplicateString(char ** targetString, std::string sourceString)
571 *targetString = new char[sourceString.length() + 1];
572 strncpy(*targetString, sourceString.c_str(), (sourceString.length() + 1));
575 OCStackResult SetPlatformInfo(std::string platformID, std::string manufacturerName,
576 std::string manufacturerUrl, std::string modelNumber, std::string dateOfManufacture,
577 std::string platformVersion, std::string operatingSystemVersion,
578 std::string hardwareVersion, std::string firmwareVersion, std::string supportUrl,
579 std::string systemTime)
581 DuplicateString(&platformInfo.platformID, platformID);
582 DuplicateString(&platformInfo.manufacturerName, manufacturerName);
583 DuplicateString(&platformInfo.manufacturerUrl, manufacturerUrl);
584 DuplicateString(&platformInfo.modelNumber, modelNumber);
585 DuplicateString(&platformInfo.dateOfManufacture, dateOfManufacture);
586 DuplicateString(&platformInfo.platformVersion, platformVersion);
587 DuplicateString(&platformInfo.operatingSystemVersion, operatingSystemVersion);
588 DuplicateString(&platformInfo.hardwareVersion, hardwareVersion);
589 DuplicateString(&platformInfo.firmwareVersion, firmwareVersion);
590 DuplicateString(&platformInfo.supportUrl, supportUrl);
591 DuplicateString(&platformInfo.systemTime, systemTime);
596 OCStackResult SetDeviceInfo()
598 OCStackResult result = OCPlatform::setPropertyValue(PAYLOAD_TYPE_DEVICE, OC_RSRVD_DEVICE_NAME,
600 if (result != OC_STACK_OK)
602 cout << "Failed to set device name" << endl;
606 result = OCPlatform::setPropertyValue(PAYLOAD_TYPE_DEVICE, OC_RSRVD_DATA_MODEL_VERSION,
608 if (result != OC_STACK_OK)
610 cout << "Failed to set data model versions" << endl;
614 result = OCPlatform::setPropertyValue(PAYLOAD_TYPE_DEVICE, OC_RSRVD_SPEC_VERSION, specVersion);
616 if (result != OC_STACK_OK)
618 cout << "Failed to set spec version" << endl;
622 result = OCPlatform::setPropertyValue(PAYLOAD_TYPE_DEVICE, OC_RSRVD_PROTOCOL_INDEPENDENT_ID,
623 protocolIndependentID);
624 if (result != OC_STACK_OK)
626 cout << "Failed to set piid" << endl;
633 int main(int argc, char* argv[])
639 int value = atoi(argv[1]);
643 useDefaultCollectionEH = true;
655 // Create PlatformConfig object
657 OC::ServiceType::InProc,
658 OC::ModeType::Server,
659 "0.0.0.0", // By setting to "0.0.0.0", it binds to all available interfaces
660 0, // Uses randomly available port
661 OC::QualityOfService::LowQos
664 OCPlatform::Configure(cfg);
665 std::cout << "Starting server & setting platform info\n";
667 OCStackResult result = SetPlatformInfo(platformId, manufacturerName, manufacturerLink,
668 modelNumber, dateOfManufacture, platformVersion, operatingSystemVersion,
669 hardwareVersion, firmwareVersion, supportLink, systemTime);
671 result = OCPlatform::registerPlatformInfo(platformInfo);
673 if (result != OC_STACK_OK)
675 std::cout << "Platform Registration failed\n";
679 result = SetDeviceInfo();
681 if (result != OC_STACK_OK)
683 std::cout << "Device Registration failed\n";
690 myRoomResource.createResources();
692 DeletePlatformInfo();
693 // A condition variable will free the mutex it is given, then do a non-
694 // intensive block until 'notify' is called on it. In this case, since we
695 // don't ever call cv.notify, this should be a non-processor intensive version
698 std::condition_variable cv;
699 std::unique_lock<std::mutex> lock(blocker);
703 catch(OCException &e)
705 std::cout << "Exception in main: " << e.what();
708 // No explicit call to stop the platform.
709 // When OCPlatform destructor is invoked, internally we do platform cleanup