def __init__(self, *, status_neopixel=None, esp=None, external_spi=None): if status_neopixel: self.neopix = neopixel.NeoPixel(status_neopixel, 1, brightness=0.2) else: self.neopix = None self.neo_status(0) self.requests = None if esp: # If there was a passed ESP Object 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: 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) requests.set_socket(socket, self.esp) self._manager = None gc.collect()
def __connect(self, spi, cs, ready, reset, log): esp = adafruit_esp32spi.ESP_SPIcontrol(spi, cs, ready, reset) requests.set_socket(socket, esp) if log: print("MAC addr:", [hex(i) for i in esp.MAC_address]) print("Connecting to AP...") while not esp.is_connected: try: esp.connect_AP(secrets['ssid'], secrets['password']) except RuntimeError as e: if log: print("could not connect to AP, retrying: ",e) continue if log: print("Connected to", str(esp.ssid, 'utf-8'), "\tRSSI:", esp.rssi) print("My IP address is", esp.pretty_ip(esp.ip_address)) self.__wifi = adafruit_esp32spi_wifimanager.ESPSPI_WiFiManager(esp, secrets) ntp = NTP(self.__esp) while not ntp.valid_time: ntp.set_time() print("Failed to obtain time, retrying in 1 seconds...") time.sleep(1) print("Time:", time.time())
def test_first_read_fails(): mocket.getaddrinfo.return_value = ((None, None, None, None, (ip, 80)), ) sock = mocket.Mocket(b"") sock2 = mocket.Mocket(headers + encoded) mocket.socket.call_count = 0 # Reset call count mocket.socket.side_effect = [sock, sock2] adafruit_requests.set_socket(mocket, mocket.interface) r = adafruit_requests.get("http://" + host + "/testwifi/index.html") sock.send.assert_has_calls([ mock.call(b"testwifi/index.html"), ]) sock.send.assert_has_calls([ mock.call(b"Host: "), mock.call(host.encode("utf-8")), mock.call(b"\r\n"), ]) sock2.send.assert_has_calls([ mock.call(b"Host: "), mock.call(host.encode("utf-8")), mock.call(b"\r\n"), ]) sock.connect.assert_called_once_with((ip, 80)) sock2.connect.assert_called_once_with((ip, 80)) # Make sure that the socket is closed after the first receive fails. sock.close.assert_called_once() assert mocket.socket.call_count == 2
def __init__( self, *, status_neopixel=None, esp=None, external_spi=None, extract_values=True, debug=False, ): self._wifi = WiFi(status_neopixel=status_neopixel, esp=esp, external_spi=external_spi) self._debug = debug self.json_transform = [] self._extract_values = extract_values try: os.stat(LOCALFILE) self.uselocal = True except OSError: self.uselocal = False requests.set_socket(socket, self._wifi.esp) gc.collect()
def iot(self,type='mqtt',group='light-group',action=None,conn=None,disc=None): from adafruit_esp32spi import adafruit_esp32spi_wifimanager import adafruit_esp32spi.adafruit_esp32spi_socket as socket import adafruit_requests as requests from adafruit_io.adafruit_io import IO_HTTP from secrets import secrets from adafruit_io.adafruit_io import IO_MQTT from adafruit_minimqtt import MQTT if not self.hardware['ESP32']: raise if not action: action=self.message if not conn: conn=self.connected if not disc: disc=self.disconnected # try: requests.set_socket(socket,self._esp) self.WIFI = adafruit_esp32spi_wifimanager.ESPSPI_WiFiManager(self._esp, secrets, status_pixel=None) self.group_name = group self.WIFI.connect() mqtt_client = MQTT( socket=socket, broker="io.adafruit.com", username=secrets["aio_username"], password=secrets["aio_key"], network_manager=self.WIFI ) self.io = IO_MQTT(mqtt_client) self.io.on_connect = conn self.io.on_disconnect = disc self.io.on_message = action # else: # return self.io.connect()
def test_second_send_fails(): mocket.getaddrinfo.return_value = ((None, None, None, None, (IP, 80)), ) sock = mocket.Mocket(HEADERS + ENCODED) sock2 = mocket.Mocket(HEADERS + ENCODED) mocket.socket.call_count = 0 # Reset call count mocket.socket.side_effect = [sock, sock2] adafruit_requests.set_socket(mocket, mocket.interface) response = adafruit_requests.get("http://" + HOST + "/testwifi/index.html") sock.send.assert_has_calls([ mock.call(b"testwifi/index.html"), ]) sock.send.assert_has_calls([ mock.call(b"Host: "), mock.call(HOST.encode("utf-8")), mock.call(b"\r\n"), ]) assert response.text == str(ENCODED, "utf-8") sock.fail_next_send = True adafruit_requests.get("http://" + HOST + "/get2") sock.connect.assert_called_once_with((IP, 80)) sock2.connect.assert_called_once_with((IP, 80)) # Make sure that the socket is closed after send fails. sock.close.assert_called_once() assert sock2.close.call_count == 0 assert mocket.socket.call_count == 2
def test_second_tls_send_fails(): mocket.getaddrinfo.return_value = ((None, None, None, None, (ip, 80)), ) sock = mocket.Mocket(headers + encoded) sock2 = mocket.Mocket(headers + encoded) mocket.socket.call_count = 0 # Reset call count mocket.socket.side_effect = [sock, sock2] adafruit_requests.set_socket(mocket, mocket.interface) r = adafruit_requests.get("https://" + host + "/testwifi/index.html") sock.send.assert_has_calls([ mock.call(b"testwifi/index.html"), ]) sock.send.assert_has_calls([ mock.call(b"Host: "), mock.call(host.encode("utf-8")), mock.call(b"\r\n"), ]) assert r.text == str(encoded, "utf-8") sock.fail_next_send = True adafruit_requests.get("https://" + host + "/get2") sock.connect.assert_called_once_with((host, 443), mocket.interface.TLS_MODE) sock2.connect.assert_called_once_with((host, 443), mocket.interface.TLS_MODE) # Make sure that the socket is closed after send fails. sock.close.assert_called_once() assert sock2.close.call_count == 0 assert mocket.socket.call_count == 2
def connect(): while not esp.is_connected: try: esp.connect_AP('SSID', 'PASSWORD'). #Edit this with your SSID and Password except RuntimeError as e: print("could not connect to AP, retrying: ",e) continue requests.set_socket(socket, esp)
def __init__(self, spi, cs, rst=None, status_pixel=None, debug=False): if rst is not None: self.eth = wiznet.WIZNET5K(spi, cs, rst) else: self.eth = wiznet.WIZNET5K(spi, cs) self.debug = debug self.statuspix = status_pixel self.pixel_status(0) sock = socket.socket() requests.set_socket(socket, self)
def test_post_string(): mocket.getaddrinfo.return_value = ((None, None, None, None, (IP, 80)), ) sock = mocket.Mocket(HEADERS + ENCODED) mocket.socket.return_value = sock adafruit_requests.set_socket(mocket, mocket.interface) data = "31F" response = adafruit_requests.post("http://" + HOST + "/post", data=data) sock.connect.assert_called_once_with((IP, 80)) sock.send.assert_called_with(b"31F") response.close()
def test_get_json(): mocket.getaddrinfo.return_value = ((None, None, None, None, (IP, 80)), ) sock = mocket.Mocket(HEADERS + ENCODED) mocket.socket.return_value = sock adafruit_requests.set_socket(mocket, mocket.interface) response = adafruit_requests.get("http://" + HOST + "/get") sock.connect.assert_called_once_with((IP, 80)) assert response.json() == RESPONSE response.close()
def test_post_string(): mocket.getaddrinfo.return_value = ((None, None, None, None, (ip, 80)), ) sock = mocket.Mocket(headers + encoded) mocket.socket.return_value = sock adafruit_requests.set_socket(mocket, mocket.interface) data = "31F" r = adafruit_requests.post("http://" + host + "/post", data=data) sock.connect.assert_called_once_with((ip, 80)) sock.send.assert_called_with(b"31F") r.close()
def test_get_json(): mocket.getaddrinfo.return_value = ((None, None, None, None, (ip, 80)), ) sock = mocket.Mocket(headers + encoded) mocket.socket.return_value = sock adafruit_requests.set_socket(mocket, mocket.interface) r = adafruit_requests.get("http://" + host + "/get") sock.connect.assert_called_once_with((ip, 80)) assert r.json() == response r.close()
def connect(essid,password): # note that these are arguments are b'essid' and b'password' print("Connecting to AP...") while not esp.is_connected: try: esp.connect_AP(essid, password) except RuntimeError as e: print("could not connect to AP, retrying: ",e) continue print("Connected to", str(esp.ssid, 'utf-8'), "\tRSSI:", esp.rssi) # Initialize a requests object with a socket and esp32spi interface requests.set_socket(socket, esp)
def SendData(self): global temp global humidity global air global motion global sound try: from secrets import secrets except ImportError: print("All secret keys are kept in secrets.py, please add them there!") raise # Initialize UART connection to the ESP8266 WiFi Module. RX = board.GP17 TX = board.GP16 uart = busio.UART( TX, RX, receiver_buffer_size=2048 ) # Use large buffer as we're not using hardware flow control. esp = adafruit_espatcontrol.ESP_ATcontrol(uart, 115200, debug=False) requests.set_socket(socket, esp) print("Resetting ESP module") esp.soft_reset() # Connect to WiFi print("Connecting to WiFi...") esp.connect(secrets) print("Connected!") yield while True: # Update the blynk datastream using HTTP GET requests requests.get("https://blynk.cloud/external/api/update?token=" + secrets["blynk_auth_token"] + "&v0=" + str(temp)) yield [pyRTOS.timeout(0.5)] # Let other tasks run requests.get("https://blynk.cloud/external/api/update?token=" + secrets["blynk_auth_token"] + "&v1=" + str(humidity)) yield [pyRTOS.timeout(0.5)] # Let other tasks run requests.get("https://blynk.cloud/external/api/update?token=" + secrets["blynk_auth_token"] + "&v2=" + str(air)) yield [pyRTOS.timeout(0.5)] # Let other tasks run requests.get("https://blynk.cloud/external/api/update?token=" + secrets["blynk_auth_token"] + "&v3=" + str(motion)) yield [pyRTOS.timeout(0.5)] # Let other tasks run requests.get("https://blynk.cloud/external/api/update?token=" + secrets["blynk_auth_token"] + "&v4=" + str(sound)) yield [pyRTOS.timeout(0.5)] # Let other tasks run # Reset the global variables if motion: motion = 0 if sound: sound = 0 yield [pyRTOS.timeout(0.5)] # Delay in seconds (Other task can run)
def __init__(self, socket, id_scope: str, device_id: str, key: str, logger: Logger = None): """Creates an instance of the device registration service :param socket: The network socket :param str id_scope: The ID scope of the device to register :param str device_id: The device ID of the device to register :param str key: The primary or secondary key of the device to register :param adafruit_logging.Logger logger: The logger to use to log messages """ self._id_scope = id_scope self._device_id = device_id self._key = key self._logger = logger if logger is not None else logging.getLogger("log") requests.set_socket(socket)
def __init__( self, esp, secrets, status_pixel=None, attempts=2, connection_type=NORMAL, debug=False, ): """ :param ESP_SPIcontrol esp: The ESP object we are using :param dict secrets: The WiFi and Adafruit IO secrets dict (See examples) :param status_pixel: (Optional) The pixel device - A NeoPixel, DotStar, or RGB LED (default=None) :type status_pixel: NeoPixel, DotStar, or RGB LED :param int attempts: (Optional) Failed attempts before resetting the ESP32 (default=2) :param const connection_type: (Optional) Type of WiFi connection: NORMAL or ENTERPRISE """ # Read the settings self.esp = esp self.debug = debug self.attempts = attempts self._connection_type = connection_type requests.set_socket(socket, esp) self.statuspix = status_pixel self.pixel_status(0) self._ap_index = 0 # Check for WPA2 SSID and password in the secrets dictionary and load if it exists if connection_type == NORMAL: if secrets.get("ssid"): self.ssid = secrets["ssid"] if secrets.get("password"): self.password = secrets.get("password", None) # Check for WPA2 Enterprise keys in the secrets dictionary and load them if they exist if connection_type == ENTERPRISE: if secrets.get("ent_ssid"): self.ent_ssid = secrets["ent_ssid"] else: self.ent_ssid = secrets["ssid"] if secrets.get("ent_ident"): self.ent_ident = secrets["ent_ident"] else: self.ent_ident = "" if secrets.get("ent_user"): self.ent_user = secrets["ent_user"] if secrets.get("ent_password"): self.ent_password = secrets["ent_password"]
def __init__(self, esp, secrets, status_pixel=None, attempts=2): """ :param ESP_SPIcontrol esp: The ESP object we are using :param dict secrets: The WiFi and Adafruit IO secrets dict (See examples) :param status_pixel: (Optional) The pixel device - A NeoPixel or DotStar (default=None) :type status_pixel: NeoPixel or DotStar :param int attempts: (Optional) Failed attempts before resetting the ESP32 (default=2) """ # Read the settings self._esp = esp self.debug = False self.secrets = secrets self.attempts = attempts requests.set_socket(socket, esp) self.statuspix = status_pixel self.pixel_status(0)
def _connect(self): try: self._conn = adafruit_esp32spi.ESP_SPIcontrol( board.SPI(), self._cs, self._ready, self._reset) requests.set_socket(socket, self._conn) print("Airlift Firmware:", str(self._conn.firmware_version, "utf-8")[:-1]) print("MAC Address:", "-".join([hex(i)[-2:] for i in self._conn.MAC_address])) print("Connecting to WiFi...") if not self._conn.is_connected: self._conn.connect_AP(secrets.WIFI_SSID, secrets.WIFI_PASSWORD) print("Connected to", str(self._conn.ssid, "utf-8"), "RSSI:", self._conn.rssi) except RuntimeError as e: print("WiFi connection failed: ", e) # TODO: Close dangling connection better? self._conn = None
def __connect(self, spi, cs, ready, reset, log): esp = adafruit_esp32spi.ESP_SPIcontrol(spi, cs, ready, reset) requests.set_socket(socket, esp) if log: print("Connecting to AP...") while not esp.is_connected: try: esp.connect_AP(secrets['ssid'], secrets['password']) except RuntimeError as e: if log: print("could not connect to AP, retrying: ", e) continue if log: print("Connected to", str(esp.ssid, 'utf-8'), "\tRSSI:", esp.rssi) print("My IP address is", esp.pretty_ip(esp.ip_address))
def test_second_tls_connect_fails(): mocket.getaddrinfo.return_value = ((None, None, None, None, (IP, 80)), ) sock = mocket.Mocket(HEADERS + ENCODED) sock2 = mocket.Mocket(HEADERS + ENCODED) sock3 = mocket.Mocket(HEADERS + ENCODED) mocket.socket.call_count = 0 # Reset call count mocket.socket.side_effect = [sock, sock2, sock3] sock2.connect.side_effect = RuntimeError("error connecting") adafruit_requests.set_socket(mocket, mocket.interface) response = adafruit_requests.get("https://" + HOST + "/testwifi/index.html") sock.send.assert_has_calls([ mock.call(b"testwifi/index.html"), ]) sock.send.assert_has_calls([ mock.call(b"Host: "), mock.call(HOST.encode("utf-8")), mock.call(b"\r\n"), ]) assert response.text == str(ENCODED, "utf-8") host2 = "test.adafruit.com" response = adafruit_requests.get("https://" + host2 + "/get2") sock.connect.assert_called_once_with((HOST, 443), mocket.interface.TLS_MODE) sock2.connect.assert_called_once_with((host2, 443), mocket.interface.TLS_MODE) sock3.connect.assert_called_once_with((host2, 443), mocket.interface.TLS_MODE) # Make sure that the socket is closed after send fails. sock.close.assert_called_once() sock2.close.assert_called_once() assert sock3.close.call_count == 0 assert mocket.socket.call_count == 3
import adafruit_requests as requests from secrets import secrets print("ESP32 SPI webclient test by Robin") JSON_URL = "http://api.coindesk.com/v1/bpi/currentprice/USD.json" # 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) spi = busio.SPI(board.SCK, board.MOSI, board.MISO) esp = adafruit_esp32spi.ESP_SPIcontrol(spi, esp32_cs, esp32_ready, esp32_reset) requests.set_socket(socket, esp) 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]) for ap in esp.scan_networks(): print("\t%s\t\tRSSI: %d" % (str(ap['ssid'], 'utf-8'), ap['rssi'])) print("Connecting to AP...") while not esp.is_connected: try: esp.connect_AP(secrets['ssid'], secrets['password']) except RuntimeError as e: print("could not connect to AP, retrying: ",e)
GATEWAY_ADDRESS = (192, 168, 0, 1) DNS_SERVER = (8, 8, 8, 8) print("Wiznet5k WebClient Test (no DHCP)") cs = digitalio.DigitalInOut(board.D10) spi_bus = busio.SPI(board.SCK, MOSI=board.MOSI, MISO=board.MISO) # Initialize ethernet interface without DHCP eth = WIZNET5K(spi_bus, cs, is_dhcp=False) # Set network configuration eth.ifconfig = (IP_ADDRESS, SUBNET_MASK, GATEWAY_ADDRESS, DNS_SERVER) # Initialize a requests object with a socket and ethernet interface requests.set_socket(socket, eth) print("Chip Version:", eth.chip) print("MAC Address:", [hex(i) for i in eth.mac_address]) print("My IP address is:", eth.pretty_ip(eth.ip_address)) print("IP lookup adafruit.com: %s" % eth.pretty_ip(eth.get_host_by_name("adafruit.com"))) #eth._debug = True print("Fetching text from", TEXT_URL) r = requests.get(TEXT_URL) print('-' * 40) print(r.text) print('-' * 40) r.close()
while not network.is_attached: print("Attaching to network...") time.sleep(0.5) print("Attached!") while not network.is_connected: print("Connecting to network...") network.connect() time.sleep(0.5) print("Network Connected!") print("My IP address is:", fona.local_ip) print("IP lookup adafruit.com: %s" % fona.get_host_by_name("adafruit.com")) # Initialize a requests object with a socket and cellular interface requests.set_socket(cellular_socket, fona) # fona._debug = True print("Fetching text from", TEXT_URL) r = requests.get(TEXT_URL) print("-" * 40) print(r.text) print("-" * 40) r.close() print() print("Fetching json from", JSON_URL) r = requests.get(JSON_URL) print("-" * 40) print(r.json()) print("-" * 40)
# PyPortal ESP32 Setup esp32_cs = DigitalInOut(board.ESP_CS) esp32_ready = DigitalInOut(board.ESP_BUSY) esp32_reset = 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) wifi = adafruit_esp32spi_wifimanager.ESPSPI_WiFiManager( esp, secrets, status_light) # Connect to WiFi wifi.connect() # Initialize a requests object with a socket and esp32spi interface requests.set_socket(socket, wifi) JSON_POST_URL = "http://tspann-mbp15-hw14277:9989/pyportal" # Set up ADT7410 sensor i2c_bus = busio.I2C(board.SCL, board.SDA) adt = adafruit_adt7410.ADT7410(i2c_bus, address=0x48) adt.high_resolution = True # Set up an analog light sensor on the PyPortal adc = AnalogIn(board.LIGHT) while True: try: light_value = adc.value print('Light Level: ', light_value)
# rtl_spi = busio.SPI(board.RTL_CLK, MOSI=board.RTL_MOSI, MISO=board.RTL_MISO) # rtl = adafruit_esp32spi.ESP_SPIcontrol(rtl_spi, rtl_cs, rtl_ready, rtl_reset) import serialrtl uart = serial.Serial('/dev/ttyACM0', 115200) time.sleep(1) while uart.in_waiting: print(uart.read().decode(), end='') print() rtl = serialrtl.SerialRTL(uart, debug=3) requests.set_socket(socket, rtl) print('Firmware version: {}'.format(rtl.firmware_version.decode())) print('mac addr: ', ':'.join(hex(i) for i in rtl.MAC_address)) if rtl.status == adafruit_esp32spi.WL_IDLE_STATUS: rtl.connect(secrets) print('connected') for k, v in rtl.network_data.items(): print(f"{k:10}: {'.'.join(str(x) for x in v)}") print('.'.join(str(x) for x in rtl.get_host_by_name('www.google.com'))) rv = requests.get('http://hafnium:8088')
from secrets import secrets except ImportError: print("WiFi secrets are kept in secrets.py, please add them there!") raise ### Variables ### pyportal = adafruit_pyportal.PyPortal() display = board.DISPLAY currentmessage = "null" mqstatus = "null" wifistatus = "null" runcount = 0 wifi = adafruit_esp32spi_wifimanager.ESPSPI_WiFiManager( pyportal._esp, secrets, None) mqtt_topic = secrets["mqtopic"] requests.set_socket(socket, pyportal._esp) headers = {'Content-Type': 'application/json'} URL = 'http://worldclockapi.com/api/json/pst/now' ### Code - Definitions ### def MQSetup(): global mqtt_client time.sleep(3) try: # Get the retained message (wait until it shows up) mqtt_client.loop() except Exception as err: print("Except: {0}".format(err)) print("Failed to pull the retained message")
spi = busio.SPI(board.SCK, board.MOSI, board.MISO) esp = adafruit_esp32spi.ESP_SPIcontrol(spi, esp32_cs, esp32_ready, esp32_reset) print("Connecting to AP...") while not esp.is_connected: try: esp.connect_AP(secrets["ssid"], secrets["password"]) except RuntimeError as e: print("could not connect to AP, retrying: ", e) continue print("Connected to", str(esp.ssid, "utf-8"), "\tRSSI:", esp.rssi) # Initialize a requests object with a socket and esp32spi interface socket.set_interface(esp) requests.set_socket(socket) JSON_GET_URL = "http://httpbin.org/get" # Define a custom header as a dict. headers = {"user-agent": "blinka/1.0.0"} print("Fetching JSON data from %s..." % JSON_GET_URL) response = requests.get(JSON_GET_URL, headers=headers) print("-" * 60) json_data = response.json() headers = json_data["headers"] print("Response's Custom User-Agent Header: {0}".format(headers["User-Agent"])) print("-" * 60)
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, json_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 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) 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 = 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 # 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 # 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 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 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=(320, 240)) # 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()
esp = adafruit_esp32spi.ESP_SPIcontrol(spi, cs, rdy, rst) while not esp.is_connected: print("\nConnecting to Wi-Fi...") try: esp.connect_AP(WIFI_SSID, WIFI_PASSWORD) except RuntimeError as e: print("Cannot connect to Wi-Fi", e) continue print("Wi-Fi connected to", str(esp.ssid, "utf-8")) print("IP address", esp.pretty_ip(esp.ip_address)) # Initialize HTTP POST client adafruit_requests.set_socket(adafruit_esp32spi_socket, esp) try: # Some test data humidity = 55 temperature = 25 # Setup server url post_url = "https://" + TS_HTTP_SERVER + "/update" # Create payload payload = "api_key=" + TS_WRITE_API_KEY + "&field1=" + \ str(temperature) + "&field2=" + str(humidity) # Send a single message response = adafruit_requests.post(post_url, data=payload)