########################################
# WFConnect
# Module to help connect microcontroller to a WiFi Access Point
# Details of the AP are in secrets.py
# 
########################################
from time import sleep
import socket
import network

DEBUG=True

########################################
# Connect to the AP with provided ssid and pwd
########################################
def connectToAP(ssid, pwd):
    # This is not an AP
    ap=network.WLAN(network.AP_IF)
    ap.active(False)
    # ap.disconnect()
    # we need a "Station"
    wlan = network.WLAN(network.STA_IF) # create station interface
    wlan.active(True)       # activate the interface
    wlan.disconnect()  
    if DEBUG:
        print("is connected:"+str(wlan.isconnected()))
        print('Waiting for wifi chip to power up...')
    sleep(2) # wait two seconds for the chip to power up and initialize

    # scan for list of avaiable APs and print them
    #ssidList = wlan.scan()
    #for ssid in ssidList:
    #    print("AP :"+str(ssid))
    while True:
        try:
            if DEBUG:
                print("Connecting to AP :"+ssid+" / "+pwd)      
            wlan.connect(ssid, pwd)
            
            # give it some time to connect
            for y in range(20):
                sleep(2)
                print('.', end='')
                if wlan.isconnected():
                    break

            if wlan.isconnected():
                print('Success! We have connected to your access point!')
                print('Try to ping the device at', wlan.ifconfig()[0])
                break
            else:
                print('Failure! We have not connected to your access point!')

        except Exception as e:
            text = str(e)
            print("There was a problem: "+text)

    if DEBUG:
        print('network config:', wlan.ifconfig())

    return wlan

########################################
# Connect to the AP with provided ssid and pwd
########################################
def OLDconnectToAP(ssid, pwd):
    # This is not an AP
    ap=network.WLAN(network.AP_IF)
    ap.active(False)
    # ap.disconnect()
    # we need a "Station"
    wlan = network.WLAN(network.STA_IF) # create station interface
    wlan.active(True)       # activate the interface
    wlan.disconnect()  
    if DEBUG:
        print("is connected:"+str(wlan.isconnected()))
        print('Waiting for wifi chip to power up...')
    sleep(2) # wait two seconds for the chip to power up and initialize

    # scan for list of avaiable APs and print them
    ssidList = wlan.scan()
    for ssid in ssidList:
        print("AP :"+str(ssid))
    try:
        # try 5 times
        for x in range(5):
            
            if DEBUG:
                print("Connecting to AP :"+ssid+" / "+pwd)      
            wlan.connect(ssid, pwd)
            
            # give it some time to connect
            for y in range(20):
                sleep(2)
                print('.', end='')
                if wlan.isconnected():
                    break

            if wlan.isconnected():
                print('Success! We have connected to your access point!')
                print('Try to ping the device at', wlan.ifconfig()[0])
                break
            else:
                print('Failure! We have not connected to your access point!')

    except Exception as e:
        text = str(e)
        print("There was a problem: "+text)

    if DEBUG:
        print('network config:', wlan.ifconfig())

    return wlan
