Example #1
0
def wifiAsAp():
    global wifi
    ap_if = WLAN(AP_IF)
    ap_if.active(True)
    ap_if.config(essid='hywcoinpo', channel=7, password='******')
    log.info('wifi as AP')
    wifi = ap_if
Example #2
0
def create_wifi():  # type: () -> str
    ssid = "QRGames Player"

    ap = WLAN(AP_IF)
    ap.active(True)
    ap.config(essid=ssid)
    return ap.ifconfig()[0]
Example #3
0
def setup_wifi(CLIENT_ID):
    AP = WLAN(AP_IF)
    AP.active(False)
    log("AP Down")

    STA = WLAN(STA_IF)
    STA.active(True)
    log("STA Up")
    STA.config(dhcp_hostname=CLIENT_ID)
    log("Config UP")
    connect_wifi(STA)
    return STA
Example #4
0
def wlan_connect(wlan_essid, wlan_password, hostname: str = ""):
    from network import WLAN, STA_IF
    from utime import sleep
    nic = WLAN(STA_IF)
    if not nic.isconnected():
        print("Connecting to network: ...")
        nic.active(True)
        if len(hostname) > 0:
            nic.config(dhcp_hostname=hostname)
        nic.connect(wlan_essid, wlan_password)
        while not nic.isconnected():
            sleep(1)
    print("Network connected, the configuration: {}".format(nic.ifconfig()))
Example #5
0
    async def EnableAP(self, aMode: bool, aPassw=None):
        Log.Print(1, 'i', 'EnableAP() %s, %s ' % (aMode, aPassw))

        R = WLAN(AP_IF)
        R.active(False)
        await sleep(1)
        R.active(aMode)

        if (aMode):
            R.config(essid='vRelay-' + GetMac(R)[-4:],
                     authmode=AUTH_WPA_WPA2_PSK,
                     password=aPassw)
            await self._WaitForReady(R.active)
        return R
Example #6
0
def set_wifi(essid, pwd, timeout=60):
    console_write('[NW: STA] SET WIFI STA NW {}'.format(essid))

    # Disable AP mode
    ap_if = WLAN(AP_IF)
    if ap_if.active():
        ap_if.active(False)
    del ap_if

    # Set STA and Connect
    sta_if = WLAN(STA_IF)
    sta_if.active(True)
    # Set custom DHCP hostname
    sta_if.config(dhcp_hostname=cfgget('devfid'))
    # Check are we already connected
    if not sta_if.isconnected():
        # Multiple essid and pwd handling with retry mechanism
        essid, pwd = __select_available_wifi_nw(sta_if, essid, pwd)

        # Connect to the located wifi network
        if essid is not None:
            console_write('\t| [NW: STA] CONNECT TO NETWORK {}'.format(essid))
            # connect to network
            sta_if.connect(essid, pwd)
            # wait for connection, with timeout set
            while not sta_if.isconnected() and timeout > 0:
                console_write(
                    "\t| [NW: STA] Waiting for connection... {} sec".format(
                        timeout))
                timeout -= 1
                sleep_ms(500)
            # Set static IP - here because some data comes from connection. (subnet, etc.)
            if sta_if.isconnected() and __set_wifi_dev_static_ip(sta_if):
                sta_if.disconnect()
                del sta_if
                return set_wifi(essid, pwd)
        else:
            console_write(
                "\t| [NW: STA] Wifi network was NOT found: {}".format(essid))
            return False
        console_write("\t|\t| [NW: STA] network config: " +
                      str(sta_if.ifconfig()))
        console_write("\t|\t| [NW: STA] CONNECTED: " +
                      str(sta_if.isconnected()))
    else:
        console_write("\t| [NW: STA] ALREADY CONNECTED TO {}".format(essid))
    cfgput("devip", str(sta_if.ifconfig()[0]))
    set_dev_uid()
    return sta_if.isconnected()
Example #7
0
def enable_ap_mode(essid=None, password=None):
    from network import AP_IF, AUTH_WPA_WPA2_PSK, WLAN
    from ubinascii import hexlify

    wifi_interface = WLAN(AP_IF)

    if not essid:
        essid = b"micropython-esp8266-%s" % hexlify(
            wifi_interface.config("mac")[-3:])
    if not password:
        password = b'micropybootconfig'

    wifi_interface.config(essid=essid,
                          authmode=AUTH_WPA_WPA2_PSK,
                          password=password)
    del hexlify
Example #8
0
def sys_config():
    from network import WLAN
    global MyName,debug,debugDNS,runREPL,runDNS,runWeb,threaded
    from config import *
    from config import MyName,debug,debugDNS,runREPL,runDNS,runWeb,threaded
    wlan=WLAN()
    ip = wlan.ifconfig()[0]
    if(ip == "0.0.0.0"): ip = "192.168.4.1"
    apMode = wlan.config('essid')
    try:
        x = open("/client.cfg")
        x.close()
        apMode += " - Wifi Client Mode"
    except:
        apMode += " - AP Enabled"
    if(wlan.isconnected()): apMode += ' - Connected'
    content = "MyName:\t\t" + str(MyName) + "\n"
    content += "Network:\t" + apMode + "\n"
    content += "IP Address:\t" + ip + "\n"
    content += "debug\t\t" + str(debug) + "\n"
    content += "debugDNS\t" + str(debugDNS) + "\n"
    content += "runREPL\t\t" + str(runREPL) + "\n"
    content += "runDNS\t\t" + str(runDNS) + "\n"
    content += "runWeb\t\t" + str(runWeb) + "\n"
    content += "threaded\t" + str(threaded) + "\n"
    return(content)
Example #9
0
class AccessPoint:
    def __init__(self):
        self.ap_if = WLAN(AP_IF)

    def get_ip(self):
        return self.ap_if.ifconfig()[0]

    def stop(self):
        self.ap_if.active(False)

    def start(self, essid, password):
        self.ap_if.active(True)
        if password:
            self.ap_if.config(essid=essid, password=password, authmode=4)
        else:
            self.ap_if.config(essid=essid, authmode=0)
Example #10
0
class WifiAp:
    def __init__(self):
        self.ap = WLAN(AP_IF)

    def start_ap(self):
        if self.ap.active():
            return
        self.ap.active(True)
        self.ap.config(essid=DEVICE_NAME, password=HW_PIN)
        while not self.ap.active():
            sleep(1)

    def stop_ap(self):
        if self.ap.active():
            self.ap.active(False)

    def get_info(self):
        if self.ap.active():
            (ip, _, gw, _) = self.ap.ifconfig()
            return {'ip': ip, 'gw': gw}
        return None
Example #11
0
def wlan_connect():
    global oled
    wlan = WLAN(STA_IF)  # create station interface
    wlan.active(True)  # bring interface up
    if not wlan.isconnected():
        oled.text('Connecting to network...', 0, 0)
        wlan.connect('SCOTTCAMPUS', 'mavericks')
        oled.text(wlan.config('essid'), 20, 35)
        oled.show()
        while not wlan.isconnected():
            pass
    print('Network config:', wlan.ifconfig())
Example #12
0
def set_access_point(_essid, _pwd, _authmode=3):
    console_write("[NW: AP] SET AP MODE: {} - {} - auth mode: {}".format(
        _essid, _pwd, _authmode))

    sta_if = WLAN(STA_IF)
    if sta_if.isconnected():
        sta_if.active(False)

    ap_if = WLAN(AP_IF)
    ap_if.active(True)
    # Set WiFi access point name (formally known as ESSID) and WiFi authmode (2): WPA2
    try:
        console_write("[NW: AP] Configure")
        ap_if.config(essid=_essid, password=_pwd, authmode=_authmode)
    except Exception as e:
        console_write("[NW: AP] Config Error: {}".format(e))
    if ap_if.active() and str(ap_if.config('essid')) == str(
            _essid) and ap_if.config('authmode') == _authmode:
        cfgput("devip", ap_if.ifconfig()[0])
    console_write("\t|\t| [NW: AP] network config: " + str(ap_if.ifconfig()))
    set_uid_macaddr_hex(ap_if)
    return ap_if.active()
Example #13
0
def sys_config_html():
    from network import WLAN
    global MyName,debug,debugDNS,runREPL,runDNS,runWeb,threaded
    from config import *
    from config import MyName,debug,debugDNS,runREPL,runDNS,runWeb,threaded
    wlan=WLAN()
    ip = wlan.ifconfig()[0]
    if(ip == "0.0.0.0"): ip = "192.168.4.1"
    apMode = wlan.config('essid')
    try:
        x = open("/client.cfg")
        x.close()
        apMode += " - Wifi Client Mode"
    except:
        apMode += " - AP Enabled"
    if(wlan.isconnected()):
        apMode += ' - Connected'
    apMode += ' <a href="/config/toggleAP">(switch)</a>'
    content = "Network:\t" + apMode + "\n"
    content += "IP Address:\t" + ip + "\n"
    for n in ["MyName","debug","debugDNS","runREPL","runDNS","runWeb","threaded"]:
        pad = " " * (15 - len(n))
        content += '<a href="/config/'+n+'">'+n+'</a>'+pad+ str(eval(n)) + "\n"
    return(content)
class Network():
    def __init__(self):
        self.wlan = WLAN(STA_IF)
        self.ap = WLAN(AP_IF)

    def is_active(self):
        """Checking Active Module

        :return: boolean
        """
        print("Check WLAN...")

        if self.wlan.active() is False:
            print("WLAN Non Active...")
            self.wlan.active(True)

        else:
            print("WLAN Active...")
            return True

        return False

    def connect(self, essid, password):
        """Connect To Network

        Keyword Arguments
        :param essid: the name essid
        :param password: the password
        :return: boolean
        """
        if self.is_active():
            print("Connecting....")
            self.wlan.connect(essid, password)

            if self.wlan.isconnected():
                print("Connected...")
                return True

            else:
                print("Failed Connect...")

        else:
            self.is_active()

    def is_connected(self):
        """ Checking Connection

        :return: boolean
        """
        res = self.wlan.isconnected()

        if res:
            print("Network Connected")

        else:
            print("Network Disconnected")

        return res

    def status(self):
        """ Checking status connection

        :return: boolean
        """
        self.is_connected()
        print("Status : ", self.wlan.ifconfig())

    def activate_ap(self, essid):
        if self.ap.active():
            print('Access Point Active')
            self.ap.config(essid=essid, password='******')

        else:
            print('Access Point Non Active')
            self.ap.active(True)

    def deactivate_ap(self):
        self.ap.active(False)
        print('Deactivate Access Point')
Example #15
0
from network import mDNS, ftp, telnet, AP_IF, STA_IF, WLAN
from machine import idle

mdns = mDNS()
ap = WLAN(AP_IF)
ap.active(True)
ap.config(essid='Sparthan')
ap.config(authmode=3, password='******')

print('WLAN connection succeeded!')
mdns.start('sparthan', 'MicroPython Sparthan ESP32')
ftp.start(user='******', password='******')
#telnet.start(user='******', password='******')
Example #16
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)
Example #17
0
def mac():
    from network import WLAN
    nw = WLAN()
    return nw.config('mac')  # 5 bytes
Example #18
0
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
Example #19
0
                    wlan.connect(net.ssid,
                                 auth=(net.sec, networks[net.ssid]),
                                 timeout=5000)
                    while not wlan.isconnected():
                        machine.idle()  # save power while waiting
                    print("WLAN: connected to " + net.ssid +
                          " with IP address:" + wlan.ifconfig()[0])
                    break
        else:
            print("WLAN: auto-connected")
elif HARDWARE == 'esp32':
    print("ESP32")
    import network
    wlan = network.WLAN(network.STA_IF)
    wlan.active(True)
    wlan.config(dhcp_hostname='hpwc')
    if not wlan.isconnected():
        print("WLAN: scanning for known network")
        nets = wlan.scan()
        for net in nets:
            print('Found network: ', net)
            ssid = net[0].decode()
            if ssid in networks:
                print('WLAN: attempting to connect to "%s"' % ssid)
                wlan.connect(ssid, networks[ssid])
                while not wlan.isconnected():
                    machine.idle()  # save power while waiting
                print("WLAN: connected to " + ssid + " with IP address:" +
                      wlan.ifconfig()[0])
                break
    else:
Example #20
0
class WifiManager:
    def __init__(self, essid=None):
        self.local_ip = AP_IP
        self.sta_if = WLAN(STA_IF)
        self.ap_if = WLAN(AP_IF)

        if essid is None:
            essid = b"ESP8266-%s" % binascii.hexlify(self.ap_if.config("mac")[-3:])

        self.essid = essid
        self.creds = Creds()

        # Turn off station and AP interface to force a reconnect
        self.sta_if.active(True)
        self.ap_if.active(False)

        self.loop = asyncio.get_event_loop()
        self.loop.create_task(self.check_wifi())

    async def start_access_point(self):
        while not self.ap_if.active():
            self.ap_if.active(True)
            await asyncio.sleep(1)

        # IP address, netmask, gateway, DNS
        self.ap_if.ifconfig(
            (self.local_ip, "255.255.255.0", self.local_ip, self.local_ip)
        )

        self.ap_if.config(essid=self.essid, authmode=AUTH_OPEN)
        print("> AP mode configured: {} ".format(self.essid.decode("utf-8")), self.ap_if.ifconfig())
            

    async def check_wifi(self):
        while True:
            self.loop.create_task(self.connect(True))

            if self.creds.load().is_valid():
                await asyncio.sleep(WAIT_FOR_CONNECT)

            if not self.sta_if.isconnected():
                self.loop.create_task(self.start_access_point())

                while not self.sta_if.isconnected():
                    await asyncio.sleep(1)

                self.ap_if.active(False)

                while self.sta_if.isconnected():
                    await asyncio.sleep(1)

    async def connect(self, autoLoop=False):
        if not self.sta_if.isconnected():
            if self.creds.load().is_valid():
                print("> Connecting to {:s}/{:s}".format(self.creds.essid, self.creds.password))

                self.sta_if.connect(self.creds.essid, self.creds.password)

                await asyncio.sleep(WAIT_FOR_CONNECT)

                if not self.sta_if.isconnected():
                    print("> Connection failed. WLAN status={:d}".format(self.sta_if.status()))

                    if autoLoop:
                        self.loop.create_task(self.connect(True))
            else:
                print("> No valid credentials file: {}".format(Creds.CRED_FILE))
Example #21
0
class Connection:
    def __init__(self):
        # Scan networks in surrounding
        self._ifc = WLAN(STA_IF)

        if not self._ifc.active(True):
            raise RuntimeError("WiFi activation failed")

        sc = self._ifc.scan()
        self.nets = []

        for n in sc:
            self.nets.append(Wifi(n[0].decode(), n[1]))

        self._ifc.active(False)

        # Start requested variant of connection
        if jumpers.hotspot:
            self._hotspot()
        else:
            self._attach()

    def _attach(self):
        # Activate WiFi interface
        self._ifc = WLAN(STA_IF)

        if not self._ifc.active(True):
            raise RuntimeError("WiFi activation failed")

        # Search first based on BSSID
        network = None

        for n in self.nets:
            for c in connection:
                if n.bssid == c.bssid:
                    network = c
                    break
            else:
                continue
            break

        # Repeat the same for SSID if BSSID was not found
        if network is None:
            for n in self.nets:
                for c in connection:
                    if n.ssid == c.ssid:
                        network = c
                        break
                else:
                    continue
                break

        # Checks if we have something and connect to WiFi
        if network is None:
            raise RuntimeError("No know WiFi found!")

        self.config = network

        self._ifc.connect(network.ssid, network.passwd, bssid=network.bssid)

        for i in range(8):
            if self._ifc.isconnected():
                log("Connected: " + str(self.ifconfig))
                self.is_hotspot = False
                return

            sleep(1)

        raise RuntimeError("Wifi connection refused")

    def _hotspot(self):
        # Create hotspot to be able to attach by FTP and configure meteostation
        self._ifc = WLAN(AP_IF)
        self._ifc.active(True)
        self._ifc.config(essid=hotspot.ssid,
                         password=hotspot.passwd,
                         authmode=3)

        while self._ifc.active() == False:
            sleep(1)

        self.is_hotspot = True
        log("Running hotspot: " + str(self.ifconfig))

    @property
    def ifconfig(self):
        return self._ifc.ifconfig()

    def http_get_json(self, url):
        log("HTTP GET: " + url)

        for retry in range(CONN_RETRY_CNT):
            try:
                return urequests.get(url).json()
                collect()
                return
            except OSError as e:
                log('ECONNRESET -> retry')
                if e.errno == ECONNRESET:
                    continue

                raise e

    def disconnect(self):
        WLAN(STA_IF).active(False)
        WLAN(AP_IF).active(False)
        self._ifc = None
Example #22
0
from network import WLAN, AP_IF, AUTH_WPA_WPA2_PSK
from webrepl import start

start()
ap_if = WLAN(AP_IF)
ap_if.active(True)
ap_if.config(essid='ESP32', authmode=AUTH_WPA_WPA2_PSK, password='******')
Example #23
0
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))
Example #24
0
def connect_to_network():
    """
    connect to a network and disable the access point
    """
    from network import WLAN, STA_IF, AP_IF
    from miscellaneous import read_json

    sta_if = WLAN(STA_IF)  # wifi station (connect to router)
    ap_if = WLAN(AP_IF)  # wifi access point (like a router)

    if read_json(
            "data/config")["network"]["networkStation"]["enabled"] is True:
        warning("Network station will be enabled")

        if sta_if.isconnected():  # check if you're already connected
            message('Already connected to network')

        while not sta_if.isconnected():
            message('Connecting to network...')

            sta_if.active(True)  # enable the station

            if read_json("data/config")["network"]["networkStation"][
                    "homeNetwork"] is True:  # check if you want to
                # connect to home wifi
                warning("Using home network")
                sta_if.connect('Hackercollective',
                               'w6HSB2S3bb042')  # let station connect to wifi
            else:  # connect to custom wifi
                warning("Using custom network config")
                ssid = read_json("data/config")["network"]["networkStation"][
                    "customSSID"]  # read custom wifi ssid
                # from json
                password = read_json("data/config")["network"][
                    "networkStation"]["customNetworkPassword"]  # read
                # custom password from json
                sta_if.connect(ssid, password)  # let station connect to wifi

            from time import time  # import time to make a timer
            start_time = time(
            ) + 120  # make timer (last value is how long the timer in ms)
            while not sta_if.isconnected():  # wait to be connected
                if time() == start_time:  # check if timer is over
                    break

        message('Network config:' + str(sta_if.ifconfig()))
        message('The ip is ' + str(sta_if.ifconfig()[0]))
    else:
        warning("Network station will be disabled")
        sta_if.active(False)  # enable network station

    if read_json("data/config")["network"]["accessPoint"][
            "enabled"] is True:  # check if you want an access point in
        # config
        warning("Access point will be enabled")
        ap_if.active(True)  # disable access point

        ap_if.config(
            essid=read_json("data/config")["network"]["accessPoint"]
            ["SSID"],  # set password and ssid of
            password=read_json("data/config")["network"]["accessPoint"]
            ["password"])  # the access point

    else:
        warning("Access point will be disabled")
        ap_if.active(False)  # enable access point
Example #25
0
def wifiAPpassword(pw=None):
  from network import WLAN, AP_IF, AUTH_WPA_WPA2_PSK
  AP = WLAN(AP_IF)
  AP.config(essid=STSSID, authmode=AUTH_WPA_WPA2_PSK, password=pw if pw else STSSIDPW)
Example #26
0
 active = wifi.active(True)
 log.info('WIFI_SSID={}'.format(config.WIFI_SSID))
 log.info('WIFI_PASS={}'.format(config.WIFI_PASS))
 connect = wifi.connect(config.WIFI_SSID,config.WIFI_PASS)
 # wait until the device is connected to the WiFi network
 MAX_ATTEMPTS = 20
 attempt_count = 0
 while not wifi.isconnected() and attempt_count < MAX_ATTEMPTS:
   attempt_count += 1
   log.info('z.')
   sleep(1)
 if attempt_count == MAX_ATTEMPTS:
   log.error('The flag pole is broken.')
 log.info('connect={}'.format(connect))
 # Get mac address
 mac = hexlify(wifi.config('mac'),':').decode()
 log.info('mac={}'.format(mac))
 # clean up this mess
 del hexlify
 del WLAN
 del AP_IF
 del STA_IF
 del ap_if
 del active
 del connect
 del MAX_ATTEMPTS
 del attempt_count
 del wifi
 collect()
 
 ##############################################################################
Example #27
0
class WiFi:
    RECONNECT_TIMEOUT = 10

    def __init__(self, config, verbose=0):
        self.verbose = verbose
        self.config = config
        self.__connecting = False
        self.connect_start = None
        self.station = WLAN(STA_IF)

    def __repr__(self):
        return '<WiFi: {}, {} at {:x}>'.format(self.station.config('essid'),
                                               self.station.ifconfig(),
                                               id(self))

    def device_id(self):
        import ubinascii
        return ubinascii.hexlify(self.station.config('mac'),
                                 ':').decode().upper()

    def connecting(self):
        return self.__connecting

    def connected(self):
        return self.station.isconnected()

    def connect(self):
        if self.__connecting:
            if self.station.isconnected():
                self.__connecting = False
                self.connect_start = None
            elif (time() - self.connect_start) > self.RECONNECT_TIMEOUT:
                # self.station.active(False)
                self.__connecting = False
                self.connect_start = time()
                if self.verbose:
                    print('-> ' 'Connect ' 'timeout')
        elif self.station.isconnected() is False:
            if self.connect_start is None or (
                    time() - self.connect_start) > self.RECONNECT_TIMEOUT:
                if self.verbose:
                    if self.connect_start is None:
                        print('-> ' 'Reconnect ' 'timer started')
                    else:
                        print('-> ' 'Reconnect ' 'timeout')
                self.connect_start = time()
            else:
                return False
            self.station.active(True)
            ssid, password = self.scan()
            if self.verbose:
                print('[{}] [{}]'.format(ssid, password))
            if ssid:
                self.station.connect(ssid, password)
                sleep(1)
                self.__connecting = True
            return True
        return False

    def disconnect(self):
        self.station.disconnect()

    def scan(self):
        ssid, password = None, None
        ap_scan = self.station.scan()
        ap_list = []
        for ap in ap_scan:
            for ssid_mask, password in self.config['wifi']:
                mask = '^{}$'.format(ssid_mask)
                if search(mask, ap[0]):
                    ap_list.append((ap[3], ap[0], password))
        ap_list.sort(reverse=True)
        if self.verbose:
            for ap in ap_list:
                print(ap)
        if len(ap_list):
            ssid, password = ap_list[0][1], ap_list[0][2]
        return ssid, password
from machine import Pin
from machine import UART
import network
from network import WLAN
from utime import sleep_ms

SERVANT_IP = "192.168.169.1"
SERVANT_PORT = 18788
REMOTE_IP = "192.168.169.2"
REMOTE_PORT = 11686

# setup access point
ACCESS_POINT = WLAN(network.AP_IF)
ACCESS_POINT.active(False)
ACCESS_POINT.config(essid="Headrush Servant",
                    authmode=4,
                    password="******",
                    hidden=True)
ACCESS_POINT.ifconfig(
    (SERVANT_IP, "255.255.255.0", "192.168.178.1", "8.8.8.8"))
ACCESS_POINT.active(True)

_STATUS_LED = Pin(23, Pin.OUT, Pin.PULL_UP)
_STATUS_LED.value(1)

# some general setup
_MIDI_TX_PIN = 18

_COMMAND_MAP = {
    b"button_rig_up": (49).to_bytes(1, "big"),
    b"button_rig_down": (55).to_bytes(1, "big"),
    b"button_scene1": (56).to_bytes(1, "big"),
import utils, usocket as socket, os
from network import WLAN, AP_IF

ap = WLAN(AP_IF)
ap.config(essid=utils.get_machine_id(), channel=11)

ap.active(True)

print('Wifi connected:', ap.ifconfig())

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind(('', 80))
s.listen(5)


def process_file(conn, addr):
    path = conn.recv(4096).decode('ascii')
    utils.mkdir(path)
    file = conn.recv(4096)
    with open(path, 'wb') as f:
        f.write(file)

    conn.close()


while 1:
    conn, addr = s.accept()
    process_file(conn, addr)
    print('got a connection from {}'.format(str(addr)))
def enable_ap_mode(essid=None, password=None):
    from network import AP_IF, AUTH_WPA_WPA2_PSK, WLAN
    from ubinascii import hexlify

    wifi_interface = WLAN(AP_IF)
        
    if not essid:
        essid = b"micropython-esp8266-%s" % hexlify(wifi_interface.config("mac")[-3:])
    if not password:
        password = b'micropybootconfig'

    wifi_interface.config(essid=essid, authmode=AUTH_WPA_WPA2_PSK, password=password)
    del hexlify