4
4
pymlgame - Controller
5
5
"""
6
6
7
+ from uuid import uuid4
7
8
import time
8
9
from datetime import datetime
9
10
import socket
@@ -19,8 +20,6 @@ class Controller(Thread):
19
20
A controller can be a game controller attached to the system or any other input that can trigger the controller
20
21
functions like a smartphone app.
21
22
"""
22
- _next_uid = 0
23
-
24
23
def __init__ (self , host = '0.0.0.0' , port = 1338 ):
25
24
"""
26
25
Creates a controller deamon
@@ -37,29 +36,25 @@ def _new_controller(self, addr, port):
37
36
"""
38
37
Get an uid for your controller.
39
38
"""
40
- #print(datetime.now(), '### new controller at', addr, ':', port)
41
39
for uid , controller in self .controllers .items ():
42
40
if controller [0 ] == addr :
43
- #print(datetime.now(), '### duplicate address. not adding this one.')
44
41
# duplicate address. sending the uid again
45
- # print(datetime.now(), '>>> /uid/{}'.format(uid) , addr, port)
42
+ print (' /uid/{} => {}:{} ' .format (uid , addr , port ) )
46
43
self .sock .sendto ('/uid/{}' .format (uid ).encode ('utf-8' ), (addr , port ))
47
44
return False
48
45
49
46
# get an uid and add the controller to the game
50
- uid = self ._next_uid
51
- self ._next_uid += 1
47
+ uid = str (uuid4 ())
52
48
self .controllers [uid ] = [addr , port , '00000000000000' , time .time ()]
53
49
54
50
# tell the controller about it
55
- # print(datetime.now(), '>>> /uid/{}'.format(uid) , addr, port)
51
+ print (' /uid/{} => {}:{} ' .format (uid , addr , port ) )
56
52
self .sock .sendto ('/uid/{}' .format (uid ).encode ('utf-8' ), (addr , port ))
57
53
58
54
# create event for pymlgame
59
55
e = Event (uid , E_NEWCTLR )
60
56
self .queue .put_nowait (e )
61
57
62
- #print(datetime.now(), '### controller added with uid', uid)
63
58
return uid
64
59
65
60
def _del_controller (self , uid ):
@@ -68,7 +63,6 @@ def _del_controller(self, uid):
68
63
"""
69
64
try :
70
65
self .controllers .pop (uid )
71
- #print(datetime.now(), '### controller', uid, 'deleted')
72
66
e = Event (uid , E_DISCONNECT )
73
67
self .queue .put_nowait (e )
74
68
except KeyError :
@@ -97,20 +91,19 @@ def _update_states(self, uid, states):
97
91
"""
98
92
#TODO: use try and catch all exceptions
99
93
# test if uid exists
100
- #print(datetime.now(), '### Checking states', states, 'for controller', uid)
101
94
if self .controllers [uid ]:
102
95
# test if states have correct lenght
103
96
if len (states ) == 14 :
104
97
old_states = self .controllers [uid ][2 ]
105
98
if old_states != states :
106
- #print(datetime.now(), '### checking old states', old_states, 'against new states', states)
107
99
for key in range (14 ):
108
100
if int (old_states [key ]) > int (states [key ]):
109
101
e = Event (uid , E_KEYUP , key )
110
102
self .queue .put_nowait (e )
111
103
elif int (old_states [key ]) < int (states [key ]):
112
104
e = Event (uid , E_KEYDOWN , key )
113
105
self .queue .put_nowait (e )
106
+ self .controllers [uid ][2 ] = states
114
107
self .controllers [uid ][3 ] = time .time ()
115
108
116
109
def _got_message (self , uid , text ):
@@ -135,16 +128,14 @@ def send(self, uid, event, payload):
135
128
addr = self .controllers [uid ][0 ]
136
129
port = self .controllers [uid ][1 ]
137
130
if event == E_MESSAGE :
138
- # print(datetime.now(), '>>> /message/{}'.format(payload) , addr, port)
131
+ print (' /message/{} => {}:{} ' .format (payload , addr , port ) )
139
132
return sock .sendto ('/message/{}' .format (payload ).encode ('utf-8' ), (addr , port ))
140
133
elif event == E_RUMBLE :
141
- # print(datetime.now(), '>>> /rumble/{}'.format(payload) , addr, port)
134
+ print (' /rumble/{} => {}:{} ' .format (payload , addr , port ) )
142
135
return sock .sendto ('/rumble/{}' .format (payload ).encode ('utf-8' ), (addr , port ))
143
136
else :
144
- #print(datetime.now(), '### Unknown event type.')
145
137
pass
146
138
else :
147
- #print(datetime.now(), '### This UID ({}) doesn\'t exist.'.format(uid))
148
139
pass
149
140
return False
150
141
@@ -156,15 +147,14 @@ def run(self):
156
147
data , sender = self .sock .recvfrom (1024 )
157
148
addr = sender [0 ]
158
149
msg = data .decode ('utf-8' )
159
- # print(datetime.now(), '<<<', msg)
150
+ print ('New msg: ' + msg )
160
151
if msg .startswith ('/controller/' ):
161
152
try :
162
153
uid = msg .split ('/' )[2 ]
163
154
if uid == 'new' :
164
155
port = int (msg .split ('/' )[3 ])
165
156
self ._new_controller (addr , port )
166
157
else :
167
- uid = int (uid )
168
158
cmd = msg .split ('/' )[3 ]
169
159
if cmd == 'ping' :
170
160
port = msg .split ('/' )[3 ]
@@ -176,17 +166,15 @@ def run(self):
176
166
self ._update_states (uid , states )
177
167
elif cmd == 'text' :
178
168
# /controller/<uid>/text/<text>
179
- text = msg [12 + len (str ( uid ) ) + 6 :]
169
+ text = msg [12 + len (uid ) + 6 :]
180
170
self ._got_message (uid , text )
181
171
except IndexError or KeyError :
182
- #print(datetime.now(), '### Error in coitus protocol.')
183
172
pass
184
173
else :
185
- #print(datetime.now(), '### This thing doesn\'t fit:', msg)
186
174
pass
187
175
188
176
# find unused controllers and delete them
189
177
ctlrs = self .controllers .items ()
190
178
for uid , state in ctlrs :
191
179
if state [3 ] < time .time () - 60 :
192
- self .controllers .pop (uid )
180
+ self .controllers .pop (uid )
0 commit comments