Newer
Older
/*=====================================================================
======================================================================*/
/**
* @file
* @brief Cross-platform support for serial ports
*
* @author Lorenz Meier <mavteam@student.ethz.ch>
*
*/
#include <QTimer>
#include <QDebug>
#include <QSerialPort>
#include <QSerialPortInfo>
dogmaphobic
committed
SerialLink::SerialLink(SerialConfiguration* config)
{
_bytesRead = 0;
_port = Q_NULLPTR;
_stopp = false;
_reqReset = false;
Q_ASSERT(config != NULL);
_config = config;
_config->setLink(this);
Lorenz Meier
committed
// We're doing it wrong - because the Qt folks got the API wrong:
// http://blog.qt.digia.com/blog/2010/06/17/youre-doing-it-wrong/
moveToThread(this);
dogmaphobic
committed
_id = getNextLinkId();
dogmaphobic
committed
qDebug() << "Create SerialLink " << config->portName() << config->baud() << config->flowControl()
<< config->parity() << config->dataBits() << config->stopBits();
qDebug() << "portName: " << config->portName();
Michael Carpenter
committed
void SerialLink::requestReset()
{
dogmaphobic
committed
QMutexLocker locker(&this->_stoppMutex);
_reqReset = true;
Michael Carpenter
committed
}
dogmaphobic
committed
// Disconnect link from configuration
_config->setLink(NULL);
dogmaphobic
committed
if(_port) delete _port;
_port = NULL;
// Tell the thread to exit
quit();
// Wait for it to exit
wait();
dogmaphobic
committed
bool SerialLink::_isBootloader()
QList<QSerialPortInfo> portList = QSerialPortInfo::availablePorts();
Lorenz Meier
committed
if( portList.count() == 0){
return false;
}
foreach (const QSerialPortInfo &info, portList)
{
// XXX debug statements will be removed once we have 100% stable link reports
Lorenz Meier
committed
// qDebug() << "PortName : " << info.portName()
// << "Description : " << info.description();
// qDebug() << "Manufacturer: " << info.manufacturer();
dogmaphobic
committed
if (info.portName().trimmed() == _config->portName() &&
(info.description().toLower().contains("bootloader") ||
info.description().toLower().contains("px4 bl") ||
info.description().toLower().contains("px4 fmu v1.6"))) {
// qDebug() << "BOOTLOADER FOUND";
Lorenz Meier
committed
return true;
}
}
// Not found
return false;
}
Lorenz Meier
committed
/**
* @brief Runs the thread
*
**/
void SerialLink::run()
{
dogmaphobic
committed
if (!_hardwareConnect(_type)) {
// Need to error out here.
Lorenz Meier
committed
QString err("Could not create port.");
dogmaphobic
committed
if (_port) {
err = _port->errorString();
Lorenz Meier
committed
}
_emitLinkError("Error connecting: " + err);
Michael Carpenter
committed
return;
Michael Carpenter
committed
}
dogmaphobic
committed
qint64 msecs = QDateTime::currentMSecsSinceEpoch();
qint64 initialmsecs = QDateTime::currentMSecsSinceEpoch();
Michael Carpenter
committed
quint64 bytes = 0;
dogmaphobic
committed
qint64 timeout = 5000;
// Qt way to make clear what a while(1) loop does
dogmaphobic
committed
QMutexLocker locker(&this->_stoppMutex);
if (_stopp) {
_stopp = false;
break; // exit the thread
}
dogmaphobic
committed
// TODO This needs a bit of TLC still...
// If there are too many errors on this link, disconnect.
Lorenz Meier
committed
if (isConnected() && (linkErrorCount > 150)) {
qDebug() << "linkErrorCount too high: re-connecting!";
Lorenz Meier
committed
emit communicationUpdate(getName(), tr("Link timeout, not receiving any data, attempting reconnect"));
dogmaphobic
committed
if (_port) {
_port->close();
delete _port;
_port = NULL;
}
QGC::SLEEP::msleep(500);
unsigned tries = 0;
const unsigned tries_max = 15;
dogmaphobic
committed
while (!_hardwareConnect(_type) && tries < tries_max) {
tries++;
QGC::SLEEP::msleep(500);
}
// Give up
if (tries == tries_max) {
break;
}
// Write all our buffered data out the serial port.
dogmaphobic
committed
if (_transmitBuffer.count() > 0) {
_writeMutex.lock();
int numWritten = _port->write(_transmitBuffer);
bool txSuccess = _port->flush();
txSuccess |= _port->waitForBytesWritten(10);
if (!txSuccess || (numWritten != _transmitBuffer.count())) {
dogmaphobic
committed
qDebug() << "TX Error! written:" << txSuccess << "wrote" << numWritten << ", asked for " << _transmitBuffer.count() << "bytes";
// Since we were successful, reset out error counter.
// Now that we transmit all of the data in the transmit buffer, flush it.
dogmaphobic
committed
_transmitBuffer = _transmitBuffer.remove(0, numWritten);
_writeMutex.unlock();
// Log this written data for this timestep. If this value ends up being 0 due to
// write() failing, that's what we want as well.
Bryant Mairs
committed
QMutexLocker dataRateLocker(&dataRateMutex);
logDataRateToBuffer(outDataWriteAmounts, outDataWriteTimes, &outDataIndex, numWritten, QDateTime::currentMSecsSinceEpoch());
//wait n msecs for data to be ready
//[TODO][BB] lower to SerialLink::poll_interval?
dogmaphobic
committed
_dataMutex.lock();
bool success = _port->waitForReadyRead(20);
dogmaphobic
committed
QByteArray readData = _port->readAll();
while (_port->waitForReadyRead(10))
readData += _port->readAll();
_dataMutex.unlock();
if (readData.length() > 0) {
emit bytesReceived(this, readData);
// Log this data reception for this timestep
Bryant Mairs
committed
QMutexLocker dataRateLocker(&dataRateMutex);
logDataRateToBuffer(inDataWriteAmounts, inDataWriteTimes, &inDataIndex, readData.length(), QDateTime::currentMSecsSinceEpoch());
// Track the total amount of data read.
dogmaphobic
committed
_bytesRead += readData.length();
dogmaphobic
committed
_dataMutex.unlock();
dogmaphobic
committed
if (bytes != _bytesRead) { // i.e things are good and data is being read.
bytes = _bytesRead;
Michael Carpenter
committed
msecs = QDateTime::currentMSecsSinceEpoch();
}
else {
if (QDateTime::currentMSecsSinceEpoch() - msecs > timeout) {
Michael Carpenter
committed
//It's been 10 seconds since the last data came in. Reset and try again
msecs = QDateTime::currentMSecsSinceEpoch();
if (msecs - initialmsecs > 25000) {
//After initial 25 seconds, timeouts are increased to 30 seconds.
//This prevents temporary silences from things like calibration commands
//from screwing things up. In all reality, timeouts should be enabled/disabled
//for events like that on a case by case basis.
//TODO ^^
timeout = 30000;
}
Michael Carpenter
committed
}
}
QGC::SLEEP::msleep(SerialLink::poll_interval);
dogmaphobic
committed
if (_port) {
qDebug() << "Closing Port #" << __LINE__ << _port->portName();
_port->close();
delete _port;
_port = NULL;
void SerialLink::writeBytes(const char* data, qint64 size)
{
dogmaphobic
committed
if(_port && _port->isOpen()) {
QByteArray byteArray(data, size);
dogmaphobic
committed
_writeMutex.lock();
_transmitBuffer.append(byteArray);
_writeMutex.unlock();
} else {
// Error occured
_emitLinkError(tr("Could not send data - link %1 is disconnected!").arg(getName()));
}
}
/**
* @brief Read a number of bytes from the interface.
*
* @param data Pointer to the data byte array to write the bytes to
* @param maxLength The maximum number of bytes to write
**/
void SerialLink::readBytes()
{
dogmaphobic
committed
if(_port && _port->isOpen()) {
const qint64 maxLength = 2048;
char data[maxLength];
dogmaphobic
committed
_dataMutex.lock();
qint64 numBytes = _port->bytesAvailable();
/* Read as much data in buffer as possible without overflow */
if(maxLength < numBytes) numBytes = maxLength;
dogmaphobic
committed
_port->read(data, numBytes);
QByteArray b(data, numBytes);
emit bytesReceived(this, b);
}
dogmaphobic
committed
_dataMutex.unlock();
}
}
/**
* @brief Disconnect the connection.
*
* @return True if connection has been disconnected, false if connection couldn't be disconnected.
**/
bool SerialLink::_disconnect(void)
{
dogmaphobic
committed
QMutexLocker locker(&_stoppMutex);
_stopp = true;
wait(); // This will terminate the thread and close the serial port
return true;
}
dogmaphobic
committed
_transmitBuffer.clear(); //clear the output buffer to avoid sending garbage at next connect
qDebug() << "Already disconnected";
}
/**
* @brief Connect the connection.
*
* @return True if connection has been established, false if connection couldn't be established.
**/
bool SerialLink::_connect(void)
qDebug() << "CONNECT CALLED";
dogmaphobic
committed
QMutexLocker locker(&this->_stoppMutex);
_stopp = false;
* @brief This function is called indirectly by the _connect() call.
* The _connect() function starts the thread and indirectly calls this method.
*
* @return True if the connection could be established, false otherwise
* @see _connect() For the right function to establish the connection.
dogmaphobic
committed
bool SerialLink::_hardwareConnect(QString &type)
{
dogmaphobic
committed
if (_port) {
qDebug() << "SerialLink:" << QString::number((long)this, 16) << "closing port";
dogmaphobic
committed
_port->close();
Lorenz Meier
committed
QGC::SLEEP::usleep(50000);
dogmaphobic
committed
delete _port;
_port = NULL;
}
dogmaphobic
committed
qDebug() << "SerialLink: hardwareConnect to " << _config->portName();
Lorenz Meier
committed
dogmaphobic
committed
if (_isBootloader()) {
Lorenz Meier
committed
qDebug() << "Not connecting to a bootloader, waiting for 2nd chance";
const unsigned retry_limit = 12;
unsigned retries;
for (retries = 0; retries < retry_limit; retries++) {
dogmaphobic
committed
if (!_isBootloader()) {
QGC::SLEEP::msleep(500);
Lorenz Meier
committed
break;
}
QGC::SLEEP::msleep(500);
}
// Check limit
if (retries == retry_limit) {
// bail out
dogmaphobic
committed
qWarning() << "Timeout waiting for something other than booloader";
Lorenz Meier
committed
return false;
}
}
dogmaphobic
committed
_port = new QSerialPort(_config->portName());
if (!_port) {
emit communicationUpdate(getName(),"Error opening port: " + _config->portName());
Michael Carpenter
committed
}
dogmaphobic
committed
_port->moveToThread(this);
// We need to catch this signal and then emit disconnected. You can't connect
// signal to signal otherwise disonnected will have the wrong QObject::Sender
dogmaphobic
committed
QObject::connect(_port, SIGNAL(aboutToClose()), this, SLOT(_rerouteDisconnected()));
QObject::connect(_port, SIGNAL(error(QSerialPort::SerialPortError)), this, SLOT(linkError(QSerialPort::SerialPortError)));
dogmaphobic
committed
// port->setCommTimeouts(QSerialPort::CtScheme_NonBlockingRead);
dogmaphobic
committed
// TODO This needs a bit of TLC still...
Lorenz Meier
committed
dogmaphobic
committed
// After the bootloader times out, it still can take a second or so for the USB driver to come up and make
// the port available for open. So we retry a few times to wait for it.
for (int openRetries = 0; openRetries < 4; openRetries++) {
if (!_port->open(QIODevice::ReadWrite)) {
qDebug() << "Port open failed, retrying";
QGC::SLEEP::msleep(500);
} else {
break;
}
Lorenz Meier
committed
}
dogmaphobic
committed
if (!_port->isOpen() ) {
emit communicationUpdate(getName(),"Error opening port: " + _port->errorString());
_port->close();
return false; // couldn't open serial port
Lorenz Meier
committed
}
dogmaphobic
committed
qDebug() << "Configuring port";
_port->setBaudRate (_config->baud());
_port->setDataBits (static_cast<QSerialPort::DataBits> (_config->dataBits()));
_port->setFlowControl (static_cast<QSerialPort::FlowControl> (_config->flowControl()));
_port->setStopBits (static_cast<QSerialPort::StopBits> (_config->stopBits()));
_port->setParity (static_cast<QSerialPort::Parity> (_config->parity()));
Lorenz Meier
committed
dogmaphobic
committed
emit communicationUpdate(getName(), "Opened port!");
dogmaphobic
committed
qDebug() << "CONNECTING LINK: " << __FILE__ << __LINE__ << "type:" << type << "with settings" << _config->portName()
<< _config->baud() << _config->dataBits() << _config->parity() << _config->stopBits();
void SerialLink::linkError(QSerialPort::SerialPortError error)
// You can use the following qDebug output as needed during development. Make sure to comment it back out
// when you are done. The reason for this is that this signal is very noisy. For example if you try to
// connect to a PixHawk before it is ready to accept the connection it will output a continuous stream
// of errors until the Pixhawk responds.
//qDebug() << "SerialLink::linkError" << error;
/**
* @brief Check if connection is active.
*
* @return True if link is connected, false otherwise.
**/
bool SerialLink::isConnected() const
{
dogmaphobic
committed
if (_port) {
bool isConnected = _port->isOpen();
// qDebug() << "SerialLink #" << __LINE__ << ":"<< m_port->portName()
// << " isConnected =" << QString::number(isConnected);
// qDebug() << "SerialLink #" << __LINE__ << ":" << m_portName
// << " isConnected = NULL";
int SerialLink::getId() const
dogmaphobic
committed
return _id;
QString SerialLink::getName() const
dogmaphobic
committed
return _config->portName();
Bryant Mairs
committed
/**
* This function maps baud rate constants to numerical equivalents.
* It relies on the mapping given in qportsettings.h from the QSerialPort library.
*/
qint64 SerialLink::getConnectionSpeed() const
{
dogmaphobic
committed
if (_port) {
baudRate = _port->baudRate();
dogmaphobic
committed
baudRate = _config->baud();
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
}
qint64 dataRate;
switch (baudRate)
{
case QSerialPort::Baud1200:
dataRate = 1200;
break;
case QSerialPort::Baud2400:
dataRate = 2400;
break;
case QSerialPort::Baud4800:
dataRate = 4800;
break;
case QSerialPort::Baud9600:
dataRate = 9600;
break;
case QSerialPort::Baud19200:
dataRate = 19200;
break;
case QSerialPort::Baud38400:
dataRate = 38400;
break;
case QSerialPort::Baud57600:
dataRate = 57600;
break;
case QSerialPort::Baud115200:
dataRate = 115200;
break;
// Otherwise do nothing.
default:
dataRate = -1;
break;
dogmaphobic
committed
void SerialLink::_resetConfiguration()
{
dogmaphobic
committed
bool somethingChanged = false;
if (_port) {
somethingChanged = _port->setBaudRate (_config->baud());
somethingChanged |= _port->setDataBits (static_cast<QSerialPort::DataBits> (_config->dataBits()));
somethingChanged |= _port->setFlowControl (static_cast<QSerialPort::FlowControl> (_config->flowControl()));
somethingChanged |= _port->setStopBits (static_cast<QSerialPort::StopBits> (_config->stopBits()));
somethingChanged |= _port->setParity (static_cast<QSerialPort::Parity> (_config->parity()));
}
if(somethingChanged) {
qDebug() << "Reconfiguring port";
emit updateLink(this);
}
dogmaphobic
committed
void SerialLink::_rerouteDisconnected(void)
{
dogmaphobic
committed
emit disconnected();
dogmaphobic
committed
void SerialLink::_emitLinkError(const QString& errorMsg)
{
dogmaphobic
committed
QString msg("Error on link %1. %2");
emit communicationError(tr("Link Error"), msg.arg(getName()).arg(errorMsg));
dogmaphobic
committed
LinkConfiguration* SerialLink::getLinkConfiguration()
{
dogmaphobic
committed
return _config;
dogmaphobic
committed
//--------------------------------------------------------------------------
//-- SerialConfiguration
dogmaphobic
committed
SerialConfiguration::SerialConfiguration(const QString& name) : LinkConfiguration(name)
{
dogmaphobic
committed
_baud = 57600;
_flowControl= QSerialPort::NoFlowControl;
_parity = QSerialPort::NoParity;
_dataBits = 8;
_stopBits = 1;
dogmaphobic
committed
SerialConfiguration::SerialConfiguration(SerialConfiguration* copy) : LinkConfiguration(copy)
{
dogmaphobic
committed
_baud = copy->baud();
_flowControl= copy->flowControl();
_parity = copy->parity();
_dataBits = copy->dataBits();
_stopBits = copy->stopBits();
_portName = copy->portName();
dogmaphobic
committed
void SerialConfiguration::copyFrom(LinkConfiguration *source)
{
dogmaphobic
committed
LinkConfiguration::copyFrom(source);
SerialConfiguration* ssource = dynamic_cast<SerialConfiguration*>(source);
Q_ASSERT(ssource != NULL);
_baud = ssource->baud();
_flowControl= ssource->flowControl();
_parity = ssource->parity();
_dataBits = ssource->dataBits();
_stopBits = ssource->stopBits();
_portName = ssource->portName();
}
dogmaphobic
committed
void SerialConfiguration::updateSettings()
{
dogmaphobic
committed
if(_link) {
SerialLink* serialLink = dynamic_cast<SerialLink*>(_link);
if(serialLink) {
serialLink->_resetConfiguration();
}
}
dogmaphobic
committed
void SerialConfiguration::setBaud(int baud)
dogmaphobic
committed
_baud = baud;
dogmaphobic
committed
void SerialConfiguration::setDataBits(int databits)
dogmaphobic
committed
_dataBits = databits;
dogmaphobic
committed
void SerialConfiguration::setFlowControl(int flowControl)
dogmaphobic
committed
_flowControl = flowControl;
dogmaphobic
committed
void SerialConfiguration::setStopBits(int stopBits)
{
dogmaphobic
committed
_stopBits = stopBits;
dogmaphobic
committed
void SerialConfiguration::setParity(int parity)
{
dogmaphobic
committed
_parity = parity;
dogmaphobic
committed
void SerialConfiguration::setPortName(const QString& portName)
{
dogmaphobic
committed
// No effect on a running connection
QString pname = portName.trimmed();
if (!pname.isEmpty() && pname != _portName) {
_portName = pname;
}
}
dogmaphobic
committed
void SerialConfiguration::saveSettings(QSettings& settings, const QString& root)
{
dogmaphobic
committed
settings.beginGroup(root);
settings.setValue("baud", _baud);
settings.setValue("dataBits", _dataBits);
settings.setValue("flowControl", _flowControl);
settings.setValue("stopBits", _stopBits);
settings.setValue("parity", _parity);
settings.setValue("portName", _portName);
settings.endGroup();
}
dogmaphobic
committed
void SerialConfiguration::loadSettings(QSettings& settings, const QString& root)
dogmaphobic
committed
settings.beginGroup(root);
if(settings.contains("baud")) _baud = settings.value("baud").toInt();
if(settings.contains("dataBits")) _dataBits = settings.value("dataBits").toInt();
if(settings.contains("flowControl")) _flowControl = settings.value("flowControl").toInt();
if(settings.contains("stopBits")) _stopBits = settings.value("stopBits").toInt();
if(settings.contains("parity")) _parity = settings.value("parity").toInt();
if(settings.contains("portName")) _portName = settings.value("portName").toString();
settings.endGroup();
dogmaphobic
committed
QList<QString> SerialConfiguration::getCurrentPorts()
dogmaphobic
committed
QList<QString> ports;
QList<QSerialPortInfo> portList = QSerialPortInfo::availablePorts();
foreach (const QSerialPortInfo &info, portList)
{
ports.append(info.portName());
}
return ports;