1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586 |
- #include <QCoreApplication>
- #include <QSerialPort>
- #include <QFile>
- #include <QDebug>
- #include <QFileSystemWatcher>
- #include <QDir>
- #include <QScopedPointer>
- #include <QTimer>
- #include <iostream>
- int main(int argc, char *argv[])
- {
- QString comPortPath;
- QString commandFile;
- QCoreApplication a(argc, argv);
- if(a.arguments().count() != 3) {
- qCritical() << "Usage SimpleSerial <COM Port> <File name>";
- return 1;
- }
- commandFile = QDir(".").absoluteFilePath(a.arguments().at(2));
- comPortPath = a.arguments().at(1);
- QSerialPort* port(new QSerialPort(comPortPath));
- port->setFlowControl(QSerialPort::SoftwareControl);
- port->setBaudRate(QSerialPort::Baud115200);
- port->setStopBits(QSerialPort::OneStop);
- port->setDataBits(QSerialPort::Data8);
- port->setParity(QSerialPort::NoParity);
- port->setReadBufferSize(100000);
- QObject::connect(port, &QSerialPort::readyRead, [&](){
- std::cout << port->readAll().data();
- });
- QObject::connect(port, &QSerialPort::errorOccurred, [&](QSerialPort::SerialPortError serialPortError){
- qCritical() << serialPortError;
- });
- if(!port->open(QIODevice::ReadWrite)) {
- qCritical() << "Unable to open" << port->portName();
- delete port;
- return 1;
- }
- QFileSystemWatcher* watcher(new QFileSystemWatcher(QStringList() << commandFile));
- QObject::connect(watcher, &QFileSystemWatcher::fileChanged, [&](const QString &path){
- qDebug() << "watcher alarm";
- if(path == commandFile) {
- QFile file(commandFile);
- if(!file.open(QFile::ReadOnly)) {
- qCritical() << "Unable to open command file: " << commandFile;
- a.exit(1);
- }
- while(!file.atEnd()) {
- QByteArray command = file.readLine();
- port->write(command);
- }
- file.close();
- watcher->addPath(commandFile);
- }
- });
- QTimer testTimer;
- testTimer.setInterval(1000);
- testTimer.setSingleShot(true);
- QObject::connect(&testTimer, &QTimer::timeout, [&]() {
- QFile file(commandFile);
- if(!file.open(QFile::ReadOnly)) {
- qCritical() << "Unable to open command file: " << commandFile;
- a.exit(1);
- }
- while(!file.atEnd()) {
- QByteArray command = file.readLine();
- port->write(command);
- }
- file.close();
- });
- testTimer.start();
- int retVal = a.exec();
- port->close();
- delete port;
- return retVal;
- }
|