Exemplo n.º 1
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!")
Exemplo n.º 2
0
from network import WLAN
import ubinascii
wl = WLAN()
ubinascii.hexlify(wl.mac())[:6] + 'FFFE' + ubinascii.hexlify(wl.mac())[6:]
Exemplo n.º 3
0
wlan = WLAN(mode=WLAN.STA)

pycom.rgbled(0xFF8C00)

wlan.connect(ssid=SSID, auth=(WIFI_SECURITY, WIFI_PASSWORD))
print('Connecting to Wifi')

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

print('Wifi connection succeded!')

pycom.rgbled(0xFF00FF)
print('Connecting to MQTT...\n')
client_id = 'pytrack_{}'.format(hexlify(wlan.mac()).decode('utf-8'))

pycom.rgbled(0x001400)

py = Pytrack()
li = LIS2HH12(py)

# after 240 seconds of waiting without a GPS fix it will
# return None, None
gnss = L76GNSS(py, timeout=10)

while True:
    pycom.rgbled(0x000014)

    print('\n\n** 3-Axis Accelerometer (LIS2HH12)')
    acceleration = li.acceleration()
Exemplo n.º 4
0
from network import WLAN
import binascii
wl = WLAN()
gate_id = binascii.hexlify(wl.mac())[:6] + 'FFFE' + binascii.hexlify(wl.mac())[6:]
print(gate_id)
Exemplo n.º 5
0
from network import WLAN
import binascii
wl = WLAN()
x = binascii.hexlify(wl.mac())[:6] + 'FFFE' + binascii.hexlify(wl.mac())[6:]
print(x)
Exemplo n.º 6
0
wlan.connect(config.WIFI_SSID, auth=(None, config.WIFI_PASS), timeout=5000)
while not wlan.isconnected():
    time.sleep(0.5)
print('WLAN connection succeeded!')

time.sleep(2)
gc.enable

# setup rtc
rtc = machine.RTC()
rtc.ntp_sync("pool.ntp.org")
utime.sleep_ms(750)
print(rtc.now())

# get MAC address as the device ID
deviceID = binascii.hexlify(wlan.mac())

#py = Pytrack()
#l76 = L76GNSS(py, timeout=30)


# user specified callback function
def customCallback(client, userdata, message):
    print("Received a new message: ")
    print(message.payload)
    print("from topic: ")
    print(message.topic)
    print("--------------\n\n")


# configure the MQTT client
Exemplo n.º 7
0
from network import WLAN
from mqtt import MQTTClient
import machine
import time
import ubinascii
import configMQTT


def settimeout(duration):
    pass


wlan = WLAN(mode=WLAN.STA)

# classical mac writing convention
print("mac address = " + ubinascii.hexlify(wlan.mac().sta_mac, ':').decode())
strID = ubinascii.hexlify(wlan.mac().sta_mac, '').decode()
# hostname from the 4 last characters
hostNameID = ("N" + strID[-5:]).upper()
print("hostname = " + hostNameID)

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

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

print("Connected to Wifi\n")
client = MQTTClient("demo", configMQTT.MQTT_SERVER, port=1883)
client.settimeout = settimeout
Exemplo n.º 8
0
class WifiManager:
    def __init__(self, jsonfile):
        # Load configuration from config JSON file.
        # wificonfig.json contans the network settings
        # STATIC_IP is 'None' or empty string -> use dynamic IP
        self._config = self.readjson(jsonfile)

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

    def readjson(self, jsonfile):
        """readjson(file) - returns the contents of file in JSON-format"""
        with open(jsonfile, 'r') as infile:
            config = json.load(infile)
        if USE_DEBUG:
            print('WifiManager::JSON settings: {}'.format(config))
        return config

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

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

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

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

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

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

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

    # wrapper for disabling Wifi radio
    def deinit(self):
        """deinit() - disable Wifi radio"""
        self._wlan.deint()  # pycom
        if USE_DEBUG:
            print('WifiManager::Wifi radio off')

    # wrapper for network scan
    def scan(self):
        """scan() - Performs a network scan and returns a list
        of named tuples with (ssid, bssid, sec, channel, rssi)
        """
        return self._wlan.scan()

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

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

    def change_access(self, user=None, passwrd=None):
        """change_access - change password for telnet and ftp access"""
        if (user is None) or (passwrd is None):
            print('WifiManager:: username and password must be specified')
            return

        server = Server()  # from network
        # disable the server
        server.deinit()
        # enable the server again with new credentials
        # for example: remote access, ftp and telnet, not USB
        server.init(login=(user, passwrd), timeout=600)
        if USE_DEBUG:
            print('WifiManager::password {} is changed...'.format(user))

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

    @property
    def mac(self):
        """returns MAC-address of device"""
        mac = hexlify(self._wlan.mac(), ':').decode()  # pycom
        # return (mac) # lower case
        return mac.upper()
Exemplo n.º 9
0
from network import WLAN
import binascii
wl = WLAN()
print("Gateway EUI: {}".format(
    binascii.hexlify(wl.mac())[:6] + 'fffe' + binascii.hexlify(wl.mac())[6:]))
Exemplo n.º 10
0
class MicroWifi:

    # ============================================================================
    # ===( Constants )============================================================
    # ============================================================================

    _ETH_AP = 1
    _ETH_STA = 0
    _IP_NONE = '0.0.0.0'
    _DEFAULT_AUTH_TYPE = WLAN.WPA2
    _AP_MASK = '255.255.255.0'
    _DEFAULT_TIMEOUT_SEC = 10

    # ============================================================================
    # ===( Utils  )===============================================================
    # ============================================================================

    @staticmethod
    def _mac2Str(binMac):
        return hexlify(binMac, ':').decode().upper()

    # ----------------------------------------------------------------------------

    def _setAPInfos(self,
                    ssid=None,
                    key=None,
                    ip=None,
                    mask=None,
                    gateway=None,
                    dns=None):
        self._apInfos = {
            'ssid': ssid,
            'key': key,
            'ip': ip,
            'mask': mask,
            'gateway': gateway,
            'dns': dns
        }

    # ----------------------------------------------------------------------------

    def _setConnectionInfos(self,
                            bssid=None,
                            ssid=None,
                            key=None,
                            ip=None,
                            mask=None,
                            gateway=None,
                            dns=None):
        self._connInfos = {
            'macBssid': bssid,
            'ssid': ssid,
            'key': key,
            'ip': ip,
            'mask': mask,
            'gateway': gateway,
            'dns': dns
        }

    # ----------------------------------------------------------------------------

    def _openConf(self):
        try:
            with open(self._filePath, 'r') as jsonFile:
                self._confObj = load(jsonFile)
        except:
            self._confObj = {}
        if self._confObj.get('STA', None) is None:
            self._confObj['STA'] = {}

    # ----------------------------------------------------------------------------

    def _writeConf(self):
        try:
            jsonStr = dumps(self._confObj)
            try:
                mkdir(self._confPath)
            except:
                pass
            jsonFile = open(self._filePath, 'wb')
            jsonFile.write(jsonStr)
            jsonFile.close()
            return True
        except:
            return False

    # ============================================================================
    # ===( Constructor )==========================================================
    # ============================================================================

    def __init__(self,
                 confName="wifi",
                 confPath="/flash/conf",
                 useExtAntenna=False):
        self._confPath = confPath
        self._filePath = '%s/%s.json' % (confPath, confName)
        self._wlan = WLAN()
        self._antenna = WLAN.EXT_ANT if useExtAntenna else WLAN.INT_ANT
        self._openConf()
        self._setAPInfos()
        self._setConnectionInfos()
        self._wlan.init(antenna=self._antenna)
        self.DisableRadio()

    # ============================================================================
    # ===( Functions )============================================================
    # ============================================================================

    def DisableRadio(self):
        self.CloseAccessPoint()
        self.CloseConnectionToAP()
        self._wlan.deinit()

    # ----------------------------------------------------------------------------

    def GetMACAddr(self):
        return self._mac2Str(self._wlan.mac())

    # ----------------------------------------------------------------------------

    def GetAPInfos(self):
        if not self.IsAccessPointOpened():
            self._setAPInfos()
        return self._apInfos

    # ----------------------------------------------------------------------------

    def GetConnectionInfos(self):
        if not self.IsConnectedToAP():
            self._setConnectionInfos()
        return self._connInfos

    # ----------------------------------------------------------------------------

    def ScanAP(self):
        try:
            if self._wlan.mode() == WLAN.STA:
                self._wlan.init(antenna=self._antenna)
            return self._wlan.scan()
        except:
            return ()

    # ----------------------------------------------------------------------------

    def OpenAccessPoint(self,
                        ssid,
                        key=None,
                        ip='192.168.0.254',
                        autoSave=True):
        if ssid and ip:
            try:
                self._wlan.ifconfig(id=self._ETH_AP,
                                    config=(ip, self._AP_MASK, ip, ip))
                auth = (self._DEFAULT_AUTH_TYPE, key) if key else None
                self._wlan.init(mode=WLAN.STA_AP,
                                ssid=ssid,
                                auth=auth,
                                antenna=self._antenna)
                print("WIFI ACCESS POINT OPENED :")
                print("  - MAC address  : %s" % self.GetMACAddr())
                print("  - Network SSID : %s" % ssid)
                print("  - IP address   : %s" % ip)
                print("  - Mask         : %s" % self._AP_MASK)
                print("  - Gateway IP   : %s" % ip)
                print("  - DNS server   : %s" % ip)
                if autoSave:
                    self._confObj['AP'] = {'ssid': ssid, 'key': key, 'ip': ip}
                    self._writeConf()
                self._setAPInfos(ssid, key, ip, self._AP_MASK, ip, ip)
                return True
            except:
                self.CloseAccessPoint()
        return False

    # ----------------------------------------------------------------------------

    def OpenAccessPointFromConf(self):
        try:
            ssid = self._confObj['AP']['ssid']
            key = self._confObj['AP']['key']
            ip = self._confObj['AP']['ip']
            return self.OpenAccessPoint(ssid, key, ip, False)
        except:
            return False

    # ----------------------------------------------------------------------------

    def RemoveAccessPointFromConf(self):
        try:
            del self._confObj['AP']
            return self._writeConf()
        except:
            return False

    # ----------------------------------------------------------------------------

    def CloseAccessPoint(self):
        try:
            ip = self._IP_NONE
            self._wlan.mode(WLAN.STA)
            self._wlan.ifconfig(id=self._ETH_AP, config=(ip, ip, ip, ip))
            return True
        except:
            return False

    # ----------------------------------------------------------------------------

    def IsAccessPointOpened(self):
        return self._wlan.ifconfig(self._ETH_AP)[0] != self._IP_NONE

    # ----------------------------------------------------------------------------

    def ConnectToAP(self,
                    ssid,
                    key=None,
                    macBssid=None,
                    timeoutSec=None,
                    autoSave=True):
        if ssid:
            if not key:
                key = ''
            if not timeoutSec:
                timeoutSec = self._DEFAULT_TIMEOUT_SEC
            timeout = timeoutSec * 1000
            if self._wlan.mode() == WLAN.STA:
                self._wlan.init(antenna=self._antenna)
            print("TRYING TO CONNECT WIFI TO AP %s..." % ssid)
            for ap in self.ScanAP():
                if ap.ssid == ssid and \
                   ( not macBssid or self._mac2Str(ap.bssid) == macBssid ) :
                    self._wlan.connect(ssid=ap.ssid,
                                       bssid=ap.bssid,
                                       auth=(self._DEFAULT_AUTH_TYPE, key),
                                       timeout=timeout)
                    t = ticks_ms()
                    while ticks_diff(t, ticks_ms()) < timeout:
                        sleep(0.100)
                        if self.IsConnectedToAP():
                            bssid = self._mac2Str(ap.bssid)
                            staCfg = self._wlan.ifconfig(id=self._ETH_STA)
                            ip = staCfg[0]
                            mask = staCfg[1]
                            gateway = staCfg[2]
                            dns = staCfg[3]
                            print("WIFI CONNECTED TO AP :")
                            print("  - MAC address   : %s" % self.GetMACAddr())
                            print("  - Network BSSID : %s" % bssid)
                            print("  - Network SSID  : %s" % ssid)
                            print("  - IP address    : %s" % ip)
                            print("  - Mask          : %s" % mask)
                            print("  - Gateway IP    : %s" % gateway)
                            print("  - DNS server    : %s" % dns)
                            if autoSave:
                                sta = {
                                    'ssid': ssid,
                                    'key': key,
                                }
                                self._confObj['STA'][bssid] = sta
                                self._writeConf()
                            self._setConnectionInfos(bssid, ssid, key, ip,
                                                     mask, gateway, dns)
                            return True
                    self.CloseConnectionToAP()
                    break
            print("FAILED TO CONNECT WIFI TO AP %s" % ssid)
        return False

    # ----------------------------------------------------------------------------

    def ConnectToAPFromConf(self, bssidMustBeSame=False, timeoutSec=None):
        if self._wlan.mode() == WLAN.STA:
            self._wlan.init(antenna=self._antenna)
        for ap in self.ScanAP():
            for bssid in self._confObj['STA']:
                macBssid = self._mac2Str(ap.bssid) if bssidMustBeSame else None
                if self._confObj['STA'][bssid]['ssid'] == ap.ssid and \
                   ( not macBssid or bssid == macBssid ) :
                    if self.ConnectToAP(ap.ssid,
                                        self._confObj['STA'][bssid]['key'],
                                        macBssid, timeoutSec, False):
                        return True
                    break
        return False

    # ----------------------------------------------------------------------------

    def RemoveConnectionToAPFromConf(self, ssid, macBssid=None):
        try:
            changed = False
            for bssid in list(self._confObj['STA']):
                if self._confObj['STA'][bssid]['ssid'] == ssid and \
                   ( not macBssid or bssid == macBssid ) :
                    del self._confObj['STA'][bssid]
                    changed = True
            if changed:
                return self._writeConf()
        except:
            pass
        return False

    # ----------------------------------------------------------------------------

    def CloseConnectionToAP(self):
        try:
            self._wlan.disconnect()
            self._wlan.ifconfig(id=self._ETH_STA, config='dhcp')
            return True
        except:
            return False

    # ----------------------------------------------------------------------------

    def IsConnectedToAP(self):
        return self._wlan.ifconfig(self._ETH_STA)[0] != self._IP_NONE

    # ----------------------------------------------------------------------------

    def ResolveIPFromHostname(self, hostname):
        originalMode = self._wlan.mode()
        if originalMode == WLAN.STA_AP:
            self._wlan.mode(WLAN.STA)
        try:
            ipResolved = getaddrinfo(hostname, 0)[0][-1][0]
        except:
            ipResolved = None
        if originalMode == WLAN.STA_AP:
            self._wlan.mode(WLAN.STA_AP)
        return ipResolved if ipResolved != self._IP_NONE else None

    # ----------------------------------------------------------------------------

    def InternetAccessIsPresent(self):
        return (self.ResolveIPFromHostname('iana.org') is not None)

    # ----------------------------------------------------------------------------

    def WaitForInternetAccess(self, timeoutSec=None):
        if not timeoutSec:
            timeoutSec = self._DEFAULT_TIMEOUT_SEC
        timeout = timeoutSec * 1000
        t = ticks_ms()
        while ticks_diff(t, ticks_ms()) < timeout:
            sleep(0.100)
            if self.InternetAccessIsPresent():
                return True
        return False
Exemplo n.º 11
0
import socket
import time
import pycom
import uos
import binascii
import struct
import machine
import sys
import network
from network import LoRa
from network import WLAN
from machine import Timer
from messageLoRa import messageLoRa
wlan = WLAN()
mySSID="WGW_lopy_"+binascii.hexlify(wlan.mac().decode('utf-8')).decode()
print("My AP name is : "+mySSID)
# configure the WLAN subsystem in station mode (the default is AP)
wlan.init(mode=WLAN.STA_AP, ssid=mySSID,auth=(WLAN.WPA2,'www.python.com'), channel=7, antenna=WLAN.INT_ANT)
#STA config
#wlan.ifconfig(id=0,config='dhcp')
#AP config
#wlan.ifconfig(id=1,config="dhcp")
print("My ip on the network [AP] is : "+wlan.ifconfig(id=1)[0])
print("My ip on the network [STA] is : "+wlan.ifconfig(id=0)[0])
# Create a TCP/IP socket
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

# Bind the socket to the port
server_address = ('192.168.4.1', 5000)
print('starting up on {} port {}'.format(*server_address))
Exemplo n.º 12
0
except:
    pass
try:
    # v1.20.1.r1
    print("wifi_ssid_sta", pycom.wifi_ssid_sta())
    print("wifi_pwd_sta", pycom.wifi_pwd_sta())
    print("wifi_ssid_ap", pycom.wifi_ssid_ap())
    print("wifi_pwd_ap", pycom.wifi_pwd_ap())
except:
    pass


print("===== wlan =======================================")
wlan = WLAN()
try:
    print("sta_mac", binascii.hexlify(wlan.mac().sta_mac))
    print("ap_mac", binascii.hexlify(wlan.mac().ap_mac))
except:
    print("mac", binascii.hexlify(wlan.mac()))
print("is_connected", wlan.isconnected())
print("ssid", wlan.ssid())
print("bssid", binascii.hexlify(wlan.bssid()))
try:
    print("country", wlan.country())
except:
    pass
print("ifconfig", wlan.ifconfig())
print('IP:', wlan.ifconfig()[0])
print("mode", wlan.mode(), end=' ')
print_wifi_mode(wlan.mode())
print()
Exemplo n.º 13
0
import math

pycom.heartbeat(False)
off = 0x000000
red = 0x7f0000
green = 0x007f00
blue = 0x00007f
white = 0xFFFAFA

wlan = WLAN(mode=WLAN.STA)
if not wlan.isconnected():
    wlan.connect('ssid', auth=(WLAN.WPA2, 'password'), timeout=5000)
    while not wlan.isconnected():
        machine.idle()

print(ubinascii.hexlify(wlan.mac(), ':').decode())
print("I got IP" + wlan.ifconfig()[0])

_LORA_PKG_FORMAT = "!BB%ds"
_LORA_INIT_FORMAT = "!BBs"
_LORA_RCV_PKG_FORMAT = "!BB%ds"
MY_ID = 0x01
my_sf = int(MY_ID) + 6
my_bw_index = 2
(guard, sync_method, sync_rate) = (40, 1, 1)
freqs = [865000000, 865600000, 866200000, 866800000, 867400000,
         868000000]  # my channels
airtime = [[0.174336, 0.087168, 0.043584], [0.307712, 0.153856, 0.076928],
           [0.553984, 0.276992, 0.138496], [1.026048, 0.513024, 0.256512],
           [2.215936, 0.944128, 0.472064], [3.940352, 1.724416, 0.862208]]
if (my_bw_index == 0):
Exemplo n.º 14
0
from network import WLAN
import binascii
wl = WLAN()
#chirpstack config FFEE
binascii.hexlify(wl.mac())[:6] + 'FFEE' + binascii.hexlify(wl.mac())[6:]
#TTN config FFFE
#binascii.hexlify(wl.mac())[:6] + 'FFFE' + binascii.hexlify(wl.mac())[6:]
Exemplo n.º 15
0
class WiFiManager:
    def __init__(self, manager, settings):
        self.manager = manager
        self.settings = settings

        # WIFI settings.
        self.stations = self.settings.get('networking.wifi.stations')
        self.station = None

    def start(self):
        """
        https://docs.pycom.io/tutorials/all/wlan.html
        https://github.com/pycom/pydocs/blob/master/firmwareapi/pycom/network/wlan.md
        """

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

        #if machine.reset_cause() == machine.SOFT_RESET:
        #   print("WiFi STA: Network connection after SOFT_RESET.")
        #    self.print_short_status()
        #    # Inform about networking status.
        #    self.print_address_status()
        #    return True

        # Save the default ssid and auth for restoring AP mode later
        original_ssid = self.station.ssid()
        original_auth = self.station.auth()

        # Inform about networking status.
        self.print_address_status()

        # Setup network interface.
        self.station.init()

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

            log.info(
                "WiFi STA: Network connection already established, will skip scanning and resume connectivity."
            )
            self.print_short_status()

            # Give system some breath.
            time.sleep(0.25)

            # Inform about networking status.
            self.print_address_status()

            return True

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

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

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

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

        # Todo: Reenable WiFi AP mode in the context of an "initial configuration" mode.
        """
        log.info('WiFi: Switching to AP mode')
        # WLAN.AP, original_ssid, original_auth, WLAN.INT_ANT
        # TOOD: Make default channel configurable
        self.station.init(mode=WLAN.AP, ssid=original_ssid, auth=original_auth, channel=6, antenna=WLAN.INT_ANT)
        """

    def power_off(self):
        """
        Power off all radio peripherals.

        - https://forum.pycom.io/topic/563/disabling-wifi-on-lopy
        - https://github.com/Hiverize/FiPy/commit/b6b15677
        """

        # WiFi
        if self.station:
            try:
                log.info('Turning off WiFi')
                self.station.deinit()
            except:
                log.exception('Turning off WiFi failed')

    def connect_stations(self, network_names):

        # Prepare information about known WiFi networks.
        network_map = {station['ssid']: station for station in self.stations}

        for network_name in network_names:
            try:
                # All the configuration details for this network.
                # {
                #    'ssid': 'FooBar',
                #    'password': '******',
                #    'ifconfig': ('192.168.42.42', '255.255.255.0', '192.168.42.1', '192.168.42.1'),
                # }
                network_selected = network_map[network_name]
                if self.connect_station(network_selected):
                    break

            except Exception:
                log.exception(
                    'WiFi STA: Connecting to "{}" failed'.format(network_name))

        if not self.station.isconnected():

            self.forget_network(network_name)

            message = 'WiFi STA: Connecting to any network candidate failed'
            description = 'Please check your WiFi configuration for one of the ' \
                          'station candidates {}.'.format(len(network_names))
            log.error('{}. {}'.format(message, description))
            log.warning(
                'Todo: We might want to switch to AP mode here or alternatively '
                'buffer telemetry data to flash to be scheduled for transmission later.'
            )
            raise WiFiException(message)

    def connect_station(self, network):

        network_name = network['ssid']

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

        auth_mode = self.get_auth_mode(network_name)

        log.info(
            'WiFi STA: Attempt connecting to network "{}" with auth mode "{}"'.
            format(network_name, auth_mode))

        password = network['password']

        # TODO: Optionally, configure hostname.
        # https://docs.micropython.org/en/latest/library/network.WLAN.html
        # https://github.com/pycom/pycom-micropython-sigfox/pull/165
        # https://forum.pycom.io/topic/3326/new-firmware-release-v1-18-0
        if 'dhcp_hostname' in network:
            if hasattr(self.station, 'config'):
                log.ingo('WiFi STA: Using dhcp_hostname "{}"'.format(
                    network['dhcp_hostname']))
                self.station.config(dhcp_hostname=network['dhcp_hostname'])
            else:
                log.error('Could not set hostname on older MicroPython')

        # Optionally, configure static IP address.
        if 'ifconfig' in network:
            log.info(
                'WiFi STA: Using static network configuration "{}"'.format(
                    network_name))
            self.station.ifconfig(config=network['ifconfig'])

        # Obtain timeout value.
        network_timeout = network.get('timeout', 15.0)

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

        # Connect to WiFi station.
        log.info(
            'WiFi STA: Starting connection to "{}" with timeout of {} seconds'.
            format(network_name, network_timeout))
        self.station.connect(network_name, (auth_mode, password),
                             timeout=int(network_timeout * 1000))

        # Wait for station network to arrive.
        # ``isconnected()`` returns True when connected to a WiFi access point *and* having a valid IP address.
        retries = int(network_timeout * network_poll_interval)
        while not self.station.isconnected() and retries > 0:

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

            # Save power while waiting.
            machine.idle()

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

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

        if not self.station.isconnected():
            raise WiFiException(
                'WiFi STA: Unable to connect to "{}"'.format(network_name))

        # Inform about networking status.
        self.print_short_status()
        self.print_address_status()

        return True

    def scan_stations(self):

        self.manager.device.feed_watchdog()

        # Inquire visible networks.
        log.info("WiFi STA: Scanning for networks")
        stations_available = self.station.scan()
        networks_found = frozenset([e.ssid for e in stations_available])

        # Print names/SSIDs of networks found.
        log.info("WiFi STA: Networks available: %s", list(networks_found))

        return stations_available

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

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

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

    def get_auth_mode(self, network_name):

        # NVRAM key for storing auth mode per network. Maximum of 15 characters.
        auth_mode_nvs_key = self.auth_mode_nvs_key(network_name)

        # Get WiFi STA auth mode from NVRAM.
        try:
            import pycom
            auth_mode = pycom.nvs_get(auth_mode_nvs_key)
            log.info('WiFi STA: Auth mode from NVRAM with key=%s, value=%s',
                     auth_mode_nvs_key, auth_mode)
        except:
            auth_mode = None

        # Fall back to find out WiFi STA auth mode by network scan.
        if auth_mode is None:
            log.info(
                'WiFi STA: Unknown auth mode for network "%s", invoking WiFi scan',
                network_name)
            wifi_neighbourhood = self.scan_stations()

            #log.info('WiFi STA: Neighbourhood is %s', wifi_neighbourhood)
            for e in wifi_neighbourhood:
                if e.ssid == network_name:
                    auth_mode = e.sec
                    break

            if not auth_mode:
                message = 'WiFi STA: Unable to inquire auth mode for network "{}"'.format(
                    network_name)
                log.warning(message)
                raise WiFiException(message)

            log.info(
                'WiFi STA: Storing auth mode into NVRAM with key=%s, value=%s',
                auth_mode_nvs_key, auth_mode)
            try:
                import pycom
                pycom.nvs_set(auth_mode_nvs_key, auth_mode)
            except:
                log.exception('WiFi STA: Storing auth mode into NVRAM failed')

        return auth_mode

    def auth_mode_nvs_key(self, ssid):
        """
        Hack to get a short representation of a WiFi SSID in order to
        squeeze it into a NVRAM key with a maximum length of 15 characters.

        Fixme: Review this.
        """
        import hashlib
        import ubinascii
        digest = ubinascii.hexlify(hashlib.sha512(ssid).digest()).decode()
        identifier = 'wa.{}'.format(digest[15:27])
        return identifier

    def forget_network(self, network_name):
        log.info('WiFi STA: Forgetting NVRAM data for network "{}"'.format(
            network_name))
        auth_mode_nvs_key = self.auth_mode_nvs_key(network_name)
        try:
            import pycom
            pycom.nvs_erase(auth_mode_nvs_key)
        except:
            pass

    def print_short_status(self):
        log.info('WiFi STA: Connected to "{}" with IP address "{}"'.format(
            self.get_ssid(), self.get_ip_address()))

    def print_address_status(self):
        mac_address = self.humanize_mac_addresses(self.station.mac())
        ifconfig = self.station.ifconfig()
        log.info('WiFi STA: Networking address (MAC): %s', mac_address)
        log.info('WiFi STA: Networking address (IP):  %s', ifconfig)

    def humanize_mac_addresses(self, mac):
        info = {}
        if hasattr(mac, 'sta_mac'):
            info['sta_mac'] = format_mac_address(
                binascii.hexlify(mac.sta_mac).decode())
        if hasattr(mac, 'ap_mac'):
            info['ap_mac'] = format_mac_address(
                binascii.hexlify(mac.ap_mac).decode())
        return info

    def print_metrics(self):
        metrics = SystemWiFiMetrics(self.station).read()
        log.info('WiFi STA: Metrics: %s', metrics)
Exemplo n.º 16
0
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)

# next ones MUST raise
try:
    wifi.init(mode=12345)
except:
    print('Exception')

try:
    wifi.init(1, mode=WLAN.AP)
except:
    print('Exception')

try:
    wifi.init(mode=WLAN.AP, ssid=None)
except:
Exemplo n.º 17
0
class WifiManager:
    def __init__(self, known_nets):
        self._known_nets = known_nets
        # create network in STAtion mode
        # pycom: device always starts up in AP-mode
        #self._wl = WLAN()
        #self._wl.mode(WLAN.STA)

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

    # 2019-1203 new, due to Exception error in legacy WifiManager
    # pre-condition: self._known_nets is not None
    # post-condition: self._wl is created
    # returns: IP
    # URL: https://docs.pycom.io/tutorials/all/wlan/
    def connect(self):
        """connect() - connects device according to network parameters in JSON-file."""
        if machine.reset_cause() != machine.SOFT_RESET:
            # from network import WLAN
            self._wl = WLAN()
            self._wl.mode(WLAN.STA)
            original_ssid = self._wl.ssid()
            original_auth = self._wl.auth()

            print_debug("Wifimanager - scanning for known wifi nets...")
            available_nets = self._wl.scan()
            nets = frozenset([e.ssid for e in available_nets])

            known_nets_names = frozenset([key for key in self._known_nets])
            net_to_use = list(nets & known_nets_names)
            print_debug("Wifimanager - SSID to use...{}".format(net_to_use))
            try:
                net_to_use = net_to_use[0]
                print_debug("Wifimanager - net to use...{}".format(net_to_use))
                net_properties = self._known_nets[net_to_use]
                pwd = net_properties['pwd']
                sec = [e.sec for e in available_nets
                       if e.ssid == net_to_use][0]
                print_debug(
                    "Wifimanager - net_properties...{}".format(net_properties))
                if 'wlan_config' in net_properties:
                    print_debug("Wifimanager - wlan_config...{}".format(
                        net_properties['wlan_config']))
                    self._wl.ifconfig(config=net_properties['wlan_config'])
                self._wl.connect(net_to_use, (sec, pwd), timeout=10000)
                ip = self.wait_for_networking(1)
                self._ssid = net_to_use
                print_debug("Connected to " + net_to_use +
                            " with IP address:" + ip)

            except Exception as e:
                print(
                    "Failed to connect to any known network, going into AP mode"
                )
                self._wl.init(mode=WLAN.AP,
                              ssid=original_ssid,
                              auth=original_auth,
                              channel=6,
                              antenna=WLAN.INT_ANT)
                self._ssid = None

        else:
            print_debug("Already connected to " + net_to_use +
                        " with IP address:" + self._wl.ifconfig()[0])

        return self._wl.ifconfig()[0]

    def wait_for_networking(self, dt=1):
        """ wait unitil network is connected and returns IP"""
        station = self._wl  # network.WLAN(mode=network.WLAN.STA)
        while not station.isconnected():
            time.sleep(dt)
            machine.idle()
        ip = station.ifconfig()[0]
        return ip

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

    # wrapper for disabling Wifi radio
    def deinit(self):
        """deinit() - disable Wifi radio"""
        self._wl.deint()  # pycom
        print_debug('WifiManager::Wifi radio off')

    # wrapper for network scan
    def scan(self):
        """scan() - Performs a network scan and returns a list
        of named tuples with (ssid, bssid, sec, channel, rssi)
        """
        return self._wl.scan()

    def change_access(self, user=None, passwrd=None):
        """change_access - change password for telnet and ftp access"""
        if (user is None) or (passwrd is None):
            print('WifiManager:: username and password must be specified')
            return

        server = Server()  # from network
        # disable the server
        server.deinit()
        # enable the server again with new credentials
        # for ftp and telnet, not USB
        server.init(login=(user, passwrd), timeout=600)
        print_debug('WifiManager::password {} is changed...'.format(user))

    # wrappers for wlan settings.
    @property
    def ssid(self):
        """ ssid() - returns SSID of connected Wifi network"""
        return self._ssid

    @property
    def isconnected(self):
        """isconnected() - returns if connected to Wifi (True)
        or not (False)"""
        return self._wl.isconnected()

    @property
    def ip(self):
        """ip() - returns IP of device on connected Wifi network"""
        return self._wl.ifconfig()[0]

    @property
    def mac(self):
        """returns MAC-address of device"""
        mac = hexlify(self._wl.mac(), ':').decode()  # pycom
        # return (mac) # lower case
        return mac.upper()

    # ================================================
    # legacy methods
    # ================================================
    import json

    def __readjson(self, jsonfile):
        """readjson(file) - returns the contents of file in JSON-format"""
        with open(jsonfile, 'r') as infile:
            config = json.load(infile)
        if USE_DEBUG:
            print('WifiManager::JSON settings: {}'.format(config))
        return config
Exemplo n.º 18
0
'''

import machine
import os
from network import WLAN

mch = os.uname().machine
if not 'LaunchPad' in mch and not 'WiPy' in mch:
    raise Exception('Board not supported!')

wifi = WLAN()

print(machine)
machine.idle()
print(machine.freq() == (80000000, ))
print(machine.unique_id() == wifi.mac())

machine.main('main.py')

rand_nums = []
for i in range(0, 100):
    rand = machine.rng()
    if rand not in rand_nums:
        rand_nums.append(rand)
    else:
        print('RNG number repeated')
        break

for i in range(0, 10):
    machine.idle()
Exemplo n.º 19
0
]
index = 0
slot = {}
KEY = {}
if (my_bw_index == 0):
    my_bw = LoRa.BW_125KHZ
    my_bw_plain = 125
elif (my_bw_index == 1):
    my_bw = LoRa.BW_250KHZ
    my_bw_plain = 250
elif (my_bw_index == 2):
    my_bw = LoRa.BW_500KHZ
    my_bw_plain = 500

wlan = WLAN(mode=WLAN.STA)
print("My MAC address is:", ubinascii.hexlify(wlan.mac(), ':').decode())
if not wlan.isconnected():
    wlan.connect('rasp', auth=(WLAN.WPA2, 'lalalala'), timeout=5000)
    while not wlan.isconnected():
        machine.idle()
print("I got IP" + wlan.ifconfig()[0])


# this is borrowed from LoRaSim (https://www.lancaster.ac.uk/scc/sites/lora/lorasim.html)
def airtime_calc(sf, cr, pl, bw):
    H = 0  # implicit header disabled (H=0) or not (H=1)
    DE = 0  # low data rate optimization enabled (=1) or not (=0)
    Npream = 8
    if bw == 125 and sf in [11, 12]:
        # low data rate optimization mandated for BW125 with SF11 and SF12
        DE = 1
from network import WLAN
import ubinascii
wl = WLAN()
print(ubinascii.hexlify(wl.mac())[:6] + 'FFFE' + ubinascii.hexlify(wl.mac())[6:])
Exemplo n.º 21
0
# test init again
wifi.init(WLAN.AP,
          ssid='www.wipy.io',
          auth=None,
          channel=5,
          antenna=WLAN.INT_ANT)
print(wifi.mode() == WLAN.AP)

# get the current instance without re-init
wifi = WLAN()
print(wifi.mode() == WLAN.AP)
wifi = WLAN(0)
print(wifi.mode() == WLAN.AP)

# test the MAC address length
print(len(wifi.mac()) == 6)

# next ones MUST raise
try:
    wifi.init(mode=12345)
except:
    print('Exception')

try:
    wifi.init(1, mode=WLAN.AP)
except:
    print('Exception')

try:
    wifi.init(mode=WLAN.AP, ssid=None)
except:
Exemplo n.º 22
0

test_wifi()
if not wifi_passed:  # try twice
    time.sleep(1.0)
    test_wifi()

EMPTY_MAC_ADDRESS = b'ffffffffffff'

pycom.heartbeat(False)

try:
    f = open('/flash/sys/test.fct', 'r')
    initial_test_result = f.readall()
    if wifi_passed and binascii.hexlify(
            wlan.mac()) != EMPTY_MAC_ADDRESS and os.uname(
            ).release == "{FW_VERSION}" and 'WiPy' in os.uname(
            ).machine and initial_test_result == 'Test OK':
        pycom.rgbled(0x008000)  # green
        green_led(1)
        print('QA Test OK')
    else:
        pycom.rgbled(0x800000)  # red
        red_led(1)
        print('QA Test failed')
    f.close()
except Exception:
    pycom.rgbled(0x800000)  # red
    red_led(1)
    print('QA Test failed')
Exemplo n.º 23
0
'''

import machine
import os
from network import WLAN

mch = os.uname().machine
if not 'LaunchPad' in mch and not'WiPy' in mch:
    raise Exception('Board not supported!')

wifi = WLAN()

print(machine)
machine.idle()
print(machine.freq() == (80000000,))
print(machine.unique_id() == wifi.mac())

machine.main('main.py')

rand_nums = []
for i in range(0, 100):
    rand = machine.rng()
    if rand not in rand_nums:
        rand_nums.append(rand)
    else:
        print('RNG number repeated')
        break

for i in range(0, 10):
    machine.idle()