比如说有一个泵,我想控制他的转速,在一个界面上输入一个大小比如1000转每分钟,然后对应的后台就自动控制泵到达了这个转速。一直很好奇这是怎么实现的,当然我想了一个方法具体的步骤如下
1、用request把我要输入的值传递到后台,这里用Python实现一下
import requests
import json
url = 'http://192.168.150.1:8081/put'
pre = 136.
requests.get(url, data=json.dumps({'data': pre}))
2.后台我用一个队列来实现两个进程之间的数据贡献,代码如下
from multiprocessing import Queue
from fastapi import FastAPI, Query, Request
import uvicorn
from pydantic import BaseModel
app = FastAPI()
queue = Queue(3)
class data(BaseModel):
data: float
@app.get("/put")
def index(data: data):
queue.put(data.data) # 把需要控制的放进去
return {"state": "输入控制变量"}
@app.get("/get")
def index():
if queue.qsize():
data = queue.get()
print(data)
else:
data = 0
return {"Hello": f'{str(data)}'}
if __name__ == '__main__':
uvicorn.run(app="waite:app", log_level="info", host="0.0.0.0", port=8081, workers=1)
上面的代码不仅写了我把数据传入队列的路由,还把我获取数据的路由也写在了下面
3.然后就是pid了,这里我一泵为例,后台不停的获取数据,如果数据不为0,那么我就更新pid控制的参数,让pid自动去计算输出量
import requests
import json
import time as t
url = 'http://192.168.150.1:8081/get'
from pid import *
dt = 0.01
time = 0
tinm_l = []
output_l = []
baoshijie = car() # 生产一辆车
pid_controller = PIDController(0.45, 0.02, 0.001) # 一个pid控制器 1speed_limit = 150 # 设定车速限制
# --------------------测试--------------------------------------------------------
# while time < 1:
# try:
# data = requests.get(url)
# _ = float(json.loads(data.text)['Hello'])
# t.sleep(0.01)
# if _ != 0:
# speed_limit = _
# except Exception as e:
# print(e)
# tinm_l.append(time)
# output_l.append(baoshijie.speed)
# error = speed_limit - baoshijie.speed
# manu = pid_controller.calculate_output(error, dt)
# baoshijie.run(manu)
# # print(baoshijie.speed)
# time += dt
# plt.plot(tinm_l, output_l)
# plt.show()
# --------------------运行------------------------------------------------
while True:
try:
data = requests.get(url)
_ = float(json.loads(data.text)['Hello'])
t.sleep(0.01)
if _ != 0:
speed_limit = _
except Exception as e:
print(e)
output_l.append(baoshijie.speed)
error = speed_limit - baoshijie.speed
manu = pid_controller.calculate_output(error, dt)
baoshijie.run(manu)
print(baoshijie.speed)
这样就实现了上面的过程,但我不知道真实的生产环境是怎么样去做的,具体的运行效果如图
整体的运行过程如下:
真实环境中的还请各位大神指导指导