* @brief Opens the currently selected serial port with the specified mode. */
| 205 | * @brief Opens the currently selected serial port with the specified mode. |
| 206 | */ |
| 207 | bool IO::Drivers::UART::open(const QIODevice::OpenMode mode) |
| 208 | { |
| 209 | if (m_deviceNames.isEmpty()) |
| 210 | refreshSerialDevices(); |
| 211 | |
| 212 | auto ports = portList(); |
| 213 | auto portId = portIndex(); |
| 214 | if (portId >= 1 && portId < ports.count()) { |
| 215 | close(); |
| 216 | m_portIndex = portId; |
| 217 | m_lastSerialDeviceIndex = m_portIndex; |
| 218 | Q_EMIT portIndexChanged(); |
| 219 | |
| 220 | const auto name = ports.at(portId); |
| 221 | |
| 222 | if (m_deviceNames.contains(name)) { |
| 223 | const auto target = |
| 224 | portId < m_deviceLocations.count() ? m_deviceLocations.at(portId) : QString(); |
| 225 | const auto live = validPorts(); |
| 226 | |
| 227 | const int matchIndex = matchPortByLocation(live, target); |
| 228 | if (matchIndex < 0) { |
| 229 | close(); |
| 230 | return false; |
| 231 | } |
| 232 | |
| 233 | m_usingCustomSerialPort = false; |
| 234 | m_port = new QSerialPort(live.at(matchIndex)); |
| 235 | } |
| 236 | |
| 237 | else if (m_customDevices.contains(name)) { |
| 238 | m_usingCustomSerialPort = true; |
| 239 | m_port = new QSerialPort(name); |
| 240 | } |
| 241 | |
| 242 | if (!m_port) |
| 243 | return false; |
| 244 | |
| 245 | port()->setParity(parity()); |
| 246 | port()->setBaudRate(baudRate()); |
| 247 | port()->setDataBits(dataBits()); |
| 248 | port()->setStopBits(stopBits()); |
| 249 | port()->setFlowControl(flowControl()); |
| 250 | port()->setReadBufferSize(idealSerialBufferSize(baudRate())); |
| 251 | |
| 252 | connect(port(), &QSerialPort::errorOccurred, this, &IO::Drivers::UART::handleError); |
| 253 | |
| 254 | if (port()->open(mode)) { |
| 255 | connect(port(), &QIODevice::readyRead, this, &IO::Drivers::UART::onReadyRead); |
| 256 | port()->setDataTerminalReady(dtrEnabled()); |
| 257 | return true; |
| 258 | } |
| 259 | |
| 260 | else { |
| 261 | Misc::Utilities::showMessageBox(tr("Failed to connect to serial port \"%1\"").arg(name), |
| 262 | port()->errorString(), |
| 263 | QMessageBox::Critical); |
| 264 | } |
nothing calls this directly
no test coverage detected