I have got a RPi 3 loaded with Raspbian GNU/Linux 8.0 (jessie) and I use
pyserial to send data over Bluetooth to an Android application. Pairing the Pi with the Android device works fine.
For my Android device to connect to the Pi, I need to run
sudo rfcomm watch hci0
sudo rfcomm listen hci0
otherwise the Android device is unable to connect (because there is no serial port abstraction available for the communication) and
/dev/rfcomm0 is never created.
rfcomm watch is runnning, the Android device is able to establish the connection and
/dev/rfcomm0 appears. I can start my python script to send data from the Pi to the Android device:
import serial from serial.serialutil import SerialException def initiate_ble_serial_port(): try: port_ble_tablet = serial.Serial("/dev/rfcomm0") print("Serial port for the Android device initialized: " + str(port_ble_tablet)) return port_ble_tablet except SerialException as e: print(e) return None port_ble_tablet = initiate_ble_serial_port() while True: # doing some unrelated stuff ble_msg = str(rcv_cnt/10) + ":::" if port_ble_tablet: port_ble_tablet.write(ble_msg.encode())
This works like a charm provided that the order between the different actions is as follow:
rfcomm watch >
Android connected >
However, if you change that order or if my Android disconnects for some reason (rebooting, restarting the application, out of range, etc.) and tries to reconnect to the Pi after some time, the communication is lost. That is, the
write instruction in the above script raises a
write failed: [Errno 5] Input/output error
/dev/rfcomm0 no longer exists, although the Android device says it is connected to the Pi. The same problem occurs both with
rfcomm watch and
Trying to reset the
Serial object in python (namely, calling
port_ble_tablet = initiate_ble_serial_port() again) does not help.
How do I ensure a smooth, robust (re)connection behaviour between my Android device and the RPi 3?