def connect_known_wlan(known_wlans): wlan = WLAN(mode=WLAN.STA) available_wlans = wlan.scan() seen_ssids = frozenset([w.ssid for w in available_wlans]) known_ssids = frozenset([ssid for ssid in known_wlans]) ssids_to_use = list(seen_ssids & known_ssids) # connect to first known wlan seen for ssid in ssids_to_use: auth_tuple = None net_properties = known_wlans[ssid] net_config = net_properties['net_config'] auth = net_properties['auth'] if auth == WLAN.WPA2: password = net_properties['password'] auth_tuple = (WLAN.WPA2, password) if net_config and _connect(wlan, ssid, net_config, auth_tuple): logger.info("connected to %s" % str(wlan.ifconfig())) return True elif _connect(wlan, ssid, auth_tuple): logger.info("connected to %s" % str(wlan.ifconfig())) return True logger.error("saw %s, failed to connect to any." % str(seen_ssids)) return False
def modbus_tcp_connection_init(): # initialize lopy wifi object lopy_wlan = WLAN() # config as station-mode lopy_wlan.init(mode=WLAN.STA) lopy_wlan.ifconfig(id=0) # Scan for an available wifi and connect to "USR-WIFI232-604_27BC" ssid_usr_wifi232 = "USR-WIFI232-604_27BC" # ssid of usr-wifi module network_list = lopy_wlan.scan() for net in network_list: try: if net.ssid == ssid_usr_wifi232 : print("USR-WIFI232 founded! Connecting...") lopy_wlan.connect(ssid_usr_wifi232, timeout=5000) # wait for connection while not lopy_wlan.isconnected(): # do nothing or save power by idle using machine.idle() machine.idle() print("Connection succeeded!") print(lopy_wlan.ifconfig()) # lid LED to green color pycom.rgbled(0xFF00) else : # If SSID is not "USR-WIFI232-604_27BC", Do nothing. pass except Exception as e: print("Maybe, USR-WIFI232 access point is not avialable.") print("Exception : {}".format(e))
class wifi_pyboard(): def __init__(self, server_ssid="USR-WIFI232-604_27BC", connection_timeout=10): self.server_ssid = server_ssid self.timeout = connection_timeout self.wlan = WLAN() def connect(self): # config as station-mode self.wlan.init(mode=WLAN.STA) self.wlan.ifconfig(id=0) # Scan for an available wifi and connect to server network_list = self.wlan.scan() for net in network_list: try: if net.ssid == self.server_ssid: print("Server founded! Connecting...") self.wlan.connect(self.server_ssid, timeout=5000) # wait for connection while not self.wlan.isconnected(): # do nothing or save power by idle using machine.idle() machine.idle() print("Connection succeeded!") print(self.wlan.ifconfig()) else: # If SSID is not "USR-WIFI232-604_27BC", Do nothing. pass except Exception as e: print("Maybe, access point is not avialable.") print("Exception : {}".format(e))
def setup_new_config(logger): """ Start a WiFi AP that provides a configuration page. The device automatically reboots and applies modifications upon successful configuration. :param logger: status logger :type logger: LoggerFactory """ # Only one of this thread is allowed to run at a time if not wifi_lock.locked(): with wifi_lock: logger.info("New configuration setup started") # Config uses LED colours to indicate the state of the connection - lock is necessary to disable error pings led_lock.acquire(1) unique_id = ubinascii.hexlify(machine.unique_id()).decode() # set pycom up as access point wlan = WLAN(mode=WLAN.AP, ssid=config.get_config("device_name") + unique_id) # Connect to PmSensor using password set by the user wlan.init( mode=WLAN.AP, ssid=config.get_config("device_name") + unique_id, auth=(WLAN.WPA2, config.get_config("password")), channel=1, antenna=WLAN.INT_ANT, ) # Load HTML via entering 192,168.4.10 to browser wlan.ifconfig( id=1, config=("192.168.4.10", "255.255.255.0", "192.168.4.1", "192.168.4.1"), ) logger.info("Access point turned on as {}".format( config.get_config("device_name") + unique_id)) logger.info( "Configuration website can be accessed at 192.168.4.10") address = socket.getaddrinfo( "0.0.0.0", 80)[0][-1] # Accept stations from all addresses sct = socket.socket() # Create socket for communication sct.settimeout(int( float(config.get_config("config_timeout")) * 60)) # session times out after x seconds gc.collect( ) # frees up unused memory if there was a previous connection sct.bind(address) # Bind address to socket sct.listen(1) # Allow one station to connect to socket pycom.rgbled(0x000055) # Blue LED - waiting for connection get_new_config(sct, logger) wlan.deinit() # turn off wifi gc.collect() logger.info("rebooting...") machine.reset()
def connect_wifi(known_nets): wl = WLAN() wl.mode(WLAN.STA) original_ssid = wl.ssid() original_auth = wl.auth() print(" [*] Scanning for known wifi nets") available_nets = wl.scan() print(' [+] Found {} WiFi APs.'.format(len(available_nets))) for available_net in available_nets: print(' - {} ({})'.format(available_net.ssid, available_net.rssi)) nets = frozenset([e.ssid for e in available_nets]) known_nets_names = frozenset([key for key in known_nets]) net_to_use = list(nets & known_nets_names) try: net_to_use = net_to_use[0] net_properties = known_nets[net_to_use] pwd = net_properties['pwd'] sec = [e.sec for e in available_nets if e.ssid == net_to_use][0] if 'wlan_config' in net_properties: wl.ifconfig(config=net_properties['wlan_config']) wl.connect(net_to_use, (sec, pwd), timeout=10000) while not wl.isconnected(): machine.idle() # save power while waiting print(" [+] Connected to " + net_to_use + " with IP address: " + wl.ifconfig()[0]) except Exception as e: print( " [-] Failed to connect to any known network, going into AP mode") wl.init(mode=WLAN.AP, ssid=original_ssid, auth=original_auth, channel=6, antenna=WLAN.INT_ANT)
def exp_start(): global stats global detailed_stats global run_stats wlan = WLAN(mode=WLAN.STA) print(ubinascii.hexlify(wlan.mac(), ':').decode()) if not wlan.isconnected(): wlan.connect(ssid='rasp', auth=(WLAN.WPA2, 'lalalala'), timeout=5000) while not wlan.isconnected(): machine.idle() print("I got IP" + wlan.ifconfig()[0]) host = wlan.ifconfig()[0] port = 8000 wlan_s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) print("socket created") wlan_s.bind((host, port)) wlan_s.listen(5) print("Waiting for initialization...") _thread.start_new_thread(receive_stats, ()) while (True): conn, addr = wlan_s.accept() print('Got connection from', addr) data = conn.recv(512) data = str(data)[2:][:-1] if (len(data) > 10): try: (init, ip, pkts) = data.split(":") if (init == "init"): pycom.rgbled(red) msg = ip + ":" + pkts run_stats = 0 time.sleep(1) lora.init(mode=LoRa.LORA, tx_iq=True, region=LoRa.EU868, frequency=freqs[0], power_mode=LoRa.TX_ONLY, bandwidth=LoRa.BW_125KHZ, sf=12) pkg = struct.pack(_LORA_PKG_FORMAT % len(msg), MY_ID, len(msg), msg) # lora_sock.send(pkg) for j in range(3): lora_sock.send(pkg) time.sleep(1) lora.init(mode=LoRa.LORA, rx_iq=True, region=LoRa.EU868, frequency=freqs[7], power_mode=LoRa.ALWAYS_ON, bandwidth=LoRa.BW_125KHZ, sf=12) pycom.rgbled(green) run_stats = 1 stats = [] detailed_stats = [] _thread.start_new_thread(receive_stats, ()) except: print("wrong packet format!")
def connect_wifi(): wlan = WLAN() wlan.init(mode=WLAN.STA) wlan.ifconfig(config=(config.WIFI_IP, config.WIFI_SUBNET, config.WIFI_GATEWAY, config.WIFI_DNS1)) wlan.connect(config.WIFI_SSID, auth=(WLAN.WPA2, config.WIFI_PASS), timeout=5000) return wlan.ifconfig()
def connect(): with open('wifi.json', 'rt') as f: config = load(f) wlan = WLAN(STA_IF) wlan.active(True) wlan.ifconfig((config['static_ip'], config['netmask'], config['gateway'], config['gateway'])) # add static IP wlan.connect(config['ssid'], config['password']) while not wlan.isconnected(): pass
def create_wifi(): print("Setting up WiFi") wlan = WLAN(mode=WLAN.AP, ssid='IOTA-CXC-MODULE', auth=(None), channel=7, antenna=WLAN.INT_ANT) wlan.ifconfig(config=('192.168.4.1', '255.255.255.0', '192.168.4.1', '8.8.8.8')) print(wlan.ifconfig())
class WiFi(): def __init__(self): self.timeout = 60 self.net = WLAN(STA_IF) self._ssid = self._password = None self.token = None def _get_network(self): raise NotImplementedError def get_network_token(self): from os import urandom r = str(int.from_bytes(urandom(2), 'little')) t = '0' * (4 - len(r)) + r del urandom, r collect() return t[:4] def Context(self, timeout): self.timeout = timeout self.token = self.get_network_token() if NET_SSID: self._ssid, self._password = NET_SSID.split('|') else: self._get_network() return WiFiContext(self) @property def connected(self): isc = self.net.isconnected() print('Is connected? {}'.format(isc)) return isc def enable(self): self.net.active(True) def connect(self, ssid=None, password=None, timeout=WIFI_TIMEOUT): ssid = self._ssid or ssid password = self._password or password self.net.ifconfig(((NET_IP, NET_NETMASK, NET_GATEWAY, NET_DNS))) self.net.connect(ssid, password) 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 send_data(self, topic, data): pass def get_data(self, topic): pass
def connectLocalBox(configFilePath): f = open(configFilePath, 'r') config=ujson.load(f) f.close() wlan = WLAN(mode=WLAN.STA) wlan.ifconfig(config=(config["ip"], config["mask"],config["gateway"], config["dns"])) wlan.scan() wlan.connect(config["ssid"], auth=(WLAN.WPA2, config["password"])) while not wlan.isconnected(): pass return wlan;
def set_wifi(essid, pwd, timeout=60): console_write('[NW: STA] SET WIFI: {}'.format(essid)) essid_found = False # Disable AP mode ap_if = WLAN(AP_IF) if ap_if.active(): ap_if.active(False) del ap_if # Set STA and Connect sta_if = WLAN(STA_IF) sta_if.active(True) if not sta_if.isconnected(): console_write('\t| [NW: STA] CONNECT TO NETWORK {}'.format(essid)) # Scan wifi network - retry workaround for _ in range(0, 2): if essid in (wifispot[0].decode('utf-8') for wifispot in sta_if.scan()): essid_found = True console_write( '\t| - [NW: STA] ESSID WAS FOUND {}'.format(essid_found)) break sleep(1) # Connect to the located wifi network if essid_found: # connect to network sta_if.connect(essid, pwd) # wait for connection, with timeout set while not sta_if.isconnected() and timeout > 0: console_write("\t| [NW: STA] Waiting for connection... " + str(timeout) + "/60") timeout -= 1 sleep(0.5) # Set static IP - here because some data comes from connection. if sta_if.isconnected() and __set_wifi_dev_static_ip(sta_if): sta_if.disconnect() del sta_if return set_wifi(essid, pwd) else: console_write( "\t| [NW: STA] Wifi network was NOT found: {}".format(essid)) return False console_write("\t|\t| [NW: STA] network config: " + str(sta_if.ifconfig())) console_write("\t|\t| [NW: STA] CONNECTED: " + str(sta_if.isconnected())) else: console_write("\t| [NW: STA] ALREADY CONNECTED TO {}".format(essid)) cfgput("devip", str(sta_if.ifconfig()[0])) set_uid_macaddr_hex(sta_if) return sta_if.isconnected()
def do_acess_point(): global ap_if if uname().machine == 'ESP32 module with ESP32': # Wemos ESP-WROOM-32 import network ap_if = network.WLAN(network.AP_IF) ap_if.active(True) ap_if.config(essid=access_point_name, authmode=network.AUTH_OPEN) elif uname().machine == 'WiPy with ESP32': # Wipy 2.0 import pycom from network import WLAN pycom.heartbeat(False) ap_if = WLAN(mode=WLAN.AP, ssid=access_point_name) ap_if.ifconfig( ('192.168.4.1', '255.255.255.0', '192.168.4.1', '192.168.4.1'))
def wlan_connect(): wifi = WLAN(mode=WLAN.STA) wifi.ifconfig(config=(__myip, __netmask, __gateway, __dns)) wifi.scan() # scan for available networks wifi.connect(ssid=__ssid, auth=(WLAN.WPA2, __nwpass)) while not wifi.isconnected(): pass syslog('WiPy is up and running') wifi.irq(trigger=WLAN.ANY_EVENT, wake=machine.SLEEP) machine.sleep()
def set_wifi(essid, pwd, timeout=60): console_write('[NW: STA] SET WIFI STA NW {}'.format(essid)) # Disable AP mode ap_if = WLAN(AP_IF) if ap_if.active(): ap_if.active(False) del ap_if # Set STA and Connect sta_if = WLAN(STA_IF) sta_if.active(True) # Set custom DHCP hostname sta_if.config(dhcp_hostname=cfgget('devfid')) # Check are we already connected if not sta_if.isconnected(): # Multiple essid and pwd handling with retry mechanism essid, pwd = __select_available_wifi_nw(sta_if, essid, pwd) # Connect to the located wifi network if essid is not None: console_write('\t| [NW: STA] CONNECT TO NETWORK {}'.format(essid)) # connect to network sta_if.connect(essid, pwd) # wait for connection, with timeout set while not sta_if.isconnected() and timeout > 0: console_write( "\t| [NW: STA] Waiting for connection... {} sec".format( timeout)) timeout -= 1 sleep_ms(500) # Set static IP - here because some data comes from connection. (subnet, etc.) if sta_if.isconnected() and __set_wifi_dev_static_ip(sta_if): sta_if.disconnect() del sta_if return set_wifi(essid, pwd) else: console_write( "\t| [NW: STA] Wifi network was NOT found: {}".format(essid)) return False console_write("\t|\t| [NW: STA] network config: " + str(sta_if.ifconfig())) console_write("\t|\t| [NW: STA] CONNECTED: " + str(sta_if.isconnected())) else: console_write("\t| [NW: STA] ALREADY CONNECTED TO {}".format(essid)) cfgput("devip", str(sta_if.ifconfig()[0])) set_dev_uid() return sta_if.isconnected()
def connect_wifi(cfg=None): if not cfg: from config import Config cfg = Config.load(debug=True) from network import WLAN import machine print('Starting WLAN, attempting to connect to ' + cfg.wifi_ssid) wlan = WLAN(0, WLAN.STA) wlan.ifconfig(config='dhcp') wlan.connect(ssid=cfg.wifi_ssid, auth=(WLAN.WPA2, cfg.wifi_key)) while not wlan.isconnected(): machine.idle() print('Connected')
def set_wlan_to_access_point(ssid="wipy_https_server", password="******", host_ip="192.168.4.1", log=lambda msg: None): log("Creating Access Point {} with password {}".format(ssid, password)) wlan = WLAN() wlan.deinit() wlan.ifconfig(config=(host_ip, '255.255.255.0', '0.0.0.0', '8.8.8.8')) wlan.init(mode=WLAN.AP, ssid=ssid, auth=(WLAN.WPA2, password), channel=5, antenna=WLAN.INT_ANT) return wlan
def connect_WiFi(ssid='NachoWifi', password='******'): wlan = WLAN(STA_IF) wlan.active(True) if not wlan.isconnected(): print('connecting to network...') wlan.connect(ssid, password) while not wlan.isconnected(): pass print('network config:', wlan.ifconfig()) mac = hexlify(WLAN().config('mac'), ':').decode() print('Oh Yes! Get Connected') print('Connected to NachoWifi') print('MAC Address: ', mac) print('IP Address: ', wlan.ifconfig()[0]) return wlan
def create_wifi(): # type: () -> str ssid = "QRGames Player" ap = WLAN(AP_IF) ap.active(True) ap.config(essid=ssid) return ap.ifconfig()[0]
def connect_wlan(): wlan = WLAN(STA_IF) wlan.active(True) wlan.connect('TPA', 'TurbenThal', 5000) while not wlan.isconnected(): continue print("Connected to WLAN ... IP", wlan.ifconfig()[0])
class WiFi(object): wlan = None config = None def can_see_ssid(self, ssid): networks = [w[0] for w in self.wlan.scan()] return ssid in networks def __init__(self, config): self.config = config self.wlan = WLAN(mode=WLAN.STA) def isconnected(): return self.wlan.isconnected() def connect_wifi(self): config = self.config if not self.wlan.isconnected(): for wlan in config['WLANS']: if self.can_see_ssid(wlan['WLAN_SSID']): print("Trying: {} ...".format(wlan['WLAN_SSID'])) self.wlan.connect(ssid=wlan['WLAN_SSID'], auth=(WLAN.WPA2, wlan['WLAN_KEY'])) # Give it a chance to get connected count = 0 while not self.wlan.isconnected() and count < 10: print("Waiting for connection... ({})".format(count)) count += 1 sleep(1) if not self.wlan.isconnected(): print("Giving up") if self.wlan.isconnected(): print("Connected: \n", self.wlan.ifconfig())
def connect_to_wifi(wifi_ssid, wifi_passwd): wlan = WLAN(mode=WLAN.STA) for ltry in range(3): print("Connecting to: " + wifi_ssid + ". Try " + str(ltry)) nets = wlan.scan() for net in nets: if net.ssid == wifi_ssid: print('Network ' + wifi_ssid + ' found!') wlan.connect(net.ssid, auth=(net.sec, wifi_passwd), timeout=5000) while not wlan.isconnected(): machine.idle() # save power while waiting break if wlan.isconnected(): break else: print('Cannot find network ' + wifi_ssid) flash_led_to(RED, 1) if not wlan.isconnected(): print('Cannot connect to network ' + wifi_ssid + '. Quitting!!!') sys.exit(1) else: print('WLAN connection succeeded!') flash_led_to(GREEN, 1) print(wlan.ifconfig())
def connect_sta(self,time_out = 120): config_dict = self.__get_board_config_js() sta_ssid = config_dict.get("sta_ssid","") if len(sta_ssid) <= 0: raise Exception("sta ssid not configed") sta_pwd = config_dict.get("sta_pwd","") if len(sta_pwd) <= 0: raise Exception("sta passworld not configed") sta_auth_type = config_dict.get("sta_auth_type","WPA2") if sta_auth_type == 'WEP': auth_type = 1 elif sta_auth_type == 'WPA': auth_type = 2 else: auth_type = 3 wlan=WLAN() wlan.mode(3) wlan.connect(ssid=sta_ssid,auth=(auth_type,sta_pwd)) time_out = int(time_out) while not wlan.isconnected(): if time_out < 0: raise Exception("Connect wifi sta timeout") time.sleep(1) time_out = time_out - 1 print(wlan.ifconfig()) return
def connect_to_network(): """ Connects to Wi-Fi Network Warning: we used firmware MicroPython 1.18.2.r7 [v1.8.6-849-df9f237], newer FW versions have an issue with the Wi-Fi driver as of 29/02/2020 (Scans OK but cannot connect) :return: True if we could connect to the Wi-Fi or otherwise False. """ wlan = WLAN(mode=WLAN.STA) # Scanning for networks nets = wlan.scan() for net in nets: print(net.ssid) if net.ssid == _WIFI_SSID: print("Found the network") wlan.connect(net.ssid, auth=(net.sec, _WIFI_PASS), timeout=5000) while not wlan.isconnected(): machine.idle() print("WLAN connection to", _WIFI_SSID, "succeeded!") break # The assigned IP address for the Pycom print("IP-address:", wlan.ifconfig()[0]) return wlan.isconnected()
class PyWiFi(object): def __init__(self, mode, ssid=None, password=None, hidden=False): self._ssid = ssid self._hidden = hidden if mode == WLAN.STA_AP or mode == WLAN.AP: self._wlan = WLAN(mode=mode, ssid=ssid, auth=(WLAN.WPA2, password), hidden=hidden) else: self._wlan = WLAN(mode=mode) def connect(self, ssid, password, timeout=5000): pycom.heartbeat(False) networks = self._wlan.scan() for network in networks: if network.ssid == ssid: print("[" + ssid + "]: connecting...") pycom.rgbled(0x110000) self._wlan.connect(network.ssid, auth=(network.sec, password), timeout=timeout) while not self._wlan.isconnected(): sleep(0.5) print("[" + ssid + "]: connected") pycom.rgbled(0x001100) break def printWLAN(self): print(self._wlan.ifconfig())
def connect_to_wifi_UPVIoT(wifi_user, wifi_passwd): wifi_ssid="UPV-IoT" wlan = WLAN(mode=WLAN.STA) if (wifi_user=="IOTPMxxx"): print("No te has leido el boletín de practicas... verdad?!?!?") sys.exit() for ltry in range(3): print("Connecting to: "+wifi_ssid+" as "+wifi_user+". Try "+str(ltry)) nets = wlan.scan() for net in nets: if net.ssid == wifi_ssid: print('Network '+wifi_ssid+' found!') wlan.connect(net.ssid, auth=(WLAN.WPA2_ENT, wifi_user, wifi_passwd), identity=wifi_user) while not wlan.isconnected(): machine.idle() # save power while waiting break if wlan.isconnected(): break else: print('Cannot find network '+wifi_ssid) flash_led_to(RED, 1) if not wlan.isconnected(): print('Cannot connect to network '+wifi_ssid+'. Quitting!!!') sys.exit(1) else: print('WLAN connection succeeded!') flash_led_to(GREEN, 1) print (wlan.ifconfig())
def sys_config(): from network import WLAN global MyName,debug,debugDNS,runREPL,runDNS,runWeb,threaded from config import * from config import MyName,debug,debugDNS,runREPL,runDNS,runWeb,threaded wlan=WLAN() ip = wlan.ifconfig()[0] if(ip == "0.0.0.0"): ip = "192.168.4.1" apMode = wlan.config('essid') try: x = open("/client.cfg") x.close() apMode += " - Wifi Client Mode" except: apMode += " - AP Enabled" if(wlan.isconnected()): apMode += ' - Connected' content = "MyName:\t\t" + str(MyName) + "\n" content += "Network:\t" + apMode + "\n" content += "IP Address:\t" + ip + "\n" content += "debug\t\t" + str(debug) + "\n" content += "debugDNS\t" + str(debugDNS) + "\n" content += "runREPL\t\t" + str(runREPL) + "\n" content += "runDNS\t\t" + str(runDNS) + "\n" content += "runWeb\t\t" + str(runWeb) + "\n" content += "threaded\t" + str(threaded) + "\n" return(content)
def connect_wpa2(ssid, password): wlan = WLAN(mode=WLAN.STA) is_connected = _connect(wlan, ssid, 'dhcp', (WLAN.WPA2, password)) if is_connected: logger.info("connected to %s" % str(wlan.ifconfig())) return is_connected
def wifiAsClient(): global wifi config = getConfig('config.wifi.json') client_if = WLAN(STA_IF) client_if.active(True) client_if.connect(config['ssid'], config['passphrase']) log.info(client_if.ifconfig()) wifi = client_if
def PrivateWlanConfiguration(): wlan = WLAN(mode=WLAN.STA) wlan.connect(ssid='OnePlus_7T_Pro', auth=(WLAN.WPA2, 'pycomTestingFacilityAtUiA')) while not wlan.isconnected(): machine.idle() print("WiFi connected succesfully") print(wlan.ifconfig()) pass
def connect_network(): sta_if = WLAN(STA_IF) if not sta_if.isconnected(): print('connecting to network...') sta_if.active(True) sta_if.connect(SSID, WPA_PASSWORD) while not sta_if.isconnected(): pass print('connected to network', sta_if.ifconfig())
def do_connect(SSID='LANTERN', PASS='******'): sta_if = WLAN(mode=WLAN.STA) if not sta_if.isconnected(): print('connecting to network...') sta_if.active(True) sta_if.connect(SSID, PASS) while not sta_if.isconnected(): pass print('network config:', sta_if.ifconfig())
def connect(): wlan = WLAN() if not wlan.isconnected(): wlan.connect(_SSID, auth=(WLAN.WPA2, 'phobiccoconut688'), timeout=5000) while not wlan.isconnected(): machine.idle() logging('WLAN connection succeeded!') logging("My IP address is: {0}".format(wlan.ifconfig()[0]))
def do_connect(): from network import WLAN sta_if = WLAN(network.STA_IF) if not sta_if.isconnected(): print('connecting to network...') sta_if.active(True) sta_if.connect(WIFISSID, WIFIPASS) while not sta_if.isconnected(): pass print('network config:', sta_if.ifconfig())
def connect_wifi(self): from network import WLAN if not self.cfg: raise ValueError("Can't initialise wifi, no config") self.log('Starting WLAN, attempting to connect to ' + ','.join(self.cfg.wifi.keys())) wlan = WLAN(0, WLAN.STA) wlan.ifconfig(config='dhcp') while not wlan.isconnected(): nets = wlan.scan() for network in nets: if network.ssid in self.cfg.wifi.keys(): self.log('Connecting to ' + network.ssid) self.feed_wdt() # just in case wlan.connect(ssid=network.ssid, auth=(network.sec, self.cfg.wifi[network.ssid])) while not wlan.isconnected(): idle() break self.feed_wdt() # just in case sleep_ms(2000) self.log('Connected as %s' % wlan.ifconfig()[0])
def connect_to_wifi_wipy(ssid, password, retries=10): """ Connect to a WIFI network """ wlan = WLAN(mode=WLAN.STA) print("Connecting to wifi network '%s'" % ssid) wlan.connect(ssid=ssid, auth=(WLAN.WPA2, password)) retry_count = 0 while not wlan.isconnected(): sleep(1) retry_count += 1 if retry_count > retries: return False print('Connected', wlan.ifconfig()) return True
def wlan(): """Connect in STA mode, fallback to AP""" try: import wlanconfig except ImportError: print("WLAN: no wlanconfig.py") wlanconfig = None wlan = WLAN(mode=WLAN.AP) except Exception as e: print("WLAN: error in wlanconfig.py: {}".format(e)) wlanconfig = None wlan = WLAN(mode=WLAN.AP) else: try: # configure the WLAN subsystem in station mode (the default is AP) wlan = WLAN(mode=WLAN.STA) print("WLAN: connecting to network (AP)...") wlan.connect(wlanconfig.ssid, auth=(WLAN.WPA2, wlanconfig.password), timeout=5000) print("WLAN: waiting for IP...") for tries in range(50): if wlan.isconnected(): print( """\ WLAN: connected! WiPy IP: {} NETMASK: {} GATEWAY: {} DNS: {}""".format( *wlan.ifconfig() ) ) break time.sleep_ms(100) except OSError: print("WLAN: found no router, going into AP mode instead") wlanconfig = None except Exception as e: print("WLAN: error: {}".format(e)) wlanconfig = None if wlanconfig is None: wlan.init(mode=WLAN.AP, ssid="wipy-wlan", auth=(WLAN.WPA2, "www.wipy.io"), channel=7, antenna=WLAN.INT_ANT)
class LocalWifi: """ Create a local WiFi connection. """ ssid = '' auth_mode = WLAN.WPA2 auth_password = '' wlan = None def __init__(self, ssid, ssid_password): self.ssid = ssid self.auth_password = ssid_password self.wlan = WLAN(mode=WLAN.STA) def connect(self): self.wlan.scan() self.wlan.connect(ssid=self.ssid, auth=(self.auth_mode, self.auth_password)) while not self.wlan.isconnected(): print('.', end="") print("\nConnected to:\n", self.wlan.ifconfig())
def wlan(): """Connect in STA mode, fallback to AP""" log = ulog.Logger('WLAN: ') try: import wlanconfig except ImportError: log.notice('no wlanconfig.py') wlanconfig = None wlan = WLAN(mode=WLAN.AP) except Exception as e: log.error('error in wlanconfig.py: {}'.format(e)) wlanconfig = None wlan = WLAN(mode=WLAN.AP) else: try: # configure the WLAN subsystem in station mode (the default is AP) wlan = WLAN(mode=WLAN.STA) log.info('connecting to network (AP)...') wlan.connect(wlanconfig.ssid, auth=(WLAN.WPA2, wlanconfig.password), timeout=5000) log.info('waiting for IP...') for tries in range(50): if wlan.isconnected(): log.notice('''connected! WiPy IP: {} NETMASK: {} GATEWAY: {} DNS: {}'''.format(*wlan.ifconfig())) break time.sleep_ms(100) except OSError: log.error('found no router, going into AP mode instead') wlanconfig = None except Exception as e: log.error('error: {}'.format(e)) wlanconfig = None if wlanconfig is None: wlan.init(mode=WLAN.AP, ssid='wipy-wlan', auth=(WLAN.WPA2,'www.wipy.io'), channel=7, antenna=WLAN.INT_ANT)
def wlan(): with open('/flash/wificonfig.txt') as f: ssid = f.readline().strip() passwd = f.readline().strip() # configure the WLAN subsystem in station mode (the default is AP) print('WLAN: connecting to network (AP)...') wlan = WLAN(mode=WLAN.STA) try: wlan.connect(ssid, auth=(WLAN.WPA2, passwd), timeout=5000) print('WLAN: waiting for IP...') for tries in range(50): if wlan.isconnected(): print('''\ WLAN: connected! WiPy IP: {} NETMASK: {} GATEWAY: {} DNS: {}'''.format(*wlan.ifconfig())) break time.sleep_ms(100) except OSError: print('WLAN: found no router, going into AP mode instead') wlan.init(mode=WLAN.AP, ssid='wipy-wlan', auth=(WLAN.WPA2,'www.wipy.io'), channel=7, antenna=WLAN.INT_ANT)
RMotorB = Pin('GPIO8', af=0, mode=Pin.OUT) LMotorB.low() RMotorB.low() # assign GPIO9 and 10 to alternate function 3 (PWM) # These will be the pins to control speed LMotorA = Pin('GPIO9', af=3, type=Pin.STD) RMotorA = Pin('GPIO10', af=3, type=Pin.STD) # Enable timer channels 3B and 4A for PWM pins LMTimer = Timer(3, mode=Timer.PWM, width=16) RMTimer = Timer(4, mode=Timer.PWM, width=16) # enable channel A @1KHz with a 50% duty cycle LMT_a = LMTimer.channel(Timer.B, freq=1000, duty_cycle=50) RMT_a = RMTimer.channel(Timer.A, freq=1000, duty_cycle=50) def Setup_WIFI() wifi = WLAN(WLAN.STA) # go for fixed IP settings wifi.ifconfig('192.168.0.107', '255.255.255.0', '192.168.0.1', '8.8.8.8') wifi.scan() # scan for available netrworks wifi.connect(ssid='mynetwork', security=2, key='mynetworkkey') while not wifi.isconnected(): pass print(wifi.ifconfig()) # enable wake on WLAN wifi.callback(wakes=Sleep.SUSPENDED) # go to sleep Sleep.suspend() # now, connect to the FTP or the Telnet server and the WiPy will wake-up
# Connect to my WiFi import machine from network import WLAN wlan = WLAN() # get current object, without changing the mode # Settings for TP-LINK home network KEY = '' IP = '192.168.1.253' # WiPy Fixed IP address GATEWAY = '192.168.1.1' # IP address of gateway DNS = '192.168.1.1' # IP address of DNS NETMASK = '255.255.255.0' # Netmask for this subnet if machine.reset_cause() != machine.SOFT_RESET: print('Switching to Wifi Device Mode') wlan.init(WLAN.STA) wlan.ifconfig(config=(IP, NETMASK, GATEWAY, DNS)) if not wlan.isconnected(): print('Attempting to connect to WiFi', end=' ') nets = wlan.scan() for net in nets: if net.ssid == 'Robotmad': KEY = 'mou3se43' break elif net.ssid == 'CoderDojo': KEY = 'coderdojo' break if KEY != '': print(net.ssid, end=" ") wlan.connect(net.ssid, auth=(net.sec, KEY), timeout=10000) if wlan.isconnected():
from machine import Timer from machine import Pin import BlynkLib from network import WLAN WIFI_SSID = 'YOUR_WIFI_SSID' WIFI_AUTH = (WLAN.WPA2, 'YOUR_WIFI_PASSORD') BLYNK_AUTH = 'YOUR_BLYNK_AUTH' # connect to WiFi wifi = WLAN(mode=WLAN.STA) wifi.connect(WIFI_SSID, auth=WIFI_AUTH, timeout=5000) while not wifi.isconnected(): pass print('IP address:', wifi.ifconfig()[0]) # assign GP9, GP10, GP11, GP24 to alternate function (PWM) p9 = Pin('GP9', mode=Pin.ALT, alt=3) p10 = Pin('GP10', mode=Pin.ALT, alt=3) p11 = Pin('GP11', mode=Pin.ALT, alt=3) p24 = Pin('GP24', mode=Pin.ALT, alt=5) # timer in PWM mode and width must be 16 buts timer10 = Timer(4, mode=Timer.PWM, width=16) timer9 = Timer(3, mode=Timer.PWM, width=16) timer1 = Timer(1, mode=Timer.PWM, width=16) # enable channels @1KHz with a 50% duty cycle pwm9 = timer9.channel(Timer.B, freq=700, duty_cycle=100) pwm10 = timer10.channel(Timer.A, freq=700, duty_cycle=100)
from network import WLAN import time import os import machine # Substitute your wifi network name & password SSID = 'My-wifi-network' AUTH = (WLAN.WPA2, 'My-wifi-password') # duplicate terminal on USB-UART uart = machine.UART(0, 115200) os.dupterm(uart) # Try connecting in station mode wlan = WLAN(mode=WLAN.STA) wlan.ifconfig(config='dhcp') wlan.connect(ssid=SSID, auth=AUTH) # Try for 30 seconds retry = 60 while not wlan.isconnected(): if retry > 0: time.sleep_ms(500) print('.', end='') retry = retry - 1 else: break # If connected print ipaddr and info if wlan.isconnected(): print('Connected to My-wifi-network\n')
# can run arbitrary Python, but best to keep it minimal import os import machine from network import WLAN # disable LED matrix first latch = machine.Pin('GP13', mode=machine.Pin.OUT) latch.value(0) spi = machine.SPI(0, mode=machine.SPI.MASTER, bits=32, pins=('GP14', 'GP16', 'GP15')) spi.write(b'\x00\x00\x00\x00') latch.value(1) # repl on serial os.dupterm(machine.UART(0, 115200)) # now wifi wlan = WLAN() if machine.reset_cause() != machine.SOFT_RESET: wlan.init(WLAN.STA) wlan.ifconfig(config=('192.168.1.254', '255.255.255.0', '192.168.1.1', '192.168.1.1')) if not wlan.isconnected(): # change the line below to match your network ssid, security and password wlan.connect('XXX', auth=(WLAN.WPA2, 'XXX'), timeout=5000) while not wlan.isconnected(): machine.idle()
import machine import config from network import WLAN wlan = WLAN(mode=WLAN.STA, antenna=WLAN.INT_ANT) print (config.ssid) nets = wlan.scan() for net in nets: if net.ssid == config.ssid: print('Network found!') wlan.connect(net.ssid, auth=(net.sec, config.password), timeout=5000) while not wlan.isconnected(): machine.idle() # save power while waiting print('WLAN connection succeeded!') break print(wlan.ifconfig())
wifi.antenna(WLAN.EXT_ANT) print(wifi.antenna() == WLAN.EXT_ANT) scan_r = wifi.scan() print(len(scan_r) > 3) for net in scan_r: if net.ssid == testconfig.wlan_ssid: print('Network found') break wifi.antenna(WLAN.INT_ANT) wifi.mode(WLAN.STA) print(wifi.mode() == WLAN.STA) wifi.connect(testconfig.wlan_ssid, auth=testconfig.wlan_auth, timeout=10000) wait_for_connection(wifi) wifi.ifconfig(config='dhcp') wait_for_connection(wifi) print('0.0.0.0' not in wifi.ifconfig()) wifi.ifconfig(0, ('192.168.178.109', '255.255.255.0', '192.168.178.1', '8.8.8.8')) wait_for_connection(wifi) print(wifi.ifconfig(0) == ('192.168.178.109', '255.255.255.0', '192.168.178.1', '8.8.8.8')) wait_for_connection(wifi) print(wifi.isconnected() == True) wifi.disconnect() print(wifi.isconnected() == False) t0 = time.ticks_ms() wifi.connect(testconfig.wlan_ssid, auth=testconfig.wlan_auth, timeout=0) print(time.ticks_ms() - t0 < 500)