我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用network.WLAN。
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 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_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 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 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.")
def disable_wifi_ap(): # Disable the built-in access point. wlan = network.WLAN(network.AP_IF) wlan.active(False) print('Disabled access point, network status is %s' % wlan.status())
def getClientID(): from ubinascii import hexlify import network return "ESP_" + str(hexlify(network.WLAN().config('mac')).decode()[6:].upper(), "utf-8")
def periodic_tasks(): # Called every few seconds # Check if the time has been set. epoch = time.mktime((2016,1,1,0,0,0,0,0,0)) time_is_set = ( time.time() > epoch ) if not time_is_set: # Check if the network STA is configured. sta = network.WLAN(network.STA_IF) if sta.isconnected(): #Trying to sync with ntp try: ntptime.settime() except OSError: print("Failed to sync with ntp")
def wait_connect(): """Wait for wifi to be connected before attempting mqtt.""" for x in range(CONNECT_WAIT): wlan = network.WLAN(network.STA_IF) if wlan.isconnected(): print(wlan.ifconfig()) return True time.sleep(1) else: return False
def WorkMode_STA(essid,pwd): sta_mode=network.WLAN(network.STA_IF)#???????STA?? sta_mode.active(True)#???? sta_mode.connect(essid,pwd)#essid:WIFI?? pwd:WIFI?? #??????????? while not sta_mode.isconnected(): pass print('IP:', sta_mode.ifconfig()[0])#??IP?? #ifconfig() (ip, subnet, gateway, dns) return sta_mode.ifconfig()[0]
def WorkMode_AP(essid,pwd): ap_mode=network.WLAN(network.AP_IF)#???????AP?? ap_mode.active(True)#???? ap_mode.config(essid,pwd)#??WIFI??,essid:WIFI?? pwd:WIFI?? print('IP:', ap_mode.ifconfig()[0])#??IP?? return ap_mode.ifconfig()[0]
def do_connect(): sta_if = network.WLAN(network.STA_IF) p2 = Pin(2, Pin.OUT) sta_if.active(False) if not sta_if.isconnected(): p2.low() print('connecting to network...') sta_if.active(True) sta_if.connect('TurnipSmart', 'turnip2016') while not sta_if.isconnected(): pass if sta_if.isconnected(): print('connect success') p2.high() print('network config:', sta_if.ifconfig())
def wifi_config(): global cfg global client global CLIENT_ID print('load configuration') f = open('config.json') cfg = json.loads(f.read()) f.close() 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'] client = MQTTClient( CLIENT_ID, mqtt_cfg["broker"], port=mqtt_cfg["port"], keepalive=mqtt_cfg["keepalive"]) will_msg = {'id': CLIENT_ID, 'status': False, 'msg': 'The connection from this device is lost:(' } client.set_last_will('/device/will/status', json.dumps(will_msg)) client.set_callback(on_message) client.connect() client.subscribe('/device/{0}/switch'.format(CLIENT_ID.decode("utf-8")), 0)
def setup(): global d d = dht.DHT22(Pin(2)) wlan = network.WLAN(network.STA_IF) wlan.active(True) cfg = load_config() ap = cfg['ap'] wlan.connect(ap['ssid'], ap['pwd']) while not wlan.isconnected(): machine.idle() wifi(cfg['mqtt'])
def ifconfig(): import network sta_if = network.WLAN(network.STA_IF) if sta_if.active() : (ip, subnet, gateway, dns) = sta_if.ifconfig() print("Station:\n\tip: {}\n\tsubnet: {}\n\tgateway: {}\n\tdns: {}".format(ip, subnet, gateway, dns)) ap_if = network.WLAN(network.AP_IF) if ap_if.active() : (ip, subnet, gateway, dns) = ap_if.ifconfig() print("Access Point:\n\tip: {}\n\tsubnet: {}\n\tgateway: {}\n\tdns: {}".format(ip, subnet, gateway, dns))
def get_sta_stats(self): sta = network.WLAN(network.STA_IF) return self.get_wlan_stats(sta)
def get_ap_stats(self): ap = network.WLAN(network.AP_IF) wlan_stats = self.get_wlan_stats(ap) wlan_stats['config'] = self.get_wlan_config_stats(ap) return wlan_stats
def save_ap_config(self, api_request): config = api_request['body'] ap = network.WLAN(network.AP_IF) logging.info("config: {}".format(config)) ap.config( #mac=config['mac'], essid=config['essid'], channel=config['channel'], hidden=config['hidden'] ) return self.get_wlan_config_stats(ap)
def main(self): loop.create_task(self.led_ctrl()) sta_if = WLAN(STA_IF) conn = False while not conn: while not sta_if.isconnected(): await asyncio.sleep(1) self.dprint('Awaiting WiFi.') # Repeats forever if no stored connection. await asyncio.sleep(3) try: await self.connect() conn = True except OSError: self.close() # Close socket self.dprint('Awaiting broker.') self.dprint('Starting.') self.outage = False n = 0 while True: await asyncio.sleep(60) gc.collect() # For RAM stats. msg = 'Mins: {} repubs: {} outages: {} RAM free: {} alloc: {} Longest outage: {}s'.format( n, self.REPUB_COUNT, self.outages, gc.mem_free(), gc.mem_alloc(), self.max_outage) self.pub_msg('debug', msg) n += 1 # Topic names in dict enables multiple Sonoff units to run this code. Only main.py differs.
def do_connect(): import network wlan = network.WLAN(network.STA_IF) wlan.active(True) if not wlan.isconnected(): print('connecting to network...') wlan.connect("MY_WIFI_SSID", "MY_PASSWORD") while not wlan.isconnected(): pass print('network config:', wlan.ifconfig())
def __init__(self,bb_mqtt_id="None",mqtt_broker="None",mqtt_port=0,mqtt_user="None",mqtt_passwd="None",topic="None"): self.relay_one = Pin(12,Pin.OUT) self.relay_two = Pin(13,Pin.OUT) self.bb_mqtt_id = "ElectroDragon" self.mqtt_broker = mqtt_broker self.mqtt_port = mqtt_port self.mqtt_user = mqtt_user self.mqtt_passwd = mqtt_passwd self.topic = topic self.mqtt = MQTTClient(self.bb_mqtt_id,self.mqtt_broker,self.mqtt_port,self.mqtt_user,self.mqtt_passwd) self.sta_if = network.WLAN(network.STA_IF) self.programs = {b'fermentation':[18.0,22.0],b'maturation':[0.0,2.0],b'priming':[23.0,25.0]}
def __init__(self, bb_mqtt_id="None", mqtt_broker="None", mqtt_port=0, mqtt_user="None", mqtt_passwd="None", step="None"): self.MINUTES_TO_SLEEP = 1 self.SLEEP_TIME = self.MINUTES_TO_SLEEP * 10 * 1000 self.DO_SLEEP = False self.MATURATION = 1 self.BREWING = 0 self.STEP = step self.mqtt_broker = mqtt_broker self.mqtt_port = mqtt_port self.mqtt_user = mqtt_user self.mqtt_passwd = mqtt_passwd self.mqtt_id = bb_mqtt_id self.sta_if = network.WLAN(network.STA_IF) # fermentacao self.brew_low = 17 self.brew_ok = 20 self.brew_bit_high = 22 self.brew_very_high = 23 # maturacao self.mat_low = 4 self.mat_ok = 6 self.mat_bit_high = 8 self.mat_very_high = 9 # temps: low, ok, bit high, high self.tempFor = {self.BREWING: [17, 20, 22, 23], self.MATURATION: [0, 4, 7, 9]} self.myMQTT = MQTTClient(self.mqtt_id, self.mqtt_broker, self.mqtt_port, self.mqtt_user, self.mqtt_passwd)
def __init__(self, bb_mqtt_id="None", mqtt_broker="None", mqtt_port=0, mqtt_user="None", mqtt_passwd="None", topic="None"): self.relay_one = Pin(12, Pin.OUT) self.relay_two = Pin(13, Pin.OUT) self.bb_mqtt_id = "ElectroDragon" self.mqtt_broker = mqtt_broker self.mqtt_port = mqtt_port self.mqtt_user = mqtt_user self.mqtt_passwd = mqtt_passwd self.topic = topic self.mqtt = MQTTClient(self.bb_mqtt_id, self.mqtt_broker, self.mqtt_port, self.mqtt_user, self.mqtt_passwd) self.sta_if = network.WLAN(network.STA_IF) self.programs = {'fermentation': [18.0, 22.0], 'maturation': [0.0, 2.0], 'priming': [20.0, 23.0]} self.style = 'fermentation' self.programLoad() self.MINIMUM = self.programs[self.style][0] self.MAXIMUM = self.programs[self.style][1] self.relay_status = "OFF" print("Waiting IP...") size = 0 while size < 11: try: size = len(self.sta_if.ifconfig()[0]) time.sleep_ms(80) except: size = 0 self.mqtt.connect()