Quantcast
Channel: Raspberry Pi Forums
Viewing all articles
Browse latest Browse all 4906

MicroPython • Re: Will I be able to run this code on MicroPython?

$
0
0
hippy
You were right not to be convinced it was impossible.
Thank you for all your help. Now I can order me a few PicoW's...
And yes, it's been yet another rainy day in the UK!
Oh and I love that I can do all of this on my Pi4 using Thonny - which I've never used before.
I remember having a hell of a game setting up the Arduino IDE (1.8) to work with my ESP32. But Thonny just worked pretty much straight away!

Code:

import networkimport urequests as requestsimport timeimport jsonimport gcdef decodeSWC(swcCode):    if swcCode == -1 : return "Trace rain"    elif swcCode == 0 : return "Clear night"    elif swcCode == 1 : return "Sunny day"    elif swcCode == 2 : return "Partly cloudy (night)"    elif swcCode == 3 : return "Partly cloudy (day)"    elif swcCode == 4 : return "Not used"    elif swcCode == 5 : return "Mist"    elif swcCode == 6 : return "Fog"    elif swcCode == 7 : return "Cloudy"    elif swcCode == 8 : return "Overcast"    elif swcCode == 9 : return "Light rain shower (night)"    elif swcCode == 10 : return "Light rain shower (day)"    elif swcCode == 11 : return "Drizzle"    elif swcCode == 12 : return "Light rain"    elif swcCode == 13 : return "Heavy rain shower (night)"    elif swcCode == 14 : return "Heavy rain shower (day)"    elif swcCode == 15 : return "Heavy rain"    elif swcCode == 16 : return "Sleet shower (night)"    elif swcCode == 17 : return "Sleet shower (day)"    elif swcCode == 18 : return "Sleet"    elif swcCode == 19 : return "Hail shower (night)"    elif swcCode == 20 : return "Hail shower (day)"    elif swcCode == 21 : return "Hail"    elif swcCode == 22 : return "Light snow shower (night)"    elif swcCode == 23 : return "Light snow shower (day)"    elif swcCode == 24 : return "Light snow"    elif swcCode == 25 : return "Heavy snow shower (night)"    elif swcCode == 26: return "Heavy snow shower (day)"    elif swcCode == 27 : return "Heavy snow"    elif swcCode == 28 : return "Thunder shower (night)"    elif swcCode == 29 : return "Thunder shower (day)"    elif swcCode == 30 : return "Thunder"    return "Unknown"def retrieve_forecast(timesteps, requestHeaders, latitude, longitude, excludeMetadata, includeLocation):        base_url = "https://data.hub.api.metoffice.gov.uk/sitespecific/v0/point/"    url = base_url + timesteps     url += "?excludeParameterMetadata=FALSE&includeLocationName=TRUE&latitude=52.2333&longitude=-2.3667"    headers = {'accept': "application/json"}    headers.update(requestHeaders)    params = {        'excludeParameterMetadata' : excludeMetadata,        'includeLocationName' : includeLocation,        'latitude' : latitude,        'longitude' : longitude        }    success = False    retries = 2    while not success and retries >0:        try:            req = requests.get(url, headers=headers)            success = True        except Exception as e:            print("Exception occurred {}", e)            retries -= 1            time.sleep(10)            if retries == 0:                print("Retries exceeded")                sys.exit()    req.encoding = 'utf-8'    print("Length of returned data = {}", len(req.text))        data_dict = json.loads(req.text)    if not isinstance(data_dict, dict) :        print("Not successfully converted into a dictionary - check API key")    else :        location = (data_dict['features'][0]['properties']['location']['name'])        time = []        windSpeed = []        temperature = []        probOfRain = []        swc = []        print("Location found is : {}".format(location))        for hours in range(4) :            time.append(data_dict['features'][0]['properties']['timeSeries'][hours]['time'])            windSpeed.append(data_dict['features'][0]['properties']['timeSeries'][hours]['windSpeed10m'])            temperature.append(data_dict['features'][0]['properties']['timeSeries'][hours]['screenTemperature'])            probOfRain.append(data_dict['features'][0]['properties']['timeSeries'][hours]['probOfPrecipitation'])            swc.append(data_dict['features'][0]['properties']['timeSeries'][hours]['significantWeatherCode'])            print("")            print("{}".format(time[hours]))            print("Temperature              :{} C".format(temperature[hours]))            print("Significant weather code :{}".format(decodeSWC(swc[hours])))            # Convert m/s to mph            print("Windspeed                :{} MPH".format(int(float(windSpeed[hours] * 2.23694))))            print("Probability of rain      :{} %".format(probOfRain[hours]))print("ESP32 : Connecting to router")wlan = network.WLAN(network.STA_IF)wlan.active(True)wlan.connect("MY_SSID", "MY_PASSWORD")while wlan.status() != network.STAT_GOT_IP:  print("  Waiting to connect ...")  time.sleep(1)print("Connected")apikey = MY_MET_OFFICE_APIrequestHeaders = {"apikey": apikey}latitude = 52.2333longitude = -2.3667gc.collect()retrieve_forecast("hourly", requestHeaders, latitude, longitude, False, True)

Statistics: Posted by MarkDH102 — Fri Feb 23, 2024 1:32 pm



Viewing all articles
Browse latest Browse all 4906

Trending Articles