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.
337 pResponse->setErrorCode(200);
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
354 pResponse->setErrorCode(200);
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);
371 pResponse->setErrorCode(200);
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->setErrorCode(200);
475 resourceResponse->setResourceRepresentation(lightPtr->get(), DEFAULT_INTERFACE);
477 result = OCPlatform::notifyListOfObservers( lightPtr->getHandle(),
478 lightPtr->m_interestedObservers,
483 result = OCPlatform::notifyAllObservers(lightPtr->getHandle());
486 if(OC_STACK_NO_OBSERVERS == result)
488 cout << "No More observers, stopping notifications" << endl;
497 void DeletePlatformInfo()
499 delete[] platformInfo.platformID;
500 delete[] platformInfo.manufacturerName;
501 delete[] platformInfo.manufacturerUrl;
502 delete[] platformInfo.modelNumber;
503 delete[] platformInfo.dateOfManufacture;
504 delete[] platformInfo.platformVersion;
505 delete[] platformInfo.operatingSystemVersion;
506 delete[] platformInfo.hardwareVersion;
507 delete[] platformInfo.firmwareVersion;
508 delete[] platformInfo.supportUrl;
509 delete[] platformInfo.systemTime;
512 void DeleteDeviceInfo()
514 delete[] deviceInfo.deviceName;
515 delete[] deviceInfo.specVersion;
516 OCFreeOCStringLL(deviceInfo.dataModelVersions);
519 void DuplicateString(char ** targetString, std::string sourceString)
521 *targetString = new char[sourceString.length() + 1];
522 strncpy(*targetString, sourceString.c_str(), (sourceString.length() + 1));
525 OCStackResult SetPlatformInfo(std::string platformID, std::string manufacturerName,
526 std::string manufacturerUrl, std::string modelNumber, std::string dateOfManufacture,
527 std::string platformVersion, std::string operatingSystemVersion,
528 std::string hardwareVersion, std::string firmwareVersion, std::string supportUrl,
529 std::string systemTime)
531 DuplicateString(&platformInfo.platformID, platformID);
532 DuplicateString(&platformInfo.manufacturerName, manufacturerName);
533 DuplicateString(&platformInfo.manufacturerUrl, manufacturerUrl);
534 DuplicateString(&platformInfo.modelNumber, modelNumber);
535 DuplicateString(&platformInfo.dateOfManufacture, dateOfManufacture);
536 DuplicateString(&platformInfo.platformVersion, platformVersion);
537 DuplicateString(&platformInfo.operatingSystemVersion, operatingSystemVersion);
538 DuplicateString(&platformInfo.hardwareVersion, hardwareVersion);
539 DuplicateString(&platformInfo.firmwareVersion, firmwareVersion);
540 DuplicateString(&platformInfo.supportUrl, supportUrl);
541 DuplicateString(&platformInfo.systemTime, systemTime);
546 OCStackResult SetDeviceInfo(std::string deviceName, std::string specVersion, std::string dataModelVersions)
548 DuplicateString(&deviceInfo.deviceName, deviceName);
550 if (!specVersion.empty())
552 DuplicateString(&deviceInfo.specVersion, specVersion);
555 if (!dataModelVersions.empty())
557 OCResourcePayloadAddStringLL(&deviceInfo.dataModelVersions, dataModelVersions.c_str());
563 void * handleSlowResponse (void *param, std::shared_ptr<OCResourceRequest> pRequest)
565 // This function handles slow response case
566 LightResource* lightPtr = (LightResource*) param;
567 // Induce a case for slow response by using sleep
568 std::cout << "SLOW response" << std::endl;
571 auto pResponse = std::make_shared<OC::OCResourceResponse>();
572 pResponse->setRequestHandle(pRequest->getRequestHandle());
573 pResponse->setResourceHandle(pRequest->getResourceHandle());
574 pResponse->setResourceRepresentation(lightPtr->get());
575 pResponse->setErrorCode(200);
576 pResponse->setResponseResult(OC_EH_OK);
578 // Set the slow response flag back to false
579 isSlowResponse = false;
580 OCPlatform::sendResponse(pResponse);
586 std::cout << std::endl;
587 std::cout << "Usage : simpleserver <value>\n";
588 std::cout << " Default - Non-secure resource and notify all observers\n";
589 std::cout << " 1 - Non-secure resource and notify list of observers\n\n";
590 std::cout << " 2 - Secure resource and notify all observers\n";
591 std::cout << " 3 - Secure resource and notify list of observers\n\n";
592 std::cout << " 4 - Non-secure resource, GET slow response, notify all observers\n";
595 static FILE* client_open(const char* /*path*/, const char *mode)
597 return fopen(SVR_DB_FILE_NAME, mode);
600 int main(int argc, char* argv[])
603 OCPersistentStorage ps {client_open, fread, fwrite, fclose, unlink, NULL, NULL};
607 isListOfObservers = false;
612 int value = atoi(argv[1]);
616 isListOfObservers = true;
620 isListOfObservers = false;
624 isListOfObservers = true;
628 isSlowResponse = true;
639 // Create PlatformConfig object
641 OC::ServiceType::InProc,
642 OC::ModeType::Server,
643 (OCTransportAdapter)(OCTransportAdapter::OC_ADAPTER_IP|OCTransportAdapter::OC_ADAPTER_TCP),
644 OC::QualityOfService::LowQos,
648 OCPlatform::Configure(cfg);
649 std::cout << "Starting server & setting platform info\n";
651 OCStackResult result = SetPlatformInfo(platformId, manufacturerName, manufacturerLink,
652 modelNumber, dateOfManufacture, platformVersion, operatingSystemVersion,
653 hardwareVersion, firmwareVersion, supportLink, systemTime);
655 result = OCPlatform::registerPlatformInfo(platformInfo);
657 if (result != OC_STACK_OK)
659 std::cout << "Platform Registration failed\n";
663 result = SetDeviceInfo(deviceName, specVersion, dataModelVersions);
664 OCResourcePayloadAddStringLL(&deviceInfo.types, "oic.wk.d");
666 result = OCPlatform::registerDeviceInfo(deviceInfo);
668 if (result != OC_STACK_OK)
670 std::cout << "Device Registration failed\n";
676 // Create the instance of the resource class
677 // (in this case instance of class 'LightResource').
678 LightResource myLight;
680 // Invoke createResource function of class light.
681 myLight.createResource();
682 std::cout << "Created resource." << std::endl;
684 myLight.addType(std::string("core.brightlight"));
685 myLight.addInterface(std::string(LINK_INTERFACE));
686 std::cout << "Added Interface and Type" << std::endl;
688 DeletePlatformInfo();
691 // A condition variable will free the mutex it is given, then do a non-
692 // intensive block until 'notify' is called on it. In this case, since we
693 // don't ever call cv.notify, this should be a non-processor intensive version
696 std::condition_variable cv;
697 std::unique_lock<std::mutex> lock(blocker);
698 std::cout <<"Waiting" << std::endl;
699 cv.wait(lock, []{return false;});
701 catch(OCException &e)
703 std::cout << "OCException in main : " << e.what() << endl;
706 // No explicit call to stop the platform.
707 // When OCPlatform::destructor is invoked, internally we do platform cleanup