
# 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

import aiy.assistant.auth_helpers
from aiy.assistant.library import Assistant
import aiy.audio
import aiy.voicehat
from google.assistant.library.event import EventType

import aiy.assistant.grpc
import serial
import time
from urllib.request import urlopen
ser = serial.Serial('/dev/ttyACM0',9600)
time.sleep(2)

# Enter Your API key here
myAPI = 'YXRIFM0KA6R7MLUG' 
# URL where we will send the data, Don't change it
baseURL = 'https://api.thingspeak.com/update?api_key=%s' % myAPI 

mflag = 0

logging.basicConfig(
    level=logging.INFO,
    format="[%(asctime)s] %(levelname)s:%(name)s:%(message)s"
)


def power_off_pi():
    aiy.audio.say('Good bye!')
    subprocess.call('sudo shutdown now', shell=True)


def reboot_pi():
    aiy.audio.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)
    aiy.audio.say('My IP address is %s' % ip_address.decode('utf-8'))
    
def music_ip():
    aiy.audio.say('Play music now')
    time.sleep(0.5)
    ser.write(str.encode('3'))                                                 
    print('music')
    ser.write(str.encode('0'))
    

def hello_pi():
    aiy.audio.say('Hello! nice to meet you.')
    time.sleep(0.5)
    ser.write(str.encode('1'))                                                 
    print('flash')                    
    ser.write(str.encode('0'))
    ser.write(str.encode('0'))
    temp = 1
    humi = 2
    conn = urlopen(baseURL + '&field1=%s&field2=%s' % (temp, humi))
    print(conn)
    
def math_test():
    aiy.audio.say('Six minus five = ?')
    time.sleep(0.5)
    ser.write(str.encode('1'))                                                 
    print('flash')                    
    ser.write(str.encode('0'))
    ser.write(str.encode('0'))
    temp = 3
    humi = 4
    conn = urlopen(baseURL + '&field1=%s&field2=%s' % (temp, humi))
    print(conn)

def correct():
    aiy.audio.say('You are right!')
    time.sleep(0.5)
    ser.write(str.encode('1'))                                                 
    print('flash')                    
    ser.write(str.encode('0'))
    ser.write(str.encode('0'))
    temp = 7
    humi = 7
    conn = urlopen(baseURL + '&field1=%s&field2=%s' % (temp, humi))
    print(conn)
    
def wrong():
    aiy.audio.say('You are wrong!')
    time.sleep(0.5)
    ser.write(str.encode('2'))                                                 
    print('flash')                    
    ser.write(str.encode('0'))
    ser.write(str.encode('0'))
    temp = 8
    humi = 8
    conn = urlopen(baseURL + '&field1=%s&field2=%s' % (temp, humi))
    print(conn)

def pronunciation():
    aiy.audio.say('Please pronoun the word "a",  "p",  "p",  "l" , "e".')
    time.sleep(0.5)
    ser.write(str.encode('1'))                                                 
    print('flash')                    
    ser.write(str.encode('0'))
    time.sleep(0.2)
    ser.write(str.encode('1'))                                                 
    print('flash')   
    ser.write(str.encode('0'))
    temp = 5
    humi = 6
    conn = urlopen(baseURL + '&field1=%s&field2=%s' % (temp, humi))
    print(conn)




def next_pi():
    aiy.audio.say('Next musical instrument.')
    ser.write(str.encode('2'))                                                 
    print('next')
    ser.write(str.encode('0'))    
    temp = 4
    humi = 3
    conn = urlopen(baseURL + '&field1=%s&field2=%s' % (temp, humi))
    print(conn)


def process_event(assistant, event):
    global mflag
    print(event)
#    print(mflag)
    status_ui = aiy.voicehat.get_status_ui()
    if event.type == EventType.ON_START_FINISHED:
        status_ui.status('ready')
        if sys.stdout.isatty():
            print('Say "OK, Google" then speak, or press Ctrl+C to quit...')

    elif event.type == EventType.ON_CONVERSATION_TURN_STARTED:
        status_ui.status('listening')

    elif event.type == EventType.ON_RECOGNIZING_SPEECH_FINISHED and event.args:
        print('You said:', event.args['text'])
        text = event.args['text'].lower()
        if mflag == 0:
            if text == 'power off':
                assistant.stop_conversation()
                power_off_pi()
            elif text == 'reboot':
                assistant.stop_conversation()
                reboot_pi()
                mflag = 0
            elif text == 'ip address':
                assistant.stop_conversation()
                say_ip()
                mflag = 0
            elif text == 'music':
                assistant.stop_conversation()
                music_ip()
                mflag = 0
            elif text == 'hello':
                assistant.stop_conversation()
                hello_pi()
                mflag = 0
            elif text == 'next':
                assistant.stop_conversation()
                next_pi()
                mflag = 0
            elif (text == 'math test' or text == 'maths test'):
                assistant.stop_conversation()
                math_test()
                mflag = 1
            elif (text == 'listening test'or ext == 'listening quiz' ):
                assistant.stop_conversation()
                pronunciation()
                mflag = 2
        elif mflag == 1:
            if (text == 'one' or text == '1'):
                assistant.stop_conversation()
                correct()
            else:
                assistant.stop_conversation()
                wrong()
            mflag = 0
        elif mflag == 2:
            if (text == 'apple'):
                assistant.stop_conversation()
                correct()
            else:
                assistant.stop_conversation()
                wrong()
            mflag = 0
    
            
    elif event.type == EventType.ON_END_OF_UTTERANCE:
        status_ui.status('thinking')

    elif (event.type == EventType.ON_CONVERSATION_TURN_FINISHED
          or event.type == EventType.ON_CONVERSATION_TURN_TIMEOUT
          or event.type == EventType.ON_NO_RESPONSE):
        status_ui.status('ready')

    elif event.type == EventType.ON_ASSISTANT_ERROR and event.args and event.args['is_fatal']:
        sys.exit(1)


def main():
    if platform.machine() == 'armv6l':
        print('Cannot run hotword demo on Pi Zero!')
        exit(-1)
        
#    print(mflag)
    
    credentials = aiy.assistant.auth_helpers.get_assistant_credentials()
    with Assistant(credentials) as assistant:
        for event in assistant.start():
            process_event(assistant, event)


if __name__ == '__main__':
    main()

