Beispiel #1
0
def connect_to_network():
    """
    Connects to Wi-Fi Network
    Warning: we used firmware MicroPython 1.18.2.r7 [v1.8.6-849-df9f237], newer FW versions have an
    issue with the Wi-Fi driver as of 29/02/2020 (Scans OK but cannot connect)

    :return: True if we could connect to the Wi-Fi or otherwise False.
    """

    wlan = WLAN(mode=WLAN.STA)

    # Scanning for networks
    nets = wlan.scan()
    for net in nets:
        print(net.ssid)
        if net.ssid == _WIFI_SSID:
            print("Found the network")
            wlan.connect(net.ssid, auth=(net.sec, _WIFI_PASS), timeout=5000)
            while not wlan.isconnected():
                machine.idle()
            print("WLAN connection to", _WIFI_SSID, "succeeded!")
            break

    # The assigned IP address for the Pycom
    print("IP-address:", wlan.ifconfig()[0])
    return wlan.isconnected()
Beispiel #2
0
def get_WLAN():
    global wlan
    if wlan == None:
        wlan = WLAN(mode=WLAN.STA)
    if wlan.isconnected():
        return True
    nets = wlan.scan()
    for net in nets:
        if net.ssid == config.WLAN_SSID:
            debugprint('Network found!')
            wlan.connect(net.ssid,
                         auth=(net.sec, config.WLAN_WPA),
                         timeout=5000)
            attempts = 0
            while (not wlan.isconnected()) and (attempts < 10):
                debugprint('Connecting...')
                attempts = attempts + 1
                time.sleep(1)
            if wlan.isconnected():
                debugprint('WLAN connection succeeded')
                return True
            else:
                debugprint('WLAN connection failed')
                end_WLAN()
                return False
    debugprint('No known WLAN SSID found')
    wlan.deinit()
    wlan = None
    return False
 def __smart_config_setup(self):
     wl = WLAN(mode=WLAN.STA)
     wl.callback(trigger=WLAN.SMART_CONF_DONE | WLAN.SMART_CONF_TIMEOUT,
                 handler=self.__smart_config_callback)
     if pycom.wifi_ssid_sta() is not None and len(
             pycom.wifi_ssid_sta()) > 0:
         print('Trying previous AP details for 60 seconds...')
         pycom.wifi_on_boot(True, True)
         try:
             start_time = time.time()
             while not wl.isconnected() and (
                     time.time() - start_time <
                     60) and self.__smart_config:
                 time.sleep(1)
         except:
             pass
         if wl.isconnected() and self.__smart_config:
             try:
                 from pybytes_config import PybytesConfig
             except:
                 from _pybytes_config import PybytesConfig
             self.__conf = PybytesConfig().smart_config()
             self.__smart_config = False
             self.start()
     if self.__smart_config:
         wl.smartConfig()
         print("Smart Provisioning started in the background")
         print("See https://docs.pycom.io/smart for details")
Beispiel #4
0
def connect_to_wifi(wifi_ssid, wifi_passwd):
    wlan = WLAN(mode=WLAN.STA)

    for ltry in range(3):
        print("Connecting to: " + wifi_ssid + ". Try " + str(ltry))
        nets = wlan.scan()
        for net in nets:
            if net.ssid == wifi_ssid:
                print('Network ' + wifi_ssid + ' found!')
                wlan.connect(net.ssid,
                             auth=(net.sec, wifi_passwd),
                             timeout=5000)
                while not wlan.isconnected():
                    machine.idle()  # save power while waiting
                break
        if wlan.isconnected():
            break
        else:
            print('Cannot find network ' + wifi_ssid)
            flash_led_to(RED, 1)

    if not wlan.isconnected():
        print('Cannot connect to network ' + wifi_ssid + '. Quitting!!!')
        sys.exit(1)
    else:
        print('WLAN connection succeeded!')
        flash_led_to(GREEN, 1)
        print(wlan.ifconfig())
Beispiel #5
0
class WiFi(object):
    wlan = None
    config = None

    def can_see_ssid(self, ssid):
        networks = [w[0] for w in self.wlan.scan()]
        return ssid in networks

    def __init__(self, config):
        self.config = config
        self.wlan = WLAN(mode=WLAN.STA)

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

    def connect_wifi(self):
        config = self.config
        if not self.wlan.isconnected():
            for wlan in config['WLANS']:
                if self.can_see_ssid(wlan['WLAN_SSID']):
                    print("Trying: {} ...".format(wlan['WLAN_SSID']))
                    self.wlan.connect(ssid=wlan['WLAN_SSID'],
                                      auth=(WLAN.WPA2, wlan['WLAN_KEY']))

                    # Give it a chance to get connected
                    count = 0
                    while not self.wlan.isconnected() and count < 10:
                        print("Waiting for connection... ({})".format(count))
                        count += 1
                        sleep(1)
                    if not self.wlan.isconnected():
                        print("Giving up")
            if self.wlan.isconnected():
                print("Connected: \n", self.wlan.ifconfig())
Beispiel #6
0
def connect_to_wifi_UPVIoT(wifi_user, wifi_passwd):
    wifi_ssid="UPV-IoT"
    wlan = WLAN(mode=WLAN.STA)

    if (wifi_user=="IOTPMxxx"):
        print("No te has leido el boletín de practicas... verdad?!?!?")
        sys.exit()

    for ltry in range(3):
        print("Connecting to: "+wifi_ssid+" as "+wifi_user+". Try "+str(ltry))
        nets = wlan.scan()
        for net in nets:
            if net.ssid == wifi_ssid:
                print('Network '+wifi_ssid+' found!')
                wlan.connect(net.ssid, auth=(WLAN.WPA2_ENT, wifi_user, wifi_passwd), identity=wifi_user)
                while not wlan.isconnected():
                    machine.idle() # save power while waiting
                break
        if wlan.isconnected():
            break
        else:
            print('Cannot find network '+wifi_ssid)
            flash_led_to(RED, 1)
    
    if not wlan.isconnected():
        print('Cannot connect to network '+wifi_ssid+'. Quitting!!!')
        sys.exit(1)
    else:
        print('WLAN connection succeeded!')
        flash_led_to(GREEN, 1)
        print (wlan.ifconfig())
Beispiel #7
0
def exp_start():
    global stats
    global detailed_stats
    global run_stats
    wlan = WLAN(mode=WLAN.STA)
    print(ubinascii.hexlify(wlan.mac(), ':').decode())
    if not wlan.isconnected():
        wlan.connect(ssid='rasp', auth=(WLAN.WPA2, 'lalalala'), timeout=5000)
    while not wlan.isconnected():
        machine.idle()
    print("I got IP" + wlan.ifconfig()[0])
    host = wlan.ifconfig()[0]
    port = 8000
    wlan_s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    print("socket created")
    wlan_s.bind((host, port))
    wlan_s.listen(5)
    print("Waiting for initialization...")
    _thread.start_new_thread(receive_stats, ())
    while (True):
        conn, addr = wlan_s.accept()
        print('Got connection from', addr)
        data = conn.recv(512)
        data = str(data)[2:][:-1]
        if (len(data) > 10):
            try:
                (init, ip, pkts) = data.split(":")
                if (init == "init"):
                    pycom.rgbled(red)
                    msg = ip + ":" + pkts
                    run_stats = 0
                    time.sleep(1)
                    lora.init(mode=LoRa.LORA,
                              tx_iq=True,
                              region=LoRa.EU868,
                              frequency=freqs[0],
                              power_mode=LoRa.TX_ONLY,
                              bandwidth=LoRa.BW_125KHZ,
                              sf=12)
                    pkg = struct.pack(_LORA_PKG_FORMAT % len(msg), MY_ID,
                                      len(msg), msg)
                    # lora_sock.send(pkg)
                    for j in range(3):
                        lora_sock.send(pkg)
                        time.sleep(1)
                    lora.init(mode=LoRa.LORA,
                              rx_iq=True,
                              region=LoRa.EU868,
                              frequency=freqs[7],
                              power_mode=LoRa.ALWAYS_ON,
                              bandwidth=LoRa.BW_125KHZ,
                              sf=12)
                    pycom.rgbled(green)
                    run_stats = 1
                    stats = []
                    detailed_stats = []
                    _thread.start_new_thread(receive_stats, ())
            except:
                print("wrong packet format!")
Beispiel #8
0
def connect():
    wlan = WLAN()
    if not wlan.isconnected():
        wlan.connect(_SSID, auth=(WLAN.WPA2, 'phobiccoconut688'), timeout=5000)
        while not wlan.isconnected():
            machine.idle()

    logging('WLAN connection succeeded!')
    logging("My IP address is: {0}".format(wlan.ifconfig()[0]))
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())
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())
Beispiel #11
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())
Beispiel #12
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())
Beispiel #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(config.WIFISSID, config.WIFIPASS)
        while not sta_if.isconnected():
            pass
    print('network config:', sta_if.ifconfig())
Beispiel #14
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()))
Beispiel #15
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())
Beispiel #16
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()
Beispiel #17
0
def connect_to_ap():
    station = WLAN(mode=WLAN.STA)
#    if not station.active():
  #      station.active(True)
    if not station.isconnected():
        print('Connecting....')
        station.connect(config.SSID, auth=(WLAN.WPA2, config.PASSWORD), timeout=5000)
        while not station.isconnected():
            time.sleep(1)
            print('.', end='')
        print("connected")
        print(station.ifconfig())
Beispiel #18
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()
Beispiel #19
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()))
Beispiel #20
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)
Beispiel #21
0
    def __cli_activation_over_wifi(self, activation_info):
        print('Please wait while we try to connect to {}'.format(
            activation_info.get('s')))
        from network import WLAN
        wlan = WLAN(mode=WLAN.STA)
        attempt = 0
        known_nets = [((activation_info['s'], activation_info['p']))]  # noqa

        print_debug(3, 'WLAN connected? {}'.format(wlan.isconnected()))
        while not wlan.isconnected() and attempt < 10:
            attempt += 1
            print_debug(3, "Wifi connection attempt: {}".format(attempt))
            print_debug(3, 'WLAN connected? {}'.format(wlan.isconnected()))
            available_nets = None
            while available_nets is None:
                try:
                    available_nets = wlan.scan()
                    for x in available_nets:
                        print_debug(5, x)
                    time.sleep(3)
                except:
                    pass

            nets = frozenset([e.ssid for e in available_nets])
            known_nets_names = frozenset([e[0] for e in known_nets])
            net_to_use = list(nets & known_nets_names)
            try:
                net_to_use = net_to_use[0]
                pwd = dict(known_nets)[net_to_use]
                sec = [e.sec for e in available_nets
                       if e.ssid == net_to_use][0]  # noqa
                print_debug(
                    99, "Connecting with {} and {}".format(net_to_use, pwd))
                if sec == 0:
                    wlan.connect(net_to_use, timeout=10000)
                else:
                    wlan.connect(net_to_use, (sec, pwd), timeout=10000)
                start_time = time.time()
                while not wlan.isconnected():
                    if time.time() - start_time > timeout:
                        raise TimeoutError(
                            'Timeout trying to connect via WiFi')
                    time.sleep(0.1)
            except Exception as e:
                if str(e) == "list index out of range" and attempt == 3:
                    print("Please review Wifi SSID and password!")
                    wlan.deinit()
                    return None
                elif attempt == 3:
                    print("Error connecting using WIFI: %s" % e)
                    return None
Beispiel #22
0
class ConnectWIFI:
    def __init__(self):
        self.wlan = WLAN(mode=WLAN.STA)

    def connectwifi(self):
        if self.isConnected():
            print("Wifi Connected")
        else:
            self.SSID = config.wifissid
            self.PASSWORD = config.wifipassword
            timeout = time.time() + 10
            self.wlan.connect(self.SSID,
                              auth=(WLAN.WPA, self.PASSWORD),
                              channel=9)
            while not self.wlan.isconnected():
                if time.time() > timeout:
                    pycom.rgbled(config.LED_ERROR)
                    time.sleep(0.5)
                    pycom.rgbled(config.LED_ERROR)
                    machine.reset()
                print(".", end="")
                pycom.rgbled(config.LED_blink_WIFI)
                time.sleep(0.5)
                pycom.rgbled(0x000000)
                time.sleep(0.5)
                machine.idle()  # save power while waiting
            print('.........WiFi connected........')
            print("Wifi Config --> ", self.wlan.ifconfig())

    def isConnected(self):
        if self.wlan.isconnected():
            return True
        else:
            return False

    def deinit(self):
        print('Deinitializing wifi radio')
        self.wlan.deinit()

    def disconnect(self):
        print("disconnecting wifi")
        self.wlan.disconnect()

    def reconnect(self):
        if self.isConnected():
            print("wifi connected")
        else:
            print("Trying to reconnect")
            self.__init__()
            self.connectwifi()
Beispiel #23
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()
Beispiel #24
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
Beispiel #25
0
def connect_wifi_sdk(ssid, pw):
    from network import WLAN
    from network import STA_IF
    import machine

    wlan = WLAN(STA_IF)
    nets = wlan.scan()
    if (wlan.isconnected()):
        wlan.disconnect()
    wlan.connect(ssid, pw)
    while not wlan.isconnected():
        machine.idle()  # save power while waiting
        print('WLAN connection succeeded!')
        break
    print("connected:", wlan.ifconfig())
Beispiel #26
0
class PyWiFi(object):
    def __init__(self, mode, ssid=None, password=None, hidden=False):
        self._ssid = ssid
        self._hidden = hidden

        if mode == WLAN.STA_AP or mode == WLAN.AP:
            self._wlan = WLAN(mode=mode,
                              ssid=ssid,
                              auth=(WLAN.WPA2, password),
                              hidden=hidden)
        else:
            self._wlan = WLAN(mode=mode)

    def connect(self, ssid, password, timeout=5000):
        pycom.heartbeat(False)
        networks = self._wlan.scan()

        for network in networks:
            if network.ssid == ssid:
                print("[" + ssid + "]: connecting...")
                pycom.rgbled(0x110000)

                self._wlan.connect(network.ssid,
                                   auth=(network.sec, password),
                                   timeout=timeout)
                while not self._wlan.isconnected():
                    sleep(0.5)

                print("[" + ssid + "]: connected")
                pycom.rgbled(0x001100)

                break

    def printWLAN(self):
        print(self._wlan.ifconfig())
Beispiel #27
0
    def connect_sta(self,time_out = 120):
        config_dict = self.__get_board_config_js()
        sta_ssid    = config_dict.get("sta_ssid","")
        if len(sta_ssid) <= 0:
            raise Exception("sta ssid not configed")
        sta_pwd     = config_dict.get("sta_pwd","")
        if len(sta_pwd) <= 0:
            raise Exception("sta passworld not configed")
        sta_auth_type = config_dict.get("sta_auth_type","WPA2")

        if sta_auth_type == 'WEP':
            auth_type = 1
        elif sta_auth_type == 'WPA':
            auth_type = 2
        else:
            auth_type = 3
        wlan=WLAN()
        wlan.mode(3)
        wlan.connect(ssid=sta_ssid,auth=(auth_type,sta_pwd))
    
        time_out = int(time_out)
        while not wlan.isconnected():
            if time_out < 0:
                raise Exception("Connect wifi sta timeout")
            time.sleep(1)
            time_out = time_out - 1
    
        print(wlan.ifconfig())
        return
Beispiel #28
0
def MQTTClientInit():
    global mqttmsg
    # wifi configuration
    WIFI_SSID = 'LAPTOP-BHHF3UMN 4817'
    WIFI_PASS = '******'
    def sub_cb(topic, msg):
        print(msg)
    

    wlan = WLAN(mode=WLAN.STA)
    wlan.connect(WIFI_SSID, auth=(WLAN.WPA2, WIFI_PASS), timeout=5000)

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

    client = MQTTClient("lights11", "io.adafruit.com",user="******", password="******", port=1883)

    client.set_callback(sub_cb)
    client.connect()
    client.subscribe(topic="Yunwei/feeds/lights")

    while True:
        print("Sending "+mqttmsg)
        client.publish(topic="Yunwei/feeds/lights", msg=mqttmsg)
        time.sleep(5)
        #print("Sending 222")
        #client.publish(topic="Yunwei/feeds/lights", msg=mqttmsg)
        client.check_msg()
        time.sleep(5)
class wifi_pyboard():
    def __init__(self,
                 server_ssid="USR-WIFI232-604_27BC",
                 connection_timeout=10):
        self.server_ssid = server_ssid
        self.timeout = connection_timeout
        self.wlan = WLAN()

    def connect(self):
        # config as station-mode
        self.wlan.init(mode=WLAN.STA)
        self.wlan.ifconfig(id=0)

        # Scan for an available wifi and connect to server
        network_list = self.wlan.scan()
        for net in network_list:
            try:
                if net.ssid == self.server_ssid:
                    print("Server founded! Connecting...")

                    self.wlan.connect(self.server_ssid, timeout=5000)
                    # wait for connection
                    while not self.wlan.isconnected():
                        # do nothing or save power by idle using machine.idle()
                        machine.idle()

                    print("Connection succeeded!")
                    print(self.wlan.ifconfig())
                else:
                    # If SSID is not "USR-WIFI232-604_27BC", Do nothing.
                    pass

            except Exception as e:
                print("Maybe, access point is not avialable.")
                print("Exception : {}".format(e))
Beispiel #30
0
def main():
    # Use the RGB LED as an indicator of WiFi status
    pycom.heartbeat(False)
    wlan = WLAN()
    if wlan.isconnected():
        pycom.rgbled(0x000f00)
    else:
        pycom.rgbled(0x0f0000)

    # Set up the onboard ADC and establish a channel for each thermistor
    adc = ADC()
    adc.vref(config.VREF_ACTUAL_IN_MILLIAMPS)
    oven_channel = adc.channel(pin=config.OVEN_THERM_ADC_PIN, attn=ADC.ATTN_11DB)
    food_channel = adc.channel(pin=config.FOOD_THERM_ADC_PIN, attn=ADC.ATTN_11DB)

    # Modify config.py with your thermistor values from the datasheet
    oven = Thermistor(oven_channel,
                      config.THERM_NOMINAL_TEMP,
                      config.THERM_NOMINAL_RES,
                      config.THERM_BETA,
                      config.SERIES_RESISTOR_1,
                      12.0)
    food = Thermistor(food_channel,
                      config.THERM_NOMINAL_TEMP,
                      config.THERM_NOMINAL_RES,
                      config.THERM_BETA,
                      config.SERIES_RESISTOR_2,
                      12.0)

    dinner_tracker = LosantDinnerTracker(oven, food, status_led=config.STATUS_LED_PIN)
    dinner_tracker.start()
Beispiel #31
0
def wifi_connect():
    global client, wlan

    wlan = WLAN(mode=WLAN.STA)
    wlan.disconnect()

    networks = wlan.scan()
    for net in networks:
        if net.ssid == WIFI_AP['name']:
            print('Wifi connecting...')
            wlan.connect(ssid=net.ssid, auth=(net.sec, WIFI_AP['pass']), timeout=40)
            while not wlan.isconnected():
                idle()
                sleep(1)
            break
    else:
        return False

    try:
        print('MQTT connecting...')
        client = MQTTClient(client_id="5bc8d724c03f971859b7747b", server="things.ubidots.com", user="******", password="******", port=1883)
        #client.set_callback(sub_cb)
        if client.connect() == -1:
            return False
        else:
            return True
        #client.subscribe(topic="youraccount/.../...")
    except Exception as e:
        return False
Beispiel #32
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
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;
Beispiel #34
0
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()
Beispiel #35
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])
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
Beispiel #37
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')
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
Beispiel #39
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
Beispiel #40
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)
Beispiel #41
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 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)
Beispiel #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)
Beispiel #44
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)
            ))
Beispiel #45
0
from network import WLAN
wlan = WLAN() 					# get current object, without changing the mode

# Settings for TP-LINK home network
KEY = ''
IP = '192.168.1.253'			# WiPy Fixed IP address
GATEWAY = '192.168.1.1'			# IP address of gateway
DNS = '192.168.1.1'				# IP address of DNS
NETMASK = '255.255.255.0'		# Netmask for this subnet

if machine.reset_cause() != machine.SOFT_RESET:
	print('Switching to Wifi Device Mode')
	wlan.init(WLAN.STA)
	wlan.ifconfig(config=(IP, NETMASK, GATEWAY, DNS))
	
if not wlan.isconnected():
	print('Attempting to connect to WiFi', end=' ')
	nets = wlan.scan()
	for net in nets:
		if net.ssid == 'Robotmad':
			KEY = 'mou3se43'
			break
		elif net.ssid == 'CoderDojo':
			KEY = 'coderdojo'
			break
	if KEY != '':
		print(net.ssid, end=" ")
		wlan.connect(net.ssid, auth=(net.sec, KEY), timeout=10000)
	if wlan.isconnected():
		print('Connected')
		tim_a.freq(10)
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)
Beispiel #47
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')
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)
Beispiel #49
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()
Beispiel #50
0
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()
wifi.connect(testconfig.wlan_ssid, auth=testconfig.wlan_auth, timeout=0)
print(time.ticks_ms() - t0 < 500)

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

# test init again
wifi.init(WLAN.AP, ssid='www.wipy.io', auth=None, channel=5, antenna=WLAN.INT_ANT)

print(len(wifi.mac()) == 6)