-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathPyEddiePlus.py
More file actions
331 lines (254 loc) · 10.5 KB
/
PyEddiePlus.py
File metadata and controls
331 lines (254 loc) · 10.5 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
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
'''
To remote control Eddie you must gain control with a "bind" process that involves:
Sending "DISCOVER" to 255.255.255.255 on port 4240
- All Eddie's on the network will respond with "DISCOVER: [unique name]".
Using the IP/name from the response send "BIND" to [ip address] on port 4240
- Eddie will respond with "BIND: OK".
Now you can send command packets (currently listed in main.c) to UDP port 4242.
EddieBalance listens for data on two ports:
- One [4240] for gaining control and the other [4242] for sending commands.
- And Eddie returns data to the last IP received on the response port.
/* Incoming UDP Command Packet handler:
*
* DRIVE[value] = + is Forwards, - is Reverse, 0.0 is IDLE
* TURN[value] = + is Right, - is Left, 0.0 is STRAIGHT
*
* SETPIDS = Changes all PIDs for speed and pitch controllers
* GETPIDS = Returns all PIDs for speed and pitch controllers via UDP
*
* PIDP[P,I,D][value] = adjust pitch PIDs
* SPID[P,I,D][value] = adjust speed PIDs
*
* KALQA[value] = adjust Kalman Q Angle
* KALQB[value] = adjust Kalman Q Bias
* KALR[value] = adjust Kalman R Measure
*
* STOPUDP = Will stop Eddie from sending UDP to current recipient
*
* STREAM[0,1] = Enable/Disable Live Data Stream
*
*/
'''
import socket
#import ctypes
import sys
import numpy as np
import re
class EddiePlus:
# Basic class to control an instance of a single EddiePlus
def __init__(self,Name):
self.Name = Name
self.host_any = ""
self.EddieBroadcastAddr = ('192.168.1.255',4240) # For Linksys E1200 --> You'rs may be different
self.EddieResponseAddr = (self.host_any, 4243)
self.sock = socket.socket(socket.AF_INET,socket.SOCK_DGRAM) # UDP
self.sock.settimeout(2.0)
self.GetStreamingData = False
# Set up the Response port
try:
self.sock.bind(self.EddieResponseAddr)
print 'Socket bound successfully '
except socket.error , msg:
print 'Bind failed. Error : ' + str(msg)
sys.exit() # bail
#self.UDPTimer = RepeatedTimer(1, self.GetPIDS())
def FindEddie(self):
# Send the 'DISCOVER' message to the broadcast address and the print a list of the responses
ByteCount = self.sock.sendto("DISCOVER", self.EddieBroadcastAddr)
#print "Send Byte Count: {0}".format(ByteCount)
# Try to recieve DISCOVER return message
# This only works for a single Eddie, but I've only got 1 on the network to test with. :(
try:
data, addr = self.sock.recvfrom(1024) # buffer size is 1024 bytes
print "received message:", data
if ("DISCOVER" in data): # If the return string contains "DISCOVER", we're good.
self.SetIPAddress(addr[0])
print "An Eddie was found at: {0}".format(self.IPAddress)
print "IP Address has been set internally"
else:
print "Discover failed for some reason."
except socket.timeout:
print "DISCOVER timed out."
def SetIPAddress(self,IPAddress):
# Set the IP Address for this Eddie (either based on the 'Find' procedure above or from your DHCP server.
self.IPAddress = IPAddress
self.EddieControlAddr = (IPAddress, 4240)
self.EddieCommandAddr = (IPAddress, 4242)
def InitializeEddie(self):
# If an Eddie responds, then there is a robot on the other side, and
# commands can be sent.
print "Looking for Eddie on: {0}".format(self.EddieControlAddr)
# Set up the receive port
try:
# Send "BIND" to the control UDP address to enable commands
ByteCount = self.sock.sendto("BIND", self.EddieControlAddr)
#print "Send Byte Count: {0}".format(ByteCount)
# Try to recieve BIND return message
try:
data, addr = self.sock.recvfrom(1024) # buffer size is 1024 bytes
print "received message:", data
if ("OK" in data): # If the return string contains "OK", we're good.
return 1
else:
print "Eddie was found, but he's unavailable for some reason."
except socket.timeout:
print "Oops. Timed out. Maybe nobody's home?"
# Eddie is here, looks like we're good to go.
return 1
except:
# Hmmmm. Something didn't work.
self.sock.close()
return 0
def Drive(self,Speed):
# Send the command to drive, along with the speed integer.
Speed = int(Speed)
if abs(Speed) > 15:
print "Whoa there sparky! Slow down"
return 0
cmd = "DRIVE{0}".format(int(Speed))
#print self.Name + ": " + cmd
ByteCount = self.sock.sendto(cmd, self.EddieCommandAddr)
return ByteCount
def Turn(self,TurnSpeed):
# Send the command to drive, along with the speed integer.
TurnSpeed = int(TurnSpeed)
if abs(TurnSpeed) > 15:
print "Seriously, do I look like a Corvette to you?"
return 0
cmd = "TURN{0}".format(int(TurnSpeed))
#print self.Name + ": " + cmd
ByteCount = self.sock.sendto(cmd, self.EddieCommandAddr)
return ByteCount
def Disconnect(self):
# Make sure that Eddie is stopped before we go.
self.Drive(0)
self.Turn(0)
self.StreamControl(False) # Shut down streaming data
# We're done for now.
self.sock.close()
def GetPIDS(self):
# GETPIDS = Returns all PIDs for speed and pitch controllers via UDP
ByteCount = self.sock.sendto("GETPIDS", self.EddieCommandAddr)
# Should return a string like:
# " CURRENTPIDS:6.500,600.000,30.000,0.020,800.000,340.000 "
try:
data, addr = self.sock.recvfrom(1024) # buffer size is 1024 bytes
print "received message:", data
except socket.timeout:
print "Oops. Timed out. Maybe nobody's home?"
def StreamControl(self,StreamOnOff):
# GETPIDS = Returns all PIDs for speed and pitch controllers via UDP
if StreamOnOff and self.GetStreamingData:
print "Already streaming data"
return
if StreamOnOff:
ByteCount = self.sock.sendto("STREAM1", self.EddieCommandAddr)
self.GetStreamingData = True
#self.UDPTimer.start()
print "DATA STREAM: On"
else:
ByteCount = self.sock.sendto("STREAM0", self.EddieCommandAddr)
self.GetStreamingData = False
#self.UDPTimer.stop()
print "DATA STREAM: Off"
# Should cause Eddie to start sending a string like:
# " "PIDout: %0.2f,%0.2f\tcompPitch: %6.2f kalPitch: %6.2f\tPe: %0.3f\tIe: %0.3f\tDe: %0.3f\tPe: %0.3f\tIe: %0.3f\tDe: %0.3f\r\n" "
def GetStreamData(self,DataPoints):
'''
speedPIDoutput = np.zeros(DataPoints)
pitchPIDoutput = np.zeros(DataPoints)
filteredPitch = np.zeros(DataPoints)
kalmanAngle = np.zeros(DataPoints)
pitchPIDError = np.zeros(DataPoints)
pitchPIDAccumulatedError = np.zeros(DataPoints)
pitchPIDDifferentialError = np.zeros(DataPoints)
speedPIDError = np.zeros(DataPoints)
speedPIDAccumulatedError = np.zeros(DataPoints)
speedPIDDifferentialError = np.zeros(DataPoints)
'''
DataValues = np.zeros((DataPoints,10))
ThisRow = 0
for ii in range(DataPoints):
try:
data, addr = self.sock.recvfrom(1024) # buffer size is 1024 bytes
#print data
values = re.findall("[-+]?\d+[\.]?\d*", data) # Pull the data out of the formatted string
#print "length is {0}".format(len(values))
if len(values) != 10:
print "Incomplete message"
else:
DataValues[ThisRow] = values
#print values
ThisRow += 1
#for term in data.split('\t'):
# values = term.split(':')
# #print "{0} = {1}".format(values[0],float(values[1]))
#print "received message:", data.split("\t")
except socket.timeout:
print "Oops. Timed out. Maybe nobody's home?"
sys.stdout.flush()
return DataValues
def SendCommand(self):
# Seems like there ought to be a use for a 'generic' command, but I'm
# not sure what it is.
pass
def __exit__(self, type, value, traceback):
# Close the UDP Port
self.StreamControl(False) # Shut down streaming data
self.sock.close()
from threading import Timer
class RepeatedTimer(object):
def __init__(self, interval, function, *args, **kwargs):
self._timer = None
self.interval = interval
self.function = function
self.args = args
self.kwargs = kwargs
self.is_running = False
#self.start() # Don't start the timer by default.
def _run(self):
self.is_running = False
self.start()
self.function(*self.args, **self.kwargs)
def start(self):
if not self.is_running:
self._timer = Timer(self.interval, self._run)
self._timer.start()
self.is_running = True
def stop(self):
self._timer.cancel()
self.is_running = False
# Usage:
#
#
#
if __name__ == "Not Really":
from time import sleep
def hello(name):
print "Hello %s!" % name
print "starting..."
rt = RepeatedTimer(1, hello, "World") # it auto-starts, no need of rt.start()
try:
sleep(5) # your long-running job goes here...
finally:
rt.stop() # better in a try/finally block to make sure the program ends!
#
#
#
#
#
if __name__ == "__main__":
import time # for the 'sleep' delay timer
# Create an instance of an EddiePlus
MyEddie = EddiePlus("Edward","192.168.1.109")
MyEddie.GetPIDS()
time.sleep(3)
MyEddie.Turn(4)
time.sleep(3)
MyEddie.Drive(6)
time.sleep(2)
MyEddie.Turn(-4)
time.sleep(3)
MyEddie.Drive(-3)
time.sleep(3)
MyEddie.Disconnect()