Esempio n. 1
0
def connect(ssid, key):
    """ Scans for and connects to the specified wifi network using key as password """
    wlan = WLAN(mode=WLAN.STA)
    nets = wlan.scan()
    for net in nets:
        if net.ssid == ssid:
            wlan.connect(net.ssid, auth=(net.sec, key), timeout=5000)
            while not wlan.isconnected():
                machine.idle() # save power while waiting
            break
Esempio n. 2
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. 3
0
def connectLocalBox(configFilePath):
    f = open(configFilePath, 'r')
    config=ujson.load(f)
    f.close()

    wlan = WLAN(mode=WLAN.STA)
    wlan.ifconfig(config=(config["ip"], config["mask"],config["gateway"], config["dns"]))
    wlan.scan()
    wlan.connect(config["ssid"], auth=(WLAN.WPA2, config["password"]))
    while not wlan.isconnected():
        pass
    return wlan;
Esempio n. 4
0
File: init.py Progetto: aidium/WiPy
def wlan_connect():
    wifi = WLAN(mode=WLAN.STA)

    wifi.ifconfig(config=(__myip, __netmask, __gateway, __dns))
    wifi.scan()     # scan for available networks
    wifi.connect(ssid=__ssid, auth=(WLAN.WPA2, __nwpass))
    while not wifi.isconnected():
        pass

    syslog('WiPy is up and running')

    wifi.irq(trigger=WLAN.ANY_EVENT, wake=machine.SLEEP)

    machine.sleep()
def connect_to_wifi_wipy(ssid, password, retries=10):
    """
    Connect to a WIFI network
    """
    wlan = WLAN(mode=WLAN.STA)
    print("Connecting to wifi network '%s'" % ssid)
    wlan.connect(ssid=ssid, auth=(WLAN.WPA2, password))
    retry_count = 0
    while not wlan.isconnected():
        sleep(1)
        retry_count += 1
        if retry_count > retries:
            return False
    print('Connected', wlan.ifconfig())
    return True
Esempio n. 6
0
def connect_wifi(cfg=None):
    if not cfg:
        from config import Config
        cfg = Config.load(debug=True)

    from network import WLAN
    import machine

    print('Starting WLAN, attempting to connect to ' + cfg.wifi_ssid)
    wlan = WLAN(0, WLAN.STA)
    wlan.ifconfig(config='dhcp')
    wlan.connect(ssid=cfg.wifi_ssid, auth=(WLAN.WPA2, cfg.wifi_key))
    while not wlan.isconnected():
        machine.idle()
    print('Connected')
Esempio n. 7
0
class Theta:

    def __init__(self):
        self.wlan = WLAN(WLAN.STA)
        pass

    def log(self, msg):
        print(msg)

    def findWifi(self):
        wlans = self.wlan.scan()
        # TODO: Return all visible Thetas
        for w in wlans:
            if w.ssid.startswith('THETA'):
                self.log('Found Theta WiFi: %s' % w.ssid)
                # THETAXL12345678     = Theta (original model) - PTP/IP
                # THETAXN12345678     = Theta m15 - PTP/IP
                # THETAXS12345678.OSC = Theta S   - OSC
                return w.ssid
        return False

    def connectWifi(self, ssid):
        password = ssid[-8:]
        return self.wlan.connect(ssid, auth=(WLAN.WPA, password))

    # convenience - might get removed
    def connect(self):
        wifi = self.findWifi()
        if not wifi:
            return False
        self.connectWifi(wifi)
        self.ptpip = ptpip.PTPIP('192.168.1.1')
        return self.ptpip

    def initPTP(self):
        answer = self.ptpip.initCommand('1234567812345678', 'WiPy')
        if not answer:
            print("Init failed!")
            return False
        (session_id, guid, name) = answer
        pass2 = self.ptpip.initEvent(session_id)
        if not pass2:
            print("Init stage 2 failed!")
            return False
        return (session_id, guid, name)

    def openSession(self):
        answer = self.ptpip.createCommand(0x1002, [])
        return answer

    def closeSession(self):
        answer = self.ptpip.createCommand(0x1003, [])
        return answer

    def shoot(self):
        answer = self.ptpip.createCommand(0x100e, [0x0, 0x0])
        return answer

    def getPTPIP(self):
        return self.ptpip
Esempio n. 8
0
def setup_wifi():
    wlan = WLAN(mode=WLAN.STA)  # Setup as station for use of existing network

    nets = wlan.scan()

    print("Scanning for networks...")
    for net in nets:
        if (net.ssid == WIFI_SSID):
            print("\nThe network", WIFI_SSID, "was found!")
            print("Establishing connection to network...")

            wlan.connect(net.ssid, auth=(net.sec, WIFI_PASSWORD), timeout=5000)

            while not wlan.isconnected():
                machine.idle()  # Save power

            print("Successful network connection!\n")
            break
Esempio n. 9
0
    def connect_to_wifi(self):
        print("connecting to wifi at " + self.ssid)
        sta = WLAN(STA_IF)
        if not sta.active():
            sta.active(1)
        sta.connect(self.ssid, self.password)

        count = 0
        while not sta.isconnected() and count < self.connect_retry:
            time.sleep(1)
            count += 1

        if not sta.isconnected():
            sta.active(0)
            print("failed to connect to wifi, deactivating STA interface")
        else:
            print("connected to wifi")
        return sta.isconnected()
Esempio n. 10
0
def do_connect(ssis, password, tries=5):
    from network import WLAN, STA_IF
    from time import sleep
    sta_if = WLAN(STA_IF)

    if not sta_if.isconnected():
        sta_if.active(True)
        sta_if.connect(ssid, password)

        for i in range(tries):
            print('Connecting to network (try {})...'.format(i + 1))
            if sta_if.isconnected():
                print('network config:', sta_if.ifconfig())
                break

            sleep(1)
        else:
            print("Failed to connect in {} seconds.".format(tries))
Esempio n. 11
0
def wifiConnect():
    beaconId = ""
    wlan = WLAN(mode=WLAN.STA)

    nets = wlan.scan()
    print(nets)
    for net in nets:
        if net.ssid == 'VMCAD4B64':
            print('Network found!')
            wlan.connect(net.ssid,
                         auth=(net.sec, 'Xdcr7zrm2Jsx'),
                         timeout=5000)
            while not wlan.isconnected():
                machine.idle()  # save power while waiting
            print('WLAN connection succeeded!')
            break
        else:
            print("Network not found")
Esempio n. 12
0
    def run(self):
        print("Starting connect...")
        sta_if = WLAN(STA_IF)

        if not sta_if.isconnected():
            print('connecting to network...')
            sta_if.active(True)
            sta_if.connect(NETWORK_CONFIG['ssid'], NETWORK_CONFIG['password'])

            while not sta_if.isconnected():
                pass

            print("Connected!")
            self.state = 1
        else:
            self.state = 1

        return self.state
Esempio n. 13
0
def wifiConnect():
    wlan = WLAN(mode=WLAN.STA)
    pycom.heartbeat(False)

    wlan.connect(ssid="telenet-4D87F74", auth=(WLAN.WPA2, "x2UcakjTsryz"))

    while not wlan.isconnected():
        time.sleep(1)
        print("WiFi not connected")
        pycom.rgbled(0xFF0000)
    print("WiFi connected succesfully")
    pycom.rgbled(0x00FF00)
    print("test")
    print(wlan.ifconfig())
    print("hond")
    while not wlan.isconnected():
        print("WiFi not connected2.0")
        pycom.rgbled(0xFF0000)
Esempio n. 14
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. 15
0
class Board(object):
    def __init__(self):

        self.led = {
            'r': LED(1),
            'g': LED(2),
            'b': LED(3),
        }

        self.wlan = WLAN()

    @staticmethod
    def get_adc_of_pin(pin_name):
        pin = Pin(pin_name, Pin.ANALOG)
        return ADC(pin)

    @staticmethod
    def get_timer(frequency):
        return Timer(8, freq=frequency)

    @staticmethod
    def get_array(length, init_value=0):
        return array('H', (init_value for _ in range(length)))

    def connect_wifi(self, ssid, key):
        # establish WIFI
        logger.info('Connect to {}'.format(ssid))
        self.wlan.active(1)
        self.wlan.connect(ssid, key)

    def is_connected(self):
        return self.wlan.isconnected()

    def turn_off_red_led(self):
        self.led['r'].off()

    def turn_on_red_led(self):
        self.led['r'].on()

    def turn_on_green_led(self):
        self.led['g'].on()

    def turn_off_green_led(self):
        self.led['g'].off()
Esempio n. 16
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. 17
0
 def __init__(self, netcfg, interface=WLAN):
     self.data_func = lambda _: None
     self.new_data = False
     if interface is WLAN:
         wlan = WLAN(mode=WLAN.STA)
         wlan.connect(ssid=netcfg[0], auth=netcfg[1])
         while not wlan.isconnected():
             machine.idle()
         self.ip, _, self.gateway, self.dns = wlan.ifconfig()
         self.__sock_data__ = (socket.AF_INET, socket.SOCK_STREAM,
                               socket.IPPROTO_TCP)
     elif interface is LoRa:
         self.ip, self.gateway, self.dns = '', '', ''
         # Do setup for LoRa Mesh
         self.lora = LoRa(mode=LoRa.LORA, region=LoRa.US915)
         self.__sock_data__ = (socket.AF_LORA, socket.SOCK_RAW)
     self.new_socket()
     self.__register__()
     self.sock.bind(('', 1234))
Esempio n. 18
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. 19
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. 20
0
def connect_to_network():
    sta_if = WLAN(STA_IF)
    sta_if.active(True)

    for essid, password in WIFI_CONNECTIONS:
        sta_if.connect(essid, password)

        current_try = 0
        while current_try < NETWORK_RETRIES:
            sleep_delay(2)

            if sta_if.isconnected():
                return sta_if

            current_try += 1

    if not sta_if.isconnected():
        raise FailedToConnectToNetworkException(
            'Unable to connect to any available network')
Esempio n. 21
0
def wifi_connect():
    """
    Connect to the WiFi network based on the configuration. Fails silently if there is no configuration.
    """
    network_config = conf.known_nets
    connected = False
    if not network_config:
        print("wifi - There is not Network Configuration")
        return connected
    try:
        wlan = WLAN(mode=WLAN.STA)

        print("Scanning wifi nets")
        available_nets = wlan.scan()
        nets = frozenset([e.ssid for e in available_nets])

        if list(network_config.keys())[0] in nets:
            sec = [
                e.sec for e in available_nets
                if e.ssid == list(network_config.keys())[0]
            ][0]
            wlan.connect(list(network_config.keys())[0],
                         (sec, list(network_config.values())[0]['pwd']),
                         timeout=10000)
            while not wlan.isconnected():
                machine.idle()
            print("Connected to {} with IP address: {}".format(
                wlan.ssid(),
                wlan.ifconfig()[0]))
            connected = True
        else:
            print("Could not find network: {}".format(
                list(network_config.keys())[0]))

    except Exception as e:
        print(
            "Failed to connect to any known network. \nnet_to_use: {}\nError: {}"
            .format(list(network_config.keys())[0], e))

    finally:
        gc.collect()
        return connected
Esempio n. 22
0
class WIFI(Connection):
    def __init__(self, networks: dict):
        from network import WLAN
        self.wlan = WLAN(mode=WLAN.STA)
        self.networks = networks

    def connect(self):
        if self.wlan.isconnected():
            return

        for _ in range(4):
            nets = self.wlan.scan()
            print("\tsearching for wifi networks...")
            for net in nets:
                if net.ssid in self.networks:
                    ssid = net.ssid
                    password = self.networks[ssid]
                    print('\twifi network ' + ssid + ' found, connecting ...')
                    self.wlan.connect(ssid,
                                      auth=(net.sec, password),
                                      timeout=5000)
                    while not self.wlan.isconnected():
                        machine.idle()  # save power while waiting
                    print('\twifi network connected')
                    print('\tIP address: {}'.format(self.wlan.ifconfig()))
                    print('\tMAC address: {}\n'.format(
                        hexlify(machine.unique_id(), ':').decode().upper()))
                    return
            print("!! no usable networks found, trying again in 30s")
            print("!! available networks:")
            print("!! " + repr([net.ssid for net in nets]))
            machine.idle()
            time.sleep(30)

        raise OSError("!! unable to connect to WIFI network.")

    def isconnected(self) -> bool:
        return self.wlan.isconnected()

    def disconnect(self):
        if self.wlan.isconnected():
            self.wlan.disconnect()
Esempio n. 23
0
def WLAN_Connect(the_ssid):
    from network import WLAN
    import machine
    from time import sleep
    ssid_found = 0
    ssid_connected = 0
    print('Attempting to connect to ' + the_ssid + '....')
    wlan = WLAN(mode=WLAN.STA)
    nets = wlan.scan()
    #print("SSIDs found = "+nets)               # for debugging
    for net in nets:
        #print("Trying ",+net)                  # for debugging
        if net.ssid == the_ssid:
            ssid_found = 1
            retries = 0
            print('Network found!')
            wlan.connect(net.ssid,
                         auth=(WLAN.WPA2, 'something_tricky!'),
                         timeout=1000)
            while not wlan.isconnected():
                machine.idle()  # save power while waiting
                #print('WLAN connection not connected yet..')   # for debugging
                retries += 1
                if retries >= 20: break
            ssid_connected = wlan.isconnected()
    if ssid_connected == 1:
        print('WLAN connection succeeded. Getting WLAN information...')
        #print("Connected to "+net_to_use+" with IP address:" + wl.ifconfig()[0])
        ip_addr = wlan.ifconfig()[0]
        retries = 0
        while (ip_addr == '0.0.0.0'):
            machine.idle()  # save power while waiting
            ip_addr = wlan.ifconfig()[0]
            retries += 1
            if retries >= 20: break
        #print(wlan.ifconfig())                 # for debugging
        if ip_addr != '0.0.0.0':
            print('IP Address = ' + ip_addr)
        else:
            print('Failed to get IP Address!')
    else:
        print('WLAN connection FAILED!')
Esempio n. 24
0
def connect_wifi(network, password, oled):
    wlan = WLAN()
    wlan.deinit()
    wlan.init(mode=WLAN.STA)
    wlan.ifconfig(config=('dhcp'))

    wlan.scan()  # scan for available networks
    wlan.connect(ssid=network, auth=(WLAN.WPA2, password))

    for _ in range(15):
        if wlan.isconnected():
            print("Joining Success")
            # Boot Text with version
            oled.fill(0)
            oled.text("Connected to:", 0, 0)
            oled.text(network, 0, 15)
            oled.text("IP Address:", 0, 40)
            oled.text(wlan.ifconfig()[0], 0, 55)
            oled.show()
            utime.sleep_ms(1000)
            return
        else:
            # Boot Text with version
            oled.fill(0)
            oled.text("Connecting to:", 0, 0)
            oled.text(network, 0, 15)
            oled.show()
            utime.sleep_ms(1000)

    # WiFi Creds probably broken
    print("Can't Join Clearing Credentials")
    kv.set("AP_PWD", False)
    kv.set("AP_SSID", False)

    oled.fill(0)
    oled.text("Failed to", 0, 0)
    oled.text("connect to:", 0, 15)
    oled.text(network, 0, 30)
    oled.text("Rebooting", 0, 55)
    oled.show()
    utime.sleep_ms(3000)
    machine.reset()
Esempio n. 25
0
def WIFI():
    global wlan
    print("Attempting to connect to WiFi...")
    pycom.rgbled(0xFF0000)  # Red
    wlan = WLAN(mode=WLAN.STA)
    if CONFIG.get('wifiExt') == True:
        Pin('P12', mode=Pin.OUT)(True)
        wlan.antenna(WLAN.EXT_ANT)
        print("Using Ext for WiFi")
    wlan.connect(CONFIG.get('ssid'),
                 auth=(WLAN.WPA2, CONFIG.get('wifiPass')),
                 timeout=5000)
    while not wlan.isconnected():
        machine.idle()
    print("WiFi Connected")
    global ip
    ip = wlan.ifconfig()
    ip = ip[0]
    print("IP is: ", ip)
    led_flash('green')  #Flashes THE LED Green
Esempio n. 26
0
def wlan():
    x = True
    y = True
    wlan = WLAN(mode=WLAN.STA)
    print("Esperando conexion Inalambrica...")
    while x:
        nets = wlan.scan()
        for net in nets:
            if net.ssid == 'broker':
                x = False
                print('Red encontrada - A1')
                wlan.connect(net.ssid,
                             auth=(net.sec, 'broker001'),
                             timeout=5000)
                while not wlan.isconnected():
                    machine.idle()  # save power while waiting
                    break
                print('WLAN conexion exitosa!!!')
                break
        time.sleep(5)
Esempio n. 27
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. 28
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. 29
0
def connect():
    ssid = "" # el nombre de tu red Wi-Fi
    password = "" # la contraseña de tu red Wi-Fi

    wlan = WLAN(mode=WLAN.STA)


    if wlan.isconnected() == True:
        print("Already connected")
        return

    #wlan.active(True)
    wlan.connect(ssid, auth=(WLAN.WPA2, password), timeout=5000)

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

    print("Connection successful")
    ip = wlan.ifconfig()
    return ip[0]
Esempio n. 30
0
def wlan():
    """Connect in STA mode, fallback to AP"""
    try:
        import wlanconfig
    except ImportError:
        print("WLAN: no wlanconfig.py")
        wlanconfig = None
        wlan = WLAN(mode=WLAN.AP)
    except Exception as e:
        print("WLAN: error in wlanconfig.py: {}".format(e))
        wlanconfig = None
        wlan = WLAN(mode=WLAN.AP)
    else:
        try:
            # configure the WLAN subsystem in station mode (the default is AP)
            wlan = WLAN(mode=WLAN.STA)
            print("WLAN: connecting to network (AP)...")
            wlan.connect(wlanconfig.ssid, auth=(WLAN.WPA2, wlanconfig.password), timeout=5000)
            print("WLAN: waiting for IP...")
            for tries in range(50):
                if wlan.isconnected():
                    print(
                        """\
WLAN: connected!
      WiPy IP: {}
      NETMASK: {}
      GATEWAY: {}
      DNS:     {}""".format(
                            *wlan.ifconfig()
                        )
                    )
                    break
                time.sleep_ms(100)
        except OSError:
            print("WLAN: found no router, going into AP mode instead")
            wlanconfig = None
        except Exception as e:
            print("WLAN: error: {}".format(e))
            wlanconfig = None
    if wlanconfig is None:
        wlan.init(mode=WLAN.AP, ssid="wipy-wlan", auth=(WLAN.WPA2, "www.wipy.io"), channel=7, antenna=WLAN.INT_ANT)
Esempio n. 31
0
    def __init__(self):

        self.ID = str(ubinascii.hexlify(machine.unique_id()))[2:-1]
        print("My ssid:")
        print(self.ID);
        '''
        self.wlan = WLAN(mode=WLAN.AP, ssid=self.ID, auth=(WLAN.WPA2, 'Own password'), channel=11, antenna=WLAN.INT_ANT)
        self.wlan.ifconfig(id=1, config=('192.168.1.1', '255.255.255.0', '192.168.1.1', '8.8.8.8'))
        print("done configuring");
        '''
        wlan = WLAN()
        wlan.init(mode=WLAN.STA)
        nets = wlan.scan()
        for net in nets:
            if net.ssid == 'Minecraft':
                print('Network found!')
                wlan.connect(net.ssid, auth=(net.sec, 'GudmundsV4genIsTheBest'), timeout=5000)
                while not wlan.isconnected():
                    machine.idle() # save power while waiting
                    print('WLAN connection succeeded!')
                    break
Esempio n. 32
0
class LocalWifi:
    """
    Create a local WiFi connection.
    """
    ssid = ''
    auth_mode = WLAN.WPA2
    auth_password = ''
    wlan = None

    def __init__(self, ssid, ssid_password):
        self.ssid = ssid
        self.auth_password = ssid_password
        self.wlan = WLAN(mode=WLAN.STA)

    def connect(self):
        self.wlan.scan()
        self.wlan.connect(ssid=self.ssid, auth=(self.auth_mode, self.auth_password))

        while not self.wlan.isconnected():
            print('.', end="")
        print("\nConnected to:\n", self.wlan.ifconfig())
def connect(wifi):
    wifi = WLAN(STA_IF)

    if wifi.isconnected():
        return True

    sleep = utime.sleep

    try:
        wifi.connect(secrets.wifi_network, secrets.wifi_password)
        sleep = utime.sleep

        while not wifi.isconnected():
            print('.')
            sleep(.5)

        print('Connected')
        return True
    except:
        print('Failed to connect to WiFi')
        return False
Esempio n. 34
0
    async def Connect(self, aESSID: str, aPassw: str, aAddr: tuple = None):
        Log.Print(1, 'i', 'Connect() %s, %s, %s' % (aESSID, aPassw, aAddr))

        # Improve connection integrity at cost of power consumption
        if (platform == 'esp8266'):
            from esp import sleep_type
            sleep_type(0)

        R = WLAN(STA_IF)
        R.active(False)
        await sleep(1)
        R.active(True)

        if (aAddr):
            R.ifconfig(aAddr)

        R.connect(aESSID, aPassw)
        await self._WaitForReady(R.isconnected)

        Log.Print(1, 'i', 'Net', R.ifconfig())
        return R
Esempio n. 35
0
def first_time_html():
    print("setting up socket")
    ap = WLAN(AP_IF)
    ap.active(1)
    sta = WLAN(STA_IF)
    sta.active(1)

    s = socket.socket()
    s.bind(("0.0.0.0", 80))
    s.listen(1)
    print("setting up socket done")

    # request form: {wifi ssid, "::", wifi password}
    while True:
        conn, addr = s.accept()
        print("got connection, from", addr)
        content = conn.recv(128)
        header, payload = read_payload(conn)
        if header[0].startswith("GET"):
            conn.send('HTTP/1.0 200 OK\r\nContent-type: text/html\r\n\r\n')
            conn.send(init_html)
            conn.close()
        elif header[0].startswith("POST"):
            ssid, password = payload[0].split("::")[:2]
            sta.connect(ssid, password)
            retries = 0
            while not sta.isconnected() and retries < 10:
                time.sleep(1)
                retries += 1
            conn.send('HTTP/1.0 200 OK\r\nContent-type: text/html\r\n\r\n')
            if not sta.isconnected():
                conn.send(failed_connect_to_wifi_html.format(ssid))
                conn.close()
                continue
            else:
                conn.send(connected_to_wifi_html.format(ssid, sta.ifconfig()[0]))
                conn.close()
                with open("wificonfig", "w") as f:
                    f.write(ssid+"\n"+password)
                break
Esempio n. 36
0
def wlan_connect(wlan=None):
    try:
        #wlan.connect(ssid='WILOC_AIRE', auth=(WLAN.WPA2, 'WiL.10.TeCH'))
        if wlan is None:
            wlan = WLAN(mode=WLAN.STA)

        wlan.connect(ssid=globalVars.wifi_ssid,
                     auth=(WLAN.WPA2, globalVars.wifi_psw))
        retries = 20
        while not wlan.isconnected():
            tools.debug("Connecting to Wifi... - Try: " + str(retries), "vv")
            utime.sleep(3)
            if retries == 0:
                tools.debug(
                    "Reseting module because it does not connect to Wifi or MQTT",
                    "v")
                machine.reset()
            else:
                retries = retries - 1
        tools.debug("Wifi connected successfully" + str(wlan.ifconfig()), "v")
    except BaseException as e:
        checkError("Error connecting to WLAN", e)
Esempio n. 37
0
def connect_to_network():
    with open("config.json", "r") as file:
        config = ujson.load(file)

    ssid = config["credentials"]["ssid"]
    password = config["credentials"]["password"]

    access_point = WLAN(AP_IF)
    access_point.active(False)

    station = WLAN(STA_IF)
    station.active(True)

    if not station.isconnected():
        print('Verbindung zu', ssid, 'wird hergestellt...')
        station.connect(ssid, password)

        while not station.isconnected():
            pass

    print('Verbindung wurde hergestellt!')
    print('Netzwerkverbinung:', station.ifconfig())
Esempio n. 38
0
def do_connect():
    ap_if = WLAN(AP_IF)
    ap_if.active(False)
    sta_if = WLAN(STA_IF)
    sta_if.active(True)
    sleep_ms(100)
    sta_if.connect('EEERover', 'exhibition')

    # Needed for reliable setup
    sleep_ms(2000)

    # reattempt network conneciton until success
    while sta_if.isconnected() == False:
        print("Attempting to re-connect to network")
        ap_if = WLAN(AP_IF)
        ap_if.active(False)
        sta_if = WLAN(STA_IF)
        sta_if.active(True)
        sleep_ms(100)
         sta_if.connect('EEERover', 'exhibition')
        #Needed for setup
        sleep_ms(2000)
Esempio n. 39
0
def connect(networks: dict, timeout: int = 10, retries: int = 5):
    """
    connect to wifi access point
    :param: networks: dict of "ssid": "password"
    :param: timeout: a timeout, how long to wait for association
    :return:
    """
    # try to join wifi at startup
    wlan = WLAN(mode=WLAN.STA)
    connected = False
    while not connected:
        nets = wlan.scan()
        print("-- searching for wifi networks...")
        for net in nets:
            if net.ssid in networks:
                ssid = net.ssid
                password = networks[ssid]
                print('-- wifi network ' + ssid + ' found, connecting ...')
                wlan.connect(ssid,
                             auth=(net.sec, password),
                             timeout=timeout * 1000)
                while not wlan.isconnected():
                    machine.idle()  # save power while waiting
                print('-- wifi network connected')
                print('-- IP address: ' + str(wlan.ifconfig()))
                rtc = machine.RTC()
                rtc.ntp_sync('pool.ntp.org', 3600)
                while not rtc.synced():
                    time.sleep(1)
                print('-- current time: ' + str(rtc.now()) + "\n")
                return
        if retries > 0:
            print("!! no usable networks found, trying again in 30s")
            print("!! available networks:")
            print("!! " + repr([net.ssid for net in nets]))
            retries -= 1
            time.sleep(30)
        else:
            raise Exception("network association failed with too many retries")
Esempio n. 40
0
class WifiController:
    def __init__(self):
        self._wlan = WLAN(mode=WLAN.STA)
        self.connect()
        self._wlan.ifconfig(config=(ADDR, SUBNET_MASK, DEFAULT_GATEWAY,
                                    DNS_SERVER))
        self._sock = self.makeSock()

    def connect(self):
        """connect to wifi"""
        self._wlan.connect('stranger',
                           auth=(WLAN.WPA2, 'inastrangewlan'),
                           timeout=CONNECTION_TIMEOUT_MS)

    def makeSock(self):
        # Open up a UDP socket to our target
        ai = usocket.getaddrinfo(url, port)
        s = usocket.socket(usocket.AF_INET, usocket.SOCK_DGRAM,
                           usocket.IPPROTO_UDP)
        s.connect(ai[0][-1])
        return s

    def canSend(self):
        """return true if interface can send data, false otherwise"""
        return self._wlan.isconnected()

    def send(self, data):
        """attempts to send via interface, returns success status"""
        #TODO encrypt data
        try:
            self._sock.write(data)
            return True
        except OSError:
            print("error!")
            self._sock.close()
            self.connect()
            self._sock = self.makeSock()
            return False
Esempio n. 41
0
def send_server():
    global sd
    from network import WLAN
    from mqtt import MQTTClient
    import machine
    import time

    def sub_cb(topic, msg):
        print(msg)

    wlan = WLAN(mode=WLAN.STA)
    wlan.connect("Android", auth=(WLAN.WPA2, "123456789a"), timeout=5000)

    while not wlan.isconnected():
        machine.idle()
    print("Connected to Wifi\n")

    client = MQTTClient("FiPy",
                        "129.241.91.125",
                        user="******",
                        password="******",
                        port=1883)
    client.set_callback(sub_cb)
    client.connect()
    client.subscribe(topic="Fuelfighter")
    last = None
    packetTemp = None
    copy_counter = 0
    while True:
        stime = (ut() + 500) // 1000
        if "server.txt" in ls('/sd') and stime != last:
            last = stime
            file = open('/sd/server.txt', 'r')
            packet = file.read()
            file.close()
            if packet != packetTemp:
                client.publish(topic="Fuelfighter", msg=packet)
                client.check_msg()
Esempio n. 42
0
def wlan():
    """Connect in STA mode, fallback to AP"""
    log = ulog.Logger('WLAN: ')
    try:
        import wlanconfig
    except ImportError:
        log.notice('no wlanconfig.py')
        wlanconfig = None
        wlan = WLAN(mode=WLAN.AP)
    except Exception as e:
        log.error('error in wlanconfig.py: {}'.format(e))
        wlanconfig = None
        wlan = WLAN(mode=WLAN.AP)
    else:
        try:
            # configure the WLAN subsystem in station mode (the default is AP)
            wlan = WLAN(mode=WLAN.STA)
            log.info('connecting to network (AP)...')
            wlan.connect(wlanconfig.ssid, auth=(WLAN.WPA2, wlanconfig.password), timeout=5000)
            log.info('waiting for IP...')
            for tries in range(50):
                if wlan.isconnected():
                    log.notice('''connected!
      WiPy IP: {}
      NETMASK: {}
      GATEWAY: {}
      DNS:     {}'''.format(*wlan.ifconfig()))
                    break
                time.sleep_ms(100)
        except OSError:
            log.error('found no router, going into AP mode instead')
            wlanconfig = None
        except Exception as e:
            log.error('error: {}'.format(e))
            wlanconfig = None
    if wlanconfig is None:
        wlan.init(mode=WLAN.AP, ssid='wipy-wlan', auth=(WLAN.WPA2,'www.wipy.io'), channel=7, antenna=WLAN.INT_ANT)
Esempio n. 43
0
def wlan():
    with open('/flash/wificonfig.txt') as f:
        ssid = f.readline().strip()
        passwd = f.readline().strip()

    # configure the WLAN subsystem in station mode (the default is AP)
    print('WLAN: connecting to network (AP)...')
    wlan = WLAN(mode=WLAN.STA)
    try:
        wlan.connect(ssid, auth=(WLAN.WPA2, passwd), timeout=5000)
        print('WLAN: waiting for IP...')
        for tries in range(50):
            if wlan.isconnected():
                print('''\
WLAN: connected!
      WiPy IP: {}
      NETMASK: {}
      GATEWAY: {}
      DNS:     {}'''.format(*wlan.ifconfig()))
                break
            time.sleep_ms(100)
    except OSError:
        print('WLAN: found no router, going into AP mode instead')
        wlan.init(mode=WLAN.AP, ssid='wipy-wlan', auth=(WLAN.WPA2,'www.wipy.io'), channel=7, antenna=WLAN.INT_ANT)
Esempio n. 44
0
    def connect_wifi(self):
        from network import WLAN

        if not self.cfg:
            raise ValueError("Can't initialise wifi, no config")

        self.log('Starting WLAN, attempting to connect to ' + ','.join(self.cfg.wifi.keys()))
        wlan = WLAN(0, WLAN.STA)
        wlan.ifconfig(config='dhcp')
        while not wlan.isconnected():
            nets = wlan.scan()
            for network in nets:
                if network.ssid in self.cfg.wifi.keys():
                    self.log('Connecting to ' + network.ssid)
                    self.feed_wdt() # just in case
                    wlan.connect(ssid=network.ssid, auth=(network.sec, self.cfg.wifi[network.ssid]))
                    while not wlan.isconnected():
                        idle()
                    break

            self.feed_wdt() # just in case
            sleep_ms(2000)

        self.log('Connected as %s' % wlan.ifconfig()[0])
Esempio n. 45
0
from machine import Timer
from machine import Pin
import BlynkLib
from network import WLAN

WIFI_SSID  = 'YOUR_WIFI_SSID'
WIFI_AUTH  = (WLAN.WPA2, 'YOUR_WIFI_PASSORD')
BLYNK_AUTH = 'YOUR_BLYNK_AUTH'

# connect to WiFi
wifi = WLAN(mode=WLAN.STA)
wifi.connect(WIFI_SSID, auth=WIFI_AUTH, timeout=5000)
while not wifi.isconnected():
    pass

print('IP address:', wifi.ifconfig()[0])

# assign GP9, GP10, GP11, GP24 to alternate function (PWM)
p9 = Pin('GP9', mode=Pin.ALT, alt=3)
p10 = Pin('GP10', mode=Pin.ALT, alt=3)
p11 = Pin('GP11', mode=Pin.ALT, alt=3)
p24 = Pin('GP24', mode=Pin.ALT, alt=5)

# timer in PWM mode and width must be 16 buts
timer10 = Timer(4, mode=Timer.PWM, width=16)
timer9 = Timer(3, mode=Timer.PWM, width=16)
timer1 = Timer(1, mode=Timer.PWM, width=16)

# enable channels @1KHz with a 50% duty cycle
pwm9 = timer9.channel(Timer.B, freq=700, duty_cycle=100)
pwm10 = timer10.channel(Timer.A, freq=700, duty_cycle=100)
Esempio n. 46
0
from machine import UART
import machine
import os
from network import WLAN

uart = UART(0, baudrate=115200)
os.dupterm(uart)

wifi_ssid = 'YOURWIFISSID'
wifi_pass = '******'

if machine.reset_cause() != machine.SOFT_RESET:
        
    wlan = WLAN(mode=WLAN.STA)
    
    wlan.connect(wifi_ssid, auth=(WLAN.WPA2, wifi_pass), timeout=5000)

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


machine.main('main.py')
Esempio n. 47
0
class NanoGateWay:
    def __init__(self):
        self.sock = None
        self.connected = False
        self.wlan = WLAN(mode=WLAN.STA)
        self.riders = {} # dictionary of riders
        # initialize LoRa as a Gateway (with Tx IQ inversion)
        self.lora = LoRa(tx_iq=True, rx_iq=False)

    def connect_to_wlan(self):
        if not self.wlan.isconnected():
            # TODO: change for the correct credentials here (ssid and password)
            self.wlan.connect(ssid='KCOMIoT', auth=(None, '10noCHOSun'), timeout=7000)
            while not self.wlan.isconnected():
                time.sleep_ms(50)

    def connect_to_server(self):
        if self.sock:
            self.sock.close()
        self.sock = socket.socket()                 # TCP
        try:
            self.sock.connect((TCP_IP, TCP_PORT))   # TODO
            self.sock.settimeout(1)
            self.connected = True
        except Exception:
             self.sock.close() # just close the socket and try again later
             print('Socket connect failed, retrying...')
             time.sleep_ms(500)
    
    def send(self, msg):
        if self.connected and self.sock:
            try:
                self.sock.send(msg)
            except Exception:
                self.connected = False
                self.sock.close()
                self.sock = None

    def new_rider(self, name, company, badge, bike, eventid, ridetimestamp):
        rider = Rider(name, company, badge, bike, eventid, ridetimestamp)
        self.riders[bike] = rider

    def recv(self):
        if self.connected and self.sock:
            try:
                data = self.sock.recv(1024)
            except socket.timeout:
                return None
            except socket.error as e:
                if e.args[0] != EAGAIN:
                    self.connected = False
                return None
            return data

    def run(self):
        data = self.recv()
        if data:
            print(data)
            parsed_json = json.loads(data.decode('ascii'))
            print(parsed_json)
            if parsed_json['RideStatus'] == "started":
                self.new_rider(parsed_json['RiderName'], parsed_json['Company'], 
                               parsed_json['BadgeNumber'], parsed_json['BikeID'],parsed_json['EventID'],parsed_json['RideTimestamp'])
                # start the race
                print(str({'id':parsed_json['BikeID'], 'cm': 's'}))
                packet_tx = json.dumps({'id':parsed_json['BikeID'], 'cm': 's'})
                print ("packet_tx = " + packet_tx)
                self.lora.send(packet_tx, True)

        lora_d = self.lora.recv()
        if lora_d:
            parsed_json = json.loads(lora_d.decode('ascii'))
            print(parsed_json)
            # update the rider info (if the rider already exists)
            bike_id = parsed_json['id']
            if bike_id in self.riders:
                self.riders[bike_id].speed = parsed_json['sp']
                self.riders[bike_id].distance = parsed_json['ds']
                self.riders[bike_id].crank = parsed_json['cr']
                if parsed_json['st'] == 'i' or parsed_json['st'] == 'f':
                    self.riders[bike_id].status = 'finished'
                elif parsed_json['st'] == 'r':
                    self.riders[bike_id].status = 'counting'
                else:
                    self.riders[bike_id].status = 'started'
                # Assemble the TCP packet
                wheel_count=self.riders[bike_id].crank * 7
                json_d = {"RiderName":self.riders[bike_id].name, "Company":self.riders[bike_id].company, "BadgeNumber":self.riders[bike_id].badge, \
                          "EventID":self.riders[bike_id].eventid, "RideTimestamp":'{:f}'.format(self.riders[bike_id].ridetimestamp), "BikeID":bike_id, \
                          "RideStatus":self.riders[bike_id].status, "RideInfo":[{"CounterTimestamp": float(time.ticks_ms()), \
                          "CrankCounter":self.riders[bike_id].crank, "WheelCounter":wheel_count}]}
                json_str = json.dumps(json_d)
                print("Outgoing from Gateway: " + str(json_str))
                self.send(json_str+"\n")
        if not self.connected:
            self.connect_to_wlan()
            self.connect_to_server()
Esempio n. 48
0
  Run the App (green triangle in the upper right corner).

Don't forget to change WIFI_SSID, WIFI_AUTH and BLYNK_AUTH ;)
"""

import BlynkLib
from network import WLAN
import time

WIFI_SSID  = 'YOUR_WIFI'
WIFI_PASS  = '******'
BLYNK_AUTH = 'YOUR_AUTH_TOKEN'

# connect to WiFi
wifi = WLAN(mode=WLAN.STA)
wifi.connect(WIFI_SSID, auth=(WLAN.WPA2, WIFI_PASS))
while not wifi.isconnected():
    pass

print('IP address:', wifi.ifconfig()[0])

# initialize Blynk
blynk = BlynkLib.Blynk(BLYNK_AUTH)

# register the task running every 3 sec
# (period must be a multiple of 50 ms)
def my_user_task():
    # do any non-blocking operations
    print('Action')
    blynk.virtual_write(2, time.ticks_ms() // 1000)
Esempio n. 49
0
class NanoGateway:
    """
    Nano gateway class, set up by default for use with TTN, but can be configured
    for any other network supporting the Semtech Packet Forwarder.
    Only required configuration is wifi_ssid and wifi_password which are used for
    connecting to the Internet.
    """

    def __init__(self, id, frequency, datarate, ssid, password, server, port, ntp_server='pool.ntp.org', ntp_period=3600):
        self.id = id
        self.server = server
        self.port = port

        self.frequency = frequency
        self.datarate = datarate

        self.ssid = ssid
        self.password = password

        self.ntp_server = ntp_server
        self.ntp_period = ntp_period

        self.server_ip = None

        self.rxnb = 0
        self.rxok = 0
        self.rxfw = 0
        self.dwnb = 0
        self.txnb = 0

        self.sf = self._dr_to_sf(self.datarate)
        self.bw = self._dr_to_bw(self.datarate)

        self.stat_alarm = None
        self.pull_alarm = None
        self.uplink_alarm = None

        self.wlan = None
        self.sock = None
        self.udp_stop = False
        self.udp_lock = _thread.allocate_lock()

        self.lora = None
        self.lora_sock = None

        self.rtc = machine.RTC()

    def start(self):
        """
        Starts the LoRaWAN nano gateway.
        """

        self._log('Starting LoRaWAN nano gateway with id: {}', self.id)

        # setup WiFi as a station and connect
        self.wlan = WLAN(mode=WLAN.STA)
        self._connect_to_wifi()

        # get a time sync
        self._log('Syncing time with {} ...', self.ntp_server)
        self.rtc.ntp_sync(self.ntp_server, update_period=self.ntp_period)
        while not self.rtc.synced():
            utime.sleep_ms(50)
        self._log("RTC NTP sync complete")

        # get the server IP and create an UDP socket
        self.server_ip = usocket.getaddrinfo(self.server, self.port)[0][-1]
        self._log('Opening UDP socket to {} ({}) port {}...', self.server, self.server_ip[0], self.server_ip[1])
        self.sock = usocket.socket(usocket.AF_INET, usocket.SOCK_DGRAM, usocket.IPPROTO_UDP)
        self.sock.setsockopt(usocket.SOL_SOCKET, usocket.SO_REUSEADDR, 1)
        self.sock.setblocking(False)

        # push the first time immediatelly
        self._push_data(self._make_stat_packet())

        # create the alarms
        self.stat_alarm = Timer.Alarm(handler=lambda t: self._push_data(self._make_stat_packet()), s=60, periodic=True)
        self.pull_alarm = Timer.Alarm(handler=lambda u: self._pull_data(), s=25, periodic=True)

        # start the UDP receive thread
        self.udp_stop = False
        _thread.start_new_thread(self._udp_thread, ())

        # initialize the LoRa radio in LORA mode
        self._log('Setting up the LoRa radio at {:.1f} Mhz using {}', self._freq_to_float(self.frequency), self.datarate)
        self.lora = LoRa(
            mode=LoRa.LORA,
            frequency=self.frequency,
            bandwidth=self.bw,
            sf=self.sf,
            preamble=8,
            coding_rate=LoRa.CODING_4_5,
            tx_iq=True
        )

        # create a raw LoRa socket
        self.lora_sock = usocket.socket(usocket.AF_LORA, usocket.SOCK_RAW)
        self.lora_sock.setblocking(False)
        self.lora_tx_done = False

        self.lora.callback(trigger=(LoRa.RX_PACKET_EVENT | LoRa.TX_PACKET_EVENT), handler=self._lora_cb)
        self._log('LoRaWAN nano gateway online')

    def stop(self):
        """
        Stops the LoRaWAN nano gateway.
        """

        self._log('Stopping...')

        # send the LoRa radio to sleep
        self.lora.callback(trigger=None, handler=None)
        self.lora.power_mode(LoRa.SLEEP)

        # stop the NTP sync
        self.rtc.ntp_sync(None)

        # cancel all the alarms
        self.stat_alarm.cancel()
        self.pull_alarm.cancel()

        # signal the UDP thread to stop
        self.udp_stop = True
        while self.udp_stop:
            utime.sleep_ms(50)

        # disable WLAN
        self.wlan.disconnect()
        self.wlan.deinit()

    def _connect_to_wifi(self):
        self.wlan.connect(self.ssid, auth=(None, self.password))
        while not self.wlan.isconnected():
            utime.sleep_ms(50)
        self._log('WiFi connected to: {}', self.ssid)

    def _dr_to_sf(self, dr):
        sf = dr[2:4]
        if sf[1] not in '0123456789':
            sf = sf[:1]
        return int(sf)

    def _dr_to_bw(self, dr):
        bw = dr[-5:]
        if bw == 'BW125':
            return LoRa.BW_125KHZ
        elif bw == 'BW250':
            return LoRa.BW_250KHZ
        else:
            return LoRa.BW_500KHZ

    def _sf_bw_to_dr(self, sf, bw):
        dr = 'SF' + str(sf)
        if bw == LoRa.BW_125KHZ:
            return dr + 'BW125'
        elif bw == LoRa.BW_250KHZ:
            return dr + 'BW250'
        else:
            return dr + 'BW500'

    def _lora_cb(self, lora):
        """
        LoRa radio events callback handler.
        """

        events = lora.events()
        if events & LoRa.RX_PACKET_EVENT:
            self.rxnb += 1
            self.rxok += 1
            rx_data = self.lora_sock.recv(256)
            stats = lora.stats()
            packet = self._make_node_packet(rx_data, self.rtc.now(), stats.rx_timestamp, stats.sfrx, self.bw, stats.rssi, stats.snr)
            self._push_data(packet)
            self._log('Received packet: {}', packet)
            self.rxfw += 1
        if events & LoRa.TX_PACKET_EVENT:
            self.txnb += 1
            lora.init(
                mode=LoRa.LORA,
                frequency=self.frequency,
                bandwidth=self.bw,
                sf=self.sf,
                preamble=8,
                coding_rate=LoRa.CODING_4_5,
                tx_iq=True
                )

    def _freq_to_float(self, frequency):
        """
        MicroPython has some inprecision when doing large float division.
        To counter this, this method first does integer division until we
        reach the decimal breaking point. This doesn't completely elimate
        the issue in all cases, but it does help for a number of commonly
        used frequencies.
        """

        divider = 6
        while divider > 0 and frequency % 10 == 0:
            frequency = frequency // 10
            divider -= 1
        if divider > 0:
            frequency = frequency / (10 ** divider)
        return frequency

    def _make_stat_packet(self):
        now = self.rtc.now()
        STAT_PK["stat"]["time"] = "%d-%02d-%02d %02d:%02d:%02d GMT" % (now[0], now[1], now[2], now[3], now[4], now[5])
        STAT_PK["stat"]["rxnb"] = self.rxnb
        STAT_PK["stat"]["rxok"] = self.rxok
        STAT_PK["stat"]["rxfw"] = self.rxfw
        STAT_PK["stat"]["dwnb"] = self.dwnb
        STAT_PK["stat"]["txnb"] = self.txnb
        return ujson.dumps(STAT_PK)

    def _make_node_packet(self, rx_data, rx_time, tmst, sf, bw, rssi, snr):
        RX_PK["rxpk"][0]["time"] = "%d-%02d-%02dT%02d:%02d:%02d.%dZ" % (rx_time[0], rx_time[1], rx_time[2], rx_time[3], rx_time[4], rx_time[5], rx_time[6])
        RX_PK["rxpk"][0]["tmst"] = tmst
        RX_PK["rxpk"][0]["freq"] = self._freq_to_float(self.frequency)
        RX_PK["rxpk"][0]["datr"] = self._sf_bw_to_dr(sf, bw)
        RX_PK["rxpk"][0]["rssi"] = rssi
        RX_PK["rxpk"][0]["lsnr"] = snr
        RX_PK["rxpk"][0]["data"] = ubinascii.b2a_base64(rx_data)[:-1]
        RX_PK["rxpk"][0]["size"] = len(rx_data)
        return ujson.dumps(RX_PK)

    def _push_data(self, data):
        token = uos.urandom(2)
        packet = bytes([PROTOCOL_VERSION]) + token + bytes([PUSH_DATA]) + ubinascii.unhexlify(self.id) + data
        with self.udp_lock:
            try:
                self.sock.sendto(packet, self.server_ip)
            except Exception as ex:
                self._log('Failed to push uplink packet to server: {}', ex)

    def _pull_data(self):
        token = uos.urandom(2)
        packet = bytes([PROTOCOL_VERSION]) + token + bytes([PULL_DATA]) + ubinascii.unhexlify(self.id)
        with self.udp_lock:
            try:
                self.sock.sendto(packet, self.server_ip)
            except Exception as ex:
                self._log('Failed to pull downlink packets from server: {}', ex)

    def _ack_pull_rsp(self, token, error):
        TX_ACK_PK["txpk_ack"]["error"] = error
        resp = ujson.dumps(TX_ACK_PK)
        packet = bytes([PROTOCOL_VERSION]) + token + bytes([PULL_ACK]) + ubinascii.unhexlify(self.id) + resp
        with self.udp_lock:
            try:
                self.sock.sendto(packet, self.server_ip)
            except Exception as ex:
                self._log('PULL RSP ACK exception: {}', ex)

    def _send_down_link(self, data, tmst, datarate, frequency):
        """
        Transmits a downlink message over LoRa.
        """

        self.lora.init(
            mode=LoRa.LORA,
            frequency=frequency,
            bandwidth=self._dr_to_bw(datarate),
            sf=self._dr_to_sf(datarate),
            preamble=8,
            coding_rate=LoRa.CODING_4_5,
            tx_iq=True
            )
        while utime.ticks_us() < tmst:
            pass
        self.lora_sock.send(data)
        self._log(
            'Sent downlink packet scheduled on {:.3f}, at {:.1f} Mhz using {}: {}',
            tmst / 1000000,
            self._freq_to_float(frequency),
            datarate,
            data
        )

    def _udp_thread(self):
        """
        UDP thread, reads data from the server and handles it.
        """

        while not self.udp_stop:
            try:
                data, src = self.sock.recvfrom(1024)
                _token = data[1:3]
                _type = data[3]
                if _type == PUSH_ACK:
                    self._log("Push ack")
                elif _type == PULL_ACK:
                    self._log("Pull ack")
                elif _type == PULL_RESP:
                    self.dwnb += 1
                    ack_error = TX_ERR_NONE
                    tx_pk = ujson.loads(data[4:])
                    tmst = tx_pk["txpk"]["tmst"]
                    t_us = tmst - utime.ticks_us() - 12500
                    if t_us < 0:
                        t_us += 0xFFFFFFFF
                    if t_us < 20000000:
                        self.uplink_alarm = Timer.Alarm(
                            handler=lambda x: self._send_down_link(
                                ubinascii.a2b_base64(tx_pk["txpk"]["data"]),
                                tx_pk["txpk"]["tmst"] - 50, tx_pk["txpk"]["datr"],
                                int(tx_pk["txpk"]["freq"] * 1000000)
                            ), 
                            us=t_us
                        )
                    else:
                        ack_error = TX_ERR_TOO_LATE
                        self._log('Downlink timestamp error!, t_us: {}', t_us)
                    self._ack_pull_rsp(_token, ack_error)
                    self._log("Pull rsp")
            except usocket.timeout:
                pass
            except OSError as ex:
                if ex.errno != errno.EAGAIN:
                    self._log('UDP recv OSError Exception: {}', ex)
            except Exception as ex:
                self._log('UDP recv Exception: {}', ex)

            # wait before trying to receive again
            utime.sleep_ms(UDP_THREAD_CYCLE_MS)

        # we are to close the socket
        self.sock.close()
        self.udp_stop = False
        self._log('UDP thread stopped')

    def _log(self, message, *args):
        """
        Outputs a log message to stdout.
        """

        print('[{:>10.3f}] {}'.format(
            utime.ticks_ms() / 1000,
            str(message).format(*args)
            ))
Esempio n. 50
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
Esempio n. 51
0
# can run arbitrary Python, but best to keep it minimal

import os

import machine
from network import WLAN

# disable LED matrix first
latch = machine.Pin('GP13', mode=machine.Pin.OUT)
latch.value(0)

spi = machine.SPI(0, mode=machine.SPI.MASTER, bits=32, pins=('GP14', 'GP16', 'GP15'))
spi.write(b'\x00\x00\x00\x00')
latch.value(1)

# repl on serial
os.dupterm(machine.UART(0, 115200))

# now wifi
wlan = WLAN()

if machine.reset_cause() != machine.SOFT_RESET:
    wlan.init(WLAN.STA)
    wlan.ifconfig(config=('192.168.1.254', '255.255.255.0', '192.168.1.1', '192.168.1.1'))

if not wlan.isconnected():
    # change the line below to match your network ssid, security and password
    wlan.connect('XXX', auth=(WLAN.WPA2, 'XXX'), timeout=5000)
    while not wlan.isconnected():
        machine.idle()
Esempio n. 52
0
Calling virtual_write updates widget value.

Don't forget to change WIFI_SSID, WIFI_AUTH and BLYNK_AUTH ;)
"""

import BlynkLib
from network import WLAN
import time

WIFI_SSID  = 'YOUR_WIFI'
WIFI_AUTH  = (WLAN.WPA2, 'YOUR_PASS')
BLYNK_AUTH = 'YOUR_AUTH_TOKEN'

# connect to WiFi
wifi = WLAN(mode=WLAN.STA)
wifi.connect(WIFI_SSID, auth=WIFI_AUTH)
while not wifi.isconnected():
    pass

print('IP address:', wifi.ifconfig()[0])

# initialize Blynk
blynk = BlynkLib.Blynk(BLYNK_AUTH)

# to register virtual pins first define a handler:
def v2_read_handler():
    # this widget will show some time in seconds..
    blynk.virtual_write(2, time.ticks_ms() // 1000)

# attach virtual pin 0 to our handler
blynk.add_virtual_pin(2, read=v2_read_handler)
Esempio n. 53
0
class NanoGateway:

    def __init__(self, id, frequency, datarate, ssid, password, server, port, ntp='pool.ntp.org', ntp_period=3600):
        self.id = id
        self.frequency = frequency
        self.datarate = datarate
        self.sf = self._dr_to_sf(datarate)
        self.ssid = ssid
        self.password = password
        self.server = server
        self.port = port
        self.ntp = ntp
        self.ntp_period = ntp_period

        self.rxnb = 0
        self.rxok = 0
        self.rxfw = 0
        self.dwnb = 0
        self.txnb = 0

        self.stat_alarm = None
        self.pull_alarm = None
        self.uplink_alarm = None

        self.udp_lock = _thread.allocate_lock()

        self.lora = None
        self.lora_sock = None

    def start(self):
        # Change WiFi to STA mode and connect
        self.wlan = WLAN(mode=WLAN.STA)
        self._connect_to_wifi()

        # Get a time Sync
        self.rtc = machine.RTC()
        self.rtc.ntp_sync(self.ntp, update_period=self.ntp_period)

        # Get the server IP and create an UDP socket
        self.server_ip = socket.getaddrinfo(self.server, self.port)[0][-1]
        self.sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
        self.sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        self.sock.setblocking(False)

        # Push the first time immediatelly
        self._push_data(self._make_stat_packet())

        # Create the alarms
        self.stat_alarm = Timer.Alarm(handler=lambda t: self._push_data(self._make_stat_packet()), s=60, periodic=True)
        self.pull_alarm = Timer.Alarm(handler=lambda u: self._pull_data(), s=25, periodic=True)

        # Start the UDP receive thread
        _thread.start_new_thread(self._udp_thread, ())

        # Initialize LoRa in LORA mode
        self.lora = LoRa(mode=LoRa.LORA, frequency=self.frequency, bandwidth=LoRa.BW_125KHZ, sf=self.sf,
                         preamble=8, coding_rate=LoRa.CODING_4_5, tx_iq=True)
        # Create a raw LoRa socket
        self.lora_sock = socket.socket(socket.AF_LORA, socket.SOCK_RAW)
        self.lora_sock.setblocking(False)
        self.lora_tx_done = False

        self.lora.callback(trigger=(LoRa.RX_PACKET_EVENT | LoRa.TX_PACKET_EVENT), handler=self._lora_cb)

    def stop(self):
        # TODO: Check how to stop the NTP sync
        # TODO: Create a cancel method for the alarm
        # TODO: kill the UDP thread
        self.sock.close()

    def _connect_to_wifi(self):
        self.wlan.connect(self.ssid, auth=(None, self.password))
        while not self.wlan.isconnected():
            time.sleep(0.5)
        print("WiFi connected!")

    def _dr_to_sf(self, dr):
        sf = dr[2:4]
        if sf[1] not in '0123456789':
            sf = sf[:1]
        return int(sf)

    def _sf_to_dr(self, sf):
        return self.datarate

    def _make_stat_packet(self):
        now = self.rtc.now()
        STAT_PK["stat"]["time"] = "%d-%02d-%02d %02d:%02d:%02d GMT" % (now[0], now[1], now[2], now[3], now[4], now[5])
        STAT_PK["stat"]["rxnb"] = self.rxnb
        STAT_PK["stat"]["rxok"] = self.rxok
        STAT_PK["stat"]["rxfw"] = self.rxfw
        STAT_PK["stat"]["dwnb"] = self.dwnb
        STAT_PK["stat"]["txnb"] = self.txnb
        return json.dumps(STAT_PK)

    def _make_node_packet(self, rx_data, rx_time, tmst, sf, rssi, snr):
        RX_PK["rxpk"][0]["time"] = "%d-%02d-%02dT%02d:%02d:%02d.%dZ" % (rx_time[0], rx_time[1], rx_time[2], rx_time[3], rx_time[4], rx_time[5], rx_time[6])
        RX_PK["rxpk"][0]["tmst"] = tmst
        RX_PK["rxpk"][0]["datr"] = self._sf_to_dr(sf)
        RX_PK["rxpk"][0]["rssi"] = rssi
        RX_PK["rxpk"][0]["lsnr"] = float(snr)
        RX_PK["rxpk"][0]["data"] = binascii.b2a_base64(rx_data)[:-1]
        RX_PK["rxpk"][0]["size"] = len(rx_data)
        return json.dumps(RX_PK)

    def _push_data(self, data):
        token = os.urandom(2)
        packet = bytes([PROTOCOL_VERSION]) + token + bytes([PUSH_DATA]) + binascii.unhexlify(self.id) + data
        with self.udp_lock:
            try:
                self.sock.sendto(packet, self.server_ip)
            except Exception:
                print("PUSH exception")

    def _pull_data(self):
        token = os.urandom(2)
        packet = bytes([PROTOCOL_VERSION]) + token + bytes([PULL_DATA]) + binascii.unhexlify(self.id)
        with self.udp_lock:
            try:
                self.sock.sendto(packet, self.server_ip)
            except Exception:
                print("PULL exception")

    def _ack_pull_rsp(self, token, error):
        TX_ACK_PK["txpk_ack"]["error"] = error
        resp = json.dumps(TX_ACK_PK)
        packet = bytes([PROTOCOL_VERSION]) + token + bytes([PULL_ACK]) + binascii.unhexlify(self.id) + resp
        with self.udp_lock:
            try:
                self.sock.sendto(packet, self.server_ip)
            except Exception:
                print("PULL RSP ACK exception")

    def _lora_cb(self, lora):
        events = lora.events()
        if events & LoRa.RX_PACKET_EVENT:
            self.rxnb += 1
            self.rxok += 1
            rx_data = self.lora_sock.recv(256)
            stats = lora.stats()
            #self._push_data(self._make_node_packet(rx_data, self.rtc.now(), stats.rx_timestamp, stats.sfrx, stats.rssi, stats.snr))
            # Fix the "not joined yet" issue: https://forum.pycom.io/topic/1330/lopy-lorawan-gateway-with-an-st-lorawan-device/2
            self._push_data(self._make_node_packet(rx_data, self.rtc.now(), time.ticks_us(), stats.sfrx, stats.rssi, stats.snr))
            self.rxfw += 1
        if events & LoRa.TX_PACKET_EVENT:
            self.txnb += 1
            lora.init(mode=LoRa.LORA, frequency=self.frequency, bandwidth=LoRa.BW_125KHZ,
                      sf=self.sf, preamble=8, coding_rate=LoRa.CODING_4_5, tx_iq=True)

    def _send_down_link(self, data, tmst, datarate, frequency):
        self.lora.init(mode=LoRa.LORA, frequency=frequency, bandwidth=LoRa.BW_125KHZ,
                       sf=self._dr_to_sf(datarate), preamble=8, coding_rate=LoRa.CODING_4_5,
                       tx_iq=True)
        while time.ticks_us() < tmst:
            pass
        self.lora_sock.send(data)

    def _udp_thread(self):
        while True:
            try:
                data, src = self.sock.recvfrom(1024)
                _token = data[1:3]
                _type = data[3]
                if _type == PUSH_ACK:
                    print("Push ack")
                elif _type == PULL_ACK:
                    print("Pull ack")
                elif _type == PULL_RESP:
                    self.dwnb += 1
                    ack_error = TX_ERR_NONE
                    tx_pk = json.loads(data[4:])
                    tmst = tx_pk["txpk"]["tmst"]
                    t_us = tmst - time.ticks_us() - 5000
                    if t_us < 0:
                        t_us += 0xFFFFFFFF
                    if t_us < 20000000:
                        self.uplink_alarm = Timer.Alarm(handler=lambda x: self._send_down_link(binascii.a2b_base64(tx_pk["txpk"]["data"]),
                                                                                               tx_pk["txpk"]["tmst"] - 10, tx_pk["txpk"]["datr"],
                                                                                               int(tx_pk["txpk"]["freq"] * 1000000)), us=t_us)
                    else:
                        ack_error = TX_ERR_TOO_LATE
                        print("Downlink timestamp error!, t_us:", t_us)
                    self._ack_pull_rsp(_token, ack_error)
                    print("Pull rsp")
            except socket.timeout:
                pass
            except OSError as e:
                if e.errno == errno.EAGAIN:
                    pass
                else:
                    print("UDP recv OSError Exception")
            except Exception:
                print("UDP recv Exception")
            # Wait before trying to receive again
            time.sleep(0.025)
Esempio n. 54
0
import machine
from network import WLAN
wlan = WLAN(mode=WLAN.STA)

nets = wlan.scan()
for net in nets:
    if net.ssid == 'MZTC':
        print('Network found!')
        wlan.connect(net.ssid, auth=(0, ''), timeout=5000)
        while not wlan.isconnected():
            machine.idle() # save power while waiting
        print('WLAN connection succeeded!')
        break
Esempio n. 55
0
wifi.antenna(WLAN.INT_ANT)
print(wifi.antenna() == WLAN.INT_ANT)

wifi.antenna(WLAN.EXT_ANT)
print(wifi.antenna() == WLAN.EXT_ANT)
scan_r = wifi.scan()
print(len(scan_r) > 3)
for net in scan_r:
    if net.ssid == testconfig.wlan_ssid:
        print('Network found')
        break

wifi.antenna(WLAN.INT_ANT)
wifi.mode(WLAN.STA)
print(wifi.mode() == WLAN.STA)
wifi.connect(testconfig.wlan_ssid, auth=testconfig.wlan_auth, timeout=10000)
wait_for_connection(wifi)

wifi.ifconfig(config='dhcp')
wait_for_connection(wifi)
print('0.0.0.0' not in wifi.ifconfig())
wifi.ifconfig(0, ('192.168.178.109', '255.255.255.0', '192.168.178.1', '8.8.8.8'))
wait_for_connection(wifi)
print(wifi.ifconfig(0) == ('192.168.178.109', '255.255.255.0', '192.168.178.1', '8.8.8.8'))
wait_for_connection(wifi)

print(wifi.isconnected() == True)
wifi.disconnect()
print(wifi.isconnected() == False)

t0 = time.ticks_ms()
Esempio n. 56
0
RMotorB = Pin('GPIO8', af=0, mode=Pin.OUT)
LMotorB.low()
RMotorB.low()

# assign GPIO9 and 10 to alternate function 3 (PWM)
# These will be the pins to control speed
LMotorA = Pin('GPIO9', af=3, type=Pin.STD)
RMotorA = Pin('GPIO10', af=3, type=Pin.STD)

# Enable timer channels 3B and 4A for PWM pins
LMTimer = Timer(3, mode=Timer.PWM, width=16)
RMTimer = Timer(4, mode=Timer.PWM, width=16)
# enable channel A @1KHz with a 50% duty cycle
LMT_a = LMTimer.channel(Timer.B, freq=1000, duty_cycle=50)
RMT_a = RMTimer.channel(Timer.A, freq=1000, duty_cycle=50)

def Setup_WIFI()
wifi = WLAN(WLAN.STA)
# go for fixed IP settings
wifi.ifconfig('192.168.0.107', '255.255.255.0', '192.168.0.1', '8.8.8.8')
wifi.scan()     # scan for available netrworks
wifi.connect(ssid='mynetwork', security=2, key='mynetworkkey')
while not wifi.isconnected():
    pass
print(wifi.ifconfig())
# enable wake on WLAN
wifi.callback(wakes=Sleep.SUSPENDED)
# go to sleep
Sleep.suspend()
# now, connect to the FTP or the Telnet server and the WiPy will wake-up
Esempio n. 57
0
import machine
from network import WLAN
wlan = WLAN(mode=WLAN.STA)

nets = wlan.scan()
for net in nets:
    if net.ssid == 'MarconiLab':
        print('Network found!')
        wlan.connect(net.ssid, auth=(net.sec, 'marconi-lab'), timeout=5000)
        while not wlan.isconnected():
            machine.idle() # save power while waiting
        print('WLAN connection succeeded!')
        break
Esempio n. 58
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. 59
0
	wlan.init(WLAN.STA)
	wlan.ifconfig(config=(IP, NETMASK, GATEWAY, DNS))
	
if not wlan.isconnected():
	print('Attempting to connect to WiFi', end=' ')
	nets = wlan.scan()
	for net in nets:
		if net.ssid == 'Robotmad':
			KEY = 'mou3se43'
			break
		elif net.ssid == 'CoderDojo':
			KEY = 'coderdojo'
			break
	if KEY != '':
		print(net.ssid, end=" ")
		wlan.connect(net.ssid, auth=(net.sec, KEY), timeout=10000)
	if wlan.isconnected():
		print('Connected')
		tim_a.freq(10)
		wlan.irq(trigger=WLAN.ANY_EVENT, wake=machine.SLEEP)
	else :
		wlan.init(WLAN.AP, ssid='wipy-wlan', auth=(WLAN.WPA2, 'www.wipy.io'), channel=5, antenna=WLAN.INT_ANT)
		print('Failed - setting up as AP wipy-wlan')	
		tim.deinit()					# Cancel timer that was flashing the LED
		led_out(True)					# True = LED Off

#print(wlan.ifconfig())
print('Done.')
#machine.sleep()
	
Esempio n. 60
0
import machine
from network import WLAN
import time
import socket
import utime

wlan = WLAN(mode=WLAN.STA)

nets = wlan.scan()
for net in nets:
    if net.ssid == 'FabLab':
        print('Network found!')
        wlan.connect(net.ssid, auth=(net.sec, 'MakerFaire'), timeout=5000)
        while not wlan.isconnected():
            machine.idle() # save power while waiting
        print('WLAN connection succeeded!')
        break

rtc = machine.RTC()
rtc.init((2015, 1, 1, 1, 0, 0, 0, 0))
print("Before network time adjust", rtc.now())
print('Setting RTC using Sodaq time server')

s=socket.socket()
addr = socket.getaddrinfo('time.sodaq.net', 80)[0][-1]
s.connect(addr)
s.send(b'GET / HTTP/1.1\r\nHost: time.sodaq.net\r\n\r\n')
ris=s.recv(1024).decode()
s.close()
rows = ris.split('\r\n')            # transform string in list of strings
seconds = rows[7]