code.py
 1  # SPDX-FileCopyrightText: 2020 Melissa LeBlanc-Williams 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 eInk Bonnet!
 8  """
 9  
10  import time
11  import urllib.request
12  import urllib.parse
13  import digitalio
14  import busio
15  import board
16  from adafruit_epd.ssd1675 import Adafruit_SSD1675
17  from adafruit_epd.ssd1680 import Adafruit_SSD1680
18  from weather_graphics import Weather_Graphics
19  
20  spi = busio.SPI(board.SCK, MOSI=board.MOSI, MISO=board.MISO)
21  ecs = digitalio.DigitalInOut(board.CE0)
22  dc = digitalio.DigitalInOut(board.D22)
23  rst = digitalio.DigitalInOut(board.D27)
24  busy = digitalio.DigitalInOut(board.D17)
25  
26  # You'll need to get a token from openweathermap.org, looks like:
27  # 'b6907d289e10d714a6e88b30761fae22'
28  OPEN_WEATHER_TOKEN = ""
29  
30  # Use cityname, country code where countrycode is ISO3166 format.
31  # E.g. "New York, US" or "London, GB"
32  LOCATION = "Manhattan, US"
33  DATA_SOURCE_URL = "http://api.openweathermap.org/data/2.5/weather"
34  
35  if len(OPEN_WEATHER_TOKEN) == 0:
36      raise RuntimeError(
37          "You need to set your token first. If you don't already have one, you can register for a free account at https://home.openweathermap.org/users/sign_up"
38      )
39  
40  # Set up where we'll be fetching data from
41  params = {"q": LOCATION, "appid": OPEN_WEATHER_TOKEN}
42  data_source = DATA_SOURCE_URL + "?" + urllib.parse.urlencode(params)
43  
44  # Initialize the Display
45  display = Adafruit_SSD1680(     # Newer eInk Bonnet
46  # display = Adafruit_SSD1675(   # Older eInk Bonnet
47      122, 250, spi, cs_pin=ecs, dc_pin=dc, sramcs_pin=None, rst_pin=rst, busy_pin=busy,
48  )
49  
50  display.rotation = 1
51  
52  gfx = Weather_Graphics(display, am_pm=True, celsius=False)
53  weather_refresh = None
54  
55  while True:
56      # only query the weather every 10 minutes (and on first run)
57      if (not weather_refresh) or (time.monotonic() - weather_refresh) > 600:
58          response = urllib.request.urlopen(data_source)
59          if response.getcode() == 200:
60              value = response.read()
61              print("Response is", value)
62              gfx.display_weather(value)
63              weather_refresh = time.monotonic()
64          else:
65              print("Unable to retrieve data at {}".format(url))
66  
67      gfx.update_time()
68      time.sleep(300)  # wait 5 minutes before updating anything again