Python 嵌套尝试使灯光变暗,然后最终将其关闭
我试着在一段时间不动后将灯调暗,然后在另一段时间后最终将其完全关闭。我面临的问题是,当它关闭时,它应该只有再次打开的选项,而不是从关闭状态随机变暗。代码如下:Python 嵌套尝试使灯光变暗,然后最终将其关闭,python,python-asyncio,Python,Python Asyncio,我试着在一段时间不动后将灯调暗,然后在另一段时间后最终将其完全关闭。我面临的问题是,当它关闭时,它应该只有再次打开的选项,而不是从关闭状态随机变暗。代码如下: async def main(self): while True: try: await asyncio.wait_for(self.movement_detected(), timeout=10) except asyncio.TimeoutError:
async def main(self):
while True:
try:
await asyncio.wait_for(self.movement_detected(), timeout=10)
except asyncio.TimeoutError:
state_off = {"state": "off"}
state_dim = {"brightness":50, "state": "ON"}
print('TIMEOUT...DIMMING ' + topic)
async with Client(self.broker) as client:
await client.publish(topic, orjson.dumps(state_dim))
try:
await asyncio.wait_for(self.movement_detected(), timeout=10)
except asyncio.TimeoutError:
print('TIMEOUT...TURNING OFF ' + topic)
async with Client(self.broker) as client:
await client.publish(topic, orjson.dumps(state_off))
当我运行它时,我得到:
ON
ON
ON
TIMEOUT...DIMMING /light
TIMEOUT...TURNING OFF /light
TIMEOUT...DIMMING /light
TIMEOUT...TURNING OFF /light
TIMEOUT...DIMMING /light
TIMEOUT...TURNING OFF /light
TIMEOUT...DIMMING /light
这意味着我假设我把try-except语句搞砸了,有人知道修复方法吗?在我周围找到了一个作品,不认为它是最美观的,但它似乎起作用了
async def main(self):
count = 0
while True:
if count == 1:
try:
await asyncio.wait_for(self.movement_detected(), timeout=60)
count = 0
except asyncio.TimeoutError:
print('TIMEOUT...TURNING OFF ' + topic)
count = 1
async with Client(self.broker) as client:
await client.publish(topic, orjson.dumps(state_off))
else:
try:
await asyncio.wait_for(self.movement_detected(), timeout=900)
count = 0
except asyncio.TimeoutError:
count = 1
state_off = {"state": "off"}
state_dim = {"brightness":50, "state": "ON"}
print('TIMEOUT...DIMMING ' + topic)
async with Client(self.broker) as client:
await client.publish(topic, orjson.dumps(state_dim))
这可以防止它从关闭状态变暗,它只能从打开状态变暗