import socket
import sys
import time
from math import floor
class Controller:
def __init__(self, sock, target_v):
self.s = sock
self.target_v = target_v
f, v = self.get_status()
self.last_v = v
self.lo = 0
while v < target_v:
self.lo = f
f = f * 2
v = self.throttle(f)
self.hi = f
print "init lo hi to", self.lo, self.hi
def throttle(self, f):
data = 'THROTTLE %.1f' % f
print "throttle:", data
self.s.sendall(data)
# !! if not block on recv, server has chance to receive both the thottle and status data in one recv() call
self.s.recv(100)
f, v = self.get_status()
while abs(v - self.last_v) < 0.00001:
time.sleep(0.1)
f, v = self.get_status()
self.last_v = v
return v
def get_status(self):
self.s.sendall('STATUS')
data = self.s.recv(100)
f, v = data.split()
return float(f), float(v)
def adjust_speed(self):
while True:
# need to floor the float at .1 precision, otherwise the +0.1 or -0.1 below may cross the boundary which causes deadloop
curr = (int(self.lo * 10) + int(self.hi * 10)) / 2 / 10.0
print "lo, hi, curr:", self.lo, self.hi, curr
v = self.throttle(curr)
if abs(v - self.target_v) < 0.00001:
print "DONE!!"
return
if v < self.target_v:
self.lo = curr + 0.1
else:
self.hi = curr - 0.1
addr = ('localhost', 5020)
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.connect(addr)
for target_v in [25, 150, 75, 100]:
print "============ adjust speed to", target_v
c = Controller(sock, target_v)
c.adjust_speed()