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::vector<std::string> dataModelVersions = {"res.1.1.0"};
55 std::string protocolIndependentID = "1cbab786-ca5f-4eb9-89b2-e90eb4820145";
57 // OCPlatformInfo Contains all the platform info to be stored
58 OCPlatformInfo platformInfo;
60 // Forward declaring the entityHandler
61 OCEntityHandlerResult entityHandler(std::shared_ptr<OCResourceRequest> request);
63 /// This class represents a single resource named 'GarageResource'.
67 /// Access this property from a TB client
70 std::string m_garageUri;
71 OCResourceHandle m_resourceHandle;
72 OCRepresentation m_garageRep;
73 ObservationIds m_interestedObservers;
75 // array of lights representation with in GarageResource
76 OCRepresentation m_lightRep;
77 std::vector<OCRepresentation> m_reps;
78 std::vector<std::vector<int>> m_hingeStates;
82 GarageResource(): m_name("John's Garage"), m_state(false), m_garageUri("/a/garage"),
83 m_hingeStates{{1,2,3},{4,5,6}}
85 // Initialize representation
86 m_garageRep.setUri(m_garageUri);
88 m_garageRep["state"] = m_state;
89 m_garageRep["name"] = m_name;
91 // For demonstration purpose we are setting x to nullptr here.
92 // In reality it may happen else where.
93 m_garageRep["nullAttribute"] = nullptr;
95 std::vector<bool> lightStates;
96 std::vector<int> lightPowers;
98 for(int i = 0; i <= 9; i++)
100 lightStates.push_back(i % 2 == 0);
101 lightPowers.push_back(i);
104 m_lightRep["states"] = lightStates;
105 m_lightRep["powers"] = lightPowers;
107 // Storing another representation within a representation
108 m_garageRep["light"] = m_lightRep;
110 OCRepresentation rep1;
112 rep1["key1"] = value1;
113 OCRepresentation rep2;
115 rep2["key2"] = value2;
117 m_reps.push_back(rep1);
118 m_reps.push_back(rep2);
120 // storing array of representations
121 m_garageRep["reps"] = m_reps;
124 // setting json string
125 std::string json = "{\"num\":10,\"rno\":23.5,\"aoa\":[[1,2],[3]],\"str\":\"john\",\
126 \"object\":{\"bl1\":false,\"ar\":[2,3]}, \"objects\":[{\"bl2\":true,\"nl\":null},{\"ar1\":[1,2]}]}";
127 m_garageRep["json"] = json;
129 m_garageRep["hinges"] = m_hingeStates;
132 /* Note that this does not need to be a member function: for classes you do not have
133 access to, you can accomplish this with a free function: */
135 /// This function internally calls registerResource API.
136 void createResource()
138 std::string resourceURI = m_garageUri; // URI of the resource
139 std::string resourceTypeName = "core.garage"; // resource type name.
140 std::string resourceInterface = DEFAULT_INTERFACE; // resource interface.
142 // OCResourceProperty is defined ocstack.h
143 uint8_t resourceProperty = OC_DISCOVERABLE | OC_OBSERVABLE;
145 // This will internally create and register the resource.
146 OCStackResult result = OCPlatform::registerResource(
147 m_resourceHandle, resourceURI, resourceTypeName,
148 resourceInterface, &entityHandler, resourceProperty);
150 if (OC_STACK_OK != result)
152 cout << "Resource creation was unsuccessful\n";
156 OCResourceHandle getHandle()
158 return m_resourceHandle;
161 // Puts representation.
162 // Gets values from the representation and
163 // updates the internal state
164 void put(OCRepresentation& rep)
167 if (rep.getValue("state", m_state))
169 cout << "\t\t\t\t" << "state: " << m_state << endl;
173 cout << "\t\t\t\t" << "state not found in the representation" << endl;
178 cout << e.what() << endl;
183 // gets the updated representation.
184 // Updates the representation with latest internal state before
186 OCRepresentation get()
188 m_garageRep["state"] = m_state;
195 // Create the instance of the resource class (in this case instance of class 'GarageResource').
196 GarageResource myGarage;
198 OCStackResult sendResponse(std::shared_ptr<OCResourceRequest> pRequest)
200 auto pResponse = std::make_shared<OC::OCResourceResponse>();
201 pResponse->setRequestHandle(pRequest->getRequestHandle());
202 pResponse->setResourceHandle(pRequest->getResourceHandle());
203 pResponse->setResourceRepresentation(myGarage.get());
204 pResponse->setResponseResult(OC_EH_OK);
206 return OCPlatform::sendResponse(pResponse);
209 OCEntityHandlerResult entityHandler(std::shared_ptr<OCResourceRequest> request)
211 cout << "\tIn Server CPP entity handler:\n";
212 OCEntityHandlerResult ehResult = OC_EH_ERROR;
216 // Get the request type and request flag
217 std::string requestType = request->getRequestType();
218 int requestFlag = request->getRequestHandlerFlag();
220 if(requestFlag & RequestHandlerFlag::RequestFlag)
222 cout << "\t\trequestFlag : Request\n";
224 // If the request type is GET
225 if(requestType == "GET")
227 cout << "\t\t\trequestType : GET\n";
228 if(OC_STACK_OK == sendResponse(request))
233 else if(requestType == "PUT")
235 cout << "\t\t\trequestType : PUT\n";
236 OCRepresentation rep = request->getResourceRepresentation();
237 // Do related operations related to PUT request
239 if(OC_STACK_OK == sendResponse(request))
244 else if(requestType == "POST")
246 // POST request operations
248 else if(requestType == "DELETE")
250 // DELETE request operations
253 if(requestFlag & RequestHandlerFlag::ObserverFlag)
255 // OBSERVE operations
260 std::cout << "Request invalid" << std::endl;
266 void DeletePlatformInfo()
268 delete[] platformInfo.platformID;
269 delete[] platformInfo.manufacturerName;
270 delete[] platformInfo.manufacturerUrl;
271 delete[] platformInfo.modelNumber;
272 delete[] platformInfo.dateOfManufacture;
273 delete[] platformInfo.platformVersion;
274 delete[] platformInfo.operatingSystemVersion;
275 delete[] platformInfo.hardwareVersion;
276 delete[] platformInfo.firmwareVersion;
277 delete[] platformInfo.supportUrl;
278 delete[] platformInfo.systemTime;
281 void DuplicateString(char ** targetString, std::string sourceString)
283 *targetString = new char[sourceString.length() + 1];
284 strncpy(*targetString, sourceString.c_str(), (sourceString.length() + 1));
287 OCStackResult SetPlatformInfo(std::string platformID, std::string manufacturerName,
288 std::string manufacturerUrl, std::string modelNumber, std::string dateOfManufacture,
289 std::string platformVersion, std::string operatingSystemVersion, std::string hardwareVersion,
290 std::string firmwareVersion, std::string supportUrl, std::string systemTime)
292 DuplicateString(&platformInfo.platformID, platformID);
293 DuplicateString(&platformInfo.manufacturerName, manufacturerName);
294 DuplicateString(&platformInfo.manufacturerUrl, manufacturerUrl);
295 DuplicateString(&platformInfo.modelNumber, modelNumber);
296 DuplicateString(&platformInfo.dateOfManufacture, dateOfManufacture);
297 DuplicateString(&platformInfo.platformVersion, platformVersion);
298 DuplicateString(&platformInfo.operatingSystemVersion, operatingSystemVersion);
299 DuplicateString(&platformInfo.hardwareVersion, hardwareVersion);
300 DuplicateString(&platformInfo.firmwareVersion, firmwareVersion);
301 DuplicateString(&platformInfo.supportUrl, supportUrl);
302 DuplicateString(&platformInfo.systemTime, systemTime);
307 OCStackResult SetDeviceInfo()
309 OCStackResult result = OCPlatform::setPropertyValue(PAYLOAD_TYPE_DEVICE, OC_RSRVD_DEVICE_NAME,
311 if (result != OC_STACK_OK)
313 cout << "Failed to set device name" << endl;
317 result = OCPlatform::setPropertyValue(PAYLOAD_TYPE_DEVICE, OC_RSRVD_DATA_MODEL_VERSION,
319 if (result != OC_STACK_OK)
321 cout << "Failed to set data model versions" << endl;
325 result = OCPlatform::setPropertyValue(PAYLOAD_TYPE_DEVICE, OC_RSRVD_SPEC_VERSION, specVersion);
326 if (result != OC_STACK_OK)
328 cout << "Failed to set spec version" << endl;
332 result = OCPlatform::setPropertyValue(PAYLOAD_TYPE_DEVICE, OC_RSRVD_PROTOCOL_INDEPENDENT_ID,
333 protocolIndependentID);
334 if (result != OC_STACK_OK)
336 cout << "Failed to set piid" << endl;
343 int main(int /*argc*/, char** /*argv[1]*/)
345 // Create PlatformConfig object
347 OC::ServiceType::InProc,
348 OC::ModeType::Server,
349 "0.0.0.0", // By setting to "0.0.0.0", it binds to all available interfaces
350 0, // Uses randomly available port
351 OC::QualityOfService::LowQos
354 OCPlatform::Configure(cfg);
355 std::cout << "Starting server & setting platform info\n";
357 OCStackResult result = SetPlatformInfo(platformId, manufacturerName, manufacturerLink,
358 modelNumber, dateOfManufacture, platformVersion, operatingSystemVersion,
359 hardwareVersion, firmwareVersion, supportLink, systemTime);
361 result = OCPlatform::registerPlatformInfo(platformInfo);
363 if (result != OC_STACK_OK)
365 std::cout << "Platform Registration failed\n";
369 result = SetDeviceInfo();
371 if (result != OC_STACK_OK)
373 std::cout << "Device Registration failed\n";
379 // Invoke createResource function of class light.
380 myGarage.createResource();
382 DeletePlatformInfo();
383 // A condition variable will free the mutex it is given, then do a non-
384 // intensive block until 'notify' is called on it. In this case, since we
385 // don't ever call cv.notify, this should be a non-processor intensive version
388 std::condition_variable cv;
389 std::unique_lock<std::mutex> lock(blocker);
397 // No explicit call to stop the OCPlatform
398 // When OCPlatform destructor is invoked, internally we do Platform cleanup