main.cpp 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. #include <QCoreApplication>
  2. #include <QSerialPort>
  3. #include <QFile>
  4. #include <QDebug>
  5. #include <QFileSystemWatcher>
  6. #include <QDir>
  7. #include <QScopedPointer>
  8. #include <QTimer>
  9. #include <iostream>
  10. int main(int argc, char *argv[])
  11. {
  12. QString comPortPath;
  13. QString commandFile;
  14. QCoreApplication a(argc, argv);
  15. if(a.arguments().count() != 3) {
  16. qCritical() << "Usage SimpleSerial <COM Port> <File name>";
  17. return 1;
  18. }
  19. commandFile = QDir(".").absoluteFilePath(a.arguments().at(2));
  20. comPortPath = a.arguments().at(1);
  21. QSerialPort* port(new QSerialPort(comPortPath));
  22. port->setFlowControl(QSerialPort::SoftwareControl);
  23. port->setBaudRate(QSerialPort::Baud115200);
  24. port->setStopBits(QSerialPort::OneStop);
  25. port->setDataBits(QSerialPort::Data8);
  26. port->setParity(QSerialPort::NoParity);
  27. port->setReadBufferSize(100000);
  28. QObject::connect(port, &QSerialPort::readyRead, [&](){
  29. std::cout << port->readAll().data();
  30. });
  31. QObject::connect(port, &QSerialPort::errorOccurred, [&](QSerialPort::SerialPortError serialPortError){
  32. qCritical() << serialPortError;
  33. });
  34. if(!port->open(QIODevice::ReadWrite)) {
  35. qCritical() << "Unable to open" << port->portName();
  36. delete port;
  37. return 1;
  38. }
  39. QFileSystemWatcher* watcher(new QFileSystemWatcher(QStringList() << commandFile, &a));
  40. QObject::connect(watcher, &QFileSystemWatcher::fileChanged, [&](const QString &path){
  41. qDebug() << "watcher alarm";
  42. if(path == commandFile) {
  43. QFile file(commandFile);
  44. if(!file.open(QFile::ReadOnly)) {
  45. qCritical() << "Unable to open command file: " << commandFile;
  46. a.exit(1);
  47. }
  48. while(!file.atEnd()) {
  49. QByteArray command = file.readLine();
  50. port->write(command);
  51. }
  52. file.close();
  53. watcher->addPath(commandFile);
  54. }
  55. });
  56. QTimer testTimer;
  57. testTimer.setInterval(1000);
  58. testTimer.setSingleShot(true);
  59. QObject::connect(&testTimer, &QTimer::timeout, [&]() {
  60. QFile file(commandFile);
  61. if(!file.open(QFile::ReadOnly)) {
  62. qCritical() << "Unable to open command file: " << commandFile;
  63. a.exit(1);
  64. }
  65. while(!file.atEnd()) {
  66. QByteArray command = file.readLine();
  67. port->write(command);
  68. }
  69. file.close();
  70. });
  71. testTimer.start();
  72. int retVal = a.exec();
  73. port->close();
  74. delete port;
  75. return retVal;
  76. }