# Better Raspberry Pi Radio
# (C) 2017 M4rc3lv
import RPi.GPIO as GPIO
import os
import time, shlex, subprocess 

GPIO.setmode(GPIO.BOARD)
CurChannel = 0
# Put here all radio channels. Format: Name, URL (Name will be pronounced by TTS)
Channels = [
   'Radio 1', 'http://icecast.omroep.nl/radio1-sb-mp3', # Radio 1
   'Radio 2', 'http://icecast.omroep.nl/radio2-sb-mp3', # Radio 2
   '3 FM','http://icecast.omroep.nl/3fm-sb-mp3', # 3FM
   'Radio 4','http://icecast.omroep.nl/radio4-sb-mp3', # Radio 4
   'Radio 5','http://icecast.omroep.nl/radio5-sb-mp3', # Radio 5
   'Bay N Err','-playlist http://bnr.cdp.triple-it.nl/playlists/bnr_mp3_96_06.pls', # BNR
   'L 1','-playlist http://icecast.omroep.nl/l1-radio-bb-mp3.m3u', # L1 (Omroep Limburg)   
   #'Studio Brussell','http://mp3.streampower.be/stubru-high.mp3', # Studfio Brussel
   #'Gelderland','http://stream.omroepgelderland.nl/radiogelderland', # Omroep Gelderland
   'Q Music','http://icecast-qmusic.cdp.triple-it.nl/Qmusic_nl_live_96.mp3' # QMusic
]

PIN_A = 5 # CLK Geel
PIN_B = 7 # CLK Oranje

VOL_UP = 38
VOL_DOWN = 40

Last=0
Prev=0

def shutdownRadio(dummy):
    #print "Houdoe"
    #raise SystemExit
    os.system("sudo halt")

def ChangeRadioChannel(up):
    global CurChannel    
    global Channels
    CurChannel=CurChannel + 2*up
    if CurChannel>=len(Channels)-1: CurChannel=0    
    os.system("pkill mplayer");
    os.system('echo "'+Channels[CurChannel]+'" | festival --tts')
    args = shlex.split("mplayer "+Channels[CurChannel+1]+" &")
    subprocess.Popen(args)
    file = open("LastChannel.txt","w")
    file.write(str(CurChannel)+"\n")
    file.close()

def Rot(channel):
    global Last
    global Prev
    
    level = GPIO.input(channel)
    Last = str(channel)+":"+str(level)
    print str(Prev)+" - "+Last
    #if Last<>Prev: ChangeRadioChannel(1)
    if Last=="5:0" and Prev=="7:0": ChangeRadioChannel(1)
    #elif Last=="7:0" and Prev=="7:0":
    #else: ChangeRadioChannel(-1)
    Prev = Last

volume = 50
def VolUp(dummy):
    global volume
    volume = volume + 4
    if volume>=100: volume = 100    
    subprocess.Popen(shlex.split("amixer sset 'PCM' "+str(volume)+"%"))
    file = open("lastvolume.txt","w")
    file.write(str(volume)+"\n") #Store volume in file in order to restore it at the next boot
    file.close()

def VolDown(dummy):
    global volume
    volume = volume - 4
    if volume<=0: volume = 0    
    subprocess.Popen(shlex.split("amixer sset 'PCM' "+str(volume)+"%"))
    file = open("lastvolume.txt","w")
    file.write(str(volume)+"\n")
    file.close()
   
try:
    try:
        # Program start: restore volume
        try:
            file = open("lastvolume.txt","r")
            volume = int(file.read())
            subprocess.Popen(shlex.split("amixer sset 'PCM' "+str(volume)+"%"))
            file.close()
        except: pass

        # Restore current channel
        file = open("LastChannel.txt","r")
        CurChannel = int(file.read())
        file.close()
        os.system('echo "'+Channels[CurChannel]+'" | festival --tts')
        args = shlex.split("mplayer "+Channels[CurChannel+1]+" &")
        subprocess.Popen(args)
    except:        
        CurChannel=0
        ChangeRadioChannel(0)

    GPIO.setup(VOL_UP, GPIO.IN, pull_up_down=GPIO.PUD_UP)
    GPIO.add_event_detect(VOL_UP, GPIO.RISING, callback=VolUp, bouncetime=150)
    GPIO.setup(VOL_DOWN, GPIO.IN, pull_up_down=GPIO.PUD_UP)
    GPIO.add_event_detect(VOL_DOWN, GPIO.RISING, callback=VolDown, bouncetime=150)
    
    GPIO.setup(32, GPIO.IN, pull_up_down=GPIO.PUD_UP)
    GPIO.setup(PIN_A, GPIO.IN) # pull_up_down=GPIO.PUD_UP)
    GPIO.setup(PIN_B, GPIO.IN, pull_up_down=GPIO.PUD_UP)
    GPIO.add_event_detect(32, GPIO.RISING, callback=shutdownRadio, bouncetime=200)

    GPIO.add_event_detect(PIN_A, GPIO.FALLING, callback=Rot)
    GPIO.add_event_detect(PIN_B, GPIO.FALLING, callback=Rot)	    
    while True:
            time.sleep(0.5)
finally:
    GPIO.cleanup()        

