sdk - 从 Google Assistant SDK 激活 GPIO 或任何 Python 脚本
问题描述
昨天我在我的 Raspberry Pi 4 上安装了 Google Assistant SDK,我使用了 Google 的这个(https://developers.google.com/assistant/sdk/guides/service/python)教程,并想让 GPIO 25 打开并通过 onoff 特征关闭,在本节中解释(https://developers.google.com/assistant/sdk/guides/service/python/extend/handle-device-commands)。
但是他们这样做的方式对我不起作用,当我运行助手并说“打开”时,Gpio 没有任何反应。
当直接运行“pushtotalk.py”时,它会给你一个错误输出,它显示设备处理程序没有定义,即使它就在 onoff 函数之前。
这是我的代码(来自谷歌):
device_handler = device_helpers.DeviceRequestHandler(device_id)
GPIO.setmode(GPIO.BCM)
GPIO.setup(25, GPIO.OUT, initial=GPIO.LOW)
device_handler.command('action.devices.commands.OnOff')
def onoff(on):
if on:
logging.info('Turning device on')
GPIO.output(25, 1)
else:
logging.info('Turning device off')
GPIO.output(25, 0)
这是错误:
Traceback (most recent call last):
File "pushtotalk.py", line 465, in <module>
main()
File "/home/pi/env/lib/python3.7/site-packages/click/core.py", line 722, in __call__
return self.main(*args, **kwargs)
File "/home/pi/env/lib/python3.7/site-packages/click/core.py", line 697, in main
rv = self.invoke(ctx)
File "/home/pi/env/lib/python3.7/site-packages/click/core.py", line 895, in invoke
return ctx.invoke(self.callback, **ctx.params)
File "/home/pi/env/lib/python3.7/site-packages/click/core.py", line 535, in invoke
return callback(*args, **kwargs)
File "pushtotalk.py", line 425, in main
device_handler.command('action.devices.commands.OnOff')
UnboundLocalError: local variable 'device_handler' referenced before assignment
解决方案
这种方式现在工作非常稳定并且设备处理程序现在被识别,即使我只更改了 if 语句中的行,显然导入 GPIO 模块存在问题。
device_handler = device_helpers.DeviceRequestHandler(device_id)
@device_handler.command('action.devices.commands.OnOff')
def onoff(on):
if on:
logging.info('Turning device on')
os.system('python <Filename>.py')
else:
logging.info('Turning device off')
os.system('python <filename>.py')
这样您就可以轻松地使用 Google Assisant 激活 Python 脚本,例如。只需说“打开”即可使用 Raspberry Pi。
推荐阅读
- scala - 如何在scala中创建列表连续的正值或负值
- c - 当我的结构数组为空时该怎么办?
- firebase - 如何在不指定文档 ID 的情况下更新文档内的数据?
- nearprotocol - 气体计数。燃烧过的煤气和用过的煤气有什么区别?
- c# - 直接动态转换为不同类型的数组
- r - ggplot2 中的条件
- python - 在 Django 中导航无法正常工作
- python - 如何在 Python-Flask 中使用 Semantic-ui 多个选项卡?
- c# - 多线程 C# 环境中的 Mysql 事务
- bash - bash 中的简单命令是否在子 shell 中运行,因为单个命令可以构成管道?