I wrote a script in Python for serial communication between my M5Stack Stick C (like Arduino) and my Raspberry Pi. I can send "X","Y" or "Z" from the Raspberry Pi to the stick and it will reply back to the Pi with the G-Force value.
This Python code runs on the Pi:
import serial
import time
import threading
ser = serial.Serial('/dev/rfcomm5') #init serial port
input_line = []#init input char array
def process_data(_data):
#called every time a sream is terminated by \n
#and the command string is ready to use
command = convert(_data)
print(command)
def convert(s): #convert the char list in a string
new = "" #init string to append all chars from char array
for x in s: # traverse in the string
new += str(x)
return new # return string
def processIncomingByte(inByte):#adding incoming chars to input_line
global input_line# globalize the input_line
if(inByte == '\n'):#if \n is incoming, end the chararray and release process data method
process_data(input_line)
input_line = []#reset input_line for next incoming string
elif(inByte == '\r'):
pass
else:#put all incoming chars in input_line
input_line.append(inByte)
while True:
while(ser.in_waiting > 0):#while some data is waiting to read....
processIncomingByte(ser.read())#.... process bytes whit method
ser.write(b'X\n')
time.sleep(0.5)
However, for the script to work, I have to manually bind the M5Stack Stick-C to /dev/rfcomm5 with Blueman. It works via GUI or console.
But now I would like to connect the stick to rfcomm5 via Python. You can assume the MAC address is known, it will be specified in a config file later on. I started to investigate a bit, but the more I research the more confused I am. I read about sockets and server-client approaches using a separate script.
I tested this code:
from bluetooth import *
target_name = "M5-Stick-C"
target_address = None
nearby_devices = discover_devices()
for address in nearby_devices:
if (target_name == lookup_name( address )):
target_address = address
break
if (target_address is not None):
print ("found target bluetooth device with address ", target_address)
else:
print ("could not find target bluetooth device nearby")
And indeed it found the device. But do I really need to make a second script/process to connect to from my script?
Is the M5stack Stick-C the server and rfcomm the socket, or is this a wrong assumption? I've coded a lot, but never with sockets or server-client, which confuses me.
Basically the communication (server/client?) works.
I just need to connect the device I found in the second script via macadress to rfcomm5 (or whatever rfcomm).
Do I need a Bluetooth socket like in this example?