Esempio n. 1
0
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)
Esempio n. 2
0
    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
Esempio n. 3
0
    def scanForNetworks(self):
        nlist = {}
        if _PLATFORM_ == "ESP32":
            wlan = WLAN(mode=WLAN.STA)
            networks = wlan.scan()
            wlan.mode(WLAN.AP)

            for n in networks:
                nlist[n[0]] = n[0] + ", rssi " + str(n[4])

        elif _PLATFORM_ == "PC":
            pass
            nlist['null'] = 'No networks found.'

        return nlist
Esempio n. 4
0
    def provision(self, ssid, password, security):
        try:
            wlan = WLAN()
            wlan.mode(WLAN.STA)
            authtype = int(security)
            wlan.connect(ssid, auth=(authtype, password), timeout=5000)
            while not wlan.isconnected():
                self._callBack({
                    'Provisioning': True,
                    'ip': self.wlan.ifconfig()
                })
                self.log("Provisioning successful, ip address: " +
                         str(self.wlan.ifconfig()))

        except:
            self.log("Provisioning failed.")
            wlan.mode(WLAN.AP)
            self._callBack({'Provisioning': True, 'ip': self.wlan.ifconfig()})
Esempio n. 5
0
    def connect_sta(self,time_out = 120):
        config_dict = self.get_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))
Esempio n. 6
0
def wlan_init():
    global w
    if w is not None:
        #print('already initialized')
        return w
    print("Initialise WiFi")
    w = WLAN()  #antenna=WLAN.EXT_ANT)
    try:
        w.hostname(
            binascii.hexlify(machine.unique_id()) + "." + os.uname().sysname +
            "." + "w")
        # hostname is not available in 1.18.2
    except:
        pass
    # print("ap_mac", binascii.hexlify(w.mac().ap_mac))
    # print("sta_mac", binascii.hexlify(w.mac().sta_mac))
    if (w.mode() == WLAN.AP):
        print("switch from AP to STA_AP")
        w.mode(WLAN.STA_AP)
    # original_ssid = w.ssid()
    # original_auth = w.auth()
    return w
Esempio n. 7
0
if not 'LaunchPad' in mch and not 'WiPy' in mch:
    raise Exception('Board not supported!')


def wait_for_connection(wifi, timeout=10):
    while not wifi.isconnected() and timeout > 0:
        time.sleep(1)
        timeout -= 1
    if wifi.isconnected():
        print('Connected')
    else:
        print('Connection failed!')


wifi = WLAN()
print(wifi.mode() == WLAN.STA)
print(wifi.antenna() == WLAN.INT_ANT)

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)
Esempio n. 8
0
                "course": str(gps.course),
                "battery": str(vBatt)
            }
        }
        response.WriteResponseJSONOk(statusJSON)

    return [('/status.json', 'GET', _statusjson)]


# Startup
print('Starting GPS (LoRaTracker)')
print('   ID: ' + str(Unit_ID))

print("Starting Network")
wlan = WLAN()
wlan.mode(WLAN.STA)
# scan for available networks
available_nets = wlan.scan()
for net in available_nets:
    print('   Found SSID: ' + net.ssid)
nets = frozenset([e.ssid for e in available_nets])
# match available nets with known nets
known_nets_names = frozenset([key for key in known_nets])
net_to_use = list(nets & known_nets_names)
# try and use the first matching network
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]
    print('   Connecting to: ' + net_to_use)
Esempio n. 9
0
if not 'LaunchPad' in mch and not 'WiPy' in mch:
    raise Exception('Board not supported!')


def wait_for_connection(wifi, timeout=10):
    while not wifi.isconnected() and timeout > 0:
        time.sleep(1)
        timeout -= 1
    if wifi.isconnected():
        print('Connected')
    else:
        print('Connection failed!')


wifi = WLAN(0, WLAN.STA)
print(wifi.mode() == WLAN.STA)
print(wifi.antenna() == WLAN.INT_ANT)

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')
Esempio n. 10
0
class WifiManager:
    def __init__(self, known_nets):
        self._known_nets = known_nets
        # create network in STAtion mode
        # pycom: device always starts up in AP-mode
        #self._wl = WLAN()
        #self._wl.mode(WLAN.STA)

    '''def print_debug(self, message):
        """print_debug() - for debugging """
        if USE_DEBUG:
            print(msg)
    '''

    # 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)
            print_debug("Wifimanager - SSID to use...{}".format(net_to_use))
            try:
                net_to_use = net_to_use[0]
                print_debug("Wifimanager - net to use...{}".format(net_to_use))
                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]
                print_debug(
                    "Wifimanager - net_properties...{}".format(net_properties))
                if 'wlan_config' in net_properties:
                    print_debug("Wifimanager - wlan_config...{}".format(
                        net_properties['wlan_config']))
                    self._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 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)
Esempio n. 12
0
# 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)
Esempio n. 13
0
wlan = WLAN()
try:
    print("sta_mac", binascii.hexlify(wlan.mac().sta_mac))
    print("ap_mac", binascii.hexlify(wlan.mac().ap_mac))
except:
    print("mac", binascii.hexlify(wlan.mac()))
print("is_connected", wlan.isconnected())
print("ssid", wlan.ssid())
print("bssid", binascii.hexlify(wlan.bssid()))
try:
    print("country", wlan.country())
except:
    pass
print("ifconfig", wlan.ifconfig())
print('IP:', wlan.ifconfig()[0])
print("mode", wlan.mode(), end=' ')
print_wifi_mode(wlan.mode())
print()

try:
    print("===== lora =======================================")
    from network import LoRa
    lora = LoRa(mode=LoRa.LORAWAN, region=LoRa.EU868)
    print("mac", binascii.hexlify(lora.mac()))
    print(lora.frequency())
    print(lora.has_joined())
    print(lora.tx_power())
    print(lora.power_mode())
    #print(lora.stats())
except:
    pass
HOSTIP = 'HOST'
device = 'DEVICE'

######################
intensity = 0
HOSTPORT = 8080
pycom.heartbeat(False)
rtc = RTC()

#whites = [0x000000, 0x191919, 0x323232,0x4B4B4B, 0x646464, 0x7D7D7D, 0x969696, 0xAFAFAF0, 0xC8C8C8, 0xE1E1E1, 0xFFFFFF]
#blues = [0x000000, 0x000019, 0x000032,0x00004B, 0x000064, 0x00007D, 0x000096, 0x0000F0, 0x0000C8, 0x0000E1, 0x0000FF]
#reds = [0x000000, 0x190000, 0x320000,0x4B0000, 0x640000, 0x7D0000, 0x960000, 0xAF0000, 0xC80000, 0xE10000, 0xFF0000]
#greens = [0x000000, 0x001900, 0x003200,0x004B00, 0x006400, 0x007D00, 0x009600, 0x00AF00, 0x00C800, 0x00E100, 0x00FF00]
rtc.ntp_sync("dk.pool.ntp.org")
wlan = WLAN(mode=WLAN.STA)
wlan.mode()
pycom.heartbeat(False)

nets = wlan.scan()
for net in nets:
    if net.ssid == WIFISSID:
        print("Found network")
        wlan.connect(net.ssid, auth=(net.sec, WIFIPASS), timeout=5000)
        while not wlan.isconnected():
            machine.idle()
        print("Connected succesfully")
        break

m_count = 0
s = socket(AF_INET, SOCK_DGRAM)
Esempio n. 15
0
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)
Esempio n. 16
0
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:
            del self._confObj['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 list(self._confObj['STA']):
                if self._confObj['STA'][bssid]['ssid'] == ssid and \
                   ( not macBssid or bssid == macBssid ) :
                    del self._confObj['STA'][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
Esempio n. 17
0
class WifiManager:
    def __init__(self, jsonfile):
        # Load configuration from config JSON file.
        # wificonfig.json contans the network settings
        # STATIC_IP is 'None' or empty string -> use dynamic IP
        self._config = self.readjson(jsonfile)

        # create network in STAtion mode
        # pycom: device always starts up in AP-mode
        self._wlan = WLAN(mode=WLAN.STA)
        if USE_DEBUG:
            print('WifiManager::WLAN mode:',
                  self._wlan.mode())  # pycom: 1=STA, 2=AP)

    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

    # pycom connect
    def connect(self):
        """connect() - connects device according to network parameters in JSON-file."""
        self._wlan = WLAN()  # get current object, without changing the mode

        # skip connecting, when a soft-reset is performed
        if machine.reset_cause() != machine.SOFT_RESET:
            self._wlan.init(mode=WLAN.STA)
            # configuration below MUST match your home router settings!!
            # IP, Subnet, Gateway, DNS
            if self._config['STATIC_IP'] is None:
                if USE_DEBUG:
                    print('WifiManager::Static IP configuration for SSID: ',
                          self._config['SSID'])
                self._wlan.ifconfig(config=(self._config['STATIC_IP'],
                                            self._config['MASKER'],
                                            self._config['GATEWAY_IP'],
                                            self._config['DNS']))
            else:
                if USE_DEBUG:
                    print('WifiManager::Dynamic IP configuration for SSID: ',
                          self._config['SSID'])
                pass

            # connect to Wifi
            if USE_DEBUG:
                print('WifiManager::isconnected:', self._wlan.isconnected())

            if not self._wlan.isconnected():
                if USE_DEBUG:
                    print(
                        "WifiManager::start '{0}' to connect to '{1}' with IP '{2}'"
                        .format(self._config['IDENTITY'], self._config['SSID'],
                                self._config['STATIC_IP']))

                # change the line below to match your network ssid, security and password
                self._wlan.connect(self._config['SSID'],
                                   auth=(WLAN.WPA2, self._config['PASSWRD']),
                                   timeout=5000)
                while not self._wlan.isconnected():
                    machine.idle()  # save power while waiting

        # connected, return network config
        return self._wlan.ifconfig()

    # wrapper for disconnecting network
    def disconnect(self):
        """disconnect() - de-activate network interface, but leaves Wifi radio on"""
        self._wlan.disconnect(
        )  # pycom - disconnect from Wifi, but leave Wif radio on.
        if USE_DEBUG:
            print('WifiManager::Wifi disconnected')

    # wrapper for disabling Wifi radio
    def deinit(self):
        """deinit() - disable Wifi radio"""
        self._wlan.deint()  # pycom
        if USE_DEBUG:
            print('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._wlan.scan()

    # wrapper for wlan.isconnected()
    @property
    def isconnected(self):
        """isconnected() - returns if connected to Wifi (True)
        or not (False)"""
        return self._wlan.isconnected()

    def print_config(self):
        """print_config() - print config data on screen."""
        for key in self._config.keys():
            print('[{0}] = {1}'.format(key, self._config[key]))

    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 example: remote access, ftp and telnet, not USB
        server.init(login=(user, passwrd), timeout=600)
        if USE_DEBUG:
            print('WifiManager::password {} is changed...'.format(user))

    @property
    def __config(self):
        """returns config tuple"""
        return self._config

    @property
    def mac(self):
        """returns MAC-address of device"""
        mac = hexlify(self._wlan.mac(), ':').decode()  # pycom
        # return (mac) # lower case
        return mac.upper()
Esempio n. 18
0
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):
        """
        https://docs.pycom.io/tutorials/all/wlan.html
        https://github.com/pycom/pydocs/blob/master/firmwareapi/pycom/network/wlan.md
        """

        # Todo: Propagate more parameters here, e.g. for using an external antenna.
        self.station = WLAN()

        #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.
        self.station.init()

        # Check WiFi connectivity.
        if self.station.isconnected():

            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_address_status()

            return True

        # Prepare information about known WiFi networks.
        networks_known = frozenset(
            [station['ssid'] for station in self.stations])

        log.info("WiFi STA: Starting interface")
        self.station.mode(WLAN.STA)

        # Attempt to connect to known/configured networks.
        log.info("WiFi STA: Directly connecting to configured networks: %s",
                 list(networks_known))
        try:
            self.connect_stations(networks_known)

        except:
            log.warning('WiFi: Switching to AP mode not implemented yet')

        # 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 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.station.isconnected():

            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 switch to AP mode here or alternatively '
                'buffer telemetry data to flash to be scheduled for transmission later.'
            )
            raise WiFiException(message)

    def connect_station(self, network):

        network_name = network['ssid']

        log.info('WiFi STA: Prepare connecting to network "{}"'.format(
            network_name))

        auth_mode = self.get_auth_mode(network_name)

        log.info(
            'WiFi STA: Attempt connecting 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)

        # Set interval how often to poll for WiFi connectivity.
        network_poll_interval = 800

        # 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 station network to arrive.
        # ``isconnected()`` returns True when connected to a WiFi access point *and* having a valid IP address.
        retries = int(network_timeout * network_poll_interval)
        while not self.station.isconnected() and retries > 0:

            log.info(
                'WiFi STA: Waiting for network "{}".'.format(network_name))
            retries -= 1

            # Save power while waiting.
            machine.idle()

            # Feed watchdog.
            self.manager.device.feed_watchdog()

            # Don't busy-wait.
            time.sleep_ms(network_poll_interval)

        if not self.station.isconnected():
            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 scan_stations(self):

        self.manager.device.feed_watchdog()

        # Inquire visible networks.
        log.info("WiFi STA: Scanning for networks")
        stations_available = self.station.scan()
        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

        # Compute set of effective networks by intersecting known with found ones.
        #network_candidates = list(networks_found & networks_known)
        #log.info("WiFi STA: Network candidates: %s", network_candidates)

    def get_ssid(self):
        return self.station.ssid()

    def get_ip_address(self):
        try:
            return self.station.ifconfig()[0]
        except:
            pass

    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)
Esempio n. 19
0
import machine
from keychain import WLAN_SSID, WLAN_PASSKEY
from helpers import setup_rtc

known_nets = [(WLAN_SSID, WLAN_PASSKEY)]

if machine.reset_cause(
) != machine.SOFT_RESET:  # needed to avoid losing connection after a soft reboot
    from network import WLAN
    wl = WLAN()

    # save the default ssid and auth
    original_ssid = wl.ssid()
    original_auth = wl.auth()

    wl.mode(WLAN.STA)

    available_nets = wl.scan()
    nets = frozenset([e.ssid for e in available_nets])

    known_nets_names = frozenset([e[0] for e in known_nets])
    net_to_use = list(nets & known_nets_names)

    try:
        net_to_use = net_to_use[0]
        pwd = dict(known_nets)[net_to_use]
        sec = [e.sec for e in available_nets if e.ssid == net_to_use][0]
        wl.connect(net_to_use, (sec, pwd), timeout=10000)
        setup_rtc()
    except:
        wl.init(mode=WLAN.AP,
Esempio n. 20
0
    print("wifi_pwd_sta", pycom.wifi_pwd_sta())
    print("wifi_ssid_ap", pycom.wifi_ssid_ap())
    print("wifi_pwd_ap", pycom.wifi_pwd_ap())
except:
    pass


print("===== wlan =======================================")
from network import WLAN
wlan = WLAN()
print("is_connected", wlan.isconnected())
print("bssid", ubinascii.hexlify(wlan.bssid()))
print("country", wlan.country())
print("ifconfig", wlan.ifconfig())
print('IP:', wlan.ifconfig()[0])
print("mode", wlan.mode(), "(STA=", WLAN.STA, "AP=", WLAN.AP, ")")

try:
    print("===== lora =======================================")
    from network import LoRa
    lora = LoRa(mode=LoRa.LORAWAN, region=LoRa.EU868)
    print("mac", ubinascii.hexlify(lora.mac()))
    print(lora.frequency())
    print(lora.has_joined())
    print(lora.tx_power())
    print(lora.power_mode())
    #print(lora.stats())
except:
    pass

try: