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 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()
class Theta: def __init__(self): self.wlan = WLAN(WLAN.STA) pass def log(self, msg): print(msg) def findWifi(self): wlans = self.wlan.scan() # TODO: Return all visible Thetas for w in wlans: if w.ssid.startswith('THETA'): self.log('Found Theta WiFi: %s' % w.ssid) # THETAXL12345678 = Theta (original model) - PTP/IP # THETAXN12345678 = Theta m15 - PTP/IP # THETAXS12345678.OSC = Theta S - OSC return w.ssid return False def connectWifi(self, ssid): password = ssid[-8:] return self.wlan.connect(ssid, auth=(WLAN.WPA, password)) # convenience - might get removed def connect(self): wifi = self.findWifi() if not wifi: return False self.connectWifi(wifi) self.ptpip = ptpip.PTPIP('192.168.1.1') return self.ptpip def initPTP(self): answer = self.ptpip.initCommand('1234567812345678', 'WiPy') if not answer: print("Init failed!") return False (session_id, guid, name) = answer pass2 = self.ptpip.initEvent(session_id) if not pass2: print("Init stage 2 failed!") return False return (session_id, guid, name) def openSession(self): answer = self.ptpip.createCommand(0x1002, []) return answer def closeSession(self): answer = self.ptpip.createCommand(0x1003, []) return answer def shoot(self): answer = self.ptpip.createCommand(0x100e, [0x0, 0x0]) return answer def getPTPIP(self): return self.ptpip
def connect(ssid, key): """ Scans for and connects to the specified wifi network using key as password """ wlan = WLAN(mode=WLAN.STA) nets = wlan.scan() for net in nets: if net.ssid == ssid: wlan.connect(net.ssid, auth=(net.sec, key), timeout=5000) while not wlan.isconnected(): machine.idle() # save power while waiting break
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 connect_to_ap(essids, tries=3): from network import WLAN, STA_IF from time import sleep wlan = WLAN(STA_IF) wlan.active(True) ## Select only known networks ap_list = list(filter(lambda ap: ap[0].decode('UTF-8') in essids.keys(), wlan.scan())) ## sort by signal strength ap_list.sort(key=lambda ap: ap[3], reverse=True) for ap in ap_list: essid = ap[0].decode('UTF-8') wlan.connect(essid, essids[essid]) for i in range(5): ## this is somewhat crude, we actually have a ## wlan.status() we can inspect. oh well... if wlan.isconnected(): return True sleep(1) return False
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])
class WifiManager: def __init__(self, known_nets): self._known_nets = known_nets self._wl = None # 2019-1203 new, due to Exception error in legacy WifiManager # pre-condition: self._known_nets is not None # post-condition: self._wl is created # returns: IP # URL: https://docs.pycom.io/tutorials/all/wlan/ def connect(self): """connect() - connects device according to network parameters in JSON-file.""" if machine.reset_cause() != machine.SOFT_RESET: # from network import WLAN self._wl = WLAN() self._wl.mode(WLAN.STA) original_ssid = self._wl.ssid() original_auth = self._wl.auth() print_debug("Wifimanager - scanning for known wifi nets...") available_nets = self._wl.scan() nets = frozenset([e.ssid for e in available_nets]) known_nets_names = frozenset([key for key in self._known_nets]) net_to_use = list(nets & known_nets_names) try: net_to_use = net_to_use[0] net_properties = self._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']) self._wl.connect(net_to_use, (sec, pwd), timeout=10000) ip = self.wait_for_networking(1) self._ssid = net_to_use print_debug("Connected to " + net_to_use + " with IP address:" + ip) except Exception as e: print( "Failed to connect to any known network, going into AP mode" ) self._wl.init(mode=WLAN.AP, ssid=original_ssid, auth=original_auth, channel=6, antenna=WLAN.INT_ANT) self._ssid = None else: print_debug("Already connected to " + net_to_use + " with IP address:" + self._wl.ifconfig()[0]) return self._wl.ifconfig()[0] def wait_for_networking(self, dt=1): """ wait unitil network is connected and returns IP""" station = self._wl # network.WLAN(mode=network.WLAN.STA) while not station.isconnected(): time.sleep(dt) machine.idle() ip = station.ifconfig()[0] return ip # wrapper for disconnecting network def disconnect(self): """disconnect() - de-activate network interface, but leaves Wifi radio on""" self._wl.disconnect( ) # pycom - disconnect from Wifi, but leave Wif radio on. print_debug('WifiManager::Wifi disconnected') # wrapper for disabling Wifi radio def deinit(self): """deinit() - disable Wifi radio""" self._wl.deint() # pycom print_debug('WifiManager::Wifi radio off') # wrapper for network scan def scan(self): """scan() - Performs a network scan and returns a list of named tuples with (ssid, bssid, sec, channel, rssi) """ return self._wl.scan() def change_access(self, user=None, passwrd=None): """change_access - change password for telnet and ftp access""" if (user is None) or (passwrd is None): print('WifiManager:: username and password must be specified') return server = Server() # from network # disable the server server.deinit() # enable the server again with new credentials # for ftp and telnet, not USB server.init(login=(user, passwrd), timeout=600) print_debug('WifiManager::password {} is changed...'.format(user)) # wrappers for wlan settings. @property def ssid(self): """ ssid() - returns SSID of connected Wifi network""" return self._ssid @property def isconnected(self): """isconnected() - returns if connected to Wifi (True) or not (False)""" return self._wl.isconnected() @property def ip(self): """ip() - returns IP of device on connected Wifi network""" return self._wl.ifconfig()[0] @property def mac(self): """returns MAC-address of device""" mac = hexlify(self._wl.mac(), ':').decode() # pycom # return (mac) # lower case return mac.upper() # ================================================ # legacy methods # ================================================ import json def __readjson(self, jsonfile): """readjson(file) - returns the contents of file in JSON-format""" with open(jsonfile, 'r') as infile: config = json.load(infile) if USE_DEBUG: print('WifiManager::JSON settings: {}'.format(config)) return config
class geolocate(): def __init__(self, google_api_key, my_ssid, wlan_check_interval=1, mcc=262, mnc=11): self.url = "https://www.googleapis.com/geolocation/v1/geolocate?key=" + google_api_key # wlan configuration and information self.wlan_scans = WLAN(mode=WLAN.STA) self.wlan_timer = 0 self.wlan_check_interval = wlan_check_interval self.wlan_number = 0 self.my_ssid = my_ssid self.nets = None self.rjson = None self.mcc = mcc self.mnc = mnc def prettify(self, mac_binary): return ':'.join('%02x' % (b) for b in mac_binary) def scan_wlan(self): logger.info(" wlan trying to scan") self.nets = self.wlan_scans.scan() self.wlan_timer = time.time() self.wlan_number = len(self.nets) logger.info(" wlan scan ready") def wlan_nodes(self): return self.wlan_number def get_location(self): valid = True if (self.nets == None) or (time.time() - self.wlan_timer >= self.wlan_check_interval): self.scan_wlan() # initializing the json request req = {} req["homeMobileCountryCode"] = self.mcc req["homeMobileNetworkCode"] = self.mnc req["radioType"] = "gsm" req["carrier"] = "O2" req["considerIp"] = "false" wlan_nodes = [] for net in self.nets: if net.ssid != self.my_ssid: #print("ssid found: " + str(net.ssid) + " " + str(self.prettify(net.bssid))) wlan_node = {} wlan_node["macAddress"] = str(self.prettify(net.bssid)) wlan_node["signalStrength"] = net.rssi wlan_node["channel"] = net.channel wlan_nodes.append(wlan_node) req["wifiAccessPoints"] = wlan_nodes try: r = requests.post(self.url, json=ujson.dumps(req)) self.rjson = r.json() except Exception as error: logger.error(str(error)) raise if (self.rjson.get("location") == None): print(self.rjson) valid = False return valid, self.rjson def get_location_string(self): location_string = None if (self.rjson.get("location") != None): location_string = str(self.rjson['location']['lat']) + "," + str( self.rjson['location']['lng']) + "," + str( self.rjson['accuracy']) + "\n" return location_string
uart = machine.UART(0, baudrate=115200) os.dupterm(uart) # Do not initialize any wireless settings useWifi = True if useWifi and machine.reset_cause() != machine.SOFT_RESET: from network import WLAN wl = WLAN() wl.mode(WLAN.STA) def_ssid = 'chris-gpy' def_auth = (WLAN.WPA2, 'micropython') print("Scanning for known wifi networks") available_networks = wl.scan() networks = frozenset([e.ssid for e in available_networks]) known_network_names = frozenset( [key for key in ConfigNetwork.KNOWN_NETWORKS]) network_to_use = list(networks & known_network_names) try: network_to_use = network_to_use[0] network_props = ConfigNetwork.KNOWN_NETWORKS[network_to_use] pwd = network_props['pwd'] sec = [e.sec for e in available_networks if e.ssid == network_to_use][0] if 'config' in network_props: wl.ifconfig(config=network_props['config']) wl.connect(network_to_use, (sec, pwd), timeout=10000)
from network import WLAN import machine # configure the WLAN subsystem in station mode (the default is AP) wlan = WLAN(mode=WLAN.STA) nets = wlan.scan() # scan for available networks for net in nets: if net.ssid == 'AndroidAP': wlan.connect(net.ssid, auth=(net.sec, 'micropython'), timeout=5000) while not wlan.isconnected(): machine.idle() # save power while waiting print('WLAN connection succeeded!') break
import machine import settings from network import WLAN wlan = WLAN(mode=WLAN.STA) nets = wlan.scan() # Scan all SSID networks print('WLAN init') for net in nets: if net.ssid == settings.wifi_ssid: wlan.connect(net.ssid, auth=(net.sec, settings.wifi_password), timeout=5000) while not wlan.isconnected(): machine.idle() # Save power while waiting print('WLAN connection succeeded!') break
class WifiManager: ip = "0.0.0.0" ssids = [] ssids_timestamp = 0 def __init__(self, ap_essid=None): self.sta_if = WLAN(STA_IF) self.ap_if = WLAN(AP_IF) self.sta_if.active(False) self.sta_if.active(True) if ap_essid is None: ap_essid = b"ESP8266-%s" % hexlify(self.ap_if.config("mac")[-3:]) self.ap_essid = ap_essid self.credentials = Credentials() # Turn off station and AP interface to force a reconnect self.sta_if.active(True) self.ap_if.active(False) self.loop = get_event_loop() self.loop.create_task(self.check_wifi()) async def check_wifi(self): while True: self.loop.create_task(self.connect(True)) if self.credentials.load().is_valid(): await sleep_ms(WAIT_FOR_CONNECT) if not self.sta_if.isconnected(): self.loop.create_task(self.start_access_point()) while not self.sta_if.isconnected(): await sleep_ms(CHECK_CONNECTED) self.ip = self.sta_if.ifconfig()[0] Blink().flash3TimesFast() print("> Connected to {} with IP: {}".format( self.credentials.essid.decode("ascii"), self.ip)) if self.ap_if.active(): # Leave a bit of time so the client can retrieve the Wifi IP address await sleep_ms(WAIT_BEFORE_AP_SHUTDOWN) print("> Shuting down AP") self.ap_if.active(False) while self.sta_if.isconnected(): await sleep_ms(CHECK_CONNECTED) async def start_access_point(self): self.ap_if.active(True) while not self.ap_if.active(): await sleep_ms(CHECK_CONNECTED) self.ip = AP_IP # IP address, netmask, gateway, DNS self.ap_if.ifconfig((self.ip, "255.255.255.0", self.ip, self.ip)) self.ap_if.config(essid=self.ap_essid, authmode=AUTH_OPEN) print( "> AP mode configured: {} ".format(self.ap_essid.decode("utf-8")), self.ap_if.ifconfig(), ) async def connect(self, autoLoop=False): if not self.sta_if.isconnected() or not autoLoop: if self.credentials.load().is_valid(): print("> Connecting to {:s}/{:s}".format( self.credentials.essid, self.credentials.password)) self.sta_if.active(False) self.sta_if.active(True) self.sta_if.connect(self.credentials.essid, self.credentials.password) await sleep_ms(WAIT_FOR_CONNECT) if not self.sta_if.isconnected(): if autoLoop: await sleep_ms(WAIT_BEFORE_RECONNECT) self.loop.create_task(self.connect(True)) else: print("> No valid credentials file: {}".format(FILE)) def set_ap_essid(self, ap_essid): self.ap_essid = ap_essid def get_ssids(self): now = ticks_ms() if len(self.ssids) == 0 or now > self.ssids_timestamp + 1000 * 30: ssids = self.sta_if.scan() self.ssids_timestamp = now self.ssids = [] for ssid in ssids: self.ssids.append('"%s"' % ssid[0].decode("ascii")) self.ssids.sort() return b'{"ssids": [%s]}' % (",".join(self.ssids))
import utime import usocket from network import WLAN import machine import bme280 import ustruct ## ------------------------------------------------------------------------------------------------------------------- ## ## --------------------------------------------------- WiFi Settings ------------------------------------------------- ## start = utime.ticks_ms() ## Set WLAN mode to STA (station/client) wlan = WLAN(mode=WLAN.STA) wlan.scan() ## scan for available networks wlan.connect('repeater_layer', auth=(WLAN.WPA2, 'password123')) ## Goes to deep sleep without active network in 10 seconds disc_counter = 0 while not wlan.isconnected(): print("no. of tries: ", disc_counter) if disc_counter >= 10: print("Total time elapsed (s): ", utime.ticks_diff(start, utime.ticks_ms()) / 1000) print( "It's been 10 seconds without a connection. Going to deep sleep..." ) machine.deepsleep(10000) utime.sleep(1) disc_counter += 1
class Wifi: def __init__(self): self.wlan = WLAN(mode=WLAN.STA, antenna=WLAN.INT_ANT) time.sleep(2) # give it chance to initialize self.scan_results = None self.ssid_list = None self.connect_timeout = 3 # seconds self.antenna = WLAN.INT_ANT self.ssid = None self.bssid = None self.rssi = None self.wifi_channel = None self.key = None self.verbose = False def scan(self): self.scan_results = self.wlan.scan() if self.verbose: print('Found SSIDs:', self.scan_results) print('Known wifi:', self.ssid_list) _ssid_list = [x[0] for x in self.ssid_list] found_aps = [n for n in self.scan_results if n.ssid in _ssid_list] if len(found_aps) == 0: if self.verbose: print('No known SSIDs found') return None if self.verbose: print('Found known SSIDs:', found_aps) strongest_ap = found_aps[0] self.ssid = strongest_ap.ssid self.bssid = strongest_ap.bssid self.rssi = strongest_ap.rssi self.channel = strongest_ap.channel self.key = dict(self.ssid_list)[self.ssid] return self.ssid, self.bssid def connect(self): def _connect(_round): self.wlan.connect(ssid=self.ssid, bssid=self.bssid, auth=(WLAN.WPA2, self.key)) t0 = time.time() while not self.wlan.isconnected(): machine.idle() if time.time() - t0 > self.connect_timeout: return False if self.verbose: print(_round, time.time()) return True round = 0 connected = False while not connected: round += 1 connected = _connect(round) if self.verbose: print("WiFi connected succesfully") print(self.wlan.ifconfig()) pycom.rgbled(0x0000FF)
import pycom import network from network import LoRa from network import WLAN import binascii mac = binascii.hexlify(network.LoRa().mac()) print("*************************************") print(" LoraSense 0.1") print("") print("MAC: " + mac.upper().decode('utf-8')) print("*************************************") pycom.heartbeat(False) pycom.rgbled(0x000000) wifi_adapter = WLAN(mode=WLAN.STA) print("Wifi Mode: " + str(wifi_adapter.mode())) nets = wifi_adapter.scan() for net in nets: print(net.ssid)
os.listdir('/flash/log') except OSError: os.mkdir('/flash/log') # stop the heartbeat pycom.heartbeat(False) led = LEDColors.pyLED() led.setLED('red') open_log_file() logger = open('/flash/log/lat-long5.csv','w+'); (lat, lon, alt, hdop) = gps.position() print("%s %s %s %s" %(lat, lon, alt, hdop)) logger.write('{},{},{},{},{}\n'.format('latitude', 'longitude', 'altitude', 'hdop', 'information')) #while True: for i in range(100): (lat, lon, alt, hdop) = gps.position() print("%s %s %s %s" %(lat, lon, alt, hdop)) if (str(lat) == 'None'): led.setLED('red') print("I do not have a fix!") else: led.setLED('green') no_of_wifi = len(wlan.scan()) logger.write('{},{},{},{},{}\n'.format(lat, lon, alt, hdop, no_of_wifi)) print("%s, %s, %s, %s, %s" %(lat, lon, alt, hdop, no_of_wifi)) time.sleep(10) logger.close();
uart = machine.UART(0, 115200) os.dupterm(uart) #JSON con las redes wifi conocidas a las que conectarse redesConocidas = { 'WLAN_Esteban_Invitados': {'pwd': 'daoiz22invitados'}, } #Conexión a una red WiFi conocida if machine.reset_cause() != machine.SOFT_RESET: wl = WLAN() wl.mode(WLAN.STA) print("Buscando redes WiFi conocidas...") redesDisponibles = wl.scan() redes = frozenset([e.ssid for e in redesDisponibles]) wifiSSIDs = frozenset([key for key in redesConocidas]) redConocida = list(redes & wifiSSIDs) try: redConocida = redConocida[0] propiedadesRedes = redesConocidas[redConocida] pwd = propiedadesRedes['pwd'] sec = [e.sec for e in redesDisponibles if e.ssid == redConocida][0] if 'wlan_config' in propiedadesRedes: wl.ifconfig(config=propiedadesRedes['wlan_config']) wl.connect(redConocida, (sec, pwd), timeout=10000) while not wl.isconnected(): machine.idle() # ahorro de energía mientras se espera conexión print("Conectado a "+redConocida+" con dirección IP:" + wl.ifconfig()[0])
signal.signal(signal.SIGTERM, sigint_handler) # Initialize led matrix framebuffer on top of HAL display = LedMatrix(driver, config['LedMatrix']) driver.clear_display() if pycom_board: # We're running under MCU here from bootscene import BootScene scene = BootScene(display, config['Boot']) wlan = WLAN(mode=WLAN.STA) if not wlan.isconnected(): print('WLAN: Scanning for networks') scene.render(0, 0, 0) default_ssid, default_auth = wlan.ssid(), wlan.auth() candidates = wlan.scan() for conf in config['networks']: nets = [ candidate for candidate in candidates if candidate.ssid == conf['ssid'] ] if not nets: continue print('WLAN: Connecting to known network: {}'.format( nets[0].ssid)) wlan.connect(nets[0].ssid, auth=(nets[0].sec, conf['password'])) for i in range(1, 40): scene.render(i, 0, 0) time.sleep(0.2) if wlan.isconnected():
def ListaWifi(): wlan = WLAN(mode=WLAN.STA) nets = wlan.scan() for net in nets: print (net)
class WiFiManager: def __init__(self, manager, settings): self.manager = manager self.settings = settings # WIFI settings. self.stations = self.settings.get('networking.wifi.stations') self.station = None def start(self): # Todo: Propagate more parameters here, e.g. for using an external antenna. self.station = WLAN() _thread.start_new_thread(self.start_real, ()) def start_real(self): """ https://docs.pycom.io/tutorials/all/wlan.html https://github.com/pycom/pydocs/blob/master/firmwareapi/pycom/network/wlan.md """ #if machine.reset_cause() == machine.SOFT_RESET: # print("WiFi STA: Network connection after SOFT_RESET.") # self.print_short_status() # # Inform about networking status. # self.print_address_status() # return True # Save the default ssid and auth for restoring AP mode later #original_ssid = self.station.ssid() #original_auth = self.station.auth() # Inform about networking status. self.print_address_status() # Setup network interface. log.info("WiFi STA+AP: Starting interface") self.station.mode(WLAN.STA_AP) self.station.init() # Check WiFi connectivity. if self.is_connected(): log.info( "WiFi STA: Network connection already established, will skip scanning and resume connectivity." ) self.print_short_status() # Give system some breath. time.sleep(0.25) # Inform about networking status. self.print_short_status() self.print_address_status() return True # Prepare information about known WiFi networks. networks_known = frozenset( [station['ssid'] for station in self.stations]) # Attempt to connect to known/configured networks. attempt = 0 while True: delay = 1 if self.is_connected(): attempt = 0 else: log.info( "WiFi STA: Connecting to configured networks: %s. Attempt: #%s", list(networks_known), attempt + 1) try: self.connect_stations(networks_known) except: log.exception( 'WiFi STA: Connecting to configured networks "{}" failed' .format(list(networks_known))) delay = backoff_time(attempt, minimum=1, maximum=600) log.info('WiFi STA: Retrying in {} seconds'.format(delay)) attempt += 1 machine.idle() time.sleep(delay) # Todo: Reenable WiFi AP mode in the context of an "initial configuration" mode. """ log.info('WiFi: Switching to AP mode') # WLAN.AP, original_ssid, original_auth, WLAN.INT_ANT # TOOD: Make default channel configurable self.station.init(mode=WLAN.AP, ssid=original_ssid, auth=original_auth, channel=6, antenna=WLAN.INT_ANT) """ def is_connected(self): try: # ``isconnected()`` returns True when connected to a WiFi access point *and* having a valid IP address. if self.station is not None and self.station.isconnected(): ssid = self.get_ssid() if ssid[0] is not None: ip_address = self.get_ip_address() if ip_address is not None and ip_address != '0.0.0.0': return True except: log.exception('Invoking "is_connected" failed') return False def power_off(self): """ Power off all radio peripherals. - https://forum.pycom.io/topic/563/disabling-wifi-on-lopy - https://github.com/Hiverize/FiPy/commit/b6b15677 """ # WiFi if self.station: try: log.info('Turning off WiFi') self.station.deinit() except: log.exception('Turning off WiFi failed') def connect_stations(self, network_names): # Prepare information about known WiFi networks. network_map = {station['ssid']: station for station in self.stations} for network_name in network_names: try: # All the configuration details for this network. # { # 'ssid': 'FooBar', # 'password': '******', # 'ifconfig': ('192.168.42.42', '255.255.255.0', '192.168.42.1', '192.168.42.1'), # } network_selected = network_map[network_name] if self.connect_station(network_selected): break except Exception: log.exception( 'WiFi STA: Connecting to "{}" failed'.format(network_name)) if not self.is_connected(): self.forget_network(network_name) message = 'WiFi STA: Connecting to any network candidate failed' description = 'Please check your WiFi configuration for one of the ' \ 'station candidates {}.'.format(len(network_names)) log.error('{}. {}'.format(message, description)) log.warning('Todo: We might want to buffer telemetry data to ' 'flash memory to be scheduled for transmission later.') raise WiFiException(message) def connect_station(self, network): network_name = network['ssid'] log.info('WiFi STA: Getting auth mode for network "{}"'.format( network_name)) auth_mode = self.get_auth_mode(network_name) log.info( 'WiFi STA: Preparing connection to network "{}" with auth mode "{}"' .format(network_name, auth_mode)) password = network['password'] # TODO: Optionally, configure hostname. # https://docs.micropython.org/en/latest/library/network.WLAN.html # https://github.com/pycom/pycom-micropython-sigfox/pull/165 # https://forum.pycom.io/topic/3326/new-firmware-release-v1-18-0 if 'dhcp_hostname' in network: if hasattr(self.station, 'config'): log.ingo('WiFi STA: Using dhcp_hostname "{}"'.format( network['dhcp_hostname'])) self.station.config(dhcp_hostname=network['dhcp_hostname']) else: log.error('Could not set hostname on older MicroPython') # Optionally, configure static IP address. if 'ifconfig' in network: log.info( 'WiFi STA: Using static network configuration "{}"'.format( network_name)) self.station.ifconfig(config=network['ifconfig']) # Obtain timeout value. network_timeout = network.get('timeout', 15.0) # Connect to WiFi station. log.info( 'WiFi STA: Starting connection to "{}" with timeout of {} seconds'. format(network_name, network_timeout)) self.station.connect(network_name, (auth_mode, password), timeout=int(network_timeout * 1000)) # Wait for network to arrive. self.wait_for_connection(network_timeout) if not self.is_connected(): raise WiFiException( 'WiFi STA: Unable to connect to "{}"'.format(network_name)) # Inform about networking status. self.print_short_status() self.print_address_status() return True def wait_for_connection(self, timeout=15.0): """ Wait for network to arrive. """ # Set interval how often to poll for WiFi connectivity. network_poll_interval = 250 # How many checks to make. checks = int(timeout / (network_poll_interval / 1000.0)) # Stopwatch for keeping track of time. stopwatch = Stopwatch() do_report = True while not self.is_connected(): delta = stopwatch.elapsed() eta = timeout - delta if checks <= 0 or eta <= 0: break # Report about the progress each 3 seconds. if int(delta) % 3 == 0: if do_report: log.info( 'WiFi STA: Waiting for network to come up within {} seconds' .format(eta)) do_report = False else: do_report = True # Save power while waiting. machine.idle() # Don't busy-wait. time.sleep_ms(network_poll_interval) checks -= 1 def scan_stations(self): # Inquire visible networks. log.info("WiFi STA: Scanning for networks") try: stations_available = self.station.scan() except OSError as ex: if 'Scan operation Failed' in str(ex): log.exception('WiFi STA: Scanning for networks failed') self.station.init() # Collect SSIDs of available stations. networks_found = frozenset([e.ssid for e in stations_available]) # Print names/SSIDs of networks found. log.info("WiFi STA: Networks available: %s", list(networks_found)) return stations_available def get_ssid(self): return self.station.ssid() def get_ip_address(self): try: return self.station.ifconfig()[0] except: log.exception('Unable to get device ip address') def get_auth_mode(self, network_name): # NVRAM key for storing auth mode per network. Maximum of 15 characters. auth_mode_nvs_key = self.auth_mode_nvs_key(network_name) # Get WiFi STA auth mode from NVRAM. try: import pycom auth_mode = pycom.nvs_get(auth_mode_nvs_key) log.info('WiFi STA: Auth mode from NVRAM with key=%s, value=%s', auth_mode_nvs_key, auth_mode) except: auth_mode = None # Fall back to find out WiFi STA auth mode by network scan. if auth_mode is None: log.info( 'WiFi STA: Unknown auth mode for network "%s", invoking WiFi scan', network_name) wifi_neighbourhood = self.scan_stations() #log.info('WiFi STA: Neighbourhood is %s', wifi_neighbourhood) for e in wifi_neighbourhood: if e.ssid == network_name: auth_mode = e.sec break if not auth_mode: message = 'WiFi STA: Unable to inquire auth mode for network "{}"'.format( network_name) log.warning(message) raise WiFiException(message) log.info( 'WiFi STA: Storing auth mode into NVRAM with key=%s, value=%s', auth_mode_nvs_key, auth_mode) try: import pycom pycom.nvs_set(auth_mode_nvs_key, auth_mode) except: log.exception('WiFi STA: Storing auth mode into NVRAM failed') return auth_mode def auth_mode_nvs_key(self, ssid): """ Hack to get a short representation of a WiFi SSID in order to squeeze it into a NVRAM key with a maximum length of 15 characters. Fixme: Review this. """ import hashlib import ubinascii digest = ubinascii.hexlify(hashlib.sha512(ssid).digest()).decode() identifier = 'wa.{}'.format(digest[15:27]) return identifier def forget_network(self, network_name): log.info('WiFi STA: Forgetting NVRAM data for network "{}"'.format( network_name)) auth_mode_nvs_key = self.auth_mode_nvs_key(network_name) try: import pycom pycom.nvs_erase(auth_mode_nvs_key) except: pass def print_short_status(self): log.info('WiFi STA: Connected to "{}" with IP address "{}"'.format( self.get_ssid(), self.get_ip_address())) def print_address_status(self): mac_address = self.humanize_mac_addresses(self.station.mac()) ifconfig = self.station.ifconfig() log.info('WiFi STA: Networking address (MAC): %s', mac_address) log.info('WiFi STA: Networking address (IP): %s', ifconfig) def humanize_mac_addresses(self, mac): info = {} if hasattr(mac, 'sta_mac'): info['sta_mac'] = format_mac_address( binascii.hexlify(mac.sta_mac).decode()) if hasattr(mac, 'ap_mac'): info['ap_mac'] = format_mac_address( binascii.hexlify(mac.ap_mac).decode()) return info def print_metrics(self): metrics = SystemWiFiMetrics(self.station).read() log.info('WiFi STA: Metrics: %s', metrics)
from network import WLAN from machine import Pin import time wlan = WLAN(mode=WLAN.STA) wlan.antenna(WLAN.EXT_ANT) Pin('P12', mode=Pin.OUT)(True) c = 0 while True: print('{} {}'.format(c, wlan.isconnected())) print(wlan.scan()) time.sleep(1) c += 1
state = CONNECTED except: print('Could not establish MQTT connection') time.sleep(0.5) continue print('MQTT LIVE!') # Subscribe for messages connection.set_callback(_recv_msg_callback) connection.subscribe(config.TOPIC) while state == CONNECTED: try: connection.check_msg() except: pass time.sleep(0.1) nets = wlan.scan() for net in nets: if net.ssid == config.WIFI_SSID: print(net.ssid +" was found!") wlan.connect(net.ssid, auth=(WLAN.WPA2, config.WIFI_PASS), timeout=5000) while not wlan.isconnected(): machine.idle() print('Connected to '+ net.ssid) run() break
wifi = WLAN(mode=WLAN.AP) print(wifi.mode() == WLAN.AP) print(wifi.channel() == 1) print(wifi.auth() == None) print(wifi.antenna() == WLAN.INT_ANT) wifi = WLAN(0, mode=WLAN.AP, ssid='test-wlan', auth=(WLAN.WPA, '123456abc'), channel=7) print(wifi.mode() == WLAN.AP) print(wifi.channel() == 7) print(wifi.ssid() == 'test-wlan') print(wifi.auth() == (WLAN.WPA, '123456abc')) print(wifi.antenna() == WLAN.INT_ANT) wifi = WLAN(mode=WLAN.STA) print(wifi.mode() == WLAN.STA) scan_r = wifi.scan() print(len(scan_r) > 3) for net in scan_r: if net.ssid == testconfig.wlan_ssid: # test that the scan results contains the desired params print(len(net.bssid) == 6) print(net.channel == None) print(net.sec == testconfig.wlan_auth[0]) print(net.rssi < 0) print('Network found') break wifi.mode(WLAN.STA) print(wifi.mode() == WLAN.STA) wifi.channel(7) print(wifi.channel() == 7)
class WLANAgent: def __init__(self, ap_config=None, sta_config=None): self._wlan = None self.networks = {} self._sta_config = sta_config self._ap_config = ap_config def isActive(self): return self._wlan != None def isconnected(self): return self._wlan.isconnected() def activate_ap_mode(self, ssid, password): if self._ap_config is None: log('No config to init AP Mode.') return try: ssid = self._ap_config['ssid'] password = self._ap_config['password'] except KeyError: log('Need password or ssid to init Access Point.') return if self._wlan: self._wlan.deinit() self._wlan = None self._wlan = WLAN( mode=WLAN.AP, ssid=ssid, auth=(WLAN.WPA2, password), ) def stop(self): if self._wlan: self._wlan.deinit() self._wlan = None def activate_sta_mode(self): if self._sta_config is None: log('No config to init STA Mode.') return try: self.networks = self._sta_config['wifi_networks'] except KeyError: log('Need networks to init Wifi Station.') return if self._wlan: self._wlan.deinit() self._wlan = None self._wlan = WLAN(mode=WLAN.STA, ) self._wlan.ifconfig(config="dhcp") self.connect_to_ap() def connect_to_ap(self): while not self._wlan.isconnected(): try: if len(list(self.networks.items())) < 1: raise Exception("Need networks to connect to Wifi AP.") if self._wlan.mode() != WLAN.STA: raise Exception( "Must in Station Mode to connect to Wifi AP.") existing_networks = self._wlan.scan() log('Found {}. existing wlan networks.'.format( len(existing_networks))) for network in existing_networks: (ssid, bssid, sec, channel, rssi) = network log('Try to connect to network {}'.format(ssid)) if ssid in self.networks: password = self.networks[ssid] self._wlan.connect(ssid, auth=(WLAN.WPA2, password)) break now = time() while not self._wlan.isconnected(): if (time() - now > 10): raise Exception( 'Failed to connect to wlan {}. Timeout.'.format( self._wlan.ssid())) sleep(0.3) (ip, subnet_mask, gateway, DNS_server) = self._wlan.ifconfig() log('Connect to wifi {}'.format(self._wlan.ssid())) log('IP: {}'.format(ip)) except Exception as err: log(err) sleep(2)
print(wifi.antenna() == WLAN.INT_ANT) wifi = WLAN(0, mode=WLAN.AP, ssid="test-wlan", auth=(WLAN.WPA, "123456abc"), channel=7) print(wifi.mode() == WLAN.AP) print(wifi.channel() == 7) print(wifi.ssid() == "test-wlan") print(wifi.auth() == (WLAN.WPA, "123456abc")) print(wifi.antenna() == WLAN.INT_ANT) wifi = WLAN(mode=WLAN.STA) print(wifi.mode() == WLAN.STA) time.sleep(5) # this ensures a full network scan scan_r = wifi.scan() print(len(scan_r) > 3) for net in scan_r: if net.ssid == testconfig.wlan_ssid: # test that the scan results contains the desired params print(len(net.bssid) == 6) print(net.channel == None) print(net.sec == testconfig.wlan_auth[0]) print(net.rssi < 0) print("Network found") break wifi.mode(WLAN.STA) print(wifi.mode() == WLAN.STA) wifi.channel(7) print(wifi.channel() == 7)
# boot.py -- run on boot-up # can run arbitrary Python, but best to keep it minimal # Copy config.example.py to config.py and modify to your needs first! import config import machine #from machine import UART from os import dupterm uart = machine.UART(0, 115200) dupterm(uart) if machine.reset_cause() != machine.SOFT_RESET: from network import WLAN wifi = WLAN() wifi.mode(WLAN.STA) ssids = wifi.scan() found = False for net in ssids: print("Checking %s" % net.ssid) if net.ssid == config.HOME_SSID: print("Found %s!" % net.ssid) wifi.connect(config.HOME_SSID, auth=(WLAN.WPA, config.HOME_PASSWORD)) found = True break if not found: print("No eligible WiFi found.") wifi.mode(WLAN.AP)
pointerLogger.overwrite(str(total_bytes_read)) del data_points collect() with open(blacklist, 'r') as fp: ap_list = fp.read() ap_list = ap_list.split("\n") ap_blacklist = ap_blacklist + list( set(ap_list[:-1]) - set(ap_blacklist)) if (speed is not None) and (speed <= 10.00): if not station.isconnected(): try: # @param nets: tuple of obj(ssid, bssid, channel, RSSI, authmode, hidden) nets = station.scan() except RuntimeError as e: #TODO: remove print print("Warning: {0}".format(str(e))) defaultLogger.warning(str(e)) # get only open nets openNets = [n for n in nets if n[4] == 0] for onet in openNets: if onet[0].decode("utf-8") not in ap_blacklist: # Try to connect to WiFi access point apSSID = onet[0] apLogger.overwrite(apSSID.decode("utf-8")) #TODO: remove print print("Connecting to {0} ...\n".format( str(onet[0], "utf-8")))
class adafruit: def __init__(self, config, data_collector, logger): self.sensor = data_collector self.Config = config self.Logger = logger self.AIO_SERVER = config["adafruit"]["AIO_SERVER"] self.AIO_PORT = config["adafruit"]["AIO_PORT"] self.AIO_USER = config["adafruit"]["AIO_USER"] self.AIO_KEY = config["adafruit"]["AIO_KEY"] self.AIO_CLIENT_ID = ubinascii.hexlify(machine.unique_id()) self.AIO_CONTROL_FEED = config["adafruit"]["AIO_CONTROL_FEED"] self.AIO_MOVEMENT_FEED = config["adafruit"]["AIO_MOVEMENT_FEED"] self.AIO_GPS_FEED = config["adafruit"]["AIO_GPS_FEED"] self.AIO_ACCELERATION_FEED = config["adafruit"][ "AIO_ACCELERATION_FEED"] self.last_random_sent_ticks = config["adafruit"][ "last_random_sent_ticks"] self.post_per_minute = config["adafruit"]["post_per_minute"] """Finding and connecting to network""" self.wlan = WLAN(mode=WLAN.STA) nets = self.wlan.scan() print("Scanning for Wifi") for net in nets: for knowNet in self.Config["network"]: if net.ssid == knowNet["name"]: print(net.ssid + ' found!') self.wlan.connect(net.ssid, auth=(net.sec, knowNet["password"]), timeout=5000) while not self.wlan.isconnected(): machine.idle() # save power while waiting print('WLAN connection succeeded!') break self.client = MQTTClient(self.AIO_CLIENT_ID, self.AIO_SERVER, self.AIO_PORT, self.AIO_USER, self.AIO_KEY) def runAdafruit(self): Time = utime.localtime(None) currentTime = str(Time[1]) + "/" + str(Time[2]) + "/" + str( Time[0]) + " at " + str(Time[3]) + ":" + str(Time[4]) + ":" + str( Time[5]) self.Logger.log("Session began at " + currentTime) #Subscribed messages will be delivered to this callback self.client.set_callback(self.sub_cb) print('Connecting to io.adafruit.com') time.sleep(10) self.client.connect() self.client.subscribe(self.AIO_CONTROL_FEED) print("Connected to %s, subscribed to %s topic" % (self.AIO_SERVER, self.AIO_CONTROL_FEED)) pycom.rgbled(0x0000FF) # Blue try: while 1: self.client.check_msg() self.sendMovement() finally: self.client.disconnect() self.client = None self.wlan.disconnect() self.wlan = None pycom.rgbled(0x000022) print("Disconnected from Adafruit IO.") #responds to messages from Adafruit IO def sub_cb(self, topic, msg): print((topic, msg)) if msg == b"ON": pycom.rgbled(0xffffff) elif msg == b"OFF": pycom.rgbled(0x000000) else: print("Unknown message") #Sends messages to Adafuit IO def sendMovement(self): #Waits 2 seconds to send data to avoid Adadruit IO if ((time.ticks_ms() - self.last_random_sent_ticks) < (1000 / (self.post_per_minute) / 60)): return angle = self.sensor.getAngle() acceleration = self.sensor.getAcceleration() gps = self.sensor.getGPS() if (str(gps[0]) == "None"): gps = "0,40.808679,-77.855693,0" else: gps = "0," + str(gps[0]) + "," + str(gps[1]) + ",0" print("Publishing: {0} to {1}, {2} to {3}, {4} to {5} ... ".format( angle, self.AIO_MOVEMENT_FEED, acceleration, self.AIO_ACCELERATION_FEED, gps, self.AIO_GPS_FEED), end='') try: self.client.publish(topic=self.AIO_MOVEMENT_FEED, msg=str(angle)) self.client.publish(topic=self.AIO_ACCELERATION_FEED, msg=str(acceleration)) self.client.publish(topic=self.AIO_GPS_FEED, msg=str(gps)) print("DONE") except Exception as e: print(e) print("FAILED") finally: self.last_random_sent_ticks = time.ticks_ms()
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
class Wifi(ConfigOp): def __init__(self, hostname, pin=2): self.__wlan = None self.__timeout = DEFAULT_TMOUT self.__led = Relay(pin) self.is_ok = False self.gw = None self.ip = None self.dns = None ConfigOp.__init__(self, 'wifi', CONFIG_NAME) self.add_command(self.__get_info, GET) self.add_command(self.__reconnect, SET, 'reconnect') self.__hostname = hostname def is_connected(self): return self.__wlan != None and self.__wlan.isconnected() async def __get_info(self, _): v = self.get_info() await sleep(0) return result(200, None, v) async def __reconnect(self, _): delayed_task(5000, self.async_connect, (True), True) return result(200, None, RECONNECT_WIFI) async def __reload_config(self): # NOSONAR return await self.__reconnect(None) def get_info(self): return { "mac": MAC, "connected": self.is_connected(), "connection tested": self.is_ok, "hostname": self.__hostname, "ip": self.ip, "gw": self.gw, "dns": self.dns } def check_wifi_config(self): self.load() return not (self.__config is None or is_str_empty(self.__config[SSID]) or is_str_empty(self.__config[PASSWORD])) def disconnect(self): if self.__wlan is not None and self.__wlan.isconnected(): self.__wlan.disconnect() self.__wlan.active(False) async def async_connect(self, force_rec=False): if self.__wlan is not None and self.__wlan.isconnected(): if force_rec: self.disconnect() return await self.__async_connect() return True return await self.__async_connect() async def __async_connect(self): self.__connect_init() return await self.__async_connect_finish() async def __async_connect_finish(self): start_time = time() # Check time while not self.__wlan.isconnected(): await sleep_ms(DEFAULT_300) self.__led.on() await sleep_ms(DEFAULT_300) self.__led.off() if time() - start_time > self.__timeout: log.error("Wifi connection timeout: %d", self.__timeout) break return self.__set_properties() def __connect_init(self): self.check_wifi_config() if self.__config is None: log.error("Wifi config is None") return log.info("Connect to wifi: %s", self.__config[SSID]) self.__wlan = WLAN(STA_IF) # 创建 station 接口 if self.__wlan.isconnected(): self.__wlan.disconnect() self.__wlan.active(True) # Activate the interface self.__wlan.scan() # Scan self.__led.off() self.__wlan.config(dhcp_hostname=self.__hostname) self.__wlan.connect(self.__config[SSID], self.__config[PASSWORD]) # 连接到指定ESSID网络 if TIMEOUT in self.__config: self.__timeout = self.__config[TIMEOUT] def __set_properties(self): if self.__wlan.isconnected(): log.info('network information: %r', self.__wlan.ifconfig()) (self.ip, _, self.gw, self.dns) = self.__wlan.ifconfig() self.is_ok = True self.__led.on() else: self.ip = None self.gw = None self.dns = None self.is_ok = False self.__wlan = None self.__led.off() return self.is_ok def check_connection(self): if hw.WIFI_CHECK_TYPE == 0: return True if not self.is_connected(): return False if hw.WIFI_CHECK_TYPE == 1: return True dest = self.gw if hw.WIFI_CHECK_TYPE == 3: if WIFI_CHECK_HOST in self.__config != None: dest = self.__config[WIFI_CHECK_HOST] else: dest = hw.WIFI_CHECK_HOST return ping_check(dest) async def monitor(self): log.debug("Setup wifi monitor") while hw.WIFI: try: await sleep(hw.WIFI_CHECK_INTVAL) if not self.check_connection(): log.info("Wifi is not ready, reconnecting...") await self.async_connect(True) except: #NOSONAR # pylint: disable=W0702 pass
def setup(): global wdt, sd, logger, AP, pin_relay_AP, pin_relay_LED, pin_switch_setupMode, pin_switch_RPi, wdt global server, server_timer, adc_c, taskTime_daily, taskTime_hourly # Logger logging.basicConfig(level=logging.DEBUG) logger = logging.getLogger(__name__) logger.info('===========================') logger.info(' Starting CTLR ') logger.info('===========================') # HW Setup wdt = WDT(timeout=20 * 60 * 1000) wdt.feed() sd = SD() os.mount(sd, '/sd') adc = machine.ADC() # adc_c = adc.channel(pin='P19', attn=ADC.ATTN_11DB) adc_c = adc.channel(pin='P18', attn=ADC.ATTN_11DB) # Output Vref of P22 # adc.vref_to_pin('P22') # while True: # time.sleep(1) # Set calibration - see note above adc.vref(1100) # # TEMPERATURE/HUMIDITY SENSOR # py = Pysense() # si7006a20 = SI7006A20(py) pin_relay_AP = Pin('P20', mode=Pin.OUT, pull=Pin.PULL_DOWN) pin_relay_LED = Pin('P19', mode=Pin.OUT, pull=Pin.PULL_DOWN) pin_switch_setupMode = Pin('P9', mode=Pin.IN, pull=Pin.PULL_DOWN) pin_switch_RPi = Pin('P7', mode=Pin.OUT, pull=Pin.PULL_DOWN) # Network Setup # CHANGE AP IN pybytes_config.json! pbconfig = pybytes.get_config() AP = pbconfig['wifi']['ssid'] # WIFI Connection if AP in ['GCAM1_AP', 'GCAM2_AP', 'GCAM2_AP']: pin_relay_AP.value(1) wlan = WLAN(mode=WLAN.STA) while not wlan.isconnected(): nets = wlan.scan() logger.info(nets) if AP in [net.ssid for net in nets]: pybytes.connect_wifi() time.sleep(5) # for net in nets: # if net.ssid == 'RUT230_7714': # pybytes.connect_wifi() # # No Internet Case # wlan.ifconfig(config=('192.168.1.100', '255.255.255.0', '192.168.1.1', '8.8.8.8')) # wlan.connect('RUT230_7714', auth=(WLAN.WPA2, 'Ei09UrDg'), timeout=5000) # while not wlan.isconnected(): # machine.idle() # save power while waiting socket_svr.switch_setupMode = pin_switch_setupMode.value() socket_svr.setup() # _thread.stack_size(16384) # UPDATE TIME BY GPS logger.info('GPS time fixing start...') shmGPSclock.update_RTC_from_GPS() socket_svr.state = 1 logger.info('GPS time fixing done...') server = Server() server.timeout(5) # Creating data/date folder of today dirToday = '/sd/data/{}'.format(date_string(time.time())) if mkdir(dirToday): logger.info('{} created'.format(dirToday)) gc.enable() # CREATING FOLDER FOR FTP mkdir('/sd/data/{}'.format(date_string(time.time()))) # PERIODIC TASKS taskTime_daily = getNextGridTime(time.time(), 3600 * 24) taskTime_hourly = getNextGridTime(time.time(), 3600)
return BattAverage #get online using known nets if available #Do this before working with anything else.. Because some code faults will kick you offline unless you're in range of the primary network in pybytes_config.json #If that happens... set up a cellphone as a hotspot using the SAME credentials as the primary network in pybytes_config.json and reboot the sensors #then when it gets back online, you can fix the code, push it and turn off the hotspot.. if machine.reset_cause() != machine.SOFT_RESET: from network import WLAN wl = WLAN() if not wl.isconnected(): wl.mode(WLAN.STA) original_ssid = wl.ssid() original_auth = wl.auth() print("Scanning for known wifi nets") available_nets = wl.scan() netsisee = frozenset([e.ssid for e in available_nets]) known_nets_names = frozenset([key for key in nets.known_nets]) net_to_use = list(netsisee & known_nets_names) try: net_to_use = net_to_use[0] net_properties = nets.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])
# 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(): print('Connected') tim_a.freq(10) wlan.irq(trigger=WLAN.ANY_EVENT, wake=machine.SLEEP) else :
class MicroWifi: # ============================================================================ # ===( Constants )============================================================ # ============================================================================ _ETH_AP = 1 _ETH_STA = 0 _IP_NONE = '0.0.0.0' _DEFAULT_AUTH_TYPE = WLAN.WPA2 _AP_MASK = '255.255.255.0' _DEFAULT_TIMEOUT_SEC = 10 # ============================================================================ # ===( Utils )=============================================================== # ============================================================================ @staticmethod def _mac2Str(binMac): return hexlify(binMac, ':').decode().upper() # ---------------------------------------------------------------------------- def _setAPInfos(self, ssid=None, key=None, ip=None, mask=None, gateway=None, dns=None): self._apInfos = { 'ssid': ssid, 'key': key, 'ip': ip, 'mask': mask, 'gateway': gateway, 'dns': dns } # ---------------------------------------------------------------------------- def _setConnectionInfos(self, bssid=None, ssid=None, key=None, ip=None, mask=None, gateway=None, dns=None): self._connInfos = { 'macBssid': bssid, 'ssid': ssid, 'key': key, 'ip': ip, 'mask': mask, 'gateway': gateway, 'dns': dns } # ---------------------------------------------------------------------------- def _openConf(self): try: with open(self._filePath, 'r') as jsonFile: self._confObj = load(jsonFile) except: self._confObj = {} if self._confObj.get('STA', None) is None: self._confObj['STA'] = {} # ---------------------------------------------------------------------------- def _writeConf(self): try: jsonStr = dumps(self._confObj) try: mkdir(self._confPath) except: pass jsonFile = open(self._filePath, 'wb') jsonFile.write(jsonStr) jsonFile.close() return True except: return False # ============================================================================ # ===( Constructor )========================================================== # ============================================================================ def __init__(self, confName="wifi", confPath="/flash/conf", useExtAntenna=False): self._confPath = confPath self._filePath = '%s/%s.json' % (confPath, confName) self._wlan = WLAN() self._antenna = WLAN.EXT_ANT if useExtAntenna else WLAN.INT_ANT self._openConf() self._setAPInfos() self._setConnectionInfos() self._wlan.init(antenna=self._antenna) self.DisableRadio() # ============================================================================ # ===( Functions )============================================================ # ============================================================================ def DisableRadio(self): self.CloseAccessPoint() self.CloseConnectionToAP() self._wlan.deinit() # ---------------------------------------------------------------------------- def GetMACAddr(self): return self._mac2Str(self._wlan.mac()) # ---------------------------------------------------------------------------- def GetAPInfos(self): if not self.IsAccessPointOpened(): self._setAPInfos() return self._apInfos # ---------------------------------------------------------------------------- def GetConnectionInfos(self): if not self.IsConnectedToAP(): self._setConnectionInfos() return self._connInfos # ---------------------------------------------------------------------------- def ScanAP(self): try: if self._wlan.mode() == WLAN.STA: self._wlan.init(antenna=self._antenna) return self._wlan.scan() except: return () # ---------------------------------------------------------------------------- def OpenAccessPoint(self, ssid, key=None, ip='192.168.0.254', autoSave=True): if ssid and ip: try: self._wlan.ifconfig(id=self._ETH_AP, config=(ip, self._AP_MASK, ip, ip)) auth = (self._DEFAULT_AUTH_TYPE, key) if key else None self._wlan.init(mode=WLAN.STA_AP, ssid=ssid, auth=auth, antenna=self._antenna) print("WIFI ACCESS POINT OPENED :") print(" - MAC address : %s" % self.GetMACAddr()) print(" - Network SSID : %s" % ssid) print(" - IP address : %s" % ip) print(" - Mask : %s" % self._AP_MASK) print(" - Gateway IP : %s" % ip) print(" - DNS server : %s" % ip) if autoSave: self._confObj['AP'] = {'ssid': ssid, 'key': key, 'ip': ip} self._writeConf() self._setAPInfos(ssid, key, ip, self._AP_MASK, ip, ip) return True except: self.CloseAccessPoint() return False # ---------------------------------------------------------------------------- def OpenAccessPointFromConf(self): try: ssid = self._confObj['AP']['ssid'] key = self._confObj['AP']['key'] ip = self._confObj['AP']['ip'] return self.OpenAccessPoint(ssid, key, ip, False) except: return False # ---------------------------------------------------------------------------- def RemoveAccessPointFromConf(self): try: self._confObj.pop('AP') return self._writeConf() except: return False # ---------------------------------------------------------------------------- def CloseAccessPoint(self): try: ip = self._IP_NONE self._wlan.mode(WLAN.STA) self._wlan.ifconfig(id=self._ETH_AP, config=(ip, ip, ip, ip)) return True except: return False # ---------------------------------------------------------------------------- def IsAccessPointOpened(self): return self._wlan.ifconfig(self._ETH_AP)[0] != self._IP_NONE # ---------------------------------------------------------------------------- def ConnectToAP(self, ssid, key=None, macBssid=None, timeoutSec=None, autoSave=True): if ssid: if not key: key = '' if not timeoutSec: timeoutSec = self._DEFAULT_TIMEOUT_SEC timeout = timeoutSec * 1000 if self._wlan.mode() == WLAN.STA: self._wlan.init(antenna=self._antenna) print("TRYING TO CONNECT WIFI TO AP %s..." % ssid) for ap in self.ScanAP(): if ap.ssid == ssid and \ ( not macBssid or self._mac2Str(ap.bssid) == macBssid ) : self._wlan.connect(ssid=ap.ssid, bssid=ap.bssid, auth=(self._DEFAULT_AUTH_TYPE, key), timeout=timeout) t = ticks_ms() while ticks_diff(t, ticks_ms()) < timeout: sleep(0.100) if self.IsConnectedToAP(): bssid = self._mac2Str(ap.bssid) staCfg = self._wlan.ifconfig(id=self._ETH_STA) ip = staCfg[0] mask = staCfg[1] gateway = staCfg[2] dns = staCfg[3] print("WIFI CONNECTED TO AP :") print(" - MAC address : %s" % self.GetMACAddr()) print(" - Network BSSID : %s" % bssid) print(" - Network SSID : %s" % ssid) print(" - IP address : %s" % ip) print(" - Mask : %s" % mask) print(" - Gateway IP : %s" % gateway) print(" - DNS server : %s" % dns) if autoSave: sta = { 'ssid': ssid, 'key': key, } self._confObj['STA'][bssid] = sta self._writeConf() self._setConnectionInfos(bssid, ssid, key, ip, mask, gateway, dns) return True self.CloseConnectionToAP() break print("FAILED TO CONNECT WIFI TO AP %s" % ssid) return False # ---------------------------------------------------------------------------- def ConnectToAPFromConf(self, bssidMustBeSame=False, timeoutSec=None): if self._wlan.mode() == WLAN.STA: self._wlan.init(antenna=self._antenna) for ap in self.ScanAP(): for bssid in self._confObj['STA']: macBssid = self._mac2Str(ap.bssid) if bssidMustBeSame else None if self._confObj['STA'][bssid]['ssid'] == ap.ssid and \ ( not macBssid or bssid == macBssid ) : if self.ConnectToAP(ap.ssid, self._confObj['STA'][bssid]['key'], macBssid, timeoutSec, False): return True break return False # ---------------------------------------------------------------------------- def RemoveConnectionToAPFromConf(self, ssid, macBssid=None): try: changed = False for bssid in self._confObj['STA']: if self._confObj['STA'][bssid]['ssid'] == ssid and \ ( not macBssid or bssid == macBssid ) : self._confObj['STA'].pop(bssid) changed = True if changed: return self._writeConf() except: pass return False # ---------------------------------------------------------------------------- def CloseConnectionToAP(self): try: self._wlan.disconnect() self._wlan.ifconfig(id=self._ETH_STA, config='dhcp') return True except: return False # ---------------------------------------------------------------------------- def IsConnectedToAP(self): return self._wlan.ifconfig(self._ETH_STA)[0] != self._IP_NONE # ---------------------------------------------------------------------------- def ResolveIPFromHostname(self, hostname): originalMode = self._wlan.mode() if originalMode == WLAN.STA_AP: self._wlan.mode(WLAN.STA) try: ipResolved = getaddrinfo(hostname, 0)[0][-1][0] except: ipResolved = None if originalMode == WLAN.STA_AP: self._wlan.mode(WLAN.STA_AP) return ipResolved if ipResolved != self._IP_NONE else None # ---------------------------------------------------------------------------- def InternetAccessIsPresent(self): return (self.ResolveIPFromHostname('iana.org') is not None) # ---------------------------------------------------------------------------- def WaitForInternetAccess(self, timeoutSec=None): if not timeoutSec: timeoutSec = self._DEFAULT_TIMEOUT_SEC timeout = timeoutSec * 1000 t = ticks_ms() while ticks_diff(t, ticks_ms()) < timeout: sleep(0.100) if self.InternetAccessIsPresent(): return True return False