def wifi_connect(essid, password):
# Connect to the wifi. Based on the example in the micropython
# documentation.
wlan = network.WLAN(network.STA_IF)
wlan.active(True)
if not wlan.isconnected():
print('connecting to network ' + essid + '...')
wlan.connect(essid, password)
# connect() appears to be async - waiting for it to complete
while not wlan.isconnected():
print('waiting for connection...')
utime.sleep(4)
print('checking connection...')
print('Wifi connect successful, network config: %s' % repr(wlan.ifconfig()))
else:
# Note that connection info is stored in non-volatile memory. If
# you are connected to the wrong network, do an explicity disconnect()
# and then reconnect.
print('Wifi already connected, network config: %s' % repr(wlan.ifconfig()))
python类WLAN的实例源码
def do_connect():
import network
s_if = network.WLAN(network.STA_IF)
a_if = network.WLAN(network.AP_IF)
if a_if.active():
a_if.active(False)
if not s_if.isconnected():
s_if.active(True)
# Set static IP if configured.
try:
s_if.ifconfig((config.IP, config.SUBNET, config.GATEWAY, config.DNS))
except:
if not config.SILENT:
print("Static IP not configured. Setting IP via DHCP.")
# Connect to Wifi.
s_if.connect(secrets.WIFI_SSID, secrets.WIFI_PASSPHRASE)
while not s_if.isconnected():
pass
if not config.SILENT:
print("Wifi connected: ", s_if.ifconfig())
def do_connect(ssid, pwd, TYPE, hard_reset=True):
interface = network.WLAN(TYPE)
# Stage zero if credential are null disconnect
if not pwd or not ssid :
print('Disconnecting ', TYPE)
interface.active(False)
return None
if TYPE == network.AP_IF:
interface.active(True)
time.sleep_ms(200)
interface.config(essid=ssid, password=pwd)
return interface
if hard_reset:
interface.active(True)
interface.connect(ssid, pwd)
# Stage one check for default connection
print('Connecting')
for t in range(120):
time.sleep_ms(250)
if interface.isconnected():
print('Yes! Connected')
return interface
if t == 60 and not hard_reset:
# if still not connected
interface.active(True)
interface.connect(ssid, pwd)
# No way we are not connected
print('Cant connect', ssid)
return None
#----------------------------------------------------------------
# MAIN PROGRAM STARTS HERE
def scan_wifi(self, mode):
import network
n = network.WLAN(mode)
return n.scan()
# @timed_function
def setup_conn(port, accept_handler):
global listen_s
listen_s = socket.socket()
listen_s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
ai = socket.getaddrinfo("0.0.0.0", port)
addr = ai[0][4]
listen_s.bind(addr)
listen_s.listen(1)
if accept_handler:
listen_s.setsockopt(socket.SOL_SOCKET, 20, accept_handler)
for i in (network.AP_IF, network.STA_IF):
iface = network.WLAN(i)
if iface.active():
print("WebREPL daemon started on ws://%s:%d" % (iface.ifconfig()[0], port))
return listen_s
def __init__(self,pin1='5',pin2='4'):
"""initialize the function with the pins 5,4 if you don't choice else
fill pin,pin in when calling the function.
In this function we initialize the i2c bus and the oled display. Than
activate wifi radio. """
self.pin1 = pin1
self.pin2 = pin2
self.name = ''
self.strengt = ''
self.status = ''
self.kanaal = ''
self.i2c = machine.I2C(machine.Pin(5), machine.Pin(4))
self.oled = ssd1306.SSD1306_I2C(128, 64, self.i2c)
self.oled.fill(1)
self.oled.show()
self.wlan = network.WLAN(network.STA_IF)
self.wlan.active(True)
def wifi_connect(essid, password):
# Connect to the wifi. Based on the example in the micropython
# documentation.
wlan = network.WLAN(network.STA_IF)
wlan.active(True)
if not wlan.isconnected():
print('connecting to network ' + essid + '...')
wlan.connect(essid, password)
# connect() appears to be async - waiting for it to complete
while not wlan.isconnected():
print('waiting for connection...')
utime.sleep(4)
print('checking connection...')
print('Wifi connect successful, network config: %s' % repr(wlan.ifconfig()))
else:
# Note that connection info is stored in non-volatile memory. If
# you are connected to the wrong network, do an explicity disconnect()
# and then reconnect.
print('Wifi already connected, network config: %s' % repr(wlan.ifconfig()))
def wifi_config():
global cfg
global client
global CLIENT_ID
cfg = load_config()
print(cfg)
print('starting wifi connection')
wlan = network.WLAN(network.STA_IF)
wlan.active(True)
wlan.connect(cfg['ap']['ssid'], cfg['ap']['pwd'])
while not wlan.isconnected():
print('wait connection...')
await asyncio.sleep(1)
wlan.ifconfig()
mqtt_cfg = cfg['mqtt']
mqtt_connection(mqtt_cfg)
def cb_listssid():
response_header = '''
<h1>Wi-Fi Client Setup</h1>
<form action="/setconf" method="post">
<label for="ssid">SSID</label>
<select name="ssid" id="ssid">'''
import network
sta_if = network.WLAN(network.STA_IF)
response_variable = ''
for ssid, *_ in if_sta.scan():
response_variable += '<option value="{0}">{0}</option>'.format(ssid.decode("utf-8"))
response_footer = '''
</select> <br/>
Password: <input name="password" type="password"></input> <br />
<input type="submit" value="Submit">
</form>
'''
return response_header + response_variable + response_footer
# Temperature Sensor contents
def main(server=SERVER):
global c
wlan = network.WLAN(network.STA_IF)
wlan.active(True)
if not wlan.isconnected():
print('connecting to network...')
wlan.connect(SSID, PASS)
while not wlan.isconnected():
pass
print('[Network Config]\n ', wlan.ifconfig())
c = MQTTClient(CLIENT_ID, server)
reconnect()
set_led() # sets led to off
try:
while True:
if not wlan.isconnected():
reconnect()
c.wait_msg()
finally:
c.disconnect()
def main(server=SERVER):
global c
wlan = network.WLAN(network.STA_IF)
wlan.active(True)
if not wlan.isconnected():
print('connecting to network...')
wlan.connect(SSID, PASS)
while not wlan.isconnected():
pass
print('[Network Config]\n ', wlan.ifconfig())
c = MQTTClient(CLIENT_ID, server)
reconnect()
set_led() # sets led to off
try:
while True:
if not wlan.isconnected():
reconnect()
c.wait_msg()
finally:
c.disconnect()
def do_connect(forCheck=True):
import network
sta_if = network.WLAN(network.STA_IF)
ap_if = network.WLAN(network.AP_IF)
if ap_if.active():
ap_if.active(False)
if not sta_if.isconnected():
print('connecting to network...')
sta_if.active(True)
sta_if.connect('SSID', 'PASSOWRD')
import time
while not sta_if.isconnected():
time.sleep(1)
print('.',)
if forCheck:
print('')
print('network config:', sta_if.ifconfig())
#do_connect()
def wifi_connect(ssid, pwd):
"""
Connect to a wifi 'ssid' with password 'pwd'
"""
sta_if = network.WLAN(network.STA_IF)
ap_if = network.WLAN(network.AP_IF)
if ap_if.active():
ap_if.active(False)
if not sta_if.isconnected():
print('Connecting to network {}...'.format(ssid))
sta_if.active(True)
sta_if.connect(ssid, pwd)
while not sta_if.isconnected():
pass
print("Connected!")
return 'IP address: %s' % sta_if.ifconfig()[0]
def wifi_connect(ssid, pwd):
"""
Connect to a wifi 'ssid' with password 'pwd'
"""
sta_if = network.WLAN(network.STA_IF)
ap_if = network.WLAN(network.AP_IF)
if ap_if.active():
ap_if.active(False)
if not sta_if.isconnected():
print('connecting to network...')
sta_if.active(True)
sta_if.connect(ssid, pwd)
while not sta_if.isconnected():
pass
return 'IP address: %s' % sta_if.ifconfig()[0]
def connect(ssid,auth,timeout=16000):
from network import WLAN, STA_IF, AP_IF
global uplink
uplink = WLAN(STA_IF)
uplink.active(True)
uplink.connect(ssid, auth)
started= ticks_ms()
while True:
if uplink.isconnected():
return True
else:
if ticks_diff(ticks_ms(), started) < timeout:
sleep_ms(100)
continue
else:
return False
def connectWifi(SSID, password):
import network
sta_if = network.WLAN(network.STA_IF)
ap_if = network.WLAN(network.AP_IF)
if ap_if.active():
ap_if.active(False)
if not sta_if.isconnected():
print('connecting to network...')
sta_if.active(True)
sta_if.connect(SSID, password)
while not sta_if.isconnected():
pass
print('Network configuration:', sta_if.ifconfig())
def connect_to_wifi(self, ssid, password, mode, wait_for_ip=0):
import network, time
log.info("Attempting to connect to WiFi '{}' with password '{}'...".format(ssid, password))
n = network.WLAN(mode)
n.active(True)
n.connect(ssid, password)
# Wait for IP address to be provided
count = 0
while not n.isconnected() and count < wait_for_ip:
log.info("Waiting to obtain IP ... ({} sec remaining)".format(str(wait_for_ip - count)))
time.sleep(1)
count += 1
# Get provided IP
ip = n.ifconfig()[0]
if ip == "0.0.0.0":
log.info("Could not obtain IP on '{}'".format(ssid))
else:
log.info("Connected with IP '{}'".format(ip))
return ip
# @timed_function
def connect():
ap_if = network.WLAN(network.AP_IF)
ap_if.active(True)
if config.USE_AP:
sta_if = network.WLAN(network.STA_IF)
sta_if.active(True)
print('connecting to network...')
start_time = time.time()
sta_if.connect(config.SSID, config.PASSWORD)
while not sta_if.isconnected() and time.time() - start_time < 3.0:
pass
print('network config:', sta_if.ifconfig())
print('AP network config:', ap_if.ifconfig())
def start(port=21, verbose = 0, splash = True):
global ftpsocket, datasocket
global verbose_l
global client_list
global client_busy
global AP_addr, STA_addr
alloc_emergency_exception_buf(100)
verbose_l = verbose
client_list = []
client_busy = False
ftpsocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
datasocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
ftpsocket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
datasocket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
ftpsocket.bind(('0.0.0.0', port))
datasocket.bind(('0.0.0.0', _DATA_PORT))
ftpsocket.listen(0)
datasocket.listen(0)
datasocket.settimeout(10)
ftpsocket.setsockopt(socket.SOL_SOCKET, _SO_REGISTER_HANDLER, accept_ftp_connect)
wlan = network.WLAN(network.AP_IF)
if wlan.active():
ifconfig = wlan.ifconfig()
# save IP address string and numerical values of IP adress and netmask
AP_addr = (ifconfig[0], num_ip(ifconfig[0]), num_ip(ifconfig[1]))
if splash:
print("FTP server started on {}:{}".format(ifconfig[0], port))
wlan = network.WLAN(network.STA_IF)
if wlan.active():
ifconfig = wlan.ifconfig()
# save IP address string and numerical values of IP adress and netmask
STA_addr = (ifconfig[0], num_ip(ifconfig[0]), num_ip(ifconfig[1]))
if splash:
print("FTP server started on {}:{}".format(ifconfig[0], port))
def __init__(self):
self.timeout = 60
self.net = WLAN(STA_IF)
self._ssid = self._password = None
self.token = None
def disable(self):
from gc import collect
from network import AP_IF
self.net.active(False)
WLAN(AP_IF).active(False) # Always ensure AP is disabled
del AP_IF
collect()
def __init__(self):
self.networks = NETWORKS
self.ap_config = AP_CONFIG
self.current_network_idx = None
self.ap = network.WLAN(network.AP_IF)
self.wlan = network.WLAN(network.STA_IF)
self.info = ()
webrepl.start()
def connect(self):
self.wlan = network.WLAN(mode=network.WLAN.STA)
if not self.wlan.isconnected() or self.ssid() != self.SSID:
for net in self.wlan.scan():
if net.ssid == self.SSID:
self.wlan.connect(self.SSID, auth=(network.WLAN.WPA2,
self.password))
while not self.wlan.isconnected():
machine.idle() # save power while waiting
break
else:
raise Exception("Cannot find network '{}'".format(SSID))
else:
# Already connected to the correct WiFi
pass
def connect(self):
self.wlan = network.WLAN(mode=network.WLAN.STA)
if not self.wlan.isconnected() or self.ssid() != self.SSID:
for net in self.wlan.scan():
if net.ssid == self.SSID:
self.wlan.connect(self.SSID, auth=(network.WLAN.WPA2,
self.password))
while not self.wlan.isconnected():
machine.idle() # save power while waiting
break
else:
raise Exception("Cannot find network '{}'".format(SSID))
else:
# Already connected to the correct WiFi
pass
def do_connect():
import network
sta_if = network.WLAN(network.STA_IF)
if not sta_if.isconnected():
print ('connecting to network...')
sta_if.active(True)
sta_if.connect('CASA_NETWORK','8fc51f86x2')
while not sta_if.isconnected():
pass
print ('network config', sta_if.ifconfig())
def do_connect():
sta_if = network.WLAN(network.STA_IF)
if not sta_if.isconnected():
print("Connecting")
sta_if.active(True)
sta_if.connect(WLAN_NAME, WLAN_PASS)
while not sta_if.isconnected():
pass
def main():
i2c = machine.I2C(machine.Pin(5), machine.Pin(4))
oled = ssd1306.SSD1306_I2C(128, 64, i2c)
oled.fill(1)
oled.show()
wlan = network.WLAN(network.STA_IF)
wlan.active(True)
while True:
try:
wlan_list = wlan.scan()
except:
wlan_list = [['NONE','NONE','NONE','NONE','NONE','NONE']]
for i in wlan_list:
name = str(i[0], 'utf8')
var = str(i[3])+' dBm'
status = return_wifi_sec(i[4])
kanaal = 'channel ' + str(i[2])
oled.fill(0)
oled.show()
if len(name) > 15:
oled.text(name[0:15],0,0)
oled.text(name[15:int(len(name))],0,10)
else:
oled.text(name,0,0)
oled.text(var,30,20)
oled.text(status,30,30)
oled.text(kanaal, 30,40)
oled.show()
utime.sleep_ms(10000)
def connect():
import network
sta_if = network.WLAN(network.STA_IF)
if not sta_if.isconnected():
print('connecting to network...')
status.violet()
sta_if.active(True)
sta_if.connect(SSID, PASSWORD)
while not sta_if.isconnected():
pass
print('network config:', sta_if.ifconfig())
def start(port=23,key=None,nostop=False): # TODO: take simpler default key as it will be reset
global _server_socket, netrepl_cfg
if nostop: # we want to check if it's already running and not restart it
if _server_socket: # not none
return # no new intialization _> stop here
stop()
if key is None:
key=netrepl_cfg.key
if key is None or len(key)==0:
key=bytearray(32) # empty default key
elif len(key) == 64:
key=ubinascii.unhexlify(key)
netrepl_cfg.key = key
# will be initialized after connection
# cc_out = chacha.ChaCha(key, bytearray(8))
_server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
_server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
ai = socket.getaddrinfo("0.0.0.0", port)
addr = ai[0][4]
_server_socket.bind(addr)
_server_socket.listen(1)
_server_socket.setsockopt(socket.SOL_SOCKET, 20, accept_telnet_connect)
for i in (network.AP_IF, network.STA_IF):
wlan = network.WLAN(i)
if wlan.active():
print("\nnetrepl: UlnoIOT netrepl server started on {}:{}".format(wlan.ifconfig()[0], port))
def wifi_disconnect():
# Disconnect from the current network. You may have to
# do this explicitly if you switch networks, as the params are stored
# in non-volatile memory.
wlan = network.WLAN(network.STA_IF)
if wlan.isconnected():
print("Disconnecting...")
wlan.disconnect()
else:
print("Wifi not connected.")