Commit 3e3a129c authored by LM's avatar LM

Minor cleanup, fixed a bug where the serial port would not connect on first...

Minor cleanup, fixed a bug where the serial port would not connect on first application launch on Linux
parent a128df00
...@@ -234,7 +234,6 @@ HEADERS += src/MG.h \ ...@@ -234,7 +234,6 @@ HEADERS += src/MG.h \
src/comm/LinkInterface.h \ src/comm/LinkInterface.h \
src/comm/SerialLinkInterface.h \ src/comm/SerialLinkInterface.h \
src/comm/SerialLink.h \ src/comm/SerialLink.h \
src/comm/SerialSimulationLink.h \
src/comm/ProtocolInterface.h \ src/comm/ProtocolInterface.h \
src/comm/MAVLinkProtocol.h \ src/comm/MAVLinkProtocol.h \
src/comm/QGCFlightGearLink.h \ src/comm/QGCFlightGearLink.h \
...@@ -365,7 +364,6 @@ SOURCES += src/main.cc \ ...@@ -365,7 +364,6 @@ SOURCES += src/main.cc \
src/comm/LinkManager.cc \ src/comm/LinkManager.cc \
src/comm/LinkInterface.cpp \ src/comm/LinkInterface.cpp \
src/comm/SerialLink.cc \ src/comm/SerialLink.cc \
src/comm/SerialSimulationLink.cc \
src/comm/MAVLinkProtocol.cc \ src/comm/MAVLinkProtocol.cc \
src/comm/QGCFlightGearLink.cc \ src/comm/QGCFlightGearLink.cc \
src/ui/CommConfigurationWindow.cc \ src/ui/CommConfigurationWindow.cc \
......
...@@ -21,16 +21,207 @@ ...@@ -21,16 +21,207 @@
#include "windows.h" #include "windows.h"
#endif #endif
using namespace TNX; #ifdef _WIN32
#include <qextserialenumerator.h>
#endif
#if defined (__APPLE__) && defined (__MACH__)
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/ioctl.h>
#include <errno.h>
#include <paths.h>
#include <termios.h>
#include <sysexits.h>
#include <sys/param.h>
#include <sys/select.h>
#include <sys/time.h>
#include <time.h>
#include <AvailabilityMacros.h>
#ifdef __MWERKS__
#define __CF_USE_FRAMEWORK_INCLUDES__
#endif
#include <CoreFoundation/CoreFoundation.h>
#include <IOKit/IOKitLib.h>
#include <IOKit/serial/IOSerialKeys.h>
#if defined(MAC_OS_X_VERSION_10_3) && (MAC_OS_X_VERSION_MIN_REQUIRED >= MAC_OS_X_VERSION_10_3)
#include <IOKit/serial/ioss.h>
#endif
#include <IOKit/IOBSD.h>
// Apple internal modems default to local echo being on. If your modem has local echo disabled,
// undefine the following macro.
#define LOCAL_ECHO
#define kATCommandString "AT\r"
#ifdef LOCAL_ECHO
#define kOKResponseString "AT\r\r\nOK\r\n"
#else
#define kOKResponseString "\r\nOK\r\n"
#endif
#endif
// Some helper functions for serial port enumeration
#if defined (__APPLE__) && defined (__MACH__)
enum {
kNumRetries = 3
};
// Function prototypes
static kern_return_t FindModems(io_iterator_t *matchingServices);
static kern_return_t GetModemPath(io_iterator_t serialPortIterator, char *bsdPath, CFIndex maxPathSize);
// Returns an iterator across all known modems. Caller is responsible for
// releasing the iterator when iteration is complete.
static kern_return_t FindModems(io_iterator_t *matchingServices)
{
kern_return_t kernResult;
CFMutableDictionaryRef classesToMatch;
/*! @function IOServiceMatching
@abstract Create a matching dictionary that specifies an IOService class match.
@discussion A very common matching criteria for IOService is based on its class. IOServiceMatching will create a matching dictionary that specifies any IOService of a class, or its subclasses. The class is specified by C-string name.
@param name The class name, as a const C-string. Class matching is successful on IOService's of this class or any subclass.
@result The matching dictionary created, is returned on success, or zero on failure. The dictionary is commonly passed to IOServiceGetMatchingServices or IOServiceAddNotification which will consume a reference, otherwise it should be released with CFRelease by the caller. */
// Serial devices are instances of class IOSerialBSDClient
classesToMatch = IOServiceMatching(kIOSerialBSDServiceValue);
if (classesToMatch == NULL) {
printf("IOServiceMatching returned a NULL dictionary.\n");
} else {
/*!
@function CFDictionarySetValue
Sets the value of the key in the dictionary.
@param theDict The dictionary to which the value is to be set. If this
parameter is not a valid mutable CFDictionary, the behavior is
undefined. If the dictionary is a fixed-capacity dictionary and
it is full before this operation, and the key does not exist in
the dictionary, the behavior is undefined.
@param key The key of the value to set into the dictionary. If a key
which matches this key is already present in the dictionary, only
the value is changed ("add if absent, replace if present"). If
no key matches the given key, the key-value pair is added to the
dictionary. If added, the key is retained by the dictionary,
using the retain callback provided
when the dictionary was created. If the key is not of the sort
expected by the key retain callback, the behavior is undefined.
@param value The value to add to or replace into the dictionary. The value
is retained by the dictionary using the retain callback provided
when the dictionary was created, and the previous value if any is
released. If the value is not of the sort expected by the
retain or release callbacks, the behavior is undefined.
*/
CFDictionarySetValue(classesToMatch,
CFSTR(kIOSerialBSDTypeKey),
CFSTR(kIOSerialBSDModemType));
// Each serial device object has a property with key
// kIOSerialBSDTypeKey and a value that is one of kIOSerialBSDAllTypes,
// kIOSerialBSDModemType, or kIOSerialBSDRS232Type. You can experiment with the
// matching by changing the last parameter in the above call to CFDictionarySetValue.
// As shipped, this sample is only interested in modems,
// so add this property to the CFDictionary we're matching on.
// This will find devices that advertise themselves as modems,
// such as built-in and USB modems. However, this match won't find serial modems.
}
/*! @function IOServiceGetMatchingServices
@abstract Look up registered IOService objects that match a matching dictionary.
@discussion This is the preferred method of finding IOService objects currently registered by IOKit. IOServiceAddNotification can also supply this information and install a notification of new IOServices. The matching information used in the matching dictionary may vary depending on the class of service being looked up.
@param masterPort The master port obtained from IOMasterPort().
@param matching A CF dictionary containing matching information, of which one reference is consumed by this function. IOKitLib can contruct matching dictionaries for common criteria with helper functions such as IOServiceMatching, IOOpenFirmwarePathMatching.
@param existing An iterator handle is returned on success, and should be released by the caller when the iteration is finished.
@result A kern_return_t error code. */
kernResult = IOServiceGetMatchingServices(kIOMasterPortDefault, classesToMatch, matchingServices);
if (KERN_SUCCESS != kernResult) {
printf("IOServiceGetMatchingServices returned %d\n", kernResult);
goto exit;
}
exit:
return kernResult;
}
/** Given an iterator across a set of modems, return the BSD path to the first one.
* If no modems are found the path name is set to an empty string.
*/
static kern_return_t GetModemPath(io_iterator_t serialPortIterator, char *bsdPath, CFIndex maxPathSize)
{
io_object_t modemService;
kern_return_t kernResult = KERN_FAILURE;
Boolean modemFound = false;
// Initialize the returned path
*bsdPath = '\0';
// Iterate across all modems found. In this example, we bail after finding the first modem.
while ((modemService = IOIteratorNext(serialPortIterator)) && !modemFound) {
CFTypeRef bsdPathAsCFString;
// Get the callout device's path (/dev/cu.xxxxx). The callout device should almost always be
// used: the dialin device (/dev/tty.xxxxx) would be used when monitoring a serial port for
// incoming calls, e.g. a fax listener.
bsdPathAsCFString = IORegistryEntryCreateCFProperty(modemService,
CFSTR(kIOCalloutDeviceKey),
kCFAllocatorDefault,
0);
if (bsdPathAsCFString) {
Boolean result;
// Convert the path from a CFString to a C (NUL-terminated) string for use
// with the POSIX open() call.
result = CFStringGetCString((CFStringRef)bsdPathAsCFString,
bsdPath,
maxPathSize,
kCFStringEncodingUTF8);
CFRelease(bsdPathAsCFString);
if (result) {
//printf("Modem found with BSD path: %s", bsdPath);
modemFound = true;
kernResult = KERN_SUCCESS;
}
}
printf("\n");
// Release the io_service_t now that we are done with it.
(void) IOObjectRelease(modemService);
}
return kernResult;
}
#endif
//#define USE_QEXTSERIAL // this allows us to revert to old serial library during transition using namespace TNX;
SerialLink::SerialLink(QString portname, int baudRate, bool hardwareFlowControl, bool parity, SerialLink::SerialLink(QString portname, int baudRate, bool hardwareFlowControl, bool parity,
int dataBits, int stopBits) : int dataBits, int stopBits) :
port(NULL) port(NULL),
ports(new QVector<QString>())
{ {
// Setup settings // Setup settings
this->porthandle = portname.trimmed(); this->porthandle = portname.trimmed();
if (this->porthandle == "" && getCurrentPorts()->size() > 0)
{
this->porthandle = getCurrentPorts()->first().trimmed();
}
#ifdef _WIN32 #ifdef _WIN32
// Port names above 20 need the network path format - if the port name is not already in this format // Port names above 20 need the network path format - if the port name is not already in this format
// catch this special case // catch this special case
...@@ -79,6 +270,86 @@ SerialLink::~SerialLink() ...@@ -79,6 +270,86 @@ SerialLink::~SerialLink()
disconnect(); disconnect();
if(port) delete port; if(port) delete port;
port = NULL; port = NULL;
if (ports) delete ports;
ports = NULL;
}
QVector<QString>* SerialLink::getCurrentPorts()
{
ports->clear();
#ifdef __linux
// TODO Linux has no standard way of enumerating serial ports
// However the device files are only present when the physical
// device is connected, therefore listing the files should be
// sufficient.
QString devdir = "/dev";
QDir dir(devdir);
dir.setFilter(QDir::System);
QFileInfoList list = dir.entryInfoList();
for (int i = 0; i < list.size(); ++i) {
QFileInfo fileInfo = list.at(i);
if (fileInfo.fileName().contains(QString("ttyUSB")) || fileInfo.fileName().contains(QString("ttyS")) || fileInfo.fileName().contains(QString("ttyACM")))
{
ports->append(fileInfo.canonicalFilePath());
}
}
#endif
#if defined (__APPLE__) && defined (__MACH__)
// Enumerate serial ports
kern_return_t kernResult; // on PowerPC this is an int (4 bytes)
io_iterator_t serialPortIterator;
char bsdPath[MAXPATHLEN];
kernResult = FindModems(&serialPortIterator);
kernResult = GetModemPath(serialPortIterator, bsdPath, sizeof(bsdPath));
IOObjectRelease(serialPortIterator); // Release the iterator.
// Add found modems
if (bsdPath[0])
{
ports->append(QString(bsdPath));
}
// Add USB serial port adapters
// TODO Strangely usb serial port adapters are not enumerated, even when connected
QString devdir = "/dev";
QDir dir(devdir);
dir.setFilter(QDir::System);
QFileInfoList list = dir.entryInfoList();
for (int i = list.size() - 1; i >= 0; i--) {
QFileInfo fileInfo = list.at(i);
if (fileInfo.fileName().contains(QString("ttyUSB")) || fileInfo.fileName().contains(QString("ttyS")) || fileInfo.fileName().contains(QString("tty.usbserial")) || fileInfo.fileName().contains(QString("ttyACM")))
{
ports->append(fileInfo.canonicalFilePath());
}
}
#endif
#ifdef _WIN32
// Get the ports available on this system
QList<QextPortInfo> ports = QextSerialEnumerator::getPorts();
// Add the ports in reverse order, because we prepend them to the list
for (int i = ports.size() - 1; i >= 0; i--)
{
QextPortInfo portInfo = ports.at(i);
QString portString = QString(portInfo.portName.toLocal8Bit().constData()) + " - " + QString(ports.at(i).friendName.toLocal8Bit().constData()).split("(").first();
// Prepend newly found port to the list
ports.append(portString);
}
//printf("port name: %s\n", ports.at(i).portName.toLocal8Bit().constData());
//printf("friendly name: %s\n", ports.at(i).friendName.toLocal8Bit().constData());
//printf("physical name: %s\n", ports.at(i).physName.toLocal8Bit().constData());
//printf("enumerator name: %s\n", ports.at(i).enumName.toLocal8Bit().constData());
//printf("===================================\n\n");
#endif
return ports;
} }
void SerialLink::loadSettings() void SerialLink::loadSettings()
...@@ -86,7 +357,8 @@ void SerialLink::loadSettings() ...@@ -86,7 +357,8 @@ void SerialLink::loadSettings()
// Load defaults from settings // Load defaults from settings
QSettings settings(QGC::COMPANYNAME, QGC::APPNAME); QSettings settings(QGC::COMPANYNAME, QGC::APPNAME);
settings.sync(); settings.sync();
if (settings.contains("SERIALLINK_COMM_PORT")) { if (settings.contains("SERIALLINK_COMM_PORT"))
{
if (porthandle == "") setPortName(settings.value("SERIALLINK_COMM_PORT").toString()); if (porthandle == "") setPortName(settings.value("SERIALLINK_COMM_PORT").toString());
setBaudRateType(settings.value("SERIALLINK_COMM_BAUD").toInt()); setBaudRateType(settings.value("SERIALLINK_COMM_BAUD").toInt());
setParityType(settings.value("SERIALLINK_COMM_PARITY").toInt()); setParityType(settings.value("SERIALLINK_COMM_PARITY").toInt());
...@@ -120,7 +392,8 @@ void SerialLink::run() ...@@ -120,7 +392,8 @@ void SerialLink::run()
hardwareConnect(); hardwareConnect();
// Qt way to make clear what a while(1) loop does // Qt way to make clear what a while(1) loop does
forever { forever
{
// Check if new bytes have arrived, if yes, emit the notification signal // Check if new bytes have arrived, if yes, emit the notification signal
checkForBytes(); checkForBytes();
/* Serial data isn't arriving that fast normally, this saves the thread /* Serial data isn't arriving that fast normally, this saves the thread
...@@ -134,16 +407,21 @@ void SerialLink::run() ...@@ -134,16 +407,21 @@ void SerialLink::run()
void SerialLink::checkForBytes() void SerialLink::checkForBytes()
{ {
/* Check if bytes are available */ /* Check if bytes are available */
if(port && port->isOpen() && port->isWritable()) { if(port && port->isOpen() && port->isWritable())
{
dataMutex.lock(); dataMutex.lock();
qint64 available = port->bytesAvailable(); qint64 available = port->bytesAvailable();
dataMutex.unlock(); dataMutex.unlock();
if(available > 0) { if(available > 0)
{
readBytes(); readBytes();
} }
} else { }
else
{
emit disconnected(); emit disconnected();
emit connected(false);
} }
} }
...@@ -238,13 +516,11 @@ bool SerialLink::disconnect() ...@@ -238,13 +516,11 @@ bool SerialLink::disconnect()
//#if !defined _WIN32 || !defined _WIN64 //#if !defined _WIN32 || !defined _WIN64
/* Block the thread until it returns from run() */ /* Block the thread until it returns from run() */
//#endif //#endif
// dataMutex.lock();
port->flushInBuffer(); port->flushInBuffer();
port->flushOutBuffer(); port->flushOutBuffer();
port->close(); port->close();
delete port; delete port;
port = NULL; port = NULL;
// dataMutex.unlock();
if(this->isRunning()) this->terminate(); //stop running the thread, restart it upon connect if(this->isRunning()) this->terminate(); //stop running the thread, restart it upon connect
......
...@@ -68,6 +68,9 @@ public: ...@@ -68,6 +68,9 @@ public:
static const int poll_interval = SERIAL_POLL_INTERVAL; ///< Polling interval, defined in configuration.h static const int poll_interval = SERIAL_POLL_INTERVAL; ///< Polling interval, defined in configuration.h
/** @brief Get a list of the currently available ports */
QVector<QString>* getCurrentPorts();
bool isConnected(); bool isConnected();
qint64 bytesAvailable(); qint64 bytesAvailable();
...@@ -163,6 +166,7 @@ protected: ...@@ -163,6 +166,7 @@ protected:
quint64 connectionStartTime; quint64 connectionStartTime;
QMutex statisticsMutex; QMutex statisticsMutex;
QMutex dataMutex; QMutex dataMutex;
QVector<QString>* ports;
void setName(QString name); void setName(QString name);
bool hardwareConnect(); bool hardwareConnect();
......
...@@ -34,6 +34,7 @@ This file is part of the QGROUNDCONTROL project ...@@ -34,6 +34,7 @@ This file is part of the QGROUNDCONTROL project
#include <QObject> #include <QObject>
#include <QString> #include <QString>
#include <QVector>
#include <LinkInterface.h> #include <LinkInterface.h>
class SerialLinkInterface : public LinkInterface class SerialLinkInterface : public LinkInterface
...@@ -41,6 +42,7 @@ class SerialLinkInterface : public LinkInterface ...@@ -41,6 +42,7 @@ class SerialLinkInterface : public LinkInterface
Q_OBJECT Q_OBJECT
public: public:
virtual QVector<QString>* getCurrentPorts() = 0;
virtual QString getPortName() = 0; virtual QString getPortName() = 0;
virtual int getBaudRate() = 0; virtual int getBaudRate() = 0;
virtual int getDataBits() = 0; virtual int getDataBits() = 0;
......
/*=====================================================================
QGroundControl Open Source Ground Control Station
(c) 2009, 2010 QGROUNDCONTROL PROJECT <http://www.qgroundcontrol.org>
This file is part of the QGROUNDCONTROL project
QGROUNDCONTROL is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
QGROUNDCONTROL is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with QGROUNDCONTROL. If not, see <http://www.gnu.org/licenses/>.
======================================================================*/
/**
* @file
* @brief Brief Description
*
* @author Lorenz Meier <mavteam@student.ethz.ch>
*
*/
#include <cstdlib>
#include <cstdio>
#include <cmath>
#include <SerialSimulationLink.h>
#include <QTime>
#include <QFile>
#include <QDebug>
#include <MG.h>
#include "QGC.h"
/**
* Create a simulated link. This link is connected to an input and output file.
* The link sends one line at a time at the specified sendrate. The timing of
* the sendrate is free of drift, which means it is stable on the long run.
* However, small deviations are mixed in which vary the sendrate slightly
* in order to simulate disturbances on a real communication link.
*
* @param readFile The file with the messages to read (must be in ASCII format, line breaks can be Unix or Windows style)
* @param writeFile The received messages are written to that file
* @param sendrate The rate at which the messages are sent (in intervals of milliseconds)
**/
SerialSimulationLink::SerialSimulationLink(QFile* readFile, QFile* writeFile, int sendrate)
{
// If a non-empty portname is supplied, the serial simulation link should attempt loopback simulation
loopBack = NULL;
/* Comments on the variables can be found in the header file */
lineBuffer = QByteArray();
lineBuffer.clear();
readyBuffer = QByteArray();
readyBuffer.clear();
simulationFile = readFile;
receiveFile = writeFile;
lastSent = MG::TIME::getGroundTimeNow();
/* Initialize the pseudo-random number generator */
srand(QTime::currentTime().msec());
maxTimeNoise = 0;
timer = new QTimer(this);
QObject::connect(timer, SIGNAL(timeout()), this, SLOT(readLine()));
_isConnected = false;
rate = sendrate;
}
SerialSimulationLink::~SerialSimulationLink()
{
//TODO Check destructor
fileStream->flush();
outStream->flush();
}
void SerialSimulationLink::run()
{
/*
forever {
quint64 currentTime = OG::TIME::getGroundTimeNow();
if(currentTime - lastSent >= rate) {
lastSent = currentTime;
readLine();
}
msleep(rate);
}*/
forever {
QGC::SLEEP::msleep(5000);
}
}
void SerialSimulationLink::enableLoopBackMode(SerialLinkInterface* loop)
{
// Lock the data
readyBufferMutex.lock();
// Disconnect this link
disconnect();
// Delete previous loopback link if exists
if(loopBack != NULL) {
delete loopBack;
loopBack = NULL;
}
// Set new loopback link
loopBack = loop;
// Connect signals
QObject::connect(loopBack, SIGNAL(connected()), this, SIGNAL(connected()));
QObject::connect(loopBack, SIGNAL(disconnected()), this, SIGNAL(disconnected()));
QObject::connect(loopBack, SIGNAL(connected(bool)), this, SIGNAL(connected(bool)));
QObject::connect(loopBack, SIGNAL(bytesReady(LinkInterface*)), this, SIGNAL(bytesReady(LinkInterface*)));
readyBufferMutex.unlock();
}
qint64 SerialSimulationLink::bytesAvailable()
{
readyBufferMutex.lock();
qint64 size = 0;
if(loopBack == 0) {
size = readyBuffer.size();
} else {
size = loopBack->bytesAvailable();
}
readyBufferMutex.unlock();
return size;
}
void SerialSimulationLink::writeBytes(char* data, qint64 length)
{
/* Write bytes to one line */
for(qint64 i = 0; i < length; i++) {
outStream->operator <<(data[i]);
outStream->flush();
}
}
void SerialSimulationLink::readBytes()
{
const qint64 maxLength = 2048;
char data[maxLength];
/* Lock concurrent resource readyBuffer */
readyBufferMutex.lock();
if(loopBack == NULL) {
// FIXME Maxlength has no meaning here
/* copy leftmost maxLength bytes and remove them from buffer */
qstrncpy(data, readyBuffer.left(maxLength).data(), maxLength);
readyBuffer.remove(0, maxLength);
} else {
//loopBack->readBytes(data, maxLength);
}
readyBufferMutex.unlock();
}
/**
* @brief Reads a line at a time of the simulation data file and sends it.
*
* The data is read binary, which means that the file doesn't have to contain
* only ASCII characters. The line break (independent of operating system) is
* NOT read. The line gets sent as a whole. Because the next line is buffered,
* the line gets sent instantly when the function is called.
*
* @bug The time noise addition is commented out because it adds some delay
* which leads to a drift in the timer. This can be fixed by multithreading.
**/
void SerialSimulationLink::readLine()
{
if(_isConnected) {
/* The order of operations in this method is arranged to
* minimize the impact of slow file read operations on the
* message emit timing. The functions should be kept in this order
*/
/* (1) Add noise for next iteration (noise is always 0 for maxTimeNoise = 0) */
addTimeNoise();
/* (2) Save content of line buffer in readyBuffer (has to be lock for thread safety)*/
readyBufferMutex.lock();
if(loopBack == NULL) {
readyBuffer.append(lineBuffer);
//qDebug() << "readLine readyBuffer: " << readyBuffer;
} else {
loopBack->writeBytes(lineBuffer.data(), lineBuffer.size());
}
readyBufferMutex.unlock();
if(loopBack == NULL) {
readBytes();
}
/* (4) Read one line and save it in line buffer */
lineBuffer.clear();
// Remove whitespaces, tabs and line breaks
QString readString = fileStream->readLine().trimmed();
readString.remove(" ");
readString.remove("\t");
readString.remove("\n");
readString.remove("\v");
readString.remove("\r");
lineBuffer.append(readString.toAscii());
//qDebug() << "SerialSimulationLink::readLine()" << readString.size() << readString;
/* Check if end of file has been reached, start from the beginning if necessary
* This has to be done after the last read, otherwise the timer is out of sync */
if (fileStream->atEnd()) {
simulationFile->reset();
}
}
}
/**
* Set the maximum time deviation noise. This amount (in milliseconds) is
* the maximum time offset (+/-) from the specified message send rate.
*
* @param milliseconds The maximum time offset (in milliseconds)
*
* @bug The current implementation might induce one milliseconds additional
* discrepancy, this will be fixed by multithreading
**/
void SerialSimulationLink::setMaximumTimeNoise(int milliseconds)
{
maxTimeNoise = milliseconds;
}
/**
* Add or subtract a pseudo random time offset. The maximum time offset is
* defined by setMaximumTimeNoise().
*
* @see setMaximumTimeNoise()
**/
void SerialSimulationLink::addTimeNoise()
{
/* Calculate the time deviation */
if(maxTimeNoise == 0) {
/* Don't do expensive calculations if no noise is desired */
timer->setInterval(rate);
} else {
/* Calculate random time noise (gauss distribution):
*
* (1) (2 * rand()) / RAND_MAX: Number between 0 and 2
* (induces numerical noise through floating point representation,
* ignored here)
*
* (2) ((2 * rand()) / RAND_MAX) - 1: Number between -1 and 1
*
* (3) Complete term: Number between -maxTimeNoise and +maxTimeNoise
*/
double timeDeviation = (((2 * rand()) / RAND_MAX) - 1) * maxTimeNoise;
timer->setInterval(static_cast<int>(rate + floor(timeDeviation)));
}
}
/**
* Disconnect the connection.
*
* @return True if connection has been disconnected, false if connection
* couldn't be disconnected.
**/
bool SerialSimulationLink::disconnect()
{
if(isConnected()) {
timer->stop();
fileStream->flush();
outStream->flush();
simulationFile->close();
receiveFile->close();
_isConnected = false;
if(loopBack == NULL) {
emit disconnected();
} else {
loopBack->disconnect();
}
exit();
}
return true;
}
/**
* Connect the link.
*
* @return True if connection has been established, false if connection
* couldn't be established.
**/
bool SerialSimulationLink::connect()
{
/* Open files */
//@TODO Add check if file can be read
simulationFile->open(QIODevice::ReadOnly);
/* Create or replace output file */
if(receiveFile->exists()) receiveFile->remove(); //TODO Read return value if file has been removed
receiveFile->open(QIODevice::WriteOnly);
fileStream = new QTextStream(simulationFile);
outStream = new QTextStream(receiveFile);
/* Initialize line buffer */
lineBuffer.clear();
lineBuffer.append(fileStream->readLine().toAscii());
_isConnected = true;
if(loopBack == NULL) {
emit connected();
} else {
loopBack->connect();
}
start(LowPriority);
timer->start(rate);
return true;
}
/**
* Check if connection is active.
*
* @return True if link is connected, false otherwise.
**/
bool SerialSimulationLink::isConnected()
{
return _isConnected;
}
qint64 SerialSimulationLink::getNominalDataRate()
{
/* 100 Mbit is reasonable fast and sufficient for all embedded applications */
return 100000000;
}
qint64 SerialSimulationLink::getTotalUpstream()
{
return 0;
//TODO Add functionality here
// @todo Add functionality here
}
qint64 SerialSimulationLink::getShortTermUpstream()
{
return 0;
}
qint64 SerialSimulationLink::getCurrentUpstream()
{
return 0;
}
qint64 SerialSimulationLink::getMaxUpstream()
{
return 0;
}
qint64 SerialSimulationLink::getBitsSent()
{
return 0;
}
qint64 SerialSimulationLink::getBitsReceived()
{
return 0;
}
qint64 SerialSimulationLink::getTotalDownstream()
{
return 0;
}
qint64 SerialSimulationLink::getShortTermDownstream()
{
return 0;
}
qint64 SerialSimulationLink::getCurrentDownstream()
{
return 0;
}
qint64 SerialSimulationLink::getMaxDownstream()
{
return 0;
}
bool SerialSimulationLink::isFullDuplex()
{
/* Full duplex is no problem when running in pure software, but this is a serial simulation */
return false;
}
int SerialSimulationLink::getLinkQuality()
{
/* The Link quality is always perfect when running in software */
return 100;
}
bool SerialSimulationLink::setPortName(QString portName)
{
Q_UNUSED(portName);
return true;
}
bool SerialSimulationLink::setBaudRate(int rate)
{
Q_UNUSED(rate);
return true;
}
bool SerialSimulationLink::setFlowType(int type)
{
Q_UNUSED(type);
return true;
}
bool SerialSimulationLink::setParityType(int type)
{
Q_UNUSED(type);
return true;
}
bool SerialSimulationLink::setDataBitsType(int type)
{
Q_UNUSED(type);
return true;
}
bool SerialSimulationLink::setStopBitsType(int type)
{
Q_UNUSED(type)
return true;
}
QString SerialSimulationLink::getPortName()
{
return tr("simulated/port");
}
int SerialSimulationLink::getBaudRate()
{
return 115200;
}
int SerialSimulationLink::getBaudRateType()
{
return 19;
}
int SerialSimulationLink::getFlowType()
{
return 0;
}
int SerialSimulationLink::getParityType()
{
return 0;
}
int SerialSimulationLink::getDataBitsType()
{
return 8;
}
int SerialSimulationLink::getStopBitsType()
{
return 2;
}
bool SerialSimulationLink::setBaudRateType(int rateIndex)
{
Q_UNUSED(rateIndex);
return true;
}
/*=====================================================================
QGroundControl Open Source Ground Control Station
(c) 2009 - 2011 QGROUNDCONTROL PROJECT <http://www.qgroundcontrol.org>
This file is part of the QGROUNDCONTROL project
QGROUNDCONTROL is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
QGROUNDCONTROL is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with QGROUNDCONTROL. If not, see <http://www.gnu.org/licenses/>.
======================================================================*/
/**
* @file
* @brief Brief Description
*
* @author Lorenz Meier <mavteam@student.ethz.ch>
*
*/
#ifndef _SERIALSIMULATIONLINK_H_
#define _SERIALSIMULATIONLINK_H_
#include <QString>
#include <QByteArray>
#include <QFile>
#include <QTimer>
#include <QTextStream>
#include <QMutex>
#include <SerialLinkInterface.h>
/**
* The serial simulation link class simulates a robot connected to the groundstation.
* It can be either file-based by reading telemetry messages from a file or realtime
* by communicating with a simulation.
*
**/
class SerialSimulationLink : public SerialLinkInterface
{
Q_OBJECT
public:
SerialSimulationLink(QFile* inputFile=NULL, QFile* outputFile=NULL, int sendrate=20);
~SerialSimulationLink();
bool isConnected();
qint64 bytesAvailable();
void run();
/* Extensive statistics for scientific purposes */
qint64 getNominalDataRate();
qint64 getTotalUpstream();
qint64 getShortTermUpstream();
qint64 getCurrentUpstream();
qint64 getMaxUpstream();
qint64 getTotalDownstream();
qint64 getShortTermDownstream();
qint64 getCurrentDownstream();
qint64 getMaxDownstream();
qint64 getBitsSent();
qint64 getBitsReceived();
void enableLoopBackMode(SerialLinkInterface * loop);
QString getPortName();
int getBaudRate();
int getBaudRateType();
int getFlowType();
int getParityType();
int getDataBitsType();
int getStopBitsType();
int getLinkQuality();
bool isFullDuplex();
public slots:
bool setPortName(QString portName);
bool setBaudRateType(int rateIndex);
bool setBaudRate(int rate);
bool setFlowType(int flow);
bool setParityType(int parity);
bool setDataBitsType(int dataBits);
bool setStopBitsType(int stopBits);
void readLine();
void writeBytes(char *bytes, qint64 length);
void readBytes();
bool connect();
bool disconnect();
void setMaximumTimeNoise(int milliseconds);
protected:
QTimer* timer;
SerialLinkInterface* loopBack;
/** File which contains the input data (simulated robot messages) **/
QFile* simulationFile;
/** File where the commands sent by the groundstation are stored **/
QFile* receiveFile;
QTextStream stream;
QTextStream* fileStream;
QTextStream* outStream;
/** Buffer for next line. The next line is read ahead */
QByteArray lineBuffer;
/** Buffer which can be read from connected protocols through readBytes(). **/
QByteArray readyBuffer;
QMutex readyBufferMutex;
bool _isConnected;
quint64 rate;
int maxTimeNoise;
quint64 lastSent;
void addTimeNoise();
signals:
//void connected();
//void disconnected();
//void bytesReady(LinkInterface *link);
};
#endif // _SERIALSIMULATIONLINK_H_
...@@ -12,7 +12,7 @@ ...@@ -12,7 +12,7 @@
#define WITH_TEXT_TO_SPEECH 1 #define WITH_TEXT_TO_SPEECH 1
#define QGC_APPLICATION_NAME "QGroundControl" #define QGC_APPLICATION_NAME "QGroundControl"
#define QGC_APPLICATION_VERSION "v. 1.0.0 (Alpha RC16)" #define QGC_APPLICATION_VERSION "v. 1.0.0 (Alpha RC17)"
namespace QGC namespace QGC
......
...@@ -35,191 +35,6 @@ This file is part of the QGROUNDCONTROL project ...@@ -35,191 +35,6 @@ This file is part of the QGROUNDCONTROL project
#include <QDir> #include <QDir>
#include <QSettings> #include <QSettings>
#include <QFileInfoList> #include <QFileInfoList>
#ifdef _WIN32
#include <qextserialenumerator.h>
#endif
#if defined (__APPLE__) && defined (__MACH__)
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/ioctl.h>
#include <errno.h>
#include <paths.h>
#include <termios.h>
#include <sysexits.h>
#include <sys/param.h>
#include <sys/select.h>
#include <sys/time.h>
#include <time.h>
#include <AvailabilityMacros.h>
#ifdef __MWERKS__
#define __CF_USE_FRAMEWORK_INCLUDES__
#endif
#include <CoreFoundation/CoreFoundation.h>
#include <IOKit/IOKitLib.h>
#include <IOKit/serial/IOSerialKeys.h>
#if defined(MAC_OS_X_VERSION_10_3) && (MAC_OS_X_VERSION_MIN_REQUIRED >= MAC_OS_X_VERSION_10_3)
#include <IOKit/serial/ioss.h>
#endif
#include <IOKit/IOBSD.h>
// Apple internal modems default to local echo being on. If your modem has local echo disabled,
// undefine the following macro.
#define LOCAL_ECHO
#define kATCommandString "AT\r"
#ifdef LOCAL_ECHO
#define kOKResponseString "AT\r\r\nOK\r\n"
#else
#define kOKResponseString "\r\nOK\r\n"
#endif
#endif
// Some helper functions for serial port enumeration
#if defined (__APPLE__) && defined (__MACH__)
enum {
kNumRetries = 3
};
// Function prototypes
static kern_return_t FindModems(io_iterator_t *matchingServices);
static kern_return_t GetModemPath(io_iterator_t serialPortIterator, char *bsdPath, CFIndex maxPathSize);
// Returns an iterator across all known modems. Caller is responsible for
// releasing the iterator when iteration is complete.
static kern_return_t FindModems(io_iterator_t *matchingServices)
{
kern_return_t kernResult;
CFMutableDictionaryRef classesToMatch;
/*! @function IOServiceMatching
@abstract Create a matching dictionary that specifies an IOService class match.
@discussion A very common matching criteria for IOService is based on its class. IOServiceMatching will create a matching dictionary that specifies any IOService of a class, or its subclasses. The class is specified by C-string name.
@param name The class name, as a const C-string. Class matching is successful on IOService's of this class or any subclass.
@result The matching dictionary created, is returned on success, or zero on failure. The dictionary is commonly passed to IOServiceGetMatchingServices or IOServiceAddNotification which will consume a reference, otherwise it should be released with CFRelease by the caller. */
// Serial devices are instances of class IOSerialBSDClient
classesToMatch = IOServiceMatching(kIOSerialBSDServiceValue);
if (classesToMatch == NULL) {
printf("IOServiceMatching returned a NULL dictionary.\n");
} else {
/*!
@function CFDictionarySetValue
Sets the value of the key in the dictionary.
@param theDict The dictionary to which the value is to be set. If this
parameter is not a valid mutable CFDictionary, the behavior is
undefined. If the dictionary is a fixed-capacity dictionary and
it is full before this operation, and the key does not exist in
the dictionary, the behavior is undefined.
@param key The key of the value to set into the dictionary. If a key
which matches this key is already present in the dictionary, only
the value is changed ("add if absent, replace if present"). If
no key matches the given key, the key-value pair is added to the
dictionary. If added, the key is retained by the dictionary,
using the retain callback provided
when the dictionary was created. If the key is not of the sort
expected by the key retain callback, the behavior is undefined.
@param value The value to add to or replace into the dictionary. The value
is retained by the dictionary using the retain callback provided
when the dictionary was created, and the previous value if any is
released. If the value is not of the sort expected by the
retain or release callbacks, the behavior is undefined.
*/
CFDictionarySetValue(classesToMatch,
CFSTR(kIOSerialBSDTypeKey),
CFSTR(kIOSerialBSDModemType));
// Each serial device object has a property with key
// kIOSerialBSDTypeKey and a value that is one of kIOSerialBSDAllTypes,
// kIOSerialBSDModemType, or kIOSerialBSDRS232Type. You can experiment with the
// matching by changing the last parameter in the above call to CFDictionarySetValue.
// As shipped, this sample is only interested in modems,
// so add this property to the CFDictionary we're matching on.
// This will find devices that advertise themselves as modems,
// such as built-in and USB modems. However, this match won't find serial modems.
}
/*! @function IOServiceGetMatchingServices
@abstract Look up registered IOService objects that match a matching dictionary.
@discussion This is the preferred method of finding IOService objects currently registered by IOKit. IOServiceAddNotification can also supply this information and install a notification of new IOServices. The matching information used in the matching dictionary may vary depending on the class of service being looked up.
@param masterPort The master port obtained from IOMasterPort().
@param matching A CF dictionary containing matching information, of which one reference is consumed by this function. IOKitLib can contruct matching dictionaries for common criteria with helper functions such as IOServiceMatching, IOOpenFirmwarePathMatching.
@param existing An iterator handle is returned on success, and should be released by the caller when the iteration is finished.
@result A kern_return_t error code. */
kernResult = IOServiceGetMatchingServices(kIOMasterPortDefault, classesToMatch, matchingServices);
if (KERN_SUCCESS != kernResult) {
printf("IOServiceGetMatchingServices returned %d\n", kernResult);
goto exit;
}
exit:
return kernResult;
}
/** Given an iterator across a set of modems, return the BSD path to the first one.
* If no modems are found the path name is set to an empty string.
*/
static kern_return_t GetModemPath(io_iterator_t serialPortIterator, char *bsdPath, CFIndex maxPathSize)
{
io_object_t modemService;
kern_return_t kernResult = KERN_FAILURE;
Boolean modemFound = false;
// Initialize the returned path
*bsdPath = '\0';
// Iterate across all modems found. In this example, we bail after finding the first modem.
while ((modemService = IOIteratorNext(serialPortIterator)) && !modemFound) {
CFTypeRef bsdPathAsCFString;
// Get the callout device's path (/dev/cu.xxxxx). The callout device should almost always be
// used: the dialin device (/dev/tty.xxxxx) would be used when monitoring a serial port for
// incoming calls, e.g. a fax listener.
bsdPathAsCFString = IORegistryEntryCreateCFProperty(modemService,
CFSTR(kIOCalloutDeviceKey),
kCFAllocatorDefault,
0);
if (bsdPathAsCFString) {
Boolean result;
// Convert the path from a CFString to a C (NUL-terminated) string for use
// with the POSIX open() call.
result = CFStringGetCString((CFStringRef)bsdPathAsCFString,
bsdPath,
maxPathSize,
kCFStringEncodingUTF8);
CFRelease(bsdPathAsCFString);
if (result) {
//printf("Modem found with BSD path: %s", bsdPath);
modemFound = true;
kernResult = KERN_SUCCESS;
}
}
printf("\n");
// Release the io_service_t now that we are done with it.
(void) IOObjectRelease(modemService);
}
return kernResult;
}
#endif
SerialConfigurationWindow::SerialConfigurationWindow(LinkInterface* link, QWidget *parent, Qt::WindowFlags flags) : QWidget(parent, flags), SerialConfigurationWindow::SerialConfigurationWindow(LinkInterface* link, QWidget *parent, Qt::WindowFlags flags) : QWidget(parent, flags),
userConfigured(false) userConfigured(false)
...@@ -378,102 +193,29 @@ void SerialConfigurationWindow::configureCommunication() ...@@ -378,102 +193,29 @@ void SerialConfigurationWindow::configureCommunication()
void SerialConfigurationWindow::setupPortList() void SerialConfigurationWindow::setupPortList()
{ {
//ui.portName->clear(); if (!link) return;
// Get list of existing items
#ifdef __linux
// TODO Linux has no standard way of enumerating serial ports
// However the device files are only present when the physical
// device is connected, therefore listing the files should be
// sufficient.
QString devdir = "/dev";
QDir dir(devdir);
dir.setFilter(QDir::System);
QFileInfoList list = dir.entryInfoList(); if (!userConfigured)
for (int i = 0; i < list.size(); ++i) { {
QFileInfo fileInfo = list.at(i); ui.portName->clear();
if (fileInfo.fileName().contains(QString("ttyUSB")) || fileInfo.fileName().contains(QString("ttyS")) || fileInfo.fileName().contains(QString("ttyACM"))) { ui.portName->clearEditText();
if (ui.portName->findText(fileInfo.canonicalFilePath()) == -1) {
ui.portName->addItem(fileInfo.canonicalFilePath());
if (!userConfigured) ui.portName->setEditText(fileInfo.canonicalFilePath());
} }
}
}
#endif
#if defined (__APPLE__) && defined (__MACH__)
// Enumerate serial ports
//int fileDescriptor;
kern_return_t kernResult; // on PowerPC this is an int (4 bytes)
io_iterator_t serialPortIterator;
char bsdPath[MAXPATHLEN];
kernResult = FindModems(&serialPortIterator);
kernResult = GetModemPath(serialPortIterator, bsdPath, sizeof(bsdPath));
IOObjectRelease(serialPortIterator); // Release the iterator.
// Add found modems
if (bsdPath[0]) {
if (ui.portName->findText(QString(bsdPath)) == -1) {
ui.portName->addItem(QString(bsdPath));
if (!userConfigured) ui.portName->setEditText(QString(bsdPath));
}
}
// Add USB serial port adapters
// TODO Strangely usb serial port adapters are not enumerated, even when connected
QString devdir = "/dev";
QDir dir(devdir);
dir.setFilter(QDir::System);
QFileInfoList list = dir.entryInfoList();
for (int i = list.size() - 1; i >= 0; i--) {
QFileInfo fileInfo = list.at(i);
if (fileInfo.fileName().contains(QString("ttyUSB")) || fileInfo.fileName().contains(QString("ttyS")) || fileInfo.fileName().contains(QString("tty.usbserial")) || fileInfo.fileName().contains(QString("ttyACM"))) {
if (ui.portName->findText(fileInfo.canonicalFilePath()) == -1) {
ui.portName->addItem(fileInfo.canonicalFilePath());
if (!userConfigured) ui.portName->setEditText(fileInfo.canonicalFilePath());
}
}
}
#endif
#ifdef _WIN32
// Get the ports available on this system // Get the ports available on this system
QList<QextPortInfo> ports = QextSerialEnumerator::getPorts(); QVector<QString>* ports = link->getCurrentPorts();
// Add the ports in reverse order, because we prepend them to the list // Add the ports in reverse order, because we prepend them to the list
for (int i = ports.size() - 1; i >= 0; i--) { for (int i = ports->size() - 1; i >= 0; --i)
QString portString = QString(ports.at(i).portName.toLocal8Bit().constData()) + " - " + QString(ports.at(i).friendName.toLocal8Bit().constData()).split("(").first(); {
// Prepend newly found port to the list // Prepend newly found port to the list
if (ui.portName->findText(portString) == -1) { if (ui.portName->findText(ports->at(i)) == -1)
ui.portName->insertItem(0, portString); {
if (!userConfigured) ui.portName->setEditText(portString); ui.portName->insertItem(0, ports->at(i));
if (!userConfigured) ui.portName->setEditText(ports->at(i));
} }
} }
//printf("port name: %s\n", ports.at(i).portName.toLocal8Bit().constData());
//printf("friendly name: %s\n", ports.at(i).friendName.toLocal8Bit().constData());
//printf("physical name: %s\n", ports.at(i).physName.toLocal8Bit().constData());
//printf("enumerator name: %s\n", ports.at(i).enumName.toLocal8Bit().constData());
//printf("===================================\n\n");
#endif
if (this->link) {
if (this->link->getPortName() != "") {
ui.portName->setEditText(this->link->getPortName()); ui.portName->setEditText(this->link->getPortName());
}
}
} }
void SerialConfigurationWindow::enableFlowControl(bool flow) void SerialConfigurationWindow::enableFlowControl(bool flow)
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment