source: libs/QtGui/src/samgargui.cpp @ 445

Revision 445, 39.4 KB checked in by lmalek, 10 years ago (diff)

Samgar edition by WRUT. Based on Qt. Initial import.

Line 
1#include "samgargui.h"
2#include "ui_samgargui.h"
3#include <sstream>
4#include <fstream>
5#include <QTextCursor>
6
7std::string int2str(int i)
8{
9    std::stringstream ss;
10    std::string outString;
11    ss << i;
12    ss >> outString;
13    return outString;
14}
15
16int str2int(std::string s)
17{
18    std::stringstream ss;
19    int i;
20    ss << s;
21    ss >> i;
22    return i;
23}
24
25void QtModuleContainer::modified() const
26{
27    emit needToRefresh();
28}
29
30void QtConnectionContainer::modified() const
31{
32    emit needToRefresh();
33}
34
35
36SamgarGui::SamgarGui(QWidget *parent) :
37    QWidget(parent),
38    ui(new Ui::SamgarGui)
39{
40    ui->setupUi(this);
41
42    ui->debugLogTextEdit->setReadOnly(true);
43    ui->debugLogTextEdit->insertPlainText("Debug Log Init \n");
44
45    ui->feedbackLogTextEdit->setReadOnly(true);
46    ui->feedbackLogTextEdit->insertPlainText("Feedback Log Init");
47
48    ui->parent1ComboBox->addItem("Source");
49    ui->parent2ComboBox->addItem("Destination");
50    ui->parentPort1ComboBox->addItem("Source Port");
51    ui->parentPort2ComboBox->addItem("Destination Port");
52    ui->lossyComboBox->addItem(Sg::SgConnection::ProtocolName(Sg::SgConnection::TCP).c_str(),1);
53    ui->lossyComboBox->addItem(Sg::SgConnection::ProtocolName(Sg::SgConnection::UDP).c_str(),2);
54    ui->lossyComboBox->addItem(Sg::SgConnection::ProtocolName(Sg::SgConnection::MCAST).c_str(),3);
55    ui->connectComboBox->addItem("Connect",1);
56    ui->connectComboBox->addItem("Disconnect",2);
57    ui->networkComboBox->addItem(Sg::SgConnection::NetworkName(Sg::SgConnection::LAN).c_str(),1);
58    ui->networkComboBox->addItem(Sg::SgConnection::NetworkName(Sg::SgConnection::PROCESS).c_str(),2);
59    ui->networkComboBox->addItem(Sg::SgConnection::NetworkName(Sg::SgConnection::PLATFORM).c_str(),3);
60
61    QStringList header;
62    header.append("Source");
63    header.append("Source Port");
64    header.append("Destination");
65    header.append("Destination Port");
66    header.append("Protocol");
67    header.append("Network");
68    header.append("State");
69    ui->tableWidget->setColumnCount(header.count());
70    ui->tableWidget->setHorizontalHeaderLabels(header);
71
72    ui->treeWidget->setColumnCount(2);
73    ui->treeWidget->setHeaderLabels(QStringList() << tr("Parameter") << tr("Value"));
74    ui->treeWidget->header()->setResizeMode(0, QHeaderView::Stretch);
75    ui->treeWidget->header()->setResizeMode(1, QHeaderView::Stretch);
76
77    WhatShownDebug[0]=1;
78    WhatShownDebug[1]=1;
79    WhatShownDebug[2]=1;
80    WhatShownDebug[3]=1;
81
82#if MIGRATION
83    MigrationPort = new MigrationPortClass;
84#endif
85    GetCurrentServerName();
86#if MIGRATION
87    RegisterMigrationPort();
88#endif
89
90    Sg::SgModule::portForModules.open(Sg::SgModule::portForModulesName.c_str());
91    //yarp::os::Network::sync(Sg::SgModule::portForModulesName.c_str());
92    Sg::SgModule::portForModules.setStrict();
93
94    connect(&timer, SIGNAL(timeout()), this, SLOT(timerCallback()));
95    connect(ui->level1CheckBox, SIGNAL(stateChanged(int)), this, SLOT(changeDebugLevel()));
96    connect(ui->level2CheckBox, SIGNAL(stateChanged(int)), this, SLOT(changeDebugLevel()));
97    connect(ui->level3CheckBox, SIGNAL(stateChanged(int)), this, SLOT(changeDebugLevel()));
98    connect(ui->level4CheckBox, SIGNAL(stateChanged(int)), this, SLOT(changeDebugLevel()));
99    connect(ui->parent1ComboBox, SIGNAL(currentIndexChanged (int)), this, SLOT(firstModulePortComboBoxUpdate()));
100    connect(ui->parent2ComboBox, SIGNAL(currentIndexChanged (int)), this, SLOT(secondModulePortComboBoxUpdate()));
101    connect(ui->proceedButton, SIGNAL(clicked()), this, SLOT(connectPorts()));
102    connect(ui->tableWidget, SIGNAL(cellClicked(int, int)), this, SLOT(connectionSelect(int, int)));
103
104    connect(ui->startModuleButton, SIGNAL(clicked()), this, SLOT(startAllModules()));
105    connect(ui->stopModulesButton, SIGNAL(clicked()), this, SLOT(stopAllModules()));
106
107    connect(ui->saveButton, SIGNAL(clicked()), this, SLOT(saveAll()));
108    connect(ui->loadButton, SIGNAL(clicked()), this, SLOT(loadAll()));
109
110    connect(this, SIGNAL(connectionTableModified()), this, SLOT(firstModuleComboBoxUpdate()));
111    connect(this, SIGNAL(connectionTableModified()), this, SLOT(secondModuleComboBoxUpdate()));
112    connect(this, SIGNAL(connectionTableModified(Sg::SgNameType)), this, SLOT(UpdateConnectionTable(Sg::SgNameType)));
113
114    connect(&modules, SIGNAL(needToRefresh()), this, SLOT(RefreshModulesTree()));
115    connect(&connections, SIGNAL(needToRefresh()), this, SLOT(RefreshConnectionsTable()));
116
117    ChangeServer(LocalServer);
118    mainPort = new DataPort(this);
119    timer.setInterval(TIMER_INTERVAL);
120    timer.start();
121}
122
123
124SamgarGui::~SamgarGui()
125{
126    Sg::SgModule::portForModules.disableCallback();
127#if MIGRATION
128    MigrationPort->disableCallback();
129#endif
130    mainPort->disableCallback();
131    timer.stop();
132
133    connections.clear();
134    modules.clear();
135
136    Sg::SgModule::portForModules.close();
137#if MIGRATION
138    MigrationPort->close();
139#endif
140    mainPort->close();
141
142    yarp::os::Network::unregisterName("/PortForModules");
143    yarp::os::Network::unregisterName("/KeyToLocalServer");
144    yarp::os::Network::fini();
145
146    delete ui;
147#if MIGRATION
148    delete MigrationPort;
149#endif
150    delete mainPort;
151}
152
153void SamgarGui::changeEvent(QEvent *e)
154{
155    QWidget::changeEvent(e);
156    switch (e->type()) {
157    case QEvent::LanguageChange:
158        ui->retranslateUi(this);
159        break;
160    default:
161        break;
162    }
163}
164
165
166/*
167 * taken from MainComponent.cpp
168 */
169
170/**
171 * changes the current namespace, allows to comunicate with with local and global server
172 *
173 * TODO: this is pointless to choose server via int value.
174 * It should allow to pass the name or some type save identifier of the server.
175 */
176void SamgarGui::ChangeServer(ServerType change)
177{
178    yarp::os::Network::setNameServerName((change==LocalServer)?NameOfServer.c_str():"/global");
179}
180
181/**
182 * Get the current namespace and save it so we can always switch back
183 */
184void SamgarGui::GetCurrentServerName(void)
185{
186    NameOfServer=yarp::os::Network::getNameServerName();
187}
188
189#if MIGRATE
190/**
191 * Register the main migration port
192 */
193void SamgarGui::RegisterMigrationPort (void)
194{
195  timer.stop();
196  ChangeServer(GlobalServer);
197  NameofMigrate = NameOfServer + "_Migration";
198  static bool opened = MigrationPort->open(NameofMigrate.c_str());
199
200  ChangeServer(LocalServer);
201  timer.start();
202
203  if(opened==true){AddToLog("Addig myself to global server :\n",1);}
204  else                  {
205    AddToLog("could not Add myself to global server :\n",1);
206    AddToLog("This program will take a long while to shut down :\n",1);
207    MigrationPort->close();
208  }
209  AddToLog(NameofMigrate.c_str(),1);
210  AddToLog("\n",1);
211}
212
213/** Migrate function
214 *
215 *  This method
216 */
217bool SamgarGui::Migrate (std::string nameofwhere)
218{
219  AddToLog(" Attempting to Migrate  \n",1);
220  timer.stop();
221  ChangeServer(GlobalServer);
222
223  if(MigrationPort->isClosed()==true){AddToLog("Migration port is closed \n",1);}
224
225  yarp::os::Bottle& MyBottle =MigrationPort->prepare();
226  MyBottle.clear();
227
228  nameofwhere = "/" + nameofwhere + "_Migration";
229
230  AddToLog(nameofwhere.c_str(),1);AddToLog(" to ",1);AddToLog(MigrationPort->getName().c_str(),1);AddToLog("\n",1);
231
232  bool true1= MigrationPort->addOutput(nameofwhere.c_str());
233
234
235  if(true1==false){AddToLog("Could not connect to migrate, operation aborted \n",1);}
236
237
238  if(true1==false){ChangeServer(LocalServer);timer.start(); return false;}
239
240  std::string line;
241  std::ifstream myfile ("Personality.txt");
242
243  if (myfile.is_open())
244    {
245      while (! myfile.eof() )
246        {
247          getline (myfile,line);
248          MyBottle.addString(line.c_str());
249        }
250      myfile.close();
251    }
252  else
253    {
254      AddToLog(" could not open file \n",1);
255      ChangeServer(LocalServer);
256      timer.start();
257      return false;
258    }
259
260  MigrationPort->write();
261  AddToLog(" Migration Sucsessfull \n",1);
262
263  yarp::os::Network::disconnect(MigrationPort->getName(),nameofwhere.c_str());
264  yarp::os::Network::disconnect(nameofwhere.c_str(),MigrationPort->getName());
265
266  ChangeServer(LocalServer);
267  timer.start();
268  return true ;// if its sucsessfull
269}
270
271
272/**
273 * update a list of available platforms we can migrate to
274 */
275void SamgarGui::UpdateMigrationProto(void)
276{
277  timer.stop();
278  static FILE *inpipe;
279  char inbuf[200];
280  std::string hello;
281
282  ChangeServer(GlobalServer);
283#ifdef  Rectangle
284  inpipe = _popen("yarp clean","r");
285  inpipe = _popen("yarp name list","r");
286#else
287  inpipe =  popen("yarp clean","r");
288  inpipe =  popen("yarp name list", "r");
289#endif
290
291  MigrationPlatformsAvail.clear();
292  if (!inpipe){AddToLog("Cannot access needid function to find other platforms\n",1);   }
293  else
294    {
295      AddToLog(" List of possible migration platforms :\n",1);
296
297      while (fgets(inbuf, sizeof(inbuf), inpipe))
298        {
299
300          std::string mystring = inbuf;
301          mystring=mystring +"\n";
302          if(mystring.find('/')!=std::string::npos && mystring.find(std::string("Migration"))!=std::string::npos)
303            {
304              size_t start = mystring.find('/');
305              size_t fin   = mystring.find(' ',start);
306
307              mystring=mystring.substr(start,fin-start);
308              MigrationPlatformsAvail.push_back(mystring);
309              mystring = "--->"+mystring+   "\n";
310              AddToLog(mystring,1);
311
312              /// need to add it to the list here as well
313            }
314        }
315    }
316
317  ChangeServer(LocalServer);
318  timer.start();
319}
320#endif
321
322/**
323 * Checks that each connection is working, ignores failed modules
324 */
325void SamgarGui::connectionsUpdate(void)
326{
327    Sg::SgConnectionContainerIterator itConn;
328    bool connected = false;
329    // look through all connection and check their state
330    for ( itConn=connections.begin() ; itConn != connections.end(); itConn++ )
331    {
332        connected = (*itConn)->getConnected();
333        if ((*itConn)->refreshState() != connected)
334            emit connectionTableModified((*itConn)->getName());
335    }
336}
337
338/**
339 * checks the main port for each module can be connected to so its up
340 * and running
341 *
342 */
343void SamgarGui::modulesUpdate()
344{
345  bool needToSendOffModules=false;
346  Sg::SgModuleContainerIterator itModule;
347  bool active = false;
348  // look through all known modules
349  for ( itModule=modules.begin() ; itModule != modules.end(); itModule++ )
350  {
351      active = (*itModule)->getActive();
352      if ( (*itModule)->refreshState() != active )
353          needToSendOffModules=true;
354  }
355  if (needToSendOffModules)
356      SendOffModuleList(); // if a modules removed send off the new list
357}
358
359/**
360 * the idea here is that everytime a new module is found or lost it
361 * will send off the new list to all the other modules
362 */
363void SamgarGui::SendOffModuleList()
364{
365    Sg::SgModuleContainerIterator itModule;
366    yarp::os::Bottle& RR = Sg::SgModule::portForModules.prepare();
367    RR.clear();
368    RR.addInt( Samgar::ResetModulesListCode );
369    // add ListOfKnownModules to bottle
370    for ( itModule=modules.begin() ; itModule != modules.end(); itModule++ )
371    {
372        RR.addString((*itModule)->getName().c_str());
373        RR.addString((*itModule)->getCategory().c_str());
374        RR.addString((*itModule)->getSubCategory().c_str());
375    }
376    Sg::SgModule::portForModules.write();
377}
378
379void SamgarGui::GetModuleCommands(void)
380{
381  static std::vector<std::string>::iterator it;
382  yarp::os::Bottle *b;
383  while(Sg::SgModule::portForModules.getPendingReads()>0)
384  {
385      b = Sg::SgModule::portForModules.read(true);
386      if(b!=NULL && b->isNull()==false) // if theres data on the port
387      {
388          /// if its a report on how well its done then add to a log else
389
390          if(b->get(0).asInt() == Samgar::ActivationCode)
391          {
392              std::string MyNewString = b->get(1).asString().c_str();
393              double ModScore = b->get(2).asInt();
394              std::ostringstream strs;
395              strs << ModScore;
396              MyNewString = MyNewString + " achived score " + strs.str() + " \n";
397          }
398          else if(b->get(0).asInt() == Samgar::LogReportCode) // add to log
399          {
400              std::string MyNewString = b->get(1).asString().c_str();
401              std::string LogScore    = b->get(2).asString().c_str();
402              MyNewString = MyNewString + " : " + LogScore + " \n";
403              AddToLog(MyNewString,b->get(3).asInt());
404          }
405          else if(b->get(0).asInt() == Samgar::AvailablePlatformsCode)
406          {
407#if MIGRATION
408              UpdateMigrationProto();
409              yarp::os::Bottle& cc = ThePortForModules->prepare();
410              //                        AddToLog("recived command to get all data from modules \n",1);
411              cc.addInt( Samgar::ResetAvailablePlatformsCode ); // code for platforms
412              for ( it=MigrationPlatformsAvail.begin() ; it != MigrationPlatformsAvail.end(); it++ )
413                {
414                  std::string temppy = *it;
415                  cc.addString(temppy.c_str());
416                }
417              ThePortForModules->write();
418#endif
419          }
420          ///// reply back with new data once a new module has been created
421          // just send on
422          // when new data is got from the module giving it new data send off the module list
423          else if(b->get(0).asInt() == Samgar::ModuleInfoCode)
424          {
425              std::cout<<"--------> ModuleInfoCode"<<std::endl;
426              Sg::SgModuleContainerIterator itModule = modules.get(b->get(1).asString().c_str());
427              if (itModule != modules.null())
428              {
429                  (*itModule)->setActive(true);
430                  (*itModule)->setCategory(b->get(2).asString().c_str());
431                  (*itModule)->setSubCategory( b->get(3).asString().c_str());
432              }
433              SendOffModuleList();
434          }
435          // send the global command on to all modules
436          else if(b->get(0).asInt()>=0 && b->get(0).asInt()<=2)
437          {
438              yarp::os::Bottle& cc = Sg::SgModule::portForModules.prepare();
439              cc.addInt(b->get(0).asInt());
440              Sg::SgModule::portForModules.write();
441          }
442          // send the personal command to all modules
443          else if(b->get(0).asInt()>=3 && b->get(0).asInt()<=5)
444          {
445              // AddToLog("recived Personal module command \n",1);
446              yarp::os::Bottle& cc = Sg::SgModule::portForModules.prepare();
447              cc.addInt   (b->get(0).asInt());
448              cc.addString(b->get(1).asString());
449              Sg::SgModule::portForModules.write();
450          }
451      }
452  }
453#if MIGRATION
454  if(MigrationPort->Ivebeenused==1)
455  {
456      AddToLog("Someone has tryed to acess my migration port \n",1);
457      MigrationPort->Ivebeenused=0;
458  }
459#endif
460}
461
462
463/**
464 * This function is used to display the modules and ports in a nice
465 * circuler pattern needs to have some work done so it resizes a little
466 * better
467 */
468void SamgarGui::RefreshModulesTree(void)
469{
470    Sg::SgModuleContainerIterator itModule;
471    ui->treeWidget->clear(); // clear tree view
472    //AddToLog("RefreshModulesTree\n",1);
473    for ( itModule=modules.begin() ; itModule != modules.end(); itModule++ )
474    {
475        // module root item
476        QTreeWidgetItem* currModuleItem=new QTreeWidgetItem(ui->treeWidget);
477        currModuleItem->setText(0,(*itModule)->getName().c_str());
478        currModuleItem->setText(1,(*itModule)->getActive()?"true":"false");
479        currModuleItem->setFlags(Qt::ItemIsEnabled);
480
481        QTreeWidgetItem* currModuleParamItem=new QTreeWidgetItem(currModuleItem);
482        currModuleParamItem->setText(0,"name");
483        currModuleParamItem->setText(1,(*itModule)->getName().c_str());
484        currModuleParamItem->setFlags(Qt::ItemIsEnabled);
485
486        currModuleParamItem=new QTreeWidgetItem(currModuleItem);
487        currModuleParamItem->setText(0,"category");
488        currModuleParamItem->setText(1,(*itModule)->getCategory().c_str());
489        currModuleParamItem->setFlags(Qt::ItemIsEnabled);
490
491        currModuleParamItem=new QTreeWidgetItem(currModuleItem);
492        currModuleParamItem->setText(0,"subcategory");
493        currModuleParamItem->setText(1,(*itModule)->getSubCategory().c_str());
494        currModuleParamItem->setFlags(Qt::ItemIsEnabled);
495
496        currModuleParamItem=new QTreeWidgetItem(currModuleItem);
497        currModuleParamItem->setText(0,"isActive");
498        currModuleParamItem->setText(1,(*itModule)->getActive()?"true":"false");
499        currModuleParamItem->setFlags(Qt::ItemIsEnabled);
500
501        currModuleParamItem=new QTreeWidgetItem(currModuleItem);
502        currModuleParamItem->setText(0,"ports");
503        currModuleParamItem->setFlags(Qt::ItemIsEnabled);
504        Sg::SgPortContainerIterator itPort;
505        for ( itPort=(*itModule)->getPorts().begin() ; itPort != (*itModule)->getPorts().end(); itPort++ )
506        {
507            QTreeWidgetItem* currPortItem=new QTreeWidgetItem(currModuleParamItem);
508            currPortItem->setText(0,(*itPort)->getName().c_str());
509            currPortItem->setFlags(Qt::ItemIsEnabled);
510        }
511    }
512    emit connectionTableModified();
513}
514
515/**
516 * RefreshConnections Used to create the network profile by figuring
517 * out what modules go where and then drawing lines from port to port
518 * to show how there interconnected, need to change connections from a
519 * array of strings to a list of objects, so they can be added easerly
520 * by other methods for starting creations
521 */
522void SamgarGui::RefreshConnectionsTable(void)
523{
524    Sg::SgConnectionContainerIterator itConn;
525    int y=0;
526    int conListSize = connections.size();
527
528    ui->tableWidget->clearContents();
529    ui->tableWidget->setRowCount(conListSize);
530    QTableWidgetItem *newTableWidgetItem;
531    for (int i=0;i<conListSize;i++){
532        for (int j=0; j<7; j++){
533            newTableWidgetItem = new QTableWidgetItem(QTableWidgetItem::Type);
534            ui->tableWidget->setItem(i, j, newTableWidgetItem);
535        }
536    }
537    for ( itConn = connections.begin(); itConn !=connections.end(); itConn++)
538    {
539         ui->tableWidget->item(y,0)->setText((*itConn)->getFirstModule()->getName().c_str());
540         ui->tableWidget->item(y,1)->setText((*itConn)->getFirstModulePort()->getName().c_str());
541         ui->tableWidget->item(y,2)->setText((*itConn)->getSecondModule()->getName().c_str());
542         ui->tableWidget->item(y,3)->setText((*itConn)->getSecondModulePort()->getName().c_str());
543         ui->tableWidget->item(y,4)->setText((*itConn)->getProtocolName().c_str());
544         ui->tableWidget->item(y,5)->setText((*itConn)->getNetworkName().c_str());
545         ui->tableWidget->item(y,6)->setText((*itConn)->getConnected()?"true":"false");
546         y++;
547    }
548}
549
550
551void SamgarGui::UpdateConnectionTable(Sg::SgNameType connectionName)
552{
553    Sg::SgConnectionContainerIterator itConn = connections.get(connectionName);
554    if (itConn == connections.null())
555        return;
556    if ((*itConn) == NULL)
557        return;
558    for ( int y=0; y < ui->tableWidget->rowCount(); y++)
559    {
560        if ((*itConn)->getFirstModule()->getName() == ui->tableWidget->item(y,0)->text().toStdString() &&
561            (*itConn)->getFirstModulePort()->getName() == ui->tableWidget->item(y,1)->text().toStdString() &&
562            (*itConn)->getSecondModule()->getName() == ui->tableWidget->item(y,2)->text().toStdString() &&
563            (*itConn)->getSecondModulePort()->getName() == ui->tableWidget->item(y,3)->text().toStdString() )
564        {
565            if ( y < ui->tableWidget->rowCount()){
566               ui->tableWidget->item(y,0)->setText((*itConn)->getFirstModule()->getName().c_str());
567               ui->tableWidget->item(y,1)->setText((*itConn)->getFirstModulePort()->getName().c_str());
568               ui->tableWidget->item(y,2)->setText((*itConn)->getSecondModule()->getName().c_str());
569               ui->tableWidget->item(y,3)->setText((*itConn)->getSecondModulePort()->getName().c_str());
570               ui->tableWidget->item(y,4)->setText((*itConn)->getProtocolName().c_str());
571               ui->tableWidget->item(y,5)->setText((*itConn)->getNetworkName().c_str());
572               ui->tableWidget->item(y,6)->setText((*itConn)->getConnected()?"true":"false");
573            }
574        }
575        y++;
576    }
577}
578
579
580/**
581 * adds data to the log, makes sure that if button is pressed it
582 * doesn't print data they dont want
583 * \param VV some kind of text (probably log info)
584 * \param priority level
585 * <ul>
586 * <li><b>0</b>  normal debug stuff </li>
587 * <li><b>1</b>  SAMGAR only debug </li>
588 * <li><b>2</b>  SAMGAR Crit Level 1 </li>
589 * <li><b>3</b>  normal CRIT Level 2 </li>
590 * </ul>
591 */
592void SamgarGui::AddToLog(const std::string VV, int priority)
593{
594    if(WhatShownDebug[priority]==1)
595    {
596        switch (priority)
597        {
598        case 0:
599            ui->debugLogTextEdit->setTextColor(QColor("black"));
600            break; // normal debug stuff
601        case 1:
602            ui->debugLogTextEdit->setTextColor(QColor("blue"));
603            break; // SAMGAR only debug
604        case 2:
605            ui->debugLogTextEdit->setTextColor(QColor("darkRed"));
606            break; // SAMGAR Crit Level 1
607        case 3:
608            ui->debugLogTextEdit->setTextColor(QColor("red"));
609            break; // normal CRIT Level 2
610        }
611        ui->debugLogTextEdit->insertPlainText(QString(VV.c_str()));
612        QTextCursor c = ui->debugLogTextEdit->textCursor();
613        c.movePosition(QTextCursor::End);
614        ui->debugLogTextEdit->setTextCursor(c);
615    }
616}
617
618
619
620
621
622//==============================================================================
623/**
624 * This function gets called by the connect button to add a new
625 * connection to the list
626 *
627 * TODO: how to use lossy and Network - connected with ConnectionAutoUpdate
628 */
629bool SamgarGui::addConnection(const Sg::SgNameType& module1Name, const Sg::SgNameType& port1Name,
630                              const Sg::SgNameType& module2Name, const Sg::SgNameType& port2Name,
631                              Sg::SgConnection::SgProtocolType protocol, Sg::SgConnection::SgNetworkType network)
632{
633    Sg::SgModuleContainerIterator itModule;
634    Sg::SgPortContainerIterator itPortStruct;
635    Sg::SgModule *module1=NULL, *module2=NULL;
636    Sg::SgPort *port1=NULL, *port2=NULL;
637    // look through all known modules
638
639    for ( itModule=modules.begin() ; itModule != modules.end(); itModule++ )
640    {
641        if ((*itModule)->getName().compare(module1Name)==0)
642            module1 = &(**itModule);
643        if ((*itModule)->getName().compare(module2Name)==0)
644            module2 = &(**itModule);
645    }
646    if (module1==NULL || module2==NULL)
647        return false;
648    for ( itPortStruct = module1->getPorts().begin() ; itPortStruct != module1->getPorts().end(); itPortStruct++ )
649    {
650        if ((*itPortStruct)->getName().compare(port1Name)==0)
651            port1=&(**itPortStruct);
652    }
653    if (port1==NULL)
654        return false;
655    for ( itPortStruct = module2->getPorts().begin() ; itPortStruct != module2->getPorts().end(); itPortStruct++ )
656    {
657        if ((*itPortStruct)->getName().compare(port2Name)==0)
658            port2=&(**itPortStruct);
659    }
660    if (port1==NULL)
661        return false;
662
663    if (connections.add(module1, port1, module2, port2, protocol, network))
664            return true;
665        else
666            return false;
667}
668
669/**
670 * This function gets called by the connect button to deleate a new
671 * connection to the list
672 *
673 * TODO: how to use lossy and Network - connected with ConnectionAutoUpdate
674 */
675bool SamgarGui::delConnection(const Sg::SgNameType& module1Name, const Sg::SgNameType& port1Name,
676                              const Sg::SgNameType& module2Name, const Sg::SgNameType& port2Name,
677                              Sg::SgConnection::SgProtocolType protocol, Sg::SgConnection::SgNetworkType network)
678{
679    Sg::SgNameType connectionName = Sg::SgConnection::FullConnectionName(module1Name, port1Name,
680                                             module2Name, port2Name,
681                                             protocol, network);
682    return connections.del(connectionName);
683}
684
685bool SamgarGui::addModule(const Sg::SgNameType & newModuleName)
686{
687    return modules.add(newModuleName);
688    //this->SendOffModuleList();
689}
690
691bool SamgarGui::addModulePort(const Sg::SgNameType & moduleName, const Sg::SgNameType & newPortName)
692{
693    return modules.addPort(moduleName, newPortName);
694}
695
696bool SamgarGui::delModule(const Sg::SgNameType & moduleName)
697{
698    return modules.del(moduleName);
699}
700
701bool SamgarGui::delModulePort(const Sg::SgNameType & moduleName, const Sg::SgNameType & portName)
702{
703    return modules.delPort(moduleName, portName);
704}
705
706
707/**************************************************************************
708                              SLOTS
709 **************************************************************************/
710
711/**
712 * Time callback checks modules and connections , also checks the
713 * keytomodules port which recives data from ports ie stop commands etc
714 * bounces a few of them back as well to enable one module to
715 * communicate with all of them
716 */
717void SamgarGui::timerCallback()
718{
719      ChangeServer(LocalServer);
720      //        Network yarp;
721      modulesUpdate();
722      connectionsUpdate();
723      GetModuleCommands();  // this one seems fine
724}
725
726void SamgarGui::changeDebugLevel()
727{
728    WhatShownDebug[0]=ui->level1CheckBox->isTristate();
729    WhatShownDebug[1]=ui->level2CheckBox->isTristate();
730    WhatShownDebug[2]=ui->level3CheckBox->isTristate();
731    WhatShownDebug[3]=ui->level4CheckBox->isTristate();
732}
733
734/** update parent1ComboBox with posible module names
735 */
736void SamgarGui::firstModuleComboBoxUpdate()
737{
738    Sg::SgModuleContainerIterator itModule;
739    // look through all known modules
740    ui->parent1ComboBox->clear();
741    for (itModule=modules.begin() ; itModule != modules.end(); itModule++ )
742        ui->parent1ComboBox->addItem((*itModule)->getName().c_str());
743    if (modules.begin() == modules.end())
744        ui->parent1ComboBox->addItem("Source");
745}
746
747/** update parentPort1ComboBox with posible module names
748 */
749void SamgarGui::firstModulePortComboBoxUpdate()
750{
751    Sg::SgModuleContainerIterator itModule;
752    Sg::SgPortContainerIterator itPortStruct;
753
754     // look through all known modules
755     ui->parentPort1ComboBox->clear();
756     for ( itModule=modules.begin() ; itModule != modules.end(); itModule++ )
757     {
758         if ((*itModule)->getName().compare(ui->parent1ComboBox->currentText().toStdString())==0)
759         {
760             for ( itPortStruct=(*itModule)->getPorts().begin(); itPortStruct != (*itModule)->getPorts().end(); itPortStruct++ )
761             {
762                ui->parentPort1ComboBox->addItem((*itPortStruct)->getName().c_str());
763             }
764             if ((*itModule)->getPorts().begin() == (*itModule)->getPorts().end())
765                 ui->parent1ComboBox->addItem("Source Port");
766         }
767     }
768}
769
770/** update parent2ComboBox with posible module names
771 */
772void SamgarGui::secondModuleComboBoxUpdate()
773{;
774    Sg::SgModuleContainerIterator itModule;
775    // look through all known modules
776    ui->parent2ComboBox->clear();
777    for ( itModule=modules.begin() ; itModule != modules.end(); itModule++ )
778        ui->parent2ComboBox->addItem((*itModule)->getName().c_str());
779    if (modules.begin() == modules.end())
780        ui->parent2ComboBox->addItem("Source");
781}
782
783void SamgarGui::secondModulePortComboBoxUpdate()
784{
785    Sg::SgModuleContainerIterator itModule;
786    Sg::SgPortContainerIterator itPortStruct;
787
788    // look through all known modules
789    ui->parentPort2ComboBox->clear();
790    for ( itModule=modules.begin() ; itModule != modules.end(); itModule++ )
791    {
792        if ((*itModule)->getName().compare(ui->parent2ComboBox->currentText().toStdString())==0)
793        {
794            for ( itPortStruct=(*itModule)->getPorts().begin();
795                  itPortStruct != (*itModule)->getPorts().end(); itPortStruct++ )
796            {
797               ui->parentPort2ComboBox->addItem((*itPortStruct)->getName().c_str());
798            }
799            if ((*itModule)->getPorts().begin() == (*itModule)->getPorts().end())
800                ui->parent2ComboBox->addItem("Source Port");
801        }
802    }
803}
804
805void SamgarGui::connectPorts()
806{
807    std::string firstStr = "/Port_" + ui->parent1ComboBox->currentText().toStdString() +
808                           "_" + ui->parentPort1ComboBox->currentText().toStdString();
809    std::string secondStr = "/Port_" + ui->parent2ComboBox->currentText().toStdString() +
810                            "_" + ui->parentPort2ComboBox->currentText().toStdString();
811
812    if(ui->connectComboBox->currentText().compare("Connect")==0)
813      {
814        AddToLog("[AddConnection] : " + firstStr + " <=> " + secondStr +
815                 ui->networkComboBox->currentText().toStdString() +"["+
816                 (ui->lossyComboBox->currentText().compare("Lossy")==0?"lossy":"unlossy")+"]",1);
817        if (addConnection(ui->parent1ComboBox->currentText().toStdString(),
818                          ui->parentPort1ComboBox->currentText().toStdString(),
819                          ui->parent2ComboBox->currentText().toStdString(),
820                          ui->parentPort2ComboBox->currentText().toStdString(),
821                          Sg::SgConnection::SgProtocolType(ui->lossyComboBox->currentIndex()),
822                          Sg::SgConnection::SgNetworkType(ui->networkComboBox->currentIndex())))
823            AddToLog("[  OK  ]\n",1);
824        else
825            AddToLog("[FAILED]\n",1);
826      }
827    else
828      {
829        AddToLog("[DelConnection] : " + firstStr + " <=> " + secondStr +
830                 ui->networkComboBox->currentText().toStdString() +"["+
831                 (ui->lossyComboBox->currentText().compare("Lossy")==0?"lossy":"unlossy")+"]",1);
832        if (delConnection(ui->parent1ComboBox->currentText().toStdString(),
833                          ui->parentPort1ComboBox->currentText().toStdString(),
834                          ui->parent2ComboBox->currentText().toStdString(),
835                          ui->parentPort2ComboBox->currentText().toStdString(),
836                          Sg::SgConnection::SgProtocolType(ui->lossyComboBox->currentIndex()),
837                          Sg::SgConnection::SgNetworkType(ui->networkComboBox->currentIndex())))
838            AddToLog("[  OK  ]\n",1);
839        else
840            AddToLog("[FAILED]\n",1);
841      }
842}
843
844void SamgarGui::connectionSelect(int row, int column)
845{
846    AddToLog("connectionSelect row="+int2str(row)+" column="+int2str(column)+" "+int2str(ui->tableWidget->rowCount())+" "+int2str(ui->tableWidget->columnCount())+"\n",3);
847    QTableWidgetSelectionRange range(row,0,row,ui->tableWidget->columnCount()-1);
848    QTableWidgetSelectionRange full(0,0,ui->tableWidget->rowCount()-1,ui->tableWidget->columnCount()-1);
849    ui->tableWidget->setRangeSelected(full,false);
850    ui->tableWidget->setRangeSelected(range,true);
851}
852
853void SamgarGui::startAllModules(void)
854{
855    Sg::SgModule::StartAll();
856}
857
858void SamgarGui::stopAllModules(void)
859{
860    Sg::SgModule::StopAll();
861}
862
863void SamgarGui::saveAll()
864{
865    std::ofstream settings;
866    settings.open("samgar.conf"); // file where information about connections is stored
867
868    // first write a list of all modules, format:
869    // M,module_name,module_category,module_subcategory,[P,port1_name,port2_name,..,portk_name],E
870    Sg::SgModuleContainerIterator itModule;
871    Sg::SgPortContainerIterator itPort;
872    // look through all known modules
873    for ( itModule=modules.begin() ; itModule != modules.end(); itModule++ )
874    {
875        settings <<  "M,"<< (*itModule)->getName() <<","<< (*itModule)->getCategory()
876                << "," << (*itModule)->getSubCategory();
877        if ((*itModule)->getPorts().size()>0)
878        {
879            settings << ",P";
880            for (itPort = (*itModule)->getPorts().begin(); itPort != (*itModule)->getPorts().end(); itPort++)
881            {
882                settings<<","<<(*itPort)->getName();
883            }
884        }
885        settings<<",E"<<std::endl;
886    }
887
888    // after modules put the list of all connections, format:
889    // C,module1_name,port1_name,module2_name,port2_name,protocol,network,E
890    Sg::SgConnectionContainerIterator itConn;
891    // look through all known modules
892    for ( itConn=connections.begin() ; itConn != connections.end(); itConn++ )
893    {
894        settings <<  "C,"<< (*itConn)->getFirstModule()->getName() <<","<< (*itConn)->getFirstModulePort()->getName()
895                << "," << (*itConn)->getSecondModule()->getName() <<","<< (*itConn)->getSecondModulePort()->getName()
896                << "," << (*itConn)->getProtocol() << "," << (*itConn)->getNetwork()<<",E"<<std::endl;
897    }
898    settings.close();
899}
900
901void SamgarGui::loadAll()
902{
903    std::ifstream settings;
904    settings.open("samgar.conf"); // file where information about connections is stored
905
906    // first write a list of all modules, format:
907    // M,module_name,module_category,module_subcategory,[P,port1_name,port2_name,..,portk_name],E
908    // connections should be after modules
909    // C,module1_name,port1_name,module2_name,port2_name,protocol,network,E
910    Sg::SgNameType moduleName, moduleCategory, moduleSubCategory, portName;
911    Sg::SgNameType module1Name, module2Name, port1Name, port2Name;
912    int protocolID, networkID;
913    std::string line, tmp1, tmp2;
914    size_t begin, end;
915
916    while(std::getline(settings, line))
917    {
918        //std::cout<<"-------> "<<line<<std::endl;
919        // line by line extracting
920        if (line[0]=='M')  // module
921        {
922            begin = line.find(',')+1;
923            end = line.find(',', begin);
924            moduleName = line.substr(begin,end-begin);
925
926            begin = line.find(',',end)+1;
927            end = line.find(',', begin);
928            moduleCategory = line.substr(begin,end-begin);
929
930            begin = line.find(',',end)+1;
931            end = line.find(',', begin);
932            moduleSubCategory = line.substr(begin,end-begin);
933
934            //std::cout<<moduleName<<"|"<<moduleCategory<<"|"<<moduleSubCategory<<"|";
935            begin = line.find(',',end)+1;
936            modules.add(moduleName, moduleCategory, moduleSubCategory);
937            if (line[begin]=='P')
938            {
939                end = line.find(',', begin);
940                begin = line.find(',',end)+1;
941                while (line[begin]!='E')
942                {
943                    end = line.find(',', begin);
944                    portName = line.substr(begin,end-begin);
945                    //std::cout<<portName<<"|";
946                    begin = line.find(',',end)+1;
947                    modules.addPort(moduleName, portName);
948                }
949            }
950            //std::cout<<std::endl;
951            modulesUpdate();
952        }
953        else if (line[0]=='C') // connection
954        {
955            begin = line.find(',')+1;
956            end = line.find(',', begin);
957            module1Name = line.substr(begin,end-begin);
958
959            begin = line.find(',',end)+1;
960            end = line.find(',', begin);
961            port1Name = line.substr(begin,end-begin);
962
963            begin = line.find(',',end)+1;
964            end = line.find(',', begin);
965            module2Name = line.substr(begin,end-begin);
966
967            begin = line.find(',',end)+1;
968            end = line.find(',', begin);
969            port2Name = line.substr(begin,end-begin);
970
971            begin = line.find(',',end)+1;
972            end = line.find(',', begin);
973            tmp1 = line.substr(begin,end-begin);
974            protocolID = str2int(tmp1);
975
976            begin = line.find(',',end)+1;
977            end = line.find(',', begin);
978            tmp2 = line.substr(begin,end-begin);
979            networkID = str2int(tmp2);
980
981            //std::cout<<module1Name<<"|"<<port1Name<<"|"<<module2Name<<"|"<<port2Name<<"|"<<protocolID <<"|"<<networkID<<"|"<<std::endl;
982
983            addConnection(module1Name, port1Name, module2Name, port2Name,
984                          Sg::SgConnection::SgProtocolType(protocolID),
985                          Sg::SgConnection::SgNetworkType(networkID));
986        }
987    }
988    settings.close();
989    connectionsUpdate();
990}
991
992
993/**********************************************************************************************************/
994
995DataPort::DataPort(SamgarGui* MyComp)
996  {
997    // cant init mycomponent here but need it to be static so its done elsewhere
998    MyComponent=MyComp; //transfer over pointer to the main gui
999    useCallback();      // set the port to use onRead
1000    MyComponent->AddToLog("Connecting to server \n",1); // add to the log
1001    open("/KeyToLocalServer"); // open the port
1002    //setStrict(true);
1003    hasitworked = yarp::os::Network::connect(yarp::os::Network::getNameServerName(),"/KeyToLocalServer","tcp"); // connect them up
1004  }
1005
1006DataPort::~DataPort()
1007{
1008    disableCallback();      // set the port to use onRead
1009    MyComponent->AddToLog("Disconnecting from server \n",1); // add to the log
1010    hasitworked = yarp::os::Network::disconnect(yarp::os::Network::getNameServerName(),"/KeyToLocalServer","tcp"); // connect them up
1011    yarp::os::Network::unregisterName("/KeyToLocalServer");
1012}
1013
1014void DataPort::onRead(yarp::os::Bottle& b)
1015  {
1016    static std::string myvar;
1017    static std::string TempVar;
1018    Sg::SgModuleContainerIterator itModule;
1019
1020    myvar=b.toString().c_str();
1021    // this adds new ports to the gui
1022    if(myvar.find("[add]")==0) // if a port is addid
1023      {
1024        if(myvar.find("/Main")==7) // if main is the next word signifying its a module and not just a port
1025          {
1026            TempVar = myvar.substr(13);
1027            TempVar = TempVar.erase(TempVar.size()-1);
1028            MyComponent->AddToLog("[onRead] module: name = ("+TempVar+")\n",1);
1029            MyComponent->addModule(TempVar);
1030          }
1031        else if(myvar.find("/Port")==7)
1032          {
1033            TempVar = myvar.substr(myvar.find("_")+1);;
1034            std::string moduleName = TempVar;
1035            moduleName = moduleName.erase(moduleName.find("_"));
1036            std::string portName = TempVar.erase(0,TempVar.find("_")+1);
1037            portName = portName.erase(portName.size()-1);
1038            MyComponent->AddToLog("[onRead] updated port: name = "+portName+"\n",1);
1039            MyComponent->addModulePort(moduleName, portName);
1040          }
1041      }
1042 }
1043
1044/**
1045 *  Interupt when any button is clicked
1046 */
1047/*
1048void SamgarGui::buttonClicked (Button* buttonThatWasClicked)
1049{
1050
1051  if (buttonThatWasClicked == MigrateButton)
1052    {
1053      if(NameOfServer == "/Red"){Migrate("Blue");}
1054      if(NameOfServer == "/Blue"){Migrate("Red");}
1055    }
1056
1057  if (buttonThatWasClicked == DebugButton1)
1058    {
1059      switch(WhatShownDebug[0])
1060        {
1061        case 0:
1062          WhatShownDebug[0]=1;
1063          DebugButton1->setButtonText (T("debug priority 1 on"));
1064          break;
1065        case 1:
1066          WhatShownDebug[0]=0;
1067          DebugButton1->setButtonText (T("debug priority 1 off"));
1068          break;
1069        }
1070    }
1071  if (buttonThatWasClicked == DebugButton2)
1072    {
1073      switch(WhatShownDebug[1])
1074        {
1075        case 0:
1076          WhatShownDebug[1]=1;
1077          DebugButton2->setButtonText (T("debug priority 2 on"));
1078          break;
1079        case 1:
1080          WhatShownDebug[1]=0;
1081          DebugButton2->setButtonText (T("debug priority 2 off"));
1082          break;
1083        }
1084    }
1085  if (buttonThatWasClicked == DebugButton3)
1086    {
1087      switch(WhatShownDebug[2])
1088        {
1089        case 0:
1090          WhatShownDebug[2]=1;
1091          DebugButton3->setButtonText (T("debug priority 3 on"));
1092          break;
1093        case 1:
1094          WhatShownDebug[2]=0;
1095          DebugButton3->setButtonText (T("debug priority 3 off"));
1096          break;
1097        }
1098    }
1099  if (buttonThatWasClicked == DebugButton4)
1100    {
1101      switch(WhatShownDebug[3])
1102        {
1103        case 0:
1104          WhatShownDebug[3]=1;
1105          DebugButton4->setButtonText (T("debug priority 4 on"));
1106          break;
1107        case 1:
1108          WhatShownDebug[3]=0;
1109          DebugButton4->setButtonText (T("debug priority 4 off"));
1110          break;
1111        }
1112    }
1113
1114  if (buttonThatWasClicked == ClearLog)
1115    {
1116      MytextEditor->clear();
1117      SamgarGui::AddToLog("Log has been cleared \n", 1);
1118    }
1119
1120  if (buttonThatWasClicked == OpenLogButton)
1121    {
1122      FileChooser chooser ("Please select log you wish to load...",
1123                           File::getSpecialLocation (File::userHomeDirectory),
1124                           "*.SamLog");
1125      if (chooser.browseForFileToOpen ())
1126        {
1127          myFileforLog = chooser.getResult ();
1128          MytextEditor->setText (myFileforLog.loadFileAsString());
1129        }
1130    }
1131
1132}
1133*/
Note: See TracBrowser for help on using the repository browser.