f3414f6d72992ea4a3ec4726726447c7492e0423
[platform/upstream/iotivity.git] / service / easy-setup / mediator / richsdk / src / RemoteEnrolleeResource.cpp
1 //******************************************************************
2 //
3 // Copyright 2015 Samsung Electronics 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 #include <functional>
22 #include <time.h>
23
24 #include "RemoteEnrolleeResource.h"
25
26 #include "OCPlatform.h"
27 #include "ESException.h"
28 #include "OCResource.h"
29 #include "logger.h"
30
31 namespace OIC
32 {
33     namespace Service
34     {
35         #define ES_REMOTE_ENROLLEE_RES_TAG "ES_REMOTE_ENROLLEE_RES"
36         #define DISCOVERY_TIMEOUT 5
37
38         static const char ES_BASE_RES_URI[] = "/oic/res";
39         static const char ES_PROV_RES_URI[] = "/oic/prov";
40         static const char ES_PROV_RES_TYPE[] = "oic.r.prov";
41
42         RemoteEnrolleeResource::RemoteEnrolleeResource(ProvConfig provConfig,
43                                                   WiFiOnboadingConnection onboardingconn)
44         {
45             m_ProvConfig = provConfig;
46             m_wifiOnboardingconn = onboardingconn;
47             m_discoveryResponse = false;
48         }
49
50         void RemoteEnrolleeResource::triggerNetworkConnectionCb(
51                 const HeaderOptions& /*headerOptions*/, const OCRepresentation& rep,
52                 const int eCode)
53         {
54             OIC_LOG_V (DEBUG, ES_REMOTE_ENROLLEE_RES_TAG, "checkProvInformationCb : %s, eCode = %d",
55                     rep.getUri().c_str(),
56                     eCode);
57
58             if (eCode != 0)
59             {
60                 OIC_LOG_V (DEBUG, ES_REMOTE_ENROLLEE_RES_TAG,
61                         "triggerNetworkConnectionCb : Trigger action failed ");
62                 std::shared_ptr< ProvisioningStatus > provStatus = std::make_shared<
63                         ProvisioningStatus >(ESResult::ES_ERROR, ESState::ES_PROVISIONING_ERROR);
64                 m_provStatusCb(provStatus);
65                 return;
66             }
67             else
68             {
69                 OIC_LOG_V (DEBUG, ES_REMOTE_ENROLLEE_RES_TAG,
70                         "triggerNetworkConnectionCb : Provisioning is success ");
71                 std::shared_ptr< ProvisioningStatus > provStatus = std::make_shared<
72                         ProvisioningStatus >(ESResult::ES_OK, ESState::ES_PROVISIONING_SUCCESS);
73                 m_provStatusCb(provStatus);
74                 return;
75             }
76         }
77
78         void RemoteEnrolleeResource::triggerNetworkConnection()
79         {
80             if (m_ocResource == nullptr)
81             {
82                 throw ESBadRequestException("Resource is not initialized");
83             }
84
85             OCRepresentation provisioningRepresentation;
86
87             provisioningRepresentation.setValue(OC_RSRVD_ES_TR, 1);
88
89             m_ocResource->post(provisioningRepresentation, QueryParamsMap(),
90                     std::function<
91                             void(const HeaderOptions& headerOptions, const OCRepresentation& rep,
92                                     const int eCode) >(
93                             std::bind(&RemoteEnrolleeResource::triggerNetworkConnectionCb, this,
94                                     std::placeholders::_1, std::placeholders::_2,
95                                     std::placeholders::_3)));
96         }
97
98         void RemoteEnrolleeResource::checkProvInformationCb(const HeaderOptions& /*headerOptions*/,
99                 const OCRepresentation& rep, const int eCode)
100         {
101             OIC_LOG_V (DEBUG, ES_REMOTE_ENROLLEE_RES_TAG, "checkProvInformationCb : %s, eCode = %d",
102                     rep.getUri().c_str(),
103                     eCode);
104
105             if (eCode != 0)
106             {
107                 OIC_LOG_V (DEBUG, ES_REMOTE_ENROLLEE_RES_TAG,
108                         "checkProvInformationCb : Provisioning is failed ");
109                 std::shared_ptr< ProvisioningStatus > provStatus = std::make_shared<
110                         ProvisioningStatus >(ESResult::ES_ERROR, ESState::ES_PROVISIONING_ERROR);
111                 m_provStatusCb(provStatus);
112                 return;
113             }
114
115             int ps = -1;
116
117             rep.getValue(OC_RSRVD_ES_PS, ps);
118
119             OIC_LOG_V (DEBUG, ES_REMOTE_ENROLLEE_RES_TAG, "checkProvInformationCb : ps - %d", ps);
120
121             //Provisioning status check
122             if (ps == ES_PS_PROVISIONING_COMPLETED)
123             {
124                 OIC_LOG_V (DEBUG, ES_REMOTE_ENROLLEE_RES_TAG,
125                         "checkProvInformationCb : Provisioning is success. "
126                         "Now trigger network connection ");
127
128                 triggerNetworkConnection();
129                 return;
130             }
131             else
132             {
133                 OIC_LOG_V (DEBUG, ES_REMOTE_ENROLLEE_RES_TAG,
134                         "checkProvInformationCb : Provisioning is failed ");
135                 std::shared_ptr< ProvisioningStatus > provStatus = std::make_shared<
136                         ProvisioningStatus >(ESResult::ES_ERROR, ESState::ES_PROVISIONING_ERROR);
137                 m_provStatusCb(provStatus);
138                 return;
139             }
140         }
141
142         void RemoteEnrolleeResource::getProvStatusResponse(const HeaderOptions& /*headerOptions*/,
143                 const OCRepresentation& rep, const int eCode)
144         {
145             OIC_LOG_V (DEBUG, ES_REMOTE_ENROLLEE_RES_TAG, "getProvStatusResponse : %s, eCode = %d",
146                     rep.getUri().c_str(),
147                     eCode);
148
149             if (eCode != 0)
150             {
151                 OIC_LOG_V (DEBUG, ES_REMOTE_ENROLLEE_RES_TAG,
152                         "getProvStatusResponse : Provisioning is failed ");
153                 std::shared_ptr< ProvisioningStatus > provStatus = std::make_shared<
154                         ProvisioningStatus >(ESResult::ES_ERROR, ESState::ES_PROVISIONING_ERROR);
155                 m_provStatusCb(provStatus);
156                 return;
157             }
158
159             int ps = -1;
160
161             rep.getValue(OC_RSRVD_ES_PS, ps);
162
163             OIC_LOG_V (DEBUG, ES_REMOTE_ENROLLEE_RES_TAG, "getProvStatusResponse : ps - %d",
164                     ps);
165
166             if (ps == ES_PS_NEED_PROVISIONING) //Indicates the need for provisioning
167             {
168                 OCRepresentation provisioningRepresentation;
169
170                 provisioningRepresentation.setValue(OC_RSRVD_ES_TNN,
171                 std::string(m_ProvConfig.provData.WIFI.ssid));
172                 provisioningRepresentation.setValue(OC_RSRVD_ES_CD,
173                 std::string(m_ProvConfig.provData.WIFI.pwd));
174
175                 OIC_LOG_V (DEBUG, ES_REMOTE_ENROLLEE_RES_TAG, "getProvStatusResponse : ssid - %s",
176                         m_ProvConfig.provData.WIFI.ssid);
177                 OIC_LOG_V (DEBUG, ES_REMOTE_ENROLLEE_RES_TAG, "getProvStatusResponse : pwd - %s",
178                         m_ProvConfig.provData.WIFI.pwd);
179
180                 m_ocResource->post(provisioningRepresentation, QueryParamsMap(),
181                         std::function<
182                                 void(const HeaderOptions& headerOptions,
183                                         const OCRepresentation& rep, const int eCode) >(
184                         std::bind(&RemoteEnrolleeResource::checkProvInformationCb, this,
185                         std::placeholders::_1, std::placeholders::_2,
186                         std::placeholders::_3)));
187             }
188             else if (ps == ES_PS_PROVISIONING_COMPLETED) //Indicates that provisioning is completed
189             {
190                 OIC_LOG_V (DEBUG, ES_REMOTE_ENROLLEE_RES_TAG,
191                         "getProvStatusResponse : Provisioning is successful");
192                 std::shared_ptr< ProvisioningStatus > provStatus = std::make_shared<
193                         ProvisioningStatus >(ESResult::ES_OK, ESState::ES_PROVISIONED_ALREADY);
194                 m_provStatusCb(provStatus);
195             }
196         }
197
198         void RemoteEnrolleeResource::registerProvStatusCallback(ProvStatusCb provStatusCb)
199         {
200             m_provStatusCb = provStatusCb;
201         }
202
203         ESResult RemoteEnrolleeResource::ESDiscoveryTimeout(unsigned short waittime)
204         {
205             struct timespec startTime;
206             startTime.tv_sec=0;
207             startTime.tv_sec=0;
208             struct timespec currTime;
209             currTime.tv_sec=0;
210             currTime.tv_nsec=0;
211
212             ESResult res = ES_OK;
213             #ifdef _POSIX_MONOTONIC_CLOCK
214                 int clock_res = clock_gettime(CLOCK_MONOTONIC, &startTime);
215             #else
216                 int clock_res = clock_gettime(CLOCK_REALTIME, &startTime);
217             #endif
218
219             if (0 != clock_res)
220             {
221                 return ES_ERROR;
222             }
223
224             while (ES_OK == res || m_discoveryResponse == false)
225             {
226                 #ifdef _POSIX_MONOTONIC_CLOCK
227                         clock_res = clock_gettime(CLOCK_MONOTONIC, &currTime);
228                 #else
229                         clock_res = clock_gettime(CLOCK_REALTIME, &currTime);
230                 #endif
231
232                 if (0 != clock_res)
233                 {
234                     return ES_ERROR;
235                 }
236                 long elapsed = (currTime.tv_sec - startTime.tv_sec);
237                 if (elapsed > waittime)
238                 {
239                     return ES_OK;
240                 }
241                 if (m_discoveryResponse)
242                 {
243                     res = ES_OK;
244                 }
245              }
246              return res;
247         }
248
249         void RemoteEnrolleeResource::onDeviceDiscovered(std::shared_ptr<OC::OCResource> resource)
250         {
251             OIC_LOG (DEBUG, ES_REMOTE_ENROLLEE_RES_TAG, "onDeviceDiscovered");
252
253             std::string resourceURI;
254             std::string hostAddress;
255             try
256             {
257                 if(resource)
258                 {
259                     // Get the resource URI
260                     resourceURI = resource->uri();
261                     OIC_LOG_V (DEBUG, ES_REMOTE_ENROLLEE_RES_TAG,
262                             "URI of the resource: %s", resourceURI.c_str());
263
264                     // Get the resource host address
265                     hostAddress = resource->host();
266                     OIC_LOG_V (DEBUG, ES_REMOTE_ENROLLEE_RES_TAG,
267                             "Host address of the resource: %s", hostAddress.c_str());
268
269                     /*
270                      * Easysetup is always performed with a single Enrollee device and
271                      * in a private network (SoftAP or BLE), so the assumption is that
272                      * only the intended device will respond for the discovery.
273                      * With the above assumption the below two statements are written.
274                      */
275                     m_ocResource = resource;
276                     m_discoveryResponse = true;
277                 }
278                 else
279                 {
280                     OIC_LOG (DEBUG, ES_REMOTE_ENROLLEE_RES_TAG, "Resource is invalid");
281                 }
282
283             }
284             catch(std::exception& e)
285             {
286                 OIC_LOG_V (DEBUG, ES_REMOTE_ENROLLEE_RES_TAG,
287                         "Exception in foundResource: %s", e.what());
288             }
289         }
290
291
292         ESResult RemoteEnrolleeResource::constructResourceObject()
293         {
294             if (m_ocResource != nullptr)
295             {
296                 throw ESBadRequestException("Remote resource is already created");
297             }
298
299 #ifdef REMOTE_ARDUINO_ENROLEE
300             //This process will create OCResource with port 55555 which is specific
301             // to Arduino WiFi enrollee
302             try
303             {
304
305                 std::vector< std::string > interface =
306                 {   DEFAULT_INTERFACE};
307                 std::vector< std::string > resTypes =
308                 {   ES_PROV_RES_TYPE};
309
310                 OIC_LOG(DEBUG, ES_REMOTE_ENROLLEE_RES_TAG, "Before OCPlatform::constructResourceObject");
311
312                 OIC_LOG_V (DEBUG, ES_REMOTE_ENROLLEE_RES_TAG, "m_host = %s",
313                         m_wifiOnboardingconn.ipAddress);
314                 OIC_LOG_V (DEBUG, ES_REMOTE_ENROLLEE_RES_TAG, "ES_PROV_RES_URI = %s", ES_PROV_RES_URI);
315                 OIC_LOG_V (DEBUG, ES_REMOTE_ENROLLEE_RES_TAG, "m_connectivityType = %d",
316                         m_ProvConfig.connType);
317                 OIC_LOG_V (DEBUG, ES_REMOTE_ENROLLEE_RES_TAG, "resTypes = %s",
318                         resTypes.at(0).c_str());
319                 OIC_LOG_V (DEBUG, ES_REMOTE_ENROLLEE_RES_TAG, "interface = %s", interface.at(0).c_str());
320
321                 std::string host;
322                 if(m_wifiOnboardingconn.isSecured)
323                 {
324                     host.append("coaps://");
325                 }
326                 else
327                 {
328                     host.append("coap://");
329                 }
330
331                 if(m_ProvConfig.connType == CT_ADAPTER_IP)
332                 {
333                     // TODO : RemoteEnrollee is current handling easysetup on IP transport.
334                     // WiFiRemoteEnrollee need to extend RemoteEnrollee for providing IP specific
335                     // Enrollee easysetup.
336
337                     host.append(m_wifiOnboardingconn.ipAddress);
338                     //TODO : If the target Enrollee is not a Arduino Wi-Fi device,
339                     // then the port number will be found during resource discovery instead of
340                     // using 55555
341                     host.append(":55555");
342                 }
343
344                 OIC_LOG_V (DEBUG, ES_REMOTE_ENROLLEE_RES_TAG, "HOST = %s", host.c_str());
345
346                 m_ocResource = OC::OCPlatform::constructResourceObject(host,
347                         ES_PROV_RES_URI,
348                         m_ProvConfig.connType,
349                         true,
350                         resTypes,
351                         interface);
352                 OIC_LOG_V(DEBUG, ES_REMOTE_ENROLLEE_RES_TAG,
353                         "created OCResource : %s", m_ocResource->uri().c_str());
354
355                 return ES_OK;
356             }
357             catch (OCException & e)
358             {
359                 OIC_LOG_V(ERROR, ES_REMOTE_ENROLLEE_RES_TAG,
360                         "Exception for constructResourceObject : %s", e.reason().c_str());
361                 return ES_ERROR;
362             }
363 #else
364             std::string host("");
365             std::string query("");
366
367             if (m_wifiOnboardingconn.isSecured)
368             {
369                 host.append("coaps://");
370             }
371             else
372             {
373                 host.append("coap://");
374             }
375
376             if (m_ProvConfig.connType == CT_ADAPTER_IP)
377             {
378                 // TODO : RemoteEnrollee is current handling easysetup on IP transport.
379                 // WiFiRemoteEnrollee need to extend RemoteEnrollee for providing IP specific
380                 // Enrollee easysetup.
381
382                 host.append(m_wifiOnboardingconn.ipAddress);
383             }
384
385             query.append(ES_BASE_RES_URI);
386             query.append("?rt=");
387             query.append(ES_PROV_RES_TYPE);
388
389             OIC_LOG(DEBUG, ES_REMOTE_ENROLLEE_RES_TAG, "Before OCPlatform::constructResourceObject");
390
391             OIC_LOG_V (DEBUG, ES_REMOTE_ENROLLEE_RES_TAG, "host = %s",
392                     host.c_str());
393             OIC_LOG_V (DEBUG, ES_REMOTE_ENROLLEE_RES_TAG, "query = %s", query.c_str());
394             OIC_LOG_V (DEBUG, ES_REMOTE_ENROLLEE_RES_TAG, "m_connectivityType = %d",
395                     m_ProvConfig.connType);
396
397             m_discoveryResponse = false;
398             std::function< void (std::shared_ptr<OC::OCResource>) > onDeviceDiscoveredCb =
399                     std::bind(&RemoteEnrolleeResource::onDeviceDiscovered, this,
400                                                     std::placeholders::_1);
401             OCStackResult result = OC::OCPlatform::findResource("", query, CT_DEFAULT,
402                     onDeviceDiscoveredCb);
403
404             if (result != OCStackResult::OC_STACK_OK)
405             {
406                 OIC_LOG(ERROR,ES_REMOTE_ENROLLEE_RES_TAG,
407                         "Failed to create device using constructResourceObject");
408                 return ES_ERROR;
409             }
410
411
412             ESResult foundResponse = ESDiscoveryTimeout (DISCOVERY_TIMEOUT);
413
414             if (foundResponse ==ES_ERROR || !m_discoveryResponse)
415             {
416                 OIC_LOG(ERROR,ES_REMOTE_ENROLLEE_RES_TAG,
417                         "Failed to create device using constructResourceObject");
418                 return ES_ERROR;
419             }
420
421             return ES_OK;
422 #endif
423         }
424
425         void RemoteEnrolleeResource::provisionEnrollee()
426
427         {
428             if (m_ocResource == nullptr)
429             {
430                 throw ESBadRequestException("Resource is not initialized");
431             }
432
433             OC::QueryParamsMap query;
434             OC::OCRepresentation rep;
435
436             std::function< OCStackResult(void) > getProvisioingStatus = [&]
437             {   return m_ocResource->get(m_ocResource->getResourceTypes().at(0),
438                         m_ocResource->getResourceInterfaces().at(0), query,
439                         std::function<
440                         void(const HeaderOptions& headerOptions, const OCRepresentation& rep,
441                                 const int eCode) >(
442                                 std::bind(&RemoteEnrolleeResource::getProvStatusResponse, this,
443                                         std::placeholders::_1, std::placeholders::_2,
444                                         std::placeholders::_3)));
445             };
446
447             OCStackResult result = getProvisioingStatus();
448
449             if (result != OCStackResult::OC_STACK_OK)
450             {
451                 std::shared_ptr< ProvisioningStatus > provStatus = std::make_shared<
452                         ProvisioningStatus >(ESResult::ES_ERROR, ESState::ES_PROVISIONING_ERROR);
453                 m_provStatusCb(provStatus);
454                 return;
455             }
456         }
457
458         void RemoteEnrolleeResource::unprovisionEnrollee()
459         {
460             if (m_ocResource == nullptr)
461             {
462                 throw ESBadRequestException("Resource is not initialized");
463             }
464
465             OCRepresentation provisioningRepresentation;
466
467             provisioningRepresentation.setValue(OC_RSRVD_ES_TNN, "");
468             provisioningRepresentation.setValue(OC_RSRVD_ES_CD, "");
469
470             m_ocResource->post(provisioningRepresentation, QueryParamsMap(),
471                     std::function<
472                             void(const HeaderOptions& headerOptions, const OCRepresentation& rep,
473                                     const int eCode) >(
474                     std::bind(&RemoteEnrolleeResource::checkProvInformationCb, this,
475                     std::placeholders::_1, std::placeholders::_2,
476                     std::placeholders::_3)));
477         }
478     }
479 }