-
Notifications
You must be signed in to change notification settings - Fork 0
/
net.py
348 lines (277 loc) · 11 KB
/
net.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
import socket
import displayprovider
DEFAULT_PORT = 10101
class DisplayServer:
"""
TCP-Server that listens on a specified port for
TCP-Connections. Every request sent to the server has to be one of the special
commands described later on or a string of 0s and 1s each specifying a dot to
be turned on or off respectively. For instance, to display the letter 'T'
on a 4x3 display of this form
::
1111
0110
0110
the following request must be sent to the server: 111101100110.
A simple command line client like nc can send this request to 'server'
listening on port 10101:
.. code-block:: bash
$ echo 111101100110 | nc server 10101
If the request contains the string 'SIZE' (ignoring case), the server
will respond with the dimensions of the display (width x height).
Lets start a server. Here we use a thread in order to be able to run the client
afterwards. In practice the server will run on a different platform and can be
started directly.
>>> import net
>>> import displayprovider
>>> import threading
>>> ds = net.DisplayServer(displayprovider.DisplayBase())
>>> th = threading.Thread(target=ds.start)
>>> th.setDaemon(True)
>>> th.start()
Starting server for dimension 4 x 3 on 0.0.0.0 at port 10101
Now we can start a client and send some pixels to the server.
>>> cl = net.RemoteDisplay(host="0.0.0.0")
Remote display will send data to 0.0.0.0 on port 10101
>>> cl.px(1, 1, True)
>>> cl.px(2, 3, True)
>>> cl.show()
Listening on 0.0.0.0 at port 10101
The output lines after show() are coming from the server.
"""
def __init__(self, display):
self.width = display.width
self.height = display.height
self.display = display
self.on_request = lambda: None
self.server_running = False
def start(self, host="0.0.0.0", port=DEFAULT_PORT):
print("Starting server for dimension", self.width, "x", self.height,
"on", host, "at port", port)
addr = (host, port)
self.server_running = True
with socket.socket() as sock:
sock.bind(addr)
print("Listening on", host, "at port", port)
sock.listen(10)
while self.server_running:
# waiting for connection
remote_sock, _cl = sock.accept()
buf = remote_sock.recv(self.width * self.height)
self.on_request()
#print("received", len(buf), "bytes")
try:
ans = self.handle_request(buf)
remote_sock.send(bytes(ans, "ascii"))
remote_sock.close()
except Exception as e:
print("ERROR", e)
def handle_request(self, payload):
s = str(payload, "ascii")
# answer with display dimension if desired
if s.lower().startswith("size"):
return "SIZE {w}x{h}".format(w=self.width, h=self.height)
# draw pixels
else:
return self._handle_display_update_request(payload)
def _handle_display_update_request(self, payload):
for y in range(self.height):
for x in range(self.width):
index = y * self.width + x
if index < len(payload):
val = chr(payload[index])
else:
val = "0"
if val in ("0", "1"):
self.display.px(x, y, val == "1")
self.display.show()
return "OK"
class RemoteDisplay(displayprovider.DisplayBase):
"Remote class to connect with a running DisplayServer instance."
def __init__(self, host="0.0.0.0", port=DEFAULT_PORT, width=28, height=13):
super().__init__(width, height)
print("Remote display will send data to", host, "on port", port)
self.host = host
self.port = port
self.buffer = []
for _x in range(width):
col = [False] * height
self.buffer.append(col)
def px(self, x, y, val):
self.buffer[x][y] = val
def show(self):
with socket.socket() as sock:
sock.connect((self.host, self.port))
payload = self._buffer_to_payload()
sock.sendall(payload)
def _buffer_to_payload(self):
payload = ""
for y in range(self.height):
for x in range(self.width):
payload += "1" if self.buffer[x][y] else "0"
return bytes(payload, "utf8")
def led(self, on_off):
pass
# TODO led support for remote display
class PixelflutServer(displayprovider.DisplayBase):
"""
PixeflutServer that conforms to the Pixelflut protocol outlined at
https://c3pixelflut.de/how.html
PX <x> <y> <rrggbb|aarrggbb> # set pixel at x,y with color rrggbb
PX <x> <y> # get pixel color info for pixel at x,y
SIZE # get size of the display
OFFSET <x> <y> # set offset for following commands
"""
def __init__(self, display):
self.width = display.width
self.height = display.height
self.display = display
self.offset_x = 0
self.offset_y = 0
self.server_running = False
def start(self, host="0.0.0.0", port=DEFAULT_PORT):
print("Starting Pixelflut server for dimension", self.width, "x", self.height,
"on", host, "at port", port)
addr = (host, port)
self.server_running = True
with socket.socket() as sock:
sock.bind(addr)
print("Listening on", host, "at port", port)
sock.listen(10)
while self.server_running:
remote_sock, _ = sock.accept()
with remote_sock:
while True:
buf = remote_sock.recv(1024)
if not buf:
break
try:
ans = self.handle_request(buf)
if ans:
remote_sock.send(bytes(ans, "ascii"))
except Exception as e:
print("ERROR", e)
def handle_request(self, payload):
"""
Handle incoming requests and execute commands based on the payload.
The payload is expected to be a string of ASCII-encoded commands
separated by newlines.
Each command is processed and appropriate actions are taken.
Commands:
- PX x y color: Set the pixel at (x, y) to the specified color.
- PX x y: Get the color of the pixel at (x, y).
- SIZE: Get the dimensions of the grid.
- OFFSET x y: Set the offset for the grid coordinates.
Args:
payload (bytes): The ASCII-encoded command string.
Returns:
str: The responses to the commands, joined by newlines.
"""
commands = str(payload, "ascii").strip().split('\n')
responses = []
for command in commands:
parts = command.strip().split()
if not parts:
continue
cmd = parts[0].upper()
if cmd == "PX":
if len(parts) == 4: # PX x y color
x = int(parts[1]) + self.offset_x
y = int(parts[2]) + self.offset_y
color = parts[3]
self.set_pixel(x, y, color)
elif len(parts) == 3: # PX x y
x = int(parts[1]) + self.offset_x
y = int(parts[2]) + self.offset_y
responses.append(self.get_pixel(x, y))
elif cmd == "SIZE":
responses.append(f"{self.width} {self.height}")
elif cmd == "OFFSET": # OFFSET x y
if len(parts) == 3:
self.offset_x = int(parts[1])
self.offset_y = int(parts[2])
return "\n".join(responses)
def set_pixel(self, x, y, color):
"""
Set the color of a specific pixel on the display.
Parameters:
x (int): The x-coordinate of the pixel.
y (int): The y-coordinate of the pixel.
color (str): The color to set the pixel to, represented as a hex string.
If the color is "000000", the pixel will be turned off.
Otherwise it will be turned on.
"""
if 0 <= x < self.width and 0 <= y < self.height:
self.display.px(x, y, color != "000000")
self.display.show()
def get_pixel(self, x, y):
"""
Get the color of a specific pixel on the display. Will return the color
of the pixel at the specified coordinates as a hex string.
"""
if 0 <= x < self.width and 0 <= y < self.height:
return "FFFFFF" if self.display.buffer[y][x] else "000000"
return "000000"
def test_networking():
import flipdotsim
import threading
import time
TEST_PORT = 1212
fdd = flipdotsim.FlipDotSim(width=15, height=15)
ds = DisplayServer(fdd)
th = threading.Thread(target=ds.start,
kwargs={'host':'127.0.0.1', 'port':TEST_PORT})
th.daemon = True
th.start()
time.sleep(0.2) # wait for server to start
remote_display = RemoteDisplay(host="127.0.0.1", port=TEST_PORT, width=15, height=15)
remote_display.px(1, 1, True)
remote_display.px(2, 1, True)
remote_display.show()
time.sleep(0.5)
import demos
demo = demos.RotatingPlasmaDemo(remote_display)
demo.fps = 30 # reduce fps for networking
demo.run(2)
ds.server_running = False
th.join(2)
fdd.close()
#exit()
def test_networking_pixelflut():
import flipdotsim
import threading
import time
TEST_PORT = 1234
fdd = flipdotsim.FlipDotSim(width=15, height=15)
ps = PixelflutServer(fdd)
th = threading.Thread(target=ps.start,
kwargs={'host':'127.0.0.1', 'port':TEST_PORT})
th.daemon = True
th.start()
time.sleep(0.2) # wait for server to start
remote_display = RemoteDisplay(host="127.0.0.1", port=TEST_PORT, width=15, height=15)
remote_display.px(1, 1, True)
remote_display.px(2, 1, True)
remote_display.show()
time.sleep(0.5)
import demos
demo = demos.RotatingPlasmaDemo(remote_display)
demo.fps = 30 # reduce fps for networking
demo.run(2)
ps.server_running = False
th.join(2)
fdd.close()
def main():
import displayprovider
import configuration
disp = displayprovider.get_display(
width=configuration.WIDTH, height=configuration.HEIGHT,
fallback=displayprovider.Fallback.SIMULATOR)
#ds = DisplayServer(disp)
#ds.start(host=configuration.display_server["host"],
# port=configuration.display_server["port"])
server = PixelflutServer(disp)
server.start(host=configuration.display_server["host"],
port=configuration.display_server["port"])
if __name__ == "__main__":
main()