import digitalio
import displayio
import framebufferio
import microcontroller
import sharpdisplay
import terminalio

try:
    import usb_hid
except ImportError:
    usb_hid = None

# Initialize the display, cleaning up after a display from the previous
# run if necessary
displayio.release_displays()
framebuffer = sharpdisplay.SharpMemoryFramebuffer(board.SPI(), board.RX, 400,
                                                  240)
display = framebufferio.FramebufferDisplay(framebuffer, auto_refresh=False)


def extraprec(add=8, num=0, den=1):
    def inner(fn):
        def wrapper(*args, **kw):
            with localcontext() as ctx:
                ctx.prec = ctx.prec + add + (ctx.prec * num + den - 1) // den
                result = fn(*args, **kw)
            return +result

        return wrapper

    return inner
Example #2
0
# SPDX-License-Identifier: MIT

import digitalio
import board

from adafruit_rgb_display.rgb import color565
import adafruit_rgb_display.st7789 as st7789

# Configuration for CS and DC pins for Raspberry Pi
cs_pin = digitalio.DigitalInOut(board.CE0)
dc_pin = digitalio.DigitalInOut(board.D25)
reset_pin = None
BAUDRATE = 64000000  # The pi can be very fast!
# Create the ST7789 display:
display = st7789.ST7789(
    board.SPI(),
    cs=cs_pin,
    dc=dc_pin,
    rst=reset_pin,
    baudrate=BAUDRATE,
    height=240,
    y_offset=80,
)

backlight = digitalio.DigitalInOut(board.D22)
backlight.switch_to_output()
backlight.value = True
buttonA = digitalio.DigitalInOut(board.D23)
buttonB = digitalio.DigitalInOut(board.D24)
buttonA.switch_to_input()
buttonB.switch_to_input()
Example #3
0
Supported products:
  * Adafruit 2.13" Black and White FeatherWing
    * https://www.adafruit.com/product/4195
  """

import time
import board
import displayio
import adafruit_ssd1675

displayio.release_displays()

epd_cs = board.D9
epd_dc = board.D10

display_bus = displayio.FourWire(board.SPI(),
                                 command=epd_dc,
                                 chip_select=epd_cs,
                                 baudrate=1000000)
time.sleep(1)

display = adafruit_ssd1675.SSD1675(display_bus,
                                   width=250,
                                   height=122,
                                   rotation=90)

g = displayio.Group()

f = open("/display-ruler.bmp", "rb")

pic = displayio.OnDiskBitmap(f)
Example #4
0
CONFIG_FILE_LOCATION = u'webapp/inputs/HWconfig.json'
SYSTEM_CONF = None

try:
    with open(CONFIG_FILE_LOCATION, 'r') as conf_file:
        SYSTEM_CONF = json.load(conf_file)
except FileNotFoundError:
    print(
        f'Unable to find config file @ {CONFIG_FILE_LOCATION}. Skipping hardware check...'
    )

has_gpio_pins = ON_RASPI or ON_JETSON

if has_gpio_pins:
    SPI_BUS = board.SPI()
    I2C_BUS = board.I2C()
    RPI_PIN_ALIAS = {
        '2': board.D2,
        '3': board.D3,
        '4': board.D4,
        '5': board.D5,
        '6': board.D6,
        '7': board.D7,
        '8': board.D8,
        '9': board.D9,
        '10': board.D10,
        '11': board.D11,
        '12': board.D12,
        '13': board.D13,
        '14': board.D14,
# Previously measured raw calibration tuple for
#   display coordinate mode (RAW_DATA = False):
CALIBRATION = ((357, 3812), (390, 3555))

# A collection of colors used for graphic objects
BLUE_DK = 0x000060  # Screen fill
RED = 0xFF0000  # Boundary
WHITE = 0xFFFFFF  # Text

# Release any resources currently in use for the displays
displayio.release_displays()

# Define the display's SPI bus connection
disp_bus = displayio.FourWire(
    board.SPI(), command=board.D10, chip_select=board.D9, reset=None
)

# Instantiate the 2.4" 320x240 TFT FeatherWing (#3315).
display = ILI9341(disp_bus, width=320, height=240)
_touch_flip = (False, False)

"""# Instantiate the 3.5" 480x320 TFT FeatherWing (#3651).
display = HX8357(disp_bus, width=480, height=320)
_touch_flip = (False, True)"""

# Check rotation value and update display.
# Always set rotation before instantiating the touchscreen.
if DISPLAY_ROTATION is not None and DISPLAY_ROTATION in (0, 90, 180, 270):
    display.rotation = DISPLAY_ROTATION
else:
    def __init__(self,
                 measurements,
                 headers=None,
                 filename=None,
                 use_SD=True,
                 spi=None,
                 SD_CS=None):
        """__init__
        :param int measurements: The number of different measurements that will be taken per reading.
        :param list headers: A list of strings of headers for the different measurements. List length must be equal to `measurements`. If None, headers will not be used.
        :param string filename: Filename of the log. Defaults to `log.txt` if none is supplied.
        :param bool use_SD: Whether to write to the SD card or the local filesystem. Defaults to SD.
        :param spi: A supplied spi bus. Creates it's own if none is supplied. Only used if `use_SD` is `True`.
        :param SD_CS: The SD card's chip select pin. if none is supplied, it will try the inbuilt `board.SD_CS`
        """

        self.reading_no = 0
        self.num_measurements = 0

        if headers:
            assert (
                measurements == len(headers)
            ), "The number of headers must equal the number of different measurements"

            self.num_measurements = measurements

            self.headers = ["Reading no"] + headers

        if filename:
            self.filename = filename
        else:
            self.filename = "log.txt"

        import storage

        if use_SD:
            import adafruit_sdcard, digitalio

            if spi:
                self.spi = spi
            else:
                import board
                self.spi = board.SPI()

            if SD_CS:
                self.SD_CS = SD_CS
            else:
                import board
                try:
                    self.SD_CS = board.SD_CS
                except AttributeError:
                    raise AttributeError(
                        "Your board does not have a built in SD card, please supply the chip select pin for the SD card of the addon board"
                    )

            self.sdcard = adafruit_sdcard.SDCard(
                self.spi, digitalio.DigitalInOut(self.SD_CS))
            self.vfs = storage.VfsFat(self.sdcard)
            storage.mount(self.vfs, "/sd")

            self.filepath = "/sd/" + self.filename

        else:
            #print("WARNING!! This will not work unless you have set up boot.py to mount the filesystem as rw, see https://learn.adafruit.com/circuitpython-essentials/circuitpython-storage")

            try:
                storage.remount("/")

                self.filepath = "/" + self.filename
            except RuntimeError as e:
                raise RuntimeError(
                    str(e) +
                    "\nLocal filesystem logging will only work when CIRCUITPY is not mounted by a computer"
                )  # will only work once running a release after https://github.com/adafruit/circuitpython/commit/8e8eb07

        try:
            with open(self.filepath, "r") as f:
                # check if continuing last log or starting a new one
                firstline = f.readline().split(",")
                for index, value in enumerate(firstline):
                    firstline[index] = value.strip()
                if firstline == self.headers or firstline[0] == "0":
                    for line in f:
                        if line != "\n":
                            lastline = line
                    lastline = lastline.split(",")
                    self.reading_no = int(lastline[0]) + 1
                    self.num_measurements = len(lastline) - 1
                    newfileneeded = False
                else:
                    from os import rename
                    rename(self.filepath, self.filepath + ".old")
                    newfileneeded = True

        except OSError as e:
            if e.args[0] == 2:
                # no such file
                newfileneeded = True

            elif e.args[0] == 30:
                # read only fs
                raise RuntimeError(
                    "The filesystem has been mounted as read only")

        if newfileneeded:
            with open(self.filepath, "w") as f:
                if headers:
                    f.write(', '.join(str(x) for x in self.headers))
                    f.write("\n")
Example #7
0
"""
Example of library usage receiving commands via an
nRF24L01 transceiver to control a Mecanum drivetrain.
"""
import board
from digitalio import DigitalInOut as Dio
from circuitpython_nrf24l01 import RF24
from drivetrain import Mecanum, BiMotor, NRF24L01rx

# instantiate transceiver radio on the SPI bus
nrf = RF24(board.SPI(), Dio(board.D5), Dio(board.D4))

# instantiate motors for a Mecanum drivetrain in the following order
# Front-Right, Rear-Right, Rear-Left, Front-Left
motors = [
    BiMotor([board.RX, board.TX]),
    BiMotor([board.D13, board.D12]),
    BiMotor([board.D11, board.D10]),
    BiMotor([board.D2, board.D7])
    ]
# NOTE there are no more PWM pins available

# instantiate receiving object for a Mecanum drivetrain
d = NRF24L01rx(nrf, Mecanum(motors))

while True: # this runs forever
    d.sync()
# doing a keyboard interupt will most likely leave the SPI bus in an
# undesirable state. You must do a hard-reset of the circuitoython MCU to
# reset the SPI bus for continued use. This code assumes power is lost on exit.
import board
import digitalio as dio
# if running this on a ATSAMD21 M0 based board
# from circuitpython_nrf24l01.rf24_lite import RF24
from circuitpython_nrf24l01.rf24 import RF24

# addresses needs to be in a buffer protocol object (bytearray)
address = [b"1Node", b"2Node"]

# change these (digital output) pins accordingly
ce = dio.DigitalInOut(board.D4)
csn = dio.DigitalInOut(board.D5)

# using board.SPI() automatically selects the MCU's
# available SPI pins, board.SCK, board.MOSI, board.MISO
spi = board.SPI()  # init spi bus object

# initialize the nRF24L01 on the spi bus object
nrf = RF24(spi, csn, ce)
nrf.dynamic_payloads = False  # the default in the TMRh20 arduino library

# set the Power Amplifier level to -12 dBm since this test example is
# usually run with nRF24L01 transceivers in close proximity
nrf.pa_level = -12

# change this variable to oppose the corresponding variable in the
# TMRh20 library's GettingStarted_HandlingData.ino example
radioNumber = True


# Create a data structure for transmitting and receiving data
import digitalio
import board

from adafruit_rgb_display.rgb import color565
import adafruit_rgb_display.st7789 as st7789

# Configuration for CS and DC pins for Raspberry Pi
cs_pin = digitalio.DigitalInOut(board.CE0)
dc_pin = digitalio.DigitalInOut(board.D25)
reset_pin = None
BAUDRATE = 64000000  # The pi can be very fast!
# Create the ST7789 display:
display = st7789.ST7789(board.SPI(),
                        cs=cs_pin,
                        dc=dc_pin,
                        rst=reset_pin,
                        baudrate=BAUDRATE,
                        width=135,
                        height=240,
                        x_offset=53,
                        y_offset=40)

backlight = digitalio.DigitalInOut(board.D22)
backlight.switch_to_output()
backlight.value = True
buttonA = digitalio.DigitalInOut(board.D23)
buttonB = digitalio.DigitalInOut(board.D24)
buttonA.switch_to_input()
buttonB.switch_to_input()

# Main loop:
Example #10
0
	def __init__(self, rowcount = NO_OF_ROWS, rowlength = ROW_LENGTH, rotation = 90):
		self.Event = threading.Event()
		self.threadLock = threading.Lock()
		threading.Thread.__init__(self, name='mytft')
		self.q = Queue(maxsize=12)
		self.rowcount = rowcount+1
		self.rowlength = rowlength
		self.last_prog_row = LAST_PROG_ROW
		self.rotation = rotation

		# Setup which pins we are using to control the hardware display
		if protoboard:
		# These are for the 2.2" tft soldered onto proto board.
			cs_pin = digitalio.DigitalInOut(board.CE0)
			dc_pin = digitalio.DigitalInOut(board.D18)		
			reset_pin = digitalio.DigitalInOut(board.D23)	
		else:				# wired tft
			cs_pin = digitalio.DigitalInOut(board.CE0)
			dc_pin = digitalio.DigitalInOut(board.D17)		
			reset_pin = digitalio.DigitalInOut(board.D23)

		# Setup SPI bus using hardware SPI:
		spi = board.SPI()
		self.disp = ili9341.ILI9341(spi, rotation=0,cs=cs_pin, dc=dc_pin, rst=reset_pin, baudrate=BAUDRATE)
		if self.disp.rotation % 180 == 90:
			height = self.disp.width   # we swap height/width to rotate it to landscape!
			width = self.disp.height
		else:
			width = self.disp.width   # we swap height/width to rotate it to landscape!
			height = self.disp.height

		self.image = Image.new("RGB", (width, height)) 	# Draw and text
		self.draw = ImageDraw.Draw(self.image)				# Get drawing object to draw on image.
		# Load a TTF Font
		self.big_font = ImageFont.truetype("/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf", BIGFONTSIZE)
		self.time_font = ImageFont.truetype("/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf", SMALLFONTSIZE)

#		self.disp = TFT.ILI9341(DC, rst=RST, spi=SPI.SpiDev(SPI_PORT, SPI_DEVICE, max_speed_hz=64000000))
#		self.disp.begin()
#		self.disp.clear()	# black
		self.old_text = [' ' for i in range(self.rowcount)]	# used for clearing oled text
#		self.font = ImageFont.load_default()
#		self.font = ImageFont.truetype('binary/morningtype.ttf',FONTSIZE)
#		self.font = ImageFont.truetype('binary/secrcode.ttf',FONTSIZE)
#		self.font = ImageFont.truetype('binary/DS-DIGI.TTF',FONTSIZE)
#		self.font = [ImageFont.load_default() for i in range(self.rowcount)]
#		self.fontsize = [DEFAULT_FONT_SIZE for i in range(self.rowcount)]
#		self.fontsize[BIG_ROW] = 36
#		if TESTING:
#			self.fontsize[2] = 24
#			self.fontsize[3] = 24
#		for i in range(self.rowcount):
#			self.font[i] = ImageFont.truetype(FONT_DIR+'Hack-Regular.ttf',self.fontsize[i])
		# setup row colours
		self.rowcolour = [WHITE for i in range(self.rowcount)]			# set the defaults
		self.rowcolour[0] = YELLOW
#		self.rowcolour[self.rowcount-1] = BLUE
#		self.calc_offsets()
#		GPIO.setmode(GPIO.BCM)
#		GPIO.setup(LED,GPIO.OUT)
#		pi_pwm=GPIO.PWM(LED,100)		# pin number, frquency
#		pi_pwm.start(100)				# duty cycle
#		GPIO.setup(L_BUTTON, GPIO.IN, pull_up_down = GPIO.PUD_UP)
#		GPIO.setup(R_BUTTON, GPIO.IN, pull_up_down = GPIO.PUD_UP)
		self.myalarm = alarm.Alarm()
		self.mypwm = pwm.PWM()
		self.mysystem = system.System()
def main():
    """Abstract main() into a function. Normally exits after execution.

    A function abstracting the main code in the module, which
    allows it to be used for libraries as well as testing (i.e., it can be
    called as a script for testing or imported as a library, without
    modification).
    """
    # Create the I2C interface.
    i2c = busio.I2C(SCL, SDA)
 
    cs_pin = digitalio.DigitalInOut(board.CE0)
    dc_pin = digitalio.DigitalInOut(board.D25)
    reset_pin = None
    BAUDRATE = 6400000

    disp = st7789.ST7789(
        board.SPI(),
        cs=cs_pin,
        dc=dc_pin,
        rst=reset_pin,
        baudrate=BAUDRATE,
        width=135,
        height=240,
        x_offset=53,
        y_offset=40,
    )

    height = disp.width
    width = disp.height
    image = Image.new("RGB", (width, height))
    rotation = 90
    
    # Get drawing object to draw on image.
    draw = ImageDraw.Draw(image)
 
    # Draw a black filled box to clear the image.
    draw.rectangle((0, 0, width, height), outline=0, fill=(0,0,0))
    disp.image(image, rotation)

    padding = -2
    top = padding
    bottom = height - padding

    x = 0
 
    font = ImageFont.truetype("/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf", 20)
 
    # Create array named difference with size 4 elements all with value 0
    difference = [0] * 4
 
    while True:
        # Draw a black filled box to clear the image.
        draw.rectangle((0, 0, width, height), outline=0, fill=0)
 
        try:
            oldstats = newstats
        except:
            print("[!] Starting i2c device")
 
        try:
            newstats = getStats()
        except Exception as e:
            print("[!] Error retrieving stats; website most likely denied request. Reattempting in 60 seconds")
            time.sleep(60)
            try:
                newstats = getStats()
            except Exception as e:
                print("[!] Error retrieving second time; waiting 2m50s then running again")
                time.sleep(150)
                continue

        try:
            difference[0] += (int(re.sub("\D", "", newstats[0])) - int(re.sub("\D", "", oldstats[0])))
            difference[1] += (int(re.sub("\D", "", newstats[1])) - int(re.sub("\D", "", oldstats[1])))
            difference[2] += (int(re.sub("\D", "", newstats[2])) - int(re.sub("\D", "", oldstats[2])))
            difference[3] += (int(re.sub("\D", "", newstats[3])) - int(re.sub("\D", "", oldstats[3])))
 
        except Exception as e:
            print("[!] Variable old stats does not exist yet; most likely first run")
        try:
            y = top
            draw.text((x, y), "US C:" + "{:>7}".format(newstats[0]) + " (+" + str(difference[0]) + ")", font=font, fill="#FFFFFF")
            y += font.getsize("US")[1]

            draw.text((x, y), "US D:" + "{:>7}".format(newstats[1]) + " (+" + str(difference[1]) + ")", font=font, fill="#FFFF00")
            y += font.getsize("US")[1]

            draw.text((x, y), "WW C:" + "{:>7}".format(newstats[2]) + " (+" + str(difference[2]) + ")", font=font, fill="#00FF00")
            y += font.getsize("WW")[1]

            draw.text((x, y), "WW D:" + "{:>7}".format(newstats[3]) + " (+" + str(difference[3]) + ")", font=font, fill="#FF00FF")
        except Exception as e:
            print("[!] Error:", e)
            continue
 
        # Display image.
        disp.image(image, rotation)
        print("[*] Updated stats at:", datetime.datetime.now())
        time.sleep(300)
# Testing nRF24L01 Functionality
#   for use in the Sparkfun Pro Micro RP2040 board
#
# [email protected]
# Date Created:  April 17th, 2021
# Last Modified: April 17th, 2021

# Import modules
import board, digitalio, struct, time # circuitpython built-ins
from circuitpython_nrf24l01.rf24 import RF24
print("Finished importing modules")

# Initialize nRF24L01
ce = digitalio.DigitalInOut(board.D5)
csn = digitalio.DigitalInOut(board.D21)
spi = board.SPI() # init spi bus w/ pins D[20,22,23]
nrf = RF24(spi, csn, ce)
irq = digitalio.DigitalInOut(board.D6) # optional IRQ pin to listen to interupts
irq.switch_to_input()  # make sure its an input object

# NOTE the the custom ACK payload feature will be enabled
# automatically when you call load_ack() passing:
# a buffer protocol object (bytearray) of
# length ranging [1,32]. And pipe number always needs
# to be an int ranging [0, 5]

# to enable the custom ACK payload feature
nrf.ack = True  # False disables again

# set the Power Amplifier level to -12 dBm since this test example is
# usually run with nRF24L01 transceivers in close proximity
    y_data[1][1].append(swp_mem.used / 1e9)

#==| User Config |========================================================
#pylint: enable=bad-continuation

# Setup X data storage
x_time = [x * REFRESH_RATE for x in range(HIST_SIZE)]
x_time.reverse()

# Setup Y data storage
y_data = [ [deque([None] * HIST_SIZE, maxlen=HIST_SIZE) for _ in plot['line_config']]
           for plot in PLOT_CONFIG
         ]

# Setup display
disp = ili9341.ILI9341(board.SPI(), baudrate = 24000000,
                       cs  = digitalio.DigitalInOut(board.D4),
                       dc  = digitalio.DigitalInOut(board.D5),
                       rst = digitalio.DigitalInOut(board.D6))

# Setup plot figure
plt.style.use('dark_background')
fig, ax = plt.subplots(2, 1, figsize=(disp.width / 100, disp.height / 100))

# Setup plot axis
ax[0].xaxis.set_ticklabels([])
for plot, a in enumerate(ax):
    # add grid to all plots
    a.grid(True, linestyle=':')
    # limit and invert x time axis
    a.set_xlim(min(x_time), max(x_time))
Example #14
0
"""Simple test script for 2.13" 212x104 monochrome display.

Supported products:
  * Adafruit Flexible 2.13" Monochrome
    * https://www.adafruit.com/product/4243
  """

import time
import board
import displayio
import adafruit_il0373

displayio.release_displays()

# This pinout works on a Feather M4 and may need to be altered for other boards.
spi = board.SPI()  # Uses SCK and MOSI
epd_cs = board.D9
epd_dc = board.D10
epd_reset = board.D5
epd_busy = board.D6

display_bus = displayio.FourWire(spi,
                                 command=epd_dc,
                                 chip_select=epd_cs,
                                 reset=epd_reset,
                                 baudrate=1000000)
time.sleep(1)

display = adafruit_il0373.IL0373(display_bus,
                                 width=212,
                                 height=104,
import board
import displayio

# Release any previously configured displays
displayio.release_displays()

# Setup SPI bus
spi_bus = board.SPI()

# Digital pins to use
tft_cs = board.D10
tft_dc = board.D9

# Setup the display bus
display_bus = displayio.FourWire(spi_bus, command=tft_dc, chip_select=tft_cs)

# Setup the initialization sequence
# stolen from adafruit_ili9341.py
INIT_SEQUENCE = (
    b"\x01\x80\x80"  # Software reset then delay 0x80 (128ms)
    b"\xEF\x03\x03\x80\x02"
    b"\xCF\x03\x00\xC1\x30"
    b"\xED\x04\x64\x03\x12\x81"
    b"\xE8\x03\x85\x00\x78"
    b"\xCB\x05\x39\x2C\x00\x34\x02"
    b"\xF7\x01\x20"
    b"\xEA\x02\x00\x00"
    b"\xc0\x01\x23"  # Power control VRH[5:0]
    b"\xc1\x01\x10"  # Power control SAP[2:0];BT[3:0]
    b"\xc5\x02\x3e\x28"  # VCM control
    b"\xc7\x01\x86"  # VCM control2
Example #16
0

#==| User Config |========================================================
#pylint: enable=bad-continuation

# Setup X data storage
x_time = [x * REFRESH_RATE for x in range(HIST_SIZE)]
x_time.reverse()

# Setup Y data storage
y_data = [[
    deque([None] * HIST_SIZE, maxlen=HIST_SIZE) for _ in plot['line_config']
] for plot in PLOT_CONFIG]

# Setup display
disp = ili9341.ILI9341(board.SPI(),
                       baudrate=24000000,
                       cs=digitalio.DigitalInOut(board.D4),
                       dc=digitalio.DigitalInOut(board.D5),
                       rst=digitalio.DigitalInOut(board.D6))

# Setup plot figure
plt.style.use('dark_background')
fig, ax = plt.subplots(2, 1, figsize=(disp.width / 100, disp.height / 100))

# Setup plot axis
ax[0].xaxis.set_ticklabels([])
for plot, a in enumerate(ax):
    # add grid to all plots
    a.grid(True, linestyle=':')
    # limit and invert x time axis
Example #17
0
    def __init__(
        self,
        *,
        url=None,
        headers=None,
        json_path=None,
        regexp_path=None,
        convert_image=True,
        default_bg=0x000000,
        status_neopixel=None,
        text_font=terminalio.FONT,
        text_position=None,
        text_color=0x808080,
        text_wrap=False,
        text_maxlen=0,
        text_transform=None,
        text_scale=1,
        json_transform=None,
        image_json_path=None,
        image_resize=None,
        image_position=None,
        image_dim_json_path=None,
        caption_text=None,
        caption_font=None,
        caption_position=None,
        caption_color=0x808080,
        image_url_path=None,
        success_callback=None,
        esp=None,
        external_spi=None,
        debug=False,
        secrets_data=None,
    ):

        graphics = Graphics(
            default_bg=default_bg,
            debug=debug,
        )

        self._default_bg = default_bg

        if external_spi:  # If SPI Object Passed
            spi = external_spi
        else:  # Else: Make ESP32 connection
            spi = board.SPI()

        if image_json_path or image_url_path:
            if debug:
                print("Init image path")
            if not image_position:
                image_position = (0, 0)  # default to top corner
            if not image_resize:
                image_resize = (
                    self.display.width,
                    self.display.height,
                )  # default to full screen

        network = Network(
            status_neopixel=status_neopixel,
            esp=esp,
            external_spi=spi,
            extract_values=False,
            convert_image=convert_image,
            image_url_path=image_url_path,
            image_json_path=image_json_path,
            image_resize=image_resize,
            image_position=image_position,
            image_dim_json_path=image_dim_json_path,
            debug=debug,
            secrets_data=secrets_data,
        )

        self.url = url

        super().__init__(
            network,
            graphics,
            url=url,
            headers=headers,
            json_path=json_path,
            regexp_path=regexp_path,
            json_transform=json_transform,
            success_callback=success_callback,
            debug=debug,
        )

        # Convenience Shortcuts for compatibility
        self.peripherals = Peripherals(spi,
                                       display=self.display,
                                       splash_group=self.splash,
                                       debug=debug)
        self.set_backlight = self.peripherals.set_backlight
        self.sd_check = self.peripherals.sd_check
        self.play_file = self.peripherals.play_file

        self.image_converter_url = self.network.image_converter_url
        self.wget = self.network.wget
        # pylint: disable=invalid-name
        self.show_QR = self.graphics.qrcode
        self.hide_QR = self.graphics.hide_QR
        # pylint: enable=invalid-name

        if hasattr(self.peripherals, "touchscreen"):
            self.touchscreen = self.peripherals.touchscreen
        if hasattr(self.peripherals, "mouse_cursor"):
            self.mouse_cursor = self.peripherals.mouse_cursor
        if hasattr(self.peripherals, "cursor"):
            self.cursor = self.peripherals.cursor

        # show thank you and bootup file if available
        for bootscreen in ("/thankyou.bmp", "/pyportal_startup.bmp"):
            try:
                os.stat(bootscreen)
                for i in range(100, -1, -1):  # dim down
                    self.set_backlight(i / 100)
                    time.sleep(0.005)
                self.set_background(bootscreen)
                try:
                    self.display.refresh(target_frames_per_second=60)
                except AttributeError:
                    self.display.wait_for_frame()
                for i in range(100):  # dim up
                    self.set_backlight(i / 100)
                    time.sleep(0.005)
                time.sleep(2)
            except OSError:
                pass  # they removed it, skip!

        try:
            self.peripherals.play_file("pyportal_startup.wav")
        except OSError:
            pass  # they deleted the file, no biggie!

        if default_bg is not None:
            self.graphics.set_background(default_bg)

        if self._debug:
            print("Init caption")
        if caption_font:
            self._caption_font = self._load_font(caption_font)
        self.set_caption(caption_text, caption_position, caption_color)

        if text_font:
            if text_position is not None and isinstance(
                    text_position[0], (list, tuple)):
                num = len(text_position)
                if not text_wrap:
                    text_wrap = [0] * num
                if not text_maxlen:
                    text_maxlen = [0] * num
                if not text_transform:
                    text_transform = [None] * num
                if not isinstance(text_scale, (list, tuple)):
                    text_scale = [text_scale] * num
            else:
                num = 1
                text_position = (text_position, )
                text_color = (text_color, )
                text_wrap = (text_wrap, )
                text_maxlen = (text_maxlen, )
                text_transform = (text_transform, )
                text_scale = (text_scale, )
            for i in range(num):
                self.add_text(
                    text_position=text_position[i],
                    text_font=text_font,
                    text_color=text_color[i],
                    text_wrap=text_wrap[i],
                    text_maxlen=text_maxlen[i],
                    text_transform=text_transform[i],
                    text_scale=text_scale[i],
                )
        else:
            self._text_font = None
            self._text = None

        gc.collect()
Example #18
0
    # https://learn.adafruit.com/circuitpython-display-support-using-displayio/display-and-display-bus
    display = board.DISPLAY

else:
    print("Starting external display")  # goes to serial only
    # Setup the LCD display with driver
    # You may need to change this to match the display driver for the chipset
    # used on your display
    from adafruit_ili9341 import ILI9341

    # from adafruit_st7789 import ST7789

    displayio.release_displays()

    # setup the SPI bus
    spi = board.SPI()
    tft_cs = board.D9  # arbitrary, pin not used
    tft_dc = board.D10
    tft_backlight = board.D12
    tft_reset = board.D11

    while not spi.try_lock():
        spi.configure(baudrate=32000000)
    spi.unlock()

    display_bus = displayio.FourWire(
        spi,
        command=tft_dc,
        chip_select=tft_cs,
        reset=tft_reset,
        baudrate=32000000,
Example #19
0
 def spi(self):
     """direct access to the SPI bus"""
     if not self._spi:
         self._spi = board.SPI()
     return self._spi