#!/usr/bin/python
# -*- coding: utf-8 -*-

'''
// Pointer Robot with Raspbery Pi and Arduino
// Copyright (C) 2018, ArduinoDeXXX All Rights Reserved.
//
// information:
// This is a sample code to command your robot to move or stop with your voice.
// Plug USB camera "Logitech C270" or a good USB microphone into Raspberry Pi 3.
// Run Julius in module mode in other terminal in advance.
// Adjust the gain of microphone by Alsamixer in other terminal.
// Pi 3 should be connected to Arduino where "adx_PR_arduino.ino" is run.
//
// This sample code is provided for an article to get Pointer robot.
// View the sites bellow to see more detail.
// https://www.instructables.com/id/Pointer-Robot-With-RPi-and-Arduino/
// https://www.instructables.com/id/Pointer-Robot-With-RPi-and-Arduino-JPN/
//
// acknowledge:
// https://raspibb2.blogspot.jp/2017/03/raspberry-pi-julius-lirc.html
// https://raw.githubusercontent.com/neuralassembly/raspi/master/recog-TV.py
'''

import socket
from io import StringIO
import re
import subprocess
import RPi.GPIO as GPIO
import time

GPIO.setmode(GPIO.BCM)
GPIO.setup(25, GPIO.OUT, initial=GPIO.LOW)                            

try:
    unicode # python2
    def u(str): return str.decode('utf-8')
    pass
except: # python3
    def u(str): return str
    pass

host = '127.0.0.1'
port = 10500
bufsize = 1024

buff = StringIO(u(''))
pattern = r'WHYPO WORD=\"(.*)\" CLASSID'
try:
    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    sock.connect((host, port))
    while True:
        data = sock.recv(bufsize)
        buff.write(data.decode('utf-8'))
        data = buff.getvalue().replace('> ', '>\n ')
        if '\n' in data:
            lines = data.splitlines()
            for i in range(len(lines)-1):
                if lines[i] != '.':
                    m = re.search(pattern, lines[i])
                    if m:
                        word = m.group(1)

                        if u('前進') in word:
                            print(word)
                            cmd = 'python /home/pi/adx_PR3_uart180.py 425' # 425 = 2(as Forward)*180 + 65（pwm: 92=255*(65/180)）
                            try:
                                subprocess.Popen(cmd, shell=True)
                            except OSError:
                                print('command not found.')
                        elif u('止まれ') in word:
                            print(word)
                            cmd = 'python /home/pi/adx_PR3_uart180.py 540' # 540 = 3(as Stop)*180 + 0（pwm: 0=255*(0/180)）
                            try:
                                subprocess.Popen(cmd, shell=True)
                            except OSError:
                                print('command not found.')
                        elif u('後退') in word:
                            print(word)
                            cmd = 'python /home/pi/adx_PR3_uart180.py 785' # 785 = 4(as Backward)*180 + 65（pwm: 92=255*(65/180)）
                            try:
                                subprocess.Popen(cmd, shell=True)
                            except OSError:
                                print('command not found.')
                        elif u('右') in word:
                            print(word)
                            cmd = 'python /home/pi/adx_PR3_uart180.py 1685' # 1685 = 9(as Turn Right)*180 + 65（pwm: 92=255*(65/180)）
                            try:
                                subprocess.Popen(cmd, shell=True)
                            except OSError:
                                print('command not found.')
                        elif u('左') in word:
                            print(word)
                            cmd = 'python /home/pi/adx_PR3_uart180.py 1865' # 1865 = 10(as Turn Left)*180 + 65（pwm: 92=255*(65/180)）
                            try:
                                subprocess.Popen(cmd, shell=True)
                            except OSError:
                                print('command not found.')
                        elif u('追尾') in word: # Auto-Tracing-and-Pointing mode
                            print(word)
                            cmd = 'python /home/pi/adx_PR3_uart180.py 540' # 540 = 3(as Stop)*180 + 0（pwm: 0=255*(0/180)）
                            try:
                                subprocess.Popen(cmd, shell=True)
                                GPIO.output(25, 0)
                            except OSError:
                                print('command not found.')
                        elif u('音声o') in word: # Following-your-voice-command mode
                            print(word)
                            cmd = 'python /home/pi/adx_PR3_uart180.py 540' # 540 = 3(as Stop)*180 + 0（pwm: 0=255*(0/180)）
                            try:
                                subprocess.Popen(cmd, shell=True)
                                GPIO.output(25, 1)
                            except OSError:
                                print('command not found.')
                        
            buff.close()
            buff = StringIO(u(''))
            if lines[len(lines)-1] != '.':
            	buff.write(lines[len(lines)-1])

except socket.error:
    print('socket error')
except KeyboardInterrupt:
    pass

sock.close()
