Below is some code im woking on. It was originally written in Python for a RPi Zero W, but the project is so small and a Pico W would be perfect.
I have very little coding knowledge so its been me finding bits and pieces and testing certain things to see what works, and also using chatgpt to cheat a bit at as well. Im running into a roadbloack with the URL portion, and was wondering if what I'm trying to do is even possible.
The original project is from here https://github.com/prueker/METARMap
The point of the project is to pull data from the aviation weather website and display the data via RGB LEDs and on an OLED screen.
Currently, I'm getting the following error, but cant figure out WHAT the invalid syntax is
Traceback (most recent call last):
File "<stdin>", line 120
SyntaxError: invalid syntax
I have very little coding knowledge so its been me finding bits and pieces and testing certain things to see what works, and also using chatgpt to cheat a bit at as well. Im running into a roadbloack with the URL portion, and was wondering if what I'm trying to do is even possible.
The original project is from here https://github.com/prueker/METARMap
The point of the project is to pull data from the aviation weather website and display the data via RGB LEDs and on an OLED screen.
Currently, I'm getting the following error, but cant figure out WHAT the invalid syntax is
Traceback (most recent call last):
File "<stdin>", line 120
SyntaxError: invalid syntax
Code:
from machine import Pin, I2Cfrom ssd1306 import SSD1306_I2Cfrom oled import Write, GFX, SSD1306_I2Cfrom oled.fonts import ubuntu_mono_15, ubuntu_mono_20from neopixel import Neopixelimport utimeimport networkimport ntptimeimport urequestsimport jsonimport udatetime as datetimeimport displaymetarssid = 'SSID'password = 'password'def connect(): #Connect to WLAN wlan = network.WLAN(network.STA_IF) wlan.active(True) wlan.connect(ssid, password) while wlan.isconnected() == False: print('Waiting for connection...') utime.sleep(1) print(wlan.ifconfig()) WIDTH =128HEIGHT= 64i2c=I2C(0,scl=Pin(17),sda=Pin(16),freq=200000)oled = SSD1306_I2C(WIDTH,HEIGHT,i2c)# NeoPixel Confif #numpix = 50strip = Neopixel(numpix, 0, 28, "GRB")strip.brightness(50)blank = (0,0,0)COLOR_VFR = (255,0,0)# GreenCOLOR_VFR_FADE = (125,0,0)# Green Fade for windCOLOR_MVFR = (0,0,255)# BlueCOLOR_MVFR_FADE = (0,0,125)# Blue Fade for windCOLOR_IFR = (0,255,0)# RedCOLOR_IFR_FADE = (0,125,0)# Red Fade for windCOLOR_LIFR = (0,125,125)# MagentaCOLOR_LIFR_FADE = (0,75,75)# Magenta Fade for windCOLOR_CLEAR = (0,0,0)# ClearCOLOR_LIGHTNING = (255,255,255)# WhiteCOLOR_HIGH_WINDS = (255,255,0) # Yellow # ----- Blink/Fade functionality for Wind and Lightning -----# Do you want the METARMap to be static to just show flight conditions, or do you also want blinking/fading based on current wind conditionsACTIVATE_WINDCONDITION_ANIMATION = True# Set this to False for Static or True for animated wind conditions#Do you want the Map to Flash white for lightning in the areaACTIVATE_LIGHTNING_ANIMATION = True# Set this to False for Static or True for animated Lightning# Fade instead of blinkFADE_INSTEAD_OF_BLINK= True# Set to False if you want blinking# Blinking Windspeed ThresholdWIND_BLINK_THRESHOLD= 15# Knots of windspeed to blink/fadeHIGH_WINDS_THRESHOLD= 25# Knots of windspeed to trigger Yellow LED indicating very High Winds, set to -1 if you don't want to use thisALWAYS_BLINK_FOR_GUSTS= False# Always animate for Gusts (regardless of speeds)# Blinking Speed in secondsBLINK_SPEED= 1.0# Float in seconds, e.g. 0.5 for half a second# Total blinking time in seconds.# For example set this to 300 to keep blinking for 5 minutes if you plan to run the script every 5 minutes to fetch the updated weatherBLINK_TOTALTIME_SECONDS= 300# ----- Daytime dimming of LEDs based on time of day or Sunset/Sunrise -----ACTIVATE_DAYTIME_DIMMING = True# Set to True if you want to dim the map after a certain time of dayBRIGHT_TIME_START= datetime.time(7,0)# Time of day to run at LED_BRIGHTNESS in hours and minutesDIM_TIME_START= datetime.time(19,0)# Time of day to run at LED_BRIGHTNESS_DIM in hours and minutesLED_BRIGHTNESS_DIM= 10# Float from 0.0 (min) to 1.0 (max)# ----- External Display support -----ACTIVATE_EXTERNAL_METAR_DISPLAY = True# Set to True if you want to display METAR conditions to a small external displayDISPLAY_ROTATION_SPEED = 5.0# Float in seconds, e.g 2.0 for two seconds# ----- Show a set of Legend LEDS at the end -----SHOW_LEGEND = True# Set to true if you want to have a set of LEDs at the end show the legend# You'll need to add 7 LEDs at the end of your string of LEDs# If you want to offset the legend LEDs from the end of the last airport from the airports file,# then change this offset variable by the number of LEDs to skip before the LED that starts the legendOFFSET_LEGEND_BY = 1# The order of LEDs is:#VFR#MVFR#IFR#LIFR#LIGHTNING#WINDY#HIGH WINDS# ---------------------------------------------------------------------------# ------------END OF CONFIGURATION-------------------------------------------# ---------------------------------------------------------------------------print("Running metar.py ")# Initialize the LED strip#bright = BRIGHT_TIME_START < datetime.datetime.now().time() < DIM_TIME_STARTprint("Wind animation:" + str(ACTIVATE_WINDCONDITION_ANIMATION))print("Lightning animation:" + str(ACTIVATE_LIGHTNING_ANIMATION))print("Daytime Dimming:" + str(ACTIVATE_DAYTIME_DIMMING) + (" using Sunrise/Sunset" if USE_SUNRISE_SUNSET and ACTIVATE_DAYTIME_DIMMING else ""))print("External Display:" + str(ACTIVATE_EXTERNAL_METAR_DISPLAY))pixels = Neopixel# Read the airports file to retrieve list of airports and use as order for LEDswith open("airports") as f:airports = f.readlines()airports = [x.strip() for x in airports]try:with open("displayairports") as f2:displayairports = f2.readlines()displayairports = [x.strip() for x in displayairports]print("Using subset airports for LED display")# Retrieve METAR from aviationweather.gov data server# Details about parameters can be found here: https://aviationweather.gov/data/api/#/Dataserver/dataserverMetarsurl = "https://aviationweather.gov/cgi-bin/data/dataserver.php?requestType=retrieve&dataSource=metars&stationString=" + ",".join([item for item in airports if item != "NULL"]) + "&hoursBeforeNow=5&format=xml&mostRecent=true&mostRecentForEachStation=constraint"print(url)response = urequests.get(url)content = response.text#req = urequests.request(url, headers={'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.198 Safari/537.36 Edg/86.0.622.69'})#content = urequests.request.urlopen(req).read()# Retrieve flying conditions from the service response and store in a dictionary for each airportroot = ET.fromstring(content)conditionDict = { "NULL": {"flightCategory" : "", "windDir": "", "windSpeed" : 0, "windGustSpeed" : 0, "windGust" : False, "lightning": False, "tempC" : 0, "dewpointC" : 0, "vis" : 0, "altimHg" : 0, "obs" : "", "skyConditions" : {}, "obsTime" : datetime.datetime.now() } }conditionDict.pop("NULL")stationList = []for metar in root.iter('METAR'):stationId = metar.find('station_id').textif metar.find('flight_category') is None:print("Missing flight condition, skipping.")continueflightCategory = metar.find('flight_category').textwindDir = ""windSpeed = 0windGustSpeed = 0windGust = Falselightning = FalsetempC = 0dewpointC = 0vis = 0altimHg = 0.0obs = ""skyConditions = []if metar.find('wind_gust_kt') is not None:windGustSpeed = int(metar.find('wind_gust_kt').text)windGust = (True if (ALWAYS_BLINK_FOR_GUSTS or windGustSpeed > WIND_BLINK_THRESHOLD) else False)if metar.find('wind_speed_kt') is not None:windSpeed = int(metar.find('wind_speed_kt').text)if metar.find('wind_dir_degrees') is not None:windDir = metar.find('wind_dir_degrees').textif metar.find('temp_c') is not None:tempC = int(round(float(metar.find('temp_c').text)))if metar.find('dewpoint_c') is not None:dewpointC = int(round(float(metar.find('dewpoint_c').text)))if metar.find('visibility_statute_mi') is not None:vis_str = metar.find('visibility_statute_mi').textvis_str = vis_str.replace('+', '')vis = int(round(float(vis_str)))if metar.find('altim_in_hg') is not None:altimHg = float(round(float(metar.find('altim_in_hg').text), 2))if metar.find('wx_string') is not None:obs = metar.find('wx_string').textif metar.find('observation_time') is not None:obsTime = datetime.datetime.fromisoformat(metar.find('observation_time').text.replace("Z","+00:00"))for skyIter in metar.iter("sky_condition"):skyCond = { "cover" : skyIter.get("sky_cover"), "cloudBaseFt": int(skyIter.get("cloud_base_ft_agl", default=0)) }skyConditions.append(skyCond)if metar.find('raw_text') is not None:rawText = metar.find('raw_text').textlightning = False if ((rawText.find('LTG', 4) == -1 and rawText.find('TS', 4) == -1) or rawText.find('TSNO', 4) != -1) else Trueprint(stationId + ":" + flightCategory + ":" + str(windDir) + "@" + str(windSpeed) + ("G" + str(windGustSpeed) if windGust else "") + ":"+ str(vis) + "SM:"+ obs + ":"+ str(tempC) + "/"+ str(dewpointC) + ":"+ str(altimHg) + ":"+ str(lightning))conditionDict[stationId] = { "flightCategory" : flightCategory, "windDir": windDir, "windSpeed" : windSpeed, "windGustSpeed": windGustSpeed, "windGust": windGust, "vis": vis, "obs" : obs, "tempC" : tempC, "dewpointC" : dewpointC, "altimHg" : altimHg, "lightning": lightning, "skyConditions" : skyConditions, "obsTime": obsTime }if displayairports is None or stationId in displayairports:stationList.append(stationId)# Start up external display outputdisp = Noneif displaymetar is not None and ACTIVATE_EXTERNAL_METAR_DISPLAY:print("setting up external display")disp = displaymetar.startDisplay()displaymetar.clearScreen(disp)# Setting LED colors based on weather conditionslooplimit = int(round(BLINK_TOTALTIME_SECONDS / BLINK_SPEED)) if (ACTIVATE_WINDCONDITION_ANIMATION or ACTIVATE_LIGHTNING_ANIMATION or ACTIVATE_EXTERNAL_METAR_DISPLAY) else 1windCycle = FalsedisplayTime = 0.0displayAirportCounter = 0numAirports = len(stationList)while looplimit > 0:i = 0for airportcode in airports:# Skip NULL entriesif airportcode == "NULL":i += 1continuecolor = COLOR_CLEARconditions = conditionDict.get(airportcode, None)windy = FalsehighWinds = FalselightningConditions = Falseif conditions != None:windy = True if (ACTIVATE_WINDCONDITION_ANIMATION and windCycle == True and (conditions["windSpeed"] >= WIND_BLINK_THRESHOLD or conditions["windGust"] == True)) else FalsehighWinds = True if (windy and HIGH_WINDS_THRESHOLD != -1 and (conditions["windSpeed"] >= HIGH_WINDS_THRESHOLD or conditions["windGustSpeed"] >= HIGH_WINDS_THRESHOLD)) else FalselightningConditions = True if (ACTIVATE_LIGHTNING_ANIMATION and windCycle == False and conditions["lightning"] == True) else Falseif conditions["flightCategory"] == "VFR":color = COLOR_VFR if not (windy or lightningConditions) else COLOR_LIGHTNING if lightningConditions else COLOR_HIGH_WINDS if highWinds else (COLOR_VFR_FADE if FADE_INSTEAD_OF_BLINK else COLOR_CLEAR) if windy else COLOR_CLEARelif conditions["flightCategory"] == "MVFR":color = COLOR_MVFR if not (windy or lightningConditions) else COLOR_LIGHTNING if lightningConditions else COLOR_HIGH_WINDS if highWinds else (COLOR_MVFR_FADE if FADE_INSTEAD_OF_BLINK else COLOR_CLEAR) if windy else COLOR_CLEARelif conditions["flightCategory"] == "IFR":color = COLOR_IFR if not (windy or lightningConditions) else COLOR_LIGHTNING if lightningConditions else COLOR_HIGH_WINDS if highWinds else (COLOR_IFR_FADE if FADE_INSTEAD_OF_BLINK else COLOR_CLEAR) if windy else COLOR_CLEARelif conditions["flightCategory"] == "LIFR":color = COLOR_LIFR if not (windy or lightningConditions) else COLOR_LIGHTNING if lightningConditions else COLOR_HIGH_WINDS if highWinds else (COLOR_LIFR_FADE if FADE_INSTEAD_OF_BLINK else COLOR_CLEAR) if windy else COLOR_CLEARelse:color = COLOR_CLEARprint("Setting LED " + str(i) + " for " + airportcode + " to " + ("lightning " if lightningConditions else "") + ("very " if highWinds else "") + ("windy " if windy else "") + (conditions["flightCategory"] if conditions != None else "None") + " " + str(color))pixels[i] = colori += 1# Legendif SHOW_LEGEND:pixels[i + OFFSET_LEGEND_BY] = COLOR_VFRpixels[i + OFFSET_LEGEND_BY + 1] = COLOR_MVFRpixels[i + OFFSET_LEGEND_BY + 2] = COLOR_IFRpixels[i + OFFSET_LEGEND_BY + 3] = COLOR_LIFRif ACTIVATE_LIGHTNING_ANIMATION == True:pixels[i + OFFSET_LEGEND_BY + 4] = COLOR_LIGHTNING if windCycle else COLOR_VFR # lightningif ACTIVATE_WINDCONDITION_ANIMATION == True:pixels[i+ OFFSET_LEGEND_BY + 5] = COLOR_VFR if not windCycle else (COLOR_VFR_FADE if FADE_INSTEAD_OF_BLINK else COLOR_CLEAR) # windyif HIGH_WINDS_THRESHOLD != -1:pixels[i + OFFSET_LEGEND_BY + 6] = COLOR_VFR if not windCycle else COLOR_HIGH_WINDS # high winds# Update actual LEDs all at oncepixels.show()# Rotate through airports METAR on external displayif disp is not None:if displayTime <= DISPLAY_ROTATION_SPEED:displaymetar.outputMetar(disp, stationList[displayAirportCounter], conditionDict.get(stationList[displayAirportCounter], None))displayTime += BLINK_SPEEDelse:displayTime = 0.0displayAirportCounter = displayAirportCounter + 1 if displayAirportCounter < numAirports-1 else 0print("showing METAR Display for " + stationList[displayAirportCounter])# Switching between animation cyclesutime.sleep(BLINK_SPEED)windCycle = False if windCycle else Truelooplimit -= 1print()print("Done")
Statistics: Posted by emersonsc — Tue Jan 16, 2024 2:23 am — Replies 1 — Views 403