Episode 2: Sending LSL Streams
Publish a pipeline’s output as a Lab Streaming Layer stream with an LSLSender, and read it in a program that is not g.Pype.
The Lab Streaming Layer, LSL, is the common language of lab software: a stream published by one program can be picked up by any other on the network. This episode publishes the recorder’s output as one, and reads it with raw pylsl.
The same Generator, Keyboard and Router as Episode 1. There is no MainApp: a sender needs no window.
11 p = gp.Pipeline()
12
13 source = gp.Generator(sampling_rate=250, channel_count=8,
14 signal_frequency=10, signal_amplitude=10,
15 noise_amplitude=10)
16 keyboard = gp.Keyboard()
17 router = gp.Router(input_channels=[gp.Router.ALL, gp.Router.ALL])
An LSLSender publishes whatever reaches it as one stream of type EEG, named gpype_lsl unless you pass stream_name=.
19 # One stream of type EEG, named gpype_lsl unless you pass stream_name
20 sender = gp.LSLSender()
21
22 p.connect(source, router["in1"])
23 p.connect(keyboard, router["in2"])
24 p.connect(router, sender)
With no window to close, the script waits in input() until you press Enter, then stops the pipeline as every script does.
26 p.start()
27 input("Streaming. Press Enter to stop.")
28 p.stop()
29 p.close()
Every channel’s role goes into the stream description as its type, EEG for a signal and Markers for a trigger, so the key-code channel arrives as a trigger whether it is named or not. Names and units travel only when you give them: put a ChannelLabeler in front of the sender, as Season 2, Episode 9 does, when the receiver needs to know which channel is which. The arrival-stamp channel every live source adds is stripped before the sender, so the stream holds only the channels you see.
The second file is what somebody else’s application sees. Nothing in it imports gpype: resolve_byprop takes the first stream of type EEG on the network, and the stream’s description carries the channel count and the rate.
27 # The stream description carries the channel count and the rate
28 streams = resolve_byprop("type", "EEG")
29 self.inlet = StreamInlet(streams[0])
30 info = self.inlet.info()
31 self.channel_count = info.channel_count()
32 self.rate = info.nominal_srate()
33 self.max_points = int(TIME_WINDOW * self.rate)
Samples are pulled one at a time into a ring buffer on a timer, and plotted.
59 def update_plot(self):
60 """Drain the inlet into the ring buffer and redraw."""
61 while True:
62 sample, _ = self.inlet.pull_sample(timeout=0.0)
63 if sample is None:
64 break
65 self.buffer[self.index % self.max_points, :] = sample
66 self.index += 1
Start the sender in one terminal and the consumer in another. The consumer’s window shows nine lanes: the eight signals, and the key codes as spikes on the last. LSL prints log lines of its own, and on a machine with several network interfaces a run of Could not bind multicast responder warnings; they are normal, and nothing has failed.
In this episode, you learned how to:
publish a pipeline’s output as an LSL stream with an LSLSender
run a pipeline with no window, until Enter
know what a stream carries: roles always, names and units when you give them
Proceed to Episode 3, where the same output goes out as UDP packets, with nothing to find and nothing to negotiate.
Nodes in this episode: Generator, Keyboard, Router, LSLSender
File s4e2_sending_lsl.py – View file on GitHub
1"""Season 4, Episode 2: signal and key presses published as an LSL stream.
2
3Headless on purpose: the pipeline streams until you press Enter. Read
4it back with s4e2_foreign_consumer.py, or with any other LSL consumer.
5"""
6
7import gpype as gp
8
9if __name__ == "__main__":
10
11 p = gp.Pipeline()
12
13 source = gp.Generator(sampling_rate=250, channel_count=8,
14 signal_frequency=10, signal_amplitude=10,
15 noise_amplitude=10)
16 keyboard = gp.Keyboard()
17 router = gp.Router(input_channels=[gp.Router.ALL, gp.Router.ALL])
18
19 # One stream of type EEG, named gpype_lsl unless you pass stream_name
20 sender = gp.LSLSender()
21
22 p.connect(source, router["in1"])
23 p.connect(keyboard, router["in2"])
24 p.connect(router, sender)
25
26 p.start()
27 input("Streaming. Press Enter to stop.")
28 p.stop()
29 p.close()
File s4e2_foreign_consumer.py – View file on GitHub
1"""Season 4, Episode 2: a consumer that is not g.Pype reads the stream.
2
3Nothing here imports gpype: raw pylsl and pyqtgraph, which is what
4somebody else's application sees when it subscribes to a stream g.Pype
5publishes. Takes the first stream of type EEG it finds, and waits
6until one appears. Requires pylsl, pyqtgraph and PySide6.
7"""
8
9import sys
10
11import numpy as np
12import pyqtgraph as pg
13from pylsl import StreamInlet, resolve_byprop
14from pyqtgraph.Qt import QtCore, QtWidgets
15
16TIME_WINDOW = 10 # seconds shown
17AMPLITUDE_LIMIT = 50 # one lane spans twice this
18
19
20class LslScope(QtWidgets.QMainWindow):
21 """A time-series plot fed by an LSL inlet."""
22
23 def __init__(self):
24 super().__init__()
25 self.setWindowTitle("LSL consumer")
26
27 # The stream description carries the channel count and the rate
28 streams = resolve_byprop("type", "EEG")
29 self.inlet = StreamInlet(streams[0])
30 info = self.inlet.info()
31 self.channel_count = info.channel_count()
32 self.rate = info.nominal_srate()
33 self.max_points = int(TIME_WINDOW * self.rate)
34
35 plot = pg.PlotWidget()
36 self.setCentralWidget(plot)
37 self.item = plot.getPlotItem()
38 self.item.showGrid(x=True, y=True, alpha=0.3)
39 self.item.getViewBox().setMouseEnabled(x=False, y=False)
40 self.item.setLabels(left="Channels", bottom="Time (s)")
41 self.item.setYRange(0, self.channel_count)
42 self.item.setXRange(0, TIME_WINDOW)
43 self.item.getAxis("left").setTicks([[
44 (self.channel_count - i - 0.5, f"CH{i + 1}")
45 for i in range(self.channel_count)]])
46 self.curves = [self.item.plot(pen=pg.mkPen(width=1))
47 for _ in range(self.channel_count)]
48
49 # A ring buffer the size of the window
50 self.times = np.arange(self.max_points) / self.rate
51 self.buffer = np.zeros((self.max_points, self.channel_count))
52 self.index = 0
53
54 # Redraw on a timer, independent of the stream's rate
55 self.timer = QtCore.QTimer()
56 self.timer.timeout.connect(self.update_plot)
57 self.timer.start(40)
58
59 def update_plot(self):
60 """Drain the inlet into the ring buffer and redraw."""
61 while True:
62 sample, _ = self.inlet.pull_sample(timeout=0.0)
63 if sample is None:
64 break
65 self.buffer[self.index % self.max_points, :] = sample
66 self.index += 1
67 step = max(1, self.max_points // max(1, self.width()))
68 for i, curve in enumerate(self.curves):
69 lane = self.channel_count - i - 0.5
70 curve.setData(self.times[::step],
71 self.buffer[::step, i] / AMPLITUDE_LIMIT / 2 + lane)
72
73
74if __name__ == "__main__":
75 app = QtWidgets.QApplication(sys.argv)
76 window = LslScope()
77 window.resize(1000, 500)
78 window.show()
79 sys.exit(app.exec())