Merge test folder of test branch
[iotivity.git] / test / src / tc / cs / gtest / csdk / src / helper / CSCsdkCloudClientHelper.cpp
1 /******************************************************************
2  *
3  * Copyright 2018 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 "CSCsdkCloudHelper.h"
22 #include "CSCsdkCloudClientHelper.h"
23 #include "CSCsdkUtilityHelper.h"
24
25
26 vector< SampleResource * > g_createdResourceList;
27 vector< shared_ptr< OCResource > > g_foundResourceList;
28 vector< OCResourceHandle > g_handleList;
29 OCRepresentation g_resourceRepresentation;
30
31 SampleResource *g_acSwitchResource;
32 SampleResource *g_acAirFlowResource;
33 SampleResource *g_acTemperatureResource;
34 SampleResource *g_acTimerResource;
35 SampleResource *g_acSwingResource;
36
37 bool g_hasCallbackArrived = false;
38 bool g_isObservingResource = false;
39 bool g_isAirConDeviceCreated = false;
40
41 QualityOfService g_qos = QualityOfService::LowQos;
42 OCConnectivityType g_connectivityType = CT_DEFAULT;
43 bool g_isSecuredServer = false;
44 bool g_isSecuredClient = false;
45 string g_commonSmartHomeUri = "URI";
46 string g_commonVendorUri = "Vendor";
47 ResourceHelper *g_resourceHelper;
48
49 static mutex s_mutex;
50 static const char CRED_FILE_SERVER[] = "oic_svr_db_server.dat";
51 static const char CRED_FILE_CLIENT[] = "oic_svr_db_client.dat";
52
53 void onResourceFound(shared_ptr< OCResource > resource)
54 {
55     s_mutex.lock();
56     cout << "Found a resource!!" << endl;
57
58     if (resource)
59     {
60         g_foundResourceList.push_back(resource);
61         cout << "uri of the found resource is " << resource->uri() << endl;
62         g_hasCallbackArrived = true;
63
64         cout << "Host of found resource: ";
65         cout << resource->host() << endl;
66         cout << "di( OCResource.sid() ) of found resource is = ";
67         cout << resource->sid() << endl;
68         cout << "unique identifier of found resource is = ";
69         cout << resource->uniqueIdentifier() << endl;
70     }
71     else
72     {
73         cout << "Found resource is invalid!!" << endl;
74     }
75
76     s_mutex.unlock();
77 }
78
79 void onPlatformInfoReceived(const OCRepresentation& rep)
80 {
81     cout << "\nPlatform Information received ---->\n";
82     string value;
83     string values[] =
84     { "pi", "Platform ID                    ", "mnmn", "Manufacturer name              ", "mnml",
85             "Manufacturer url               ", "mnmo", "Manufacturer Model No          ", "mndt",
86             "Manufactured Date              ", "mnpv", "Manufacturer Platform Version  ", "mnos",
87             "Manufacturer OS version        ", "mnhw", "Manufacturer hardware version  ", "mnfv",
88             "Manufacturer firmware version  ", "mnsl", "Manufacturer support url       ", "st",
89             "Manufacturer system time       " };
90
91     for (unsigned int i = 0; i < sizeof(values) / sizeof(values[0]); i += 2)
92     {
93         if (rep.getValue(values[i], value))
94         {
95             std::cout << values[i + 1] << " : " << value << std::endl;
96         }
97     }
98     g_resourceHelper->printRepresentation(rep);
99     g_hasCallbackArrived = true;
100 }
101
102 void onDeviceInfoReceived(const OCRepresentation& rep)
103 {
104     cout << "\nDevice Information received ---->\n";
105     string value;
106     string values[] =
107     { "di", "Device ID        ", "n", "Device name      ", "lcv", "Spec version url ", "dmv",
108             "Data Model Model ", };
109
110     for (unsigned int i = 0; i < sizeof(values) / sizeof(values[0]); i += 2)
111     {
112         if (rep.getValue(values[i], value))
113         {
114             std::cout << values[i + 1] << " : " << value << std::endl;
115         }
116     }
117
118     g_resourceHelper->printRepresentation(rep);
119     g_hasCallbackArrived = true;
120 }
121
122 // callback handler on GET request
123 void onGet(const HeaderOptions &headerOptions, const OCRepresentation &rep, const int eCode)
124 {
125     OC_UNUSED(headerOptions);
126     if (eCode == SUCCESS_RESPONSE || eCode == OC_STACK_OK)
127     {
128         cout << "Response: GET request was successful" << endl;
129
130         vector< string > interfacelist = rep.getResourceInterfaces();
131
132         bool isCollection = false;
133         for (auto interface = interfacelist.begin(); interface != interfacelist.end(); interface++)
134         {
135             if (((*interface).compare(GROUP_INTERFACE) == 0)
136                     || ((*interface).compare(BATCH_INTERFACE) == 0))
137             {
138                 isCollection = true;
139                 break;
140             }
141         }
142
143         if (isCollection)
144         {
145             vector< OCRepresentation > children = rep.getChildren();
146
147             cout << "\nCHILD RESOURCE OF GROUP" << endl;
148             for (auto iter = children.begin(); iter != children.end(); ++iter)
149             {
150                 cout << "\tURI :: " << (*iter).getUri() << endl;
151             }
152             cout << endl;
153         }
154         else
155         {
156             g_resourceRepresentation = rep;
157             cout << "THe GET Response has the following representation:" << endl;
158             g_resourceHelper->printRepresentation(rep);
159         }
160     }
161     else
162     {
163         cout << "onGET Response error: " << eCode << endl;
164     }
165     g_hasCallbackArrived = true;
166 }
167
168 void onPublish(const OCRepresentation &, const int &eCode)
169 {
170     cout << "Publish resource response received, code: " << eCode << endl;
171     g_hasCallbackArrived = true;
172 }
173
174 // callback handler on PUT request
175 void onPut(const HeaderOptions &headerOptions, const OCRepresentation &rep, const int eCode)
176 {
177     OC_UNUSED(headerOptions);
178
179     if (eCode == SUCCESS_RESPONSE || eCode == OC_STACK_RESOURCE_CREATED
180             || eCode == OC_STACK_RESOURCE_CHANGED)
181     {
182         cout << "Response: PUT request was successful" << endl;
183         cout << "THe PUT response has the following representation:" << endl;
184         g_resourceHelper->printRepresentation(rep);
185     }
186     else
187     {
188         cout << "onPUT Response error: " << eCode << endl;
189     }
190     g_hasCallbackArrived = true;
191 }
192
193 // callback handler on POST request
194 void onPost(const HeaderOptions &headerOptions, const OCRepresentation &rep, const int eCode)
195 {
196     OC_UNUSED(headerOptions);
197
198     if (eCode == SUCCESS_RESPONSE || eCode == OC_STACK_RESOURCE_CHANGED
199             || eCode == OC_STACK_RESOURCE_CREATED)
200     {
201         cout << "Response: POST request was successful" << endl;
202         cout << "THe POST Response has the following representation:" << endl;
203         g_resourceHelper->printRepresentation(rep);
204     }
205     else
206     {
207         cout << "onPOST Response error: " << eCode << endl;
208     }
209     g_hasCallbackArrived = true;
210
211 }
212
213 // callback handler on DELETE request
214 void onDelete(const HeaderOptions &headerOptions, const int eCode)
215 {
216     OC_UNUSED(headerOptions);
217
218     if (eCode == SUCCESS_RESPONSE || eCode == OC_STACK_RESOURCE_DELETED)
219     {
220         cout << "Response: DELETE request was successful" << endl;
221     }
222     else
223     {
224         cout << "onDELETE Response error: " << eCode << endl;
225     }
226     g_hasCallbackArrived = true;
227 }
228
229 void onObserve(const HeaderOptions headerOptions, const OCRepresentation &rep, const int &eCode,
230         const int &sequenceNumber)
231 {
232     OC_UNUSED(headerOptions);
233     try
234     {
235         if (eCode == SUCCESS_RESPONSE || eCode == OC_STACK_OK)
236         {
237             cout << "OBSERVE RESULT:" << endl;
238             cout << "\tSequenceNumber: " << sequenceNumber << endl;
239             ResourceHelper::getInstance()->printRepresentation(rep);
240         }
241         else
242         {
243             cout << "Observe Response/Notification Error: " << eCode << endl;
244         }
245     }
246     catch (exception &e)
247     {
248         cout << "Exception: " << e.what() << " in onObserve" << endl;
249     }
250     g_hasCallbackArrived = true;
251 }
252
253 void waitForCallback()
254 {
255     int elapsedSecond = 0;
256     while (g_hasCallbackArrived == false)
257     {
258         g_resourceHelper->waitInSecond(CALLBACK_WAIT_MIN);
259         elapsedSecond++;
260         if (elapsedSecond > CALLBACK_WAIT_MAX)
261         {
262             break;
263         }
264     }
265 }
266
267 FILE* server_fopen(const char *path, const char *mode)
268 {
269     (void) path;
270     return fopen(CRED_FILE_SERVER, mode);
271 }
272
273 FILE* client_fopen(const char *path, const char *mode)
274 {
275     (void) path;
276     return fopen(CRED_FILE_CLIENT, mode);
277 }
278
279 void createAirConDevice(bool isSecured)
280 {
281
282     OCStackResult result = OC_STACK_ERROR;
283     if (g_isAirConDeviceCreated == false)
284     {
285         cout << "Creating AirCon Device Resources!!" << endl;
286         vector<string> deviceTypes;
287         deviceTypes.push_back(Device_TYPE_AC);
288         SampleResource::setDeviceInfo("Vendor Smart Home AirCon Device", deviceTypes);
289
290         g_acSwitchResource = new SampleResource();
291         g_acSwitchResource->setResourceProperties(AC_SWITCH_URI, SWITCH_RESOURCE_TYPE,
292         SWITCH_RESOURCE_INTERFACE);
293         g_acSwitchResource->setAsDiscoverableResource();
294         g_acSwitchResource->setAsObservableResource();
295         if (isSecured)
296         {
297             g_acSwitchResource->setAsSecuredResource();
298         }
299         OCRepresentation switchRep;
300         string key = BINARY_SWITCH_KEY;
301         string value = "";
302         vector< int > range;
303         vector< double > rangeTemperature;
304         switchRep.setValue(key, BINARY_SWITCH_VALUE);
305         g_acSwitchResource->setResourceRepresentation(switchRep);
306
307         result = g_acSwitchResource->startResource();
308
309         if (result == OC_STACK_OK)
310         {
311             cout << "AirConditioner Binary Switch Resource created successfully" << endl;
312             g_createdResourceList.push_back(g_acSwitchResource);
313             g_isAirConDeviceCreated = true;
314         }
315         else
316         {
317             cout << "Unable to create AirConditioner Binary Switch resource" << endl;
318         }
319
320         g_acTemperatureResource = new SampleResource();
321         g_acTemperatureResource->setResourceProperties(AC_TEMPERATURE_URI,
322         TEMPERATURE_RESOURCE_TYPE,
323         TEMPERATURE_RESOURCE_INTERFACE);
324         g_acTemperatureResource->setAsDiscoverableResource();
325         g_acTemperatureResource->setAsObservableResource();
326         if (isSecured)
327         {
328             g_acTemperatureResource->setAsSecuredResource();
329         }
330         OCRepresentation temperatureRep;
331         value = TEMPERATURE_UNITS_SUPPORTED_VALUE;
332         key = TEMPERATURE_UNITS_KEY;
333         temperatureRep.setValue(key, value);
334         g_acTemperatureResource->setAsReadOnly(key);
335         rangeTemperature.push_back(TEMPERATURE_RANGE_START_VALUE);
336         rangeTemperature.push_back(TEMPERATURE_RANGE_END_VALUE);
337         key = TEMPERATURE_RANGE_KEY;
338         temperatureRep.setValue(key, rangeTemperature);
339         g_acTemperatureResource->setAsReadOnly(key);
340         double temperature = TEMPERATURE_VALUE;
341         key = TEMPERATURE_KEY;
342         temperatureRep.setValue(key, temperature);
343         g_acTemperatureResource->setResourceRepresentation(temperatureRep);
344         result = g_acTemperatureResource->startResource();
345
346         if (result == OC_STACK_OK)
347         {
348             cout << "Air Conditioner Temperature Resource created successfully" << endl;
349             g_createdResourceList.push_back(g_acTemperatureResource);
350             g_isAirConDeviceCreated = true;
351         }
352         else
353         {
354             cout << "Unable to create Air Conditioner Temperature resource" << endl;
355         }
356
357     }
358     else
359     {
360         cout << "Already Smart Home AirCon Device Resources are  created!!" << endl;
361     }
362
363 }
364
365 void publishResource() {
366     g_hasCallbackArrived = false;
367     ResourceHandles resourceHandles;
368     resourceHandles.push_back(g_acSwitchResource->getResourceHandle());
369     resourceHandles.push_back(g_acTemperatureResource->getResourceHandle());
370
371     RDClient::Instance().publishResourceToRD(CloudCommonUtil::getDefaultHostAddess().c_str(), OCConnectivityType::CT_ADAPTER_TCP,
372              resourceHandles,
373              &onPublish);
374
375     waitForCallback();
376 }
377
378 void findAllResources(string host, string query)
379 {
380     g_foundResourceList.clear();
381     std::ostringstream requestURI;
382
383     try
384     {
385         // makes it so that all boolean values are printed as 'true/false' in this stream
386         std::cout.setf(std::ios::boolalpha);
387         // Find all resources
388         if (query.compare("") == 0)
389         {
390             requestURI << OC_RSRVD_WELL_KNOWN_URI;
391         }
392         else
393         {
394             requestURI << OC_RSRVD_WELL_KNOWN_URI << "?" << query;
395         }
396
397         OCPlatform::findResource(host, requestURI.str(), OCConnectivityType::CT_DEFAULT,
398                 &onResourceFound, g_qos);
399         cout << "Finding Resource...." << endl;
400
401     }
402     catch (OCException &e)
403     {
404         oclog() << "Exception in main: " << e.what();
405     }
406     waitForCallback();
407 }
408
409 AttributeValue getResourceAttributeValue(string uri, string& key)
410 {
411     AttributeValue value;
412     static double temperatureValue = 25;
413     static string directionValue = "left";
414     static int hourValue = 1;
415     static bool swingerValue = true;
416     static bool binaryValue = false;
417
418     if (!uri.compare(AC_SWITCH_URI) || !uri.compare(AC_SWITCH_URI_CHILD))
419     {
420         key = string(ON_OFF_KEY);
421         value = binaryValue = !binaryValue;
422     }
423     else if (!uri.compare(AC_TEMPERATURE_URI) || !uri.compare(AC_TEMPERATURE_URI_CHILD))
424     {
425         key = string(TEMPERATURE_KEY);
426         value = temperatureValue =
427                 temperatureValue > 0 ? (temperatureValue - 26) : (temperatureValue + 26);
428     }
429     else if (!uri.compare(AC_AIR_FLOW_URI) || !uri.compare(AC_AIR_FLOW_URI_CHILD))
430     {
431         key = string(DIRECTION_KEY);
432         value = directionValue = directionValue.compare("left") ? "left" : "right";
433     }
434     else if (!uri.compare(AC_TIMER_URI) || !uri.compare(AC_TIMER_URI_CHILD))
435     {
436         key = string(TIMER_HOUR_KEY);
437         value = (hourValue % 2) ? (hourValue * 2) : (hourValue / 2);
438     }
439     else if (!uri.compare(AC_SWING_URI) || !uri.compare(AC_SWING_URI_CHILD))
440     {
441         key = string("x.com.vendor.swing.on");
442         value = swingerValue = !swingerValue;
443     }
444
445     return value;
446 }
447
448 void sendGetRequest(ResourceSelectionType type)
449 {
450     vector< shared_ptr< OCResource > > remoteResourceList = getRemoteResourceList(type);
451     if (remoteResourceList.size() > 0)
452     {
453         QueryParamsMap qpMap;
454         for (auto resource : remoteResourceList)
455         {
456             g_hasCallbackArrived = false;
457             cout << "Sending Get Request to the resource: " << resource->host() << resource->uri()
458                     << endl;
459             resource->get(qpMap, onGet, g_qos);
460             cout << "GET request sent!!" << endl;
461         }
462
463         waitForCallback();
464
465     }
466     else
467     {
468         cout << "No resource to send GET!!" << endl;
469     }
470 }
471
472 void sendPutRequest(ResourceSelectionType type)
473 {
474
475     vector< shared_ptr< OCResource > > remoteResourceList = getRemoteResourceList(type);
476     if (remoteResourceList.size() > 0)
477     {
478         OCRepresentation rep;
479         QueryParamsMap qpMap;
480         string key = REGION_KEY;
481         string value = DEFAULT_REGION;
482         rep.setValue(key, value);
483         key = POWER_KEY;
484         value = DEFAULT_POWER_STATE;
485         rep.setValue(key, value);
486         key = INTENSITY_KEY;
487         value = DEFAULT_INTENSITY;
488         rep.setValue(key, value);
489         key = MANUFACTURER_KEY;
490         value = DEFAULT_MANUFACTURER;
491         rep.setValue(key, value);
492
493         for (auto resource : remoteResourceList)
494         {
495             g_hasCallbackArrived = false;
496             cout << "Sending PUT Request to the resource: " << resource->host() << resource->uri()
497                     << endl;
498             resource->put(rep, qpMap, onPut, g_qos);
499             cout << "PUT request sent!!" << endl;
500         }
501
502         waitForCallback();
503
504     }
505     else
506     {
507         cout << "No resource to send PUT!!" << endl;
508     }
509 }
510
511 void sendPostRequest(ResourceSelectionType type)
512 {
513     vector< shared_ptr< OCResource > > remoteResourceList = getRemoteResourceList(type);
514     if (remoteResourceList.size() > 0)
515     {
516         OCRepresentation rep;
517         QueryParamsMap qpMap;
518         string key = "";
519         AttributeValue value;
520
521         for (auto resource : remoteResourceList)
522         {
523             g_hasCallbackArrived = false;
524             if (ResourceSelectionType::VERTICAL_RESOURCE == type)
525             {
526                 value = getResourceAttributeValue(resource->uri(), key);
527             }
528             else if (ResourceSelectionType::SYSTEM_RESOURCE == type)
529             {
530                 key = REGION_KEY;
531                 value = DEFAULT_REGION;
532             }
533
534             rep.setValue(key, value);
535             cout << "Sending POST Request to the resource: " << resource->host() << resource->uri()
536                     << endl;
537             resource->post(rep, qpMap, onPost, g_qos);
538             cout << "POST request sent!!" << endl;
539         }
540
541         waitForCallback();
542
543     }
544     else
545     {
546         cout << "No resource to send POST!!" << endl;
547     }
548 }
549
550 void sendDeleteRequest(ResourceSelectionType type)
551 {
552     vector< shared_ptr< OCResource > > remoteResourceList = getRemoteResourceList(type);
553     if (remoteResourceList.size() > 0)
554     {
555         for (auto resource : remoteResourceList)
556         {
557             g_hasCallbackArrived = false;
558             cout << "Sending Delete Request to the resource: " << resource->host()
559                     << resource->uri() << endl;
560             resource->deleteResource(onDelete, g_qos);
561             cout << "Delete request sent!!" << endl;
562         }
563
564         waitForCallback();
565
566     }
567     else
568     {
569         cout << "No resource to send Delete!!" << endl;
570     }
571 }
572
573 void observeResource(ResourceSelectionType type)
574 {
575     vector< shared_ptr< OCResource > > remoteResourceList = getRemoteResourceList(type);
576     if (remoteResourceList.size() > 0)
577     {
578         for (auto resource : remoteResourceList)
579         {
580             g_hasCallbackArrived = false;
581             cout << "Sending Observe Request to the resource: " << resource->host()
582                     << resource->uri() << endl;
583             resource->observe(ObserveType::Observe, QueryParamsMap(), &onObserve, g_qos);
584             cout << "Observe request sent!!" << endl;
585         }
586         g_isObservingResource = true;
587         waitForCallback();
588     }
589     else
590     {
591         cout << "No resource to Observe!!" << endl;
592     }
593 }
594
595 string getHost()
596 {
597     string host = "";
598
599     for (auto resource : g_foundResourceList)
600     {
601         if (resource->uri().compare(AC_TEMPERATURE_URI) == 0)
602         {
603             host = resource->host();
604             break;
605         }
606     }
607     if (host.compare("") == 0)
608     {
609         cout << "No remote resource found to send Unicast" << endl;
610     }
611     return host;
612 }
613
614 vector< shared_ptr< OCResource > > getRemoteResourceList(ResourceSelectionType type)
615 {
616     vector< shared_ptr< OCResource > > desiredResourceList;
617     desiredResourceList.clear();
618     string remoteHost = getHost();
619
620     for (auto resource : g_foundResourceList)
621     {
622         if (ResourceSelectionType::VERTICAL_NON_OBSERVABLE_RESOURCE == type)
623         {
624             if (resource->uri().compare(AC_TIMER_URI) == 0)
625             {
626                 desiredResourceList.clear();
627                 desiredResourceList.push_back(resource);
628                 break;
629             }
630         }
631         else if (ResourceSelectionType::VERTICAL_OBSERVABLE_RESOURCE == type)
632         {
633             if (resource->uri().find(g_commonSmartHomeUri) != string::npos)
634             {
635                 desiredResourceList.push_back(resource);
636             }
637
638         }
639         else if (ResourceSelectionType::VERTICAL_RESOURCE == type)
640         {
641             if ((resource->uri().find(g_commonVendorUri) != string::npos)
642                     || (resource->uri().find(g_commonSmartHomeUri) != string::npos))
643             {
644                 desiredResourceList.push_back(resource);
645             }
646
647         }
648         else
649         {
650             if ((remoteHost.compare(resource->host()) == 0)
651                     && ((resource->uri().compare(OC_RSRVD_DEVICE_URI) == 0)
652                             || (resource->uri().compare(OC_RSRVD_PLATFORM_URI) == 0)))
653             {
654                 desiredResourceList.push_back(resource);
655             }
656         }
657     }
658     return desiredResourceList;
659 }
660
661