Saturday, December 19, 2020

Python (on Raspberry Pi) Bluetooth communicate with ESP32 SerialToSerialBT, using pybluez

It's a simple Python example using pybluez extension module, run on Raspberry Pi 4/Raspberry Pi OS, to communicate with ESP32 SerialToSerialBT example.

pybluez (or https://github.com/pybluez/pybluez)is a Python extension module allowing access to system Bluetooth resources.

Install pybluez for Python3, enter the command in Terminal:

$ sudo pip3 install pybluez

Copy and modify pybluez/examples/simple/rfcomm-client.py in Raspberry Pi Thonny.

It's my modified version, pyBTSimpleClient.py

from bluetooth import *

def input_and_send():
    print("\nType something\n")
    while True:
        data = input()
        if len(data) == 0: break
        sock.send(data)
        sock.send("\n")
        
def rx_and_echo():
    sock.send("\nsend anything\n")
    while True:
        data = sock.recv(buf_size)
        if data:
            print(data)
            sock.send(data)
            
#MAC address of ESP32
addr = "24:0A:C4:E8:0F:9A"
#uuid = "94f39d29-7d6d-437d-973b-fba39e49d4ee"
#service_matches = find_service( uuid = uuid, address = addr )
service_matches = find_service( address = addr )

buf_size = 1024;

if len(service_matches) == 0:
    print("couldn't find the SampleServer service =(")
    sys.exit(0)

for s in range(len(service_matches)):
    print("\nservice_matches: [" + str(s) + "]:")
    print(service_matches[s])
    
first_match = service_matches[0]
port = first_match["port"]
name = first_match["name"]
host = first_match["host"]

port=1
print("connecting to \"%s\" on %s, port %s" % (name, host, port))

# Create the client socket
sock=BluetoothSocket(RFCOMM)
sock.connect((host, port))

print("connected")

#input_and_send()
rx_and_echo()

sock.close()
print("\n--- bye ---\n")


How it run on Raspberry Pi 4/Raspberry Pi OS, communicate with ESP32 (ESP32-DevKitC V4) SerialToSerialBT example. The code in ESP32 side is in my another blog Arduino-er: ESP32 Bluetooth serial example.
 

Next:


ImportError: libbluetooth.so.3


If you reported with error of:
ImportError: libbluetooth.so.3: cannot open shared object file: No such file or directory

Install required library by entering the command in Terminal:
$ sudo apt install bluetooth bluez libbluetooth-dev


No comments: