首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >嵌套Try-Except语句使灯光变暗,然后最终将其关闭

嵌套Try-Except语句使灯光变暗,然后最终将其关闭
EN

Stack Overflow用户
提问于 2021-04-21 18:44:30
回答 1查看 24关注 0票数 0

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

代码语言:javascript
复制
    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))

当我运行它时,我得到:

代码语言:javascript
复制
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--除了语句,有人知道修复方法吗?

EN

回答 1

Stack Overflow用户

发布于 2021-04-21 21:46:27

我自己找到了一个解决方案,不认为它是最美观的,但它似乎起作用了。

代码语言:javascript
复制
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))

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

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/67194274

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档