Imported Upstream version 1.0.1
[platform/upstream/iotivity.git] / service / simulator / examples / server / service_provider.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 "simulator_manager.h"
22
23 class AppLogger : public ILogger
24 {
25     public:
26         void write(std::string time, ILogger::Level level, std::string message)
27         {
28             std::cout << "[APPLogger] " << time << " " << ILogger::getString(level) << " "
29                     << message;
30         }
31 };
32 std::shared_ptr<AppLogger> gAppLogger(new AppLogger());
33
34 class SimLightResource
35 {
36     public:
37         void startTest()
38         {
39             printMenu();
40             bool cont = true;
41             while (cont)
42             {
43                 int choice = -1;
44                 std::cout << "Enter your choice: ";
45                 std::cin >> choice;
46                 if (choice < 0 || choice > 10)
47                 {
48                     std::cout << "Invaild choice !" << std::endl; continue;
49                 }
50
51                 switch (choice)
52                 {
53                     case 1 : simulateResource(); break;
54                     case 2 : displayResource(); break;
55                     case 3 : deleteResource(); break;
56                     case 4 : updateAttributePower(); break;
57                     case 5 : updateAttributeIntensity(); break;
58                     case 6 : automateResourceUpdate(); break;
59                     case 7 : automateAttributeUpdate(); break;
60                     case 8 : stopAutomation(); break;
61                     case 9 : getObservers(); break;
62                     case 10: printMenu(); break;
63                     case 0: cont = false;
64                 }
65             }
66         }
67
68     private:
69         void printMenu()
70         {
71             std::cout << "########### LIGHT RESOURCE TESTING ###########" << std::endl;
72             std::cout << "1. Simulate resource" << std::endl;
73             std::cout << "2. Display resource information" << std::endl;
74             std::cout << "3. Delete resource" << std::endl;
75             std::cout << "4. Update attribute \"power\"" << std::endl;
76             std::cout << "5. Update attribute \"intensity\"" << std::endl;
77             std::cout << "6. Automate resource update" << std::endl;
78             std::cout << "7. Automate attributes update" << std::endl;
79             std::cout << "8. Stop Automation" << std::endl;
80             std::cout << "9. Get Observers of a resource" << std::endl;
81             std::cout << "10: Help" << std::endl;
82             std::cout << "0. Exit" << std::endl;
83             std::cout << "#######################################" << std::endl;
84         }
85
86         int selectResource()
87         {
88             if (0 == m_resources.size())
89             {
90                 std::cout << "No resouces!" << std::endl;
91                 return -1;
92             }
93
94             int index = 1;
95             for (auto & resource : m_resources)
96             {
97                 std::cout << index++ << ": " << resource->getURI().c_str() << std::endl;
98             }
99
100             int choice = -1;
101             std::cout << "Choose the resource: ";
102             std::cin >> choice;
103
104             if (choice < 1 || choice > index - 1)
105             {
106                 std::cout << "Invalid choice !" << std::endl;
107                 choice = -1;
108             }
109
110             return choice;
111         }
112
113         void onResourceModelChanged(const std::string &uri,
114                                     const SimulatorResourceModel &resModel)
115         {
116             std::cout << "[callback] Resource model is changed URI: " << uri.c_str()
117                     << " Count : " << resModel.size() << std::endl;
118             std::cout << "#### Modified attributes are ####" << std::endl;
119             for (auto & attribute : resModel.getAttributes())
120             {
121                 std::cout << attribute.second.getName() << " :  "
122                         << attribute.second.valueToString().c_str() << std::endl;
123             }
124             std::cout << "########################" << std::endl;
125         }
126
127         void simulateResource()
128         {
129             SimulatorResourceServer::ResourceModelChangedCB callback = std::bind(
130                         &SimLightResource::onResourceModelChanged, this, std::placeholders::_1,
131                         std::placeholders::_2);
132
133             try
134             {
135                 std::string configPath;
136                 std::cout << "Enter RAML path: ";
137                 std::cin>>configPath;
138                 SimulatorResourceServerSP resource =
139                         SimulatorManager::getInstance()->createResource(configPath, callback);
140                 m_resources.push_back(resource);
141                 std::cout << "Resource created successfully! URI= " << resource->getURI().c_str()
142                         << std::endl;
143             }
144             catch (InvalidArgsException &e)
145             {
146                 std::cout << "InvalidArgsException occured [code : " << e.code() << " Detail: "
147                         << e.what() << "]" << std::endl;
148             }
149             catch (SimulatorException &e)
150             {
151                 std::cout << "SimulatorException occured [code : " << e.code() << " Detail: "
152                         << e.what() << "]" << std::endl;
153             }
154         }
155
156         void deleteResource()
157         {
158             int choice = -1;
159             std::cout << "1. Delete single resource" << std::endl;
160             std::cout << "2. Delete resources on resource types" << std::endl;
161             std::cout << "3. Delete all resources" << std::endl;
162
163             std::cout << "Enter your choice: ";
164             std::cin >> choice;
165             if (choice < 1 || choice > 3)
166             {
167                 std::cout << "Invalid choice !" << std::endl;
168                 return;
169             }
170
171             switch (choice)
172             {
173                 case 1:
174                     {
175                         int index = selectResource();
176                         if (-1 == index)
177                             return;
178
179                         SimulatorManager::getInstance()->deleteResource(m_resources[index - 1]);
180                         std::cout << "Resource deleted successfully! " << std::endl;
181                         m_resources.erase(m_resources.begin() + (index - 1));
182
183                     } break;
184
185                 case 2:
186                     {
187                         std::string resourceType;
188                         std::cout  << "Enter resource type:  ";
189                         std::cin >> resourceType;
190                         if (resourceType.empty())
191                         {
192                             std::cout << "Invalid resource type!" << std::endl;
193                             break;
194                         }
195
196                         try
197                         {
198                             SimulatorManager::getInstance()->deleteResource(resourceType);
199                             std::cout << "Resources of type \"" << resourceType << "\"" <<
200                                     " deleted successfully! " << std::endl;
201                             std::vector<SimulatorResourceServerSP>::iterator ite = m_resources.begin();
202                             while (ite != m_resources.end())
203                             {
204                                 if (!resourceType.compare((*ite)->getResourceType()))
205                                 {
206                                     ite = m_resources.erase(ite);
207                                     continue;
208                                 }
209                                 ite++;
210                             }
211                         }
212                         catch (InvalidArgsException &e)
213                         {
214                             std::cout << "InvalidArgsException occured [code : " << e.code()
215                                     << " Detail: " << e.what() << "]" << std::endl;
216                         }
217                         catch (SimulatorException &e)
218                         {
219                             std::cout << "SimulatorException occured [code : " << e.code()
220                                     << " Detail: " << e.what() << "]" << std::endl;
221                         }
222                     } break;
223
224                 case 3:
225                     {
226                         SimulatorManager::getInstance()->deleteResource();
227                         std::cout << "All resources deleted successfully! " << std::endl;
228                         m_resources.clear();
229                     } break;
230             }
231
232         }
233
234         void updateAttributePower()
235         {
236             int index = selectResource();
237             if (-1 == index)
238                 return;
239
240             SimulatorResourceServerSP resource = m_resources[index - 1];
241             SimulatorResourceModel resModel = resource->getModel();
242             SimulatorResourceModel::Attribute powerAttribute;
243             resModel.getAttribute("power", powerAttribute);
244
245             int allowedValuesSize = powerAttribute.getAllowedValuesSize();
246             if (0 == allowedValuesSize)
247             {
248                 std::cout << "This attribute does not have allowed values!" << std::endl;
249                 return;
250             }
251
252             std::cout << "Setting the new values from allowed values list to power attribute" <<
253                     std::endl;
254             // Update all possible values from allowed values
255             for (int index = 0; index < allowedValuesSize; index++)
256             {
257                 // Update the new value and display the resource model after modifying
258                 resource->updateFromAllowedValues("power", index);
259                 std::cout << "Attribute value is modified ####" << std::endl;
260
261                 // Display the resource to user to verify the changed attribute value
262                 displayResource(resource);
263                 std::cout << std::endl << std::endl;
264
265                 // Get user input for continuing this operation
266                 if ((index + 1) < allowedValuesSize)
267                 {
268                     int choice;
269                     std::cout << "Would you like to change attribute value again ? (1/0): ";
270                     std::cin >> choice;
271                     if (0 == choice)
272                         break;
273                 }
274             }
275
276             std::cout << "All the allowed values are tried!" << std::endl;
277         }
278
279         void updateAttributeIntensity()
280         {
281             int index = selectResource();
282             if (-1 == index)
283                 return;
284
285             SimulatorResourceServerSP resource = m_resources[index - 1];
286             SimulatorResourceModel resModel = resource->getModel();
287             SimulatorResourceModel::Attribute intensityAttribute;
288             resModel.getAttribute("intensity", intensityAttribute);
289
290             int min, max;
291             intensityAttribute.getRange(min, max);
292             if (!min && !max)
293             {
294                 std::cout << "This attribute does not have range!" << std::endl;
295                 return;
296             }
297
298             std::cout << "Setting the new values from allowed values list to intensity attribute"
299                     << std::endl;
300             // Update all possible values from allowed values
301             for (int index = min; index <= max; index++)
302             {
303                 // Update the new value and display the resource model after modifying
304                 resource->updateAttributeValue("intensity", index);
305                 std::cout << "Attribute value is modified ####" << std::endl;
306
307                 // Display the resource to user to verify the changed attribute value
308                 displayResource(resource);
309                 std::cout << std::endl << std::endl;
310
311                 // Get user input for continuing this operation
312                 if ((index + 1) <= max)
313                 {
314                     int choice;
315                     std::cout << "Would you like to change attribute value again ? (1/0): ";
316                     std::cin >> choice;
317                     if (0 == choice)
318                         break;
319                 }
320             }
321
322             std::cout << "All the allowed values are tried!" << std::endl;
323         }
324
325         void displayResource()
326         {
327             int index = selectResource();
328             if (-1 == index)
329                 return;
330
331             SimulatorResourceServerSP resource = m_resources[index - 1];
332             displayResource(resource);
333         }
334
335         void displayResource(SimulatorResourceServerSP resource)
336         {
337             std::cout << "#############################" << std::endl;
338             std::cout << "Name: " << resource->getName().c_str() << std::endl;
339             std::cout << "URI: " << resource->getURI().c_str() << std::endl;
340             std::cout << "R. Type: " << resource->getResourceType().c_str() << std::endl;
341             std::cout << "I. Type: " << resource->getInterfaceType().c_str() << std::endl;
342
343             // Attributes
344             SimulatorResourceModel resModel = resource->getModel();
345             std::map<std::string, SimulatorResourceModel::Attribute> attributes =
346                     resModel.getAttributes();
347             std::cout << "##### Attributes [" << attributes.size() << "]" << std::endl;
348             for (auto & attribute : attributes)
349             {
350                 std::cout << (attribute.second).getName() << " :  {" << std::endl;
351                 std::cout << "value: " << (attribute.second).valueToString().c_str() << std::endl;
352                 int min, max;
353                 (attribute.second).getRange(min, max);
354                 std::cout << "min: " << min << std::endl;
355                 std::cout << "max: " << max << std::endl;
356                 std::cout << "allowed values : ";
357                 std::cout << "[ ";
358                 for (auto & value : (attribute.second).allowedValuesToString())
359                     std::cout << value << " ";
360                 std::cout << "]" << std::endl;
361                 std::cout << "}" << std::endl << std::endl;
362             }
363             std::cout << "#############################" << std::endl;
364         }
365
366         void onUpdateAutomationCompleted(const std::string &uri,
367                                          const int id)
368         {
369             std::cout << "Update automation is completed [URI: " << uri.c_str()
370                     << "  AutomationID: " << id << "] ###" << std::endl;
371         }
372
373         void automateResourceUpdate()
374         {
375             int index = selectResource();
376             if (-1 == index)
377                 return;
378
379             AutomationType type = AutomationType::NORMAL;
380             int choice = 0;
381             std::cout << "Press 1 if you want recurrent automation: ";
382             std::cin >> choice;
383             if (1 == choice)
384                 type = AutomationType::RECURRENT;
385
386             try
387             {
388                 int id = m_resources[index - 1]->startUpdateAutomation(type, 500,
389                          std::bind(&SimLightResource::onUpdateAutomationCompleted, this,
390                                  std::placeholders::_1, std::placeholders::_2));
391
392                 std::cout << "startUpdateAutomation() returned succces : " << id << std::endl;
393             }
394             catch (SimulatorException &e)
395             {
396                 std::cout << "SimulatorException occured [code : " << e.code() << " Detail: " <<
397                         e.what() << "]" << std::endl;
398             }
399         }
400
401         void automateAttributeUpdate()
402         {
403             int index = selectResource();
404             if (-1 == index)
405                 return;
406
407             SimulatorResourceServerSP resource = m_resources[index - 1];
408             SimulatorResourceModel resModel = resource->getModel();
409             std::map<std::string, SimulatorResourceModel::Attribute> attributes =
410                     resModel.getAttributes();
411             int size = 0;
412             for (auto & attribute : attributes)
413             {
414                 std::cout << ++size << ": " << attribute.first.c_str() << std::endl;
415             }
416
417             if (0 == size)
418             {
419                 std::cout << "This resource doest not contain any attributes!" << std::endl;
420                 return;
421             }
422
423             int choice = -1;
424             std::cout << "Select the attribute which you want to automate for updation: " <<
425                     std::endl;
426             std::cin >> choice;
427             if (choice < 0 || choice > size)
428             {
429                 std::cout << "Invalid selection!" << std::endl;
430                 return;
431             }
432
433             int count = 0;
434             std::string attributeName;
435             for (auto & attribute : attributes)
436             {
437                 if (count == choice - 1)
438                 {
439                     attributeName = attribute.first;
440                     break;
441                 }
442
443                 count++;
444             }
445
446             AutomationType type = AutomationType::NORMAL;
447             std::cout << "Press 1 if you want recurrent automation: ";
448             std::cin >> choice;
449             if (1 == choice)
450                 type = AutomationType::RECURRENT;
451
452             std::cout << "Requesting attribute automation for " << attributeName.c_str() <<
453                     std::endl;
454
455             try
456             {
457
458                 int id = resource->startUpdateAutomation(attributeName, type, 500,
459                          std::bind(&SimLightResource::onUpdateAutomationCompleted, this,
460                                 std::placeholders::_1, std::placeholders::_2));
461                 std::cout << "startUpdateAutomation() returned succces : " << id << std::endl;
462             }
463             catch (SimulatorException &e)
464             {
465                 std::cout << "SimulatorException occured [Error: " << e.code() << " Details: " <<
466                         e.what() << "]" << std::endl;
467             }
468         }
469
470         void stopAutomation()
471         {
472             int index = selectResource();
473             if (-1 == index)
474                 return;
475
476             SimulatorResourceServerSP resource = m_resources[index - 1];
477
478             // Select the automation to stop
479             std::vector<int> ids;
480             {
481                 std::vector<int> rids = resource->getResourceAutomationIds();
482                 std::vector<int> aids = resource->getAttributeAutomationIds();
483                 ids.insert(ids.end(), rids.begin(), rids.end());
484                 ids.insert(ids.end(), aids.begin(), aids.end());
485             }
486
487             if (!ids.size())
488             {
489                 std::cout << "No automation operation is going on this resource right now!" <<
490                         std::endl;
491                 return;
492             }
493
494             for (auto & id : ids)
495                 std::cout <<  id  << " ";
496
497             int automationid;
498             std::cout << "\nEnter automation id: " << std::endl;
499             std::cin >> automationid;
500             resource->stopUpdateAutomation(automationid);
501         }
502
503         void onObserverChanged(const std::string &uri, ObservationStatus state,
504                                const ObserverInfo &observerInfo)
505         {
506             std::cout << "[callback] Observer notification received..." << uri.c_str() << std::endl;
507             std::ostringstream out;
508             out << "ID:  " << (int) observerInfo.id << std::endl;
509             out << " [address: " << observerInfo.address << " port: " << observerInfo.port
510                     << "]" << std::endl;
511             std::cout << out.str();
512         }
513
514         void getObservers()
515         {
516             int index = selectResource();
517             if (-1 == index)
518                 return;
519
520             SimulatorResourceServerSP resource = m_resources[index - 1];
521
522             SimulatorResourceServer::ObserverCB callback = std::bind(
523                         &SimLightResource::onObserverChanged, this, std::placeholders::_1,
524                         std::placeholders::_2, std::placeholders::_3);
525             resource->setObserverCallback(callback);
526
527             std::vector<ObserverInfo> observersList = resource->getObserversList();
528
529             std::cout << "##### Number of Observers [" << observersList.size() << "]" << std::endl;
530             for (auto & observerInfo : observersList)
531             {
532                 std::cout << " ID :  " << (int) observerInfo.id << " [address: " <<
533                         observerInfo.address << " port: " << observerInfo.port << "]" << std::endl;
534             }
535             std::cout << "########################" << std::endl;
536         }
537
538     private:
539         std::vector<SimulatorResourceServerSP> m_resources;
540 };
541
542 void printMainMenu()
543 {
544     std::cout << "############### MAIN MENU###############" << std::endl;
545     std::cout << "1. Test simulation of resource" << std::endl;
546     std::cout << "2. Set Logger" << std::endl;
547     std::cout << "3. Help" << std::endl;
548     std::cout << "0. Exit" << std::endl;
549     std::cout << "######################################" << std::endl;
550 }
551
552 void setLogger()
553 {
554     std::cout << "1. Default console logger" << std::endl;
555     std::cout << "2. Default file logger" << std::endl;
556     std::cout << "3. custom logger" << std::endl;
557
558     int choice = -1;
559     std::cin >> choice;
560     if (choice <= 0 || choice > 3)
561     {
562         std::cout << "Invalid selection !" << std::endl;
563         return;
564     }
565
566     switch (choice)
567     {
568         case 1:
569             {
570                 if (false == SimulatorManager::getInstance()->setConsoleLogger())
571                     std::cout << "Failed to set the default console logger" << std::endl;
572             } break;
573         case 2:
574             {
575                 std::string filePath;
576                 std::cout << "Enter the file path (without file name) : ";
577                 std::cin >> filePath;
578                 if (false == SimulatorManager::getInstance()->setFileLogger(filePath))
579                     std::cout << "Failed to set default file logger" << std::endl;
580             } break;
581         case 3: SimulatorManager::getInstance()->setLogger(gAppLogger);
582     }
583 }
584
585 int main(int argc, char *argv[])
586 {
587     SimLightResource lightResource;
588
589     printMainMenu();
590     bool cont = true;
591     while (cont == true)
592     {
593         int choice = -1;
594         std::cout << "Enter your choice: ";
595         std::cin >> choice;
596         if (choice < 0 || choice > 3)
597         {
598             std::cout << "Invaild choice !" << std::endl; continue;
599         }
600
601         switch (choice)
602         {
603             case 1: lightResource.startTest();
604                 std::cout << "Welcome back to main menu !" << std::endl;
605                 break;
606             case 2: setLogger(); break;
607             case 3: printMainMenu(); break;
608             case 0: cont = false;
609         }
610     }
611
612     std::cout << "Terminating test !!!" << std::endl;
613 }