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 provides steps to define an interface for a resource
23 /// (properties and methods) and host this resource on the server.
25 #include "iotivity_config.h"
35 #include <condition_variable>
37 #include "OCPlatform.h"
43 #include "ocpayload.h"
47 namespace PH = std::placeholders;
49 static const char* SVR_DB_FILE_NAME = "./oic_svr_db_server.dat";
51 void * ChangeLightRepresentation (void *param);
52 void * handleSlowResponse (void *param, std::shared_ptr<OCResourceRequest> pRequest);
54 // Set of strings for each of platform Info fields
55 std::string platformId = "0A3E0D6F-DBF5-404E-8719-D6880042463A";
56 std::string manufacturerName = "OCF";
57 std::string manufacturerLink = "https://www.iotivity.org";
58 std::string modelNumber = "myModelNumber";
59 std::string dateOfManufacture = "2016-01-15";
60 std::string platformVersion = "myPlatformVersion";
61 std::string operatingSystemVersion = "myOS";
62 std::string hardwareVersion = "myHardwareVersion";
63 std::string firmwareVersion = "1.0";
64 std::string supportLink = "https://www.iotivity.org";
65 std::string systemTime = "2016-01-15T11.01";
67 // Set of strings for each of device info fields
68 std::string deviceName = "IoTivity Simple Server";
69 std::string specVersion = "core.1.1.0";
70 std::string dataModelVersions = "res.1.1.0,sh.1.1.0";
72 // OCPlatformInfo Contains all the platform info to be stored
73 OCPlatformInfo platformInfo;
75 // OCDeviceInfo Contains all the device info to be stored
76 OCDeviceInfo deviceInfo;
78 // Specifies where to notify all observers or list of observers
79 // false: notifies all observers
80 // true: notifies list of observers
81 bool isListOfObservers = false;
83 // Specifies secure or non-secure
84 // false: non-secure resource
85 // true: secure resource
86 bool isSecure = false;
88 /// Specifies whether Entity handler is going to do slow response or not
89 bool isSlowResponse = false;
91 // Forward declaring the entityHandler
93 /// This class represents a single resource named 'lightResource'. This resource has
94 /// two simple properties named 'state' and 'power'
100 /// Access this property from a TB client
104 std::string m_lightUri;
105 OCResourceHandle m_resourceHandle;
106 OCRepresentation m_lightRep;
107 ObservationIds m_interestedObservers;
112 :m_name("John's light"), m_state(false), m_power(0), m_lightUri("/a/light"),
113 m_resourceHandle(nullptr) {
114 // Initialize representation
115 m_lightRep.setUri(m_lightUri);
117 m_lightRep.setValue("state", m_state);
118 m_lightRep.setValue("power", m_power);
119 m_lightRep.setValue("name", m_name);
122 /* Note that this does not need to be a member function: for classes you do not have
123 access to, you can accomplish this with a free function: */
125 /// This function internally calls registerResource API.
126 void createResource()
128 //URI of the resource
129 std::string resourceURI = m_lightUri;
130 //resource type name. In this case, it is light
131 std::string resourceTypeName = "core.light";
132 // resource interface.
133 std::string resourceInterface = DEFAULT_INTERFACE;
135 // OCResourceProperty is defined ocstack.h
136 uint8_t resourceProperty;
139 resourceProperty = OC_DISCOVERABLE | OC_OBSERVABLE | OC_SECURE;
143 resourceProperty = OC_DISCOVERABLE | OC_OBSERVABLE;
145 EntityHandler cb = std::bind(&LightResource::entityHandler, this,PH::_1);
147 // This will internally create and register the resource.
148 OCStackResult result = OCPlatform::registerResource(
149 m_resourceHandle, resourceURI, resourceTypeName,
150 resourceInterface, cb, resourceProperty);
152 if (OC_STACK_OK != result)
154 cout << "Resource creation was unsuccessful\n";
158 OCStackResult createResource1()
160 // URI of the resource
161 std::string resourceURI = "/a/light1";
162 // resource type name. In this case, it is light
163 std::string resourceTypeName = "core.light";
164 // resource interface.
165 std::string resourceInterface = DEFAULT_INTERFACE;
167 // OCResourceProperty is defined ocstack.h
168 uint8_t resourceProperty;
171 resourceProperty = OC_DISCOVERABLE | OC_OBSERVABLE | OC_SECURE;
175 resourceProperty = OC_DISCOVERABLE | OC_OBSERVABLE;
177 EntityHandler cb = std::bind(&LightResource::entityHandler, this,PH::_1);
179 OCResourceHandle resHandle;
181 // This will internally create and register the resource.
182 OCStackResult result = OCPlatform::registerResource(
183 resHandle, resourceURI, resourceTypeName,
184 resourceInterface, cb, resourceProperty);
186 if (OC_STACK_OK != result)
188 cout << "Resource creation was unsuccessful\n";
194 OCResourceHandle getHandle()
196 return m_resourceHandle;
199 // Puts representation.
200 // Gets values from the representation and
201 // updates the internal state
202 void put(OCRepresentation& rep)
205 if (rep.getValue("state", m_state))
207 cout << "\t\t\t\t" << "state: " << m_state << endl;
211 cout << "\t\t\t\t" << "state not found in the representation" << endl;
214 if (rep.getValue("power", m_power))
216 cout << "\t\t\t\t" << "power: " << m_power << endl;
220 cout << "\t\t\t\t" << "power not found in the representation" << endl;
225 cout << e.what() << endl;
230 // Post representation.
231 // Post can create new resource or simply act like put.
232 // Gets values from the representation and
233 // updates the internal state
234 OCRepresentation post(OCRepresentation& rep)
236 static int first = 1;
238 // for the first time it tries to create a resource
243 if(OC_STACK_OK == createResource1())
245 OCRepresentation rep1;
246 rep1.setValue("createduri", std::string("/a/light1"));
252 // from second time onwards it just puts
258 // gets the updated representation.
259 // Updates the representation with latest internal state before
261 OCRepresentation get()
263 m_lightRep.setValue("state", m_state);
264 m_lightRep.setValue("power", m_power);
269 void addType(const std::string& type) const
271 OCStackResult result = OCPlatform::bindTypeToResource(m_resourceHandle, type);
272 if (OC_STACK_OK != result)
274 cout << "Binding TypeName to Resource was unsuccessful\n";
278 void addInterface(const std::string& iface) const
280 OCStackResult result = OCPlatform::bindInterfaceToResource(m_resourceHandle, iface);
281 if (OC_STACK_OK != result)
283 cout << "Binding TypeName to Resource was unsuccessful\n";
288 // This is just a sample implementation of entity handler.
289 // Entity handler can be implemented in several ways by the manufacturer
290 OCEntityHandlerResult entityHandler(std::shared_ptr<OCResourceRequest> request)
292 cout << "\tIn Server CPP entity handler:\n";
293 OCEntityHandlerResult ehResult = OC_EH_ERROR;
296 // Get the request type and request flag
297 std::string requestType = request->getRequestType();
298 int requestFlag = request->getRequestHandlerFlag();
300 if(requestFlag & RequestHandlerFlag::RequestFlag)
302 cout << "\t\trequestFlag : Request\n";
303 auto pResponse = std::make_shared<OC::OCResourceResponse>();
304 pResponse->setRequestHandle(request->getRequestHandle());
305 pResponse->setResourceHandle(request->getResourceHandle());
307 // Check for query params (if any)
308 QueryParamsMap queries = request->getQueryParameters();
310 if (!queries.empty())
312 std::cout << "\nQuery processing upto entityHandler" << std::endl;
314 for (auto it : queries)
316 std::cout << "Query key: " << it.first << " value : " << it.second
320 // If the request type is GET
321 if(requestType == "GET")
323 cout << "\t\t\trequestType : GET\n";
324 if(isSlowResponse) // Slow response case
326 static int startedThread = 0;
329 std::thread t(handleSlowResponse, (void *)this, request);
333 ehResult = OC_EH_SLOW;
335 else // normal response case.
338 pResponse->setResponseResult(OC_EH_OK);
339 pResponse->setResourceRepresentation(get());
340 if(OC_STACK_OK == OCPlatform::sendResponse(pResponse))
346 else if(requestType == "PUT")
348 cout << "\t\t\trequestType : PUT\n";
349 OCRepresentation rep = request->getResourceRepresentation();
351 // Do related operations related to PUT request
352 // Update the lightResource
355 pResponse->setResponseResult(OC_EH_OK);
356 pResponse->setResourceRepresentation(get());
357 if(OC_STACK_OK == OCPlatform::sendResponse(pResponse))
362 else if(requestType == "POST")
364 cout << "\t\t\trequestType : POST\n";
366 OCRepresentation rep = request->getResourceRepresentation();
368 // Do related operations related to POST request
369 OCRepresentation rep_post = post(rep);
370 pResponse->setResourceRepresentation(rep_post);
372 if(rep_post.hasAttribute("createduri"))
374 pResponse->setResponseResult(OC_EH_RESOURCE_CREATED);
375 pResponse->setNewResourceUri(rep_post.getValue<std::string>("createduri"));
379 pResponse->setResponseResult(OC_EH_OK);
382 if(OC_STACK_OK == OCPlatform::sendResponse(pResponse))
387 else if(requestType == "DELETE")
389 cout << "Delete request received" << endl;
393 if(requestFlag & RequestHandlerFlag::ObserverFlag)
395 ObservationInfo observationInfo = request->getObservationInfo();
396 if(ObserveAction::ObserveRegister == observationInfo.action)
398 m_interestedObservers.push_back(observationInfo.obsId);
400 else if(ObserveAction::ObserveUnregister == observationInfo.action)
402 m_interestedObservers.erase(std::remove(
403 m_interestedObservers.begin(),
404 m_interestedObservers.end(),
405 observationInfo.obsId),
406 m_interestedObservers.end());
411 HANDLE threadHandle = INVALID_HANDLE_VALUE;
416 cout << "\t\trequestFlag : Observer\n";
418 static int startedThread = 0;
420 // Observation happens on a different thread in ChangeLightRepresentation function.
421 // If we have not created the thread already, we will create one here.
425 threadHandle = CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)ChangeLightRepresentation, (void*)this, 0, &threadId);
427 pthread_create (&threadId, NULL, ChangeLightRepresentation, (void *)this);
436 std::cout << "Request invalid" << std::endl;
444 // ChangeLightRepresentaion is an observation function,
445 // which notifies any changes to the resource to stack
446 // via notifyObservers
447 void * ChangeLightRepresentation (void *param)
449 LightResource* lightPtr = (LightResource*) param;
451 // This function continuously monitors for the changes
458 // If under observation if there are any changes to the light resource
459 // we call notifyObservors
461 // For demostration we are changing the power value and notifying.
462 lightPtr->m_power += 10;
464 cout << "\nPower updated to : " << lightPtr->m_power << endl;
465 cout << "Notifying observers with resource handle: " << lightPtr->getHandle() << endl;
467 OCStackResult result = OC_STACK_OK;
469 if(isListOfObservers)
471 std::shared_ptr<OCResourceResponse> resourceResponse =
472 {std::make_shared<OCResourceResponse>()};
474 resourceResponse->setResourceRepresentation(lightPtr->get(), DEFAULT_INTERFACE);
476 result = OCPlatform::notifyListOfObservers( lightPtr->getHandle(),
477 lightPtr->m_interestedObservers,
482 result = OCPlatform::notifyAllObservers(lightPtr->getHandle());
485 if(OC_STACK_NO_OBSERVERS == result)
487 cout << "No More observers, stopping notifications" << endl;
496 void DeletePlatformInfo()
498 delete[] platformInfo.platformID;
499 delete[] platformInfo.manufacturerName;
500 delete[] platformInfo.manufacturerUrl;
501 delete[] platformInfo.modelNumber;
502 delete[] platformInfo.dateOfManufacture;
503 delete[] platformInfo.platformVersion;
504 delete[] platformInfo.operatingSystemVersion;
505 delete[] platformInfo.hardwareVersion;
506 delete[] platformInfo.firmwareVersion;
507 delete[] platformInfo.supportUrl;
508 delete[] platformInfo.systemTime;
511 void DuplicateString(char ** targetString, std::string sourceString)
513 *targetString = new char[sourceString.length() + 1];
514 strncpy(*targetString, sourceString.c_str(), (sourceString.length() + 1));
517 OCStackResult SetPlatformInfo(std::string platformID, std::string manufacturerName,
518 std::string manufacturerUrl, std::string modelNumber, std::string dateOfManufacture,
519 std::string platformVersion, std::string operatingSystemVersion,
520 std::string hardwareVersion, std::string firmwareVersion, std::string supportUrl,
521 std::string systemTime)
523 DuplicateString(&platformInfo.platformID, platformID);
524 DuplicateString(&platformInfo.manufacturerName, manufacturerName);
525 DuplicateString(&platformInfo.manufacturerUrl, manufacturerUrl);
526 DuplicateString(&platformInfo.modelNumber, modelNumber);
527 DuplicateString(&platformInfo.dateOfManufacture, dateOfManufacture);
528 DuplicateString(&platformInfo.platformVersion, platformVersion);
529 DuplicateString(&platformInfo.operatingSystemVersion, operatingSystemVersion);
530 DuplicateString(&platformInfo.hardwareVersion, hardwareVersion);
531 DuplicateString(&platformInfo.firmwareVersion, firmwareVersion);
532 DuplicateString(&platformInfo.supportUrl, supportUrl);
533 DuplicateString(&platformInfo.systemTime, systemTime);
538 void * handleSlowResponse (void *param, std::shared_ptr<OCResourceRequest> pRequest)
540 // This function handles slow response case
541 LightResource* lightPtr = (LightResource*) param;
542 // Induce a case for slow response by using sleep
543 std::cout << "SLOW response" << std::endl;
546 auto pResponse = std::make_shared<OC::OCResourceResponse>();
547 pResponse->setRequestHandle(pRequest->getRequestHandle());
548 pResponse->setResourceHandle(pRequest->getResourceHandle());
549 pResponse->setResourceRepresentation(lightPtr->get());
551 pResponse->setResponseResult(OC_EH_OK);
553 // Set the slow response flag back to false
554 isSlowResponse = false;
555 OCPlatform::sendResponse(pResponse);
561 std::cout << std::endl;
562 std::cout << "Usage : simpleserver <value>\n";
563 std::cout << " Default - Non-secure resource and notify all observers\n";
564 std::cout << " 1 - Non-secure resource and notify list of observers\n\n";
565 std::cout << " 2 - Secure resource and notify all observers\n";
566 std::cout << " 3 - Secure resource and notify list of observers\n\n";
567 std::cout << " 4 - Non-secure resource, GET slow response, notify all observers\n";
570 static FILE* client_open(const char* /*path*/, const char *mode)
572 return fopen(SVR_DB_FILE_NAME, mode);
575 int main(int argc, char* argv[])
578 OCPersistentStorage ps {client_open, fread, fwrite, fclose, unlink };
582 isListOfObservers = false;
587 int value = atoi(argv[1]);
591 isListOfObservers = true;
595 isListOfObservers = false;
599 isListOfObservers = true;
603 isSlowResponse = true;
614 // Create PlatformConfig object
616 OC::ServiceType::InProc,
617 OC::ModeType::Server,
618 "0.0.0.0", // By setting to "0.0.0.0", it binds to all available interfaces
619 0, // Uses randomly available port
620 OC::QualityOfService::LowQos,
624 OCPlatform::Configure(cfg);
625 std::cout << "Starting server & setting platform info\n";
627 OCStackResult result = SetPlatformInfo(platformId, manufacturerName, manufacturerLink,
628 modelNumber, dateOfManufacture, platformVersion, operatingSystemVersion,
629 hardwareVersion, firmwareVersion, supportLink, systemTime);
631 result = OCPlatform::registerPlatformInfo(platformInfo);
633 if (result != OC_STACK_OK)
635 std::cout << "Platform Registration failed\n";
639 result = OCPlatform::setPropertyValue(PAYLOAD_TYPE_DEVICE, OC_RSRVD_DEVICE_NAME, deviceName);
640 result = OCPlatform::setPropertyValue(PAYLOAD_TYPE_DEVICE, OC_RSRVD_SPEC_VERSION, specVersion);
641 result = OCPlatform::setPropertyValue(PAYLOAD_TYPE_DEVICE, OC_RSRVD_DATA_MODEL_VERSION,
643 OCResourceHandle handle = OCGetResourceHandleAtUri(OC_RSRVD_DEVICE_URI);
646 OCBindResourceTypeToResource(handle, "oic.wk.tv");
649 if (result != OC_STACK_OK)
651 std::cout << "Device Registration failed\n";
657 // Create the instance of the resource class
658 // (in this case instance of class 'LightResource').
659 LightResource myLight;
661 // Invoke createResource function of class light.
662 myLight.createResource();
663 std::cout << "Created resource." << std::endl;
665 myLight.addType(std::string("core.brightlight"));
666 myLight.addInterface(std::string(LINK_INTERFACE));
667 std::cout << "Added Interface and Type" << std::endl;
669 DeletePlatformInfo();
671 // A condition variable will free the mutex it is given, then do a non-
672 // intensive block until 'notify' is called on it. In this case, since we
673 // don't ever call cv.notify, this should be a non-processor intensive version
676 std::condition_variable cv;
677 std::unique_lock<std::mutex> lock(blocker);
678 std::cout <<"Waiting" << std::endl;
679 cv.wait(lock, []{return false;});
681 catch(OCException &e)
683 std::cout << "OCException in main : " << e.what() << endl;
686 // No explicit call to stop the platform.
687 // When OCPlatform::destructor is invoked, internally we do platform cleanup