from config import WIFI_SSID, WIFI_PW, SERVER_IP # Turn on GREEN LED pycom.heartbeat(False) pycom.rgbled(0xff00) # Setup OTA ota = WiFiOTA( WIFI_SSID, WIFI_PW, SERVER_IP, # Update server address 8000) # Update server port # Turn off WiFi to save power w = WLAN() w.deinit() # Initialize LoRa in LORAWAN mode. lora = LoRa(mode=LoRa.LORAWAN, region=LoRa.EU868) app_eui = binascii.unhexlify('ENTER_ME') app_key = binascii.unhexlify('ENTER_ME') # join a network using OTAA (Over the Air Activation) lora.join(activation=LoRa.OTAA, auth=(app_eui, app_key), timeout=0) # wait until the module has joined the network while not lora.has_joined(): time.sleep(2.5) print('Not yet joined...')
import os import machine uart = machine.UART(0, 115200) os.dupterm(uart) known_nets = { '<YOUR WIFI SSID>': {'pwd': '<YOUR WIFI PWD'} } if machine.reset_cause() != machine.SOFT_RESET: from network import WLAN wl = WLAN() 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'] 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)
def print_iv(state): global ina v = ina.voltage() i = ina.current() print("{:40s} {:8.0f}mA {:8.3}V".format(state, i, v)) # no wifi for _ in range(3): print_iv("cpu on, wifi off") sleep(1) # start wlan wlan = WLAN(STA_IF) wlan.active(True) for _ in range(3): print_iv("cpu on, wlan active, no connection") sleep(1) # connect to wifi t_start = ticks_ms() wlan.connect('TPA', 'TurbenThal', 5000) while not wlan.isconnected(): continue t_stop = ticks_ms() print("{:8.3}s for connecting to wlan".format(
#################################################### import gc, ubinascii, machine, pycom, struct, sys mac = ubinascii.hexlify(machine.unique_id(), ':').decode().replace(":", "") pycom.heartbeat(False) print(mac) gc.enable() sys.path.append('/flash/ch') sys.path.append('/flash/www') ############## INITIALISE WiFi ################### from network import WLAN wlan = WLAN(mode=WLAN.AP, ssid='AlphaX-MHM4-' + mac[-4:], auth=(WLAN.WPA2, mac), channel=11, antenna=WLAN.EXT_ANT) ######### START WEBBROWSER IF NOT CONFIGURED ######### if 'config.py' not in os.listdir('/flash'): print('Start WebServer') import webserver while True: pass ######## INITIALISE EXTERNAL STORAGE IF FITTED ####### import os from machine import SD try: sd = SD()
), channel=7, antenna=WLAN.INT_ANT) Server().deinit() Server().init(login=(coda_common.CODA_CONFIG["server_userid"], coda_common.CODA_CONFIG["server_pwd"]), timeout=60) #begin code server = Server() gc.enable() time.sleep(1) wlan = WLAN() try: wlan.disconnect() except: pass wlan.init(mode=WLAN.STA) time.sleep(1) nets = [] netlist = [] retries = 0 coda_common.led_off() while True:
import machine from network import WLAN from ws2812 import WS2812 import time wlan = WLAN(mode=WLAN.STA) # get current object, without changing the mode if not wlan.isconnected(): # change the line below to match your network ssid, security and password wlan.connect('wifi', auth=(WLAN.WPA2, 'password'), timeout=5000) print('Network Found..') while not wlan.isconnected(): chain = WS2812(ledNumber=5) data = [ (0, 0, 255), (0, 0, 0), (0, 0, 0), (0, 0, 0), (0, 0, 0), ] chain.show(data) time.sleep(0.1) chain = WS2812(ledNumber=5) data = [ (0, 0, 0), (0, 0, 255), (0, 0, 0), (0, 0, 0), (0, 0, 0), ] chain.show(data)
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) # configuration below MUST match your home router settings!! wlan.ifconfig(config=('192.168.1.100', '255.255.255.0', '192.168.1.1', '8.8.8.8')) if not wlan.isconnected(): # change the line below to match your network ssid, security and password wlan.connect('FabLab', auth=(WLAN.WPA2, 'MakerFaire'), timeout=5000) while not wlan.isconnected(): machine.idle() # save power while waiting
def __init__(self, devices): self.devices = devices print("Starting promiscuous mode") self.wlan = WLAN(mode=WLAN.PROMISCUOUS, channel=config.WIFI_SCAN_CHANNEL, antenna=config.WIFI_ANTENNA)
import gc from network import WLAN, AP_IF, STA_IF import webrepl AP_WLAN = WLAN(AP_IF) STA_WLAN = WLAN(STA_IF) AP_WLAN.active(False) # AP_WLAN.config(essid='pyoak2', password='******') STA_WLAN.active(True) STA_WLAN.connect('caravela', 'deprecated') while not STA_WLAN.isconnected(): pass webrepl.start() del WLAN, AP_IF, STA_IF, webrepl gc.collect() del gc
import ssl global DISCONNECTED DISCONNECTED = 0 global CONNECTING CONNECTING = 1 global CONNECTED CONNECTED = 2 release = uos.uname().release global board board = uos.uname().sysname global MAC if release[:4] == '1.20': MAC = str.upper(hexlify(machine.unique_id(), ).decode()) else: MAC = str.upper(hexlify(WLAN().mac(), ).decode()) rtc = RTC() global ROOT_CA ROOT_CA = '/flash/cert/ca.pem' global CLIENT_CERT CLIENT_CERT = '/flash/cert/cert.pem' global PRIVATE_KEY PRIVATE_KEY = '/flash/cert/cert.key' TOPIC = CONFIG.get('topic1') + "/" + MAC + "/" + CONFIG.get('topic2') + "/" #Allow easy call to flash LED different colour def led_flash(colour): c = colour
'Sand': 'EXCLAMATION_MARK', 'Ash': 'EXCLAMATION_MARK', 'Squall': 'EXCLAMATION_MARK', 'Tornado': 'EXCLAMATION_MARK', 'Clear': 'CONDITIONS_SUNNY', 'Clouds': 'CONDITIONS_CLOUDY' } # ############################################################################# # ############################################################################# # ############################################################################# # Declarations spi = SPI(1, baudrate=SPI_BAUDRATE, polarity=0, phase=0) display = Matrix8x8(spi, Pin(CS_PIN, Pin.OUT), NUM_MATRICES) wifi = WLAN(STA_IF) pot = ADC(0) # Leds led_0 = Signal(LED_0_PIN, Pin.OUT, invert=True) led_2 = Signal(LED_2_PIN, Pin.OUT, invert=False) led_1 = Signal(LED_1_PIN, Pin.OUT, invert=False) # Insertion detection insertion = Signal(INSERTION_PIN, Pin.IN) # Read brightness from trim pot at A0 and set it brightness = set_matrix_brightness(pot, display, 0) # Draw WiFi symbol led_0.on()
import ssd1306 from network import WLAN, STA_IF, AP_IF from machine import Pin, I2C, Timer, reset from simple1 import MQTTClient from time import sleep_ms, sleep i2c = I2C(scl=Pin(14), sda=Pin(2), freq=100000) s = ssd1306.SSD1306_I2C(128, 64, i2c) SERVER = "pszvvvd.mqtt.iot.gz.baidubce.com" PORT = 1883 CLIENT_ID = "11122223333123" USER_NAME = "pszvvvd/esp8266_test" PASSWORD = "******" TOPIC = "topic" sta_if = WLAN(STA_IF) ap_if = WLAN(AP_IF) def sub_cb(topic, msg): print("{:s},{:s}".format(topic, msg)) s.fill(0) s.text("{:s}:{:s}".format(topic, msg), 0, 0) s.show() def restart_and_reconnect(): print('Failed to connect to MQTT broker. Reconnecting...') sleep(10) reset()
def on_led(value): led.value(not value) return not led.value() def get_btn(value): global btn_value return btn_value def ds(value): ds.convert_temp() return ds STA = WLAN(STA_IF) STA.active(True) while not STA.isconnected(): print("Connecting to Wi-Fi...") wifi_reconnect_time = time() + WIFI_CONNECTION_TIMEOUT STA.connect(*WIFI_SSID_PASSWORD) while not STA.isconnected() and time() < wifi_reconnect_time: sleep(0.5) if not STA.isconnected(): print("Connection FAILED!") continue print("Connected!")
def connect_to_WLAN(): wlan = WLAN(mode=WLAN.STA) if not wlan.isconnected(): wlan = __connect_to_WLAN(wlan, WLAN_SSID, WLAN_PASSKEY) return wlan
# terms of the GNU General Public License as published by the Free Software Foundation, # version 3 of the License. # # This program is distributed in the hope that it will be useful, but WITHOUT ANY # WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A # PARTICULAR PURPOSE. # See the GNU General Public License for more details. # You should have received a copy of the GNU General Public License along with this # program. If not, see <https://www.gnu.org/licenses/>. import utime from network import WLAN from network import AP_IF from network import STA_IF wlan = WLAN(STA_IF) ap = WLAN(AP_IF) wlan.active(False) ap.active(False) def wlan_connect(ssid, password, wait=True, timeout=10, ifconfig="dhcp"): wlan.active(True) wlan.ifconfig(ifconfig) wlan.connect(ssid, password) if wait: return wlan_wait_connected(timeout) return None
def __init__(self): self.sta_if = WLAN(STA_IF) self.loop = get_event_loop() self.loop.create_task(self.wait_for_station())
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=(2019, 02, 01, 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) while True: blynk.run()
def disable(): wlan = WLAN() logger.info("disabling wlan.") wlan.deinit()
async def main_task(self, _): got_params = False # Await connection parameters (init record) while not got_params: istr = await self.await_obj(100) ilst = istr.split(SEP) command = ilst[0] if command == 'init': got_params = True ssid, pw, broker, mqtt_user, mqtt_pw, ssl_params = ilst[1:7] use_default = bool(int(ilst[7])) fast = bool(int(ilst[10])) debug = bool(int(ilst[12])) config['server'] = broker config['port'] = int(ilst[8]) config['user'] = mqtt_user config['password'] = mqtt_pw config['keepalive'] = int(ilst[11]) config['ping_interval'] = int(ilst[16]) config['ssl'] = bool(int(ilst[9])) config['ssl_params'] = eval(ssl_params) config['response_time'] = int(ilst[15]) config['clean'] = bool(int(ilst[13])) config['max_repubs'] = int(ilst[14]) config['timeserver'] = ilst[17] elif command == WILL: config['will'] = (ilst[1:3] + [bool(ilst[3])] + [int(ilst[4])]) self.send(argformat(STATUS, WILLOK)) else: self.send(argformat(STATUS, UNKNOWN, 'Expected init, got: ', istr)) # Got parameters if debug: Client.DEBUG = True # verbose output on UART if fast: freq(160000000) # try default LAN if required sta_if = WLAN(STA_IF) if use_default: self.send(argformat(STATUS, DEFNET)) secs = _WIFI_DELAY while secs >= 0 and not sta_if.isconnected(): await asyncio.sleep(1) secs -= 1 # If can't use default, use specified LAN if not sta_if.isconnected(): self.send(argformat(STATUS, SPECNET)) # Pause for confirmation. User may opt to reboot instead. istr = await self.await_obj(100) ap = WLAN(AP_IF) # create access-point interface ap.active(False) # deactivate the interface sta_if.active(True) sta_if.connect(ssid, pw) while not sta_if.isconnected(): await asyncio.sleep(1) # WiFi is up: connect to the broker await asyncio.sleep(5) # Let WiFi stabilise before connecting self.client = Client(self, config) self.send(argformat(STATUS, BROKER_CHECK)) try: await self.client.connect() # Clean session. Throws OSError if broker down. # Sends BROKER_OK and RUNNING except OSError: # Cause Pyboard to reboot us when application requires it. self.send(argformat(STATUS, BROKER_FAIL)) while True: await asyncio.sleep(60) # Twiddle my thumbs. PB will reset me. self.send(argformat(STATUS, BROKER_OK)) self.send(argformat(STATUS, RUNNING)) # Set channel running asyncio.create_task(self.from_pyboard()) while True: gc.collect() gc.threshold(gc.mem_free() // 4 + gc.mem_alloc()) await asyncio.sleep(1)
global lcd lcd.fill( 0 ) # Remplir en noir lcd.text( 'T %sC' % temp, 0,6, 1 ) lcd.text( operation, 0, 24, 1) if chaud_etat == 'MARCHE': lcd.fill_rect( 70,0, 58,20, 1 ) lcd.text( chaud_etat, 74, 6, 0) else: lcd.rect( 70,0, 58,20, 1 ) lcd.text( chaud_etat, 74, 6, 1) lcd.show() try: # annonce connexion objet sMac = hexlify( WLAN().config( 'mac' ) ).decode() q.publish( "connect/%s" % CLIENT_ID , sMac ) # Annonce l'état operation = 'Waiting data...' update_lcd() except Exception as e: print( e ) led_error( step=5 ) import uasyncio as asyncio def heartbeat(): """ Led eteinte 200ms toutes les 10 sec """ # PS: LED déjà éteinte par run_every! time.sleep( 0.2 )
print("Running Wlan Connect Test") from network import WLAN from time import sleep print("Starting WLAN") wlan = WLAN(0) wlan.active(True) print("Setting Time") wlan.rtc_set((2018, 8, 27, 10, 00)) print(wlan.rtc_now()) print("Scanning") print(wlan.scan()) sleep(1) print(wlan.scan()) sleep(1) print("Connecting...") wlan.connect("MYENTAP", "entpassword", enterprise=True, entuser="******", entmethod=wlan.EAP_METHOD_PEAP0_MSCHAPv2, entserverauth=True) sleep(1) print("connected status is ") print(wlan.isconnected()) print("ifconfig status is ") sleep(1) print(wlan.ifconfig()) print("done")
def __init__(self, networks: dict): from network import WLAN self.wlan = WLAN(mode=WLAN.STA) self.networks = networks
AP_LIST = json.loads(f.read()) f.close() except: pass else: f = open(ap_list_fname, 'w') f.write(json.dumps(AP_LIST)) f.close() load_ap_list() SSID = coda_common.CODA_CONFIG["lastssid"] PWD = coda_common.CODA_CONFIG["lastappwd"] print("Connecting to ", SSID) wlan = WLAN(mode=WLAN.STA) wlan.connect(SSID, auth=(WLAN.WPA2, PWD)) intTimeout = 0 while not wlan.isconnected(): time.sleep_ms(50) intTimeout += 50 if intTimeout > 10000: break if not wlan.isconnected(): SCAN_LIST = WLAN().scan() time.sleep(3) gc.collect() SCAN_LIST = WLAN().scan()
auth="c3fnh0ile", ) mobileConfig = dict( broker="192.168.43.202", ssid="glue", auth="eulGpassword!", ) debugConfig = mobileConfig #debugConfig = None MQTTClient.DEBUG = False # suppress mqtt_as Memory reports # shutdown 'access point' network interface downlink = WLAN(AP_IF) if downlink.active(): downlink.active(False) # bring up 'station' network interface uplink = WLAN(STA_IF) if not (uplink.active()): uplink.active(True) # prevent certain verbose errors esp.osdebug(None) # overclock CPU for speed freq(160000000) characterIndex = 1
# main.py -- put your code here! from network import WLAN import socket import machine import ssl import time import pycom import connection from machine import Pin from dth import DTH wlan = WLAN(mode=WLAN.STA) th = DTH('P3', 0) time.sleep(2) api_key = '4Y1AM0EW3R2NNC6D' host = 'api.thingspeak.com' while not connection.connect(): connection.connect() addr = socket.getaddrinfo(host, 80)[0][-1] while True: result = th.read() pycom.rgbled(0x001000) # green print("Temperature: %d C" % result.temperature) print("Humidity: %d %%" % result.humidity) path = 'update?api_key=' + api_key + '&' + 'field1' + '=' + str( result.temperature) + '&' + 'field2' + '=' + str(result.humidity) s = socket.socket() s.connect(addr)
from network import mDNS, ftp, telnet, AP_IF, STA_IF, WLAN from machine import idle mdns = mDNS() ap = WLAN(AP_IF) ap.active(True) ap.config(essid='Sparthan') ap.config(authmode=3, password='******') print('WLAN connection succeeded!') mdns.start('sparthan', 'MicroPython Sparthan ESP32') ftp.start(user='******', password='******') #telnet.start(user='******', password='******')
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() # feed the dog self.wdt.feed() # 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 {} 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')
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(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)
################################################## ## MAIN loop ################################################## # print software version info print (os.uname()) print ('Starting BASE (LoRaTracker)') print (' UnitID: ' + str(my_ID)) print ("Starting LED") led.h(led.BLUE) print ("Starting Network") wlan = WLAN() wlan.mode(WLAN.STA) # scan for available networks available_nets = wlan.scan() for net in available_nets: print(' Found SSID: '+ net.ssid) nets = frozenset([e.ssid for e in available_nets]) # match available nets with known nets known_nets_names = frozenset([key for key in known_nets]) net_to_use = list(nets & known_nets_names) # try and use the first matching network 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]
# HELPFUL ## Get files in dir # import os # os.listdir() ## Run python script within REPL # execfile('<filename>') # if the SD card does not mount reset # manually remove and reinsert SD card before reset to fix # TODO: "Figure this out Ben you big dummy" - Ben # sd_wdt = WDT(timeout=((5)*1000)) # Create a station object to store our connection station = WLAN(STA_IF) # activate station station.active(True) def sd_gdt_func(timer): print("SD card did not mount correctly") # TODO: add LED sigal from board to signify this try: umount("/sdcard") except OSError as e: # TODO: add LED signal from board to signify this print("Reinsert SD Card in SD Card reader") # TODO: remove sleep once LED signal is done # sleep gives time to read comment before reseting the board