[IOT-1538] Add support for Protocol-Independent ID
[platform/upstream/iotivity.git] / resource / examples / garageserver.cpp
1 //******************************************************************
2 //
3 // Copyright 2014 Intel Mobile Communications GmbH All Rights Reserved.
4 //
5 //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
6 //
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
10 //
11 //      http://www.apache.org/licenses/LICENSE-2.0
12 //
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.
18 //
19 //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
20
21 ///
22 /// This sample provides using varous json types in the representation.
23 ///
24
25 #include <functional>
26
27 #include <pthread.h>
28 #include <mutex>
29 #include <condition_variable>
30
31 #include "OCPlatform.h"
32 #include "OCApi.h"
33 #include "ocpayload.h"
34
35 using namespace OC;
36 using namespace std;
37
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";
50
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";
56
57 // OCPlatformInfo Contains all the platform info to be stored
58 OCPlatformInfo platformInfo;
59
60 // Forward declaring the entityHandler
61 OCEntityHandlerResult entityHandler(std::shared_ptr<OCResourceRequest> request);
62
63 /// This class represents a single resource named 'GarageResource'.
64 class GarageResource
65 {
66 public:
67     /// Access this property from a TB client
68     std::string m_name;
69     bool m_state;
70     std::string m_garageUri;
71     OCResourceHandle m_resourceHandle;
72     OCRepresentation m_garageRep;
73     ObservationIds m_interestedObservers;
74
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;
79
80 public:
81     /// Constructor
82     GarageResource(): m_name("John's Garage"), m_state(false), m_garageUri("/a/garage"),
83         m_hingeStates{{1,2,3},{4,5,6}}
84     {
85         // Initialize representation
86         m_garageRep.setUri(m_garageUri);
87
88         m_garageRep["state"] = m_state;
89         m_garageRep["name"] = m_name;
90
91         // For demonstration purpose we are setting x to nullptr here.
92         // In reality it may happen else where.
93         m_garageRep["nullAttribute"] = nullptr;
94
95         std::vector<bool> lightStates;
96         std::vector<int>  lightPowers;
97
98         for(int i = 0; i <= 9; i++)
99         {
100             lightStates.push_back(i % 2 == 0);
101             lightPowers.push_back(i);
102         }
103
104         m_lightRep["states"] = lightStates;
105         m_lightRep["powers"] = lightPowers;
106
107         // Storing another representation within a representation
108         m_garageRep["light"] = m_lightRep;
109
110         OCRepresentation rep1;
111         int value1 = 5;
112         rep1["key1"] = value1;
113         OCRepresentation rep2;
114         int value2 = 10;
115         rep2["key2"] = value2;
116
117         m_reps.push_back(rep1);
118         m_reps.push_back(rep2);
119
120         // storing array of representations
121         m_garageRep["reps"] =  m_reps;
122
123
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;
128
129         m_garageRep["hinges"] = m_hingeStates;
130     }
131
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: */
134
135     /// This function internally calls registerResource API.
136     void createResource()
137     {
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.
141
142         // OCResourceProperty is defined ocstack.h
143         uint8_t resourceProperty = OC_DISCOVERABLE | OC_OBSERVABLE;
144
145         // This will internally create and register the resource.
146         OCStackResult result = OCPlatform::registerResource(
147                                     m_resourceHandle, resourceURI, resourceTypeName,
148                                     resourceInterface, &entityHandler, resourceProperty);
149
150         if (OC_STACK_OK != result)
151         {
152             cout << "Resource creation was unsuccessful\n";
153         }
154     }
155
156     OCResourceHandle getHandle()
157     {
158         return m_resourceHandle;
159     }
160
161     // Puts representation.
162     // Gets values from the representation and
163     // updates the internal state
164     void put(OCRepresentation& rep)
165     {
166         try {
167             if (rep.getValue("state", m_state))
168             {
169                 cout << "\t\t\t\t" << "state: " << m_state << endl;
170             }
171             else
172             {
173                 cout << "\t\t\t\t" << "state not found in the representation" << endl;
174             }
175         }
176         catch (exception& e)
177         {
178             cout << e.what() << endl;
179         }
180
181     }
182
183     // gets the updated representation.
184     // Updates the representation with latest internal state before
185     // sending out.
186     OCRepresentation get()
187     {
188         m_garageRep["state"] = m_state;
189
190         return m_garageRep;
191     }
192
193 };
194
195 // Create the instance of the resource class (in this case instance of class 'GarageResource').
196 GarageResource myGarage;
197
198 OCStackResult sendResponse(std::shared_ptr<OCResourceRequest> pRequest)
199 {
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);
205
206     return OCPlatform::sendResponse(pResponse);
207 }
208
209 OCEntityHandlerResult entityHandler(std::shared_ptr<OCResourceRequest> request)
210 {
211     cout << "\tIn Server CPP entity handler:\n";
212     OCEntityHandlerResult ehResult = OC_EH_ERROR;
213
214     if(request)
215     {
216         // Get the request type and request flag
217         std::string requestType = request->getRequestType();
218         int requestFlag = request->getRequestHandlerFlag();
219
220         if(requestFlag & RequestHandlerFlag::RequestFlag)
221         {
222             cout << "\t\trequestFlag : Request\n";
223
224             // If the request type is GET
225             if(requestType == "GET")
226             {
227                 cout << "\t\t\trequestType : GET\n";
228                 if(OC_STACK_OK == sendResponse(request))
229                 {
230                     ehResult = OC_EH_OK;
231                 }
232             }
233             else if(requestType == "PUT")
234             {
235                 cout << "\t\t\trequestType : PUT\n";
236                 OCRepresentation rep = request->getResourceRepresentation();
237                 // Do related operations related to PUT request
238                 myGarage.put(rep);
239                 if(OC_STACK_OK == sendResponse(request))
240                 {
241                     ehResult = OC_EH_OK;
242                 }
243             }
244             else if(requestType == "POST")
245             {
246                 // POST request operations
247             }
248             else if(requestType == "DELETE")
249             {
250                 // DELETE request operations
251             }
252         }
253         if(requestFlag & RequestHandlerFlag::ObserverFlag)
254         {
255             // OBSERVE operations
256         }
257     }
258     else
259     {
260         std::cout << "Request invalid" << std::endl;
261     }
262
263     return ehResult;
264 }
265
266 void DeletePlatformInfo()
267 {
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;
279 }
280
281 void DuplicateString(char ** targetString, std::string sourceString)
282 {
283     *targetString = new char[sourceString.length() + 1];
284     strncpy(*targetString, sourceString.c_str(), (sourceString.length() + 1));
285 }
286
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)
291 {
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);
303
304     return OC_STACK_OK;
305 }
306
307 OCStackResult SetDeviceInfo()
308 {
309     OCStackResult result = OCPlatform::setPropertyValue(PAYLOAD_TYPE_DEVICE, OC_RSRVD_DEVICE_NAME,
310                                                         deviceName);
311     if (result != OC_STACK_OK)
312     {
313         cout << "Failed to set device name" << endl;
314         return result;
315     }
316
317     result = OCPlatform::setPropertyValue(PAYLOAD_TYPE_DEVICE, OC_RSRVD_DATA_MODEL_VERSION,
318                                           dataModelVersions);
319     if (result != OC_STACK_OK)
320     {
321         cout << "Failed to set data model versions" << endl;
322         return result;
323     }
324
325     result = OCPlatform::setPropertyValue(PAYLOAD_TYPE_DEVICE, OC_RSRVD_SPEC_VERSION, specVersion);
326     if (result != OC_STACK_OK)
327     {
328         cout << "Failed to set spec version" << endl;
329         return result;
330     }
331
332     result = OCPlatform::setPropertyValue(PAYLOAD_TYPE_DEVICE, OC_RSRVD_PROTOCOL_INDEPENDENT_ID,
333                                           protocolIndependentID);
334     if (result != OC_STACK_OK)
335     {
336         cout << "Failed to set piid" << endl;
337         return result;
338     }
339
340     return OC_STACK_OK;
341 }
342
343 int main(int /*argc*/, char** /*argv[1]*/)
344 {
345     // Create PlatformConfig object
346     PlatformConfig cfg {
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
352     };
353
354     OCPlatform::Configure(cfg);
355     std::cout << "Starting server & setting platform info\n";
356
357     OCStackResult result = SetPlatformInfo(platformId, manufacturerName, manufacturerLink,
358             modelNumber, dateOfManufacture, platformVersion, operatingSystemVersion,
359             hardwareVersion, firmwareVersion, supportLink, systemTime);
360
361     result = OCPlatform::registerPlatformInfo(platformInfo);
362
363     if (result != OC_STACK_OK)
364     {
365         std::cout << "Platform Registration failed\n";
366         return -1;
367     }
368
369     result = SetDeviceInfo();
370
371     if (result != OC_STACK_OK)
372     {
373         std::cout << "Device Registration failed\n";
374         return -1;
375     }
376
377     try
378     {
379         // Invoke createResource function of class light.
380         myGarage.createResource();
381
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
386         // of while(true);
387         std::mutex blocker;
388         std::condition_variable cv;
389         std::unique_lock<std::mutex> lock(blocker);
390         cv.wait(lock);
391     }
392     catch(OCException e)
393     {
394         oclog() << e.what();
395     }
396
397     // No explicit call to stop the OCPlatform
398     // When OCPlatform destructor is invoked, internally we do Platform cleanup
399
400     return 0;
401 }
402