"""
┏━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓
┃ Mango X2 Starter System Program Ver.1.1                     ┃
┃                                                             ┃
┃ A micropython program to display all Mango X2 Starter's     ┃
┃ functions and support to execute 2 customized programs.     ┃
┃ Customized programs must be named by p1.py and p2.py        ┃
┃                                                             ┃
┃ Copyright (c) 2024 歐陽芳泉、羅治民                          ┃
┃ Authorized for 校園文化有限公司                              ┃
┗━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┛
"""
import utime,mydisplay,framebuf
import board
from mango.x2 import rgb,tank
from machine import Pin,ADC
from mango import display,utils,hcsr04,sound

#各項參數設定
board.GP4 = Pin(4, Pin.IN, Pin.PULL_DOWN)
board.GP17 = Pin(17, Pin.IN, Pin.PULL_DOWN)
tank = tank.Tank()
dist_sensor = hcsr04.HCSR04(2)
rgb.ledCount=8
rgb.leds = rgb.setLeds(7, 8)
item = ['G4 1','P 0.25','E4 1','P 0.25','E4 2','P 0.25','F4 1','P 0.25','D4 1','P 0.25','D4 2','P 0.25','C4 1','P 0.25','D4 1','P 0.25','E4 1','P 0.25','F4 1','P 0.25','G4 1','P 0.25','G4 1','P 0.25','G4 2','P 0.25']
disp=mydisplay.init()
#disp.oled.rotate(True)
sound_player = sound.Music(22)
LightPower = 10
SoundVol = 2
MovePower30 = 30 #循跡時的馬達轉速
MovePower50 = 50 #循跡時的馬達轉速
MovePower70 = 70 #循跡時的馬達轉速
MovePower100 = 100 #循跡時的馬達轉速
Skip = None
FollowOn = None
AvoidOn = None
Ver = "1.1"
HitTime = 0 #聲波避障前行逾時

fun1_name='基本功能展示'
fun2_name='執行二路循跡'
fun3_name='執行聲波避障'
fun4_name='顯示現在溫度'
fun5_name='彩燈亮度調整'
fun6_name='音量強度調整'
fun7_name='自訂程式Ｐ１'
fun8_name='自訂程式Ｐ２'
total_page=4 #選單總頁數
current_page=1 #選單現在頁數
current_fun=1 #現在功能位置
TempSensor = ADC(4) #取得內建溫度腳位
conversion_factor = 3.3 / 65535 #內建溫度類比轉換係數


#紅色按鈕（選擇功能）
def RedBtn():
    global current_fun    
    if (board.GP4.value()) == 1:
        nextFun()    
#顏色按鈕（執行功能）
def ExecBtn():
    global Skip
    if (board.GP17.value()) == 1:
        Skip = 0        
        if Skip == 0:
            if current_fun == 1:                
                Fun1()
            elif current_fun == 2:
                Fun2()                
            elif current_fun == 3:
                Fun3()
            elif current_fun == 4:
                Fun4()
            elif current_fun == 5:
                Fun5()
            elif current_fun == 6:
                Fun6()
            elif current_fun == 7:
                Fun7()
            elif current_fun == 8:
                Fun8()

# 展示商標
def display_logo(oled,delay):        
    fb = framebuf.FrameBuffer(bytearray(
    b'\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff'
    b'\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff'
    b'\xff\xff\xff\xff\xdf\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xfe\xbf\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff'
    b'\xff\xff\xff\xff\xd7\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xfd\xd7\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff'
    b'\xff\xff\xff\xfb\xcf\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xfb\xdf\x40\xbf\xff\xff\xff\xfe\xbe\xde\x9f\xff\xff'
    b'\xff\xff\xff\xf3\x3c\x7f\x0f\xff\xff\x81\x94\x06\xa1\x2f\xff\xff\xff\xff\xfc\x07\x7f\xff\xe7\xff\xff\x9d\x80\xb6\x21\x6f\xff\xff'
    b'\xff\xff\xf2\xfe\x0f\xff\xf9\xff\xff\x9f\xed\xfe\x9e\x97\xff\xff\xff\xff\xcf\xf6\x00\x77\xfc\xff\xff\x9f\xff\xff\xff\xff\xff\xff'
    b'\xff\xff\xbf\xfe\x01\x8f\xff\x7f\xff\x9f\xff\xff\xff\xff\xff\xff\xff\xfe\xff\xe6\x9f\xff\xef\x3f\xff\x9f\xff\xff\xff\xff\xff\xff'
    b'\xff\xfd\xff\xf7\xef\xff\xff\xbf\xff\xff\xff\xff\xff\xff\xff\xff\xff\xf9\xff\xff\xf7\xff\xff\xdf\xff\xff\xff\xff\xff\xbf\xff\xff'
    b'\xff\xfb\xff\xff\xf9\xff\xff\xff\xff\xff\xff\xff\xff\x0f\xff\xff\xff\xf7\xff\xff\xfe\xff\xff\xff\xff\xff\xff\xff\xff\x0f\xff\xff'
    b'\xff\xf7\xff\xff\xff\xef\xff\xdf\xff\xff\xff\xff\xff\x0f\xff\xff\xff\xf6\x5f\xff\xff\xe0\xff\xbf\xff\xff\xff\xff\x9f\x9f\xff\xff'
    b'\xff\xfe\xcf\xff\xff\xf3\x0e\xff\xff\xff\xff\xff\x87\xff\xff\xff\xff\xfc\xff\xff\xff\xfb\xff\xff\xff\xff\xff\xff\x81\xff\xbf\xff'
    b'\xff\xfd\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\x80\xff\x1f\xff\xff\xfd\xff\xff\xff\xf9\xff\xff\xff\xff\xff\xff\xfc\x1c\x3f\xff'
    b'\xff\xdf\xff\xff\xff\xfd\xff\xff\xff\xff\xff\xff\xfe\x00\x7f\xff\xff\xde\xdf\xff\xff\xfd\xff\xff\xff\xff\xff\xff\xff\x81\xff\xff'
    b'\xff\xfe\xcf\xff\xff\xfe\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xfe\xcf\xff\xff\xfe\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff'
    b'\xff\xff\x5f\xff\xff\xfe\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xef\xff\xff\xff\xfe\xff\xff\xff\xff\xff\xfd\xfe\x1f\xff\xff'
    b'\xff\xe7\xff\xff\xff\xff\xff\xff\xff\xff\xff\xf8\xf0\x07\xff\xff\xff\xf7\xff\xff\xff\xfd\xff\xff\xff\xff\xff\xfc\x01\xe3\xff\xff'
    b'\xff\xf7\xff\xff\xff\xfd\xff\xff\xff\xff\xff\xfe\x07\xf1\xff\xff\xff\xf3\xff\xff\xff\xfd\xff\xff\xff\x9f\xff\xff\xff\xf9\xff\xff'
    b'\xff\xfb\xff\xff\xff\xfd\xff\xff\xff\x9f\xff\xff\xff\xf8\xff\xff\xff\xfb\xff\xff\xff\xfb\xff\xff\xff\x9f\xff\xff\xff\xf9\xff\xff'
    b'\xff\xf9\xff\xff\xff\xf9\xff\xff\xff\x9f\xff\xff\xff\xf1\xff\xff\xff\xfd\xff\xfb\xff\xfb\xff\xff\xff\x9f\xff\xfe\xff\xf9\xff\xff'
    b'\xff\xfd\xff\xc1\xff\xf3\xff\xff\xff\x81\x81\x00\xc2\x7f\xff\xff\xff\xfd\xff\x83\xff\xf7\xff\xff\xff\xff\x80\x00\x02\x7f\xff\xff'
    b'\xff\xfd\xff\x72\x0f\xf7\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xfd\xff\x70\x1f\xef\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff'
    b'\xff\xfd\xfe\x70\x1f\xef\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xfd\xfc\x60\x97\xcd\xff\xff\xff\x88\x10\x01\x00\x1c\xbb\xff'
    b'\xff\xfd\xfc\xc3\x00\x18\xdf\xff\xff\x89\x30\x01\x9f\x39\xbb\xff\xff\xfc\xf8\xc7\x01\x10\x07\xff\xff\x0b\x90\x01\xce\x71\x93\xff'
    b'\xff\xfc\xf9\xe7\x1e\x01\x0f\xff\xff\x09\x32\x09\xe1\xf9\x83\xff\xff\xfe\xff\xff\x3e\x41\xff\xff\xff\x0c\x72\x41\xe1\xf9\xbf\xff'
    b'\xff\xfe\xff\xff\x3d\xf8\xff\xff\xff\x04\x30\x01\x8c\x39\x9f\xff\xff\xff\x7f\xff\x7b\xf0\xff\xff\xff\xdb\xb8\x03\x3f\x3f\x83\xff'
    b'\xff\xff\xbf\xff\xf7\xe0\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\x9f\xff\xdf\xf0\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff'
    b'\xff\xff\xef\xff\x3f\xff\xff\xff\xff\x36\xcc\x93\x26\x4d\x9b\xff\xff\xff\xf2\x70\xff\xff\xff\xff\xff\xff\xfd\x9b\x76\xcd\xdf\xff'
    b'\xff\xff\xff\x8f\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff'
    b'\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff'
    b'\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff'
    b'\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff'),
    128, 64, framebuf.MONO_HLSB)   
    oled.fill(0)
    oled.blit(fb, 0, 0)
    oled.show()
    utime.sleep(3)    
    fb = framebuf.FrameBuffer(bytearray(
    b'\xc0\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x03\x9f\xff\xff\xfe\x7f\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xf9'
    b'\x3f\xff\xff\xfe\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xfc\x7f\xff\xff\xfe\x7f\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xfe'
    b'\x7f\xff\xff\xfe\x7c\x1f\xff\xff\xff\xff\xdf\xbf\xff\xff\xff\xfe\x7f\xff\xff\xfe\x7d\x9f\xff\xff\xff\xff\xdf\xbf\xff\xff\xff\xfe'
    b'\x7e\x03\xe0\x7e\x7d\x9c\x64\xd8\xe1\x0e\x1f\x86\x67\xff\xff\xfe\x7e\x01\x80\x3e\x7c\x19\x30\x12\x67\x6c\x9f\x93\x4f\xff\xff\xfe'
    b'\x7e\x01\x80\x3e\x7d\xfb\xb0\x10\x66\x04\xdf\xb3\x0f\xff\xff\xfe\x7e\x00\x80\x7e\x7d\xf9\x31\x33\xe7\x7c\x9f\x93\x0f\xff\xff\xfe'
    b'\x7e\x01\x80\x7e\x7d\xfc\x79\x38\x67\x0e\x1f\x87\x9f\xff\xff\xfe\x7f\x03\xc0\xfe\x7f\xff\xff\xff\xff\xff\xff\xff\x9f\xff\xff\xfe'
    b'\x7f\xc7\xe1\xfe\x7f\xff\xff\xff\xff\xff\xff\xff\x3f\xff\xff\xfe\x7f\xee\x37\xfe\x7f\xff\xff\xff\xfe\x7f\xff\xff\xff\xff\xfc\xfe'
    b'\x7f\x80\x11\xfe\x7c\x0f\xff\xff\xfe\x7f\xff\xff\xff\xf8\x1c\xfe\x7f\x08\x18\xfe\x7c\x07\xff\xff\xfe\x7f\xff\xff\xff\xf0\x0f\xfe'
    b'\x7f\x3e\x3c\xfe\x7c\xe7\xff\xff\xfe\x7f\xff\xff\xff\xf1\xcf\xfe\x7f\x63\xc2\x7e\x7c\xe7\x07\x0e\x0e\x07\x06\x10\x18\xf1\xcc\xfe'
    b'\x7f\xc1\x81\xfe\x7c\xe6\x26\x66\x46\x26\x26\x10\x99\xf1\xcc\xfe\x7c\x80\x81\x3e\x7c\x0f\xe6\x7e\x66\x62\x66\x73\x99\xf0\x0c\xfe'
    b'\x7c\x80\x81\x1e\x7c\x47\x06\x0e\x66\x72\x06\x73\xc9\xf0\x1c\xfe\x7c\x81\x81\x1e\x7c\xe6\x27\xc6\x66\x72\x7e\x73\xc3\xf1\xfc\xfe'
    b'\x7c\xc3\xc1\x1e\x7c\xe6\x66\x66\x66\x62\x7e\x73\xc3\xf1\xfc\xfe\x7c\xe4\x37\xbe\x7c\xe2\x06\x06\x06\x07\x06\x73\xe3\xf1\xfc\xfe'
    b'\x7f\xf8\x1c\x7e\x7d\xf3\x37\x0e\x0e\xcf\x8e\x73\xe7\xfb\xfc\xfe\x7e\x18\x08\x7e\x7f\xff\xff\xfe\x7f\xff\xff\xff\xe7\xff\xff\xfe'
    b'\x7e\x08\x08\x7e\x7f\xff\xff\xfc\x7f\xff\xff\xff\x8f\xff\xff\xfe\x7f\x08\x10\x7e\x7f\xff\xff\xfe\xff\xff\xff\xff\x9f\xff\xff\xfe'
    b'\x7f\x0c\x30\xfe\x7f\xff\xff\xff\xff\xff\xff\xff\xff\xff\xc3\xfe\x7f\x8f\xf1\xfe\x7f\xff\xff\xff\xff\xff\xff\xff\xff\xff\xc0\xfe'
    b'\x7f\xf8\x1f\xfe\x7f\xff\xff\xff\xff\xff\xff\xff\xff\xff\x80\xfe\x7f\xf8\x0f\xfe\x78\x7f\x07\xf8\x3f\x83\xfc\x1f\xc0\xfe\x03\xfe'
    b'\x7f\xfc\x3f\xfe\x7c\x3e\x21\xe1\x1f\x10\xf0\x87\x88\x78\x03\xfe\x7f\xff\xff\xfe\x7f\x80\xf8\x07\xc0\x7c\x03\xe0\x3e\x01\xc0\xfe'
    b'\x7f\xff\xff\xfe\x7f\xc1\xfe\x1f\xe0\xff\x0f\xf0\x7f\x87\xc3\xfe\x7f\xff\xff\xfe\x7f\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xfe'
    b'\x3f\xff\xff\xfe\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xfc\x9f\xff\xff\xfe\x7f\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xf9'
    b'\xc0\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x03'),
    128, 39, framebuf.MONO_HLSB)
    oled.fill(0)    
    oled.blit(fb, 0, 15)        
    oled.show()
    utime.sleep(delay)    

# 展示歡迎頁
def welcome_show():
    disp.clear()   
    disp.oled.drawtext('歡迎！', 40, 10)
    disp.show()
    utime.sleep(1)
    disp.clear()   
    disp.oled.drawtext('一次搞懂', 25, 10)    
    disp.show()
    utime.sleep(0.5)
    disp.oled.drawtext('教育機器人是什麼', 0, 45)
    disp.show()
    utime.sleep(2)
    disp.clear()
    disp.text20('Mango X2', 22, 5)  
    disp.text20(f'Starter {Ver}', 10, 30)
    disp.show()    
    step=5
    for i in range(10):
        step+=5
        disp.text20('.',(20+step),45)
        disp.show()
        utime.sleep(0.1)       

# 畫出標題
def title():
    disp.clear()
    disp.fill_rect(0,0,128,19,1)
    disp.oled.drawtext('功能選單', 30, 1,1)
    disp.oled.drawtext(str(current_page), 100, 1,1)
    disp.oled.drawtext('/', 108, 1,1)
    disp.oled.drawtext(str(total_page), 116, 1,1)
    disp.show()

# 展示執行程式頁
def exec_page(title,msg='',delay=0):
    global LightPower
    disp.clear()
    disp.fill_rect(0,0,128,19,1)
    disp.oled.drawtext('功能執行中', 30, 1,1)
    disp.oled.drawtext(title, 17, 25)
    disp.text20(msg, 55, 45)
    disp.show()
    utime.sleep(delay)

# 展示功能選擇頁1
def page1(fun):
    global current_page,fun1_name,fun2_name
    current_page=1
    disp.oled.drawtext(str(current_page), 100, 1,1)
    disp.oled.drawtext(f'1、{fun1_name}', 1, 23)
    disp.oled.drawtext(f'2、{fun2_name}', 1, 42)
    disp.show()
    if fun==1:
        selectF1()
    elif fun==2:
        selectF2()

# 展示功能選擇頁2
def page2(fun):
    global current_page,fun3_name,fun4_name
    current_page=2
    disp.oled.drawtext(str(current_page), 100, 1,1)
    disp.oled.drawtext(f'3、{fun3_name}', 1, 23)
    disp.oled.drawtext(f'4、{fun4_name}', 1, 42)
    disp.show()
    if fun==3:
        selectF1()
    elif fun==4:
        selectF2()

# 展示功能選擇頁3        
def page3(fun):
    global current_page,fun5_name,fun6_name
    current_page=3
    disp.oled.drawtext(str(current_page), 100, 1,1)
    disp.oled.drawtext(f'5、{fun5_name}', 1, 23)
    disp.oled.drawtext(f'6、{fun6_name}', 1, 42)
    disp.show()
    if fun==5:
        selectF1()
    elif fun==6:
        selectF2()

# 展示功能選擇頁4
def page4(fun):
    global current_page,fun7_name,fun8_name
    current_page=4
    disp.oled.drawtext(str(current_page), 100, 1,1)
    disp.oled.drawtext(f'7、{fun7_name}', 1, 23)
    disp.oled.drawtext(f'8、{fun8_name}', 1, 42)
    disp.show()
    if fun==7:
        selectF1()
    elif fun==8:
        selectF2()

# 功能選擇(上)
def selectF1():    
    disp.rect(0,40,128,21,0) # Funtion2 Frame hide
    disp.rect(0,20,128,21,1) # Function1 Frame show
    disp.show()
    sound_player.playSong(['C4 0.125'])

# 功能選擇(下)
def selectF2():        
    disp.rect(0,20,128,21,0) # Function1 Frame hide
    disp.rect(0,40,128,21,1) # Funtion2 Frame show
    disp.show()
    sound_player.playSong(['C4 0.125'])

# 選擇下一個功能
def nextFun(OnlyDisplay=False):
    global current_fun
    if OnlyDisplay==False:
        current_fun+=1                
    if current_fun>8:
        current_fun=1        
    if current_fun==1 or current_fun==2:
        page1(current_fun)
        if current_fun==1:
            rgb.rgbClose(rgb.leds)
            rgb.rgbTurnOn(rgb.leds, 0, '#ff0000') 
            #rgb.rgbTurnOn(rgb.leds, 7, '#ffffff')
        elif current_fun==2:
            rgb.rgbClose(rgb.leds)
            rgb.rgbTurnOn(rgb.leds, 1, '#ff6600')
            #rgb.rgbTurnOn(rgb.leds, 6, '#993399')        
    if current_fun==3 or current_fun==4:
        page2(current_fun)
        if current_fun==3:
            rgb.rgbClose(rgb.leds)
            rgb.rgbTurnOn(rgb.leds, 2, '#ffff00')
            #rgb.rgbTurnOn(rgb.leds, 5, '#6600cc')
        elif current_fun==4:
            rgb.rgbClose(rgb.leds)
            rgb.rgbTurnOn(rgb.leds, 3, '#33cc00')
            #rgb.rgbTurnOn(rgb.leds, 4, '#3333ff')
    if current_fun==5 or current_fun==6:
        page3(current_fun)
        if current_fun==5:
            rgb.rgbClose(rgb.leds)
            rgb.rgbTurnOn(rgb.leds, 4, '#3333ff')
            #rgb.rgbTurnOn(rgb.leds, 3, '#33cc00')
        elif current_fun==6:
            rgb.rgbClose(rgb.leds)
            rgb.rgbTurnOn(rgb.leds, 5, '#6600cc')
            #rgb.rgbTurnOn(rgb.leds, 2, '#ffff00')
    if current_fun==7 or current_fun==8:
        page4(current_fun)
        if current_fun==7:
            rgb.rgbClose(rgb.leds)
            rgb.rgbTurnOn(rgb.leds, 6, '#993399')
            #rgb.rgbTurnOn(rgb.leds, 1, '#ff6600')
        elif current_fun==8:
            rgb.rgbClose(rgb.leds)
            rgb.rgbTurnOn(rgb.leds, 7, '#ffffff')
            #rgb.rgbTurnOn(rgb.leds, 0, '#ff0000')        

    print(f'目前選擇功能：{current_fun}')

# 車子向前
def MoveF(T):    
    rgb.rgbClose(rgb.leds)
    rgb.rgbFills(rgb.leds, '#009900')    
    tank.move_forward(MovePower100)
    utime.sleep(T)
    tank.move_stop()
    rgb.rgbClose(rgb.leds)

# 車子向後
def MoveB(T):    
    rgb.rgbClose(rgb.leds)
    rgb.rgbFills(rgb.leds, '#ffffff')
    tank.move_backward(MovePower100)
    utime.sleep(T)
    tank.move_stop()
    rgb.rgbClose(rgb.leds)

# 車子左轉
def TurnL(T):   
    rgb.rgbClose(rgb.leds)
    rgb.rgbTurnOnRange(rgb.leds, 0, 1, '#ffcc33')
    tank.turn_left(MovePower100)
    utime.sleep(T)
    tank.move_stop()
    rgb.rgbClose(rgb.leds)

# 車子右轉
def TurnR(T):    
    rgb.rgbClose(rgb.leds)
    rgb.rgbTurnOnRange(rgb.leds, 6, 7, '#ffcc33')    
    tank.turn_right(MovePower100)
    utime.sleep(T)
    tank.move_stop()
    rgb.rgbClose(rgb.leds)

# 車子左旋
def RotateL(T):    
    rgb.rgbClose(rgb.leds)
    rgb.rgbTurnOnRange(rgb.leds, 0, 3, '#ffcc33')
    tank.rot_left(MovePower100)
    utime.sleep(T)
    tank.move_stop()
    rgb.rgbClose(rgb.leds)

# 車子右旋
def RotateR(T):    
    rgb.rgbClose(rgb.leds)
    rgb.rgbTurnOnRange(rgb.leds, 4, 7, '#ffcc33')    
    tank.rot_right(MovePower100)
    utime.sleep(T)
    tank.move_stop()
    rgb.rgbClose(rgb.leds)

# 車子循線向前
def FollowF():    
    if not tank.direct_equ(tank.FORWARD):
        rgb.rgbClose(rgb.leds)
        rgb.rgbFills(rgb.leds, '#009900')        
        tank.move_forward(MovePower30)

# 車子循線向後
def FollowB():    
    if not tank.direct_equ(tank.BACKWARD):
        rgb.rgbClose(rgb.leds)
        rgb.rgbFills(rgb.leds, '#ffffff')        
        tank.move_backward(MovePower50)

# 車子循線向左
def FollowL():    
    if not tank.direct_equ(tank.LEFT):
        rgb.rgbClose(rgb.leds)
        rgb.rgbTurnOnRange(rgb.leds, 0, 1, '#ffcc33')        
        tank.turn_left(MovePower50)

# 車子循線向右
def FollowR():    
    if not tank.direct_equ(tank.RIGHT):
        rgb.rgbClose(rgb.leds)
        rgb.rgbTurnOnRange(rgb.leds, 6, 7, '#ffcc33')        
        tank.turn_right(MovePower50)

# 判斷是否啟動超聲波避障功能
def SonicDetect():
    global AvoidOn,HitTime
    if AvoidOn == 1:
        SonicVal = dist_sensor.ping()
        HitTime+=0.1
        print(SonicVal,HitTime)
        if SonicVal > 0 and SonicVal < 30: #在避障範圍中
            if not tank.direct_equ(tank.LEFT):
                AvoidHit(0.5)
        elif SonicVal > 29: #在避障範圍外:直行
            if not tank.direct_equ(tank.FORWARD):                
                rgb.rgbClose(rgb.leds)
                tank.move_stop()
                utime.sleep(0.2)
                rgb.rgbFills(rgb.leds, '#009900')                
                tank.move_forward(MovePower100)                
        if HitTime>5:#避障死角卡死預防:5秒無轉向則執行避障
            AvoidHit(1)

# 超聲波避障:執行迴避動作
def AvoidHit(back_time):
    global AvoidOn,HitTime
    rgb.rgbClose(rgb.leds)
    tank.move_stop() #停止
    utime.sleep(0.2)
    rgb.rgbFills(rgb.leds, '#6600cc')                
    tank.move_backward(MovePower70) #後退
    utime.sleep(back_time)
    tank.move_stop()       #停止
    tank.rot_left(MovePower100) #左旋                
    utime.sleep(0.1)
    tank.move_stop()
    HitTime = 0


# 判斷是否啟動二路循跡
def LineFollowerDetect():
    global FollowOn
    if FollowOn == 1:
        R = board.GP12.value()
        L = board.GP13.value()
        if R == 1 and L == 1:
            FollowF()
        elif R == 0 and L == 0:
            FollowB()
        elif R == 1 and L == 0:
            FollowL()
        elif R == 0 and L == 1:
            FollowR()

# 調整彩燈亮度
def setLight():
    global LightPower
    LightPower += 10
    if LightPower > 100:
        LightPower = 10
    rgb.setBrightness(rgb.leds, LightPower)
    selectLightFX()
    
# 調整亮度時展示燈效
def selectLightFX():    
    rgb.rgbClose(rgb.leds)
    rgb.rgbTurnOn(rgb.leds, 0, '#ff0000')
    rgb.rgbTurnOn(rgb.leds, 1, '#ff6600')
    rgb.rgbTurnOn(rgb.leds, 2, '#ffff00')
    rgb.rgbTurnOn(rgb.leds, 3, '#33cc00')
    rgb.rgbTurnOn(rgb.leds, 4, '#3333ff')
    rgb.rgbTurnOn(rgb.leds, 5, '#6600cc')
    rgb.rgbTurnOn(rgb.leds, 6, '#993399')
    rgb.rgbTurnOn(rgb.leds, 7, '#ffffff')
    utime.sleep(1)
    rgb.rgbClose(rgb.leds)

# 調整蜂鳴器音量
def setSoundVol():
    global SoundVol
    SoundVol += 1
    if SoundVol > 5:
        SoundVol = 1
    if SoundVol == 1:
        sound_player.setDuty(1000)
    elif SoundVol == 2:
        sound_player.setDuty(2000)
    elif SoundVol == 3:
        sound_player.setDuty(3000)
    elif SoundVol == 4:
        sound_player.setDuty(4000)
    elif SoundVol == 5:
        sound_player.setDuty(5000)
    for i in range(2):
        try:
        	sound_player.playSong(['B4 0.25','P 0.125'])
        except KeyboardInterrupt:
            break   

# 執行基本功能展示
def Fun1():    
    exec_page(fun1_name)
    MoveF(1)
    MoveB(1)
    TurnL(1)
    TurnR(1)
    RotateL(2)
    RotateR(2)
    rgb.rgbChases(rgb.leds)
    sound_player.playSong(item)
    rgb.rgbRainbow(rgb.leds)
    rgb.rgbClose(rgb.leds)
    title()
    nextFun(True)

# 執行二路循跡
def Fun2():
    global FollowOn
    if FollowOn == 1:
        FollowOn = 0
        tank.move_stop()
        title()
        nextFun(True)
    else:
        FollowOn = 1        
        exec_page('按執行鍵退出','',0) 

# 執行聲波避障
def Fun3():
    global AvoidOn
    if AvoidOn == 1:
        AvoidOn = 0
        tank.move_stop()
        title()
        nextFun(True)
    else:
        AvoidOn = 1
        exec_page('按執行鍵退出','',0)                    

# 執行顯示現在溫度
def Fun4():
    global TempSensor
    data = TempSensor.read_u16() * conversion_factor  
    temperature = 27-(data-0.706)/0.001721
    temp = str(round(temperature,1))+"*C"        
    exec_page(fun4_name,str(temp),3)            
    title()
    nextFun(True)

# 執行彩燈亮度調整
def Fun5():
    global LightPower
    msg=LightPower+10
    if (LightPower+10)>100:        
        msg=10
    exec_page(fun5_name,str(msg),1)    
    setLight()    
    title()
    nextFun(True)

# 執行音量強度調整
def Fun6():
    global SoundVol    
    msg=SoundVol+1
    if (SoundVol+1)>5:        
        msg=1
    exec_page(fun6_name,str(msg),1)    
    setSoundVol()
    title()
    nextFun(True)    

# 執行自訂micropython程式1:p1.py
def Fun7():        
    exec_page(fun7_name,'',1)
    msg=''
    try:
        exec(open("p1.py").read())
    except OSError:
        msg='p1.py執行錯誤'
        exec_page(msg,'',1)
    title()
    nextFun(True)    

# 執行自訂micropython程式2:p2.py
def Fun8():        
    exec_page(fun8_name,'',1)
    msg=''
    try:
        exec(open("p2.py").read())
    except OSError:
        msg='p2.py執行錯誤'
        exec_page(msg,'',1)
    title()
    nextFun(True)    

#中止程式
def break_process():    
    rgb.rgbClose(rgb.leds)
    sound_player.release()

#主程式
def main(): 
    display_logo(disp.oled,3) #展示商標LOGO
    welcome_show() #展示歡迎頁
    title() #畫出標題
    page1(1) #顯示第一頁選單
    rgb.rgbClose(rgb.leds)
    rgb.rgbTurnOn(rgb.leds, 0, '#ff0000') 
    #rgb.rgbTurnOn(rgb.leds, 7, '#ffffff')    
    while True:
        try:
            LineFollowerDetect()
            SonicDetect()                    
            RedBtn()
            ExecBtn()
            utime.sleep(0.1)
        except KeyboardInterrupt:
            break

try:
    main()
except KeyboardInterrupt:
    print("break")
    break_process()