有没有一种方法可以在不停止主循环的情况下连续更改某个值



我想要一个改变房间灯光的程序。系统运行在一个我可以通过MQTT和REST访问的控制器上。我有一种方法可以改变强度,但它非常突然。因为我希望系统的其余部分在变化发生时继续运行(因为我有传感器运行其余的照明(,所以我不能只使用循环来稳步增加强度。我查看了Timers,但我无法让它们正常工作以满足我的需求。有办法做到这一点吗?

这是我的循环问题:

client.message_callback_add(path("zones",Office,"devices",Sensor1_Presence,"data","presence"), on_message_Presence_callback)
client.message_callback_add(path("zones",Office,"devices",Sensor2_Presence,"data","presence"), on_message_colorchange_callback)
#client.message_callback_add(path("zones","#"), on_message_callback)
startTimer()
WeatherTimer()
client.connect(MQTT_HOST, port=MQTT_PORT)
client.loop_forever()

我希望能够启动和停止功能(最好是使用bool(

我有一个改变功能,已经改变了特定的参数:

def change_parameter(URL, parameter_name ,parameter_value):
r = requests.put(
f"https://{MQTT_HOST}/rest/v1/{URL}",
headers=litecom_headers(),
verify=False,
json={f"{parameter_name}": parameter_value}
)
return r.status_code

有办法做我想做的事吗?提前感谢!

我假设您的桌面电脑上运行了控制灯光的python脚本?

如果是这样的话,您肯定至少有2个cpu核心可供使用,并且可以使用python的ProcessPoolExecutor并行运行参数更改函数。然后,您可以逐步更改参数,直到达到所需的值。为了获得平滑的效果,你只需要在步骤之间尝试步长和睡眠值,直到你对结果感到满意。

伪ish实现:

def change_param_smooth(URL, parameter_name, target_value, stepsize, duration):
current_value = 0 // get the current value from your device
while current_value < target_value:
current_value += step_size
# avoid overshooting
if current_value > target_value:
current_value = target_value
change_parameter(URL, parameter_name, current_value)
time.sleep(duration)

相关内容

最新更新