-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPyUDPReceive.py
More file actions
67 lines (48 loc) · 1.62 KB
/
Copy pathPyUDPReceive.py
File metadata and controls
67 lines (48 loc) · 1.62 KB
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
import socket
import select
import struct
import time
class UDPController:
# Listens on a UDP port for gamepad data, and provides the most recently recieved data.
def __init__(self, port = 5005):
self.updPort = port
self.reset()
self.sock = socket.socket(socket.AF_INET, # Internet
socket.SOCK_DGRAM) # UDP
self.sock.bind(('', self.updPort))
self.sock.setblocking(0)
def reset(self):
self.y = 0
self.x = 0
self.num = 0
self.lastPacket = time.time()
def _checkTimeout(self):
dt = time.time() - self.lastPacket
if dt > 2:
self.reset()
return True
return False
def _parsePacket(self, data):
self.num += 1
try:
joy_data = struct.unpack("ff", data)
self.x = joy_data[0]
self.y = joy_data[1]
self.lastPacket = time.time()
except:
print "Data error encountered."
def read(self):
ready = select.select([self.sock], [], [], 0)
if not ready[0]:
return self._checkTimeout()
data, addr = self.sock.recvfrom(1024) # buffer size is 1024 bytes
self._parsePacket(data)
return True
# -------------------------------------------------------------------------------
# Simple test for running from the command line
#
if __name__ == '__main__':
controller = UDPController()
while True:
if controller.read():
print "Controller packet {0} - ({1}, {2})".format( controller.num, controller.x, controller.y)