## Reference
# https://www.filipeflop.com/blog/como-conectar-a-raspberry-pi-pico-ao-wifi-com-esp8266/
import machine
import utime
import json
 
# Put your network information here
ssid = "Wokwi-GUEST"
password = ""
 
# Put here the latitude and longitude of your city
latitude = '-23.63283'
longitude = '-46.692355'
 
# Switch to True to show commands and responses
debug = True
 
# Start the UART
uart0 = machine.UART(0, baudrate=115200, rxbuf=10000)
 
# Read a line terminated by \n
def leResp(uart=uart0, timeout=2000, ignoreVazias=True):
    resp = b""
    try:
        limit = utime.ticks_ms()+timeout
        while utime.ticks_ms() < limit:
            if uart.any():
                c = uart.read(1)
                if c == b'\r': # ignore \r
                    continues
                if c == b'\n':
                    if resp != b"" or not ignoreEmpty:
                        break
                else:
                    resp = resp+c
        if debug:
            print("RESP: "+resp.decode())
        return resp.decode()
    except Exception as e:
        if debug:
            print(e)
        return ""
     
# Send a command to ESP-01 and read the response
def sendCmdESP(cmd, uart=uart0, timeout=2000):
    if debug:
        print("CMD: "+cmd)
    uart.write(cmd+"\r\n")
    leResp(timeout=timeout) # command echo
    return leResp(timeout=timeout)
 
# send data
def sendDadosESP(data, uart=uart0, timeout=2000):
    tam = len(data)
    if sendCmdESP("AT+CIPSEND="+str(tam), timeout=timeout) == "OK":
        uart.write(data)
        while True:
            resp = leResp(timeout=timeout)
            if resp == 'SEND OK':
                return True
            if resp == 'ERROR':
                return False
            if resp == 'SEND FAIL':
                return False
            if resp == '':
                return False
    else:
        return False
 
# Read HTTP response
def leRespHTTP(uart=uart0, timeout=10000):
    leResp(ignoraVazias=False, timeout=timeout)
    while not leResp(ignoraVazias=False, timeout=timeout) == "":
        pass
    resp = ""
    while True:
        r = leResp(ignoraVazias=False, timeout=500)
        resp = resp+r
        if r == "":
            return resp
 
# Test if communication OK
def testESP(uart=uart0):
    resp = sendCmdESP("AT")
    return resp == "OK"
 
# Connect to WiFi network
def connectWiFi(uart=uart0):
    # Put in Station mode
    if not sendCmdESP("AT+CWMODE=1") == "OK":
        print("Error putting in Station mode")
        return False
    # Trigger connection
    if not sendCmdESP('AT+CWJAP="'+ssid+'","'+password+'"',
                       timeout=10000) == "WIFI CONNECTED":
        print("Unexpected response")
        return False
    if not leResp(timeout=10000) == "WIFI GOT IP":
        print("Error requesting IP")
        return False
    return leResp() == "OK"
 
# Query the API
def queryTime(uart=uart0):
    # Connect to website
    ip = '167.99.8.254'
    if not sendCmdESP('AT+CIPSTART="TCP","'+ip+'",80',
                       timeout=10000) == "CONNECT":
        print("Error connecting to website")
        return None
    leResp() # Read "OK"
    # Send the request
    url = '/bin/civillight.php?lon='+longitude+'&lat='+latitude+ \
        '&output=json'
    if not sendESPData('GET '+url+ \
        ' HTTP/1.1\r\nHost: www.7timer.info\r\n\r\n'):
        print("Error sending request")
        return None
    # Read the answer
    resp = leRespHTTP(timeout=10000)
    try:
        return json.loads(resp)
    except JSONDecodeError:
        print("Answer in incorrect format")
        return None
 
# Dictionary to translate the forecast
forecasts = {
    'clear': 'clear',
    'mcloudy': 'partly cloudy',
    'cloudy': 'cloudy',
    'rain': 'rain',
    'snow': 'snow',
    'ts': 'storm',
    'tsrain': 'storm with rain'
    }
 
# Main Program
print()
print('----------------------------------')
if not testESP():
    print("ESP not responding correctly!")
print("Connecting to network...")
if connectWiFi():
    print("ESP connected to network")
    print("Checking the weather forecast...")
    resp = queryTime()
    if (not resp is None) and ('dataseries' in resp):
        date = str(resp['dataseries'][0]['date'])
        print('Date: '+date[6:8]+'/'+date[4:6]+'/'+date[0:4])
        forecast = resp['dataseries'][0]['weather']
        if forecast in forecasts:
            prediction = predictions[forecast]
        print('Forecast: '+forecast)

utime.sleep(5)
BOOTSELLED1239USBRaspberryPiPico©2020RP2-8020/21P64M15.00TTT
Loading
esp-01