Esempio n. 1
0
def setup():
    wlan = WLAN(mode=WLAN.STA)
    wlan.antenna(WLAN.INT_ANT)
    wlan.connect(config.WIFI_SSID,
                 auth=(WLAN.WPA2, config.WIFI_PASSWORD),
                 timeout=5000)

    while not wlan.isconnected():
        machine.idle()
Esempio n. 2
0
def connect_to_wifi():
    wlan = WLAN(mode=WLAN.STA)
    wlan.antenna(WLAN.INT_ANT)

    # Assign your Wi-Fi credentials
    wlan.connect(cred.WLAN_name, auth=(WLAN.WPA2, cred.WLAN_pass), timeout=5000)

    while not wlan.isconnected():
        machine.idle()
    print("Connected to Wifi\n")
Esempio n. 3
0
    def WiFi_Setup(self):
        # Use nvram values to connect to a WiFi
        wlan = WLAN(mode=WLAN.STA)
        wlan.antenna(WLAN.EXT_ANT)
        NvsExtract(SSID)
        wlan.connect(NvsExtract(SSID).retval(),
                     auth=(WLAN.WPA2, NvsExtract(PASS).retval()),
                     timeout=5000)

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

        print("Connected to WiFi\n")
Esempio n. 4
0
class C_Wifi:

    def __init__(self, network):
        print('[Wifi] Wifi starting...')
        self.wlan = WLAN(mode=WLAN.STA)
        self.wlan.antenna(WLAN.EXT_ANT) #por defeito escolhe sempre a interna
        # Versão da Documentação Oficial:
        self.wlan.connect(ssid=network["SSID"], auth=(WLAN.WPA2_ENT, network["USER"],network["PASS"]), identity=network["USER"])

        # Versão documentada no github da pycom pelo autor no ficheiro de coneção WLAN:

        # self.wlan.connect(ssid=network["SSID"], auth=(WLAN.WPA2_ENT,""), wpa2_ent_method=WLAN.EAP_PEAP, wpa2_ent_auth=(network["USER"],network["PASS"]), identity=network["USER"], timeout=5000)

        while not self.wlan.isconnected():
            utime.sleep_ms(50)
        print('[Wifi] Wifi connected to '+network["SSID"])
Esempio n. 5
0
def WIFI():
    global wlan
    print("Attempting to connect to WiFi...")
    pycom.rgbled(0xFF0000)  # Red
    wlan = WLAN(mode=WLAN.STA)
    if CONFIG.get('wifiExt') == True:
        Pin('P12', mode=Pin.OUT)(True)
        wlan.antenna(WLAN.EXT_ANT)
        print("Using Ext for WiFi")
    wlan.connect(CONFIG.get('ssid'),
                 auth=(WLAN.WPA2, CONFIG.get('wifiPass')),
                 timeout=5000)
    while not wlan.isconnected():
        machine.idle()
    print("WiFi Connected")
    global ip
    ip = wlan.ifconfig()
    ip = ip[0]
    print("IP is: ", ip)
    led_flash('green')  #Flashes THE LED Green
Esempio n. 6
0
File: main.py Progetto: smjnab/WiPee
def ConnectWLAN(onOff):
    wlan = WLAN()

    # Connect to wlan
    if onOff:
        wlan.antenna(wlanAntType)

        if machine.reset_cause() != machine.SOFT_RESET:
            wlan.init(mode=WLAN.STA)
            wlan.ifconfig(config=(ip, subnet, router, dns))

        if not wlan.isconnected():
            wlan.connect(wlanName, auth=(wlanType, wlanPass), timeout=5000)

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

    # Disconnect from wlan
    else:
        wlan.disconnect()

        while wlan.isconnected():
            machine.idle()
Esempio n. 7
0
from network import WLAN
import urequests as requests
import machine
import time
from dht import DHT
from machine import Pin

TOKEN = "Token here"  #Put here your TOKEN
DELAY = 60  # Delay in seconds

th = DHT(Pin('P23', mode=Pin.OPEN_DRAIN),
         0)  # DHT sensor is connected to port 23
time.sleep(2)  # wait 2 seconds

wlan = WLAN(mode=WLAN.STA)
wlan.antenna(WLAN.INT_ANT)

# Assign your Wi-Fi credentials
wlan.connect("wifi-name", auth=(WLAN.WPA2, "wifi-password"), timeout=5000)

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


# Builds the json to send the request
def build_json(variable1, value1, variable2, value2):
    try:
        data = {variable1: {"value": value1}, variable2: {"value": value2}}
        return data
    except:
Esempio n. 8
0
#broker = "broker.hivemq.com"
BROKER = "mqtt.avist.io"
TOPIC = "/accelerometer"
SSID = "itps-guest" #"Wart-29"
PASS = "******"  # "77599544151"
ACCEL_TRESHOLD = 2000 # shake deteted when acceleration is more than  0.001xG
ACCEL_DURATION = 200  # shake duration is more than 200ms
MAX_TIMEOUT = 20      # time in seconds to wait if nothing happens, then go to go to sleep
TIME_TO_SLEEP = 300   # time to sleep in seconds, then wake up.



print("Connecting to WiFi %s.."%SSID)
wlan = WLAN(mode=WLAN.STA)
wlan.antenna(WLAN.EXT_ANT)
wlan.connect(SSID, auth=(WLAN.WPA2, PASS), timeout=5000)
while not wlan.isconnected():
     machine.idle()
print("Connected to Wifi %s"%SSID)

queue = MessageBuffer(broker=BROKER, topic=TOPIC)

py = Pytrack()
# display the reset reason code and the sleep remaining in seconds
# possible values of wakeup reason are:
# WAKE_REASON_ACCELEROMETER = 1
# WAKE_REASON_PUSH_BUTTON = 2
# WAKE_REASON_TIMER = 4
# WAKE_REASON_INT_PIN = 8
Esempio n. 9
0
    # JSON build
    data = b'{ "pressure" : %s,"altitude" : %s, "temp_mpl" : %s, "temp_si" : %s, "rel_hum" : %s, "amb_hum" : %s, "dew_point" : %s, "lux_blue" : %s, "lux_red" : %s }' % (
        pressure, altitude, temperature_mpl, temperature_si, relative_humidity,
        ambient_humidty, dewpoint, light[0], light[1])

    return data


'''
RUN ON BOOT FILE
'''
# Network's inizalitation
wlan = WLAN(
    mode=WLAN.STA
)  # Set STA (Station Aka Client, connects to an AP) as WLAN network interface 'STA_IF' (Station aka client, connects to upstream WiFi Access points)
wlan.antenna(
    WLAN.EXT_ANT)  # Set antenna type (INT_ANT: Internal, EXT_ANT: External)
wifi_connect(wifi_ssid, wifi_password)

# Sensors' inizalitation
py = Pysense()

# Establishes connection with the MQTT server
try:
    client = connect_mqtt()
except OSError as e:
    restart_and_reconnect()

# Main function
while True:
    try:
        # Network reconnection
Esempio n. 10
0
# boot.py -- run on boot-up
import os
import machine

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

from network import WLAN
wlan = WLAN()  # get current object, without changing the mode

if machine.reset_cause() != machine.SOFT_RESET:
    wlan.init(mode=WLAN.STA)
    wlan.antenna(1)
    # configuration below MUST match your home router settings!!
    wlan.ifconfig(id=0, config='dhcp')
    print("WLAN details:", wlan.ifconfig())

if not wlan.isconnected():
    # change the line below to match your network ssid, security and password
    wlan.connect('basket1000', auth=(WLAN.WPA2, 'gpz32914'), timeout=5000)
Esempio n. 11
0
    raise Exception('Board not supported!')


def wait_for_connection(wifi, timeout=10):
    while not wifi.isconnected() and timeout > 0:
        time.sleep(1)
        timeout -= 1
    if wifi.isconnected():
        print('Connected')
    else:
        print('Connection failed!')


wifi = WLAN()
print(wifi.mode() == WLAN.STA)
print(wifi.antenna() == WLAN.INT_ANT)

wifi = WLAN(mode=WLAN.AP)
print(wifi.mode() == WLAN.AP)
print(wifi.channel() == 1)
print(wifi.auth() == None)
print(wifi.antenna() == WLAN.INT_ANT)
wifi = WLAN(0, mode=WLAN.AP, ssid='test-wlan', auth=(WLAN.WPA, '123456abc'), channel=7)
print(wifi.mode() == WLAN.AP)
print(wifi.channel() == 7)
print(wifi.ssid() == 'test-wlan')
print(wifi.auth() == (WLAN.WPA, '123456abc'))
print(wifi.antenna() == WLAN.INT_ANT)

wifi = WLAN(mode=WLAN.STA)
print(wifi.mode() == WLAN.STA)
Esempio n. 12
0
class Scanner:
    def __init__(self):
        # Initialize wlan
        self.wlan = WLAN(mode=WLAN.STA)
        # Internal (WLAN.INT_ANT) or external (WLAN.EXT_ANT) antenna
        self.wlan.antenna(WLAN.INT_ANT)
        self.nets = []
        # Define the named tuple that contains the WiFi access point information
        self.net = namedtuple('net',
                              ('ssid', 'bssid', 'sec', 'channel', 'rssi'))

    def get(self, testNetworksValid=False, testNetworks=[]):
        if testNetworksValid:
            self.nets = testNetworks
        else:
            # Scan available networks
            self.nets = self.wlan.scan(type=WLAN.SCAN_PASSIVE, scantime=120)
            # Switch WiFi off
            self.wlan.deinit()

        # Nets is defined None if no networks are found
        if self.nets is None:
            self.nets = []

        # If more than one network, order the list by RSSI (strongest first)
        if len(self.nets) > 1:
            sorted(self.nets, key=self.__byRssi_key)

        # Flash file storage not used because it is slow
        #self.storeNets(self.convertNetList(self.nets))
        #print(self.readNets())
        return self.nets

    # Convert from list of named tuples to list of dictionaries
    # ssid', 'bssid', 'sec', 'channel', 'rssi'
    def convertNetList(self, tupleNetList):
        dictNetList = []
        for tupleNet in tupleNetList:
            dictNet = {
                "ssid": tupleNet.ssid,
                "bssid": tupleNet.bssid,
                "sec": tupleNet.sec,
                "channel": tupleNet.channel,
                "rssi": tupleNet.rssi
            }
            dictNetList.append(dictNet)
        return dictNetList

    def writeLongList(self, name, longVars, maxLen):
        i = 0
        while i < len(longVars) and i < maxLen:
            pycom.nvs_set(name + str(i) + 'l',
                          struct.unpack(">I", longVars[i][-4:])[0])
            pycom.nvs_set(name + str(i) + 'm',
                          struct.unpack(">H", longVars[i][0:2])[0])
            i = i + 1
        try:
            pycom.nvs_erase(name + str(i) + 'l')
            pycom.nvs_erase(name + str(i) + 'm')
        except:
            return
        else:
            return

    def readLongList(self, name):
        longVars = []
        i = 0
        while True:
            try:
                lsb = pycom.nvs_get(name + str(i) + 'l')
                msb = pycom.nvs_get(name + str(i) + 'm')
            except:
                break
            else:
                longVars.append(struct.pack(">HI", msb, lsb))
                i = i + 1
        return longVars

    def writeStore(self):
        macList = []
        i = 0
        while i < len(self.nets):
            macList.append(self.nets[i].bssid)
            i = i + 1
        self.writeLongList('net', macList, 10)
        return

    def readStore(self):
        macList = self.readLongList('net')

        self.storedNets = []
        for mac in macList:
            self.storedNets.append(
                self.net(ssid='', bssid=mac, sec=0, channel=1, rssi=-100))
        return self.storedNets

    def storeNets(self, nets):
        f = open('data.txt', 'w+')
        for net in nets:
            f.write(repr(net) + '\n')
        f.close()

    def readNets(self):
        dictNetList = []
        f = open('data.txt')
        nets = f.readlines()
        for net in nets:
            dictNetList.append(eval(net))
        f.close()
        return dictNetList

    def createMessage(self):
        message = bytearray()
        i = 0
        while i < len(self.nets) and i < 3:
            # Add BSSID to the LoRa message
            message = message + self.nets[i].bssid
            # Add RSSI (without minus) to the LoRa message
            message.append(self.nets[i].rssi * -1)
            i = i + 1
        return message

    def netDiff(self, nets1=[], nets2=[]):
        matchCnt = 0
        # Define the named tuple that contains the result of the matching
        diffRes = namedtuple('diffRes', ('net1', 'net2', 'match', 'noMatch'))
        for net1 in nets1:
            for net2 in nets2:
                if net1.bssid == net2.bssid:
                    matchCnt = matchCnt + 1
        noMatchCnt = len(nets1) + len(nets2) - (2 * matchCnt)
        return diffRes(net1=len(nets1),
                       net2=len(nets2),
                       match=matchCnt,
                       noMatch=noMatchCnt)

    def __byRssi_key(self, net):
        return net.rssi
Esempio n. 13
0
    raise Exception('Board not supported!')


def wait_for_connection(wifi, timeout=10):
    while not wifi.isconnected() and timeout > 0:
        time.sleep(1)
        timeout -= 1
    if wifi.isconnected():
        print('Connected')
    else:
        print('Connection failed!')


wifi = WLAN(0, WLAN.STA)
print(wifi.mode() == WLAN.STA)
print(wifi.antenna() == WLAN.INT_ANT)

wifi = WLAN(mode=WLAN.AP)
print(wifi.mode() == WLAN.AP)
print(wifi.channel() == 1)
print(wifi.auth() == None)
print(wifi.antenna() == WLAN.INT_ANT)
wifi = WLAN(0,
            mode=WLAN.AP,
            ssid='test-wlan',
            auth=(WLAN.WPA, '123456abc'),
            channel=7)
print(wifi.mode() == WLAN.AP)
print(wifi.channel() == 7)
print(wifi.ssid() == 'test-wlan')
print(wifi.auth() == (WLAN.WPA, '123456abc'))
Esempio n. 14
0
# boot.py -- run on boot-up

import pycom
import time
import machine
from network import WLAN

wlan = WLAN()
wlan.antenna(WLAN.INT_ANT)  # antena que uso, la interna
wlan.init(
    mode=WLAN.STA
)  # modo de funcionamiento, estacion. Ahora mismo estaria como router

# configuration below MUST match your home router setings
wlan.ifconfig(config=('192.168.2.161', '255.255.255.0', '192.168.2.1',
                      '8.8.8.8'))  #configuracion de red
wlan.connect('DeepWAVES_modem4G_01',
             auth=(WLAN.WPA2, 'deepwavesmodem4G'),
             timeout=5000)  # red wifi que uso y su contraseña

while not wlan.isconnected(
):  #chequea si nos conectamos a la red wifi, sino lo deja al minimo
    #save power while waiting
    machine.idle()

pycom.heartbeat(False)
pycom.rgbled(0x007f00)
time.sleep(2)
pycom.rgbled(0x000000)
time.sleep(1)
pycom.heartbeat(True)
Esempio n. 15
0
from network import WLAN
from mqtt import MQTTClient
import machine
import time

def settimeout(duration): 
    pass

wlan = WLAN(mode=WLAN.STA)
wlan.antenna(WLAN.EXT_ANT)
wlan.connect("yourwifinetwork", auth=(WLAN.WPA2, "wifipassword"), timeout=5000)

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

print("Connected to Wifi\n")
client = MQTTClient("demo", "broker.hivemq.com", port=1883)
client.settimeout = settimeout
client.connect()

while True:
     print("Sending ON")
     client.publish("/lights", "ON")
     time.sleep(1)
     print("Sending OFF")
     client.publish("/lights", "OFF")
     time.sleep(1)