-
Notifications
You must be signed in to change notification settings - Fork 0
/
cobus.py
53 lines (45 loc) · 1.33 KB
/
cobus.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
# cobus.py
#
# Coroutine-based dataflow processing
from socket import *
from coroutine import coroutine
# Produce a stream of messages sent to UDP socket
def produce_messages(sock,maxsize,target):
while True:
msg, addr = sock.recvfrom(maxsize)
target.send(msg)
# Convert a sequence of byte messages to string
@coroutine
def decode_messages(encoding, target):
while True:
msg = yield
target.send(msg.decode(encoding))
# Split a sequence of lines into rows
@coroutine
def splitter(sep, target):
while True:
line = yield
target.send(line.split(sep))
# Turn a sequence of rows into dictionaries
@coroutine
def make_dicts(keys,target):
while True:
row = yield
target.send(dict(zip(keys,row)))
# Printer
@coroutine
def printer():
while True:
item = yield
print(item)
# This requires the bus simulator in Data/bussim.py to be running
if __name__ == '__main__':
sock = socket(AF_INET, SOCK_DGRAM)
# Send the handshake
sock.sendto(b"",("localhost",31337))
# Stack a collection of coroutines together into a pipeline
produce_messages(sock, 8192,
decode_messages('latin-1',
splitter(',',
make_dicts(['sequence','time','id','run','route','lat','lon'],
printer()))))