|
| 1 | +# SPDX-FileCopyrightText: 2019 ladyada for Adafruit Industries |
| 2 | +# SPDX-License-Identifier: MIT |
| 3 | + |
| 4 | +import os |
| 5 | +import board |
| 6 | +import busio |
| 7 | +from digitalio import DigitalInOut |
| 8 | +import adafruit_requests as requests |
| 9 | +import adafruit_esp32spi.adafruit_esp32spi_socket as socket |
| 10 | +from adafruit_esp32spi import adafruit_esp32spi |
| 11 | + |
| 12 | +print("ESP32 SPI webclient test") |
| 13 | + |
| 14 | +TEXT_URL = "http://wifitest.adafruit.com/testwifi/index.html" |
| 15 | +JSON_URL = "http://api.coindesk.com/v1/bpi/currentprice/USD.json" |
| 16 | + |
| 17 | +# If you are using a board with pre-defined ESP32 Pins: |
| 18 | +esp32_cs = DigitalInOut(board.ESP_CS) |
| 19 | +esp32_ready = DigitalInOut(board.ESP_BUSY) |
| 20 | +esp32_reset = DigitalInOut(board.ESP_RESET) |
| 21 | + |
| 22 | +spi = busio.SPI(board.SCK, board.MOSI, board.MISO) |
| 23 | +esp = adafruit_esp32spi.ESP_SPIcontrol(spi, esp32_cs, esp32_ready, esp32_reset) |
| 24 | + |
| 25 | +requests.set_socket(socket, esp) |
| 26 | + |
| 27 | +if esp.status == adafruit_esp32spi.WL_IDLE_STATUS: |
| 28 | + print("ESP32 found and in idle mode") |
| 29 | +print("Firmware vers.", esp.firmware_version) |
| 30 | +print("MAC addr:", [hex(i) for i in esp.MAC_address]) |
| 31 | + |
| 32 | +for ap in esp.scan_networks(): |
| 33 | + print("\t%s\t\tRSSI: %d" % (str(ap["ssid"], "utf-8"), ap["rssi"])) |
| 34 | + |
| 35 | +print("Connecting to AP...") |
| 36 | +while not esp.is_connected: |
| 37 | + try: |
| 38 | + esp.connect_AP(os.getenv('CIRCUITPY_WIFI_SSID'), os.getenv('CIRCUITPY_WIFI_PASSWORD')) |
| 39 | + except OSError as e: |
| 40 | + print("could not connect to AP, retrying: ", e) |
| 41 | + continue |
| 42 | +print("Connected to", str(esp.ssid, "utf-8"), "\tRSSI:", esp.rssi) |
| 43 | +print("My IP address is", esp.pretty_ip(esp.ip_address)) |
| 44 | +print( |
| 45 | + "IP lookup adafruit.com: %s" % esp.pretty_ip(esp.get_host_by_name("adafruit.com")) |
| 46 | +) |
| 47 | +print("Ping google.com: %d ms" % esp.ping("google.com")) |
| 48 | + |
| 49 | +# esp._debug = True |
| 50 | +print("Fetching text from", TEXT_URL) |
| 51 | +r = requests.get(TEXT_URL) |
| 52 | +print("-" * 40) |
| 53 | +print(r.text) |
| 54 | +print("-" * 40) |
| 55 | +r.close() |
| 56 | + |
| 57 | +print() |
| 58 | +print("Fetching json from", JSON_URL) |
| 59 | +r = requests.get(JSON_URL) |
| 60 | +print("-" * 40) |
| 61 | +print(r.json()) |
| 62 | +print("-" * 40) |
| 63 | +r.close() |
| 64 | + |
| 65 | +print("Done!") |
0 commit comments