python speed_controller_client.py

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python speed_controller_client.py相关的知识,希望对你有一定的参考价值。

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()

以上是关于python speed_controller_client.py的主要内容,如果未能解决你的问题,请参考以下文章

Python代写,Python作业代写,代写Python,代做Python

Python开发

Python,python,python

Python 介绍

Python学习之认识python

python初识