从 Google Assistant SDK 激活 GPIO 或任何 Python 脚本

Activate GPIO or any Python Script from Google Assistant SDK

昨天我在我的 Raspberry Pi 4 上安装了 Google 助手 SDK,我用这个 (https://developers.google.com/assistant/sdk/guides/service/python) tutorial from Google and wanted to make GPIO 25 to turn on and off via the onoff trait, explained in this section (https://developers.google.com/assistant/sdk/guides/service/python/extend/handle-device-commands).

但他们这样做的方式对我不起作用,当我 运行 助手说“打开”时,Gpio 没有任何反应。

当直接 运行ning "pushtotalk.py" 时,它会给你一个错误输出,它显示,设备处理程序没有定义,即使它就在 onoff 函数之前。

这是我的代码(源自Google):

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

Python 对缩进级别(不是字符)有严格要求。您的 device 声明有缩进。使其与 device_handler 对齐应该可以解决该错误。

device = '3eeb4608-7913-11ea-ad54-dca632812cbd'
device_handler = device_helpers.DeviceRequestHandler(device)
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)

这种方式现在工作非常稳定,现在可以识别设备处理程序,即使我只更改了 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')

这样你就可以很容易地激活 Python 脚本与 Google 助手例如。 Raspberry Pi 只需说“打开”即可。