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

Jason Friedman write.to.jason at gmail.com
Fri Apr 17 07:55:09 BST 2020


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
10.15.4. When I run the below code, I get the error: 'unknown error', I'd
be happy to know what I am doing wrong, or a pointer to a python example (I
could not find any online). I have managed to get the scanning for
Bluetooth devices working using PyQt. My code is below:

**************
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()

**************

Thanks,

Jason
-- 
Jason Friedman, PhD
Senior Lecturer
Department of Physical Therapy
Tel Aviv University
email: write.to.jason at gmail.com
web: http://curiousjason.com
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://www.riverbankcomputing.com/pipermail/pyqt/attachments/20200417/53e130cc/attachment.htm>


More information about the PyQt mailing list