Episode 4: Receiving UDP

Receive trigger codes from another program over UDP with a UDPReceiver, and place them beside the signal.

Episode 3 sent samples out. The way in is narrower, and on purpose: a UDPReceiver takes trigger codes, one number per datagram, from a stimulus program or any other process that can open a socket. The codes land on the sample grid beside the signal, which is what a paradigm needs.

The stimulus program

The other program is a thread in this file, and nothing in it imports gpype: a socket sends a number as text, 1 and 2 in turn, once a second. The receiver’s default port, 1000, needs root on macOS and Linux, so pick one from 1024 to 49151 and point both ends at it. In a real session this is somebody else’s process, often on another machine; delete the thread and keep the rest.

14# The default port, 1000, needs root on macOS and Linux: use one from
15# 1024 to 49151, and point the sender at the same one
16PORT = 5005
17
18
19def stimulus_program(stop: threading.Event) -> None:
20    """Send the codes 1 and 2 in turn, one a second, as text."""
21    sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
22    code = 1
23    while not stop.wait(1.0):
24        sock.sendto(str(code).encode(), ("127.0.0.1", PORT))
25        code = 3 - code
26    sock.close()
The receiver

A UDPReceiver listens on ip and port. Each datagram’s number becomes one sample carrying that value on a trigger channel, followed by a 0 ten milliseconds later, so a code is a short pulse rather than a level that stays on. A payload that is not a number is reported in the log and dropped. The receiver sets no rate of its own: its samples are placed onto the sampled source’s grid, the Generator’s here.

34    source = gp.Generator(sampling_rate=250, channel_count=8,
35                          signal_frequency=10, signal_amplitude=10,
36                          noise_amplitude=10)
37
38    # Each datagram's number becomes one sample on a trigger channel,
39    # followed by a 0 ten milliseconds later
40    receiver = gp.UDPReceiver(ip="127.0.0.1", port=PORT)
Merge and show

A Router puts the generator’s eight channels first and the trigger after them, so the codes land on channel 8, as the key codes did in Season 3. Two markers watch that channel for a 1 and a 2, and the channel itself is hidden.

42    # The generator's 8 channels, then the trigger: codes on channel 8
43    router = gp.Router(input_channels=[gp.Router.ALL, gp.Router.ALL])
44
45    mk = gp.TimeSeriesScope.Markers
46    markers = [mk(color="r", label="one", channel=8, value=1),
47               mk(color="g", label="two", channel=8, value=2)]
48    scope = gp.TimeSeriesScope(amplitude_limit=30, time_window=10,
49                               markers=markers, hidden_channels=[8])
50
51    p.connect(source, router["in1"])
52    p.connect(receiver, router["in2"])
53    p.connect(router, scope)
54    app.add_widget(scope)
Start both

The thread starts before the pipeline and is told to stop after the window closes. A datagram sent before the receiver listens is lost, which costs nothing here: the next one comes a second later.

56    stop = threading.Event()
57    threading.Thread(target=stimulus_program, args=(stop,),
58                     daemon=True).start()
59
60    p.start()
61    app.run()
62    p.stop()
63    p.close()
64    stop.set()
Result

Run the script. A marker appears every second, red and green in turn, drawn on the sample the code arrived on.

Eight channels with a red and a green marker alternating once a second

Figure 33: Codes from the socket, placed beside the signal.

When nothing arrives

A port the receiver cannot bind, because another program holds it, the system reserves it, or it needs root, is reported in the log as an error naming the likely cause, and the pipeline runs on without triggers. A datagram sent to a port nobody listens on vanishes without a word, so read the log before suspecting the sender. Season 5’s ParadigmPresenter receives its codes the same way, and is itself a UDP receiver on the same default address.

Summary

In this episode, you learned how to:

  • receive trigger codes over UDP with a UDPReceiver

  • send them from a program that is not g.Pype, with a plain socket

  • merge them onto the signal’s grid and mark them in a scope

Proceed to Episode 5, where one recording is written in four file formats at once, and read back from each.

Nodes in this episode: Generator, UDPReceiver, Router, TimeSeriesScope

File s4e4_receiving_udp.py – View file on GitHub

 1"""Season 4, Episode 4: trigger codes received over UDP, beside the signal.
 2
 3The stimulus program is the thread below, and nothing in it imports
 4gpype: a plain socket sending a number as text. In a real session it
 5is somebody else's process, often on another machine; delete the
 6thread and keep the rest.
 7"""
 8
 9import socket
10import threading
11
12import gpype as gp
13
14# The default port, 1000, needs root on macOS and Linux: use one from
15# 1024 to 49151, and point the sender at the same one
16PORT = 5005
17
18
19def stimulus_program(stop: threading.Event) -> None:
20    """Send the codes 1 and 2 in turn, one a second, as text."""
21    sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
22    code = 1
23    while not stop.wait(1.0):
24        sock.sendto(str(code).encode(), ("127.0.0.1", PORT))
25        code = 3 - code
26    sock.close()
27
28
29if __name__ == "__main__":
30
31    app = gp.MainApp()
32    p = gp.Pipeline()
33
34    source = gp.Generator(sampling_rate=250, channel_count=8,
35                          signal_frequency=10, signal_amplitude=10,
36                          noise_amplitude=10)
37
38    # Each datagram's number becomes one sample on a trigger channel,
39    # followed by a 0 ten milliseconds later
40    receiver = gp.UDPReceiver(ip="127.0.0.1", port=PORT)
41
42    # The generator's 8 channels, then the trigger: codes on channel 8
43    router = gp.Router(input_channels=[gp.Router.ALL, gp.Router.ALL])
44
45    mk = gp.TimeSeriesScope.Markers
46    markers = [mk(color="r", label="one", channel=8, value=1),
47               mk(color="g", label="two", channel=8, value=2)]
48    scope = gp.TimeSeriesScope(amplitude_limit=30, time_window=10,
49                               markers=markers, hidden_channels=[8])
50
51    p.connect(source, router["in1"])
52    p.connect(receiver, router["in2"])
53    p.connect(router, scope)
54    app.add_widget(scope)
55
56    stop = threading.Event()
57    threading.Thread(target=stimulus_program, args=(stop,),
58                     daemon=True).start()
59
60    p.start()
61    app.run()
62    p.stop()
63    p.close()
64    stop.set()