code.py
 1  # SPDX-FileCopyrightText: 2019 Limor Fried for Adafruit Industries
 2  #
 3  # SPDX-License-Identifier: MIT
 4  
 5  """
 6  This example will access the coindesk API, grab a number like bitcoin value in
 7  USD, multiply it by your # of bitcoins and display it on a screen
 8  If you can find something that spits out JSON data, we can display it!
 9  """
10  import time
11  import board
12  from adafruit_pyportal import PyPortal
13  
14  # You can display in 'GBP', 'EUR' or 'USD'
15  CURRENCY = 'USD'
16  NUM_BITCOINS = 3.14    # how many bitcoins to display
17  # Set up where we'll be fetching data from
18  DATA_SOURCE = "https://api.coindesk.com/v1/bpi/currentprice.json"
19  DATA_LOCATION = ['bpi', CURRENCY, 'rate_float']
20  
21  # We will convert the value from coindesk into a string that calculates our
22  # total bitcoin value!
23  def text_transform(val):
24      format_str = "{:,.2f} Bitcoins\n = {:,d}"
25      if CURRENCY == 'USD':
26          format_str = "{:,.2f} Bitcoins\n = ${:,d}"
27      if CURRENCY == 'EUR':
28          format_str = "{:,.2f} Bitcoins\n = €{:,d}"
29      if CURRENCY == 'GBP':
30          format_str = "{:,.2f} Bitcoins\n = £{:,d}"
31      return format_str.format(NUM_BITCOINS, int(val*NUM_BITCOINS))
32  
33  # the current working directory (where this file is)
34  cwd = ("/"+__file__).rsplit('/', 1)[0]
35  pyportal = PyPortal(url=DATA_SOURCE, json_path=DATA_LOCATION,
36                      status_neopixel=board.NEOPIXEL,
37                      default_bg=cwd+"/bitcoin_background.bmp",
38                      text_font=cwd+"/fonts/Arial-BoldItalic-12-Complete.bdf",
39                      text_position=(192, 130),
40                      text_color=0x0,
41                      text_transform=text_transform)
42  pyportal.preload_font()  # preload alphanums
43  pyportal.preload_font((0x00A3, 0x20AC)) # preload gbp/euro symbol
44  
45  while True:
46      try:
47          value = pyportal.fetch()
48          print("Response is", value)
49      except (ValueError, RuntimeError, ConnectionError, OSError) as e:
50          print("Some error occured, retrying! -", e)
51  
52      time.sleep(3*60)  # wait 3 minutes