PageRenderTime 24ms CodeModel.GetById 30ms RepoModel.GetById 1ms app.codeStats 0ms

/qtserialbus/examples/serialbus/can/mainwindow.cpp

https://bitbucket.org/lotiuss/qt-5.11.0
C++ | 239 lines | 151 code | 39 blank | 49 comment | 17 complexity | 2bbe8a7eb86380a5aab830c2b7a013f8 MD5 | raw file
Possible License(s): GPL-3.0, MPL-2.0, CC-BY-SA-3.0, LGPL-2.0, Unlicense, BSD-3-Clause, Apache-2.0, LGPL-3.0, MIT, WTFPL, GPL-2.0, MPL-2.0-no-copyleft-exception, AGPL-3.0, LGPL-2.1, BSD-2-Clause, 0BSD, JSON, ISC
  1. /****************************************************************************
  2. **
  3. ** Copyright (C) 2017 The Qt Company Ltd.
  4. ** Contact: https://www.qt.io/licensing/
  5. **
  6. ** This file is part of the examples of the QtSerialBus module.
  7. **
  8. ** $QT_BEGIN_LICENSE:BSD$
  9. ** Commercial License Usage
  10. ** Licensees holding valid commercial Qt licenses may use this file in
  11. ** accordance with the commercial license agreement provided with the
  12. ** Software or, alternatively, in accordance with the terms contained in
  13. ** a written agreement between you and The Qt Company. For licensing terms
  14. ** and conditions see https://www.qt.io/terms-conditions. For further
  15. ** information use the contact form at https://www.qt.io/contact-us.
  16. **
  17. ** BSD License Usage
  18. ** Alternatively, you may use this file under the terms of the BSD license
  19. ** as follows:
  20. **
  21. ** "Redistribution and use in source and binary forms, with or without
  22. ** modification, are permitted provided that the following conditions are
  23. ** met:
  24. ** * Redistributions of source code must retain the above copyright
  25. ** notice, this list of conditions and the following disclaimer.
  26. ** * Redistributions in binary form must reproduce the above copyright
  27. ** notice, this list of conditions and the following disclaimer in
  28. ** the documentation and/or other materials provided with the
  29. ** distribution.
  30. ** * Neither the name of The Qt Company Ltd nor the names of its
  31. ** contributors may be used to endorse or promote products derived
  32. ** from this software without specific prior written permission.
  33. **
  34. **
  35. ** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  36. ** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  37. ** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  38. ** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  39. ** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  40. ** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  41. ** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  42. ** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  43. ** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  44. ** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  45. ** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE."
  46. **
  47. ** $QT_END_LICENSE$
  48. **
  49. ****************************************************************************/
  50. #include "mainwindow.h"
  51. #include "ui_mainwindow.h"
  52. #include "connectdialog.h"
  53. #include <QCanBus>
  54. #include <QCanBusFrame>
  55. #include <QCloseEvent>
  56. #include <QDesktopServices>
  57. #include <QTimer>
  58. MainWindow::MainWindow(QWidget *parent) :
  59. QMainWindow(parent),
  60. m_ui(new Ui::MainWindow)
  61. {
  62. m_ui->setupUi(this);
  63. m_connectDialog = new ConnectDialog;
  64. m_status = new QLabel;
  65. m_ui->statusBar->addPermanentWidget(m_status);
  66. m_written = new QLabel;
  67. m_ui->statusBar->addWidget(m_written);
  68. initActionsConnections();
  69. QTimer::singleShot(50, m_connectDialog, &ConnectDialog::show);
  70. }
  71. MainWindow::~MainWindow()
  72. {
  73. delete m_canDevice;
  74. delete m_connectDialog;
  75. delete m_ui;
  76. }
  77. void MainWindow::initActionsConnections()
  78. {
  79. m_ui->actionDisconnect->setEnabled(false);
  80. m_ui->sendFrameBox->setEnabled(false);
  81. connect(m_ui->sendFrameBox, &SendFrameBox::sendFrame, this, &MainWindow::sendFrame);
  82. connect(m_ui->actionConnect, &QAction::triggered, m_connectDialog, &ConnectDialog::show);
  83. connect(m_connectDialog, &QDialog::accepted, this, &MainWindow::connectDevice);
  84. connect(m_ui->actionDisconnect, &QAction::triggered, this, &MainWindow::disconnectDevice);
  85. connect(m_ui->actionQuit, &QAction::triggered, this, &QWidget::close);
  86. connect(m_ui->actionAboutQt, &QAction::triggered, qApp, &QApplication::aboutQt);
  87. connect(m_ui->actionClearLog, &QAction::triggered, m_ui->receivedMessagesEdit, &QTextEdit::clear);
  88. connect(m_ui->actionPluginDocumentation, &QAction::triggered, this, []() {
  89. QDesktopServices::openUrl(QUrl("http://doc.qt.io/qt-5/qtcanbus-backends.html#can-bus-plugins"));
  90. });
  91. }
  92. void MainWindow::processErrors(QCanBusDevice::CanBusError error) const
  93. {
  94. switch (error) {
  95. case QCanBusDevice::ReadError:
  96. case QCanBusDevice::WriteError:
  97. case QCanBusDevice::ConnectionError:
  98. case QCanBusDevice::ConfigurationError:
  99. case QCanBusDevice::UnknownError:
  100. m_status->setText(m_canDevice->errorString());
  101. break;
  102. default:
  103. break;
  104. }
  105. }
  106. void MainWindow::connectDevice()
  107. {
  108. const ConnectDialog::Settings p = m_connectDialog->settings();
  109. QString errorString;
  110. m_canDevice = QCanBus::instance()->createDevice(p.pluginName, p.deviceInterfaceName,
  111. &errorString);
  112. if (!m_canDevice) {
  113. m_status->setText(tr("Error creating device '%1', reason: '%2'")
  114. .arg(p.pluginName).arg(errorString));
  115. return;
  116. }
  117. m_numberFramesWritten = 0;
  118. connect(m_canDevice, &QCanBusDevice::errorOccurred, this, &MainWindow::processErrors);
  119. connect(m_canDevice, &QCanBusDevice::framesReceived, this, &MainWindow::processReceivedFrames);
  120. connect(m_canDevice, &QCanBusDevice::framesWritten, this, &MainWindow::processFramesWritten);
  121. if (p.useConfigurationEnabled) {
  122. for (const ConnectDialog::ConfigurationItem &item : p.configurations)
  123. m_canDevice->setConfigurationParameter(item.first, item.second);
  124. }
  125. if (!m_canDevice->connectDevice()) {
  126. m_status->setText(tr("Connection error: %1").arg(m_canDevice->errorString()));
  127. delete m_canDevice;
  128. m_canDevice = nullptr;
  129. } else {
  130. m_ui->actionConnect->setEnabled(false);
  131. m_ui->actionDisconnect->setEnabled(true);
  132. m_ui->sendFrameBox->setEnabled(true);
  133. QVariant bitRate = m_canDevice->configurationParameter(QCanBusDevice::BitRateKey);
  134. if (bitRate.isValid()) {
  135. m_status->setText(tr("Plugin: %1, connected to %2 at %3 kBit/s")
  136. .arg(p.pluginName).arg(p.deviceInterfaceName)
  137. .arg(bitRate.toInt() / 1000));
  138. } else {
  139. m_status->setText(tr("Plugin: %1, connected to %2")
  140. .arg(p.pluginName).arg(p.deviceInterfaceName));
  141. }
  142. }
  143. }
  144. void MainWindow::disconnectDevice()
  145. {
  146. if (!m_canDevice)
  147. return;
  148. m_canDevice->disconnectDevice();
  149. delete m_canDevice;
  150. m_canDevice = nullptr;
  151. m_ui->actionConnect->setEnabled(true);
  152. m_ui->actionDisconnect->setEnabled(false);
  153. m_ui->sendFrameBox->setEnabled(false);
  154. m_status->setText(tr("Disconnected"));
  155. }
  156. void MainWindow::processFramesWritten(qint64 count)
  157. {
  158. m_numberFramesWritten += count;
  159. m_written->setText(tr("%1 frames written").arg(m_numberFramesWritten));
  160. }
  161. void MainWindow::closeEvent(QCloseEvent *event)
  162. {
  163. m_connectDialog->close();
  164. event->accept();
  165. }
  166. static QString frameFlags(const QCanBusFrame &frame)
  167. {
  168. QString result = QLatin1String(" --- ");
  169. if (frame.hasBitrateSwitch())
  170. result[1] = QLatin1Char('B');
  171. if (frame.hasErrorStateIndicator())
  172. result[2] = QLatin1Char('E');
  173. if (frame.hasLocalEcho())
  174. result[3] = QLatin1Char('L');
  175. return result;
  176. }
  177. void MainWindow::processReceivedFrames()
  178. {
  179. if (!m_canDevice)
  180. return;
  181. while (m_canDevice->framesAvailable()) {
  182. const QCanBusFrame frame = m_canDevice->readFrame();
  183. QString view;
  184. if (frame.frameType() == QCanBusFrame::ErrorFrame)
  185. view = m_canDevice->interpretErrorFrame(frame);
  186. else
  187. view = frame.toString();
  188. const QString time = QString::fromLatin1("%1.%2 ")
  189. .arg(frame.timeStamp().seconds(), 10, 10, QLatin1Char(' '))
  190. .arg(frame.timeStamp().microSeconds() / 100, 4, 10, QLatin1Char('0'));
  191. const QString flags = frameFlags(frame);
  192. m_ui->receivedMessagesEdit->append(time + flags + view);
  193. }
  194. }
  195. void MainWindow::sendFrame(const QCanBusFrame &frame) const
  196. {
  197. if (!m_canDevice)
  198. return;
  199. m_canDevice->writeFrame(frame);
  200. }