請按照下列操作說明在裝置上執行自訂程式碼,以回應 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 指令。如果尚未新增,請略過下一節,瞭解如何新增更多特徵和處理常式。
後續步驟 - Raspberry Pi
現在您已瞭解如何處理傳入的指令,請將程式碼範例修改成 LED 燈。如果您使用的是 Raspberry Pi,將會需要一些額外的硬體。
匯入 GPIO 套件
如要簡化 Raspberry Pi 上一般用途輸入/輸出 (GPIO) 接腳的軟體存取程序,請在虛擬環境中安裝 RPi.GPIO 套件。
pip install RPi.GPIO
修改樣本
開啟 hotword.py
檔案。
nano hotword.py
在 hotword.py
檔案中匯入「RPi.GPIO」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 燈應該就會亮起。
不過,真正的重頭戲還在後面。瞭解如何新增更多特徵和處理常式。