-
Notifications
You must be signed in to change notification settings - Fork 1
/
peer.py
66 lines (51 loc) · 1.7 KB
/
peer.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
import stackless
from utils import Every
# Add local time with different offset and speed
# Or number of executed instructions
class Peer:
def __init__(self):
# Unique Peer ID
self.pid = None
# Packet sequence number
self.seq = 0
# 2D-position of peer
self.pos = [0,0]
# Stackless tasklet
self.task = stackless.tasklet(self.main)()
# Receive and Send packet buffer
self.recvarr = []
self.sendarr = []
# Statistics output interval
self.statint = Every(0.5)
# Flag input and output
self.flagin = []
self.flagout = []
# Peer state - only this should be accessed within update()
self.state = {}
# Main tasklet function
def main(self):
self.setup()
while True:
self.update()
# Setting up self.state
def setup(self):
pass
# Adds received packets to the receive buffer, discards them if they are not addressed
# to either the peer or the broadcast address (None)
def recv(self, msg):
if msg["target"] in [None, self.pid]:
self.recvarr.append(msg)
# Constructs a packet and puts it in the outgoing buffer
# By default, the packet is broadcast to all peers
def send(self, msg, target=None, seq=None):
if seq is None:
seq = self.seq
self.seq += 1
self.sendarr.append({"target":target, "source":self.pid, "seq":seq, "content":msg})
# This function is called as long as the peer is alive
def update(self):
pass
# Facilitates debug output for peer 0
def p(self, *args):
if self.pid == 0:
print(self.pid, str(args))