You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

树莓派3使用Python调用Google Assistant库遇凭证不被接受问题及LED控制需求

Hey there! Great job getting Google Assistant up and running on your Raspberry Pi 3 — that's half the battle done. Let's tackle adding LED control based on specific voice commands, and fix that argparse issue you mentioned along the way.

Step 1: Wire Up Your LED

First, let's get the hardware sorted (super straightforward):

  • Connect the long leg (anode) of your LED to Raspberry Pi's GPIO18 pin
  • Attach the short leg (cathode) to a 220Ω resistor, then connect the other end of the resistor to a GND pin
  • Double-check the wiring to avoid short circuits

Step 2: Fix Argparse & Integrate LED Control

Your main() function's --credentials parameter was cut off, so I'll fill that out properly while adding the LED control logic. Here's a complete, working example:

First, import all required libraries:

import argparse
import os
import RPi.GPIO as GPIO
from google.assistant.library import Assistant
from google.assistant.library.event import EventType

Initialize GPIO for the LED:

# Set up GPIO for LED control
LED_PIN = 18
GPIO.setmode(GPIO.BCM)
GPIO.setup(LED_PIN, GPIO.OUT)
GPIO.output(LED_PIN, GPIO.LOW)  # Start with LED off

Now fix the main() function with proper argparse handling and command recognition:

def main():
    parser = argparse.ArgumentParser(
        formatter_class=argparse.RawTextHelpFormatter
    )
    # Fix the --credentials argument (checks if the file exists)
    parser.add_argument(
        '--credentials',
        type=str,
        required=True,
        help='Full path to your Google Assistant credentials JSON file'
    )
    # Add your device ID argument (matches the --d flag you use)
    parser.add_argument(
        '--d', '--device-id',
        type=str,
        required=True,
        help='Device ID for your Google Assistant instance (device_id1234 in your example)'
    )
    args = parser.parse_args()

    # Verify credentials file exists before proceeding
    if not os.path.isfile(args.credentials):
        print(f"Error: Credentials file '{args.credentials}' not found!")
        return

    # Define how to handle Assistant events
    def process_event(event):
        if event.type == EventType.ON_RECOGNIZING_SPEECH_FINISHED:
            command = event.args['text'].lower()
            print(f"Recognized command: {command}")

            # Trigger LED actions based on specific phrases
            if "turn on the led" in command or "打开led" in command:
                GPIO.output(LED_PIN, GPIO.HIGH)
                print("LED turned ON")
                assistant.say("LED is now on")
            elif "turn off the led" in command or "关闭led" in command:
                GPIO.output(LED_PIN, GPIO.LOW)
                print("LED turned OFF")
                assistant.say("LED is now off")

    # Start the Google Assistant and listen for commands
    try:
        with Assistant(args.credentials, args.device_id) as assistant:
            for event in assistant.start():
                process_event(event)
    except Exception as e:
        print(f"Error running Assistant: {str(e)}")
    finally:
        # Clean up GPIO to avoid pin issues on shutdown
        GPIO.cleanup()

if __name__ == '__main__':
    main()

Step 3: Run the Script

Execute the script with your actual credentials path and device ID:

python3 your_script_name.py --credentials /home/pi/.config/google-oauthlib-tool/credentials.json --d device_id1234

Key Notes

  • I replaced the incomplete existing... type check with a manual file existence check — it's more reliable for path-related edge cases
  • The process_event function listens for completed speech recognition, then matches your target phrases to trigger LED actions
  • The finally block ensures GPIO is cleaned up properly, even if the script crashes

If you hit issues with library imports, Assistant initialization, or command recognition, just share more details and I'll help tweak things further!

内容的提问来源于stack exchange,提问作者Brosch

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.20 12:11:59