def modbus_tcp_connection_init(): # initialize lopy wifi object lopy_wlan = WLAN() # config as station-mode lopy_wlan.init(mode=WLAN.STA) lopy_wlan.ifconfig(id=0) # Scan for an available wifi and connect to "USR-WIFI232-604_27BC" ssid_usr_wifi232 = "USR-WIFI232-604_27BC" # ssid of usr-wifi module network_list = lopy_wlan.scan() for net in network_list: try: if net.ssid == ssid_usr_wifi232 : print("USR-WIFI232 founded! Connecting...") lopy_wlan.connect(ssid_usr_wifi232, timeout=5000) # wait for connection while not lopy_wlan.isconnected(): # do nothing or save power by idle using machine.idle() machine.idle() print("Connection succeeded!") print(lopy_wlan.ifconfig()) # lid LED to green color pycom.rgbled(0xFF00) else : # If SSID is not "USR-WIFI232-604_27BC", Do nothing. pass except Exception as e: print("Maybe, USR-WIFI232 access point is not avialable.") print("Exception : {}".format(e))
def setWiFi(): import time from pycom import wifi_pwd_ap, wifi_ssid_ap try: W_SSID = 'MySense-AAAA' #try: from Config import W_SSID #except: pass if W_SSID[-4:] == 'AAAA': from machine import unique_id import binascii W_SSID = W_SSID[:-4] + binascii.hexlify( unique_id()).decode('utf-8')[-4:].lower() PASS = '******' # only for 1 hr, then powered off (dflt) or changed print("WiFi: %s/%s (SSID/pwd)" % (wifi_ssid_ap(), wifi_pwd_ap())) if (PASS != wifi_pwd_ap()) or (W_SSID != wifi_ssid_ap()): print("Reset wifi: %s/%s (SSID/pwd)" % (W_SSID, PASS)) from network import WLAN wlan = WLAN() wifi_ssid_ap(W_SSID) wifi_pwd_ap(PASS) wlan.init(mode=WLAN.AP, ssid=W_SSID, auth=(WLAN.WPA2, PASS), channel=7, antenna=WLAN.INT_ANT) sleep_ms(2000) except: pass
def setup_new_config(logger): """ Start a WiFi AP that provides a configuration page. The device automatically reboots and applies modifications upon successful configuration. :param logger: status logger :type logger: LoggerFactory """ # Only one of this thread is allowed to run at a time if not wifi_lock.locked(): with wifi_lock: logger.info("New configuration setup started") # Config uses LED colours to indicate the state of the connection - lock is necessary to disable error pings led_lock.acquire(1) unique_id = ubinascii.hexlify(machine.unique_id()).decode() # set pycom up as access point wlan = WLAN(mode=WLAN.AP, ssid=config.get_config("device_name") + unique_id) # Connect to PmSensor using password set by the user wlan.init( mode=WLAN.AP, ssid=config.get_config("device_name") + unique_id, auth=(WLAN.WPA2, config.get_config("password")), channel=1, antenna=WLAN.INT_ANT, ) # Load HTML via entering 192,168.4.10 to browser wlan.ifconfig( id=1, config=("192.168.4.10", "255.255.255.0", "192.168.4.1", "192.168.4.1"), ) logger.info("Access point turned on as {}".format( config.get_config("device_name") + unique_id)) logger.info( "Configuration website can be accessed at 192.168.4.10") address = socket.getaddrinfo( "0.0.0.0", 80)[0][-1] # Accept stations from all addresses sct = socket.socket() # Create socket for communication sct.settimeout(int( float(config.get_config("config_timeout")) * 60)) # session times out after x seconds gc.collect( ) # frees up unused memory if there was a previous connection sct.bind(address) # Bind address to socket sct.listen(1) # Allow one station to connect to socket pycom.rgbled(0x000055) # Blue LED - waiting for connection get_new_config(sct, logger) wlan.deinit() # turn off wifi gc.collect() logger.info("rebooting...") machine.reset()
def connect_wifi(known_nets): wl = WLAN() wl.mode(WLAN.STA) original_ssid = wl.ssid() original_auth = wl.auth() print(" [*] Scanning for known wifi nets") available_nets = wl.scan() print(' [+] Found {} WiFi APs.'.format(len(available_nets))) for available_net in available_nets: print(' - {} ({})'.format(available_net.ssid, available_net.rssi)) 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'] 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']) wl.connect(net_to_use, (sec, pwd), timeout=10000) while not wl.isconnected(): machine.idle() # save power while waiting print(" [+] Connected to " + net_to_use + " with IP address: " + wl.ifconfig()[0]) except Exception as e: print( " [-] Failed to connect to any known network, going into AP mode") wl.init(mode=WLAN.AP, ssid=original_ssid, auth=original_auth, channel=6, antenna=WLAN.INT_ANT)
class wifi_pyboard(): def __init__(self, server_ssid="USR-WIFI232-604_27BC", connection_timeout=10): self.server_ssid = server_ssid self.timeout = connection_timeout self.wlan = WLAN() def connect(self): # config as station-mode self.wlan.init(mode=WLAN.STA) self.wlan.ifconfig(id=0) # Scan for an available wifi and connect to server network_list = self.wlan.scan() for net in network_list: try: if net.ssid == self.server_ssid: print("Server founded! Connecting...") self.wlan.connect(self.server_ssid, timeout=5000) # wait for connection while not self.wlan.isconnected(): # do nothing or save power by idle using machine.idle() machine.idle() print("Connection succeeded!") print(self.wlan.ifconfig()) else: # If SSID is not "USR-WIFI232-604_27BC", Do nothing. pass except Exception as e: print("Maybe, access point is not avialable.") print("Exception : {}".format(e))
def connect_wifi(): wlan = WLAN() wlan.init(mode=WLAN.STA) wlan.ifconfig(config=(config.WIFI_IP, config.WIFI_SUBNET, config.WIFI_GATEWAY, config.WIFI_DNS1)) wlan.connect(config.WIFI_SSID, auth=(WLAN.WPA2, config.WIFI_PASS), timeout=5000) return wlan.ifconfig()
def start_provisioning_server(): global index_content led.blink_blue() wlan = WLAN() wlan.init(mode=WLAN.STA_AP, ssid='appliance-sensor', auth=(WLAN.WPA2, 'evrythng'), channel=7, antenna=WLAN.INT_ANT) f = open(index_page_path, mode='r') index_content = f.read() f.close() gc.collect() s = socket.socket() # Binding to all interfaces - server will be accessible to other hosts! ai = socket.getaddrinfo("0.0.0.0", 80) print("Bind address info:", ai) addr = ai[0][-1] s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) s.bind(addr) s.listen(5) print("Listening, connect your browser to http://192.168.4.1:80/") while True: res = s.accept() client_s = res[0] client_addr = res[1] client_s.settimeout(2) try: data = client_s.recv(4096) except socket.timeout: print('timeout reading data from client {}'.format(client_addr)) else: print("received {} bytes from client {}".format( len(data), client_addr)) if len(data): header, content = parse_request(data.decode('utf-8')) if header != '': client_s.write(header) totalsent = 0 while totalsent < len(content): try: sent = client_s.write(content) except: pass totalsent += sent finally: client_s.close() gc.collect()
def bringup_wlan(ext_ant=False): wlan = WLAN() wlan.deinit() init_kwargs = { "mode": WLAN.STA, "antenna": WLAN.INT_ANT if not ext_ant else WLAN.EXT_ANT } wlan.init(**init_kwargs) return wlan
def set_wlan_to_access_point(ssid="wipy_https_server", password="******", host_ip="192.168.4.1", log=lambda msg: None): log("Creating Access Point {} with password {}".format(ssid, password)) wlan = WLAN() wlan.deinit() wlan.ifconfig(config=(host_ip, '255.255.255.0', '0.0.0.0', '8.8.8.8')) wlan.init(mode=WLAN.AP, ssid=ssid, auth=(WLAN.WPA2, password), channel=5, antenna=WLAN.INT_ANT) return wlan
def setWiFi(): try: from machine import unique_id import binascii SSID = 'MySense-' + binascii.hexlify( unique_id()).decode('utf-8')[-4:].lower() PASS = '******' from network import WLAN wlan = WLAN() wlan.init(mode=WLAN.AP, ssid=SSID, auth=(WLAN.WPA2, PASS), channel=7, antenna=WLAN.INT_ANT) except: pass
def config_ap(ssid, channel, auth_tuple, antenna, net_config): AP_INTERFACE_ID = 1 wlan = WLAN.init(mode=WLAN.AP, ssid=ssid, auth=auth_tuple, channel=channel, antenna=antenna) wlan.ifconfig(id=AP_INTERFACE_ID, config=net_config)
def wifiTask(): global wifi_wdt_lock, wifi_stop_flag logger = Logger(name='WIFI ' + __version__, level=logging.INFO, filename=None) logger.info('** WIFI Task started **') wlan = WLAN() wlan.deinit() uid = str(binascii.hexlify(machine.unique_id())[6:]) Ssid = 'ENS-PP-' + uid[2:8] logger.info('Using Hidden AP SSID:' + Ssid) wlan.init(mode=WLAN.AP, ssid=Ssid, auth=(WLAN.WPA2, 'Li56#fd0gertQQ'), channel=8, antenna=WLAN.INT_ANT, hidden=True) server = network.Server() server.deinit() # disable the server # enable the server again with new settings server.init(login=('ensuser', 'n0ty0urbu5ine55'), timeout=120) wifi_ap_init_done = True while not wifi_stop_flag.locked(): if wifi_wdt_lock.locked(): wifi_wdt_lock.release() time.sleep(1) if fota_wifi_release_sem.locked() and wifi_ap_init_done == True: wlan.deinit() wifi_ap_init_done = False wlan = None logger.info('Deinit AP mode for FOTA') try: wlan.deinit() except: pass logger.error('** WIFI Task ended **')
def main(): first = True while True: if first == True: om2m.createApplication('http://smart-iot.lan.uow.edu.au:8181/~/in-cse', 'admin:admin', 'LOPY5') om2m.createContainer('http://smart-iot.lan.uow.edu.au:8181/~/in-cse/in-name/LOPY5', 'admin:admin', 'WiFi_Connectivity') om2m.subscribeResource('http://smart-iot.lan.uow.edu.au:8181/~/in-cse/in-name/LOPY5/WiFi_Connectivity', 'admin:admin', 'lopy5_wifi_sub', 'http://smart-iot.lan.uow.edu.au:8081/monitorLopy5Wifi') wlan = WLAN() wlan.init(mode=WLAN.STA) wfResults = wlan.scan() wifiCon = getWifiConnectivity(wfResults) print('WiFi Connectivity:') print(wifiCon) print(len(wifiCon['names'])) wifiData = { 'Networks': wifiCon['names'], 'MAC Addresses': wifiCon['macs'], 'Signal Strengths': wifiCon['strengths'] } om2m.createContentInstance('http://smart-iot.lan.uow.edu.au:8181/~/in-cse/in-name/LOPY5/WiFi_Connectivity', 'admin:admin', json.dumps(wifiData) ) if first == True: om2m.createContainer('http://smart-iot.lan.uow.edu.au:8181/~/in-cse/in-name/LOPY5', 'admin:admin', 'BT_Connectivity') om2m.subscribeResource('http://smart-iot.lan.uow.edu.au:8181/~/in-cse/in-name/LOPY5/BT_Connectivity', 'admin:admin', 'lopy5_bt_sub', 'http://smart-iot.lan.uow.edu.au:8081/monitorLopy5BT') first = False bluetooth = Bluetooth() bluetooth.start_scan(3) while bluetooth.isscanning(): time.sleep(1) btResults = bluetooth.get_advertisements() btCon = getBTConnectivity(btResults) print('BT Connectivity:') print(btCon) btData = { 'MAC Addresses': btCon['macs'], 'Signal Strengths': btCon['strengths'] } om2m.createContentInstance('http://smart-iot.lan.uow.edu.au:8181/~/in-cse/in-name/LOPY5/BT_Connectivity', 'admin:admin', json.dumps(btData) ) time.sleep(30)
def connect_wifi(network, password, oled): wlan = WLAN() wlan.deinit() wlan.init(mode=WLAN.STA) wlan.ifconfig(config=('dhcp')) wlan.scan() # scan for available networks wlan.connect(ssid=network, auth=(WLAN.WPA2, password)) for _ in range(15): if wlan.isconnected(): print("Joining Success") # Boot Text with version oled.fill(0) oled.text("Connected to:", 0, 0) oled.text(network, 0, 15) oled.text("IP Address:", 0, 40) oled.text(wlan.ifconfig()[0], 0, 55) oled.show() utime.sleep_ms(1000) return else: # Boot Text with version oled.fill(0) oled.text("Connecting to:", 0, 0) oled.text(network, 0, 15) oled.show() utime.sleep_ms(1000) # WiFi Creds probably broken print("Can't Join Clearing Credentials") kv.set("AP_PWD", False) kv.set("AP_SSID", False) oled.fill(0) oled.text("Failed to", 0, 0) oled.text("connect to:", 0, 15) oled.text(network, 0, 30) oled.text("Rebooting", 0, 55) oled.show() utime.sleep_ms(3000) machine.reset()
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 __init__(self): self.ID = str(ubinascii.hexlify(machine.unique_id()))[2:-1] print("My ssid:") print(self.ID); ''' self.wlan = WLAN(mode=WLAN.AP, ssid=self.ID, auth=(WLAN.WPA2, 'Own password'), channel=11, antenna=WLAN.INT_ANT) self.wlan.ifconfig(id=1, config=('192.168.1.1', '255.255.255.0', '192.168.1.1', '8.8.8.8')) print("done configuring"); ''' wlan = WLAN() wlan.init(mode=WLAN.STA) nets = wlan.scan() for net in nets: if net.ssid == 'Minecraft': print('Network found!') wlan.connect(net.ssid, auth=(net.sec, 'GudmundsV4genIsTheBest'), timeout=5000) while not wlan.isconnected(): machine.idle() # save power while waiting print('WLAN connection succeeded!') break
def setWiFi(): try: W_SSID = 'MySense-AAAA' try: from Config import W_SSID except: pass if W_SSID[-4:] == 'AAAA': from machine import unique_id import binascii W_SSID = W_SSID[:-4] + binascii.hexlify( unique_id()).decode('utf-8')[-4:].lower() PASS = '******' # only for 1 hr, then powered off (dflt) or changed from network import WLAN wlan = WLAN() wlan.init(mode=WLAN.AP, ssid=W_SSID, auth=(WLAN.WPA2, PASS), channel=7, antenna=WLAN.INT_ANT) except: pass
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()
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 {}...'.format(wlanconfig.ssid)) 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)
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)
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)
# This is the boot file operated once at start up from machine import UART import machine from network import WLAN import os import ujson # Set up USB UART uart = UART(0, baudrate=115200) os.dupterm(uart) secrets = ujson.load(open("secret.json", "r")) # Set up LAN 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=('10.0.0.50', '255.255.255.0', '10.0.0.254', '8.8.8.8')) if not wlan.isconnected(): # change the line below to match your network ssid, security and password wlan.connect(secrets["SSID"], auth=(WLAN.WPA2, secrets["WIFIPassword"]), timeout=5000) while not wlan.isconnected(): machine.idle() # save power while waiting # machine.main('main.py')
# wlan.connect('Mano', auth=(WLAN.WPA2, 'alausalaus')) # while not wlan.isconnected(): # time.sleep_ms(50) # print("waiting") # print(wlan.ifconfig()) ##initiate as STA wlan = WLAN(mode=WLAN.STA) wlan.antenna(WLAN.EXT_ANT) nets = wlan.scan() for net in nets: print(net) ##reinitiate as AP wlan = WLAN() wlan.antenna(WLAN.EXT_ANT) wlan.init(mode=WLAN.AP, ssid='wipy-wlan', auth=(WLAN.WPA2, 'www.wipy.io'), channel=7, antenna=WLAN.EXT_ANT) wlan.antenna(WLAN.EXT_ANT) print("done") pycom.heartbeat(False) pycom.rgbled(0x010101) # yellow #time.sleep(1)
# boot.py -- run on boot-up import machine 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, antenna=WLAN.EXT_ANT) # configuration below MUST match your home router settings!! wlan.ifconfig(config=('192.168.1.252', '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(ssid='TheBunns', auth=(WLAN.WPA2, 'nowisthetime'), timeout=5000) while not wlan.isconnected(): machine.idle() # save power while waiting
# 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()
# 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=' ') nets = wlan.scan() for net in nets: if net.ssid == 'Robotmad': KEY = 'mou3se43' break elif net.ssid == 'CoderDojo': KEY = 'coderdojo' break if KEY != '': print(net.ssid, end=" ") wlan.connect(net.ssid, auth=(net.sec, KEY), timeout=10000)
from network import WLAN from machine import UART import os import pycom import machine uart = UART(0, 115200) os.dupterm(uart) wlan = WLAN(mode=WLAN.STA) pycom.heartbeat(False) pycom.rgbled(0x00ff) if machine.reset_cause() != machine.SOFT_RESET: wlan.init(mode=WLAN.STA) # configuration below MUST match your home router settings!! wlan.ifconfig(config=('10.0.0.5', '255.255.255.0', '10.0.0.1', '8.8.8.8')) nets = wlan.scan() for net in nets: if net.ssid == 'wpa_00': print('Network found!') wlan.connect(net.ssid, auth=(net.sec, 'horst123'), timeout=5000) while not wlan.isconnected(): machine.idle() # save power while waiting print('WLAN connection succeeded!') break else: wlan = WLAN(mode=WLAN.AP)
# Turn off Bluetooth bt = Bluetooth() bt.deinit() # Configure WLAN wlan = WLAN() wlan.deinit() wlan_sta = Pin('P11', mode=Pin.IN, pull=Pin.PULL_UP) wlan_ap = Pin('P12', mode=Pin.IN, pull=Pin.PULL_UP) if not wlan_ap() and wlan_sta(): print('WLAN: AP mode') wlan.init(mode=WLAN.AP, ssid='ttn-be-mapper', auth=(WLAN.WPA2, 'reppam-eb-ntt'), channel=7, antenna=WLAN.INT_ANT) elif not wlan_sta() and wlan_ap(): print('WLAN: STA mode') wlan.init(mode=WLAN.STA) if not wlan.isconnected(): wlan.connect(WLAN_SSID, auth=WLAN_AUTH, timeout=5000) while not wlan.isconnected(): machine.idle() # save power while waiting else: print('WLAN: Disabled')
print(wifi.ifconfig(0) == ('192.168.178.109', '255.255.255.0', '192.168.178.1', '8.8.8.8')) wait_for_connection(wifi) print(wifi.isconnected() == True) wifi.disconnect() print(wifi.isconnected() == False) t0 = time.ticks_ms() wifi.connect(testconfig.wlan_ssid, auth=testconfig.wlan_auth, timeout=0) print(time.ticks_ms() - t0 < 500) wifi.disconnect() print(wifi.isconnected() == False) # test init again wifi.init(WLAN.AP, ssid='www.wipy.io', auth=None, channel=5, antenna=WLAN.INT_ANT) print(len(wifi.mac()) == 6) # next ones MUST raise try: wifi.init(mode=12345) except: print('Exception') try: wifi.init(1, mode=WLAN.AP) except: print('Exception') try:
pwd = net_properties['pwd'] sec = [e.sec for e in available_nets if e.ssid == net_to_use][0] print(' Connecting to: ' + net_to_use) if 'wlan_config' in net_properties: wlan.ifconfig(config=net_properties['wlan_config']) wlan.connect(net_to_use, auth=(sec, pwd), timeout=5000) while not wlan.isconnected(): machine.idle() # save power while waiting print(' Connected.') print(' IP address: ' + wlan.ifconfig()[0]) network_OK = True except Exception as e: print(' Cant connect to known networks') print(' Entering AP mode') wlan.init(mode=WLAN.AP, ssid='GPSnode', channel=6, antenna=WLAN.INT_ANT) if use_WebServer: print("Starting Webserver") routes = WWW_routes() mws = MicroWebSrv(routeHandlers=routes, webPath=webFilePath) gc.collect() mws.Start() gc.collect() print('Starting Clocks') if network_OK: print(' Syncing RTC to ' + ntp_source) rtc.ntp_sync(ntp_source) utime.sleep_ms(1500) print(' RTC Time :', rtc.now())
from machine import I2C, Pin, Timer, rng from network import LoRa, WLAN import time import pycom import socket MYID = "1:1" IP_receive = "192.168.4.1" IP_send = "192.128.4.2" PORT = 5005 wlan = WLAN() wlan.init(mode=WLAN.AP, ssid='TEST ' + MYID, auth=(WLAN.WPA2, '12345678')) s_UDP = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) s_UDP.setblocking(False) lora = LoRa(mode=LoRa.LORA, region=LoRa.EU868) # Do we need this??? s_LORA = socket.socket(socket.AF_LORA, socket.SOCK_RAW) s_LORA.setblocking(False) s_UDP.bind( (IP_receive, PORT) ) # A problem may occur - if so try writing manually the IP_receive and PORT def RGB_LED(color, delay): pycom.rgbled(color) # set led to <color> time.sleep_ms(delay) # for <time> time pycom.rgbled(0) # reset led to none
) != machine.SOFT_RESET: # needed to avoid losing connection after a soft reboot from network import WLAN wl = WLAN() # save the default ssid and auth original_ssid = wl.ssid() original_auth = wl.auth() wl.mode(WLAN.STA) available_nets = wl.scan() nets = frozenset([e.ssid for e in available_nets]) known_nets_names = frozenset([e[0] for e in known_nets]) net_to_use = list(nets & known_nets_names) try: net_to_use = net_to_use[0] pwd = dict(known_nets)[net_to_use] sec = [e.sec for e in available_nets if e.ssid == net_to_use][0] wl.connect(net_to_use, (sec, pwd), timeout=10000) setup_rtc() except: wl.init(mode=WLAN.AP, ssid=original_ssid, auth=original_auth, channel=6, antenna=WLAN.INT_ANT) machine.main('main.py')
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()
from network import WLAN from machine import I2C import bme280 import socket wlan = WLAN() wlan.init(mode=wlan.AP, ssid='Teste01', auth=(wlan.WPA2, 'nelio')) i2c = I2C(0, I2C.MASTER, baudrate=100000) bme = bme280.BME280(i2c=i2c) addr = socket.getaddrinfo('0.0.0.0', 80)[0][-1] s = socket.socket() s.bind(addr) s.listen(1) print('listening on', addr) while True: cl, addr = s.accept() print('client connected from', addr) cl_file = cl.makefile('rb', 0) while True: line = cl_file.readline() if not line or line == b'\r\n': break dados = bme.formated_values html = "<!DOCTYPE html>" html += "<head>" html += " <meta http-equiv='refresh' content='2'>"
lora = LoRa(mode=LoRa.LORA, frequency=freq, tx_power=tx_pow, bandwidth=band, sf=spreadf, preamble=prea, coding_rate=cod_rate, power_mode=pow_mode, tx_iq=tx_iq_inv, rx_iq=rx_iq_inv, adr=ada_dr, public=pub, tx_retries=tx_retr, region=LoRa.EU868, device_class=dev_class) # The lopy is configured as an Access Point and HTTP server my_lora_address = binascii.hexlify(network.LoRa().mac()) lopy_name = "messenger_" + my_lora_address.decode()[-3:] print ("Network Name: " + lopy_name) wlan = WLAN() wlan.init(mode=WLAN.STA_AP, ssid=lopy_name, auth=None, channel=7, antenna=WLAN.INT_ANT) tabla = BaseDatos(mode_print) # Instance Class Database print ("Starting web server") s = Server(80, mode_print) # Construct server object s.activate_server() # Acquire the socket s.connectionLoRa() # Acquire Socket LoRa s.conexion()