DIVA - DIVersely Assisted

Making the Google Assistant more accessible by using buttons and RFID tags to trigger commands.

IntermediateFull instructions provided1.5 hours2,611
DIVA - DIVersely Assisted

Things used in this project

Hardware components

AIY Voice
Google AIY Voice
×1
RFID reader (generic)
×1

Story

Read more

Code

diva.py

Python
#!/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.

import argparse
import json
import logging
import os
import pathlib2 as pathlib
import platform
import sys
import subprocess
import threading

import google.oauth2.credentials

from aiy.board import Board, Led
from google.assistant.library import Assistant
from google.assistant.library.event import EventType
from google.assistant.library.file_helpers import existing_file
from google.assistant.library.device_helpers import register_device


logging.basicConfig(
   level=logging.INFO,
   format="[%(asctime)s] %(levelname)s:%(name)s:%(message)s"
)


COMMANDS = {}
# Configure here the command you want to associate to the button
COMMANDS['BUTTON'] = "Tell me a joke"
# Configure here the RFID TAG ID with the associated command
COMMANDS['TAG_ID_1'] = "Play YouTube videos on my Chromecast"
COMMANDS['TAG_ID_2'] = "Play Pop Music from Google Play Music on my Chromecast"


class DivaAssistant(object):

 def __init__(self, credentials_file, device_config):
   self._assistant = None
   self._board = Board()
   self._device_config = device_config
   self._can_start_conversation = False
   self._credentials_file = credentials_file
   self._task = threading.Thread(target=self._run_task)

 def start(self):
   """Starts the Assistant event loop and begin processing events."""
   self._board.button.when_pressed = self._on_button_pressed
   self._task.daemon = True
   self._task.start()

 def _on_button_pressed(self):
   query = COMMANDS.get('BUTTON', 'Repeat after me, Not configured')
   self.send_text(query)

 def _run_task(self):
   """Starts the Assistant.

   Retrieve Credentials, Device Configuration and start the assistant.
   """
   with open(self._credentials_file, 'r') as f:
     self._credentials = google.oauth2.credentials.Credentials(token=None,
                                                               **json.load(f))

   with open(self._device_config, 'r') as f:
     id_data = json.load(f)
     self._device_id = id_data["device_id"]
     self._device_model_id = id_data["model_id"]

   with Assistant(self._credentials, self._device_model_id) as assistant:
     self._assistant = assistant
     print('device_model_id:', self._device_model_id + '\n' +
           'device_id:', self._device_id + '\n')
     for event in assistant.start():
       self._process_event(event)

 def _process_event(self, event):
   """Process the event from the Assistant."""
   if event.type == EventType.ON_START_FINISHED:
     self._can_start_conversation = True
     self._board.led.status = Led.BEACON_DARK  # Ready.
     if sys.stdout.isatty():
       print('Say "OK, Google" then speak, write a command, press the button or tap a card. '
             'Press Ctrl+C to quit...')
   elif event.type == EventType.ON_CONVERSATION_TURN_STARTED:
     self._can_start_conversation = False
     self._board.led.state = Led.ON  # Listening.

   elif event.type == EventType.ON_END_OF_UTTERANCE:
     self._board.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):
     self._board.led.state = Led.BEACON_DARK  # Ready.
     self._can_start_conversation = True

   elif event.type == EventType.ON_ASSISTANT_ERROR and event.args and event.args['is_fatal']:
     sys.exit(1)

 def send_text(self, message):
   """Send text massage to the Assistant."""
   if self._can_start_conversation:
     print('Sending to the Assistant message: %s' % message)
     self._assistant.send_text_query(message)


def main():
 parser = argparse.ArgumentParser(
     formatter_class=argparse.RawTextHelpFormatter)
 parser.add_argument('--credentials', type=existing_file,
                     metavar='OAUTH2_CREDENTIALS_FILE',
                     default=os.path.join(
                         os.path.expanduser('~/.cache'),
                         'voice-recognizer',
                         'assistant_credentials.json'
                     ),
                     help='Path to store and read OAuth2 credentials')
 parser.add_argument('--device_config', type=existing_file,
                     metavar='DEVICE_CONFIG',
                     default=os.path.join(
                         os.path.expanduser('~/.cache'),
                         'voice-recognizer',
                         'device_id.json'),
                     help='The file containing device model ID registered')

 args = parser.parse_args()

 # initialize and start the Assistant
 assistant = DivaAssistant(args.credentials, args.device_config)
 assistant.start()

 # accept keyboard inputs
 while True:
   # wait for keyboard input
   message = input()
   # check if the message is registered as command in
   # the COMMAND variable
   message = COMMANDS.get(message, message)
   # send message to the Assistant
   assistant.send_text(message)


if __name__ == '__main__':
 main()

Credits

Lorenzo Caggioni

Lorenzo Caggioni

1 project • 3 followers
Paolo Pigozzo

Paolo Pigozzo

1 project • 2 followers
Davide Ferraro

Davide Ferraro

0 projects • 1 follower
Thanks to Egil Hogholt, Teresa Pato, and Thomas Riga.

Comments