'post.bmp', 'spider.bmp', 'thor.bmp', 'vis.bmp', 'witch.bmp' ] # the current working directory (where this file is) cwd = ("/"+__file__).rsplit('/', 1)[0] pyportal = PyPortal(status_neopixel=board.NEOPIXEL) # pyportal.play_file(audio) # speed up projects with lots of text by preloading the font! pyportal.preload_font() pyportal.set_backlight(1.00) i = 0.001 # disp while True: try: for image in images: pyportal.set_background(image) board.DISPLAY.refresh_soon() board.DISPLAY.wait_for_frame() time.sleep(i) except RuntimeError as e: print("Some error occured, retrying! -", e) time.sleep(0.1)
back_button_group = displayio.Group() social_status_label = label.Label( bitmap_font.load_font("/fonts/Junction-regular-24.bdf"), text="Social Battery", color=0xFFFFFF, x=30, y=30, ) init() while True: touch = pyportal.touchscreen.touch_point if touch: for button in buttons: if button.contains(touch): if button.name == "back": back_button_group.hidden = True button_group.hidden = False social_status_label.hidden = False pyportal.set_background(background_color) if button.name in status_backgrounds: back_button_group.hidden = False button_group.hidden = True social_status_label.hidden = True pyportal.set_background(status_backgrounds[button.name]) pixel_pattern.color = button.fill_color break pixel_pattern.update()
time_str = format_str % (hour, minute) time_textarea.text = time_str if gremlin_since_midnite < mogwai_since_midnite: #print("Gremlin time before mogwai time") if gremlin_since_midnite <= time_since_midnite < mogwai_since_midnite: is_gremlin_time = True else: is_gremlin_time = False else: #print("Mogwai time before gremlin time") if mogwai_since_midnite <= time_since_midnite < gremlin_since_midnite: is_gremlin_time = False else: is_gremlin_time = True if is_gremlin_time != last_gremlin_time: if is_gremlin_time: print("GREMLIN TIME!") pyportal.set_background(gremlin_image) pyportal.play_file(gremlin_sound) else: print("MOGWAI TIME!") pyportal.set_background(mogwai_image) pyportal.play_file(mogwai_sound) last_gremlin_time = is_gremlin_time # update every 10 seconds #time.sleep(10)
import displayio from analogio import AnalogIn from adafruit_pyportal import PyPortal analogin = AnalogIn(board.LIGHT) cwd = ("/" + __file__).rsplit('/', 1)[0] laura = (cwd + "/laura.bmp") woodsman = (cwd + "/woodsman.bmp") gottaLight = (cwd + "/gottaLight.wav") pyportal = PyPortal(default_bg=laura) def getVoltage(pin): # helper return (pin.value * 3.3) / 65536 while True: if getVoltage(analogin) > 0.175: pyportal.set_background(laura) time.sleep(1) else: pyportal.set_background(woodsman) pyportal.play_file(gottaLight) time.sleep(1)
if (not refresh_time) or (time.monotonic() - refresh_time) > 3600: try: print("Getting time from internet!") pyportal.get_local_time() refresh_time = time.monotonic() except RuntimeError as e: print("Some error occured, retrying! -", e) continue now = time.localtime() print("Current time:", now) remaining = time.mktime(event_time) - time.mktime(now) print("Time remaining (s):", remaining) if remaining < 0: # oh, its event time! pyportal.set_background(event_background) while True: # that's all folks pass secs_remaining = remaining % 60 remaining //= 60 mins_remaining = remaining % 60 remaining //= 60 hours_remaining = remaining % 24 remaining //= 24 days_remaining = remaining print("%d days, %d hours, %d minutes and %s seconds" % (days_remaining, hours_remaining, mins_remaining, secs_remaining)) text_areas[0].text = '{:>2}'.format(days_remaining) # set days textarea text_areas[1].text = '{:>2}'.format(hours_remaining) # set hours textarea text_areas[2].text = '{:>2}'.format(mins_remaining) # set minutes textarea
timestamp = time.localtime() now = time.struct_time(( timestamp[0], timestamp[1], timestamp[2], 0, 0, 0, # we don't track seconds -1, -1, False)) # we dont know day of week/year or DST print("Current time:", now) remaining = time.mktime(event_time) - time.mktime(now) print("Time remaining (s):", remaining) if remaining == 0: # oh, its event time! pyportal.set_background(event_background) countdown_text.text = '' pyportal.set_caption('', (13, 215), 0x000000) while True: # that's all folks pass days_remaining = remaining // 86400 print("%d days remaining" % (days_remaining)) countdown_text.text = '{:>3}'.format(days_remaining) pyportal.set_background(backgrounds[random.randint(0, len(backgrounds) - 1)]) # update every minute time.sleep(60)
# S&P 500 ("Market Data") info MARKET_DATA_SOURCE = "https://www.alphavantage.co/query?function=GLOBAL_QUOTE&symbol=INX" MARKET_DATA_SOURCE += "&apikey=" + secrets['alpha_advantage_key'] # Shower thoughts info ST_DATA_SOURCE = "https://www.reddit.com/r/Showerthoughts/new.json?sort=new&limit=1" # Loop through all the applications localtime_refresh = None weather_refresh = None st_refresh = None market_refresh = None while True: # Day, date, and time # only query the online time once per hour (and on first run) pyportal.set_background(cwd + "/day_bitmap.bmp") try: if (not localtime_refresh) or (time.monotonic() - localtime_refresh) > 3600: print("Getting time from internet!") pyportal.get_local_time() localtime_refresh = time.monotonic() text_group = day_graphics.day_graphics(medium_font=medium_font, large_font=large_font) pyportal.splash.append(text_group) # Display for seven seconds, then empty the pyportal.splash group so it can be loaded with new display info time.sleep(linger) except RuntimeError as e: print("Some error occured, skipping this iteration! -", e) continue pyportal.splash.pop()
pyportal = PyPortal(status_neopixel=board.NEOPIXEL, default_bg="/bgs/loading.bmp") time_last_refreshed = None time_remaining = None event_time = time.struct_time((2020, 1, 1, 0, 0, 0, None, None, None)) themes.initialize(pyportal) while True: touched_left, touched_right = touched_sides(pyportal.touchscreen) if touched_left: themes.prev_theme(pyportal) elif touched_right: themes.next_theme(pyportal) if events.should_refresh_time(event_time, time_last_refreshed): time_last_refreshed = events.update_local_time_from_internet( pyportal, debug=True ) time_remaining = events.time_remaining(event_time) days_left, hours_left, mins_left = events.time_periods_in_epoch(time_remaining) themes.current_theme.update_time(days_left, hours_left, mins_left) if time_remaining < 0: print("Event elapsed! Setting event background, sleeping for 1 hour") pyportal.set_background("/bgs/final.bmp") while True: time.sleep(60 * 60) # 1 hour in seconds.
#### END INIT PORTAL #### # Play boot-up sound play_panel_beep(20) # Update device local time and preload the font pyportal.preload_font() pyportal.get_local_time() screen_brightness() #### Primary screen operation loop #### while True: # Primary functions inside exception handler with 1-minute timeout. try: # Run any scheduled activities #run_scheduler(last_metar_time) # When screen is touched: if pyportal.touchscreen.touch_point: play_panel_beep(0) # If a new METAR is scheduled to be obtained if time_for_new_metar(last_metar_time): response = pyportal.fetch() play_panel_beep(2) last_metar_time = time.time() except Exception as e: print("Some error occured, retrying in 1 minute: ", e) pyportal.set_background(error_bg) pyportal.set_text('LCARS', index=2) play_offline_audio() time.sleep(60)
'darksky_key', 'KEYMISSING'), secrets.get('latitude', 0), secrets.get('longitude', 0)) # the current working directory (where this file is) cwd = ("/" + __file__).rsplit('/', 1)[0] pyportal = PyPortal(url=darksky, json_path=[], status_neopixel=board.NEOPIXEL, default_bg=cwd + "/pyportal_startup.bmp") last_weather = 0 last_time = 0 last_flip = 0 pixel_around() pyportal.set_background(cwd + "/pyportal_startup2.bmp") pages = [] pp = displayio.Group(max_size=10, x=0, y=0) pages.append(pp) page = 0 preload = b'0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ-!,.%_ "\'?!\u00b0' # NOQA font1 = bitmap_font.load_font(cwd + "/fonts/Anton-Regular-30.bdf") font1.load_glyphs(preload) font1_height = font1.get_bounding_box()[1] date_label = Label(font1, max_glyphs=30,
bitmap=displayio.Bitmap, palette=displayio.Palette) # ------------- neopixel setup ------------- # pixel = neopixel.NeoPixel(board.NEOPIXEL, 1, brightness=1) WHITE = 0xffffff LITE_WHT = 0x202020 RED = 0xff0000 LITE_RED = 0x400000 GREEN = 0x00ff00 BLUE = 0x0000ff BLACK = 0x000000 # ------------- Setup for Images ------------- # # Display an image until the loop starts pyportal.set_background('/images/risk_board1.bmp') bg_group = displayio.Group(max_size=1) main.append(bg_group) # ------------- Font stuff ------------------- # # Set the font and preload glyphs font16 = bitmap_font.load_font("/fonts/Arial-16.bdf") font16.load_glyphs(b'abcdefghjiklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890- ()') # ------------- Button groups ---------------- # buttons = [] att_buttons = [] def_buttons = [] roll_buttons = [] # ---------- Main view -----------------------------------------------------------------#
### main.cheerlight_text.PyPortal.py """ Minimalist Cheerlight for PyPortal: - Fetch the text API to get color in web format (#FF00FF) - Use PyPortal and set_background to set color cheerlight_text_PyPortal.py """ import time import board from adafruit_pyportal import PyPortal # Set up where we'll be fetching data from DATA_SOURCE = "http://api.thingspeak.com/channels/1417/field/2/last.txt" pyportal = PyPortal(url=DATA_SOURCE, status_neopixel=board.NEOPIXEL) while True: try: value = pyportal.fetch() print("Response is", value) pyportal.set_background(int(value.lstrip("#"), 16)) except RuntimeError as e: print("Some error occured, retrying! -", e) time.sleep(10)
themes.initialize(pyportal) theme_switch_mins = 5 time_last_refreshed = None while True: # Decide if we should refresh the PyPortal's local time from the internet if events.should_refresh_time(event_time, time_last_refreshed): time_last_refreshed = events.update_local_time_from_internet(pyportal) # Get the time remaining until the event days_remaining, hours_remaining, mins_remaining = events.days_hours_mins_to_event(event_time) # Update the display with the time remaining themes.current_theme.update_time(days_remaining, hours_remaining, mins_remaining) # Switch themes occasionally, for the mins defined in theme_switch_mins if mins_remaining % theme_switch_mins == 0: themes.next_theme(pyportal) time.sleep(60) # Sleep for one minute in seconds # If the event has passed, clear the screen and show the event started background if events.event_passed(event_time): print("Event passed! Setting event background, stopping countdown.") pyportal.splash.pop() pyportal.set_background("/bgs/party.bmp") while True: pass
except ValueError: pass def showLayer(show_target): try: time.sleep(0.1) splash.append(show_target) except ValueError: pass # ------------- Setup for Images ------------- # # Display an image until the loop starts pyportal.set_background('/images/loading.bmp') bg_group = displayio.Group() splash.append(bg_group) icon_group = displayio.Group() icon_group.x = 180 icon_group.y = 120 icon_group.scale = 1 view2.append(icon_group) # This will handel switching Images and Icons def set_image(group, filename): """Set the image file for a given goup for display. This is most useful for Icons or image slideshows.
from secrets import secrets from fonts_and_styles import * from display_helpers import * from date_helpers import * print("After Imports -- " + str(gc.mem_free())) # ------------- Inputs and Outputs Setup ------------- # # init. the light sensor light_sensor = AnalogIn(board.LIGHT) # -------------- Screen Setup -------------- # display = board.DISPLAY pyportal = PyPortal(status_neopixel=board.NEOPIXEL) pyportal.set_backlight(0.3) pyportal.set_background('pyportal_startup.bmp') # ----------- Touchscreen setup ----------- # # Rotate 0: ts = adafruit_touchscreen.Touchscreen(board.TOUCH_XL, board.TOUCH_XR, board.TOUCH_YD, board.TOUCH_YU, calibration=((5200, 59000), (5800, 57000)), size=(display.width, display.height)) # ------------- Display Groups ------------- # splash = displayio.Group(max_size=15) # The Main Display Group bg_group = displayio.Group(max_size=5) # The Background Group splash.append(bg_group)
text=format_datetime(event_start), ) pyportal.splash.append(label_event_time) label_event_desc = label.Label( font_events, x=88, y=70 + (event_idx * 40), color=0x000000, text=event_name, line_spacing=0.75, ) pyportal.splash.append(label_event_desc) pyportal.set_background(0xFFFFFF) # Add the header line_header = Line(0, 50, 320, 50, color=0x000000) pyportal.splash.append(line_header) font_h1 = bitmap_font.load_font("fonts/Arial-18.pcf") label_header = label.Label(font_h1, x=10, y=30, color=0x000000) pyportal.splash.append(label_header) # Set up calendar event fonts font_events = bitmap_font.load_font("fonts/Arial-14.pcf") if not google_auth.refresh_access_token(): raise RuntimeError( "Unable to refresh access token - has the token been revoked?")
text_font=cwd + "/fonts/Helvetica-Bold-100.bdf", text_position=(90, 100), text_color=0x000000, # pad caption string so there's room for lat/long later caption_text="Air Quality Index ", caption_font=cwd + "/fonts/HelveticaNeue-24.bdf", caption_position=(15, 220), caption_color=0x000000, ) while True: try: value = pyportal.fetch() print("Response is", value) if 0 <= value <= 50: pyportal.set_background(0x66bb6a) # good if 51 <= value <= 100: pyportal.set_background(0xffeb3b) # moderate if 101 <= value <= 150: pyportal.set_background(0xf39c12) # sensitive if 151 <= value <= 200: pyportal.set_background(0xff5722) # unhealthy if 201 <= value <= 300: pyportal.set_background(0x8e24aa) # very unhealthy if 301 <= value <= 500: pyportal.set_background(0xb71c1c) # hazardous if AVG_LAT and AVG_LONG: pyportal.set_caption( 'AQI for ({0:5.2f}, {1:6.2f})'.format(AVG_LAT, AVG_LONG), (15, 220), 0x000000)
hours_remaining = EVENT_HOUR - the_time[3] if hours_remaining < 0: hours_remaining += 24 # add hours to go forward the_time = time.localtime(time.mktime(the_time) + hours_remaining * 60 * 60) #print("hour fastforward:", the_time) days_remaining = EVENT_WEEKDAY - the_time[6] if days_remaining < 0: days_remaining += 7 total_sec_remaining = days_remaining * 24 * 60 * 60 total_sec_remaining += hours_remaining * 60 * 60 total_sec_remaining += mins_remaining * 60 print("Remaining: %d days, %d hours, %d minutes (%d total seconds)" % (days_remaining, hours_remaining, mins_remaining, total_sec_remaining)) week_of_seconds = 604800 if (week_of_seconds - total_sec_remaining) < EVENT_DURATION: print("ITS HAPPENING!") pyportal.set_background(event_background) else: pyportal.set_background(countdown_background) text_areas[0].text = '{:>1}'.format(days_remaining) # set days textarea text_areas[1].text = '{:>2}'.format(hours_remaining) # set hours textarea text_areas[2].text = '{:>2}'.format(mins_remaining) # set minutes textarea # update every 30 seconds time.sleep(30)
# ------------- Inputs and Outputs Setup ------------- # adt = None # ------------- Screen Setup ------------- # display = board.DISPLAY display.rotation = 270 def set_backlight(val): val = max(0, min(1.0, val)) board.DISPLAY.auto_brightness = False board.DISPLAY.brightness = val # Set the Backlight set_backlight(0.1) pyportal = PyPortal() # Display an image until the loop starts pyportal.set_background('/images/c.bmp') pyportal.get_local_time() outlet = digitalio.DigitalInOut(board.D4) outlet.direction = digitalio.Direction.OUTPUT outlet.value = False refresh_time = None # init. the light sensor light_sensor = AnalogIn(board.LIGHT) pixel = neopixel.NeoPixel(board.NEOPIXEL, 1, brightness=1) WHITE = 0xffffff
print("<><><><> SOME ERROR OCCURRED! -", OSError, e) print("Please restart PyPortal by pressing the Reset button on the back of the device") except RuntimeError as e: print("<><><><> SOME ERROR OCCURRED! -", e) print("Retrying last wget") # pyportal.wget(pyportal.image_converter_url(image_url,320, 240,color_depth=16), directory+fileName, chunk_size=12000) except KeyError as e: print("<><><><> SOME ERROR OCCURRED! -", e) print("Retrying last wget") # pyportal.wget(pyportal.image_converter_url(image_url,320, 240,color_depth=16), directory+fileName, chunk_size=12000) if access_attempts > 3: print("ERROR: cannot resume. Try pressing Update PyPortal in app and rebooting the PyPortal.") break print("Setting background to:", directory+"Home.bmp") pyportal.set_background(directory+"Home.bmp") for screen in screens: print(screen.pageID) print(screen.screenURL) print("Screen can be accessed at", screen.file_location) print("This screen has", len(screen.buttons), "buttons") for index in range(len(screen.buttons)): print(" Button", index, "text =", screen.buttons[index].buttonText) return screens screens = reload_all_data(directory) lastDateChecked = check_last_update() next_check = (CHECK_AFTER_MINUTES * 60) + time.monotonic() print("** Current time.monotoic() = ", time.monotonic())
strip.fill(0) pyportal = PyPortal(default_bg=background_color) buttons = create_buttons() # TODO NZ: Do we want to add the buttons to a group before # adding them to the pyportal splash screen for button in buttons: pyportal.splash.append(button.group) current_color = 0 current_offset = 0 while True: touch = pyportal.touchscreen.touch_point if touch: for button in buttons: if button.contains(touch): if button.name == "green": print("Let's display the full battery image.") pyportal.splash.pop(1) pyportal.splash.pop(1) pyportal.splash.pop(1) pyportal.set_background("images/full.bmp") print("Touched", button.name) current_color = button.fill_color break current_offset = chase_pattern(color=current_color, offset=current_offset) time.sleep(0.05)
refresh_time = time.monotonic() except RuntimeError as e: print("Some error occured, retrying! -", e) continue now = time.localtime() print("Current time:", now) remaining = time.mktime(event_time) - time.mktime(now) print("Time remaining (s):", remaining) if remaining < 0: # oh, the event started! # how much time until the end? remaining = time.mktime(end_time) - time.mktime(now) if remaining < 0: # oh, the event is over! pyportal.set_background(its_over_background) while True: # that's all folks pass else: pyportal.set_background(on_air_background) secs_remaining = remaining % 60 remaining //= 60 mins_remaining = remaining % 60 remaining //= 60 hours_remaining = remaining % 24 remaining //= 24 days_remaining = remaining print("%d days, %d hours, %d minutes and %s seconds" % (days_remaining, hours_remaining, mins_remaining, secs_remaining)) text_areas[0].text = '{:>2}'.format(days_remaining) # set days textarea
except ValueError: pass def showLayer(show_target): try: time.sleep(0.1) splash.append(show_target) except ValueError: pass # ------------- Setup for Images ------------- # # Display an image until the loop starts pyportal.set_background("/images/loading.bmp") bg_group = displayio.Group(max_size=1) splash.append(bg_group) icon_group = displayio.Group(max_size=1) icon_group.x = 180 icon_group.y = 120 icon_group.scale = 1 view2.append(icon_group) # This will handel switching Images and Icons def set_image(group, filename): """Set the image file for a given goup for display. This is most useful for Icons or image slideshows.
for i, filename in enumerate(imagefiles): imagefiles[i] = cwd + "/backgrounds/" + filename print("Image files found: ", imagefiles) pyportal = PyPortal( url=DATA_SOURCE, json_path=TEXT_LOCATION, status_neopixel=board.NEOPIXEL, default_bg=imagefiles[0], text_font=cwd + "/fonts/Arial-Italic-12.bdf", text_position=(25, 20), text_color=0xFFFFFF, text_wrap=35, # character to wrap around text_maxlen=280, # cut off characters ) pyportal.preload_font() while True: response = None try: pyportal.set_background(random.choice(imagefiles)) response = pyportal.fetch() print("Response is", response) except (IndexError, RuntimeError, ValueError) as e: print("Some error occured, retrying! -", e) # next tweet should be random! tweet_idx = random.randint(0, NUM_TWEETS) TEXT_LOCATION[3] = tweet_idx time.sleep(60)
json_path=(BG_VALUE, BG_DIRECTION), status_neopixel=board.NEOPIXEL, default_bg=0xFFFFFF, text_font=cwd + "/fonts/Arial-Bold-24-Complete.bdf", text_position=( (90, 120), # VALUE location (140, 160)), # DIRECTION location text_color=( 0x000000, # sugar text color 0x000000), # direction text color text_wrap=( 35, # characters to wrap for sugar 0), # no wrap for direction text_maxlen=(180, 30), # max text size for sugar & direction text_transform=(text_transform_bg, text_transform_direction), ) # speed up projects with lots of text by preloading the font! pyportal.preload_font(b'mg/dl012345789') pyportal.preload_font((0x2191, 0x2192, 0x2193)) #pyportal.preload_font() while True: try: value = pyportal.fetch() pyportal.set_background(get_bg_color(value[0])) print("Response is", value) except RuntimeError as e: print("Some error occured, retrying! -", e) time.sleep(180)
pyportal.splash.append(timer_text_area) for textarea in ans_text_areas: pyportal.splash.append(textarea) while True: # Load new question when screen is touched while not pyportal.touchscreen.touch_point: pass reveal_text_area.text = '' q_text_area.text = '' for textarea in ans_text_areas: textarea.text = '' timer_text_area.text = '' pyportal.set_background(cwd + "/trivia.bmp") loading_text_area.text = "Loading question..." while True: try: value = pyportal.fetch() break except RuntimeError as e: print("Some error occured, retrying! -", e) continue print("Response is", value) question = value[0] correct_answer = value[1] answers = shuffle(value[1:5]) loading_text_area.text = ''
thor = 'thor.bmp' vis = 'vis.bmp' witch = 'witch.bmp' # the current working directory (where this file is) cwd = ("/"+__file__).rsplit('/', 1)[0] pyportal = PyPortal(status_neopixel=board.NEOPIXEL) # pyportal.play_file(audio) # speed up projects with lots of text by preloading the font! pyportal.preload_font() pyportal.set_backlight(1.00) i = 0.001 # disp pyportal.set_background(a1) board.DISPLAY.refresh_soon() board.DISPLAY.wait_for_frame() time.sleep(i) pyportal.set_background(a2) board.DISPLAY.refresh_soon() board.DISPLAY.wait_for_frame() time.sleep(i) pyportal.set_background(a3) board.DISPLAY.refresh_soon() board.DISPLAY.wait_for_frame() time.sleep(i) pyportal.set_background(a4)