Update snapshot(2017-12-14)
[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::string  dataModelVersions = "res.1.1.0";
55
56 // OCPlatformInfo Contains all the platform info to be stored
57 OCPlatformInfo platformInfo;
58
59 // OCDeviceInfo Contains all the device info to be stored
60 OCDeviceInfo deviceInfo;
61
62 // Forward declaring the entityHandler
63 OCEntityHandlerResult entityHandler(std::shared_ptr<OCResourceRequest> request);
64
65 /// This class represents a single resource named 'GarageResource'.
66 class GarageResource
67 {
68 public:
69     /// Access this property from a TB client
70     std::string m_name;
71     bool m_state;
72     std::string m_garageUri;
73     OCResourceHandle m_resourceHandle;
74     OCRepresentation m_garageRep;
75     ObservationIds m_interestedObservers;
76
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;
81
82 public:
83     /// Constructor
84     GarageResource(): m_name("John's Garage"), m_state(false), m_garageUri("/a/garage"),
85         m_hingeStates{{1,2,3},{4,5,6}}
86     {
87         // Initialize representation
88         m_garageRep.setUri(m_garageUri);
89
90         m_garageRep["state"] = m_state;
91         m_garageRep["name"] = m_name;
92
93         // For demonstration purpose we are setting x to nullptr here.
94         // In reality it may happen else where.
95         m_garageRep["nullAttribute"] = nullptr;
96
97         std::vector<bool> lightStates;
98         std::vector<int>  lightPowers;
99
100         for(int i = 0; i <= 9; i++)
101         {
102             lightStates.push_back(i % 2 == 0);
103             lightPowers.push_back(i);
104         }
105
106         m_lightRep["states"] = lightStates;
107         m_lightRep["powers"] = lightPowers;
108
109         // Storing another representation within a representation
110         m_garageRep["light"] = m_lightRep;
111
112         OCRepresentation rep1;
113         int value1 = 5;
114         rep1["key1"] = value1;
115         OCRepresentation rep2;
116         int value2 = 10;
117         rep2["key2"] = value2;
118
119         m_reps.push_back(rep1);
120         m_reps.push_back(rep2);
121
122         // storing array of representations
123         m_garageRep["reps"] =  m_reps;
124
125
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;
130
131         m_garageRep["hinges"] = m_hingeStates;
132     }
133
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: */
136
137     /// This function internally calls registerResource API.
138     void createResource()
139     {
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.
143
144         // OCResourceProperty is defined ocstack.h
145         uint8_t resourceProperty = OC_DISCOVERABLE | OC_OBSERVABLE;
146
147         // This will internally create and register the resource.
148         OCStackResult result = OCPlatform::registerResource(
149                                     m_resourceHandle, resourceURI, resourceTypeName,
150                                     resourceInterface, &entityHandler, resourceProperty);
151
152         if (OC_STACK_OK != result)
153         {
154             cout << "Resource creation was unsuccessful\n";
155         }
156     }
157
158     OCResourceHandle getHandle()
159     {
160         return m_resourceHandle;
161     }
162
163     // Puts representation.
164     // Gets values from the representation and
165     // updates the internal state
166     void put(OCRepresentation& rep)
167     {
168         try {
169             if (rep.getValue("state", m_state))
170             {
171                 cout << "\t\t\t\t" << "state: " << m_state << endl;
172             }
173             else
174             {
175                 cout << "\t\t\t\t" << "state not found in the representation" << endl;
176             }
177         }
178         catch (exception& e)
179         {
180             cout << e.what() << endl;
181         }
182
183     }
184
185     // gets the updated representation.
186     // Updates the representation with latest internal state before
187     // sending out.
188     OCRepresentation get()
189     {
190         m_garageRep["state"] = m_state;
191
192         return m_garageRep;
193     }
194
195 };
196
197 // Create the instance of the resource class (in this case instance of class 'GarageResource').
198 GarageResource myGarage;
199
200 OCStackResult sendResponse(std::shared_ptr<OCResourceRequest> pRequest)
201 {
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);
208
209     return OCPlatform::sendResponse(pResponse);
210 }
211
212 OCEntityHandlerResult entityHandler(std::shared_ptr<OCResourceRequest> request)
213 {
214     cout << "\tIn Server CPP entity handler:\n";
215     OCEntityHandlerResult ehResult = OC_EH_ERROR;
216
217     if(request)
218     {
219         // Get the request type and request flag
220         std::string requestType = request->getRequestType();
221         int requestFlag = request->getRequestHandlerFlag();
222
223         if(requestFlag & RequestHandlerFlag::RequestFlag)
224         {
225             cout << "\t\trequestFlag : Request\n";
226
227             // If the request type is GET
228             if(requestType == "GET")
229             {
230                 cout << "\t\t\trequestType : GET\n";
231                 if(OC_STACK_OK == sendResponse(request))
232                 {
233                     ehResult = OC_EH_OK;
234                 }
235             }
236             else if(requestType == "PUT")
237             {
238                 cout << "\t\t\trequestType : PUT\n";
239                 OCRepresentation rep = request->getResourceRepresentation();
240                 // Do related operations related to PUT request
241                 myGarage.put(rep);
242                 if(OC_STACK_OK == sendResponse(request))
243                 {
244                     ehResult = OC_EH_OK;
245                 }
246             }
247             else if(requestType == "POST")
248             {
249                 // POST request operations
250             }
251             else if(requestType == "DELETE")
252             {
253                 // DELETE request operations
254             }
255         }
256         if(requestFlag & RequestHandlerFlag::ObserverFlag)
257         {
258             // OBSERVE operations
259         }
260     }
261     else
262     {
263         std::cout << "Request invalid" << std::endl;
264     }
265
266     return ehResult;
267 }
268
269 void DeletePlatformInfo()
270 {
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;
282 }
283
284 void DeleteDeviceInfo()
285 {
286     delete[] deviceInfo.deviceName;
287     delete[] deviceInfo.specVersion;
288     OCFreeOCStringLL(deviceInfo.dataModelVersions);
289 }
290
291 void DuplicateString(char ** targetString, std::string sourceString)
292 {
293     *targetString = new char[sourceString.length() + 1];
294     strncpy(*targetString, sourceString.c_str(), (sourceString.length() + 1));
295 }
296
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)
301 {
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);
313
314     return OC_STACK_OK;
315 }
316
317 OCStackResult SetDeviceInfo(std::string deviceName, std::string specVersion, std::string dataModelVersions)
318 {
319     DuplicateString(&deviceInfo.deviceName, deviceName);
320
321     if (!specVersion.empty())
322     {
323         DuplicateString(&deviceInfo.specVersion, specVersion);
324     }
325
326     if (!dataModelVersions.empty())
327     {
328         OCResourcePayloadAddStringLL(&deviceInfo.dataModelVersions, dataModelVersions.c_str());
329     }
330
331     return OC_STACK_OK;
332 }
333
334 int main(int /*argc*/, char** /*argv[1]*/)
335 {
336     // Create PlatformConfig object
337     PlatformConfig cfg {
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
343     };
344
345     OCPlatform::Configure(cfg);
346     std::cout << "Starting server & setting platform info\n";
347
348     OCStackResult result = SetPlatformInfo(platformId, manufacturerName, manufacturerLink,
349             modelNumber, dateOfManufacture, platformVersion, operatingSystemVersion,
350             hardwareVersion, firmwareVersion, supportLink, systemTime);
351
352     result = OCPlatform::registerPlatformInfo(platformInfo);
353
354     if (result != OC_STACK_OK)
355     {
356         std::cout << "Platform Registration failed\n";
357         return -1;
358     }
359
360     result = SetDeviceInfo(deviceName, specVersion, dataModelVersions);
361     OCResourcePayloadAddStringLL(&deviceInfo.types, "oic.wk.d");
362
363     result = OCPlatform::registerDeviceInfo(deviceInfo);
364
365     if (result != OC_STACK_OK)
366     {
367         std::cout << "Device Registration failed\n";
368         return -1;
369     }
370     try
371     {
372         // Invoke createResource function of class light.
373         myGarage.createResource();
374
375         DeletePlatformInfo();
376         DeleteDeviceInfo();
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
380         // of while(true);
381         std::mutex blocker;
382         std::condition_variable cv;
383         std::unique_lock<std::mutex> lock(blocker);
384         cv.wait(lock);
385     }
386     catch(OCException e)
387     {
388         oclog() << e.what();
389     }
390
391     // No explicit call to stop the OCPlatform
392     // When OCPlatform destructor is invoked, internally we do Platform cleanup
393
394     return 0;
395 }
396