How to send messages from Pure Data to Python?
Asked Answered
T

1

5

I am trying to send messages from Pure Data to Python (to display on an SSD1306 OLED). Someone suggested I use sockets. They also provided the following Python code:

import socket
s = socket.socket()
host = socket.gethostname()
port = 3000

s.connect((host, port))
mess = "hello"
Msg = mess + " ;"
s.send(message.encode('utf-8'))

In Pure Data, a [netreceive 3000] object and a print object are connected together.

This works, but I want to do the exact opposite. Send data from Pure Data to Python using sockets. I found some tutorials but they all talked about Python to Python message receiving and sending. How can I implement Pd in that?

Tampere answered 18/4, 2020 at 6:56 Comment(2)
Isn't it just the case of using [netsend] in Pd? write.flossmanuals.net/pure-data/send-and-receiveStanford
Yeah, I tried to use [netsend] in pd, but I don't know how to receive the messages in python... I tried s.recv but still it did not work. I tried the [connect localhost 3000] object in pd, but no luck.Tampere
S
7

You can use Python's socket library to connect to a Pd patch that sends information through [netsend]. Here is a working minimal example. In Pd, create a simple patch that connects a [netsend] to a port on your localhost network:

enter image description here

Create and save a listener script in Python (adapted from here). The script below uses Python 3.6:

import socket
import sys

sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_address = ('localhost', 13001)
print(f'starting up on {server_address[0]} port {server_address[1]}')
sock.bind(server_address)
sock.listen(1)

while True:
    print('waiting for a connection')
    connection, client_address = sock.accept()
    try:
        print('client connected:', client_address)
        while True:
            data = connection.recv(16)
            data = data.decode("utf-8")
            data = data.replace('\n', '').replace('\t','').replace('\r','').replace(';','')
            print(f'received {data}')
            if not data:
                break
    finally:
        connection.close()

Run this script, then run Pd's patch. Dragging that numberbox will send values to Python. In this example above, all received values are just printed with their labels:

enter image description here

You can then adapt these to your needs.

Stanford answered 18/4, 2020 at 15:53 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.