Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Communicate between a processing sketch and a python program?

I have a program written in processing (to process live audio) and a program written in python (to call gatttool to talk over bluetooth low energy to a peripheral). Is there a straightforward way to send values from processing to python? Should I create a serial connection and pass bytes that way?

like image 668
orangenarwhals Avatar asked Dec 14 '22 21:12

orangenarwhals


1 Answers

Keeping in mind that they're running on the same computer, it's best to use sockets to create a server on the Python side, and a client on the processing side, and send your data from the client to the server that way. The Python server will sit and wait for a connection from the Processing client, and make use of the data once it's received.

You can find examples and such all over the web, but here are the examples given by the Processing and Python docs (port in Processing example changed from 5204 to 50007 so you can copy-paste):

Processing client:

import processing.net.*; 
Client myClient;
     
void setup() { 
    size(200, 200); 
    /* Connect to the local machine at port 50007
     *  (or whichever port you choose to run the
     *  server on).
     * This example will not run if you haven't
     *  previously started a server on this port.
     */
    myClient = new Client(this, "127.0.0.1", 50007); 
} 
     
void draw() { 
    myClient.write("Paging Python!"); // send whatever you need to send here
} 

Python server:

# Echo server program
import socket

HOST = ''                 # Symbolic name meaning all available interfaces
PORT = 50007              # Arbitrary non-privileged port
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((HOST, PORT))
s.listen(1)
conn, addr = s.accept()
print('Connected by', addr)
while True:
    data = conn.recv(1024)
    if not data: break
    print(data) # Paging Python!
    # do whatever you need to do with the data
conn.close()
# optionally put a loop here so that you start 
# listening again after the connection closes
like image 177
Derek Redfern Avatar answered Mar 15 '23 17:03

Derek Redfern