Deprecate OCSetDeviceInfo and registerDeviceInfo
[platform/upstream/iotivity.git] / resource / examples / presenceserver.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 steps to define an interface for a resource
23 /// (properties and methods) and host this resource on the server.
24 ///
25
26 #include "iotivity_config.h"
27 #include <functional>
28
29 #ifdef HAVE_PTHREAD_H
30 #include <pthread.h>
31 #endif
32 #include <array>
33 #include <mutex>
34 #include <condition_variable>
35
36 #include "OCPlatform.h"
37 #include "OCApi.h"
38 #include "ocpayload.h"
39
40 #ifdef HAVE_WINDOWS_H
41 #include <windows.h>
42 #endif
43
44 using namespace OC;
45 using namespace std;
46
47 #define numPresenceResources (2)
48
49 // Set of strings for each of platform Info fields
50 std::string  platformId = "0A3E0D6F-DBF5-404E-8719-D6880042463A";
51 std::string  manufacturerName = "OCF";
52 std::string  manufacturerLink = "https://www.iotivity.org";
53 std::string  modelNumber = "myModelNumber";
54 std::string  dateOfManufacture = "2016-01-15";
55 std::string  platformVersion = "myPlatformVersion";
56 std::string  operatingSystemVersion = "myOS";
57 std::string  hardwareVersion = "myHardwareVersion";
58 std::string  firmwareVersion = "1.0";
59 std::string  supportLink = "https://www.iotivity.org";
60 std::string  systemTime = "2016-01-15T11.01";
61
62 // Set of strings for each of device info fields
63 std::string  deviceName = "IoTivity Presence Server";
64 std::string  specVersion = "core.1.1.0";
65 std::vector<std::string> dataModelVersions = {"res.1.1.0"};
66
67 // OCPlatformInfo Contains all the platform info to be stored
68 OCPlatformInfo platformInfo;
69
70 // Forward declaring the entityHandler
71 OCEntityHandlerResult entityHandler(std::shared_ptr<OCResourceRequest> request);
72
73 /// This class represents a single resource named 'lightResource'. This resource has
74 /// two simple properties named 'state' and 'power'
75
76 class LightResource
77 {
78 public:
79     /// Access this property from a TB client
80     bool m_state;
81     int m_power;
82     std::string m_lightUri;
83     std::string m_lightUri2;
84     std::string m_lightUri3;
85     OCResourceHandle m_resourceHandle;
86     OCResourceHandle m_resourceHandle2;
87     OCResourceHandle m_resourceHandle3;
88
89 public:
90     /// Constructor
91     LightResource(): m_state(false), m_power(0), m_lightUri("/a/light"),
92                      m_lightUri2("/a/light2"),m_lightUri3("/a/light3") {}
93
94     /* Note that this does not need to be a member function: for classes you do not have
95     access to, you can accomplish this with a free function: */
96
97     /// This function internally calls registerResource API.
98     void createResource()
99     {
100         std::string resourceURI = m_lightUri; // URI of the resource
101         std::string resourceTypeName = "core.light"; // resource type name.
102         std::string resourceInterface = DEFAULT_INTERFACE; // resource interface.
103
104         // OCResourceProperty is defined ocstack.h
105         uint8_t resourceProperty = OC_DISCOVERABLE | OC_OBSERVABLE;
106
107         // This will internally create and register the resource.
108         OCStackResult result = OCPlatform::registerResource(
109                                     m_resourceHandle, resourceURI, resourceTypeName,
110                                     resourceInterface, &entityHandler, resourceProperty);
111
112         if (OC_STACK_OK != result)
113         {
114             cout << "Resource creation was unsuccessful\n";
115         }
116     }
117
118     /// This function internally calls registerResource API.
119     void createResource2()
120     {
121         std::string resourceURI = m_lightUri2; // URI of the resource
122         std::string resourceTypeName = "core.light"; // resource type name. In this case, it is light
123         std::string resourceInterface = DEFAULT_INTERFACE; // resource interface.
124
125         // OCResourceProperty is defined ocstack.h
126         uint8_t resourceProperty = OC_DISCOVERABLE | OC_OBSERVABLE;
127
128         // This will internally create and register the resource.
129         OCStackResult result = OCPlatform::registerResource(
130                                     m_resourceHandle2, resourceURI, resourceTypeName,
131                                     resourceInterface, &entityHandler, resourceProperty);
132
133         if (OC_STACK_OK != result)
134         {
135             cout << "Resource creation was unsuccessful\n";
136         }
137     }
138
139     void createResource3()
140     {
141         std::string resourceURI = m_lightUri3; // URI of the resource
142         std::string resourceTypeName = "core.light";
143         std::string resourceInterface = DEFAULT_INTERFACE; // resource interface.
144
145         // OCResourceProperty is defined ocstack.h
146         uint8_t resourceProperty = OC_DISCOVERABLE | OC_OBSERVABLE;
147
148         // This will internally create and register the resource.
149         OCStackResult result = OCPlatform::registerResource(
150                                     m_resourceHandle3, resourceURI, resourceTypeName,
151                                     resourceInterface, &entityHandler, resourceProperty);
152
153         if (OC_STACK_OK != result)
154         {
155             cout << "Resource creation was unsuccessful\n";
156         }
157     }
158
159     OCResourceHandle getHandle()
160     {
161         return m_resourceHandle;
162     }
163
164     void addType(const std::string& type) const
165     {
166         OCStackResult result = OC::OCPlatform::bindTypeToResource(m_resourceHandle, type);
167         if (OC_STACK_OK != result)
168         {
169             cout << "Binding TypeName to Resource was unsuccessful\n";
170         }
171     }
172
173     void addInterface(const std::string& iface) const
174     {
175         OCStackResult result = OC::OCPlatform::bindInterfaceToResource(m_resourceHandle, iface);
176         if (OC_STACK_OK != result)
177         {
178             cout << "Binding TypeName to Resource was unsuccessful\n";
179         }
180     }
181
182 };
183
184 void createPresenceResources()
185 {
186     std::array<std::string, numPresenceResources> resourceURI { {
187         "/a/fan",
188         "/a/led" } };
189     std::array<std::string, numPresenceResources> resourceTypeName { {
190         "core.fan",
191         "core.led" } };
192
193     std::string resourceInterface = DEFAULT_INTERFACE; // resource interface.
194     OCResourceHandle handle;
195     // OCResourceProperty is defined ocstack.h
196     uint8_t resourceProperty = OC_DISCOVERABLE | OC_OBSERVABLE;
197
198     // This will internally create and register the resource.
199     OCStackResult result = OC_STACK_OK;
200     for(int i=0; i<numPresenceResources; i++)
201     {
202         result = OCPlatform::registerResource(handle,
203                 resourceURI.at(i), resourceTypeName.at(i), resourceInterface,
204                 &entityHandler, resourceProperty);
205         if (result != OC_STACK_OK)
206         {
207             cout << "Resource creation was unsuccessful with resource URI "
208                     << resourceURI.at(i);
209         }
210     }
211 }
212
213 // Create the instance of the resource class (in this case instance of class 'LightResource').
214 LightResource myLightResource;
215
216 OCEntityHandlerResult entityHandler(std::shared_ptr<OCResourceRequest> /*request*/)
217 {
218     cout << "\tIn Server CPP entity handler:\n";
219     return OC_EH_OK;
220 }
221
222 void DeletePlatformInfo()
223 {
224     delete[] platformInfo.platformID;
225     delete[] platformInfo.manufacturerName;
226     delete[] platformInfo.manufacturerUrl;
227     delete[] platformInfo.modelNumber;
228     delete[] platformInfo.dateOfManufacture;
229     delete[] platformInfo.platformVersion;
230     delete[] platformInfo.operatingSystemVersion;
231     delete[] platformInfo.hardwareVersion;
232     delete[] platformInfo.firmwareVersion;
233     delete[] platformInfo.supportUrl;
234     delete[] platformInfo.systemTime;
235 }
236
237 void DuplicateString(char ** targetString, std::string sourceString)
238 {
239     *targetString = new char[sourceString.length() + 1];
240     strncpy(*targetString, sourceString.c_str(), (sourceString.length() + 1));
241 }
242
243 OCStackResult SetPlatformInfo(std::string platformID, std::string manufacturerName,
244         std::string manufacturerUrl, std::string modelNumber, std::string dateOfManufacture,
245         std::string platformVersion, std::string operatingSystemVersion,
246         std::string hardwareVersion, std::string firmwareVersion, std::string supportUrl,
247         std::string systemTime)
248 {
249     DuplicateString(&platformInfo.platformID, platformID);
250     DuplicateString(&platformInfo.manufacturerName, manufacturerName);
251     DuplicateString(&platformInfo.manufacturerUrl, manufacturerUrl);
252     DuplicateString(&platformInfo.modelNumber, modelNumber);
253     DuplicateString(&platformInfo.dateOfManufacture, dateOfManufacture);
254     DuplicateString(&platformInfo.platformVersion, platformVersion);
255     DuplicateString(&platformInfo.operatingSystemVersion, operatingSystemVersion);
256     DuplicateString(&platformInfo.hardwareVersion, hardwareVersion);
257     DuplicateString(&platformInfo.firmwareVersion, firmwareVersion);
258     DuplicateString(&platformInfo.supportUrl, supportUrl);
259     DuplicateString(&platformInfo.systemTime, systemTime);
260
261     return OC_STACK_OK;
262 }
263
264 OCStackResult SetDeviceInfo()
265 {
266     OCStackResult result = OCPlatform::setPropertyValue(PAYLOAD_TYPE_DEVICE, OC_RSRVD_DEVICE_NAME,
267                                                         deviceName);
268     if (result != OC_STACK_OK)
269     {
270         cout << "Failed to set device name" << endl;
271         return result;
272     }
273
274     result = OCPlatform::setPropertyValue(PAYLOAD_TYPE_DEVICE, OC_RSRVD_DATA_MODEL_VERSION,
275                                           dataModelVersions);
276     if (result != OC_STACK_OK)
277     {
278         cout << "Failed to set data model versions" << endl;
279         return result;
280     }
281
282     result = OCPlatform::setPropertyValue(PAYLOAD_TYPE_DEVICE, OC_RSRVD_SPEC_VERSION, specVersion);
283     if (result != OC_STACK_OK)
284     {
285         cout << "Failed to set spec version" << endl;
286         return result;
287     }
288
289     return OC_STACK_OK;
290 }
291
292 int main()
293 {
294     // Create PlatformConfig object
295     PlatformConfig cfg {
296         OC::ServiceType::InProc,
297         OC::ModeType::Server,
298         "0.0.0.0", // By setting to "0.0.0.0", it binds to all available interfaces
299         0,         // Uses randomly available port
300         OC::QualityOfService::LowQos
301     };
302
303     OCPlatform::Configure(cfg);
304     std::cout << "Starting server & setting platform info\n";
305
306     OCStackResult result = SetPlatformInfo(platformId, manufacturerName, manufacturerLink,
307             modelNumber, dateOfManufacture, platformVersion, operatingSystemVersion,
308             hardwareVersion, firmwareVersion, supportLink, systemTime);
309
310     result = OCPlatform::registerPlatformInfo(platformInfo);
311
312     if (result != OC_STACK_OK)
313     {
314         std::cout << "Platform Registration failed\n";
315         return -1;
316     }
317
318     result = SetDeviceInfo();
319     if (result != OC_STACK_OK)
320     {
321         std::cout << "Device Registration failed\n";
322         return -1;
323     }
324
325     try
326     {
327         using namespace OC::OCPlatform;
328         // Time to Live is 30 seconds
329         startPresence(30);
330
331         // Invoke createResource function of class light.
332         myLightResource.createResource();
333         std :: cout << "Creating first resource of type \"core.light\"" << std :: endl;
334
335         std :: cout << "Will start creating/deleting resources for presence in 10 seconds.\n";
336
337         sleep(10);
338
339         std :: cout << "\nCreating the second resource of type \"core.light\"" <<  std :: endl;
340         sleep(1);
341
342         myLightResource.createResource2();
343
344         std :: cout << "Stopping presence\n" << std :: endl;
345         sleep(1);
346         stopPresence();
347
348         std :: cout << "Restarting presence\n" << std :: endl;
349         sleep(1);
350
351         startPresence(30);
352
353         std :: cout << "Creating a third resource of type \"core.light\"\n" << std :: endl;
354         sleep(1);
355
356         myLightResource.createResource3();
357
358         std :: cout << "Creating two non-operational resources.\"\n" << std :: endl;
359         sleep(1);
360
361         createPresenceResources();
362
363         DeletePlatformInfo();
364
365         // A condition variable will free the mutex it is given, then do a non-
366         // intensive block until 'notify' is called on it.  In this case, since we
367         // don't ever call cv.notify, this should be a non-processor intensive version
368         // of while(true);
369         std::mutex blocker;
370         std::condition_variable cv;
371         std::unique_lock<std::mutex> lock(blocker);
372         cv.wait(lock);
373     }
374     catch(OCException& e)
375     {
376         oclog() << "Exception in main: "<< e.what();
377     }
378
379     // No explicit call to stop the platform.
380     // When OCPlatform destructor is invoked, internally we do platform cleanup
381
382     return 0;
383 }
384