2

I'm trying to create bidirectional comms over a bluetooth socket between 2 RPis. I need to run the main program on the master while waiting for the connection then have the ability to push a message from either device at any time and interrupt main thread on either when received. A message received will perform an action on the other RPi. E.g. switch on master will turn on LED on slave based on the message sent from master to slave and visa versa. I'm tackling this in small steps and currently working on waiting for the connection and at this point just use the connection for send/receive input.

I have my socket working in send / receive mode fine. I'm now trying to move into multi-processes to wait for the connection and this works however I lose the connection because from what I understand I can't access it outside of the process it was made. So I'm trying to work out next step and I'm thinking should I use threading, asynchronous or stick with processes.

Really appreciate any ideas you have to solve this challenge.

Here's the Master Pi's code. Slave connects fine. My server_program function is the basic send / receive handshake that is working fine when not in running the connection in a process. The error occurs at the line "data = conn.recv(1024).decode()" because 'conn' is not defined.

I've been playing around with multiprocessors manager and value but they don't seem to be able to handle the connection of the socket.

from multiprocessing import Pool
import socket

#----------- Processes -----------
def WaitSlaveConnection():
    print("Waiting for slave")
    hostMACAddress = 'XX:XX:XX:XX:XX:XX' # The MAC address of a Bluetooth adapter on the server.
    port = 3
    size = 1024
    server_socket = socket.socket(socket.AF_BLUETOOTH, socket.SOCK_STREAM, socket.BTPROTO_RFCOMM)
    server_socket.bind((hostMACAddress,port))
    server_socket.listen(1)

    conn, address = server_socket.accept()  # accept new connection
    print("Connection from: " + str(address))

    return "Connected"

#############################
###########  Main ###########
#############################

def server_program():

    while True:
        data = conn.recv(1024).decode()
        if not data:
            # if data is not received break
            break
        print("from connected user: " + str(data))
        data = input(' -> ')
        conn.send(data.encode())  # send data to the client

    conn.close()  # close the connection


if __name__ == '__main__':
    app_pool = Pool(processes=20)

    slave_conn = app_pool.apply_async(WaitSlaveConnection)

    while True:
        if slave_conn.get(timeout=None) == "Connected":
            print("Yes")

            server_program()

        else:
            print("Waiting for Slave")
JCBman
  • 21
  • 2

0 Answers0