Last active
July 18, 2022 17:25
-
-
Save james2doyle/7b5c0c04844dc857a5dd428e2f28eecc to your computer and use it in GitHub Desktop.
An ESP32 script that connects to WIFI and starts a UDP server
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import network | |
import utime | |
import socket | |
import machine | |
p2 = machine.Pin(2, machine.Pin.OUT) # create input pin on GPIO2 (builtin LED) | |
p2.off() | |
def toggle_pin(): | |
p2.value(1) if p2.value() == 0 else p2.value(0) | |
tim0 = machine.Timer(0) | |
ssid = "my_ssid" | |
passwd = "my_password" | |
sta_if = network.WLAN(network.STA_IF) # create station interface | |
def connect(): | |
count = 0 | |
if sta_if.isconnected(): | |
sta_if.disconnect() | |
print ('started in the connected state') | |
print ('but now it is disconnected') | |
else: | |
print ('started in the disconnected state') | |
utime.sleep(1) # maybe try reducing this | |
if not sta_if.isconnected(): | |
print('connecting to hotspot...') | |
sta_if.ifconfig(('192.168.0.112', '255.255.255.0', '192.168.0.1', '8.8.8.8')) | |
sta_if.active(True) | |
try: | |
sta_if.connect(ssid, passwd) | |
except OSError as error: | |
try: | |
with open('errors.txt', 'a') as outfile: | |
outfile.write(str(error) + '\n') | |
except OSError: | |
pass | |
while (count < 5): | |
count += 1 | |
if (sta_if.isconnected()): | |
count = 0 | |
print ('network config:', sta_if.ifconfig()) | |
tim0.init(period=2000, mode=machine.Timer.PERIODIC, callback=lambda t:toggle_pin()) | |
break | |
print ('.', end = '') | |
utime.sleep(1) | |
if (count == 5): | |
try: | |
with open('errors.txt', 'a') as outfile: | |
outfile.write('failed to connect after 5 tries' + '\n') | |
except OSError: | |
pass | |
disconnect() # or you could get errors | |
machine.reset() # start again | |
try: | |
rssi = sta_if.status('rssi') | |
print ('RSSI = ' + str(rssi) + 'dBm') | |
except: | |
print ('signal level too low') | |
count = 0 # reset count | |
utime.sleep(1) | |
def disconnect(): | |
try: | |
# disconnects STA, even if it is not connected | |
sta_if.disconnect() | |
except: | |
pass | |
sta_if.active(False) | |
utime.sleep(1) | |
connect() | |
local_ip = '0.0.0.0' | |
server = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) # UDP protocol | |
server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) | |
server.bind((local_ip, 61234)) | |
print("start Listening at 61234. Use nc -u 192.168.0.112 61234 and start sending messages") | |
while True: | |
data, client_addr = server.recvfrom(1000) | |
print('client connected from', client_addr) | |
print("data: ", data) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment