bool SerialCommunication::SerialDisconnect() { // serial disconnect if (serial.isOpen()) { serial.close(); return true; } return false; }
/** * This functions takes a serial port and tries if it can find a Kettler bike connected * to it. */ bool Kettler::discover(QString portName) { bool found = false; QSerialPort sp; sp.setPortName(portName); if (sp.open(QSerialPort::ReadWrite)) { m_kettlerConnection.configurePort(&sp); // Discard any existing data QByteArray data = sp.readAll(); // Read id from bike sp.write("cd\r\n"); sp.waitForBytesWritten(500); QByteArray reply = sp.readAll(); reply.append('\0'); QString replyString(reply); if (replyString.startsWith("ACK") || replyString.startsWith("RUN")) { found = true; } } sp.close(); return found; }
void MainWindow::initPort() { foreach(const QSerialPortInfo &info, QSerialPortInfo::availablePorts()){ QSerialPort serialtmp; serialtmp.setPort(info); /* 判断端口是否能打开 */ if(serialtmp.open(QIODevice::ReadWrite)) { int isHaveItemInList = 0; /* 判断是不是已经在列表中了 */ for(int i=0; i<ui->portNameCombo->count(); i++) { /* 如果,已经在列表中了,那么不添加这一项了就 */ if(ui->portNameCombo->itemData(i) == serialtmp.portName()) { isHaveItemInList++; } } if(isHaveItemInList == 0) { ui->portNameCombo->addItem(serialtmp.portName()); } serialtmp.close(); } }
PortSettings PositioningMethodSerialPortOptions::getPortSettings(const QString &APortName) { PortSettings portSettings; OptionsNode node; if (Options::hasNode(OPV_POSITIONING_METHOD_SERIALPORT, APortName)) node = Options::node(OPV_POSITIONING_METHOD_SERIALPORT, APortName); else { QSerialPort *serialPort = new QSerialPort(APortName); if (serialPort->open(QIODevice::ReadOnly)) { portSettings.FBaudRate = serialPort->baudRate(); portSettings.FDataBits = serialPort->dataBits(); portSettings.FStopBits = serialPort->stopBits(); portSettings.FParity = serialPort->parity(); portSettings.FFlowControl = serialPort->flowControl(); serialPort->close(); } else // Failed to open the port node = Options::node(OPV_POSITIONING_METHOD_SERIALPORT, APortName); serialPort->deleteLater(); } if (!node.isNull()) { portSettings.FBaudRate = node.value("baud-rate").toLongLong(); portSettings.FDataBits = (QSerialPort::DataBits)node.value("data-bits").toInt(); portSettings.FStopBits = (QSerialPort::StopBits)node.value("stop-bits").toInt(); portSettings.FParity = (QSerialPort::Parity)node.value("parity").toInt(); portSettings.FFlowControl = (QSerialPort::FlowControl)node.value("flow-control").toInt(); } return portSettings; }
void MainWindow::on_connectAction_triggered(bool connect) { if(connect) { ConnectDialog dlg(this); if(dlg.exec() == QDialog::Accepted) { if(dlg.connectionType() == Serial) { QSerialPort* serialPort = new QSerialPort(this); _ioDevice = serialPort; serialPort->setPort( dlg.serialPortInfo()); if(serialPort->open(QIODevice::ReadWrite)) { // TODO hardcoded settings if(!serialPort->setBaudRate(QSerialPort::Baud115200) || !serialPort->setDataBits(QSerialPort::Data8) || !serialPort->setParity(QSerialPort::NoParity) || !serialPort->setFlowControl(QSerialPort::NoFlowControl) || !serialPort->setStopBits(QSerialPort::TwoStop)) { serialPort->close(); QMessageBox::critical(this, "Logger", "Can't configure serial port, reason: " + serialErrorString()); return; } } else { QMessageBox::critical(this, "Logger", "Serial port connection failed, reason: " + serialErrorString(), QMessageBox::Ok); return; } } else if(dlg.connectionType() == File) { QFile* file = new QFile(dlg.fileName(), this); _ioDevice = file; } _logParser = new LogParser(_ioDevice, this); QObject::connect(_logParser, SIGNAL(logMessageReceived(QString)), SLOT(onLogMessageReceived(QString))); QObject::connect(_logParser, SIGNAL(packetParsed(Packet)), SLOT(onPacketParsed(Packet))); _logParser->setParent(0); _logParser->moveToThread(_parserThread); _parserThread->start(); _logParser->openDevice(); } } else { _ioDevice->close(); } updateStatus(); }
void SerialSetup::GetSerialport() { foreach (const QSerialPortInfo &info, QSerialPortInfo::availablePorts()) { qDebug() << "Name : " << info.portName(); QSerialPort serial; serial.setPort(info); if (serial.open(QIODevice::ReadWrite)) { serial.close(); ui->SerialPort->addItem(info.portName()); } }
/** * This functions takes a serial port and tries if it can find a Monark bike connected * to it. */ bool MonarkConnection::discover(QString portName) { bool found = false; QSerialPort sp; sp.setPortName(portName); if (sp.open(QSerialPort::ReadWrite)) { configurePort(&sp); // Discard any existing data QByteArray data = sp.readAll(); // Read id from bike sp.write("id\r"); sp.waitForBytesWritten(-1); QByteArray id; do { bool readyToRead = sp.waitForReadyRead(1000); if (readyToRead) { id.append(sp.readAll()); } else { id.append('\r'); } } while ((id.indexOf('\r') == -1)); id.replace("\r", "\0"); // Should check for all bike ids known to use this protocol if (QString(id).toLower().contains("lt") || QString(id).toLower().contains("lc") || QString(id).toLower().contains("novo")) { found = true; } } sp.close(); return found; }
int main(int argc, char **argv) { ros::init(argc, argv, "nav"); ros::NodeHandle n; ros::Publisher chatter_pub = n.advertise<mini::naviLoc>("navmsg", 1); QSerialPort sp; sp.setPortName("/dev/ttyS4"); sp.setBaudRate(QSerialPort::Baud115200); sp.setDataBits(QSerialPort::Data8); sp.setParity(QSerialPort::NoParity); sp.setStopBits(QSerialPort::OneStop); sp.open(QIODevice::ReadWrite); int data_len = 10; char rcv_buf[100]; FILE* fp = fopen("/home/haha/catkin_ws/odom.txt","w"); int ret; while (ros::ok()) { mini::naviLoc msg; struct timeval tv; int ret; while(1) { //ROS_INFO(" "); ret = sp.read(rcv_buf,1); //ROS_INFO("[%d]",ret); //usleep(10000); if(ret==1) { //ROS_INFO("[%02X]",rcv_buf[0]); } if(ret==1 && rcv_buf[0]==char(0xA2)) { break; } } int counter = 1; while(counter<data_len) { //ROS_INFO(" "); ret = sp.read(&rcv_buf[counter],1); //ROS_INFO("[%d]",ret); if(ret!=1) { continue; } counter++; } gettimeofday(&tv,0); if(rcv_buf[data_len-1]!=char(0x2A)) { continue; } unsigned int timeStamp = tv.tv_sec%100000*1000+tv.tv_usec/1000; SerialData2Msg(timeStamp, rcv_buf, data_len, msg); chatter_pub.publish(msg); //ROS_INFO("[%d],[%f],[%f],[%f]",msg.timestamp,msg.x,msg.y,msg.theta); //fprintf(fp,"%d %f %f %f\n",msg.timestamp,msg.x,msg.y,msg.theta); //fflush(fp); ros::spinOnce(); //usleep(20000); } sp.close(); fclose(fp); return 0; }
//! [4] void MasterThread::run() { bool currentPortNameChanged = false; mutex.lock(); //! [4] //! [5] QString currentPortName; quint32 currentBaudRate; QSerialPort::DataBits currentDataBits; QSerialPort::Parity currentParity; QSerialPort::StopBits currentStopBits; QSerialPort::FlowControl currentFlowControl; if ((currentPortName != portName) || (currentBaudRate != baudRate) || (currentDataBits != dataBits) || (currentParity != parity) || (currentStopBits != stopBits) || (currentFlowControl != flowControl)) { currentPortName = portName; currentBaudRate = baudRate; currentDataBits = dataBits; currentParity = parity; currentStopBits = stopBits; currentFlowControl = flowControl; currentPortNameChanged = true; } QString currentRequest = request; mutex.unlock(); //! [5] //! [6] QSerialPort serial; while (!quit) { //![6] //! [7] if (currentPortNameChanged) { serial.close(); serial.setPortName(currentPortName); if (!serial.open(QIODevice::ReadWrite)) { emit error(tr("Не удалось подключиться к порту %1, код ошибки %2") .arg(portName).arg(serial.error())); return; } // if (!serial.setBaudRate(QSerialPort::Baud9600)) { if (!serial.setBaudRate(currentBaudRate)) { emit error(tr("Не удалось установить скорость для порта %1, код ошибки %2") .arg(portName).arg(serial.error())); return; } // if (!serial.setDataBits(QSerialPort::Data8)) { if (!serial.setDataBits(currentDataBits)) { emit error(tr("Не удалось установить количество бит для порта %1, код ошибки %2") .arg(portName).arg(serial.error())); return; } // if (!serial.setParity(QSerialPort::NoParity)) { if (!serial.setParity(currentParity)) { emit error(tr("Не удалось установить четность для порта %1, код ошибки %2") .arg(portName).arg(serial.error())); return; } // if (!serial.setStopBits(QSerialPort::OneStop)) { if (!serial.setStopBits(currentStopBits)) { emit error(tr("Не удалось установить стоповый бит для порта %1, код ошибки %2") .arg(portName).arg(serial.error())); return; } // if (!serial.setFlowControl(QSerialPort::NoFlowControl)) { if (!serial.setFlowControl(currentFlowControl)) { emit error(tr("Не удалось установить контроль четности для порта %1, код ошибки %2") .arg(portName).arg(serial.error())); return; } } QByteArray requestData = 0; StringToByteArray(currentRequest, requestData); serial.write(requestData); if (serial.waitForBytesWritten(WAIT_TIMEOUT)) { // read response if (serial.waitForReadyRead(WAIT_TIMEOUT)) { QByteArray responseData = serial.readAll(); while (serial.waitForReadyRead(10)) responseData += serial.readAll(); QString response(responseData); emit this->response(response); } else { emit timeout(tr("Время ожидания ответа истекло: %1") .arg(QTime::currentTime().toString())); } } else { emit timeout(tr("Время ожидания записи истекло: %1") .arg(QTime::currentTime().toString())); } mutex.lock(); cond.wait(&mutex); if ((currentPortName != portName) || (currentBaudRate != baudRate) || (currentDataBits != dataBits) || (currentParity != parity) || (currentStopBits != stopBits) || (currentFlowControl != flowControl)) { currentPortName = portName; currentBaudRate = baudRate; currentDataBits = dataBits; currentParity = parity; currentStopBits = stopBits; currentFlowControl = flowControl; currentPortNameChanged = true; } else { currentPortNameChanged = false; } currentRequest = request; mutex.unlock(); } //! [13] }
void SerialThread::run() { QSerialPort serial; int cr; serial.setPortName(m_portName); if (!serial.setBaudRate(115200)) { qDebug() << "Serial set baud rate failed!"; emit this->serialError(tr("Can't set baud rate for %1, error code %2. %3.") .arg(m_portName).arg(serial.error()).arg(serial.errorString())); return; } if (!serial.setDataBits(QSerialPort::Data8)) { qDebug() << "Serial set data bits failed!"; emit this->serialError(tr("Can't set data bits for %1, error code %2. %3.") .arg(m_portName).arg(serial.error()).arg(serial.errorString())); return; } if (!serial.setParity(QSerialPort::NoParity)) { qDebug() << "Serial set parity failed!"; emit this->serialError(tr("Can't set parity for %1, error code %2. %3.") .arg(m_portName).arg(serial.error()).arg(serial.errorString())); return; } if (!serial.setStopBits(QSerialPort::OneStop)) { qDebug() << "Serial set stop bits failed!"; emit this->serialError(tr("Can't set stop bits for %1, error code %2. %3.") .arg(m_portName).arg(serial.error()).arg(serial.errorString())); return; } if (!serial.setFlowControl(QSerialPort::NoFlowControl)) { qDebug() << "Serial set flow control failed!"; emit this->serialError(tr("Can't set flow control for %1, error code %2. %3.") .arg(m_portName).arg(serial.error()).arg(serial.errorString())); return; } for (cr = 0; cr < m_connectAttempts; cr++) { if (serial.open(QIODevice::ReadWrite)) { break; } sleep(1); qDebug() << "Serial connect retry..."; } if (cr == m_connectAttempts) { qDebug() << "Connection failed!"; emit this->serialError(tr("Can't open %1, error code %2. %3.") .arg(m_portName).arg(serial.error()).arg(serial.errorString())); return; } emit this->serialConnected(); qDebug() << "Serial Thread is ready..."; m_mutex.lock(); /* Unlock resources and wait for the first job. */ m_cond.wait(&m_mutex); m_mutex.unlock(); while (!m_quit) { /* Protect shared resources while thread is working. */ m_mutex.lock(); if (m_txBuf.size() > 0) { qint64 bytesWritten = serial.write(m_txBuf); if (serial.waitForBytesWritten(SERIAL_WRITE_TIMEOUT_MS)) { m_txBuf.remove(0, bytesWritten); } else { qDebug() << "Write request timeout!"; /* Unlock resources and exit. */ m_mutex.unlock(); emit serialTimeout(tr("Write request timeout!")); break; } } if (serial.waitForReadyRead(SERIAL_READ_TIMEOUT_MS)) { m_rxBuf += serial.readAll(); while (serial.waitForReadyRead(SERIAL_READ_TIMEOUT_EXTRA_MS)) { m_rxBuf += serial.readAll(); } if (m_rxBuf.size() >= TELEMETRY_MSG_SIZE_BYTES) { processInputData(); } } else { qDebug() << "Read response timeout!"; /* Unlock resources and exit. */ m_mutex.unlock(); emit serialTimeout(tr("Read response timeout!")); break; } //qDebug() << "Serial Thread is sleeping..."; /* Unlock resources and wait for the next job. */ m_cond.wait(&m_mutex); m_mutex.unlock(); } qDebug() << "Serial Thread is terminating..."; serial.close(); }
void ReceiveDataThread::run() { bool currentPortNameChanged = false; quit = false;//这一句是必须的 mutex.lock(); QString currentPortName; if (currentPortName != portName) { currentPortName = portName; currentPortNameChanged = true; } mutex.unlock(); QSerialPort serial; while (!quit) { if (currentPortNameChanged) { serial.close(); serial.setPortName(currentPortName); serial.setBaudRate(baudRate); serial.setStopBits(stopBits); serial.setParity(parity); serial.setDataBits(dataBits); if (!serial.open(QIODevice::ReadWrite)) { emit error(tr("无法打开串口%1, 错误码为%2") .arg(portName).arg(serial.error())); return; } //成功打开串口 emit success(); } if (serial.waitForReadyRead(100)) { //读取数据 // QByteArray requestData = serial.readAll(); data += serial.readAll(); // while (serial.waitForReadyRead(1000)) // requestData += serial.readAll(); // qDebug() << "requestData.size() = " << requestData.size(); //如果接收到的数据加起来超过了800个字节,则发送给主界面 // if(requestData.size() > 800) if(data.size() > 400) { // QString request(requestData); qDebug() << "data.size() = " << data.size(); QString request(data); emit this->request(request);//发送数据 data.clear(); } } mutex.lock(); if (currentPortName != portName) { currentPortName = portName; currentPortNameChanged = true; } else { currentPortNameChanged = false; } mutex.unlock(); } serial.close(); qDebug() << "串口被关闭" << endl; }
void SerialPortThread::run() { bool __isStopped = true; m_serialPortMutex.lock(); __isStopped = m_isStopped; m_serialPortMutex.unlock(); qDebug("thread running"); SerialPortSettings::Settings __mSettings; bool __isSettingsChanged = false; QByteArray __dataReceived; QByteArray __dataToSend; // unsigned char rx_buffer[256]; QSerialPort serial; while(!__isStopped) { m_serialPortMutex.lock(); if(m_isSettingsChanged){ m_isSettingsChanged =false; __isSettingsChanged = true; } m_serialPortMutex.unlock(); if(__isSettingsChanged){ __isSettingsChanged =false; if(serial.isOpen()){ serial.close(); } m_serialPortMutex.lock(); __mSettings = m_currentSettings; m_serialPortMutex.unlock(); serial.setPortName(__mSettings.name); serial.setBaudRate(__mSettings.baudRate); serial.setDataBits(__mSettings.dataBits); serial.setParity(__mSettings.parity); serial.setStopBits(__mSettings.stopBits); serial.setFlowControl(__mSettings.flowControl); emit message(QString("settings changed !")); }//settings changed if(!serial.isOpen()){ if(serial.open(QIODevice::ReadWrite)){ emit message(QString("open successfully !")); } else{ m_serialPortMutex.lock(); m_isStopped = true; m_serialPortMutex.unlock(); emit message(QString("open failed !")); break; } }//if not open , while loop break /*=== opened , processing data here ===*/ m_serialPortMutex.lock(); if(!m_dataToSend.isEmpty()){ __dataToSend.append(m_dataToSend); m_dataToSend.clear(); } m_serialPortMutex.unlock(); if(! __dataToSend.isEmpty()){ if(serial.write(__dataToSend) > 0){ if (serial.waitForBytesWritten(100) == true) { qDebug() <<"write successfully !"; __dataToSend.clear(); } else qDebug() <<"write time out !"; } } if (serial.waitForReadyRead(100)) { __dataReceived = serial.readAll(); while (serial.waitForReadyRead(10)) __dataReceived += serial.readAll(); } //unpack the data received if(__dataReceived.size() > 0){ emit message(__dataReceived); // for(int i = 0; i < __dataReceived.size(); i ++){ // if(FrameUnpack(__dataReceived.at(i),rx_buffer)){ // tHeader* pHeader = (tHeader*)rx_buffer; // if( pHeader->cmd == CMD_ID_SENSOR_INFO){ // // Cmd_Data *pData = (Cmd_Data *)&rx_buffer[sizeof(tHeader)];// // } // else{ // } // } // } }//unpack code end /*=== processing data end ===*/ m_serialPortMutex.lock(); __isStopped = m_isStopped; m_serialPortMutex.unlock(); }//while loop end if(serial.isOpen()){ serial.close(); emit message(QString("close successfully !")); } qDebug("thread exit"); }
void SerialPortThread::run() { bool currentPortNameChanged = false; mutex.lock(); QString currentPortName; if(currentPortName != portName) { currentPortName = portName; currentPortNameChanged = true; } int currentWaitTimeout = waitTimeout; QString currentRequest = request; mutex.unlock(); QSerialPort serial; while(!quit) { if(currentPortNameChanged) { serial.close(); serial.setPortName(currentPortName); if(!serial.open(QIODevice::ReadWrite)) { emit this->S_PortNotOpen(); //串口未成功打开,信号返回到主程序 return; } serial.setBaudRate(QSerialPort::Baud19200); //波特率 serial.setDataBits(QSerialPort::Data8); //数据位 serial.setParity(QSerialPort::NoParity); //校验位 serial.setStopBits(QSerialPort::OneStop); //停止位 serial.setFlowControl(QSerialPort::NoFlowControl); //流控制 } QByteArray requestData = currentRequest.toLocal8Bit(); serial.write(requestData); if(serial.waitForBytesWritten(waitTimeout)) { if(serial.waitForReadyRead(currentWaitTimeout)) { QByteArray responseData = serial.readAll(); while(serial.waitForReadyRead(80)) responseData += serial.readAll(); QString response(responseData); emit this->response(response); } else { emit this->timeout(); return; } } else { emit this->timeout(); return; } mutex.lock(); cond.wait(&mutex); if(currentPortName != portName) { currentPortName = portName; currentPortNameChanged = true; } else currentPortNameChanged = false; currentWaitTimeout = waitTimeout; currentRequest = request; mutex.unlock(); } }
QString Builder::GetLeonardoSerialPort(QString defaultPort) { QStringList before, after; QSerialPortInfo serialList; QSerialPort port; SetPercentage(100); for (int i=0; i < serialList.availablePorts().count(); i++) { before.append(serialList.availablePorts().at(i).portName()); } /*#ifdef Q_OS_WIN PrepareSerialPort(project->serialPort, "1200"); #endif*/ port.setPortName(project->serialPort); port.setFlowControl(QSerialPort::NoFlowControl); port.setBaudRate(QSerialPort::Baud1200); port.setParity(QSerialPort::NoParity); port.setStopBits(QSerialPort::OneStop); port.setDataBits(QSerialPort::Data8); bool open = port.open (QIODevice::ReadWrite); //#endif if (open == false) { progress->SetPhase(BuildWindowTypes::detectingLeonardo2); msg.Add("Could not reset board automatically via serial port " + project->serialPort + "! Press RESET button at your board NOW!", mtWarning); } /*char buffer[20] = "Hello!\r\n"; port.write ((const char *)buffer);*/ //QThread::msleep(10); port.close(); QThread::msleep(100); int counter = 50; after.clear(); bool warningMessage = true; while (counter > 0) { QSerialPortInfo newSerialList; for (int i=0; i < newSerialList.availablePorts().count(); i++) { after.append(newSerialList.availablePorts().at(i).portName()); } for (int i=0; i < after.count(); i++) { if (before.indexOf(after.at(i)) < 0) { return after.at(i); } } QThread::msleep(120); counter--; if ( (progress->value() > 40) && warningMessage) { warningMessage = false; progress->SetPhase(BuildWindowTypes::detectingLeonardo2); msg.Add("Could not reset board automatically via serial port " + project->serialPort + "! Press RESET button at your board NOW!", mtWarning); } SetPercentage(100 - counter * 2); if (GetCancel()) { counter = 0; break; } } msg.Add("Could not detect Leonardo serial port for programming. Please try pressing the RESET button at your board when you see the dialog message 'Detecting Leonardo port...'!", mtError); return ""; }
void SlaveThread::run() { bool currentPortNameChanged = false; mutex.lock(); QString currentPortName; if (currentPortName != portName) { currentPortName = portName; currentPortNameChanged = true; } int currentWaitTimeout = waitTimeout; QString currentRespone = response; mutex.unlock(); QSerialPort serial; while (!quit) { if (currentPortNameChanged) { serial.close(); serial.setPortName(currentPortName); if (!serial.open(QIODevice::ReadWrite)) { emit error(tr("Can't open %1, error code %2") .arg(portName).arg(serial.error())); return; } } if (serial.waitForReadyRead(currentWaitTimeout)) { // read all request QByteArray requestData = serial.readAll(); while (serial.waitForReadyRead(10)) requestData += serial.readAll(); // write all response QByteArray responseData = currentRespone.toLocal8Bit(); serial.write(responseData); if (serial.waitForBytesWritten(waitTimeout)) { QString request(requestData); emit this->request(request); } else { emit timeout(tr("Wait write response timeout %1") .arg(QTime::currentTime().toString())); } } else { emit timeout(tr("Wait read request timeout %1") .arg(QTime::currentTime().toString())); } mutex.lock(); if (currentPortName != portName) { currentPortName = portName; currentPortNameChanged = true; } else { currentPortNameChanged = false; } currentWaitTimeout = waitTimeout; currentRespone = response; mutex.unlock(); } }
void PSerialPort::run() { reinitPort = true; mutex.lock(); // cond.wait(&mutex); QString currentRequest = request; mutex.unlock(); QSerialPort serial; while (!quit) { if (reinitPort) { serial.close(); mutex.lock(); // cond.wait(&mutex); serial.setPortName(portName); if (!serial.open(QIODevice::ReadWrite)) { emit error(tr("Не удалось подключиться к порту %1, код ошибки %2") .arg(portName).arg(serial.error())); return; } if (!serial.setBaudRate(baudRate)) { emit error(tr("Не удалось установить скорость для порта %1, код ошибки %2") .arg(portName).arg(serial.error())); return; } if (!serial.setDataBits(dataBits)) { emit error(tr("Не удалось установить количество бит для порта %1, код ошибки %2") .arg(portName).arg(serial.error())); return; } if (!serial.setParity(parity)) { emit error(tr("Не удалось установить четность для порта %1, код ошибки %2") .arg(portName).arg(serial.error())); return; } if (!serial.setStopBits(stopBits)) { emit error(tr("Не удалось установить стоповый бит для порта %1, код ошибки %2") .arg(portName).arg(serial.error())); return; } if (!serial.setFlowControl(flowControl)) { emit error(tr("Не удалось установить контроль четности для порта %1, код ошибки %2") .arg(portName).arg(serial.error())); return; } reinitPort = false; mutex.unlock(); } QByteArray requestData = 0; stringToByteArray(currentRequest, requestData); if (serial.write(requestData) == -1) reinitPort = true; // else // qDebug() << "Write" << requestData; serial.write(requestData); if (serial.waitForBytesWritten(PORT_WAIT_TIMEOUT)) { // qDebug() << "START" << adress; if (serial.waitForReadyRead(PORT_WAIT_TIMEOUT)) { QByteArray responseData = serial.readAll(); while (serial.waitForReadyRead(10)) responseData += serial.readAll(); QString response; byteArrayToString(responseData, response); emit this->response(response); } else { emit timeout(tr("Время ожидания ответа истекло: %1") .arg(QTime::currentTime().toString())); } } else { emit timeout(tr("Время ожидания записи истекло: %1") .arg(QTime::currentTime().toString())); } mutex.lock(); cond.wait(&mutex); currentRequest = request; mutex.unlock(); } //! [13] }
//! [4] void MasterThread::run() { bool currentPortNameChanged = false; mutex.lock(); //! [4] //! [5] QString currentPortName; if (currentPortName != portName) { currentPortName = portName; currentPortNameChanged = true; } int currentWaitTimeout = waitTimeout; QString currentRequest = request; mutex.unlock(); //! [5] //! [6] QSerialPort serial; while (!quit) { //![6] //! [7] if (currentPortNameChanged) { serial.close(); serial.setPortName(currentPortName); if (!serial.open(QIODevice::ReadWrite)) { emit error(tr("Can't open %1, error code %2") .arg(portName).arg(serial.error())); return; } if (!serial.setBaudRate(QSerialPort::Baud9600)) { emit error(tr("Can't set baud rate 9600 baud to port %1, error code %2") .arg(portName).arg(serial.error())); return; } if (!serial.setDataBits(QSerialPort::Data8)) { emit error(tr("Can't set 8 data bits to port %1, error code %2") .arg(portName).arg(serial.error())); return; } if (!serial.setParity(QSerialPort::NoParity)) { emit error(tr("Can't set no parity to port %1, error code %2") .arg(portName).arg(serial.error())); return; } if (!serial.setStopBits(QSerialPort::OneStop)) { emit error(tr("Can't set 1 stop bit to port %1, error code %2") .arg(portName).arg(serial.error())); return; } if (!serial.setFlowControl(QSerialPort::NoFlowControl)) { emit error(tr("Can't set no flow control to port %1, error code %2") .arg(portName).arg(serial.error())); return; } } //! [7] //! [8] // write request QByteArray requestData = currentRequest.toLocal8Bit(); serial.write(requestData); if (serial.waitForBytesWritten(waitTimeout)) { //! [8] //! [10] // read response if (serial.waitForReadyRead(currentWaitTimeout)) { QByteArray responseData = serial.readAll(); while (serial.waitForReadyRead(10)) responseData += serial.readAll(); QString response(responseData); //! [12] emit this->response(response); //! [10] //! [11] //! [12] } else { emit timeout(tr("Wait read response timeout %1") .arg(QTime::currentTime().toString())); } //! [9] //! [11] } else { emit timeout(tr("Wait write request timeout %1") .arg(QTime::currentTime().toString())); } //! [9] //! [13] mutex.lock(); cond.wait(&mutex); if (currentPortName != portName) { currentPortName = portName; currentPortNameChanged = true; } else { currentPortNameChanged = false; } currentWaitTimeout = waitTimeout; currentRequest = request; mutex.unlock(); } //! [13] }
void MainWindow::gatherInfo(){ int i, bytes_available; // ConnectionThread connection; fingerprints = new FingerprintScanPopup[10]; bioGuised = new BioGuised; biomodel = new BioModel; // Initialize Serial QSerialPort serial; serial.setPortName("COM6"); serial.open(QIODevice::ReadWrite); serial.setBaudRate(QSerialPort::Baud9600); serial.setDataBits(QSerialPort::Data8); serial.setParity(QSerialPort::NoParity); serial.setStopBits(QSerialPort::OneStop); serial.setFlowControl(QSerialPort::NoFlowControl); qDebug() << "connected"; //delay(500); while(!serial.isWritable()); QByteArray index("n"); serial.write(index); for(int i = 0; i < FINGERS; i++){ do{ serial.waitForReadyRead(1000); bytes_available = serial.bytesAvailable(); }while(bytes_available <= 0); QByteArray byte_array = serial.read(bytes_available); // qDebug() << byte_array; char *rawData = byte_array.data(); int data = (int)*rawData; qDebug() << data; if(data == 1){ positions[i] = true; } else{ positions[i] = false; } if(serial.flush()) { qDebug() << "flushed ok" << endl; } } serial.close(); //std::thread first(); // connection.start(); i = 0; int flag = 0; do{ if(positions[i] == true){ on_RegisterButton_clicked(); flag = 1; } }while( i < FINGERS && positions[i++] == false && flag == 0); // run(); }
void MasterThread::run() { // qDebug()<<"run()"; bool currentPortNameChanged = false; bool currentBaudRateChanged = false; bool currentStopBitsChanged = false; bool currentDataBitsChanged = false; bool currentParityChanged = false; mutex.lock(); //! [4] //! [5] QString currentPortName; if (currentPortName != portName) { currentPortName = portName; currentPortNameChanged = true; } int currentBaudRate = this->baudRate; int currentStopBits = this->stopBits; int currentDataBits = this->dataBits; int currentParity = this->parity; int currentWaitTimeout = this->waitTimeout; mutex.unlock(); //! [5] //! [6] QSerialPort serial; while (!quit) { //![6] //! [7] if (currentPortNameChanged) { serial.close(); serial.setPortName(currentPortName); if (!serial.open(QIODevice::ReadWrite)) { emit error(tr("Can't open %1, error code %2") .arg(portName).arg(serial.error())); return; } } if (currentBaudRateChanged) { serial.setBaudRate(currentBaudRate); } if (currentDataBitsChanged) { serial.setDataBits(QSerialPort::DataBits(currentDataBits)); } if (currentStopBitsChanged) { serial.setStopBits(QSerialPort::StopBits(currentStopBits)); } if (currentParityChanged) { serial.setParity(QSerialPort::Parity(currentParity)); } if (serial.waitForReadyRead(currentWaitTimeout)) { QByteArray responseData = serial.readAll(); while (serial.waitForReadyRead(10)) responseData += serial.readAll(); QString response(responseData); //! [12] Decoding(response); // emit this->response(response); //! [10] //! [11] //! [12] } else { emit timeout(tr("Wait read response timeout %1") .arg(QTime::currentTime().toString())); } mutex.lock(); // cond.wait(&mutex); if (currentPortName != portName) { currentPortName = portName; currentPortNameChanged = true; } else { currentPortNameChanged = false; } if (currentBaudRate != baudRate) { currentBaudRate = baudRate; currentBaudRateChanged = true; } else { currentBaudRateChanged = false; } if (currentDataBits != dataBits) { currentDataBits = dataBits; currentDataBitsChanged = true; } else { currentDataBitsChanged = false; } if (currentStopBits != stopBits) { currentStopBits = stopBits; currentStopBitsChanged = true; } else { currentStopBitsChanged = false; } if (currentParity != parity) { currentParity = parity; currentParityChanged = true; } else { currentParityChanged = false; } currentWaitTimeout = waitTimeout; mutex.unlock(); } //! [13] }