REFERENCE: https://stackoverflow.com/questions/18743962/python-send-udp-packet
This is my POC using python to send data and Processing listening for any packages. Note that Processing’s draw loop is blocked so you need to send data to see some action. To run this demo, run first your Processing sketch and then run the python script. I have provided some instructions to set up the virtual environment more for my record.
Processing sketch will only store 10 incoming messages in a StringArray object and it gets emptied when it reaches the limit.
Change the sleep time in python to increase the rate
Kf
import java.net.*;
import java.io.*;
import java.nio.charset.StandardCharsets;
final int TEXT_SIZE=16;
// Port we are receiving.
int port = 9100;
DatagramSocket ds;
// A byte array to read into (max size of 65536, could be smaller)
StringList lines;
void setup() {
size(400, 600);
lines = new StringList();
textSize(TEXT_SIZE);
try {
ds = new DatagramSocket(port);
}
catch (SocketException e) {
e.printStackTrace();
}
}
void draw() {
background(0);
checkForData();
printData();
}
void checkForData() {
byte[] buffer = new byte[65536];
DatagramPacket p = new DatagramPacket(buffer, buffer.length);
try {
ds.receive(p);
}
catch (IOException e) {
e.printStackTrace();
}
println("Received datagram with " + p.getLength() + " bytes." );
byte[] data = new byte[p.getLength()];
System.arraycopy(p.getData(), p.getOffset(), data, 0, p.getLength());
String mystr = new String(data, StandardCharsets.UTF_8);
if (lines.size()>10) { //Arbitrary value
lines.clear();
}
lines.append(mystr);
}
void printData() {
int size=lines.size();
for (int line=0; line<size; line++) {
text(lines.get(line), 50, line*(2*TEXT_SIZE)+50);
}
}
# ==================================================
# PYTHON3 INSTRUCTIONS:
#
# python3 -m pip install --upgrade pip
# pip install virtualenv
# which python3
# virtualenv -v venv --python=/usr/bin/python3
# source ./venv/bin/activate
# python -V
# echo "NOW let's send some data"
# python tx-session.py
import socket
import time
UDP_IP = "127.0.0.1"
UDP_PORT = 9100
def sender(args):
message = args
print(f"UDP target IP: {UDP_IP}")
print(f"UDP target port: {UDP_PORT}")
print(f"message: {message}")
sock = socket.socket(socket.AF_INET,socket.SOCK_DGRAM)
sock.sendto(bytes(message, "utf-8"), (UDP_IP, UDP_PORT))
def create_message(base_msg, number_of_stars):
"""
Appends a defined number of stars to the msg parameter and the actual star number
For example: 'Hello world***[3]'
"""
msg = base_msg
for x in range(ctr):
msg = msg + "*"
return f"{msg}[{ctr}]"
if __name__ == "__main__":
ctr = 0
while 1:
msg = create_message("Hellow World", ctr)
sender(msg)
time.sleep(0.5) # 500msec
ctr = ctr + 1
if ctr > 25: ## Arbitrary value
ctr = 0