我正在尝试为车道创建一个典型的传感器激活的灯。该单元将是连接到PIR传感器的Arduino(Wemos),该传感器将与充当中心“控制点”的树莓派进行通信。它运行良好,但是我找不到控制光延迟的方法。我希望能够通过rPi做到这一点。
如果检测到运动,则Arduino发送一条消息,如果外面很暗,则rPi告诉Arduino打开灯。
现在我还希望rPi根据上一次移动来确定“延迟”,例如打开灯30秒钟,如果检测到进一步的移动,则计时器归零。
我当前的代码(仅限rPi端):
import paho.mqtt.client as mqtt
import arrow
from astral import Astral
inTopic = "wemos/status"
outTopic = "wemos/cmds"
Astral().solar_depression = 'civil'
city_name = 'Copenhagen'
city = Astral()[city_name]
def day() -> bool:
now = arrow.now('Europe/Copenhagen')
sun = city.sun(date=now, local=True)
return (now > sun['dawn'] and now < sun['dusk'])
def on_connect(client, userdata, flags, rc):
print(f"Connected with result code {str(rc)}")
client.subscribe(inTopic)
def on_message(client, userdata, msg):
print(f'{msg.topic}: {str(msg.payload)}')
if msg.topic == inTopic and msg.payload == b'Motion detected':
if not day():
client.publish(outTopic, payload="lightOn")
elif msg.topic == inTopic and msg.payload == b'No motion detected':
client.publish(outTopic, payload="lightOff")
client = mqtt.Client()
client.on_connect = on_connect
client.on_message = on_message
client.connect("192.168.0.14", 1883, 60)
client.loop_forever()
如果外面很暗,这将打开灯,但是当Arduino返回“未检测到运动”时,它将关闭灯。
我想在循环中注册消息,例如(非常伪科迪):
on_message:
if message == 'Motion detected':
client.publish(outTopic, payload="lightOn")
counter = 30
while True:
time.sleep(1)
counter -= 1
if counter == 0:
client.publish(outTopic, payload="lightOff")
break
if new_message = 'Motion detected':
counter = 30
但是,我在处理on_message
函数中的第一条消息时不知道如何处理新消息。我正在研究paho库的loop()
,loop_start()
和loop_stop()
方法,但似乎不太理解...
真诚的感谢您!