rayyy424
Posts: 1
Joined: Tue Dec 03, 2019 1:18 pm

Combine code

Tue Dec 03, 2019 1:32 pm

Hi, I am new to raspberry pi. I want to know how I want to combine coding from led_chaser.py to assistant_grpc_demo.py(import board.py and grpc.py). I want to know where should I put the led_chaser.py code into the assistant_grpc_demo.py code or should I put the led_chaser code into the other two code which is board.py and grpc.py. Really appreciate any help from you guys. All the code is included in the attachments.
Attachments
code.rar
(7.82 KiB) Downloaded 4 times

User avatar
DougieLawson
Posts: 36526
Joined: Sun Jun 16, 2013 11:19 pm
Location: Basingstoke, UK
Contact: Website Twitter

Re: Combine code

Tue Dec 03, 2019 8:36 pm

If you look at ../aiyprojects-raspbian/src/examples/voice/assistant_library_with_local_commands_demo.py it gives a good clue where you can insert your own code.

Code: Select all

#!/usr/bin/env python3
# Copyright 2017 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

"""Run a recognizer using the Google Assistant Library.

The Google Assistant Library has direct access to the audio API, so this Python
code doesn't need to record audio. Hot word detection "OK, Google" is supported.

It is available for Raspberry Pi 2/3 only; Pi Zero is not supported.
"""

import logging
import platform
import subprocess
import sys

from google.assistant.library.event import EventType

from aiy.assistant import auth_helpers
from aiy.assistant.library import Assistant
from aiy.board import Board, Led
from aiy.voice import tts

def power_off_pi():
    tts.say('Good bye!')
    subprocess.call('sudo shutdown now', shell=True)


def reboot_pi():
    tts.say('See you in a bit!')
    subprocess.call('sudo reboot', shell=True)


def say_ip():
    ip_address = subprocess.check_output("hostname -I | cut -d' ' -f1", shell=True)
    tts.say('My IP address is %s' % ip_address.decode('utf-8'))


def process_event(assistant, led, event):
    logging.info(event)
    if event.type == EventType.ON_START_FINISHED:
        led.state = Led.BEACON_DARK  # Ready.
        print('Say "OK, Google" then speak, or press Ctrl+C to quit...')
    elif event.type == EventType.ON_CONVERSATION_TURN_STARTED:
        led.state = Led.ON  # Listening.
    elif event.type == EventType.ON_RECOGNIZING_SPEECH_FINISHED and event.args:
        print('You said:', event.args['text'])
        text = event.args['text'].lower()
        if text == 'power off':
            assistant.stop_conversation()
            power_off_pi()
        elif text == 'reboot':
            assistant.stop_conversation()
            reboot_pi()
        elif text == 'ip address':
            assistant.stop_conversation()
            say_ip()
    elif event.type == EventType.ON_END_OF_UTTERANCE:
        led.state = Led.PULSE_QUICK  # Thinking.
    elif (event.type == EventType.ON_CONVERSATION_TURN_FINISHED
          or event.type == EventType.ON_CONVERSATION_TURN_TIMEOUT
          or event.type == EventType.ON_NO_RESPONSE):
        led.state = Led.BEACON_DARK  # Ready.
    elif event.type == EventType.ON_ASSISTANT_ERROR and event.args and event.args['is_fatal']:
        sys.exit(1)


def main():
    logging.basicConfig(level=logging.INFO)

    credentials = auth_helpers.get_assistant_credentials()
    with Board() as board, Assistant(credentials) as assistant:
        for event in assistant.start():
            process_event(assistant, board.led, event)


if __name__ == '__main__':
    main()
The "say_ip()" function that's triggered by "OK Google IP Address" is the example I'd use (take the "power off" and "reboot" functions out - they'll only cause trouble).

So we take your code

Code: Select all

leds = (LED(PIN_A), LED(PIN_B), LED(PIN_C), LED(PIN_D))
while True:
    for led in leds:
        led.on()
        sleep(0.5)
        led.off()
And turn that into a one-shot function (that doesn't run forever)

Code: Select all

from time import sleep
from gpiozero import LED
from aiy.pins import (PIN_A, PIN_B, PIN_C, PIN_D)

# ... lots of other stuff here.
# Reboot and power off functions get deleted.

def say_ip():
    ip_address = subprocess.check_output("hostname -I | cut -d' ' -f1", shell=True)
    tts.say('My IP address is %s' % ip_address.decode('utf-8'))

def wink_leds():
    tts.say("I'm winking some LEDs for you.")
    leds = (LED(PIN_A), LED(PIN_B), LED(PIN_C), LED(PIN_D))
    for i in range(1,100): # 100 times should be noticable alter to taste
       for led in leds:
          led.on()
          sleep(0.5)
          led.off()
          sleep(0.5)
          
# ... code snipped to make things clearer.
# Reboot and power off code gets deleted ...

        if text == 'ip address':
            assistant.stop_conversation()
            say_ip()
        elif text == 'wink leds':
            assistant.stop_conversation()
            wink_leds()

Note: Having anything humorous in your signature is completely banned on this forum. Wear a tin-foil hat and you'll get a ban.

Any DMs sent on Twitter will be answered next month.

This is a doctor free zone.

Return to “Staffroom, classroom and projects”