12,925
回編集
(→非同期) |
(→非同期) |
||
135行目: | 135行目: | ||
private: | private: | ||
QSerialPort *m_serialPort; | QSerialPort *m_serialPort; | ||
qint64 m_bytesWritten; | |||
qint64 m_totalBytesToWrite; | |||
public: | public: | ||
explicit SerialCommunication(QObject *parent = nullptr) : QObject(parent) | explicit SerialCommunication(QObject *parent = nullptr) : QObject(parent), m_bytesWritten(0), m_totalBytesToWrite(0) | ||
{ | { | ||
m_serialPort = new QSerialPort(this); | |||
connect(m_serialPort, &QSerialPort::readyRead, this, &SerialCommunication::handleReadyRead); | |||
connect(m_serialPort, &QSerialPort::errorOccurred, this, &SerialCommunication::handleError); | |||
connect(m_serialPort, &QSerialPort::bytesWritten, this, &SerialCommunication::handleBytesWritten); | |||
} | } | ||
166行目: | 169行目: | ||
{ | { | ||
if (m_serialPort->isOpen()) { | if (m_serialPort->isOpen()) { | ||
m_bytesWritten = 0; | |||
m_totalBytesToWrite = data.size(); | |||
qint64 bytesWritten = m_serialPort->write(data); | qint64 bytesWritten = m_serialPort->write(data); | ||
if (bytesWritten == -1) { | if (bytesWritten == -1) { | ||
qDebug() << "ポートへのデータの書き込みに失敗: " << m_serialPort->errorString(); | qDebug() << "ポートへのデータの書き込みに失敗: " << m_serialPort->errorString(); | ||
179行目: | 185行目: | ||
} | } | ||
} | } | ||
signals: | |||
void transmissionComplete(); | |||
private slots: | private slots: | ||
192行目: | 201行目: | ||
void handleBytesWritten(qint64 bytes) | void handleBytesWritten(qint64 bytes) | ||
{ | { | ||
qDebug() << " | m_bytesWritten += bytes; | ||
qDebug() << "Bytes written:" << bytes << "Total:" << m_bytesWritten << "of" << m_totalBytesToWrite; | |||
// ここで送信完了後の処理を行う | if (m_bytesWritten >= m_totalBytesToWrite) { | ||
qDebug() << "Transmission complete!"; | |||
emit transmissionComplete(); | |||
// ここで送信完了後の処理を行う | |||
// ...略 | |||
} | |||
} | } | ||
243行目: | 258行目: | ||
SerialCommunication serialComm; | SerialCommunication serialComm; | ||
QObject::connect(&serialComm, &SerialCommunication::transmissionComplete, []() { | |||
qDebug() << "送信完了のシグナルを受信した時"; | |||
// ここで送信完了後の処理を行う | |||
// ...略 | |||
}); | |||
// 任意のポート名を指定すること | // 任意のポート名を指定すること |