|
| 1 | +import board |
| 2 | +import busio |
| 3 | +from digitalio import DigitalInOut |
| 4 | +import adafruit_esp32spi.adafruit_esp32spi_socket as socket |
| 5 | +from adafruit_esp32spi import adafruit_esp32spi |
| 6 | +import adafruit_requests as requests |
| 7 | + |
| 8 | +# If you are using a board with pre-defined ESP32 Pins: |
| 9 | +esp32_cs = DigitalInOut(board.ESP_CS) |
| 10 | +esp32_ready = DigitalInOut(board.ESP_BUSY) |
| 11 | +esp32_reset = DigitalInOut(board.ESP_RESET) |
| 12 | + |
| 13 | +# If you have an externally connected ESP32: |
| 14 | +# esp32_cs = DigitalInOut(board.D9) |
| 15 | +# esp32_ready = DigitalInOut(board.D10) |
| 16 | +# esp32_reset = DigitalInOut(board.D5) |
| 17 | + |
| 18 | +spi = busio.SPI(board.SCK, board.MOSI, board.MISO) |
| 19 | +esp = adafruit_esp32spi.ESP_SPIcontrol(spi, esp32_cs, esp32_ready, esp32_reset) |
| 20 | + |
| 21 | +print("Connecting to AP...") |
| 22 | +while not esp.is_connected: |
| 23 | + try: |
| 24 | + esp.connect_AP(b'MY_SSID_NAME', b'MY_SSID_PASSWORD') |
| 25 | + except RuntimeError as e: |
| 26 | + print("could not connect to AP, retrying: ",e) |
| 27 | + continue |
| 28 | +print("Connected to", str(esp.ssid, 'utf-8'), "\tRSSI:", esp.rssi) |
| 29 | + |
| 30 | +# Initialize a requests object with a socket and esp32spi interface |
| 31 | +requests.set_socket(socket, esp) |
| 32 | + |
| 33 | +JSON_GET_URL = "http://httpbin.org/get" |
| 34 | + |
| 35 | +# Define a custom header as a dict. |
| 36 | +headers = {"user-agent" : "blinka/1.0.0"} |
| 37 | + |
| 38 | +print("Fetching JSON data from %s..."%JSON_GET_URL) |
| 39 | +response = requests.get(JSON_GET_URL, headers=headers) |
| 40 | +print('-'*60) |
| 41 | + |
| 42 | +json_data = response.json() |
| 43 | +headers = json_data['headers'] |
| 44 | +print("Response's Custom User-Agent Header: {0}".format(headers['User-Agent'])) |
| 45 | +print('-'*60) |
| 46 | + |
| 47 | +# Read Response's HTTP status code |
| 48 | +print("Response HTTP Status Code: ", response.status_code) |
| 49 | +print('-'*60) |
| 50 | + |
| 51 | +# Read Response, as raw bytes instead of pretty text |
| 52 | +print("Raw Response: ", response.content) |
| 53 | + |
| 54 | +# Close, delete and collect the response data |
| 55 | +response.close() |
0 commit comments