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 using varous json types in the representation.
29 #include <condition_variable>
31 #include "OCPlatform.h"
33 #include "ocpayload.h"
38 // Set of strings for each of platform Info fields
39 std::string platformId = "0A3E0D6F-DBF5-404E-8719-D6880042463A";
40 std::string manufacturerName = "OCF";
41 std::string manufacturerLink = "https://www.iotivity.org";
42 std::string modelNumber = "myModelNumber";
43 std::string dateOfManufacture = "2016-01-15";
44 std::string platformVersion = "myPlatformVersion";
45 std::string operatingSystemVersion = "myOS";
46 std::string hardwareVersion = "myHardwareVersion";
47 std::string firmwareVersion = "1.0";
48 std::string supportLink = "https://www.iotivity.org";
49 std::string systemTime = "2016-01-15T11.01";
51 // Set of strings for each of device info fields
52 std::string deviceName = "IoTivity Garage Server";
53 std::string specVersion = "core.1.1.0";
54 std::string dataModelVersions = "res.1.1.0";
56 // OCPlatformInfo Contains all the platform info to be stored
57 OCPlatformInfo platformInfo;
59 // OCDeviceInfo Contains all the device info to be stored
60 OCDeviceInfo deviceInfo;
62 // Forward declaring the entityHandler
63 OCEntityHandlerResult entityHandler(std::shared_ptr<OCResourceRequest> request);
65 /// This class represents a single resource named 'GarageResource'.
69 /// Access this property from a TB client
72 std::string m_garageUri;
73 OCResourceHandle m_resourceHandle;
74 OCRepresentation m_garageRep;
75 ObservationIds m_interestedObservers;
77 // array of lights representation with in GarageResource
78 OCRepresentation m_lightRep;
79 std::vector<OCRepresentation> m_reps;
80 std::vector<std::vector<int>> m_hingeStates;
84 GarageResource(): m_name("John's Garage"), m_state(false), m_garageUri("/a/garage"),
85 m_hingeStates{{1,2,3},{4,5,6}}
87 // Initialize representation
88 m_garageRep.setUri(m_garageUri);
90 m_garageRep["state"] = m_state;
91 m_garageRep["name"] = m_name;
93 // For demonstration purpose we are setting x to nullptr here.
94 // In reality it may happen else where.
95 m_garageRep["nullAttribute"] = nullptr;
97 std::vector<bool> lightStates;
98 std::vector<int> lightPowers;
100 for(int i = 0; i <= 9; i++)
102 lightStates.push_back(i % 2 == 0);
103 lightPowers.push_back(i);
106 m_lightRep["states"] = lightStates;
107 m_lightRep["powers"] = lightPowers;
109 // Storing another representation within a representation
110 m_garageRep["light"] = m_lightRep;
112 OCRepresentation rep1;
114 rep1["key1"] = value1;
115 OCRepresentation rep2;
117 rep2["key2"] = value2;
119 m_reps.push_back(rep1);
120 m_reps.push_back(rep2);
122 // storing array of representations
123 m_garageRep["reps"] = m_reps;
126 // setting json string
127 std::string json = "{\"num\":10,\"rno\":23.5,\"aoa\":[[1,2],[3]],\"str\":\"john\",\
128 \"object\":{\"bl1\":false,\"ar\":[2,3]}, \"objects\":[{\"bl2\":true,\"nl\":null},{\"ar1\":[1,2]}]}";
129 m_garageRep["json"] = json;
131 m_garageRep["hinges"] = m_hingeStates;
134 /* Note that this does not need to be a member function: for classes you do not have
135 access to, you can accomplish this with a free function: */
137 /// This function internally calls registerResource API.
138 void createResource()
140 std::string resourceURI = m_garageUri; // URI of the resource
141 std::string resourceTypeName = "core.garage"; // resource type name.
142 std::string resourceInterface = DEFAULT_INTERFACE; // resource interface.
144 // OCResourceProperty is defined ocstack.h
145 uint8_t resourceProperty = OC_DISCOVERABLE | OC_OBSERVABLE;
147 // This will internally create and register the resource.
148 OCStackResult result = OCPlatform::registerResource(
149 m_resourceHandle, resourceURI, resourceTypeName,
150 resourceInterface, &entityHandler, resourceProperty);
152 if (OC_STACK_OK != result)
154 cout << "Resource creation was unsuccessful\n";
158 OCResourceHandle getHandle()
160 return m_resourceHandle;
163 // Puts representation.
164 // Gets values from the representation and
165 // updates the internal state
166 void put(OCRepresentation& rep)
169 if (rep.getValue("state", m_state))
171 cout << "\t\t\t\t" << "state: " << m_state << endl;
175 cout << "\t\t\t\t" << "state not found in the representation" << endl;
180 cout << e.what() << endl;
185 // gets the updated representation.
186 // Updates the representation with latest internal state before
188 OCRepresentation get()
190 m_garageRep["state"] = m_state;
197 // Create the instance of the resource class (in this case instance of class 'GarageResource').
198 GarageResource myGarage;
200 OCStackResult sendResponse(std::shared_ptr<OCResourceRequest> pRequest)
202 auto pResponse = std::make_shared<OC::OCResourceResponse>();
203 pResponse->setRequestHandle(pRequest->getRequestHandle());
204 pResponse->setResourceHandle(pRequest->getResourceHandle());
205 pResponse->setResourceRepresentation(myGarage.get());
206 pResponse->setErrorCode(200);
207 pResponse->setResponseResult(OC_EH_OK);
209 return OCPlatform::sendResponse(pResponse);
212 OCEntityHandlerResult entityHandler(std::shared_ptr<OCResourceRequest> request)
214 cout << "\tIn Server CPP entity handler:\n";
215 OCEntityHandlerResult ehResult = OC_EH_ERROR;
219 // Get the request type and request flag
220 std::string requestType = request->getRequestType();
221 int requestFlag = request->getRequestHandlerFlag();
223 if(requestFlag & RequestHandlerFlag::RequestFlag)
225 cout << "\t\trequestFlag : Request\n";
227 // If the request type is GET
228 if(requestType == "GET")
230 cout << "\t\t\trequestType : GET\n";
231 if(OC_STACK_OK == sendResponse(request))
236 else if(requestType == "PUT")
238 cout << "\t\t\trequestType : PUT\n";
239 OCRepresentation rep = request->getResourceRepresentation();
240 // Do related operations related to PUT request
242 if(OC_STACK_OK == sendResponse(request))
247 else if(requestType == "POST")
249 // POST request operations
251 else if(requestType == "DELETE")
253 // DELETE request operations
256 if(requestFlag & RequestHandlerFlag::ObserverFlag)
258 // OBSERVE operations
263 std::cout << "Request invalid" << std::endl;
269 void DeletePlatformInfo()
271 delete[] platformInfo.platformID;
272 delete[] platformInfo.manufacturerName;
273 delete[] platformInfo.manufacturerUrl;
274 delete[] platformInfo.modelNumber;
275 delete[] platformInfo.dateOfManufacture;
276 delete[] platformInfo.platformVersion;
277 delete[] platformInfo.operatingSystemVersion;
278 delete[] platformInfo.hardwareVersion;
279 delete[] platformInfo.firmwareVersion;
280 delete[] platformInfo.supportUrl;
281 delete[] platformInfo.systemTime;
284 void DeleteDeviceInfo()
286 delete[] deviceInfo.deviceName;
287 delete[] deviceInfo.specVersion;
288 OCFreeOCStringLL(deviceInfo.dataModelVersions);
291 void DuplicateString(char ** targetString, std::string sourceString)
293 *targetString = new char[sourceString.length() + 1];
294 strncpy(*targetString, sourceString.c_str(), (sourceString.length() + 1));
297 OCStackResult SetPlatformInfo(std::string platformID, std::string manufacturerName,
298 std::string manufacturerUrl, std::string modelNumber, std::string dateOfManufacture,
299 std::string platformVersion, std::string operatingSystemVersion, std::string hardwareVersion,
300 std::string firmwareVersion, std::string supportUrl, std::string systemTime)
302 DuplicateString(&platformInfo.platformID, platformID);
303 DuplicateString(&platformInfo.manufacturerName, manufacturerName);
304 DuplicateString(&platformInfo.manufacturerUrl, manufacturerUrl);
305 DuplicateString(&platformInfo.modelNumber, modelNumber);
306 DuplicateString(&platformInfo.dateOfManufacture, dateOfManufacture);
307 DuplicateString(&platformInfo.platformVersion, platformVersion);
308 DuplicateString(&platformInfo.operatingSystemVersion, operatingSystemVersion);
309 DuplicateString(&platformInfo.hardwareVersion, hardwareVersion);
310 DuplicateString(&platformInfo.firmwareVersion, firmwareVersion);
311 DuplicateString(&platformInfo.supportUrl, supportUrl);
312 DuplicateString(&platformInfo.systemTime, systemTime);
317 OCStackResult SetDeviceInfo(std::string deviceName, std::string specVersion, std::string dataModelVersions)
319 DuplicateString(&deviceInfo.deviceName, deviceName);
321 if (!specVersion.empty())
323 DuplicateString(&deviceInfo.specVersion, specVersion);
326 if (!dataModelVersions.empty())
328 OCResourcePayloadAddStringLL(&deviceInfo.dataModelVersions, dataModelVersions.c_str());
334 int main(int /*argc*/, char** /*argv[1]*/)
336 // Create PlatformConfig object
338 OC::ServiceType::InProc,
339 OC::ModeType::Server,
340 "0.0.0.0", // By setting to "0.0.0.0", it binds to all available interfaces
341 0, // Uses randomly available port
342 OC::QualityOfService::LowQos
345 OCPlatform::Configure(cfg);
346 std::cout << "Starting server & setting platform info\n";
348 OCStackResult result = SetPlatformInfo(platformId, manufacturerName, manufacturerLink,
349 modelNumber, dateOfManufacture, platformVersion, operatingSystemVersion,
350 hardwareVersion, firmwareVersion, supportLink, systemTime);
352 result = OCPlatform::registerPlatformInfo(platformInfo);
354 if (result != OC_STACK_OK)
356 std::cout << "Platform Registration failed\n";
360 result = SetDeviceInfo(deviceName, specVersion, dataModelVersions);
361 OCResourcePayloadAddStringLL(&deviceInfo.types, "oic.wk.d");
363 result = OCPlatform::registerDeviceInfo(deviceInfo);
365 if (result != OC_STACK_OK)
367 std::cout << "Device Registration failed\n";
372 // Invoke createResource function of class light.
373 myGarage.createResource();
375 DeletePlatformInfo();
377 // A condition variable will free the mutex it is given, then do a non-
378 // intensive block until 'notify' is called on it. In this case, since we
379 // don't ever call cv.notify, this should be a non-processor intensive version
382 std::condition_variable cv;
383 std::unique_lock<std::mutex> lock(blocker);
391 // No explicit call to stop the OCPlatform
392 // When OCPlatform destructor is invoked, internally we do Platform cleanup