def manager(self, secrets): """Initialize the WiFi Manager if it hasn't been cached and return it""" if self._manager is None: self._manager = adafruit_esp32spi_wifimanager.ESPSPI_WiFiManager( self.esp, secrets, None ) return self._manager
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 __init__(self, name): """Create an instance.""" # 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) # Set your Adafruit IO Username and Key in secrets.py # (visit io.adafruit.com if you need to create an account, # or if you need your Adafruit IO key.) ADAFRUIT_IO_USER = secrets['adafruit_io_user'] ADAFRUIT_IO_KEY = secrets['adafruit_io_key'] # Create an instance of the Adafruit IO REST client self._io = RESTClient(ADAFRUIT_IO_USER, ADAFRUIT_IO_KEY, wifi) self._name = '{0}-logging'.format(name) try: # Get the logging feed from Adafruit IO self._log_feed = self._io.get_feed(self._name) except AdafruitIO_RequestError: # If no logging feed exists, create one self._log_feed = self._io.create_new_feed(self._name)
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 _initialize_wifi(self): # Get wifi details and more from a secrets.py file try: from secrets import secrets self._secrets = secrets except ImportError as e: print( "WiFi secrets are kept in secrets.py, please add them there!") raise e from None # ESP32 Setup try: esp32_cs = DigitalInOut(board.D13) esp32_ready = DigitalInOut(board.D11) esp32_reset = DigitalInOut(board.D12) except AttributeError: esp32_cs = DigitalInOut(board.ESP_CS) esp32_ready = DigitalInOut(board.ESP_BUSY) esp32_reset = DigitalInOut(board.ESP_RESET) self._spi = busio.SPI(board.SCK, board.MOSI, board.MISO) self._esp = adafruit_esp32spi.ESP_SPIcontrol( self._spi, esp32_cs, esp32_ready, esp32_reset, service_function=self.service) status_light = neopixel.NeoPixel(board.NEOPIXEL, 1, brightness=0.1) self.wifi = adafruit_esp32spi_wifimanager.ESPSPI_WiFiManager( self._esp, self._secrets, status_light)
def initialize(myName, motorFunc): robotName = myName esp32_cs = DigitalInOut(board.D13) esp32_ready = DigitalInOut(board.D11) esp32_reset = DigitalInOut(board.D12) spi = busio.SPI(board.SCK, board.MOSI, board.MISO) esp = adafruit_esp32spi.ESP_SPIcontrol(spi, esp32_cs, esp32_ready, esp32_reset) if esp.status == adafruit_esp32spi.WL_IDLE_STATUS: broadcast.send("ESP32 found") """Use below for Most Boards""" status_light = neopixel.NeoPixel( board.NEOPIXEL, 1, brightness=0.2) # Uncomment for Most Boards wifi = adafruit_esp32spi_wifimanager.ESPSPI_WiFiManager( esp, secrets, status_light) ### Feeds ### publishes["status"] = "{}/status".format(robotName) subscribes["motor"] = "{}/cmd/motor".format(robotName) subscribe_funcs["{}/cmd/motor".format(robotName)] = motorFunc subscribes["beep"] = "{}/cmd/beep".format(robotName) subscribes["servo"] = "{}/cmd/servo".format(robotName) # Connect to WiFi broadcast.send("Connecting to WiFi...") try: wifi.connect() broadcast.send("Connected!") except: broadcast.send("Could not connect") raise # Initialize MQTT interface with the esp interface minimqtt.set_socket(socket, esp) # Set up a MiniMQTT Client global mqtt_client mqtt_client = minimqtt.MQTT( broker=secrets["mqtt_broker"], port=1883, ) # Setup the callback methods above mqtt_client.on_connect = connected mqtt_client.on_disconnect = disconnected mqtt_client.on_message = message # Connect the client to the MQTT broker. broadcast.send("Connecting to MQTT Broker {}...".format( secrets["mqtt_broker_name"])) mqtt_client.connect() broadcast.send("MQTT initialized") global MQTT MQTT = True
def get_wifi(secrets): 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) esp = adafruit_esp32spi.ESP_SPIcontrol( spi, esp32_cs, esp32_ready,esp32_reset, esp32_gpio0) status_rgb = neopixel.NeoPixel(board.NEOPIXEL,1,brightness=0.2) return adafruit_esp32spi_wifimanager.ESPSPI_WiFiManager( esp,secrets,status_rgb)
def connect_wifi(): print('Connecting wifi...') 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) wifi = adafruit_esp32spi_wifimanager.ESPSPI_WiFiManager(esp, secrets, status_light) print('Done.') gc.collect() return wifi
def __init__(self): # Get wifi details and more from a secrets.py file esp32_cs = DigitalInOut(board.D13) esp32_ready = DigitalInOut(board.D11) esp32_reset = DigitalInOut(board.D12) self.spi = busio.SPI(board.SCK, board.MOSI, board.MISO) self.esp = adafruit_esp32spi.ESP_SPIcontrol(self.spi, esp32_cs, esp32_ready, esp32_reset) if self.esp.status == adafruit_esp32spi.WL_IDLE_STATUS: print("ESP32 found and in idle mode") print("Firmware vers.", self.esp.firmware_version) print("MAC addr:", [hex(i) for i in self.esp.MAC_address]) """Use below for Most Boards""" # status_light = neopixel.NeoPixel(board.NEOPIXEL, 1, brightness=0.2) # Uncomment for Most Boards #status_light = pygamer.pygamerNeoPixels self.wifi = adafruit_esp32spi_wifimanager.ESPSPI_WiFiManager( self.esp, secrets) #, status_light) ### Feeds ### self.status_feed = "roger/status/#" self.motor_cmd_feed = "roger/cmd/feather/motor" self.beep_cmd_feed = "roger/cmd/feather/beep" self.servo_cmd_feed = "roger/cmd/feather/servo" # Connect to WiFi print("Connecting to WiFi...") self.wifi.connect() print("Connected!") # Initialize MQTT interface with the esp interface MQTT.set_socket(socket, self.esp) # Set up a MiniMQTT Client self.mqtt_client = MQTT.MQTT( broker=secrets["mqtt_broker"], port=1883, ) # Setup the callback methods above self.mqtt_client.on_connect = self.connected self.mqtt_client.on_disconnect = self.disconnected self.mqtt_client.on_message = self.message # Connect the client to the MQTT broker. print("Connecting to MQTT...Broker {0}".format( secrets["mqtt_broker_name"])) self.mqtt_client.connect() print("Connected to broker {0}".format(secrets["mqtt_broker_name"]))
def __init__(self, name, status_light): esp32_cs = DigitalInOut(board.D13) esp32_ready = DigitalInOut(board.D11) esp32_reset = DigitalInOut(board.D12) self.spi = busio.SPI(board.SCK, board.MOSI, board.MISO) self.esp = adafruit_esp32spi.ESP_SPIcontrol(self.spi, esp32_cs, esp32_ready, esp32_reset) if self.esp.status == adafruit_esp32spi.WL_IDLE_STATUS: print("ESP32 found and in idle mode") print("Firmware vers.", self.esp.firmware_version) print("MAC addr:", [hex(i) for i in self.esp.MAC_address]) self.status_light = status_light # pygamer.pygamerNeoPixels self.wifi = adafruit_esp32spi_wifimanager.ESPSPI_WiFiManager(self.esp, secrets, self.status_light) ### Feeds ### self.name = name self.status_feed = "{0}/status".format(name) # Connect to WiFi print("Connecting to WiFi...") self.wifi.connect() print("Connected!") # Initialize MQTT interface with the esp interface MQTT.set_socket(socket, self.esp) # Set up a MiniMQTT Client self.mqtt_client = MQTT.MQTT( broker=secrets["mqtt_broker"], port=1883, ) # Setup the callback methods above self.mqtt_client.on_connect = self.connected self.mqtt_client.on_disconnect = self.disconnected self.mqtt_client.on_message = self.message # Connect the client to the MQTT broker. print("Connecting to MQTT...Broker {0}".format(secrets["mqtt_broker_name"])) self.mqtt_client.connect() print("Connected to broker {0}".format(secrets["mqtt_broker_name"])) self.publish_message(self.status_feed, "{0} has connected to {1}".format(name, secrets["mqtt_broker_name"]))
def push_to_io(self, feed_key, data): # pylint: disable=line-too-long """Push data to an adafruit.io feed :param str feed_key: Name of feed key to push data to. :param data: data to send to feed """ # pylint: enable=line-too-long try: aio_username = secrets["aio_username"] aio_key = secrets["aio_key"] except KeyError: raise KeyError( "Adafruit IO secrets are kept in secrets.py, please add them there!\n\n" ) wifi = adafruit_esp32spi_wifimanager.ESPSPI_WiFiManager( self._esp, secrets, None ) io_client = IO_HTTP(aio_username, aio_key, wifi) while True: try: feed_id = io_client.get_feed(feed_key) except AdafruitIO_RequestError: # If no feed exists, create one feed_id = io_client.create_new_feed(feed_key) except RuntimeError as exception: print("An error occured, retrying! 1 -", exception) continue break while True: try: io_client.send_data(feed_id["key"], data) except RuntimeError as exception: print("An error occured, retrying! 2 -", exception) continue except NameError as exception: print(feed_id["key"], data, exception) continue break
import adafruit_esp32spi.adafruit_esp32spi_socket as socket import adafruit_minimqtt as MQTT try: from settings import settings except ImportError: print("Settings import failed") raise # --- Wifi Variables esp32_cs = DigitalInOut(board.D9) esp32_ready = DigitalInOut(board.D11) esp32_reset = DigitalInOut(board.D12) spi = busio.SPI(board.SCK, board.MOSI, board.MISO) esp = adafruit_esp32spi.ESP_SPIcontrol(spi, esp32_cs, esp32_ready, esp32_reset) wifi = adafruit_esp32spi_wifimanager.ESPSPI_WiFiManager(esp, settings) ip = str(settings['ip']) # --- MQTT Variables client_id = "creature" + str(settings['creature_id']) sensors_topic = "/" + client_id + "/sensors" actuators_topic = "/" + client_id + "/actuators" mqtt_client = MQTT.MQTT(broker=ip, port=1883, client_id=client_id) # --- Message Variables command = -1 payload = -1 message_received = True # --- Command list Variable commands = {
from esp32spi_settings import settings except ImportError: print("WiFi settings are kept in esp32spi_settings.py, please add them there!") raise print("ESP32 SPI webclient test") DATA_SOURCE = "https://api.thingspeak.com/channels/1417/feeds.json?results=1" DATA_LOCATION = ["feeds", 0, "field2"] 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) wifi = adafruit_esp32spi_wifimanager.ESPSPI_WiFiManager(esp, settings, board.NEOPIXEL) # neopixels pixels = neopixel.NeoPixel(board.A1, 16, brightness=0.3) pixels.fill(0) # we'll save the value in question last_value = value = None while True: try: print("Fetching json from", DATA_SOURCE) response = wifi.get(DATA_SOURCE) print(response.json()) value=response.json() for key in DATA_LOCATION:
# Get wifi details and more from a secrets.py file try: from secrets import secrets except ImportError: print("WiFi secrets are kept in secrets.py, please add them there!") raise # Raspberry Pi RP2040 esp32_cs = DigitalInOut(board.GP13) esp32_ready = DigitalInOut(board.GP14) esp32_reset = DigitalInOut(board.GP15) spi = busio.SPI(board.GP10, board.GP11, board.GP12) esp = adafruit_esp32spi.ESP_SPIcontrol(spi, esp32_cs, esp32_ready, esp32_reset) wifi = adafruit_esp32spi_wifimanager.ESPSPI_WiFiManager(esp, secrets) # Configure the RP2040 Pico LED Pin as an output led_pin = DigitalInOut(board.LED) led_pin.switch_to_output() # Define callback functions which will be called when certain events happen. # pylint: disable=unused-argument def connected(client): # Connected function will be called when the client is connected to Adafruit IO. print("Connected to Adafruit IO! ") def subscribe(client, userdata, topic, granted_qos): # This method is called when the client subscribes to a new feed.
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 print("MAC addr:", [hex(i) for i in esp.MAC_address]) print("MAC addr actual:", [hex(i) for i in esp.MAC_address_actual]) # 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) 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() ## To you want to create an un-protected WIFI hotspot to connect to with secrets:" # secrets = {"ssid": "My ESP32 AP!"} # wifi = wifimanager.ESPSPI_WiFiManager(esp, secrets, status_light) # wifi.create_ap() class SimpleWSGIApplication: """
import ujson as json_module print("ESP32 SPI simple web server test!") # SAM32 board ESP32 Setup dtr = DigitalInOut(board.DTR) esp32_cs = DigitalInOut(board.TMS) #GPIO14 esp32_ready = DigitalInOut(board.TCK) #GPIO13 esp32_reset = DigitalInOut(board.RTS) spi = busio.SPI(board.SCK, board.MOSI, board.MISO) esp = adafruit_esp32spi.ESP_SPIcontrol(spi, esp32_cs, esp32_ready, esp32_reset, gpio0_pin=dtr, debug=False) ## 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) wifi.create_ap() class SimpleWSGIApplication: """ An example of a simple WSGI Application that supports basic route handling and static asset file serving for common file types """ INDEX = "/index.html" CHUNK_SIZE = 8912 # max number of bytes to read at once when reading files def __init__(self, static_dir=None, debug=False): self._debug = debug self._listeners = {} self._start_response = None
def restart_server(): print("Failed to update server, restarting ESP32\n", e) wifi = wifimanager.ESPSPI_WiFiManager(esp, secrets, status_light) wifi.create_ap() wsgiServer.start()
import adafruit_requests as requests try: 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:
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
try: esp32_cs = DigitalInOut(board.ESP_CS) esp32_ready = DigitalInOut(board.ESP_BUSY) esp32_reset = DigitalInOut(board.ESP_RESET) except AttributeError: 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) 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) wifi = adafruit_esp32spi_wifimanager.ESPSPI_WiFiManager( esp, secrets, status_light) # Set your Adafruit IO Username and Key in secrets.py # (visit io.adafruit.com if you need to create an account, # or if you need your Adafruit IO key.) aio_username = secrets["aio_username"] aio_key = secrets["aio_key"] # Create an instance of the Adafruit IO HTTP client io = IO_HTTP(aio_username, aio_key, wifi) try: # Get the 'light' feed from Adafruit IO light_feed = io.get_feed("light") except AdafruitIO_RequestError: # If no 'light' feed exists, create one
led = DigitalInOut(board.D59) led.direction = digitalio.Direction.OUTPUT led.value = False print("Assigned SPI Module") spi = busio.SPI(board.SCK, board.MOSI, board.MISO) print("Assigned ESP SPI control") esp = adafruit_esp32spi.ESP_SPIcontrol(spi, esp32_cs, esp32_ready, esp32_reset, gpio0_pin=dtr, debug=False) status_light = neopixel.NeoPixel(board.NEOPIXEL, 1, brightness=0.2) print("ESP--Socket Interface Set") socket.set_interface(esp) secrets = {"ssid": "Hey Steve", "password": "******"} wificonnection = wifimanager.ESPSPI_WiFiManager(esp, secrets) wificonnection.connect() sam32webserverip = "http://192.168.4.1" sam32websererport = ":80" rgbArr = [(255,0,0), (0,255,0), (0,0,255)] duty_cycle_counter = 0 def pulseLED(led): led.value = True time.sleep(2) led.value = False def readAnalogPin(pin): analogvalue = analogReadPin.value