1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136
| class SerialThread: public QThread
{
QextSerialPort * port;
protected:
virtual void run()
{
int compteur_sans_com = 0;
qDebug("THREAD lecture COM : %i", (int)currentThreadId());
QextSerialPort * port = new QextSerialPort("COM6", QextSerialPort::EventDriven);
while(1){
/////////// si le port est ouvert, on lit les données :
if( port->isOpen() ){
Sleep(DELAI_lecture_port_COM); //////// pour eviter de surcharger ce thread et donc laisser les autres threads travailler
char data[4096];
int bytesRead = port->read(data, 4096);
data[bytesRead] = '\0';
////////////// si on a recu qq chose :
if( bytesRead > 0 ){
qDebug("%s ## %i", data, (int)currentThreadId());
// qDebug(" %i", (int)currentThreadId());
} else {
qDebug("RIEN %i", compteur_sans_com);
if (!(port->lineStatus() & LS_DSR)) {
compteur_sans_com++;
if( compteur_sans_com > NBR_sans_com_before_reopen_COM6 ){
compteur_sans_com = 0;
qDebug("On referme le port COM !!!");
port->close();
Sleep(10);
}
}
}
} else {
port = new QextSerialPort("COM6", QextSerialPort::EventDriven);
port->setBaudRate(BAUD9600);
port->setFlowControl(FLOW_OFF);
port->setParity(PAR_NONE);
port->setDataBits(DATA_8);
port->setStopBits(STOP_2);
port->open(QIODevice::ReadWrite);
port->setTimeout(500);
qDebug("On essai de reouvrir !! ");
Sleep(5000); ////////// la negociation avec le materiel peut prendre du temps
}
}
}
signals:
// Émet un entier
void unEntier(int);
public slots:
void close_COM()
{
qDebug("demande fermeture port com !!!");
port->close();
}
};
int main(int argc, char *argv[])
{
int exec;
QApplication app(argc, argv);
//redirect debug messages to the MessageWindow dialog
qInstallMsgHandler(MessageWindow::AppendMsgWrapper);
MainWindow mainWindow(APP_TITLE);
mainWindow.show();
qDebug("THREAD MAIN : %i", (int)QThread::currentThreadId());
// SerialThread * thread = new SerialThread(port);
SerialThread * thread = new SerialThread();
app.connect(thread, SIGNAL(finished()), & app, SLOT(quit()));
QPushButton BOUTON_CLOSE_COM("Fermer COM");
BOUTON_CLOSE_COM.resize(75, 30);
BOUTON_CLOSE_COM.setFont(QFont("Times", 15, QFont::Bold));
app.connect(&BOUTON_CLOSE_COM, SIGNAL(clicked()), thread, SLOT(close_COM()));
BOUTON_CLOSE_COM.show();
thread->start();
exec = app.exec();
return exec;
} |
Partager