import wifi, audio, time, system,  machine, touchpads, sndmixer

vol = machine.nvs_getint('system', 'volume')
if vol == None:
    vol = 255;
    
if not wifi.status():
    audio.play('/cache/system/wifi_connecting.mp3')
    wifi.connect()
    wifi.wait()
    if not wifi.status():
        audio.play('/cache/system/wifi_failed.mp3')
        time.sleep(6)
        system.launcher()
    

url = 'http://62.75.236.17:8004/stream.mp3'
audio.play(url)

# volume control
is_down = False;
def vol_up(is_pressed):
    global vol
    if is_pressed:
        vol += 32
        if vol > 255:
            vol = 255
        setvolume(vol)

def vol_down(is_pressed):
    global vol
    if is_pressed:
        vol -= 32
        if vol < 0:
            vol = 0
        setvolume(vol)
        
def setvolume(volume):
    print(volume)
    for index in audio.handles.keys():
        sndmixer.volume(index, volume)


touchpads.on(touchpads.RIGHT, vol_up)
touchpads.on(touchpads.LEFT, vol_down)