繁体   English   中英

嵌套 Try-Except 语句以调暗灯光,然后最终将其关闭

[英]Nesting Try-Except statements to dim lights and then eventually shut them off

在一段时间没有移动后,我试图调暗灯光,然后在另一段时间后最终将它们完全关闭。 我面临的问题是,当它关闭时,它应该只能选择再次打开,而不是从关闭状态随机变暗。 下面的代码:

    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 语句,有人知道解决方法吗?

自己找到了一个解决方法,不认为它是最美观的,但它似乎是 function。

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

这可以防止它从关闭状态变暗,它只能从开启状态变暗。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM