'Have Bluetooth socket reconnect (in Python) after BT switched off and on again
I connect a bluetooth device in a python (3.10) program like this:
import socket
serverMACAddress = '00:07:80:e0:a4:fc'
port = 1
size = 1024
s = socket.socket(socket.AF_BLUETOOTH, socket.SOCK_STREAM, socket.BTPROTO_RFCOMM)
s.connect((serverMACAddress,port))
In the main loop I have this:
try:
while 1: #main loop
data = s.recv(size)
if data:
data_received( data )
else:
try:
s.????
except:
print("no data")
except:
print("Closing socket")
s.close()
Everything works fine unless the bluetooth device is switched off and then switched on again. I am trying to solve how to have the bluetooth device re-connect with the logic in the try-statement (s.????) within the loop, but I am unable to come up with a solution.
I am a beginner in BT and Python, but this should be pretty straightforward, right? I must be missing something very obvious. Any suggestions out there?
Modified version based on the suggestion by ukBaz:
try:
while 1: #main loop
try:
data = s.recv(size)
except socket.error():
connected = False
s = socket.socket
while not connected:
#attempt to re-connect
try:
s.connect((serverMACAddress,port))
connected = True
except:
time.sleep(5)
if data:
data_received( data )
except:
print("Closing socket")
s.close()
After adding clientSocket.send:
while True: #main loop
# attempt to reconnect, otherwise sleep for 2 seconds
if not connected:
try:
# configure socket and connect to server
clientSocket = socket.socket(
socket.AF_BLUETOOTH, socket.SOCK_STREAM, socket.BTPROTO_RFCOMM
)
clientSocket.connect((serverMACAddress, port))
connected = True
print("Connection successful")
except socket.error:
print("No connection, retrying")
# time.sleep(2)
# attempt to send and receive, otherwise reset connection status
else:
data = clientSocket.recv(size)
if data:
data_received( data )
# Use send to check if scale is connected
try:
clientSocket.send(b"x")
except socket.error:
print("connection lost... reconnecting")
# set connection status
connected = False
Solution 1:[1]
Problem with response which was an array rather that a string.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Jasr |
