code.py
 1  # SPDX-FileCopyrightText: 2019 Limor Fried for Adafruit Industries
 2  #
 3  # SPDX-License-Identifier: MIT
 4  
 5  """
 6  This example queries the Open Weather Maps site API to find out the current
 7  weather for your location... and display it on a screen!
 8  if you can find something that spits out JSON data, we can display it
 9  """
10  import sys
11  import time
12  import board
13  from adafruit_pyportal import PyPortal
14  cwd = ("/"+__file__).rsplit('/', 1)[0] # the current working directory (where this file is)
15  sys.path.append(cwd)
16  import openweather_graphics  # pylint: disable=wrong-import-position
17  
18  # Get wifi details and more from a secrets.py file
19  try:
20      from secrets import secrets
21  except ImportError:
22      print("WiFi secrets are kept in secrets.py, please add them there!")
23      raise
24  
25  # Use cityname, country code where countrycode is ISO3166 format.
26  # E.g. "New York, US" or "London, GB"
27  LOCATION = "Manhattan, US"
28  
29  # Set up where we'll be fetching data from
30  DATA_SOURCE = "http://api.openweathermap.org/data/2.5/weather?q="+LOCATION
31  DATA_SOURCE += "&appid="+secrets['openweather_token']
32  # You'll need to get a token from openweather.org, looks like 'b6907d289e10d714a6e88b30761fae22'
33  DATA_LOCATION = []
34  
35  
36  # Initialize the pyportal object and let us know what data to fetch and where
37  # to display it
38  pyportal = PyPortal(url=DATA_SOURCE,
39                      json_path=DATA_LOCATION,
40                      status_neopixel=board.NEOPIXEL,
41                      default_bg=0x000000)
42  
43  gfx = openweather_graphics.OpenWeather_Graphics(pyportal.splash, am_pm=True, celsius=False)
44  
45  localtile_refresh = None
46  weather_refresh = None
47  while True:
48      # only query the online time once per hour (and on first run)
49      if (not localtile_refresh) or (time.monotonic() - localtile_refresh) > 3600:
50          try:
51              print("Getting time from internet!")
52              pyportal.get_local_time()
53              localtile_refresh = time.monotonic()
54          except RuntimeError as e:
55              print("Some error occured, retrying! -", e)
56              continue
57  
58      # only query the weather every 10 minutes (and on first run)
59      if (not weather_refresh) or (time.monotonic() - weather_refresh) > 600:
60          try:
61              value = pyportal.fetch()
62              print("Response is", value)
63              gfx.display_weather(value)
64              weather_refresh = time.monotonic()
65          except RuntimeError as e:
66              print("Some error occured, retrying! -", e)
67              continue
68  
69      gfx.update_time()
70      time.sleep(30)  # wait 30 seconds before updating anything again