Example #1
1
 def disconnectWLAN(self):
  try:
   from network import WLAN
   wlan=None
   if self.isWipy1():
    wlan=WLAN()
   else:
    wlan=WLAN(mode=WLAN.STA)
   wlan.disconnect()
  except:
   pass
Example #2
0
class Theta:

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

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

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

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

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

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

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

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

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

    def getPTPIP(self):
        return self.ptpip
Example #3
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
Example #4
0
File: init.py Project: aidium/WiPy
def wlan_connect():
    wifi = WLAN(mode=WLAN.STA)

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

    syslog('WiPy is up and running')

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

    machine.sleep()
def connect_to_wifi_wipy(ssid, password, retries=10):
    """
    Connect to a WIFI network
    """
    wlan = WLAN(mode=WLAN.STA)
    print("Connecting to wifi network '%s'" % ssid)
    wlan.connect(ssid=ssid, auth=(WLAN.WPA2, password))
    retry_count = 0
    while not wlan.isconnected():
        sleep(1)
        retry_count += 1
        if retry_count > retries:
            return False
    print('Connected', wlan.ifconfig())
    return True
Example #6
0
    def disconnectWLAN(self):
        # disconnect wlan because it spams debug messages that disturb the monitor protocol
        try:
            from network import WLAN
            wlan = None
            if self.isWipy1():
                wlan = WLAN()
            else:
                wlan = WLAN(mode=WLAN.STA)

            wlan.disconnect()
        except:
            # if wifi disconnect fails for whatever reason, let it continue to sync
            # often this is the 'OSError: the requested oparation is not possible' thrown by the wlan.disconnect line
            pass
Example #7
0
 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 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)
Example #9
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())
Example #10
0
def connectLocalBox(configFilePath):
    f = open(configFilePath, 'r')
    config=ujson.load(f)
    f.close()

    wlan = WLAN(mode=WLAN.STA)
    wlan.ifconfig(config=(config["ip"], config["mask"],config["gateway"], config["dns"]))
    wlan.scan()
    wlan.connect(config["ssid"], auth=(WLAN.WPA2, config["password"]))
    while not wlan.isconnected():
        pass
    return wlan;
Example #11
0
    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')
Example #12
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)
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)
Example #14
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])
Example #15
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')
Example #16
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
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
Example #18
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)
Example #19
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())
Example #20
0
#Part 1: Connect to Internet

from network import WLAN, STA_IF
from network import mDNS
import time

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

wlan.connect('<add here>', '<add here>', 5000)

for x in range(0, 10):
    if not wlan.isconnected():
        print("Waiting for wlan connection")
        time.sleep(1)
    else:
        break
print("Wifi connected at", wlan.ifconfig()[0])

#Advertise as 'hostname', alternative to IP address
try:
    hostname = 'wifinetwork'
    mdns = mDNS(wlan)
    mdns.start(hostname, "MicroPython REPL")
    mdns.addService('_repl', '_tcp', 23, hostname)
    print("Advertised locally as {}.local".format(hostname))
except OSERROR:
    print("Failed starting mDNS server - already started?")

#start telnet server for remote login
from network import telnet
Example #21
0
from network import WLAN
from network import Bluetooth
from machine import UART
import os

uart = UART(0, 115200)
os.dupterm(uart)
wlan = WLAN()
wlan.init(mode=WLAN.STA)
wlan.deinit()
bt = Bluetooth()
bt.deinit()
Example #22
0
  Run the App (green triangle in the upper right corner).

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

import BlynkLib
from network import WLAN
from machine import RTC

WIFI_SSID = 'YourWiFiNetwork'
WIFI_AUTH = (WLAN.WPA2, 'YourWiFiPassword')

BLYNK_AUTH = 'YourAuthToken'

# Set the current time (mandatory to validate certificates)
RTC(datetime=(2017, 04, 18, 11, 30, 0, 0, None))

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

print(wifi.ifconfig())

# Initialize Blynk with security enabled
blynk = BlynkLib.Blynk(BLYNK_AUTH, ssl=True)

# Start Blynk (this call should never return)
blynk.run()
Example #23
0
                break
        # Disable automatic rendering of time
        driver.set_auto_time(False)
        # Trap Ctrl-C and service termination
        signal.signal(signal.SIGINT, sigint_handler)
        signal.signal(signal.SIGTERM, sigint_handler)

    # Initialize led matrix framebuffer on top of HAL
    display = LedMatrix(driver, config['LedMatrix'])
    driver.clear_display()

    if pycom_board:
        # We're running under MCU here
        from bootscene import BootScene
        scene = BootScene(display, config['Boot'])
        wlan = WLAN(mode=WLAN.STA)
        if not wlan.isconnected():
            print('WLAN: Scanning for networks')
            scene.render(0, 0, 0)
            default_ssid, default_auth = wlan.ssid(), wlan.auth()
            candidates = wlan.scan()
            for conf in config['networks']:
                nets = [
                    candidate for candidate in candidates
                    if candidate.ssid == conf['ssid']
                ]
                if not nets:
                    continue
                print('WLAN: Connecting to known network: {}'.format(
                    nets[0].ssid))
                wlan.connect(nets[0].ssid,
class Tempstation():
    """Tempstation according to the Tempstation API."""

    MAC_ADDRESS = str(hexlify(WLAN().config('mac')).decode())
    SENSOR = None
    ID = 0
    TEMP_MIN = 0
    TEMP_MAX = 0
    HUM_MIN = 0
    HUM_MAX = 0
    INTERVAL = 0
    LED_BLUE = None
    LED_RED = None
    LED_GREEN = None

    def set_up_pins(self):
        """Set up all necessary pins on the board."""
        self.SENSOR = dht.DHT22(Pin(4))
        self.LED_BLUE = Pin(2, Pin.OUT)
        self.LED_BLUE.on()
        self.LED_RED = Pin(13, Pin.OUT)
        self.LED_RED.on()
        self.LED_GREEN = Pin(12, Pin.OUT)
        self.LED_GREEN.on()
        print("Pins are set up.")

    def initialize_controller_data(self):
        """Assign controller values given by the API."""
        api_data = urequests.get(
            credentials.get_controller_data.format(
                hardware_id=self.MAC_ADDRESS)).json()
        print("Received following API data: ", api_data)
        self.ID = api_data['id']
        critical_values = api_data['location']['criticalValues']

        for values in critical_values:
            if (values['id'] == 1):
                self.TEMP_MIN = values['minValue']
                self.TEMP_MAX = values['maxValue']
            if (values['id'] == 2):
                self.HUM_MIN = values['minValue']
                self.HUM_MAX = values['maxValue']
        self.INTERVAL = api_data['settings']['measureDuration']
        print("Assigned controller values from the API.")

    def _give_led_signal(self, values):
        """Light the LED to signal if measured data breaks critical values."""
        if ((values['temperature'][0] > self.TEMP_MAX)
                or (values['humidity'][0] > self.HUM_MAX)
                or (values['temperature'][0] < self.TEMP_MIN)
                or (values['humidity'][0] < self.HUM_MIN)):
            for i in range(0, 3):
                self.LED_RED.off()
                sleep(1)
                self.LED_RED.on()
                sleep(1)
        else:
            for i in range(0, 3):
                self.LED_GREEN.off()
                sleep(1)
                self.LED_GREEN.on()
                sleep(1)

    def measure_and_post(self):
        """Measure data and post to the API."""
        self.LED_BLUE.off()
        values = {}
        self.SENSOR.measure()
        values['temperature'] = [self.SENSOR.temperature(), 1]
        values['humidity'] = [self.SENSOR.humidity(), 2]
        print("Measured the following: ", values)
        for key in values:
            data_dict = {}
            data_dict['value'] = values[key][0]
            data_dict['unitId'] = values[key][1]
            resp = urequests.post(
                credentials.post_data.format(station_ID=self.ID),
                data=ujson.dumps(data_dict),
                headers={'Content-Type': 'application/json'})
            print("Sending", key, resp.status_code, resp.text)
        self.LED_BLUE.on()
        sleep(2)
        self._give_led_signal(values)
Example #25
0
print("Waiting for bluetooth...")

#odottaa uutta bluetooth-yhteyttä enintään 20 sekuntia
while proceed==False:
    if connected==False and bluetoothTimer.read()>=20:
        print("20 seconds passed, waiting stopped, proceeding.")
        proceed=True
    pass

bluetoothTimer.stop()
bluetoothTimer.reset()
del bluetoothTimer

#nettiin yhdistys
wlan = WLAN(mode=WLAN.STA)
nets = wlan.scan()
while not wlan.isconnected():
    for net in nets:
        if net.ssid == ssid:
            print('Network found!')
            if password=="":
                wlan.connect(net.ssid, timeout=5000)
            else:
                wlan.connect(net.ssid, timeout=5000, auth=(WLAN.WPA2, password))
            sleep(5)
            if wlan.isconnected():
                print('WLAN connection succeeded!')
                break
    if not wlan.isconnected():
        print("Trying again for connection.")
Example #26
0
#
# Copyright (c) 2019, Pycom Limited.
#
# This software is licensed under the GNU GPL version 3 or any
# later version, with permitted additional terms. For more information
# see the Pycom Licence v1.0 document supplied with this file, or
# available at https://www.pycom.io/opensource/licensing
#

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')
Example #27
0
def init_wlan_station() -> WLAN:
    station = WLAN(STA_IF)
    station.active(True)
    return station
Example #28
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)
            try:
                net_to_use = net_to_use[0]
                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]
                if 'wlan_config' in net_properties:
                    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
Example #29
0
  Add a Push notification widget.
  Run the App (green triangle in the upper right corner).

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

import BlynkLib
from network import WLAN
import time

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

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

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

# initialize Blynk
blynk = BlynkLib.Blynk(BLYNK_AUTH)


# to register virtual pins first define a handler
def v4_write_handler(value):
    if value:  # is the the button is pressed?
        blynk.notify('You pressed the button and I know it ;)')
        blynk.tweet(
Example #30
0
class Wifi:
    """
    A module for controlling the Wifi radio of the device. The methods in this
    module are permissive. For instance, if the Wifi radio is not yet
    activated, it will automatically be turned on when connecting to an access
    point.

    In order to save battery, the Wifi radio should be turned off through a
    call to `deactivate()` whenever possible.

    Since this module is shared by multiple threads, there is a potential risk
    in one thread turning off the Wifi radio when it is used by another. Thus,
    whenever a thread uses the Wifi radio, it should inform the wifi module
    first. It is also vital to inform the Wifi module when done using the Wifi
    radio - otherwise it may never be possile to deactivate it again. Other
    threads are not able to disable Wifi when it is in use. However, threads
    are free to enable Wifi at any time.

    The Wifi locking mechanism used in this module is a simple readers-writer
    lock using the Raynal method. Thus, the technique prefers users of the Wifi
    radio.
    """

    def __init__(self, ssid: str, pw: str):
        self._station = WLAN(STA_IF)
        self._ssid = ssid
        self._pw = pw

        # Readers-writer lock for activation/deactivation
        self.__readers_lock = _thread.allocate_lock()
        self.__global_lock = _thread.allocate_lock()
        self.__clients = []

    def activate(self):
        """Turn on the Wifi radio if it is off."""
        if not self._station.active():
            self._station.active(True)

    def deactivate(self, blocking=True):
        """
        Turn off the Wifi radio. This will also disconnect from the access
        point, if connected. If the Wifi radio is used by other threads, this
        method will block until Wifi can be deactivated. Alternatively, the the
        client can pass `False` to the `blocking` parameter to return
        immediately if the radio is used by others. This is useful if
        deactivation of the radio is not a hard requirement, but simply a hint.
        """
        if self.__global_lock.acquire(1 if blocking else 0):
            try:
                if self._station.isconnected():
                    self.__disconnect()
                if self._station.active():
                    self._station.active(False)
            finally:
                self.__global_lock.release()

    def connect(self) -> bool:
        """
        Connect to the access point if not already connected. This method will
        also ativate the Wifi radio if it is not currently on. However, if the
        method fails, it will not turn off the radio again.
        """
        self.activate()

        if self._station.isconnected():
            return True
        
        self._station.connect(self._ssid, self._pw)
        utime.sleep(2)  # Allow the radio some time to connect
        if self._station.isconnected():
            return True
        
        self._station.disconnect()
        return False

    def is_connected(self):
        """Check if currently connected to the access point."""
        return self._station.isconnected()

    def disconnect(self, blocking=True):
        """
        Disconnect from the access point if currently connected. If the Wifi
        radio is currently used by other threads, this method will block until
        it is possible to disconnect. Alternatively, the the client can pass
        `False` to the `blocking` parameter to return immediately if the radio 
        is used by others. This is useful if deactivation of the radio is not a
        hard requirement, but simply a hint.
        """
        if self.__global_lock.acquire(1 if blocking else 0):
            try:
                self.__disconnect()
            finally:
                self.__global_lock.release()
    
    def __disconnect(self):
        if self.is_connected():
            self._station.disconnect()
    
    def scan(self):
        """
        Scan for nearby access points. If the Wifi radio is not on, it will
        automatically be enabled.
        """
        self.activate()
        for _ in range(3):
            try:
                return self._station.scan()
            except RuntimeError:
                utime.sleep(1)  # Give radio time to turn on

    def acquire(self):
        """
        Inform the Wifi module that a thread wishes to use the Wifi radio. It
        is vital to match each call to this method with a similar call to
        `release()`. Each thread will be registered only once, regardless of
        how many times it calls this method.
        """
        self.__readers_lock.acquire()
        try:
            tid = _thread.get_ident()
            if not tid in self.__clients:
                self.__clients.append(tid)
                self.__global_lock.acquire(0)
        finally:
            self.__readers_lock.release()

    def release(self):
        """
        Inform the Wifi module that a client is done using the Wifi radio. If
        the calling thread has not been registered by a previous call to
        `acquire()`, then calling this method has no effect. Furthermore, it
        has no effect if a thread calls this method multiple times in
        succession.
        """
        self.__readers_lock.acquire()
        try:
            tid = _thread.get_ident()
            if tid in self.__clients:
                self.__clients.remove(tid)
                if len(self.__clients) == 0 and self.__global_lock.locked():
                    self.__global_lock.release()
        finally:
            self.__readers_lock.release()
Example #31
0
# Create one-off log file
f = open('wifi.log', 'w')

known_nets = {
    'WIFI_AP1': {
        'pwd': 'xxxxxyyyyyZZZZZ'
    },  # (ip, subnet_mask, gateway, DNS_server)
    'WIFI_AP2': {
        'pwd': 'aaaaabbbbbCCCCC'
    }
}
f.write("Connecting to known WiFi networks...\n")
if machine.reset_cause() != machine.SOFT_RESET:
    from network import WLAN
    wl = WLAN()
    while not wl.isconnected():
        wl.mode(WLAN.STA)
        original_ssid = wl.ssid()
        original_auth = wl.auth()

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

        known_nets_names = frozenset([key for key in known_nets])
        net_to_use = list(nets & known_nets_names)
        try:
            net_to_use = net_to_use[0]
            net_properties = known_nets[net_to_use]
            pwd = net_properties['pwd']
Example #32
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))
#################################################
#                Connect to WiFi                #
#################################################

from network import WLAN
import machine
wlan = WLAN(mode=WLAN.STA)

nets = wlan.scan()
print(nets)
for net in nets:
    if net.ssid == 'hotspotdemo':
        print('Network found!')
        wlan.connect(net.ssid, auth=(net.sec, 'emmastestdemo'), timeout=5000)
        while not wlan.isconnected():
            machine.idle()  # save power while waiting
        print('WLAN connection succeeded!')
        break
    else:
        print("Network not found")
Example #34
0
# declare le bus i2c
i2c = I2C(sda=Pin(4), scl=Pin(5))

# créer les senseurs
try:
    tsl = TSL2561(i2c=i2c)
    bmp = BME280(i2c=i2c, address=BMP280_I2CADDR)
    am = AM2315(i2c=i2c)
except Exception as e:
    print(e)
    led_error(step=4)

try:
    # annonce connexion objet
    sMac = hexlify(WLAN().config('mac')).decode()
    q.publish("connect/%s" % CLIENT_ID, sMac)
except Exception as e:
    print(e)
    led_error(step=5)

import uasyncio as asyncio


def capture_1h():
    """ Executé pour capturer des donnees chaque heure """
    global q
    global tsl
    global am
    # tsl2561 - senseur lux
    lux = "{0:.2f}".format(tsl.read())
Example #35
0
import machine
from network import WLAN
wlan = WLAN()  # get current object, without changing the mode

if machine.reset_cause() != machine.SOFT_RESET:
    wlan.init(WLAN.STA)
    # configuration below MUST match your home router settings!!
    wlan.ifconfig(config=('192.168.178.107', '255.255.255.0', '192.168.178.1',
                          '8.8.8.8'))

if not wlan.isconnected():
    # change the line below to match your network ssid, security and password
    wlan.connect('mywifi', auth=(WLAN.WPA2, 'mywifikey'), timeout=5000)
    while not wlan.isconnected():
        machine.idle()  # save power while waiting
Example #36
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()
Example #37
0
from network import WLAN
wlan = WLAN(mode=WLAN.STA)


def connect():
    nets = wlan.scan()
    for net in nets:
        if net.ssid == 'A4-WiFi':
            print('Network found!')
            wlan.connect(net.ssid,
                         auth=(net.sec, 'AFourtech@321$'),
                         timeout=5000)
            while not wlan.isconnected():
                machine.idle()  # save power while waiting
            print('WLAN connection succeeded!')
            break
Example #38
0
import urequests as requests
import machine
import time
import pycom

# Your WiFi network credentials
WIFI_SSID = ''
WIFI_KEY = ''

# Get this from the Wia dashboard
DEVICE_SECRET_KEY = ''

# Delay between each event
DELAY = 5

wlan = WLAN(mode=WLAN.STA)
nets = wlan.scan()

# Connect to the WiFi network
for net in nets:
    if net.ssid == WIFI_SSID:
        print('Network found!')
        wlan.connect(net.ssid, auth=(net.sec, WIFI_KEY), timeout=5000)
        print('Connecting...')
        while not wlan.isconnected():
             machine.idle() # save power while waiting
        print('WLAN connection succeeded!')
        break


# Post an Event to the Wia cloud
Example #39
0
import pycom
from network import WLAN, Bluetooth
from BLE_Decoder import BLEAdvReader
import urequests
import machine
import ubinascii

pycom.heartbeat(False)

wlan = WLAN(mode=WLAN.STA)
bluetooth = Bluetooth()

#Change accordingly
url = 'http://***.hub.ubeac.io/mygateway'
#****************************************

#Change accordingly
wifi_ssid = "abc123"
wifi_pass = "******"
#*********************

my_beacons = []

nets = wlan.scan()

connected = False
for net in nets:
    if net.ssid == wifi_ssid:
        print('Network found!')
        wlan.connect(net.ssid, auth=(net.sec, wifi_pass), timeout=5000)
        while not wlan.isconnected():
Example #40
0
import machine
from network import WLAN
import time
import socket
import utime

wlan = WLAN(mode=WLAN.STA)

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

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

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

wlan = WLAN()
Example #42
0
mch = os.uname().machine
if not 'LaunchPad' in mch and not 'WiPy' in mch:
    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)
Example #43
0
import _thread

import bluetooth
from machine import ADC
from machine import Pin
import machine
from micropython import const
from network import WLAN
from utime import sleep_ms
import esp32

from ble_advertising import advertising_payload

WLAN(0).active(False)
WLAN(1).active(False)

machine.freq(240000000)


def _create_pin_in(pin_id: int) -> Pin:
    return Pin(pin_id, Pin.IN, Pin.PULL_UP)


# in seconds
_LED_BLING_TIME = 1
_LED_ON = False
_CURRENT_PATCH = 1

_BUTTON_PIN_MAP = {
    "button_rig_up": _create_pin_in(32),
    "button_rig_down": _create_pin_in(33),
Example #44
0
"""creating Config object"""
class Config(object):
    def __init__(self):
        try:
            with open('config.json', encoding='utf-8') as config:
                self.__dict__ = json.load(config)
        except (OSError, IOError) as e:
            Logger.log("Error: Could not load config" + str(e))
config = Config().__dict__


"""Setting up Time"""
rtc = machine.RTC()
Logger.log("Syncing Clock. Attempting to find network")
wlan = WLAN(mode=WLAN.STA)
nets = wlan.scan()
Logger.log("Scanning for Wifi")
for net in nets:
    for knowNet in config["network"]:
        if net.ssid == knowNet["name"]:
            Logger.log(net.ssid + ' found!')
            wlan.connect(net.ssid, auth=(net.sec, knowNet["password"]), timeout=5000)
            while not wlan.isconnected():
                machine.idle() # save power while waiting
            Logger.log('WLAN connection succeeded!')
            rtc.ntp_sync("pool.ntp.org")
            break
time.sleep(10)

sensors = dataCollector(Logger)
Example #45
0
def check_open_network(ssid, wlan: WLAN) -> bool:
    result = connect_to_ap(wlan, ssid) and ping(SERVICE_ADDRESS)
    if wlan.isconnected():
        wlan.disconnect()
    return result
Example #46
0
class WifiManager:
    def __init__(self, essid=None):
        self.local_ip = AP_IP
        self.sta_if = WLAN(STA_IF)
        self.ap_if = WLAN(AP_IF)

        if essid is None:
            essid = b"ESP8266-%s" % binascii.hexlify(self.ap_if.config("mac")[-3:])

        self.essid = essid
        self.creds = Creds()

        # Turn off station and AP interface to force a reconnect
        self.sta_if.active(True)
        self.ap_if.active(False)

        self.loop = asyncio.get_event_loop()
        self.loop.create_task(self.check_wifi())

    async def start_access_point(self):
        while not self.ap_if.active():
            self.ap_if.active(True)
            await asyncio.sleep(1)

        # IP address, netmask, gateway, DNS
        self.ap_if.ifconfig(
            (self.local_ip, "255.255.255.0", self.local_ip, self.local_ip)
        )

        self.ap_if.config(essid=self.essid, authmode=AUTH_OPEN)
        print("> AP mode configured: {} ".format(self.essid.decode("utf-8")), self.ap_if.ifconfig())
            

    async def check_wifi(self):
        while True:
            self.loop.create_task(self.connect(True))

            if self.creds.load().is_valid():
                await asyncio.sleep(WAIT_FOR_CONNECT)

            if not self.sta_if.isconnected():
                self.loop.create_task(self.start_access_point())

                while not self.sta_if.isconnected():
                    await asyncio.sleep(1)

                self.ap_if.active(False)

                while self.sta_if.isconnected():
                    await asyncio.sleep(1)

    async def connect(self, autoLoop=False):
        if not self.sta_if.isconnected():
            if self.creds.load().is_valid():
                print("> Connecting to {:s}/{:s}".format(self.creds.essid, self.creds.password))

                self.sta_if.connect(self.creds.essid, self.creds.password)

                await asyncio.sleep(WAIT_FOR_CONNECT)

                if not self.sta_if.isconnected():
                    print("> Connection failed. WLAN status={:d}".format(self.sta_if.status()))

                    if autoLoop:
                        self.loop.create_task(self.connect(True))
            else:
                print("> No valid credentials file: {}".format(Creds.CRED_FILE))
Example #47
0
            self.blynk.lcd_write(0, 0, 0, "Customer:       ")
            self.blynk.lcd_write(0, 0, 1, config.CUSTOMER)
            self.blynk.lcd_write(7, 0, 0, "Serial:         ")
            self.blynk.lcd_write(7, 0, 1, config.SERIAL)
            self._send_coins()
            self.time = 0

        c_coins =[self.coins[2].count, self.coins[3].count]
        if self.prev_coins != c_coins:
            self.prev_coins = c_coins
            self.leds.coin_in()
            self._send_coins()

wdt = WDT(timeout=WDT_TIMEOUT)

wlan = WLAN(mode=WLAN.STA)
connect_to_wlan(wlan) # the WDT will reset if this takes more than 15s

wdt.feed()

# set the current time (mandatory to validate certificates)
RTC(datetime=(2015, 12, 12, 11, 30, 0, 0, None))

# initialize Blynk with SSL enabled
blynk = BlynkLib.Blynk(BLYNK_AUTH, wdt=False, ssl=True)

# register the main task
s_task = MainTask(blynk, wdt, MAIN_TASK_PERIOD, COIN_INPUTS[config.COIN_10_CENT],
                                                COIN_INPUTS[config.COIN_20_CENT],
                                                COIN_INPUTS[config.COIN_50_CENT],
                                                COIN_INPUTS[config.COIN_1_EUR],
Example #48
0
from network import WLAN
import ubinascii
wl = WLAN()
print("Gateway UIE: {}".format(
    ubinascii.hexlify(wl.mac())[:6] + 'FFFE' +
    ubinascii.hexlify(wl.mac())[6:]))
Example #49
0
# can run arbitrary Python, but best to keep it minimal

import os

import machine
from network import WLAN

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

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

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

# now wifi
wlan = WLAN()

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

if not wlan.isconnected():
    # change the line below to match your network ssid, security and password
    wlan.connect('XXX', auth=(WLAN.WPA2, 'XXX'), timeout=5000)
    while not wlan.isconnected():
        machine.idle()
Example #50
0
from network import WLAN, STA_IF
from network import mDNS
import time
#### TO DO: Add switching action based on user input
wlan = WLAN(STA_IF)
wlan.active(True)
if not wlan.isconnected():
	wlan.connect('thwireless', 'blue&gold', 5000)

for i in range(10):
	if not wlan.isconnected():
		print("Waiting for network connection...")
		time.sleep(1)
	else:
		break

print("WiFi Connected at", wlan.ifconfig()[0])

try:
    hostname = 'BOSERBOIS'
    mdns = mDNS(wlan)
    mdns.start(hostname, "MicroPython REPL")
    mdns.addService('_repl', '_tcp', 23, hostname)
    print("Advertised locally as {}.local".format(hostname))
except OSError:
    print("Failed starting mDNS server - already started?")


#### TO DO: Modify mqtt broker, get this publisher set up as a callback to a timer
#start telnet server for remote login
from network import telnet
Example #51
0
RMotorB = Pin('GPIO8', af=0, mode=Pin.OUT)
LMotorB.low()
RMotorB.low()

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

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

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

import machine
from network import WLAN
from time import sleep

from include.secrets import _ssid, _pass

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

if machine.reset_cause() != machine.SOFT_RESET:
    wlan.init(mode=WLAN.STA)
    # configuration below MUST match your home router settings!!
    # wlan.ifconfig(config=('192.168.178.107', '255.255.255.0', '192.168.178.1', '8.8.8.8'))

if not wlan.isconnected():
    # change the line below to match your network ssid, security and password
    connstat = ''
    print('connecting to ', _ssid, connstat)
    wlan.connect(_ssid, auth=(WLAN.WPA2, _pass), timeout=5000)
    while not wlan.isconnected():
        connstat += '.'
        print(connstat)
        sleep(2)
        #machine.idle()  # save power while waiting

    else:
        print('connected to ssid: ', _ssid, '!')
Example #53
0
def connect_to_ap(client: WLAN, ssid) -> bool:
    client.connect(ssid)
    while client.status() is STAT_CONNECTING:
        pass
    return client.isconnected()
Example #54
0
File: irq.py Project: iot49/iot49
def connect_wlan():
    """ Connect to wlan. Hard reset to disconnect! """
    wlan = WLAN(STA_IF)
    wlan.active(True)
    wlan.connect('TPA', 'TurbenThal', 5000)
    while not wlan.isconnected(): continue
Example #55
0
tim = Timer(1, mode=Timer.PERIODIC)
tim_a = tim.channel(Timer.A, freq=5)
# The slowest frequency the timer can run at is 5Hz
# so we divide the frequency down to toggle the LED
# BUT the callback function doesn't appear to have been developed
# Worth trying again as it is now included in the documentation
	
tim_a.irq(handler=lambda t:led_out.toggle(), trigger=Timer.TIMEOUT)	# Toggle LED on Timer interrupt

#btn_in = Pin('GP17', mode=Pin.IN, pull=Pin.PULL_UP)


# Connect to my WiFi
import machine
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=' ')
Example #56
0
import usocket as socket
from network import Bluetooth
from network import WLAN

pycom.heartbeat(False)

UDPServer = "UDPServerHost"
UDPPort = 33333
LANSID = 'YourWIFISID'
LANPassword = '******'
HashKey = b'YourKey'
machine_id = machine.unique_id()

listBuffer = []

wlan = WLAN()
wlan.init(mode=WLAN.STA, antenna=WLAN.EXT_ANT, channel=1)
gc.enable()
bluetooth = Bluetooth()
bluetooth.start_scan(-1)


def createHash(data):
    m = uhashlib.sha256()
    m.update(data + HashKey)
    return m.digest()


def sendudp(data):
    sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    sock.sendto(data, (UDPServer, UDPPort))
Example #57
0
# boot.py -- run on boot-up
# can run arbitrary Python, but best to keep it minimal

# Copy config.example.py to config.py and modify to your needs first!
import config
import machine

#from machine import UART
from os import dupterm
uart = machine.UART(0, 115200)
dupterm(uart)

if machine.reset_cause() != machine.SOFT_RESET:
    from network import WLAN
    wifi = WLAN()
    wifi.mode(WLAN.STA)
    ssids = wifi.scan()
    found = False
    for net in ssids:
        print("Checking %s" % net.ssid)
        if net.ssid == config.HOME_SSID:
            print("Found %s!" % net.ssid)
            wifi.connect(config.HOME_SSID, auth=(WLAN.WPA, config.HOME_PASSWORD))
            found = True
            break
    if not found:
        print("No eligible WiFi found.")
        wifi.mode(WLAN.AP)
Example #58
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')
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)
def enable_ap_mode(essid=None, password=None):
    from network import AP_IF, AUTH_WPA_WPA2_PSK, WLAN
    from ubinascii import hexlify

    wifi_interface = WLAN(AP_IF)
        
    if not essid:
        essid = b"micropython-esp8266-%s" % hexlify(wifi_interface.config("mac")[-3:])
    if not password:
        password = b'micropybootconfig'

    wifi_interface.config(essid=essid, authmode=AUTH_WPA_WPA2_PSK, password=password)
    del hexlify