Tuesday, December 29, 2020

Raspberry Pi/Python as Bluetooth classic client, bi-direction communication with ESP32

Raspberry Pi/Python act as GUI Bluetooth classic client, using tkinter/pybluez:
Connect to bluetooth classic server with hard-coded MAC.
User enter text to sent on bottom Text Frame, send to server.
Display the data received from server on upper Text frame.

The server side, run on ESP32 (NodeMCU ESP-32S), with SPI ST7735 IPS screen. It echo back received data. ESP32 (Arduino framework) code: Arduino-er: ESP-32S as Bluetooth classic Server, bi-direction communication with Raspberry Pi/Python.

Python code, pySPPClient.py.

import sys
from tkinter import *
from bluetooth import *
from threading import Thread
import time

rqsStopBtHandler = False

buf_size = 255

def btHandler():
    global rqsStopBtHandler
    rqsStopBtHandler = False
    
    print("btHandler Started")
    
    #Set sock.settimeout(),
    #to prevent program blocked by sock.recv()
    #and cannot end btHandler
    sock.settimeout(1.0)
    while rqsStopBtHandler!=True:
        try:
            datarx = sock.recv(buf_size)
            datarxToStr = datarx.decode("utf-8")
            print(datarxToStr)
            textCenter.insert(INSERT, datarxToStr)
        except Exception:
            continue
        
    print("btHandler End")
    
def startBtHandler():
    btThread = Thread(target=btHandler)
    btThread.start()
    
def close_window():
    global rqsStopBtHandler
    rqsStopBtHandler = True
    sock.close()
    print("Socket closed")
    print("Window closed")
    root.destroy()

def cmdSend():
    stringSent = textBottom.get(1.0, END)
    print(stringSent)
    sock.send(stringSent)
    #sock.send("\n")
    print("- Sent")
    
#===============================================
#Prepare Bluetooth Classic
print("Python version: ")
print(sys.version)
print("tkinter version: ", TkVersion)
print("=============================")
print("Connect to ESP32 Bluetooth Classic SPP Server")
#addr = "24:0A:C4:E8:0F:9A"
addr = "3C:71:BF:0D:DD:6A"
print(addr)
service_matches = find_service( address = addr )

if len(service_matches) == 0:
    print("couldn't find the ESP32 Bluetooth Classic SPP 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")

#===============================================
#Prepare GUI
root = Tk()
root.configure(bg="darkgray") 
root.wm_title("SPP Client")
root.protocol("WM_DELETE_WINDOW", close_window)

rootFrame = Frame(root)
rootFrame.pack()

labelTitle = Label(root,
                   text="helloraspberrypi.blogspot.com",
                   font=("Helvetica", 18),
                   fg="White", bg="darkgray")
labelTitle.pack()

frameCenter = Frame(root, bg="lightgray")
frameCenter.pack()

textCenter= Text(frameCenter, width=26, height=10, font=("Helvetica", 18))
textCenter.pack(padx=10,pady=5)

frameBottom = Frame(root, bg="gray")
frameBottom.pack(expand=True, fill='both')

textBottom = Text(frameBottom, width=26, height=10, font=("Helvetica", 18))
textBottom.insert(INSERT, "Enter text here")
textBottom.pack(padx=10,pady=5)

buttonSend = Button(frameBottom, text="Send", command=cmdSend)
buttonSend.pack(padx=10,pady=5)

startBtHandler()

root.mainloop()

print("--- bye ---")

Related:

No comments: