Created
June 16, 2023 02:37
-
-
Save SealtielFreak/0473f125b2582231a2a7452110994f59 to your computer and use it in GitHub Desktop.
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 uwebsockets.client | |
import time | |
import network | |
import urequests | |
import micropython | |
DEFAULT_ESSID = 'network-esp8266' | |
DEFAULT_PASSWORD = 'ultra-secret-password' | |
def main_loop(): | |
if not connect_wlan(DEFAULT_ESSID, DEFAULT_PASSWORD): | |
print('Failure connection!') | |
return | |
valid_address = find_valid_ip('192.168.4.0', '255.255.255.0') | |
print('Valid socket addres:', valid_address) | |
while True: | |
with uwebsockets.client.connect('ws://' + valid_address + '/arm') as ws: | |
ws.send('Hello world!') | |
response = ws.recv() | |
print(response) | |
def connect_wlan(ssid, password, tries=8): | |
print('Connecting to WiFi Network Name:', DEFAULT_ESSID) | |
wlan = network.WLAN(network.STA_IF) | |
wlan.active(True) | |
start = time.ticks_ms() # start a millisecond counter | |
if not wlan.isconnected(): | |
wlan.connect(DEFAULT_ESSID, DEFAULT_PASSWORD) | |
print("Waiting for connection...") | |
counter = 0 | |
while not wlan.isconnected(): | |
time.sleep(1) | |
print(counter, '.', sep='', end='', ) | |
counter += 1 | |
if counter > tries: | |
return False | |
delta = time.ticks_diff(time.ticks_ms(), start) | |
print("Connect Time:", delta, 'milliseconds') | |
print('IP Address:', wlan.ifconfig()[0]) | |
return True | |
def ip_address_generator(ip_address, subnet_mask): | |
ip_binary = ''.join([bin(int(x)+256)[3:] for x in ip_address.split('.')]) | |
subnet_binary = ''.join([bin(int(x)+256)[3:] for x in subnet_mask.split('.')]) | |
network_address_binary = ip_binary[:subnet_binary.count('1')] + '0' * (32 - subnet_binary.count('1')) | |
broadcast_address_binary = ip_binary[:subnet_binary.count('1')] + '1' * (32 - subnet_binary.count('1')) | |
for i in range(int(network_address_binary, 2) + 1, int(broadcast_address_binary, 2)): | |
yield '.'.join([str(int(i >> (j * 8)) & 0xff) for j in range(4)][::-1]) | |
def find_valid_ip(ip_address, subnet_mask): | |
for ip in ip_address_generator(ip_address, subnet_mask): | |
try: | |
data = urequests.get("http://" + ip) | |
if data.status_code == 200: | |
return ip | |
except OSError: | |
continue | |
if __name__ == "__main__": | |
main_loop() | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment