📢 Webサイト閉鎖と移転のお知らせ
このWebサイトは2026年9月に閉鎖いたします。
新しい記事は移転先で追加しております。(旧サイトでは記事を追加しておりません)

452行目: 452行目:
* 接続パラメータの最適化
* 接続パラメータの最適化
*: 電力消費、通信速度、接続の安定性等のバランスを取る。
*: 電力消費、通信速度、接続の安定性等のバランスを取る。
<br>
<syntaxhighlight lang="c++">
#include <QBluetoothSocket>
#include <QDebug>
#include <memory>
class BluetoothConnection : public QObject
{
    Q_OBJECT
private:
    std::unique_ptr<QBluetoothSocket> socket;
    // エラーコードを文字列に変換するヘルパー関数
    QString errorToString(QBluetoothSocket::SocketError error)
    {
      switch (error) {
          case QBluetoothSocket::NoSocketError:        return "エラーなし";
          case QBluetoothSocket::UnknownSocketError:  return "不明なエラー";
          case QBluetoothSocket::HostNotFoundError:    return "ホストが見つかりません";
          case QBluetoothSocket::ServiceNotFoundError: return "サービスが見つかりません";
          case QBluetoothSocket::NetworkError:        return "ネットワークエラー";
          case QBluetoothSocket::OperationError:      return "操作エラー";
          default:                                    return "予期せぬエラー";
      }
    }
    // 接続状態を文字列に変換するヘルパー関数
    QString stateToString(QBluetoothSocket::SocketState state)
    {
      switch (state) {
          case QBluetoothSocket::UnconnectedState:  return "未接続";
          case QBluetoothSocket::ConnectingState:    return "接続中";
          case QBluetoothSocket::ConnectedState:    return "接続済み";
          case QBluetoothSocket::BoundState:        return "バインド済み";
          case QBluetoothSocket::ClosingState:      return "切断中";
          case QBluetoothSocket::ServiceLookupState: return "サービス検索中";
          default:                                  return "不明な状態";
      }
    }
public:
    explicit BluetoothConnection(QObject* parent = nullptr) : QObject(parent)
    {
      try {
          // RFCOMMソケットの作成
          socket = std::make_unique<QBluetoothSocket>(QBluetoothServiceInfo::RfcommProtocol, this);
          // 各種シグナルとスロットの接続
          connect(socket.get(), &QBluetoothSocket::connected, this, &BluetoothConnection::onConnected);
          connect(socket.get(), &QBluetoothSocket::disconnected, this, &BluetoothConnection::onDisconnected);
          connect(socket.get(), &QBluetoothSocket::errorOccurred, this, &BluetoothConnection::onError);
          connect(socket.get(), &QBluetoothSocket::readyRead, this, &BluetoothConnection::onDataReceived);
          connect(socket.get(), &QBluetoothSocket::stateChanged, this, &BluetoothConnection::onStateChanged);
      }
      catch (const std::exception &e) {
          qDebug() << "初期化エラー: " << e.what();
          throw;
      }
    }
    // デバイスに接続
    void connectToDevice(const QBluetoothAddress &address, quint16 port)
    {
      try {
          if (socket->state() == QBluetoothSocket::ConnectedState) {
            qDebug() << "既に接続済み";
            return;
          }
          qDebug() << "デバイスに接続します: " << address.toString();
          qDebug() << "ポート: " << port;
          socket->connectToService(address, port);
      }
      catch (const std::exception &e) {
          qDebug() << "接続エラー: " << e.what();
          throw;
      }
    }
    // 接続を切断
    void disconnect()
    {
      try {
          if (socket->state() != QBluetoothSocket::UnconnectedState) {
            qDebug() << "接続を切断...";
            socket->disconnectFromService();
          }
      }
      catch (const std::exception &e) {
          qDebug() << "切断エラー: " << e.what();
          throw;
      }
    }
    // データを送信
    bool sendData(const QByteArray &data)
    {
      try {
          if (socket->state() != QBluetoothSocket::ConnectedState) {
            qDebug() << "送信エラー: 接続されていません";
            return false;
          }
          qint64 bytesWritten = socket->write(data);
          if (bytesWritten == -1) {
            qDebug() << "送信エラー: データの書き込みに失敗";
            return false;
          }
          qDebug() << bytesWritten << "バイトデータの送信完了";
          return true;
      }
      catch (const std::exception &e) {
          qDebug() << "送信エラー: " << e.what();
          throw;
      }
    }
private slots:
    // 接続確立時のスロット
    void onConnected()
    {
      qDebug() << "接続が確立";
      qDebug() << "  ローカルアドレス:" << socket->localAddress().toString();
      qDebug() << "  リモートアドレス:" << socket->peerAddress().toString();
    }
    // 切断時のスロット
    void onDisconnected()
    {
      qDebug() << "接続が切断";
    }
    // エラー発生時のスロット
    void onError(QBluetoothSocket::SocketError error)
    {
      qDebug() << "エラーが発生: " << errorToString(error);
    }
    // データ受信時のスロット
    void onDataReceived()
    {
      QByteArray data = socket->readAll();
      qDebug() << "データを受信: " << data.size() << "バイト";
      // ここでデータを処理する
      // ...略
    }
    // 接続状態変更時のスロット
    void onStateChanged(QBluetoothSocket::SocketState state)
    {
      qDebug() << "接続状態が変更: " << stateToString(state);
    }
};
</syntaxhighlight>
<br><br>
<br><br>