Esempio n. 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
Esempio n. 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]
Esempio n. 3
0
def connect_wlan():
    wlan = WLAN(STA_IF)
    wlan.active(True)
    wlan.connect('TPA', 'TurbenThal', 5000)
    while not wlan.isconnected():
        continue
    print("Connected to WLAN ... IP", wlan.ifconfig()[0])
def run():
    sleep = utime.sleep
    dhtPin = Pin(2, Pin.IN, Pin.PULL_UP)
    sensor = DHT11(dhtPin)
    measure = sensor.measure
    temp = sensor.temperature
    hum = sensor.humidity
    httpget = urequests.get

    wifi = WLAN(STA_IF)

    if not wifi.active():
        wifi.active(True)

    while True:
        if not connect(wifi):
            return

        try:
            measure()
            t = temp() * 1.8 + 32
            h = hum()

            print(t, h)
            httpget(
                THINGSPEAK_REQUEST.format(temperature=t,
                                          humidity=h,
                                          location='livingroom',
                                          api_key=secrets.THINKSPEAK_API_KEY))
        except:
            print('Failed to read sensor')

        sleep(PUBLISH_PERIOD_IN_SEC)
Esempio n. 5
0
    def __init__(self, connect_retry=10):

        ap = WLAN(AP_IF)
        ap.active(1)
        sta = WLAN(STA_IF)
        sta.active(1)
        self.s = socket.socket()
        self.s.bind(("0.0.0.0", 80))
        self.s.listen(1)
        
        self.ssid, self.password = "", ""
        self.connect_retry = connect_retry
        self.lock_status = 0
        try:
            wificonfig = open("wificonfig", "r")
            self.ssid, self.password = config.read().split("\n")[:2]
            wificonfig.close()
        except Exception:
            pass

        if not self.ssid:
            print("config does not exist, initializing config")
            self.first_time_raw()
        else:
            print("found existing config, connecting to wifi")
            success = self.connect_to_wifi()

        self.s.settimeout(2)

        self.IV = bytes()
        self.key = bytes()
        with open("aes", "rb") as f:
            self.IV = f.read(16)
            self.key = f.read()
        self.IV = b'[S\x83\x11v\x9cY;\xbcH\xe3\t\xd6\xf9\xbf\x9f'
        self.key = b'b\xe7\x02$D\x18\x0c\xd8I5:\x1d%\xeft\xdb'
        self.cipher = ucryptolib.aes(key, 2, IV)

        self.last_sender_addr = "0.0.0.0"
        with open("lastsender", "r") as f:
            self.last_sender_addr = f.read()
        
        topic = "mcer4294967296/data"
        broker = "mqtt.eclipse.org"
        print("connecting to MQTT")
        mqtt = MQTTClient("umqtt_client", broker)
        mqtt.connect()
        print("connected to MQTT")
        mqtt.subscribe(topic)
        mqtt.set_callback(self.on_receive_mqtt)

        self.override = False
        self.at_home = False
        self.dist_thresh = 0.5 # kilometer
        self.timestamp_left = time.time()
        self.time_thresh = 60 # seconds
        self.poll_interval = 5 # seconds
        self.key_update_thresh = 86400 # a day
        self.last_key_update = time.time()
Esempio n. 6
0
def wifiAsClient():
    global wifi
    config = getConfig('config.wifi.json')
    client_if = WLAN(STA_IF)
    client_if.active(True)
    client_if.connect(config['ssid'], config['passphrase'])
    log.info(client_if.ifconfig())
    wifi = client_if
Esempio n. 7
0
def do_connect(SSID='LANTERN', PASS='******'):
    sta_if = WLAN(mode=WLAN.STA)
    if not sta_if.isconnected():
        print('connecting to network...')
        sta_if.active(True)
        sta_if.connect(SSID, PASS)
        while not sta_if.isconnected():
            pass
    print('network config:', sta_if.ifconfig())
Esempio n. 8
0
def connect():
	with open('wifi.json', 'rt') as f:
		config = load(f)
	wlan = WLAN(STA_IF)
	wlan.active(True)
	wlan.ifconfig((config['static_ip'], config['netmask'], config['gateway'], config['gateway']))  # add static IP
	wlan.connect(config['ssid'], config['password'])
	while not wlan.isconnected():
		pass
Esempio n. 9
0
def connect_network():
    sta_if = WLAN(STA_IF)
    if not sta_if.isconnected():
        print('connecting to network...')
        sta_if.active(True)
        sta_if.connect(SSID, WPA_PASSWORD)
        while not sta_if.isconnected():
            pass
    print('connected to network', sta_if.ifconfig())
def do_connect():
    sta_if = WLAN(STA_IF)
    if not sta_if.isconnected():
        print('connecting to network...')
        sta_if.active(True)
        sta_if.connect(essid, password)
        while not sta_if.isconnected():
            pass
    print('network config:', sta_if.ifconfig())
Esempio n. 11
0
def do_connect():
    from network import WLAN
    sta_if = WLAN(network.STA_IF)
    if not sta_if.isconnected():
        print('connecting to network...')
        sta_if.active(True)
        sta_if.connect(config.WIFISSID, config.WIFIPASS)
        while not sta_if.isconnected():
            pass
    print('network config:', sta_if.ifconfig())
Esempio n. 12
0
def connect_to_ap():
    station = WLAN(STA_IF)
    if not station.active():
        station.active(True)
        if not station.isconnected():
            LOGGER.debug('Connecting....')
            station.connect(SSID, PASSWORD)
            while not station.isconnected():
                sleep(1)
    LOGGER.debug('Connected {}'.format(station.ifconfig()))
Esempio n. 13
0
def do_connect():
    from network import WLAN
    sta_if = WLAN(network.STA_IF)
    if not sta_if.isconnected():
        print('connecting to network...')
        sta_if.active(True)
        sta_if.connect(WIFISSID, WIFIPASS)
        while not sta_if.isconnected():
            pass
    print('network config:', sta_if.ifconfig())
Esempio n. 14
0
class WiFi():
    def __init__(self):
        self.timeout = 60
        self.net = WLAN(STA_IF)
        self._ssid = self._password = None
        self.token = None

    def _get_network(self):
        raise NotImplementedError

    def get_network_token(self):
        from os import urandom
        r = str(int.from_bytes(urandom(2), 'little'))
        t = '0' * (4 - len(r)) + r
        del urandom, r
        collect()
        return t[:4]

    def Context(self, timeout):
        self.timeout = timeout
        self.token = self.get_network_token()
        if NET_SSID:
            self._ssid, self._password = NET_SSID.split('|')
        else:
            self._get_network()
        return WiFiContext(self)

    @property
    def connected(self):
        isc = self.net.isconnected()
        print('Is connected? {}'.format(isc))
        return isc

    def enable(self):
        self.net.active(True)

    def connect(self, ssid=None, password=None, timeout=WIFI_TIMEOUT):
        ssid = self._ssid or ssid
        password = self._password or password
        self.net.ifconfig(((NET_IP, NET_NETMASK, NET_GATEWAY, NET_DNS)))
        self.net.connect(ssid, password)

    def disable(self):
        from gc import collect
        from network import AP_IF
        self.net.active(False)
        WLAN(AP_IF).active(False) # Always ensure AP is disabled
        del AP_IF
        collect()

    def send_data(self, topic, data):
        pass

    def get_data(self, topic):
        pass
Esempio n. 15
0
def wifi_connect():
 while True:
  try:
   sta_if = WLAN(STA_IF)
   sta_if.active(True)
   sta_if.disconnect()
   sta_if.connect(*WIFI_SSID_PASSWORD)
   break
   time.sleep(0.5)
  except Exception as e:
   print("Error in Wlan connect: [Exception] %s: %s" % (type(e).__name__, e))
Esempio n. 16
0
def connect_wifi():
    print('\nConnecting to %s...' % SSID)
    STA = WLAN(STA_IF)
    STA.active(True)
    STA.connect(SSID, pwd)
    status_led = Pin(2, Pin.OUT)
    while not STA.isconnected():
        status = 0 if 'status' not in globals() or status else 1
        status_led.value(status)
        sleep(0.1)
    status_led.on()  # off
    print('Ready!  IP: %s' % STA.ifconfig()[0])
Esempio n. 17
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())
Esempio n. 18
0
def wifi_connect():
    led.off()
    wlan = WLAN(STA_IF)
    if not wlan.isconnected():
        wlan.active(True)
        wlan.connect(ssid, ssidpassword)

        while not wlan.isconnected():
            idle()
            pass
    # print('Network secrets:', sta_if.ifconfig())
    led.on()
Esempio n. 19
0
    def __init__(self, ssid, passphrase):

        wlan = WLAN(STA_IF)

        wlan.active(True)

        wlan.connect(ssid, passphrase)

        while not wlan.isconnected():
            machine.idle()

        print('Wifi connected:', wlan.ifconfig())
Esempio n. 20
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
Esempio n. 21
0
def set_wifi(essid, pwd, timeout=60):
    console_write('[NW: STA] SET WIFI: {}'.format(essid))
    essid_found = False

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

    # Set STA and Connect
    sta_if = WLAN(STA_IF)
    sta_if.active(True)
    if not sta_if.isconnected():
        console_write('\t| [NW: STA] CONNECT TO NETWORK {}'.format(essid))
        # Scan wifi network - retry workaround
        for _ in range(0, 2):
            if essid in (wifispot[0].decode('utf-8')
                         for wifispot in sta_if.scan()):
                essid_found = True
                console_write(
                    '\t| - [NW: STA] ESSID WAS FOUND {}'.format(essid_found))
                break
            sleep(1)
        # Connect to the located wifi network
        if essid_found:
            # connect to network
            sta_if.connect(essid, pwd)
            # wait for connection, with timeout set
            while not sta_if.isconnected() and timeout > 0:
                console_write("\t| [NW: STA] Waiting for connection... " +
                              str(timeout) + "/60")
                timeout -= 1
                sleep(0.5)
            # Set static IP - here because some data comes from connection.
            if sta_if.isconnected() and __set_wifi_dev_static_ip(sta_if):
                sta_if.disconnect()
                del sta_if
                return set_wifi(essid, pwd)
        else:
            console_write(
                "\t| [NW: STA] Wifi network was NOT found: {}".format(essid))
            return False
        console_write("\t|\t| [NW: STA] network config: " +
                      str(sta_if.ifconfig()))
        console_write("\t|\t| [NW: STA] CONNECTED: " +
                      str(sta_if.isconnected()))
    else:
        console_write("\t| [NW: STA] ALREADY CONNECTED TO {}".format(essid))
    cfgput("devip", str(sta_if.ifconfig()[0]))
    set_uid_macaddr_hex(sta_if)
    return sta_if.isconnected()
Esempio n. 22
0
def wifi2connect(ssid=None, password=None):
  from network import WLAN, STA_IF
  STA = WLAN(STA_IF)
  STA.active(True)
  STA.disconnect()
  wfScan=STA.scan()
  nets=[]
  [nets.append(nw[0].decode("utf-8")) for nw in wfScan]
  if ssid in nets:
    STA.connect(ssid if ssid else APSSID, password if password else APSSIDPW)
  else:
    print("\n".join(nets), end="\n"+"="*80+"\n")
    STA.active(False)
Esempio n. 23
0
    def connect_to_wifi(self, config):
        wlan = WLAN(0)
        wlan.active(True)
        time.sleep(1.0)
        if not wlan.isconnected():
            logger.log('connecting to network...')
            wlan.connect(config['SSID'], config['PASSWORD'])
            while not wlan.isconnected():
                time.sleep(1.0)
                pass

        logger.log(wlan.ifconfig())
        time.sleep(1.0)
Esempio n. 24
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()))
Esempio n. 25
0
class WiFi:
    def __init__(self, ssid: str, pw: str):
        self.station = WLAN(STA_IF)
        self.station.active(True)
        self.ssid = ssid
        self.pw = pw
        self.connection = None

    def renew_connection(self):
        if self.connection:
            self.connection.close()

        # UDP connection
        self.connection = socket(AF_INET, SOCK_DGRAM)
Esempio n. 26
0
def main():
    wlan = WLAN(STA_IF)
    wlan.active(True)
    nets = wlan.scan()
    for net in nets:
        ssid = net[0]
        if ssid == b'Jxxxxxxxxxe':
            wlan.connect(ssid, 'xxxxxxxx')
            while not wlan.isconnected():
                idle()  # save power while waiting
            print('WLAN connection succeeded!')
            ftp.start(user='******', password='******')
            telnet.start(user='******', password='******')
            break
Esempio n. 27
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
Esempio n. 28
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()
Esempio n. 29
0
def connect_WiFi(ssid='NachoWifi', password='******'):
    wlan = WLAN(STA_IF)
    wlan.active(True)
    if not wlan.isconnected():
        print('connecting to network...')
        wlan.connect(ssid, password)
        while not wlan.isconnected():
            pass
    print('network config:', wlan.ifconfig())
    mac = hexlify(WLAN().config('mac'), ':').decode()
    print('Oh Yes! Get Connected')
    print('Connected to NachoWifi')
    print('MAC Address: ', mac)
    print('IP Address: ', wlan.ifconfig()[0])
    return wlan
Esempio n. 30
0
def connect(ssid, auth, timeout=16000):
    from network import WLAN, STA_IF, AP_IF
    global uplink
    uplink = WLAN(STA_IF)
    uplink.active(True)
    uplink.connect(ssid, auth)
    started = ticks_ms()
    while True:
        if uplink.isconnected():
            return True
        else:
            if ticks_diff(ticks_ms(), started) < timeout:
                sleep_ms(100)
                continue
            else:
                return False
Esempio n. 31
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)
Esempio n. 32
0
def connect_to_wifi(ssid, password, retries=10):
    """
    Connect to a WIFI network
    """
    try:
        from network import STA_IF
    except ImportError:
        return connect_to_wifi_wipy(ssid, password, retries=retries)

    wlan = WLAN(STA_IF)
    wlan.active(True)
    wlan.connect(ssid, password)
    retry_count = 0
    while not wlan.isconnected():
        sleep(1)
        retry_count += 1
        if retry_count > retries:
            return False
    return True
Esempio n. 33
0
def connect_to_ap(essids, tries=3):
    from network import WLAN, STA_IF
    from time import sleep
    wlan = WLAN(STA_IF)
    wlan.active(True)
    ## Select only known networks
    ap_list = list(filter(lambda ap: ap[0].decode('UTF-8') in 
            essids.keys(), wlan.scan()))
    ## sort by signal strength
    ap_list.sort(key=lambda ap: ap[3], reverse=True)
    for ap in ap_list:
        essid = ap[0].decode('UTF-8')
        wlan.connect(essid, essids[essid])
        for i in range(5):
            ## this is somewhat crude, we actually have a
            ## wlan.status() we can inspect. oh well...
            if wlan.isconnected():
                return True
            sleep(1)
    return False
Esempio n. 34
0
File: main.py Progetto: psy0rz/stuff
# bare minimum to initalize webrepl and start meowton

# disable debug
# import esp
# esp.osdebug(1)

### network stuff
import config
import network
from network import WLAN
wlan = WLAN(network.STA_IF) # get current object, without changing the mode
wlan.active(True)
# wlan.ifconfig(config.network)
wlan.connect(config.wifi_essid, config.wifi_password)

import webrepl
webrepl.start()

# import utelnetserver
# utelnetserver.start()

import temp