[PyQt] Connecting and sending a message in bluetooth using python and PyQt5

Jason Friedman write.to.jason at gmail.com
Sat Apr 18 08:43:13 BST 2020


David,

Thanks for taking the time to answer.

I found the problem - I was mixing "regular" Bluetooth and QtBluetooth.

In particular, this line:
        self.sock = QtBluetooth.QBluetoothSocket(bluetooth.RFCOMM)
should have been:
        self.sock =
QtBluetooth.QBluetoothSocket(QtBluetooth.QBluetoothServiceInfo.RfcommProtocol)

> You are already creating and starting a QApplication instance in your main
code. Does removing this help at all?

Now the program works. And after I removed the duplicate calls to
QApplication, it stopped crashing on exit also :)

> Perhaps it would be useful to see the regular Python code.

For reference, this was the original python code (no PyQt):

***
import bluetooth

bt_addr = '98:D3:C1:FD:2C:46'
port = 1
sock = bluetooth.BluetoothSocket(bluetooth.RFCOMM)
sock.connect((bt_addr,port))
sock.send('A'.encode())
data = sock.recv(1024)
if data:
    print(data.decode())

****

and the fixed code using PyQt5:

****

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(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()
    sys.exit(app.exec_())

if __name__ == '__main__':
        main()

******

Thanks,

Jason
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://www.riverbankcomputing.com/pipermail/pyqt/attachments/20200418/008dc233/attachment.htm>


More information about the PyQt mailing list