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 youtube API, grab a number like number of views
 7  or subscribers... and display it on a screen
 8  If you can find something that spits out JSON data, we can display it!
 9  
10  Requires a youtube API key!
11  """
12  import time
13  import board
14  from adafruit_pyportal import PyPortal
15  
16  # Get wifi details and more from a secrets.py file
17  try:
18      from secrets import secrets
19  except ImportError:
20      print("WiFi secrets are kept in secrets.py, please add them there!")
21      raise
22  
23  # Set up where we'll be fetching data from
24  CHANNEL_ID = "UCpOlOeQjj7EsVnDh3zuCgsA" # this isn't a secret but you have to look it up
25  #CHANNEL_ID = "UC6p-tjZN8s9GBSbiN4K-bwg"
26  CAPTION = "www.youtube.com/adafruit"
27  #CAPTION = "www.youtube.com/c/JohnParkMakes"
28  
29  # pylint: disable=line-too-long
30  DATA_SOURCE = "https://www.googleapis.com/youtube/v3/channels/?part=statistics&id="+CHANNEL_ID+"&key="+secrets['youtube_token']
31  DATA_LOCATION1 = ["items", 0, "statistics", "viewCount"]
32  DATA_LOCATION2 = ["items", 0, "statistics", "subscriberCount"]
33  # pylint: enable=line-too-long
34  
35  # the current working directory (where this file is)
36  cwd = ("/"+__file__).rsplit('/', 1)[0]
37  pyportal = PyPortal(url=DATA_SOURCE,
38                      json_path=(DATA_LOCATION1, DATA_LOCATION2),
39                      status_neopixel=board.NEOPIXEL,
40                      default_bg=cwd+"/youtube_background.bmp",
41                      text_font=cwd+"/fonts/Collegiate-50.bdf",
42                      text_position=((100, 129), (155, 180)),
43                      text_color=(0xFFFFFF, 0xFFFFFF),
44                      caption_text=CAPTION,
45                      caption_font=cwd+"/fonts/Collegiate-24.bdf",
46                      caption_position=(40, 220),
47                      caption_color=0xFFFFFF)
48  
49  # track the last value so we can play a sound when it updates
50  last_subs = 0
51  
52  while True:
53      try:
54          views, subs = pyportal.fetch()
55          subs = int(subs)
56          views = int(views)
57          print("Subscribers:", subs)
58          print("Views:", views)
59          if last_subs < subs:  # ooh it went up!
60              print("New subscriber!")
61              pyportal.play_file(cwd+"/coin.wav")
62          last_subs = subs
63      except RuntimeError as e:
64          print("Some error occured, retrying! -", e)
65  
66      time.sleep(60)