请按照以下说明在您的设备上执行自定义代码,以响应 Google 助理发出的命令。
运行示例
现在,您已经定义了一个特征并更新了模型,请进行检查以确保 Google 助理针对相应查询发回“开启/关闭”命令。
googlesamples-assistant-hotword --device-model-id my-model
请尝试以下查询:
Ok Google,开启。
您应该会在控制台输出中看到以下语句。如果没有,请参阅问题排查说明。
ON_RECOGNIZING_SPEECH_FINISHED:
{'text': 'turn on'}
ON_DEVICE_ACTION:
{'inputs': [{'payload': {'commands': [{'execution': [{'command': 'action.devices.commands.OnOff',
'params': {'on': True}}], 'devices': [{'id': 'E56D39D894C2704108758EA748C71255'}]}]},
'intent': 'action.devices.EXECUTE'}], 'requestId': '4785538375947649081'}
Do command action.devices.commands.OnOff with params {'on': True}
您可以在源代码中找到这些语句的显示位置。
获取源代码
您现在可以开始自己的项目了:
git clone https://github.com/googlesamples/assistant-sdk-python
查找命令处理程序
示例代码中的 hotword.py
文件使用 SDK 发送请求和接收来自 Google 助理的响应。
cd assistant-sdk-python/google-assistant-sdk/googlesamples/assistant/library
nano hotword.py
搜索以下处理程序定义:
def process_event(event):
目前,此函数使用以下行输出每个设备操作事件名称和所有参数:
print('Do command', command, 'with params', str(params))
此代码会处理 action.devices.commands.OnOff
命令。此命令是 OnOff 特征架构的一部分。目前,此代码仅会将输出输出到控制台。您可以修改此代码,以便在项目中执行所需的任何操作。在 process_event()
中的 print
命令下添加以下代码块。
print('Do command', command, 'with params', str(params)) # Add the following: if command == "action.devices.commands.OnOff": if params['on']: print('Turning the LED on.') else: print('Turning the LED off.')
直接运行修改后的源代码即可查看输出。
python hotword.py --device-model-id my-model
使用与之前相同的查询:
Ok Google,开启。
如果您将 LED 连接到 Raspberry Pi,请继续阅读以了解如何根据 OnOff 命令点亮 LED 灯。否则,请跳过下一部分,了解如何添加更多特征和处理程序。
后续步骤 - Raspberry Pi
现在您已经知道如何处理传入的命令,请修改示例代码以点亮 LED 灯。如果您使用的是 Raspberry Pi,则需要一些额外的硬件。
导入 GPIO 软件包
如需简化软件对 Raspberry Pi 上的通用输入/输出 (GPIO) 引脚的访问,请在虚拟环境中安装 RPi.GPIO 软件包。
pip install RPi.GPIO
修改示例
打开 hotword.py
文件。
nano hotword.py
在 hotword.py
文件中,导入 RPi.GPIO 模块以控制 Pi 上的 GPIO 引脚。将以下语句放在其他 import
语句附近:
import RPi.GPIO as GPIO
修改代码,以便将输出引脚最初设置为低逻辑状态。在处理事件之前,请在 main()
函数中执行此操作:
with Assistant(credentials, device_model_id) as assistant: events = assistant.start() device_id = assistant.device_id print('device_model_id:', device_model_id) print('device_id:', device_id + '\n') GPIO.setmode(GPIO.BCM) GPIO.setup(25, GPIO.OUT, initial=GPIO.LOW) ...
修改您在 process_event()
中添加的代码。收到 on 命令后,将引脚设置为高逻辑状态。收到关闭命令后,将引脚设置为低逻辑状态。
if command == "action.devices.commands.OnOff": if params['on']: print('Turning the LED on.') GPIO.output(25, 1) else: print('Turning the LED off.') GPIO.output(25, 0)
保存更改并关闭该文件。
运行示例
运行修改后的示例代码。
python hotword.py --device-model-id my-model
使用与之前相同的查询。LED 灯应亮起。
这仅仅只是开始。了解如何添加更多特征和处理程序。