/ examples / adafruit_io_http / adafruit_io_simpletest.py
adafruit_io_simpletest.py
 1  """
 2  Sending data to Adafruit IO and receiving it.
 3  """
 4  from random import randint
 5  import board
 6  import busio
 7  from digitalio import DigitalInOut
 8  
 9  # ESP32 SPI
10  from adafruit_esp32spi import adafruit_esp32spi, adafruit_esp32spi_wifimanager
11  
12  # Import NeoPixel Library
13  import neopixel
14  
15  # Import Adafruit IO HTTP Client
16  from adafruit_io.adafruit_io import IO_HTTP, AdafruitIO_RequestError
17  
18  # Get wifi details and more from a secrets.py file
19  try:
20      from secrets import secrets
21  except ImportError:
22      print("WiFi secrets are kept in secrets.py, please add them there!")
23      raise
24  
25  # ESP32 Setup
26  try:
27      esp32_cs = DigitalInOut(board.ESP_CS)
28      esp32_ready = DigitalInOut(board.ESP_BUSY)
29      esp32_reset = DigitalInOut(board.ESP_RESET)
30  except AttributeError:
31      esp32_cs = DigitalInOut(board.D9)
32      esp32_ready = DigitalInOut(board.D10)
33      esp32_reset = DigitalInOut(board.D5)
34  
35  spi = busio.SPI(board.SCK, board.MOSI, board.MISO)
36  esp = adafruit_esp32spi.ESP_SPIcontrol(spi, esp32_cs, esp32_ready, esp32_reset)
37  status_light = neopixel.NeoPixel(
38      board.NEOPIXEL, 1, brightness=0.2
39  )  # Uncomment for Most Boards
40  """Uncomment below for ItsyBitsy M4"""
41  # status_light = dotstar.DotStar(board.APA102_SCK, board.APA102_MOSI, 1, brightness=0.2)
42  wifi = adafruit_esp32spi_wifimanager.ESPSPI_WiFiManager(esp, secrets, status_light)
43  
44  # Set your Adafruit IO Username and Key in secrets.py
45  # (visit io.adafruit.com if you need to create an account,
46  # or if you need your Adafruit IO key.)
47  aio_username = secrets["aio_username"]
48  aio_key = secrets["aio_key"]
49  
50  # Create an instance of the Adafruit IO HTTP client
51  io = IO_HTTP(aio_username, aio_key, wifi)
52  
53  try:
54      # Get the 'temperature' feed from Adafruit IO
55      temperature_feed = io.get_feed("temperature")
56  except AdafruitIO_RequestError:
57      # If no 'temperature' feed exists, create one
58      temperature_feed = io.create_new_feed("temperature")
59  
60  # Send random integer values to the feed
61  random_value = randint(0, 50)
62  print("Sending {0} to temperature feed...".format(random_value))
63  io.send_data(temperature_feed["key"], random_value)
64  print("Data sent!")
65  
66  # Retrieve data value from the feed
67  print("Retrieving data from temperature feed...")
68  received_data = io.receive_data(temperature_feed["key"])
69  print("Data from temperature feed: ", received_data["value"])