Jason
Jason

Reputation: 160

Connecting and sending a message in bluetooth using python and PyQt5

I have been trying to connect to a Bluetooth device (regular, not low energy - an HC-06) using PyQt5 but with no success. I can connect to the same device using standard python calls. I am running Python 3.7 on MacOS. When I run the below code, I get the error: 'unknown error', I'd be happy to know what I am doing wrong.

import sys
import bluetooth
import os

from PyQt5.QtWidgets import QApplication, QWidget
from PyQt5.QtCore import Qt
from PyQt5 import QtBluetooth

class bluetoothTest(QWidget):

    def __init__(self, parent = None):

        super(bluetoothTest, self).__init__(parent)

        self.connectToRobot()

        self.app = QApplication(sys.argv)
        self.win = QWidget()
        self.win.show()
        sys.exit(self.app.exec_())

    def connectToRobot(self):
        self.sock = QtBluetooth.QBluetoothSocket(bluetooth.RFCOMM)

        self.sock.connected.connect(self.connectedToBluetooth)
        self.sock.readyRead.connect(self.receivedBluetoothMessage)
        self.sock.disconnected.connect(self.disconnectedFromBluetooth)
        self.sock.error.connect(self.socketError)
        port = 1
        self.sock.connectToService(QtBluetooth.QBluetoothAddress("98:D3:C1:FD:2C:46"),port)

    def socketError(self,error):
        print(self.sock.errorString())

    def connectedToBluetooth(self):
        self.sock.write('A'.encode())

    def disconnectedFromBluetooth(self):
        self.print('Disconnected from bluetooth')

    def receivedBluetoothMessage(self):
        while sock.canReadLine():
            line = sock.readLine()
            print(line)

def main():
    # deal with a bluetooth bug on mac
    if sys.platform == 'darwin':
        os.environ['QT_EVENT_DISPATCHER_CORE_FOUNDATION'] = '1'

    app = QApplication(sys.argv)
    ex = bluetoothTest()
    ex.show()
    sys.exit(app.exec_())

if __name__ == '__main__':
        main()

Upvotes: 0

Views: 3276

Answers (1)

Jason
Jason

Reputation: 160

The problem with my code was the mixing of "regular" Bluetooth and Qt Bluetooth functions, in particular this line:

 self.sock = QtBluetooth.QBluetoothSocket(bluetooth.RFCOMM)

which should have been

self.sock = QtBluetooth.QBluetoothSocket(QtBluetooth.QBluetoothServiceInfo.RfcommProtocol)

Here is the complete working code example:

import sys
import os

from PyQt5.QtWidgets import QApplication, QWidget
from PyQt5.QtCore import Qt
from PyQt5 import QtBluetooth

class bluetoothTest(QWidget):

    def __init__(self, parent = None):
        super(bluetoothTest, self).__init__(parent)
        self.connectToRobot()
        self.win = QWidget()
        self.win.show()

    def connectToRobot(self):
        self.sock = QtBluetooth.QBluetoothSocket(QtBluetooth.QBluetoothServiceInfo.RfcommProtocol)

        self.sock.connected.connect(self.connectedToBluetooth)
        self.sock.readyRead.connect(self.receivedBluetoothMessage)
        self.sock.disconnected.connect(self.disconnectedFromBluetooth)
        self.sock.error.connect(self.socketError)
        port = 1
        self.sock.connectToService(QtBluetooth.QBluetoothAddress("98:D3:C1:FD:2C:46"),port)

    def socketError(self,error):
        print(self.sock.errorString())

    def connectedToBluetooth(self):
        self.sock.write('A'.encode())

    def disconnectedFromBluetooth(self):
        self.print('Disconnected from bluetooth')

    def receivedBluetoothMessage(self):
        while self.sock.canReadLine():
            line = self.sock.readLine()
            print(str(line, "utf-8"))

def main():
    # deal with a bluetooth bug on mac
    if sys.platform == 'darwin':
        os.environ['QT_EVENT_DISPATCHER_CORE_FOUNDATION'] = '1'

    app = QApplication(sys.argv)
    ex = bluetoothTest()
    sys.exit(app.exec_())

if __name__ == '__main__':
        main()

Upvotes: 1

Related Questions