def set_background(self, file_or_color, position=None): """The background image to a bitmap file. :param file_or_color: The filename of the chosen background image, or a hex color. :param tuple position: Optional x and y coordinates to place the background at. """ while self._bg_group: self._bg_group.pop() if not position: position = (0, 0) # default in top corner if not file_or_color: return # we're done, no background desired if self._bg_file: self._bg_file.close() if isinstance(file_or_color, str): # its a filenme: self._bg_file = open(file_or_color, "rb") background = displayio.OnDiskBitmap(self._bg_file) self._bg_sprite = displayio.TileGrid( background, pixel_shader=displayio.ColorConverter(), x=position[0], y=position[1], ) elif isinstance(file_or_color, int): # Make a background color fill color_bitmap = displayio.Bitmap(self.display.width, self.display.height, 1) color_palette = displayio.Palette(1) color_palette[0] = file_or_color self._bg_sprite = displayio.TileGrid( color_bitmap, pixel_shader=color_palette, x=position[0], y=position[1], ) else: raise RuntimeError("Unknown type of background") self._bg_group.append(self._bg_sprite) gc.collect()
def set_icon(self, filename): print("Set icon to ", filename) if self._icon_group: self._icon_group.pop() if not filename: return if self._icon_file: self._icon_file.close() self._icon_file = open(filename, "rb") icon = displayio.OnDiskBitmap(self._icon_file) try: self._icon_sprite = displayio.TileGrid( icon, pixel_shader=displayio.ColorConverter()) except TypeError: self._icon_sprite = displayio.TileGrid( icon, pixel_shader=displayio.ColorConverter(), position=(0, 0)) self._icon_group.append(self._icon_sprite) board.DISPLAY.refresh_soon() board.DISPLAY.wait_for_frame()
def show_splash(self): """ Shows the loading screen """ if self.debug: return with open('blinka-pyloton.bmp', 'rb') as bitmap_file: bitmap1 = displayio.OnDiskBitmap(bitmap_file) tile_grid = displayio.TileGrid( bitmap1, pixel_shader=displayio.ColorConverter()) self.loading_group.append(tile_grid) self.display.show(self.loading_group) status_heading = label.Label(font=self.arial16, x=80, y=175, text="Status", color=self.YELLOW) rect = Rect(0, 165, 240, 75, fill=self.PURPLE) self.loading_group.append(rect) self.loading_group.append(status_heading)
def render(self): screen = displayio.Group() screen.append(Rect(0, 0, badge.display.width, 32, fill=0xffffff)) banner_image = displayio.OnDiskBitmap( open("/apps/radio/icon.bmp", "rb")) banner = displayio.TileGrid(banner_image, pixel_shader=displayio.ColorConverter(), x=4, y=-2) screen.append(banner) app_label = label.Label(terminalio.FONT, text="Radio", color=0x0) app_label_group = displayio.Group(scale=2, x=40, y=14) app_label_group.append(app_label) screen.append(app_label_group) controls_group = displayio.Group(scale=2, x=8, y=48) if self.fm is not None: volume_label = label.Label(terminalio.FONT, text="Volume: {}".format( self.fm.volume), color=0xffffff) channel_label = label.Label(terminalio.FONT, text="Station: {} FM".format( self.fm.channel), color=0xffffff, y=16) controls_group.append(volume_label) controls_group.append(channel_label) else: missing_module_label = label.Label( terminalio.FONT, text="FM module missing\n or not working", color=0xffffff) controls_group.append(missing_module_label) screen.append(controls_group) badge.display.show(screen)
def enter(self): self.adjust_backlight_based_on_light(force=True) for ta in self.text_areas: pyportal.splash.append(ta) pyportal.splash.append(self.weather_icon) if snooze_time: if self.snooze_file: self.snooze_file.close() self.snooze_file = open('/icons/zzz.bmp', "rb") icon = displayio.OnDiskBitmap(self.snooze_file) icon_sprite = displayio.TileGrid( icon, pixel_shader=displayio.ColorConverter(), position=(0, 0)) self.snooze_icon.append(icon_sprite) pyportal.splash.append(self.snooze_icon) if alarm_enabled: self.text_areas[1].text = '%2d:%02d' % (alarm_hour, alarm_minute) else: self.text_areas[1].text = ' ' board.DISPLAY.refresh_soon() board.DISPLAY.wait_for_frame()
def set_image(group, filename): """Set the image file for a given goup for display. This is most useful for Icons or image slideshows. :param group: The chosen group :param filename: The filename of the chosen image """ print("Set image to ", filename) if group: group.pop() if not filename: return # we're done, no icon desired image_file = open(filename, "rb") image = displayio.OnDiskBitmap(image_file) try: image_sprite = displayio.TileGrid(image, pixel_shader=displayio.ColorConverter()) except TypeError: image_sprite = displayio.TileGrid(image, pixel_shader=displayio.ColorConverter(), position=(0, 0)) group.append(image_sprite)
def set_image(group, filename): print("Set image to ", filename) if group: group.pop() if not filename: return # we're done, no icon desired try: if image_file: image_file.close except NameError: pass image_file = open(filename, "rb") image = displayio.OnDiskBitmap(image_file) try: image_sprite = displayio.TileGrid( image, pixel_shader=displayio.ColorConverter()) except TypeError: image_sprite = displayio.TileGrid( image, pixel_shader=displayio.ColorConverter(), position=(0, 0)) group.append(image_sprite)
def image_switch(direction): # advance or go back through image list # pylint: disable=global-statement global tab_number # pylint: disable=global-statement global sub_number # pylint: disable=global-statement global image # pylint: disable=global-statement global palette if direction == 0: # right tab_number = (tab_number + 1) % len(screenmap) if direction == 1: # left tab_number = (tab_number - 1) % len(screenmap) if direction == 2: # down sub_number = (sub_number + 1) % len((screenmap[tab_number])) if direction == 3: # up sub_number = (sub_number - 1) % len((screenmap[tab_number])) image = displayio.OnDiskBitmap(screenmap[tab_number][sub_number]) palette = image.pixel_shader screen[0] = displayio.TileGrid(image, pixel_shader=palette)
def set_bitmap(self, candidates): """Find and use a background from among candidates, or else the fallback bitmap""" for i in candidates + self._fallback_bitmap: if i == self._bitmap_filename: return # Already loaded # CircuitPython 6 & 7 compatible try: bitmap_file = open(i, 'rb') except OSError: continue bitmap = displayio.OnDiskBitmap(bitmap_file) self._bitmap_filename = i # Create a TileGrid to hold the bitmap self.tile_grid = displayio.TileGrid( bitmap, pixel_shader=getattr(bitmap, "pixel_shader", displayio.ColorConverter()), ) # # CircuitPython 7+ compatible # try: # bitmap = displayio.OnDiskBitmap(i) # except OSError: # continue # self._bitmap_filename = i # # Create a TileGrid to hold the bitmap # self.tile_grid = displayio.TileGrid( # bitmap, pixel_shader=bitmap.pixel_shader # ) # Add the TileGrid to the Group if len(self.group) == 0: self.group.append(self.tile_grid) else: self.group[0] = self.tile_grid self.tile_grid.x = (160 - bitmap.width) // 2 self.tile_grid.y = self.glyph_height * 2 + max( 0, (96 - bitmap.height) // 2) break
def show_image(filename): # CircuitPython 6 & 7 compatible try: image_file = open(filename, "rb") except OSError: image_file = open("missing.bmp", "rb") odb = displayio.OnDiskBitmap(image_file) face = displayio.TileGrid(odb, pixel_shader=getattr(odb, 'pixel_shader', displayio.ColorConverter())) # # CircuitPython 7+ compatible # try: # odb = displayio.OnDiskBitmap(filename) # except (OSError, ValueError): # odb = displayio.OnDiskBitmap("missing.bmp") # face = displayio.TileGrid(odb, pixel_shader=odb.pixel_shader) backlight.value = False splash.append(face) board.DISPLAY.refresh(target_frames_per_second=60) backlight.value = True
def set_icon(self, filename): """The background image to a bitmap file. :param filename: The filename of the chosen icon """ print("Set icon to ", filename) if self._icon_group: self._icon_group.pop() if not filename: return # we're done, no icon desired if self._icon_file: self._icon_file.close() self._icon_file = open(filename, "rb") icon = displayio.OnDiskBitmap(self._icon_file) self._icon_sprite = displayio.TileGrid( icon, pixel_shader=displayio.ColorConverter(), position=(0, 0)) self._icon_group.append(self._icon_sprite) board.DISPLAY.refresh_soon() board.DISPLAY.wait_for_frame()
def showImage(imageFile): image_file = open(imageFile, "rb") bitmap_contents = displayio.OnDiskBitmap(image_file) tile_grid = displayio.TileGrid( bitmap_contents, pixel_shader=displayio.ColorConverter(), default_tile=0, x=0, # Position relative to its parent group y=0, width=1, # Number of tiles in the grid height=1, # tile_width=500, # Number of tiles * tile size must match BMP size # tile_height=431, # None means auto size the tiles ) group = displayio.Group() group.append(tile_grid) board.DISPLAY.show(group) time.sleep(1) image_file.close()
def set_icon(self, filename): """Sets the background image to a bitmap file. :param filename: The filename of the chosen icon """ print("Set icon to ", filename) if self._icon_group: self._icon_group.pop() if not filename: return # we're done, no icon desired if self._icon_file: self._icon_file.close() self._icon_file = open(filename, "rb") icon = displayio.OnDiskBitmap(self._icon_file) try: self._icon_sprite = displayio.TileGrid( icon, pixel_shader=displayio.ColorConverter()) except TypeError: self._icon_sprite = displayio.TileGrid( icon, pixel_shader=displayio.ColorConverter(), position=(0, 0)) self._icon_group.append(self._icon_sprite)
def build_weather(self): try: forecastdata = self.fetch_forecast() for idx, x in enumerate(forecastdata): if self._debug: print(idx, " ", x[0], " ", str(x[1]), " ", str(x[2])) weather_icon = "/icons/weather/" + x[0] + ".bmp" try: icon_file = open(weather_icon, "rb") except OSError as e: icon_file = open(self._settings["default_weather_icon"], "rb") icon = displayio.OnDiskBitmap(icon_file) icon_sprite = displayio.TileGrid( icon, pixel_shader=displayio.ColorConverter(), x=16 + (idx * 50), y=100) self._display_groups["weather_group"].append(icon_sprite) temp = "H:" + str(x[2]) + "\nL:" + str(x[1]) temp_area = label.Label(terminalio.FONT, text=temp) temp_area.x = 22 + (idx * 50) temp_area.y = 150 self._display_groups["temp_group"].append(temp_area) d = self.get_dayname(self._today + idx) day_area = label.Label(terminalio.FONT, text=d) day_area.x = 22 + (idx * 50) day_area.y = 90 self._display_groups["days_group"].append(day_area) except (ValueError, RuntimeError) as e: self._debug_error_counter += 1 print("Failed to get forecast data, retrying\n", e) self._wifi_client.reset() time.sleep(5)
def load_image(): """ Load an image as a sprite """ # pylint: disable=global-statement global current_frame, current_loop, frame_count, frame_duration while sprite_group: sprite_group.pop() filename = SPRITESHEET_FOLDER + "/" + file_list[current_image] # CircuitPython 6 & 7 compatible bitmap = displayio.OnDiskBitmap(open(filename, "rb")) sprite = displayio.TileGrid( bitmap, pixel_shader=getattr(bitmap, 'pixel_shader', displayio.ColorConverter()), tile_width=bitmap.width, tile_height=matrix.display.height, ) # # CircuitPython 7+ compatible # bitmap = displayio.OnDiskBitmap(filename) # sprite = displayio.TileGrid( # bitmap, # pixel_shader=bitmap.pixel_shader, # tile_width=bitmap.width, # tile_height=matrix.display.height, # ) sprite_group.append(sprite) current_frame = 0 current_loop = 0 frame_count = int(bitmap.height / matrix.display.height) frame_duration = DEFAULT_FRAME_DURATION if file_list[current_image] in FRAME_DURATION_OVERRIDES: frame_duration = FRAME_DURATION_OVERRIDES[file_list[current_image]]
def SovietRoutine(): with open("/soviet.bmp", "rb") as bitmap_file: # Setup the file as the bitmap data source bitmap = displayio.OnDiskBitmap(bitmap_file) # Create a TileGrid to hold the bitmap tile_grid = displayio.TileGrid(bitmap, pixel_shader=displayio.ColorConverter()) # Create a Group to hold the TileGrid group = displayio.Group() # Add the TileGrid to the Group group.append(tile_grid) # Add the Group to the Display display.show(group) while bluetooth_input == 1: TryMoves.resetServo() toTheTsar(0.2) buzzer.duty_cycle = 0 readBluetooth() buzzer.duty_cycle = 2**15
def set_background(self, filename, *, with_fade=True): """The background image to a bitmap file. :param filename: The filename of the chosen background """ print("Set background to", filename) if with_fade: self.backlight_fade(0) if self._background_group: self._background_group.pop() if filename: if self._background_file: self._background_file.close() self._background_file = open(self._gamedirectory + "/" + filename, "rb") background = displayio.OnDiskBitmap(self._background_file) self._background_sprite = displayio.TileGrid( background, pixel_shader=displayio.ColorConverter(), x=0, y=0) self._background_group.append(self._background_sprite) if with_fade: board.DISPLAY.refresh_soon() board.DISPLAY.wait_for_frame() self.backlight_fade(1.0)
def load_image(): """ Load an image as a sprite """ # pylint: disable=global-statement global CURRENT_FRAME, CURRENT_LOOP, FRAME_COUNT, FRAME_DURATION while sprite_group: sprite_group.pop() filename = SPRITESHEET_FOLDER + "/" + file_list[CURRENT_IMAGE] # CircuitPython 6 & 7 compatible bitmap = displayio.OnDiskBitmap(open(filename, "rb")) sprite = displayio.TileGrid( bitmap, pixel_shader=getattr(bitmap, 'pixel_shader', displayio.ColorConverter()), tile_width=bitmap.width, tile_height=matrix.display.height, ) # # CircuitPython 7+ compatible # bitmap = displayio.OnDiskBitmap(filename) # sprite = displayio.TileGrid( # bitmap, # pixel_shader=bitmap.pixel_shader, # tile_width=bitmap.width, # tile_height=matrix.display.height, # ) sprite_group.append(sprite) FRAME_COUNT = int(bitmap.height / matrix.display.height) FRAME_DURATION = DEFAULT_FRAME_DURATION CURRENT_FRAME = 0 CURRENT_LOOP = 0
def IdleRoutine(): with open("/skate.bmp", "rb") as bitmap_file: # Setup the file as the bitmap data source bitmap = displayio.OnDiskBitmap(bitmap_file) # Create a TileGrid to hold the bitmap tile_grid = displayio.TileGrid(bitmap, pixel_shader=displayio.ColorConverter()) # Create a Group to hold the TileGrid group = displayio.Group() # Add the TileGrid to the Group group.append(tile_grid) # Add the Group to the Display display.show(group) for j in range(5): for i in range(len(TryMoves.skate_copy)): move = TryMoves.skate_copy[i] move.limb.angle = move.degree time.sleep(move.duration) readBluetooth() if bluetooth_input is not 4: return with open("/lkick.bmp", "rb") as bitmap_file: # Setup the file as the bitmap data source bitmap = displayio.OnDiskBitmap(bitmap_file) # Create a TileGrid to hold the bitmap tile_grid = displayio.TileGrid(bitmap, pixel_shader=displayio.ColorConverter()) # Create a Group to hold the TileGrid group = displayio.Group() # Add the TileGrid to the Group group.append(tile_grid) # Add the Group to the Display display.show(group) TryMoves.resetServo() for j in range(3): for i in range(len(TryMoves.Move1_copy)): move = TryMoves.Move1_copy[i] move.limb.angle = move.degree time.sleep(move.duration) readBluetooth() if bluetooth_input is not 4: return with open("/wave.bmp", "rb") as bitmap_file: # Setup the file as the bitmap data source bitmap = displayio.OnDiskBitmap(bitmap_file) # Create a TileGrid to hold the bitmap tile_grid = displayio.TileGrid(bitmap, pixel_shader=displayio.ColorConverter()) # Create a Group to hold the TileGrid group = displayio.Group() # Add the TileGrid to the Group group.append(tile_grid) # Add the Group to the Display display.show(group) TryMoves.resetServo() for j in range(5): for i in range(len(TryMoves.wave_copy)): move = TryMoves.wave_copy[i] move.limb.angle = move.degree time.sleep(move.duration) readBluetooth() if bluetooth_input is not 4: return with open("/dab.bmp", "rb") as bitmap_file: # Setup the file as the bitmap data source bitmap = displayio.OnDiskBitmap(bitmap_file) # Create a TileGrid to hold the bitmap tile_grid = displayio.TileGrid(bitmap, pixel_shader=displayio.ColorConverter()) # Create a Group to hold the TileGrid group = displayio.Group() # Add the TileGrid to the Group group.append(tile_grid) # Add the Group to the Display display.show(group) TryMoves.resetServo() for j in range(5): for i in range(len(TryMoves.dab_copy)): move = TryMoves.dab_copy[i] move.limb.angle = move.degree time.sleep(move.duration) readBluetooth() if bluetooth_input is not 4: return with open("/left.bmp", "rb") as bitmap_file: # Setup the file as the bitmap data source bitmap = displayio.OnDiskBitmap(bitmap_file) # Create a TileGrid to hold the bitmap tile_grid = displayio.TileGrid(bitmap, pixel_shader=displayio.ColorConverter()) # Create a Group to hold the TileGrid group = displayio.Group() # Add the TileGrid to the Group group.append(tile_grid) # Add the Group to the Display display.show(group) TryMoves.resetServo() for j in range(5): for i in range(len(TryMoves.turnLeftCopy)): move = TryMoves.turnLeftCopy[i] move.limb.angle = move.degree time.sleep(move.duration) readBluetooth() if bluetooth_input is not 4: return with open("/humping.bmp", "rb") as bitmap_file: # Setup the file as the bitmap data source bitmap = displayio.OnDiskBitmap(bitmap_file) # Create a TileGrid to hold the bitmap tile_grid = displayio.TileGrid(bitmap, pixel_shader=displayio.ColorConverter()) # Create a Group to hold the TileGrid group = displayio.Group() # Add the TileGrid to the Group group.append(tile_grid) # Add the Group to the Display display.show(group) TryMoves.resetServo() for j in range(3): for i in range(len(TryMoves.humpingCopy)): move = TryMoves.humpingCopy[i] move.limb.angle = move.degree time.sleep(move.duration) readBluetooth() if bluetooth_input is not 4: return with open("/right.bmp", "rb") as bitmap_file: # Setup the file as the bitmap data source bitmap = displayio.OnDiskBitmap(bitmap_file) # Create a TileGrid to hold the bitmap tile_grid = displayio.TileGrid(bitmap, pixel_shader=displayio.ColorConverter()) # Create a Group to hold the TileGrid group = displayio.Group() # Add the TileGrid to the Group group.append(tile_grid) # Add the Group to the Display display.show(group) TryMoves.resetServo() for j in range(5): for i in range(len(TryMoves.turnRightCopy)): move = TryMoves.turnRightCopy[i] move.limb.angle = move.degree time.sleep(move.duration) TryMoves.resetServo() readBluetooth()
from adafruit_clue import clue from adafruit_display_text import label import displayio import terminalio import pwmio moist_level = 50 # adjust this value as needed for your plant board.DISPLAY.brightness = 0.8 clue.pixel.fill(0) # turn off NeoPixel clue_display = displayio.Group(max_size=4) # draw the dry plant dry_plant_file = open("dry.bmp", "rb") dry_plant_bmp = displayio.OnDiskBitmap(dry_plant_file) dry_plant_sprite = displayio.TileGrid(dry_plant_bmp, pixel_shader=displayio.ColorConverter()) clue_display.append(dry_plant_sprite) # draw the happy plant on top (so it can be moved out of the way when needed) happy_plant_file = open("happy.bmp", "rb") happy_plant_bmp = displayio.OnDiskBitmap(happy_plant_file) happy_plant_sprite = displayio.TileGrid( happy_plant_bmp, pixel_shader=displayio.ColorConverter()) clue_display.append(happy_plant_sprite) # Create text # first create the group text_group = displayio.Group(max_size=3, scale=3) # Make a label
board.MTX_ADDRC, board.MTX_ADDRD ], clock_pin=board.MTX_CLK, latch_pin=board.MTX_LAT, output_enable_pin=board.MTX_OE) # Associate matrix with a Display to use displayio features DISPLAY = framebufferio.FramebufferDisplay(MATRIX, auto_refresh=False, rotation=0) # Load BMP image, create Group and TileGrid to hold it FILENAME = "wales.bmp" # CircuitPython 6 & 7 compatible BITMAP = displayio.OnDiskBitmap(open(FILENAME, "rb")) TILEGRID = displayio.TileGrid(BITMAP, pixel_shader=getattr(BITMAP, 'pixel_shader', displayio.ColorConverter()), tile_width=BITMAP.width, tile_height=BITMAP.height) # # CircuitPython 7+ compatible # BITMAP = displayio.OnDiskBitmap(FILENAME) # TILEGRID = displayio.TileGrid( # BITMAP, # pixel_shader=BITMAP.pixel_shader, # tile_width=BITMAP.width, # tile_height=BITMAP.height # )
# create MagTag and connect to network try: magtag = MagTag() magtag.network.connect() except (ConnectionError, ValueError, RuntimeError) as e: print("*** MagTag(), Some error occured, retrying! -", e) # Exit program and restart in 1 seconds. magtag.exit_and_deep_sleep(1) # displayio groups group = displayio.Group(max_size=30) tree_group = displayio.Group(max_size=30) circle_group = displayio.Group(max_size=30) # import tree bitmap tree = displayio.OnDiskBitmap(open("/atree.bmp", "rb")) tree_grid = displayio.TileGrid(tree, pixel_shader=displayio.ColorConverter()) # add bitmap to its group tree_group.append(tree_grid) # add tree group to the main group group.append(tree_group) # list of circle positions spots = ((246, 53), (246, 75), (206, 42), (206, 64), (206, 86), (176, 31), (176, 53), (176, 75), (176, 97), (136, 42), (136, 64), (136, 86), (106, 31), (106, 53), (106, 75), (106, 97), (66, 31), (66, 53), (66, 75), (66, 97), (36, 20), (36, 42), (36, 64), (36, 86), (36, 108)) # circles to cover-up bitmap's number ornaments
PRECISION = 2.0 # Lower numbers = more sensitive to steps SAMPLE_INTERVAL = 1.0 / SAMPLE_RATE_HZ FILTER_SIZE = 4 # Number of accelerometer readings to average FILTER_BUF = [0] * FILTER_SIZE FILTER_SUM = 0 # Initial average value FILTER_INDEX = 0 # Current position in sample-averaging buffer # Display BMP image. If this fails, it's not catastrophic (probably just # older CircuitPython) and the code will continue with the step detection. try: import displayio board.DISPLAY.brightness = 0 SCREEN = displayio.Group() board.DISPLAY.show(SCREEN) BITMAP = displayio.OnDiskBitmap(open(IMAGEFILE, 'rb')) SCREEN.append( displayio.TileGrid(BITMAP, pixel_shader=displayio.ColorConverter(), x=0, y=0)) board.DISPLAY.brightness = 1.0 # Turn on display backlight except (ImportError, NameError, AttributeError) as err: pass # Probably earlier CircuitPython; no displayio support # If everything has initialized correctly, turn off the onboard NeoPixel: PIXEL = neopixel.NeoPixel(board.NEOPIXEL, 1, brightness=0) PIXEL.show() # Read initial accelerometer state and assign to various things to start X, Y, Z = ACCEL.acceleration
def tick(self, now): global alarm_armed, snooze_time, update_time, current_time # is the snooze button pushed? Cancel the snooze if so. if not snooze_button.value: if snooze_time: self.snooze_icon.pop() snooze_time = None alarm_armed = False # is snooze active and the snooze time has passed? Transition to alram is so. if snooze_time and ((now - snooze_time) >= snooze_interval): change_to_state('alarm') return # check light level and adjust background & backlight #self.adjust_backlight_based_on_light() # only query the online time once per hour (and on first run) if (not self.refresh_time) or ((now - self.refresh_time) > 3600): logger.debug('Fetching time') try: pyportal.get_local_time(location=secrets['timezone']) self.refresh_time = now except RuntimeError as e: self.refresh_time = now - 3000 # delay 10 minutes before retrying logger.error('Some error occured, retrying! - %s', str(e)) # only query the weather every 10 minutes (and on first run) if (not self.weather_refresh) or (now - self.weather_refresh) > 600: logger.debug('Fetching weather') try: value = pyportal.fetch() weather = json.loads(value) # set the icon/background weather_icon_name = weather['weather'][0]['icon'] try: self.weather_icon.pop() except IndexError: pass filename = "/icons/"+weather_icon_name+".bmp" if filename: if self.icon_file: self.icon_file.close() self.icon_file = open(filename, "rb") icon = displayio.OnDiskBitmap(self.icon_file) try: icon_sprite = displayio.TileGrid(icon, pixel_shader=displayio.ColorConverter(), x=0, y=0) except TypeError: icon_sprite = displayio.TileGrid(icon, pixel_shader=displayio.ColorConverter(), position=(0, 0)) self.weather_icon.append(icon_sprite) temperature = weather['main']['temp'] - 273.15 # its...in kelvin if celcius: temperature_text = '%3d C' % round(temperature) else: temperature_text = '%3d F' % round(((temperature * 9 / 5) + 32)) self.text_areas[2].text = temperature_text self.weather_refresh = now board.DISPLAY.refresh_soon() board.DISPLAY.wait_for_frame() except RuntimeError as e: self.weather_refresh = now - 540 # delay a minute before retrying logger.error("Some error occured, retrying! - %s", str(e)) if (not update_time) or ((now - update_time) > 30): # Update the time update_time = now current_time = time.localtime() time_string = '%02d:%02d' % (current_time.tm_hour,current_time.tm_min) self.text_areas[0].text = time_string board.DISPLAY.refresh_soon() board.DISPLAY.wait_for_frame() # Check if alarm should sound if current_time is not None and not snooze_time: minutes_now = current_time.tm_hour * 60 + current_time.tm_min minutes_alarm = alarm_hour * 60 + alarm_minute if minutes_now == minutes_alarm: if alarm_armed: change_to_state('alarm') else: alarm_armed = alarm_enabled
OFF = (0, 0, 0) RED = (255, 0, 0) YELLOW = (255, 150, 0) GREEN = (0, 255, 0) CYAN = (0, 255, 255) BLUE = (0, 0, 255) PURPLE = (180, 0, 255) display = board.DISPLAY # Open the file with open("/nrelabs-pixels.bmp", "rb") as bitmap_file: # Setup the file as the bitmap data source bitmap = displayio.OnDiskBitmap(bitmap_file) # Create a sprite (tilegrid) tile_grid = displayio.TileGrid(bitmap, pixel_shader=displayio.ColorConverter()) # Create a Group to hold the TileGrid group = displayio.Group() # Add the TileGrid to the Group group.append(tile_grid) # Add the Group to the Display display.show(group) show_rainbow = False blackout()
def __init__(self, display, layout_json): self.json = layout_json if "view_type" not in layout_json: raise MissingTypeError if layout_json["view_type"] != "OnDiskBitmap": raise IncorrectTypeError( "view_type '{}' does not match Layout Class 'Image'".format( layout_json["view_type"])) self._display = display if "attributes" in layout_json: _missing_attrs = [] for attribute in REQUIRED_ATTRIBUTES: if attribute not in layout_json: _missing_attrs.append(attribute) if len(_missing_attrs) > 0: raise MissingRequiredAttributesError( "Missing required attributes: {}".format(_missing_attrs)) _image_filepath = None if "image_file" in layout_json["attributes"]: _image_filepath = layout_json["attributes"]["image_file"] _background_color = None if "background_color" in layout_json["attributes"]: _background_color = int( layout_json["attributes"]["background_color"], 16) _padding_top = 0 if "padding_top" in layout_json["attributes"]: _padding_top = int(layout_json["attributes"]["padding_top"]) _padding_right = 0 if "padding_right" in layout_json["attributes"]: _padding_right = int( layout_json["attributes"]["padding_right"]) _padding_left = 0 if "padding_left" in layout_json["attributes"]: _padding_left = int(layout_json["attributes"]["padding_left"]) _padding_bottom = 0 if "padding_bottom" in layout_json["attributes"]: _padding_bottom = int( layout_json["attributes"]["padding_bottom"]) _padding = 0 if "padding" in layout_json["attributes"]: _padding = int(layout_json["attributes"]["padding"]) f = open(_image_filepath, "rb") odb = displayio.OnDiskBitmap(f) odb_grid = displayio.TileGrid( odb, pixel_shader=displayio.ColorConverter()) group = displayio.Group() odb_grid.x = _padding // 2 odb_grid.y = _padding // 2 _width = odb.width _height = odb.height self.width = _width self.height = _height if _padding and _background_color: # Draw a green background bg_bitmap = displayio.Bitmap(odb.width + _padding, odb.height + _padding, 1) bg_palette = displayio.Palette(1) bg_palette[0] = _background_color _width = bg_bitmap.width _height = bg_bitmap.height bg_sprite = displayio.TileGrid(bg_bitmap, pixel_shader=bg_palette, x=0, y=0) group.append(bg_sprite) _x = 0 if "x" in layout_json["attributes"]: _x = self.keyword_compiler(layout_json["attributes"]["x"], { "WIDTH": _width, "HEIGHT": _height }) _y = 0 if "y" in layout_json["attributes"]: _y = self.keyword_compiler(layout_json["attributes"]["y"], { "WIDTH": _width, "HEIGHT": _height }) group.x = _x group.y = _y group.append(odb_grid) self.on_disk_bitmap = group if "anchor_point" in layout_json["attributes"]: point = layout_json["attributes"]["anchor_point"] self.on_disk_bitmap.anchor_point = (point[0], point[1]) if "anchored_position" in layout_json["attributes"]: pos = layout_json["attributes"]["anchored_position"] self.on_disk_bitmap.anchored_position = (self.keyword_compiler( pos[0]), self.keyword_compiler(pos[1])) self.view = self.on_disk_bitmap else: #default attributes pass
import displayio import adafruit_lis3dh splash = displayio.Group() board.DISPLAY.show(splash) # get all images images = list(filter(lambda x: x.endswith("bmp"), os.listdir("/"))) i = random.randint(0, (len(images) - 1)) # initial image is randomly selected while True: with open(images[i], "rb") as f: print("Image load {}".format(images[i])) try: odb = displayio.OnDiskBitmap(f) except ValueError: print("Image unsupported {}".format(images[i])) del images[i] continue face = displayio.TileGrid(odb, pixel_shader=displayio.ColorConverter()) # Fade up the backlight for b in range(101): board.DISPLAY.brightness = b / 100 time.sleep(0.01) # default (0.01) splash.append(face) # Wait for the image to load. board.DISPLAY.wait_for_frame()
def __init__( self, playlist_file="playlist.json", skin_image="/base_240x320.bmp", skin_config_file="base_config.json", pyportal_titano=False, ): self.SKIN_IMAGE = skin_image self.SKIN_CONFIG_FILE = skin_config_file self.PLAYLIST_FILE = playlist_file # read the skin config data into variable f = open(self.SKIN_CONFIG_FILE, "r") self.CONFIG_DATA = json.loads(f.read()) f.close() if self.PLAYLIST_FILE: try: # read the playlist data into variable f = open(self.PLAYLIST_FILE, "r") self.PLAYLIST = json.loads(f.read()) f.close() except OSError: # file not found self.auto_find_tracks() except ValueError: # json parse error self.auto_find_tracks() else: # playlist file argument was None self.auto_find_tracks() if self.PLAYLIST: try: if len(self.PLAYLIST["playlist"]["files"]) == 0: # valid playlist json data, but no tracks self.auto_find_tracks() except KeyError: self.auto_find_tracks() # initialize clock display self.clock_display = ClockDisplay( text_color=self.CONFIG_DATA["time_color"]) if not pyportal_titano: # standard PyPortal and pynt clock display location # and playlist display parameters self.clock_display.x = 44 self.clock_display.y = 22 _max_playlist_display_chars = 30 _rows = 3 else: # PyPortal Titano clock display location # and playlist display parameters self.clock_display.x = 65 self.clock_display.y = 37 _max_playlist_display_chars = 42 _rows = 4 # initialize playlist display self.playlist_display = PlaylistDisplay( text_color=self.CONFIG_DATA["text_color"], max_chars=_max_playlist_display_chars, rows=_rows, ) if not pyportal_titano: # standard PyPortal and pynt playlist display location self.playlist_display.x = 13 self.playlist_display.y = 234 else: # PyPortal Titano playlist display location self.playlist_display.x = 20 self.playlist_display.y = 354 # set playlist into playlist display self.playlist_display.from_files_list( self.PLAYLIST["playlist"]["files"]) self.playlist_display.current_track_number = 1 # get name of current song self.current_song_file_name = self.PLAYLIST["playlist"]["files"][ self.playlist_display.current_track_number - 1] if not pyportal_titano: # standard PyPortal and pynt max characters for track title _max_chars = 22 else: # PyPortal Titano max characters for track title _max_chars = 29 # initialize ScrollingLabel for track name self.current_song_lbl = scrolling_label.ScrollingLabel( terminalio.FONT, text=self.playlist_display.current_track_title, color=self.CONFIG_DATA["text_color"], max_characters=_max_chars, ) self.current_song_lbl.anchor_point = (0, 0) if not pyportal_titano: # standard PyPortal and pynt track title location self.current_song_lbl.anchored_position = (98, 19) else: # PyPortal Titano track title location self.current_song_lbl.anchored_position = (130, 33) # Setup the skin image file as the bitmap data source self.background_bitmap = displayio.OnDiskBitmap(self.SKIN_IMAGE) # Create a TileGrid to hold the bitmap self.background_tilegrid = displayio.TileGrid( self.background_bitmap, pixel_shader=self.background_bitmap.pixel_shader) # initialize parent displayio.Group super().__init__() # Add the TileGrid to the Group self.append(self.background_tilegrid) # add other UI componenets self.append(self.current_song_lbl) self.append(self.clock_display) self.append(self.playlist_display) # Start playing first track self.current_song_file = open(self.current_song_file_name, "rb") self.decoder = MP3Decoder(self.current_song_file) self.audio = AudioOut(board.SPEAKER) self.audio.play(self.decoder) self.CURRENT_STATE = self.STATE_PLAYING # behavior variables. self._start_time = time.monotonic() self._cur_time = time.monotonic() self._pause_time = None self._pause_elapsed = 0 self._prev_time = None self._seconds_elapsed = 0 self._last_increment_time = 0
def advance(self): """Displays the next image. Returns True when a new image was displayed, False otherwise.""" if self._image_file: self._fade_down() self._group.pop() self._image_file.close() self._image_file = None self._current_image += self.direction # Try and load an OnDiskBitmap until a valid file is found or we run out of options. This # loop stops because we either set odb or reduce the length of _file_list. odb = None while not odb and self._file_list: if 0 <= self._current_image < len(self._file_list): pass elif not self.loop: return False else: image_count = len(self._file_list) if self._current_image < 0: self._current_image += image_count elif self._current_image >= image_count: self._current_image -= image_count self._reorder_images() image_name = self._file_list[self._current_image] self._image_file = open(image_name, "rb") try: odb = displayio.OnDiskBitmap(self._image_file) except ValueError: self._image_file.close() self._image_file = None del self._file_list[self._current_image] if not odb: raise RuntimeError("No valid images") if self._h_align == HorizontalAlignment.RIGHT: self._group.x = self._display.width - odb.width elif self._h_align == HorizontalAlignment.CENTER: self._group.x = round(self._display.width / 2 - odb.width / 2) else: self._group.x = 0 if self._v_align == VerticalAlignment.BOTTOM: self._group.y = self._display.height - odb.height elif self._v_align == VerticalAlignment.CENTER: self._group.y = round(self._display.height / 2 - odb.height / 2) else: self._group.y = 0 try: sprite = self._sprite_class( odb, pixel_shader=displayio.ColorConverter()) except TypeError: sprite = self._sprite_class( odb, pixel_shader=displayio.ColorConverter(), position=(0, 0)) self._group.append(sprite) if hasattr(self._display, "refresh"): self._display.refresh() self._fade_up() self._img_start = time.monotonic() return True
import pulseio from adafruit_lsm6ds.lsm6ds33 import LSM6DS33 from adafruit_lsm6ds import AccelRange, AccelHPF, Rate from adafruit_display_text import label import displayio import terminalio button_a = DigitalInOut(board.BUTTON_A) button_a.direction = Direction.INPUT button_a.pull = Pull.UP splash = displayio.Group(max_size=3) # draw the bad egg! begg_file = open("broken_egg.bmp", "rb") begg_bmp = displayio.OnDiskBitmap(begg_file) begg_sprite = displayio.TileGrid(begg_bmp, pixel_shader=displayio.ColorConverter()) splash.append(begg_sprite) # draw the good egg on top gegg_file = open("good_egg.bmp", "rb") gegg_bmp = displayio.OnDiskBitmap(gegg_file) gegg_sprite = displayio.TileGrid(gegg_bmp, pixel_shader=displayio.ColorConverter()) splash.append(gegg_sprite) # Draw a label text_group = displayio.Group(max_size=1, scale=2, x=10, y=220) text = "Current & Max Acceleration" text_area = label.Label(terminalio.FONT, text=text, color=0x0000FF)