def __init__(self,
                 *,
                 url=None,
                 headers=None,
                 json_path=None,
                 regexp_path=None,
                 default_bg=0x000000,
                 status_neopixel=None,
                 text_font=None,
                 text_position=None,
                 text_color=0x808080,
                 text_wrap=False,
                 text_maxlen=0,
                 text_transform=None,
                 image_json_path=None,
                 image_resize=None,
                 image_position=None,
                 caption_text=None,
                 caption_font=None,
                 caption_position=None,
                 caption_color=0x808080,
                 success_callback=None,
                 debug=False):

        self._debug = debug

        try:
            self._backlight = pulseio.PWMOut(board.TFT_BACKLIGHT)  # pylint: disable=no-member
        except ValueError:
            self._backlight = None
        self.set_backlight(1.0)  # turn on backlight

        self._url = url
        self._headers = headers
        if json_path:
            if isinstance(json_path[0], (list, tuple)):
                self._json_path = json_path
            else:
                self._json_path = (json_path, )
        else:
            self._json_path = None

        self._regexp_path = regexp_path
        self._success_callback = success_callback

        if status_neopixel:
            self.neopix = neopixel.NeoPixel(status_neopixel, 1, brightness=0.2)
        else:
            self.neopix = None
        self.neo_status(0)

        try:
            os.stat(LOCALFILE)
            self._uselocal = True
        except OSError:
            self._uselocal = False

        if self._debug:
            print("Init display")
        self.splash = displayio.Group(max_size=15)

        if self._debug:
            print("Init background")
        self._bg_group = displayio.Group(max_size=1)
        self._bg_file = None
        self._default_bg = default_bg
        self.splash.append(self._bg_group)

        # show thank you and bootup file if available
        for bootscreen in ("/thankyou.bmp", "/pyportal_startup.bmp"):
            try:
                os.stat(bootscreen)
                board.DISPLAY.show(self.splash)
                for i in range(100, -1, -1):  # dim down
                    self.set_backlight(i / 100)
                    time.sleep(0.005)
                self.set_background(bootscreen)
                board.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!

        self._speaker_enable = DigitalInOut(board.SPEAKER_ENABLE)
        self._speaker_enable.switch_to_output(False)
        self.audio = audioio.AudioOut(board.AUDIO_OUT)
        try:
            self.play_file("pyportal_startup.wav")
        except OSError:
            pass  # they deleted the file, no biggie!

        # Make ESP32 connection
        if self._debug:
            print("Init ESP32")
        esp32_ready = DigitalInOut(board.ESP_BUSY)
        esp32_gpio0 = DigitalInOut(board.ESP_GPIO0)
        esp32_reset = DigitalInOut(board.ESP_RESET)
        esp32_cs = DigitalInOut(board.ESP_CS)
        spi = busio.SPI(board.SCK, board.MOSI, board.MISO)

        self._esp = adafruit_esp32spi.ESP_SPIcontrol(spi, esp32_cs,
                                                     esp32_ready, esp32_reset,
                                                     esp32_gpio0)
        #self._esp._debug = 1
        for _ in range(3):  # retries
            try:
                print("ESP firmware:", self._esp.firmware_version)
                break
            except RuntimeError:
                print("Retrying ESP32 connection")
                time.sleep(1)
                self._esp.reset()
        else:
            raise RuntimeError("Was not able to find ESP32")
        requests.set_interface(self._esp)

        if url and not self._uselocal:
            self._connect_esp()

        # set the default background
        self.set_background(self._default_bg)
        board.DISPLAY.show(self.splash)

        if self._debug:
            print("Init SD Card")
        sd_cs = DigitalInOut(board.SD_CS)
        self._sdcard = None
        try:
            self._sdcard = adafruit_sdcard.SDCard(spi, sd_cs)
            vfs = storage.VfsFat(self._sdcard)
            storage.mount(vfs, "/sd")
        except OSError as error:
            print("No SD card found:", error)

        self._qr_group = None

        if self._debug:
            print("Init caption")
        self._caption = None
        if caption_font:
            self._caption_font = bitmap_font.load_font(caption_font)
        self.set_caption(caption_text, caption_position, caption_color)

        if text_font:
            if 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
            else:
                num = 1
                text_position = (text_position, )
                text_color = (text_color, )
                text_wrap = (text_wrap, )
                text_maxlen = (text_maxlen, )
                text_transform = (text_transform, )
            self._text = [None] * num
            self._text_color = [None] * num
            self._text_position = [None] * num
            self._text_wrap = [None] * num
            self._text_maxlen = [None] * num
            self._text_transform = [None] * num
            self._text_font = bitmap_font.load_font(text_font)
            if self._debug:
                print("Loading font glyphs")
            # self._text_font.load_glyphs(b'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'
            #                             b'0123456789:/-_,. ')
            gc.collect()

            for i in range(num):
                if self._debug:
                    print("Init text area", i)
                self._text[i] = None
                self._text_color[i] = text_color[i]
                self._text_position[i] = text_position[i]
                self._text_wrap[i] = text_wrap[i]
                self._text_maxlen[i] = text_maxlen[i]
                self._text_transform[i] = text_transform[i]
        else:
            self._text_font = None
            self._text = None

        self._image_json_path = image_json_path
        self._image_resize = image_resize
        self._image_position = image_position
        if image_json_path:
            if self._debug:
                print("Init image path")
            if not self._image_position:
                self._image_position = (0, 0)  # default to top corner
            if not self._image_resize:
                self._image_resize = (320, 240)  # default to full screen

        if self._debug:
            print("Init touchscreen")
        # pylint: disable=no-member
        self.touchscreen = adafruit_touchscreen.Touchscreen(
            board.TOUCH_XL,
            board.TOUCH_XR,
            board.TOUCH_YD,
            board.TOUCH_YU,
            calibration=((5200, 59000), (5800, 57000)),
            size=(320, 240))
        # pylint: enable=no-member

        self.set_backlight(1.0)  # turn on backlight

        gc.collect()
Example #2
0
except ImportError:
    print("WiFi secrets are kept in secrets.py, please add them there!")
    raise

# If you are using a board with pre-defined ESP32 Pins:
esp32_cs = DigitalInOut(board.ESP_CS)
esp32_ready = DigitalInOut(board.ESP_BUSY)
esp32_reset = DigitalInOut(board.ESP_RESET)

# If you have an externally connected ESP32:
# esp32_cs = DigitalInOut(board.D9)
# esp32_ready = DigitalInOut(board.D10)
# esp32_reset = DigitalInOut(board.D5)

spi = busio.SPI(board.SCK, board.MOSI, board.MISO)
esp = adafruit_esp32spi.ESP_SPIcontrol(spi, esp32_cs, esp32_ready, esp32_reset)
"""Use below for Most Boards"""
status_light = neopixel.NeoPixel(
    board.NEOPIXEL, 1, brightness=0.2)  # Uncomment for Most Boards
"""Uncomment below for ItsyBitsy M4"""
# status_light = dotstar.DotStar(board.APA102_SCK, board.APA102_MOSI, 1, brightness=0.2)
# Uncomment below for an externally defined RGB LED
# import adafruit_rgbled
# from adafruit_esp32spi import PWMOut
# RED_LED = PWMOut.PWMOut(esp, 26)
# GREEN_LED = PWMOut.PWMOut(esp, 27)
# BLUE_LED = PWMOut.PWMOut(esp, 25)
# status_light = adafruit_rgbled.RGBLED(RED_LED, BLUE_LED, GREEN_LED)
wifi = adafruit_esp32spi_wifimanager.ESPSPI_WiFiManager(
    esp, secrets, status_light)
    6: "June",
    7: "July",
    8: "August",
    9: "September",
    10: "October",
    11: "November",
    12: "December"
}


esp32_cs = digitalio.DigitalInOut(board.ESP_CS)
esp32_ready = digitalio.DigitalInOut(board.ESP_BUSY)
esp32_reset = digitalio.DigitalInOut(board.ESP_RESET)

spi = busio.SPI(board.SCK, board.MOSI, board.MISO)
esp = adafruit_esp32spi.ESP_SPIcontrol(spi, esp32_cs, esp32_ready, esp32_reset, debug=False)
requests.set_socket(socket, esp)

# initialize pyportal
pyportal = PyPortal(esp=esp,
                    external_spi=spi,
                    default_bg = None)

# set pyportal's backlight brightness
pyportal.set_backlight(0.2)

if esp.status == adafruit_esp32spi.WL_IDLE_STATUS:
    print("ESP32 found and in idle mode")
    print("Firmware vers.", esp.firmware_version)
    print("MAC addr:", [hex(i) for i in esp.MAC_address])
Example #4
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):

        self._debug = debug
        self._convert_image = convert_image

        try:
            if hasattr(board, "TFT_BACKLIGHT"):
                self._backlight = pulseio.PWMOut(board.TFT_BACKLIGHT)  # pylint: disable=no-member
            elif hasattr(board, "TFT_LITE"):
                self._backlight = pulseio.PWMOut(board.TFT_LITE)  # pylint: disable=no-member
        except ValueError:
            self._backlight = None
        self.set_backlight(1.0)  # turn on backlight

        self._url = url
        self._headers = headers
        if json_path:
            if isinstance(json_path[0], (list, tuple)):
                self._json_path = json_path
            else:
                self._json_path = (json_path, )
        else:
            self._json_path = None

        self._regexp_path = regexp_path
        self._success_callback = success_callback

        if status_neopixel:
            self.neopix = neopixel.NeoPixel(status_neopixel, 1, brightness=0.2)
        else:
            self.neopix = None
        self.neo_status(0)

        try:
            os.stat(LOCALFILE)
            self._uselocal = True
        except OSError:
            self._uselocal = False

        if self._debug:
            print("Init display")
        self.splash = displayio.Group(max_size=15)

        if self._debug:
            print("Init background")
        self._bg_group = displayio.Group(max_size=1)
        self._bg_file = None
        self._default_bg = default_bg
        self.splash.append(self._bg_group)

        # show thank you and bootup file if available
        for bootscreen in ("/thankyou.bmp", "/pyportal_startup.bmp"):
            try:
                os.stat(bootscreen)
                board.DISPLAY.show(self.splash)
                for i in range(100, -1, -1):  # dim down
                    self.set_backlight(i / 100)
                    time.sleep(0.005)
                self.set_background(bootscreen)
                try:
                    board.DISPLAY.refresh(target_frames_per_second=60)
                except AttributeError:
                    board.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!

        self._speaker_enable = DigitalInOut(board.SPEAKER_ENABLE)
        self._speaker_enable.switch_to_output(False)
        if hasattr(board, "AUDIO_OUT"):
            self.audio = audioio.AudioOut(board.AUDIO_OUT)
        elif hasattr(board, "SPEAKER"):
            self.audio = audioio.AudioOut(board.SPEAKER)
        else:
            raise AttributeError("Board does not have a builtin speaker!")
        try:
            self.play_file("pyportal_startup.wav")
        except OSError:
            pass  # they deleted the file, no biggie!

        if esp:  # If there was a passed ESP Object
            if self._debug:
                print("Passed ESP32 to PyPortal")
            self._esp = esp
            if external_spi:  # If SPI Object Passed
                spi = external_spi
            else:  # Else: Make ESP32 connection
                spi = busio.SPI(board.SCK, board.MOSI, board.MISO)
        else:
            if self._debug:
                print("Init ESP32")
            esp32_ready = DigitalInOut(board.ESP_BUSY)
            esp32_gpio0 = DigitalInOut(board.ESP_GPIO0)
            esp32_reset = DigitalInOut(board.ESP_RESET)
            esp32_cs = DigitalInOut(board.ESP_CS)
            spi = busio.SPI(board.SCK, board.MOSI, board.MISO)

            self._esp = adafruit_esp32spi.ESP_SPIcontrol(
                spi, esp32_cs, esp32_ready, esp32_reset, esp32_gpio0)
        # self._esp._debug = 1
        for _ in range(3):  # retries
            try:
                print("ESP firmware:", self._esp.firmware_version)
                break
            except RuntimeError:
                print("Retrying ESP32 connection")
                time.sleep(1)
                self._esp.reset()
        else:
            raise RuntimeError("Was not able to find ESP32")
        requests.set_socket(socket, self._esp)

        if url and not self._uselocal:
            self._connect_esp()

        if self._debug:
            print("My IP address is",
                  self._esp.pretty_ip(self._esp.ip_address))

        # set the default background
        self.set_background(self._default_bg)
        board.DISPLAY.show(self.splash)

        if self._debug:
            print("Init SD Card")
        sd_cs = board.SD_CS
        if not NATIVE_SD:
            sd_cs = DigitalInOut(sd_cs)
        self._sdcard = None
        try:
            self._sdcard = sdcardio.SDCard(spi, sd_cs)
            vfs = storage.VfsFat(self._sdcard)
            storage.mount(vfs, "/sd")
        except OSError as error:
            print("No SD card found:", error)

        self._qr_group = None
        # Tracks whether we've hidden the background when we showed the QR code.
        self._qr_only = False

        if self._debug:
            print("Init caption")
        self._caption = None
        if caption_font:
            self._caption_font = bitmap_font.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, )
            self._text = [None] * num
            self._text_color = [None] * num
            self._text_position = [None] * num
            self._text_wrap = [None] * num
            self._text_maxlen = [None] * num
            self._text_transform = [None] * num
            self._text_scale = [None] * num
            if text_font is not terminalio.FONT:
                self._text_font = bitmap_font.load_font(text_font)
            else:
                self._text_font = terminalio.FONT
            if self._debug:
                print("Loading font glyphs")
            # self._text_font.load_glyphs(b'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'
            #                             b'0123456789:/-_,. ')
            gc.collect()

            for i in range(num):
                if self._debug:
                    print("Init text area", i)
                self._text[i] = None
                self._text_color[i] = text_color[i]
                self._text_position[i] = text_position[i]
                self._text_wrap[i] = text_wrap[i]
                self._text_maxlen[i] = text_maxlen[i]
                self._text_transform[i] = text_transform[i]
                if not isinstance(text_scale[i],
                                  (int, float)) or text_scale[i] < 1:
                    text_scale[i] = 1
                self._text_scale[i] = text_scale[i]
        else:
            self._text_font = None
            self._text = None

        # Add any JSON translators
        self._json_transform = []
        if json_transform:
            if callable(json_transform):
                self._json_transform.append(json_transform)
            else:
                self._json_transform.extend(filter(callable, json_transform))

        self._image_json_path = image_json_path
        self._image_url_path = image_url_path
        self._image_resize = image_resize
        self._image_position = image_position
        self._image_dim_json_path = image_dim_json_path
        if image_json_path or image_url_path:
            if self._debug:
                print("Init image path")
            if not self._image_position:
                self._image_position = (0, 0)  # default to top corner
            if not self._image_resize:
                self._image_resize = (
                    board.DISPLAY.width,
                    board.DISPLAY.height,
                )  # default to full screen
        if hasattr(board, "TOUCH_XL"):
            if self._debug:
                print("Init touchscreen")
            # pylint: disable=no-member
            self.touchscreen = adafruit_touchscreen.Touchscreen(
                board.TOUCH_XL,
                board.TOUCH_XR,
                board.TOUCH_YD,
                board.TOUCH_YU,
                calibration=((5200, 59000), (5800, 57000)),
                size=(board.DISPLAY.width, board.DISPLAY.height),
            )
            # pylint: enable=no-member

            self.set_backlight(1.0)  # turn on backlight
        elif hasattr(board, "BUTTON_CLOCK"):
            if self._debug:
                print("Init cursor")
            self.mouse_cursor = Cursor(board.DISPLAY,
                                       display_group=self.splash,
                                       cursor_speed=8)
            self.mouse_cursor.hide()
            self.cursor = CursorManager(self.mouse_cursor)
        else:
            raise AttributeError(
                "PyPortal module requires either a touchscreen or gamepad.")

        gc.collect()
Example #5
0
# We are using the wsgi server made for the ESP32

print("ESP32 SPI simple web app test!")

# If you are using a board with pre-defined ESP32 Pins:
esp32_cs = DigitalInOut(board.ESP_CS)
esp32_ready = DigitalInOut(board.ESP_BUSY)
esp32_reset = DigitalInOut(board.ESP_RESET)

# If you have an externally connected ESP32:
# esp32_cs = DigitalInOut(board.D9)
# esp32_ready = DigitalInOut(board.D10)
# esp32_reset = DigitalInOut(board.D5)

spi = busio.SPI(board.SCK, board.MOSI, board.MISO)
esp = adafruit_esp32spi.ESP_SPIcontrol(spi, esp32_cs, esp32_ready, esp32_reset)  # pylint: disable=line-too-long
"""Use below for Most Boards"""
status_light = neopixel.NeoPixel(board.NEOPIXEL, 1,
                                 brightness=0.2)  # Uncomment for Most Boards
"""Uncomment below for ItsyBitsy M4"""
# import adafruit_dotstar as dotstar
# status_light = dotstar.DotStar(board.APA102_SCK, board.APA102_MOSI, 1, brightness=1)

## If you want to connect to wifi with secrets:
wifi = wifimanager.ESPSPI_WiFiManager(esp, secrets, status_light, debug=True)
wifi.connect()

## If you want to create a WIFI hotspot to connect to with secrets:
# secrets = {"ssid": "My ESP32 AP!", "password": "******"}
# wifi = wifimanager.ESPSPI_WiFiManager(esp, secrets, status_light)
# wifi.create_ap()
Example #6
0
import board
import busio
import digitalio
from adafruit_esp32spi import adafruit_esp32spi

# FeatherWing ESP32 AirLift, nRF52840
cs = digitalio.DigitalInOut(board.D13)
rdy = digitalio.DigitalInOut(board.D11)
rst = digitalio.DigitalInOut(board.D12)

spi = busio.SPI(board.SCK, board.MOSI, board.MISO)
wifi = adafruit_esp32spi.ESP_SPIcontrol(spi, cs, rdy, rst)

print("MAC address:", [hex(i) for i in wifi.MAC_address])
Example #7
0
    "January",
    "February",
    "March",
    "April",
    "May",
    "June",
    "July",
    "Augsut",
    "September",
    "October",
    "November",
    "December",
)
spi = busio.SPI(board.SCK, board.MOSI, board.MISO)
esp = adafruit_esp32spi.ESP_SPIcontrol(spi, DigitalInOut(board.ESP_CS),
                                       DigitalInOut(board.ESP_BUSY),
                                       DigitalInOut(board.ESP_RESET))
requests.set_socket(socket, esp)


def get_data_source_url(api="onecall", location=None):
    if api.upper() == "FORECAST5":
        URL = "https://api.openweathermap.org/data/2.5/forecast?"
        URL += "q=" + location
    elif api.upper() == "ONECALL":
        URL = "https://api.openweathermap.org/data/2.5/onecall?exclude=minutely,hourly,alerts"
        URL += "&lat={}".format(location[0])
        URL += "&lon={}".format(location[1])
    else:
        raise ValueError("Unknown API type: " + api)
    return URL + "&appid=" + secrets["openweather_token"]
Example #8
0
    def __init__(self, debug=False):
        self._settings = {
            "wifi_ssid": secrets["ssid"],
            "wifi_password": secrets["password"],
            "aio_username": secrets["aio_username"],
            "aio_key": secrets["aio_key"],
            "darksky_key": secrets["darksky_api_key"],
            "darksky_url": secrets["darksky_api_forecast"],
            "twitch_key": secrets["twitch_api_key"],
            "twitch_secret": secrets["twitch_api_secret"],
            "twitch_streamers": secrets["twitch_api_streamers"],
            "nhl_url": secrets["sports_api_nhl"],
            "nhl_teams": secrets["sports_api_nhl_teams"],
            "nfl_url": secrets["sports_api_nfl"],
            "nfl_teams": secrets["sports_api_nfl_teams"],
            "mlb_url": secrets["sports_api_mlb"],
            "mlb_teams": secrets["sports_api_mlb_teams"],
            "prem_url": secrets["sports_api_prem"],
            "prem_teams": secrets["sports_api_prem_teams"],
            "default_weather_icon": "/icons/weather/unknown.bmp",
            "default_twitch_icon": "/icons/streamers/twitch.bmp"
        }

        self._debug = debug
        self._debug_refresh_counter = 0
        self._debug_error_counter = 0
        self._debug_total_error_counter = 0
        self._today = 0
        self._updated = ""
        self._twitch_bearer_token = ""
        self._display_groups = {}
        self.reset_display_groups()

        # PyPortal ESP32 Setup
        esp32_cs = digitalio.DigitalInOut(board.ESP_CS)
        esp32_ready = digitalio.DigitalInOut(board.ESP_BUSY)
        esp32_reset = digitalio.DigitalInOut(board.ESP_RESET)
        spi = busio.SPI(board.SCK, board.MOSI, board.MISO)
        esp = adafruit_esp32spi.ESP_SPIcontrol(spi, esp32_cs, esp32_ready,
                                               esp32_reset)
        status_light = neopixel.NeoPixel(board.NEOPIXEL, 1, brightness=0.2)
        self._led = digitalio.DigitalInOut(board.D13)
        self._led.direction = digitalio.Direction.OUTPUT

        # WiFi Setup
        if self._debug:
            print("Visible SSIDs:")
            for ap in esp.scan_networks():
                print("%s  RSSI: %d" % (str(ap["ssid"], "utf-8"), ap["rssi"]))

        print("Connecting configured WiFi...")
        while not esp.is_connected:
            try:
                esp.connect(secrets)
            except RuntimeError as e:
                print("Could not connect to WiFi, retrying: ", e)
                continue

        print("Connected to:", str(esp.ssid, "utf-8"), "  RSSI:", esp.rssi)
        print("IP address:", esp.pretty_ip(esp.ip_address))

        self._wifi_client = adafruit_esp32spi_wifimanager.ESPSPI_WiFiManager(
            esp, secrets, status_light)

        # PyPortal Board Setup
        board.DISPLAY.auto_brightness = False
        board.DISPLAY.brightness = 1
Example #9
0
status_pixel = neopixel.NeoPixel(
    board.NEOPIXEL,
    1,
    brightness=0.05,
    auto_write=True,
    pixel_order=neopixel.GRB)  # Uses the onboard NeoPixel.
status_pixel.fill(0xFF0000)  # red because we aren't connected yet

# Here, we define the pins the ESP32 uses. This only works for boards with built-in ESP32s,
# such as the MatrixPortal and Metro M4 Airlift. Read the guide for your add-on to find which pins to use.
cs = digitalio.DigitalInOut(board.ESP_CS)
busy = digitalio.DigitalInOut(board.ESP_BUSY)
rst = digitalio.DigitalInOut(board.ESP_RESET)

spi = busio.SPI(board.SCK, board.MOSI, board.MISO)  # Define the SPI object
esp = adafruit_esp32spi.ESP_SPIcontrol(spi, cs, busy,
                                       rst)  # Start talking to the ESP32.
requests.set_socket(
    socket, esp)  # Tell the requests library to use the ESP32 connection.
io = IO_HTTP(config["aio_username"], config["aio_key"],
             requests)  # Start talking to Adafruit IO.

# Print info about the ESP32
if esp.status == adafruit_esp32spi.WL_IDLE_STATUS:
    print("ESP32 found and in idle mode")
print("Firmware vers.", esp.firmware_version)
print("MAC addr:", [hex(i) for i in esp.MAC_address])

# Connect to Wifi.
print("Connecting to Wifi...")
while not esp.is_connected:
    try:
Example #10
0
    def __init__(self,
                 *,
                 url,
                 json_path=None,
                 xml_path=None,
                 default_bg=None,
                 status_neopixel=None,
                 text_font=None,
                 text_position=None,
                 text_color=0x808080,
                 text_wrap=0,
                 text_maxlen=0,
                 image_json_path=None,
                 image_resize=None,
                 image_position=None,
                 time_between_requests=60,
                 success_callback=None,
                 caption_text=None,
                 caption_font=None,
                 caption_position=None,
                 caption_color=0x808080,
                 debug=True):

        self._debug = debug

        try:
            self._backlight = pulseio.PWMOut(board.TFT_BACKLIGHT)
        except:
            self._backlight = None
        self.set_backlight(1.0)  # turn on backlight

        self._url = url
        if json_path:
            if isinstance(json_path[0], tuple) or isinstance(
                    json_path[0], list):
                self._json_path = json_path
            else:
                self._json_path = (json_path, )
        else:
            self._json_path = None

        self._xml_path = xml_path
        self._time_between_requests = time_between_requests
        self._success_callback = success_callback

        if status_neopixel:
            self.neopix = neopixel.NeoPixel(status_neopixel, 1, brightness=0.2)
        else:
            self.neopix = None
        self.neo_status(0)

        try:
            os.stat(LOCALFILE)
            self._uselocal = True
        except OSError:
            self._uselocal = False

        # Make ESP32 connection
        if self._debug:
            print("Init ESP32")
        esp32_cs = DigitalInOut(microcontroller.pin.PB14)  # PB14
        esp32_ready = DigitalInOut(microcontroller.pin.PB16)
        esp32_gpio0 = DigitalInOut(microcontroller.pin.PB15)
        esp32_reset = DigitalInOut(microcontroller.pin.PB17)
        spi = busio.SPI(board.SCK, board.MOSI, board.MISO)

        if not self._uselocal:
            self._esp = adafruit_esp32spi.ESP_SPIcontrol(
                spi, esp32_cs, esp32_ready, esp32_reset, esp32_gpio0)
            #self._esp._debug = 1
            for _ in range(3):  # retries
                try:
                    print("ESP firmware:", self._esp.firmware_version)
                    break
                except RuntimeError:
                    print("Retrying ESP32 connection")
                    time.sleep(1)
                    self._esp.reset()
            else:
                raise RuntimeError("Was not able to find ESP32")

            requests.set_interface(self._esp)

        if self._debug:
            print("Init display")
        self.splash = displayio.Group(max_size=5)
        board.DISPLAY.show(self.splash)

        if self._debug:
            print("Init background")
        self._bg_group = displayio.Group(max_size=1)
        self._bg_file = None
        self.set_background(default_bg)
        self.splash.append(self._bg_group)

        self._qr_group = None

        if self._debug:
            print("Init caption")
        self._caption = None
        if caption_font:
            self._caption_font = bitmap_font.load_font(caption_font)
        self.set_caption(caption_text, caption_position, caption_color)

        if text_font:
            if isinstance(text_position[0], tuple) or isinstance(
                    text_position[0], list):
                num = len(text_position)
                if not text_wrap:
                    text_wrap = [0] * num
                if not text_maxlen:
                    text_maxlen = [0] * num
            else:
                num = 1
                text_position = (text_position, )
                text_color = (text_color, )
                text_wrap = (text_wrap, )
                text_maxlen = (text_maxlen, )
            self._text = [None] * num
            self._text_color = [None] * num
            self._text_position = [None] * num
            self._text_wrap = [None] * num
            self._text_maxlen = [None] * num
            self._text_font = bitmap_font.load_font(text_font)
            if self._debug:
                print("Loading font glyphs")
            #self._text_font.load_glyphs(b'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789:/-_,. ')
            gc.collect()

            for i in range(num):
                if self._debug:
                    print("Init text area", i)
                self._text[i] = None
                self._text_color[i] = text_color[i]
                self._text_position[i] = text_position[i]
                self._text_wrap[i] = text_wrap[i]
                self._text_maxlen[i] = text_maxlen[i]
        else:
            self._text_font = None
            self._text = None

        self._image_json_path = image_json_path
        self._image_resize = image_resize
        self._image_position = image_position
        if image_json_path:
            if self._debug:
                print("Init image path")
            if not self._image_position:
                self._image_position = (0, 0)  # default to top corner
            if not self._image_resize:
                self._image_resize = (320, 240)  # default to full screen

        if self._debug:
            print("Init touchscreen")
        self.ts = adafruit_touchscreen.Touchscreen(microcontroller.pin.PB01,
                                                   microcontroller.pin.PB08,
                                                   microcontroller.pin.PA06,
                                                   microcontroller.pin.PB00,
                                                   calibration=((5200, 59000),
                                                                (5800, 57000)),
                                                   size=(320, 240))

        self.set_backlight(1.0)  # turn on backlight
        gc.collect()
Example #11
0
    def __init__(self,
                 *,
                 url=None,
                 headers=None,
                 json_path=None,
                 regexp_path=None,
                 default_bg=0x000000,
                 status_neopixel=None,
                 text_font=None,
                 text_position=None,
                 text_color=0x808080,
                 text_wrap=False,
                 text_maxlen=0,
                 text_transform=None,
                 image_json_path=None,
                 image_resize=None,
                 image_position=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):

        self._debug = debug

        self._url = url
        self._headers = headers
        if json_path:
            if isinstance(json_path[0], (list, tuple)):
                self._json_path = json_path
            else:
                self._json_path = (json_path, )
        else:
            self._json_path = None

        self._regexp_path = regexp_path
        self._success_callback = success_callback

        if status_neopixel:
            self.neopix = neopixel.NeoPixel(status_neopixel, 1, brightness=0.2)
        else:
            self.neopix = None
        self.neo_status(0)

        try:
            os.stat(LOCALFILE)
            self._uselocal = True
        except OSError:
            self._uselocal = False

        if self._debug:
            print("Init display")
        self.splash = displayio.Group(max_size=15)

        if self._debug:
            print("Init background")
        self._bg_group = displayio.Group(max_size=1)
        self._bg_file = None
        self._default_bg = default_bg
        self.splash.append(self._bg_group)

        # show thank you and bootup file if available
        for bootscreen in ("/thankyou.bmp", "/pyportal_startup.bmp"):
            try:
                os.stat(bootscreen)
                board.DISPLAY.show(self.splash)
                time.sleep(2)
                self.set_background(bootscreen, position=(0, 0))
                board.DISPLAY.wait_for_frame()
                time.sleep(2)
            except OSError:
                pass  # they removed it, skip!

        if esp:  # If there was a passed ESP Object
            if self._debug:
                print("Passed ESP32 to PyPortal")
            self._esp = esp
            if external_spi:  #If SPI Object Passed
                spi = external_spi
            else:  # Else: Make ESP32 connection
                spi = busio.SPI(board.SCK, board.MOSI, board.MISO)
        else:
            if self._debug:
                print("Init ESP32")
            esp32_cs = DigitalInOut(board.D10)
            esp32_ready = DigitalInOut(board.D9)
            esp32_reset = DigitalInOut(board.D6)
            #esp32_gpio0 = DigitalInOut(board.ESP_GPIO0)
            spi = busio.SPI(board.SCK, board.MOSI, board.MISO)

            #self._esp = adafruit_esp32spi.ESP_SPIcontrol(spi, esp32_cs, esp32_ready, esp32_reset, esp32_gpio0)
            self._esp = adafruit_esp32spi.ESP_SPIcontrol(
                spi, esp32_cs, esp32_ready, esp32_reset)
        #self._esp._debug = 1
        for _ in range(3):  # retries
            try:
                print("ESP firmware:", self._esp.firmware_version)
                break
            except RuntimeError:
                print("Retrying ESP32 connection")
                time.sleep(1)
                self._esp.reset()
        else:
            raise RuntimeError("Was not able to find ESP32")
        requests.set_interface(self._esp)

        if url and not self._uselocal:
            self._connect_esp()

        if self._debug:
            print("My IP address is",
                  self._esp.pretty_ip(self._esp.ip_address))

        # set the default background
        self.set_background(self._default_bg)
        board.DISPLAY.show(self.splash)

        self._qr_group = None
        # Tracks whether we've hidden the background when we showed the QR code.
        self._qr_only = False

        if self._debug:
            print("Init caption")
        self._caption = None
        if caption_font:
            self._caption_font = bitmap_font.load_font(caption_font)
        self.set_caption(caption_text, caption_position, caption_color)

        if text_font:
            if 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
            else:
                num = 1
                text_position = (text_position, )
                text_color = (text_color, )
                text_wrap = (text_wrap, )
                text_maxlen = (text_maxlen, )
                text_transform = (text_transform, )
            self._text = [None] * num
            self._text_color = [None] * num
            self._text_position = [None] * num
            self._text_wrap = [None] * num
            self._text_maxlen = [None] * num
            self._text_transform = [None] * num
            self._text_font = bitmap_font.load_font(text_font)
            if self._debug:
                print("Loading font glyphs")
            # self._text_font.load_glyphs(b'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'
            #                             b'0123456789:/-_,. ')
            gc.collect()

            for i in range(num):
                if self._debug:
                    print("Init text area", i)
                self._text[i] = None
                self._text_color[i] = text_color[i]
                self._text_position[i] = text_position[i]
                self._text_wrap[i] = text_wrap[i]
                self._text_maxlen[i] = text_maxlen[i]
                self._text_transform[i] = text_transform[i]
        else:
            self._text_font = None
            self._text = None

        self._image_json_path = image_json_path
        self._image_url_path = image_url_path
        self._image_resize = image_resize
        self._image_position = image_position
        if image_json_path or image_url_path:
            if self._debug:
                print("Init image path")
            if not self._image_position:
                self._image_position = (0, 0)  # default to top corner
            if not self._image_resize:
                self._image_resize = (320, 240)  # default to full screen