machine.PWRON_RESET: 'PWRON', # Press reset button on FiPy machine.HARD_RESET: 'HARD', machine.WDT_RESET: 'WDT', # Upload and restart from USB or machine.reset() machine.DEEPSLEEP_RESET: 'DEEPSLEEP', machine.SOFT_RESET: 'SOFT', machine.BROWN_OUT_RESET: 'BROWN_OUT' } # init _config = Config.getInstance() _ds_positions = { v: k for k, v in _config.get_value('sensors', 'ds1820', 'positions').items() } _wm = WLanManager(_config) _wlan = network.WLAN(id=0) measurement_interval = _config.get_value('general', 'general', 'measurement_interval') #set up watchdog, on start timeout only after 1min wdt = machine.WDT(timeout=60 * 1000) loop_run = True cycle = 0 crcerrcnt = 0 oled = _config.get_value('general', 'general', 'oled') if oled: i2c = I2C(0, I2C.MASTER, pins=('P9', 'P10')) # PyCom FiPy _oled = sensors.ssd1306.SSD1306_I2C(128, 64, i2c) # x, y, bus
def start_measurement(): global cycle, loop_run, crcerrcnt perf = machine.Timer.Chrono() #pycom.heartbeat(False) #pycom.rgbled(0x007f00) # reconfigure watchdog timeout wdt.init(timeout=3 * measurement_interval * 1000) until_wifi_reconnect = _config.get_value('general', 'general', 'until_wifi_reconnect') #log("Memory dump on startup:") #micropython.mem_info(True) while loop_run: cycle = cycle + 1 text = str(cycle) + ". Messung" log(text) # start time measuring perf.start() rgb_led(0x003000) # Measure all enabled sensors data = {} #read RSSI try: wlan = network.WLAN(mode=network.WLAN.STA) data['rssi'] = _wlan.joined_ap_info().rssi except: data['rssi'] = 0 pass # Start DS1820 conversion if ds1820 is not None: roms = ds1820.scan() if roms: ds1820.convert_temp() time.sleep_ms(750) print(' DS18B20: Messung gestartet...') else: print("No DS1820 found. Is it connected properly?") ms_conversion_start = perf.read_ms() # Read data from BME280 if bme280 is not None: try: bme280val = bme280.read_compensated_data() # auslesen BME280 bme280tmp = int(bme280val[0] * 10) / 10 # 1 Stelle nach Komma bme280pre = int(bme280val[1] / 10) / 10 bme280hum = int(bme280val[2] * 10) / 10 print(' BME280: ', bme280tmp, 'C', bme280pre, 'mbar', bme280hum, '%') data['t'] = bme280tmp data['p'] = bme280pre data['h'] = bme280hum except: log("BME280 not measuring.") ms_bme_read = perf.read_ms() - ms_conversion_start # Read data from HX711 if hx711 is not None: hx711akt = hx711.get_value(times=1) hx711akt = int( hx711akt * 1000) / 1000 # 3 Dezimalstellen nach Komma print(' HX711: ', hx711akt, 'kg') data['weight_kg'] = hx711akt ms_hx_read = perf.read_ms() - ms_bme_read # Read data from DS1820 # if ds1820 is not None and ds1820.roms: # ms_to_conversion = 750 - perf.read_ms() # if ms_to_conversion > 0: # time.sleep_ms(int(ms_to_conversion)) # for rom in ds1820.roms: # try: # ds_measurement = ds1820.read_temp_async(rom=rom) # ds_name = binascii.hexlify(rom).decode('utf-8') # if ds_name in _ds_positions: # data[_ds_positions[ds_name]] = ds_measurement # except: # log("Did not find rom.") # ms_ds_read = perf.read_ms() - ms_hx_read if ds1820 is not None: print(' DS18B20:', end=' ') ds_data = ds1820.read_all(_ds_positions) data.update(ds_data) print(' ') ms_ds_read = perf.read_ms() - ms_hx_read #Ermitteln und Ausgabe der Zeit write_time = time.time() write_time = write_time + 3600 # UTC + 1 Stunde datetime_list = time.localtime(write_time) datetime_string = "{:4d}-{:02d}-{:02d} {:02d}:{:02d}:{:02d}".format( *datetime_list[0:6]) time_string = "{:02d}:{:02d}:{:02d}".format(*datetime_list[3:6]) print(' Zeiten: ', end=' ') print(time_string, end=' ') if oled: try: _oled.fill(0) # alles aus _oled.text(str(cycle), 0, 0) _oled.text(time_string, 64, 0) _oled.text("Waage ", 0, 9) if 'weight_kg' in data: _oled.text(str(data['weight_kg']), 64, 9) _oled.text("kg", 110, 9) _oled.text("BME280 ", 0, 18) if 't' in data: _oled.text(str(data['t']), 0, 27) if 'p' in data: _oled.text(str(data['p']), 40, 27) if 'h' in data: _oled.text(str(data['h']), 95, 27) _oled.text("DS18B20 ", 0, 36) if 't_i_1' in data: # _oled.text(str(round(data['t_i_1'],1)), 0, 45) _oled.text(str(data['t_i_1']), 0, 45) if 't_i_2' in data: _oled.text(str(data['t_i_2']), 50, 45) if 't_i_3' in data: _oled.text(str(data['t_i_3']), 95, 45) if 't_i_4' in data: _oled.text(str(data['t_i_4']), 0, 54) if 't_i_5' in data: _oled.text(str(data['t_i_5']), 50, 54) if 't_o' in data: _oled.text(str(data['t_o']), 95, 54) _oled.show() # anzeigen except: print('OLED Fehler', end=' ') print(' WLAN: ', end=' ') # Log measured values, if possible if (_config.get_value('networking', 'wlan', 'enabled') and _wlan.mode() == network.WLAN.STA and _wlan.isconnected() and _beep is not None): _beep.add(data) log(data) """ Daten auf SD-Karte """ # print(' Daten an SD-Karte') if _csv is not None: # _csv.add_dict(data) _csv.add_data_didi(data) ms_log_data = perf.read_ms() - ms_ds_read # Trying to reconnect to wifi if possible: if (_config.get_value('networking', 'wlan', 'enabled') and _beep is not None and ((not _wlan.mode() == network.WLAN.STA) or (not _wlan.isconnected()))): log("wlan is enabled but not connected.") until_wifi_reconnect -= 1 log("trying to reconnect in {} intervals".format( until_wifi_reconnect)) if until_wifi_reconnect <= 0: log('wlan not connected try to reconnect') wdt.init(timeout=1 * 60 * 1000) _wm.enable_client() until_wifi_reconnect = _config.get_value( 'general', 'general', 'until_wifi_reconnect') wdt.init(timeout=3 * measurement_interval * 1000) else: until_wifi_reconnect = _config.get_value('general', 'general', 'until_wifi_reconnect') # Collect garbage gc.collect() micropython.mem_info() ms_gc = perf.read_ms() - ms_log_data perf.stop() time_elapsed = perf.read_ms() time_until_measurement = measurement_interval * 1000 - time_elapsed perf.reset() # cycle += 1 # log("#{:d}, Seconds elapsed: {:.3f}s," # "time until next measurement: {:.3f}s".format(cycle, # time_elapsed/1000, # time_until_measurement/1000)) # log("DS1820: {:.0f}ms + {:.0f}ms, BME280: {:.0f}ms, HX711: {:.0f}ms " # "Log: {:.0f}ms, GC: {:.0f}ms".format(ms_conversion_start, # ms_ds_read, # ms_bme_read, # ms_hx_read, # ms_log_data, # ms_gc)) wdt.feed() if time_until_measurement > 0: rgb_led(0x080800) time.sleep_ms(int(time_until_measurement))
async def _publish(self): val = {} if platform != "linux": sta = network.WLAN(network.STA_IF) else: sta = None val["Pysmartnode version"] = config.VERSION if config.RTC_SYNC_ACTIVE is True: if self._last_boot is None: for _ in range(5): if time.localtime()[0] == 2000: # not synced await asyncio.sleep(1) t = time.time() # polling earlier might not have synced. s = round(time.ticks_ms() / 1000) self._last_boot = time.localtime( t - s) # last real boot/reset, not soft reset t = self._last_boot val["Last boot"] = "{}-{:02d}-{:02d} {:02d}:{:02d}:{:02d}".format( t[0], t[1], t[2], t[3], t[4], t[5]) s = int(time.time() - time.mktime(t)) else: s = int(time.ticks_ms() / 1000 + 0.5) # approximate uptime depending on accuracy of ticks_ms() m, s = divmod(s, 60) h, m = divmod(m, 60) d, h = divmod(h, 24) val["Uptime"] = '{:d}T{:02d}:{:02d}:{:02d}'.format(d, h, m, s) logging.getLogger("RAM").info(gc.mem_free(), local_only=True) val["RAM free (bytes)"] = gc.mem_free() if sta is not None: try: val["RSSI"] = sta.status("rssi") except Exception as e: val["RSSI"] = 0 # platform doesn't support reading rssi print(e) try: val["IPAddress"] = sta.ifconfig()[0] except Exception as e: print(e) pass else: val["RSSI"] = 0 # can't read rssi on unix port, might not even be connected by WLAN try: val["Micropython version"] = os.uname().version except: pass s = int(_mqtt.getDowntime()) m, s = divmod(s, 60) h, m = divmod(m, 60) d, h = divmod(h, 24) val["MQTT Downtime"] = '{:d}T{:02d}:{:02d}:{:02d}'.format(d, h, m, s) val["MQTT Reconnects"] = _mqtt.getReconnects() val["MQTT Dropped messages"] = _mqtt.getDroppedMessages() val["MQTT Subscriptions"] = _mqtt.getLenSubscribtions() if config.DEBUG: # only needed for debugging and could be understood wrongly otherwise val["MQTT TimedOutOps"] = _mqtt.getTimedOutOperations() val["MQTT Repubs"] = _mqtt.REPUB_COUNT val["Asyncio waitq"] = "{!s}/{!s}".format( len(asyncio.get_event_loop().waitq), config.LEN_ASYNC_QUEUE) await _mqtt.publish(_mqtt.getDeviceTopic("status"), val, qos=1, retain=False, timeout=5) del val gc.collect() if config.DEBUG: # DEBUG to check RAM/Heap fragmentation import micropython micropython.mem_info(1)
def __init__(self, config): self.config = config self.wlan = network.WLAN()
from third_party import string import network import socket import os import utime import ssl from third_party import rsa from third_party.umqtt.simple import MQTTClient from ubinascii import b2a_base64 from machine import Pin, ADC, I2C, RTC import ntptime import ujson import config #setup wireles interface sta_if = network.WLAN(network.STA_IF) def on_message(topic, message): print((topic, message)) def connect(): if not sta_if.isconnected(): print('connecting to network...') sta_if.active(True) sta_if.connect(config.wifi_config['ssid'], config.wifi_config['password']) while not sta_if.isconnected(): pass print('network config: {}'.format(sta_if.ifconfig()))
SSID = "Studio Tau" PASSWORD = "******" #SSID="lokalet" #PASSWORD="******" import network, time print("Starting graphics") import runner print("Connecting to WiFi (%s)..." % (SSID)) wlan = network.WLAN(network.STA_IF) wlan.active(True) wlan.connect(SSID, PASSWORD) wlan.config('mac') time.sleep(4) wlan.ifconfig() print("Starting WebRepl") import webrepl webrepl.start()
def test(): import network sta_if = network.WLAN(network.STA_IF) local_addr = sta_if.ifconfig()[0] server = SlimDNSServer(local_addr, "micropython") server.run_forever()
import gc import uasyncio import uos import network import machine import time import ubinascii import usocket import uselect import gc import ure import tinyweb import logging gc.collect() wifi = network.WLAN(network.STA_IF) loop = uasyncio.get_event_loop() CLIENT_ID = ubinascii.hexlify(machine.unique_id()) SERVER = '' #已经在config文件配置过 PUB_TOPIC = CLIENT_ID + b'/state' # TOPIC的ID, TOPIC需要byte类型 SUB_TOPIC = CLIENT_ID + b'/set' MSG_INTERVAL = 5 # MQTT消息间隔5s MQTTClient.DEBUG = False # Optional: print diagnostic messages uart = UART(0) sreader = uasyncio.StreamReader(uart) swriter = uasyncio.StreamWriter(uart, {}) config['subs_cb'] = sub_callback config['connect_coro'] = conn_han
def captive_portal(self): existing_config = False try: with open("wifi.json", "r") as f: configs = f.read() j = ujson.loads(configs) print(j) con = self.connection(j['network_name'], j['network_password']) if con is True: existing_config = True print("Network connected") else: existing_config = False print("Incorrect network configuration") except: print("No saved network") if existing_config is False: ap = network.WLAN(network.AP_IF) ap.active(True) ap.config(essid=self.essid_name, authmode=1) ip = ap.ifconfig()[0] print("DNS Server: dom.query. 60 in A {:s}".format(ip)) udps = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) udps.setblocking(False) udps.bind(('', 53)) s = socket.socket() ai = socket.getaddrinfo(ip, 80) print("Web Server: Bind address information: ", ai) addr = ai[0][-1] s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) s.bind(addr) s.listen(1) s.settimeout(2) print("Web Server: Listening http://{}:80/".format(ip)) # Modify this to match the form response that you are expecting regex = ure.compile("network\?ssid=(.*?)&password=(.*?)\sHTTP") set_connection = False while set_connection is False: try: data, addr = udps.recvfrom(4096) print("Incoming data...") dns = DNSQuery(data) udps.sendto(dns.response(ip), addr) print("Replying: {:s} -> {:s}".format(dns.domain, ip)) except: print("No DNS") try: res = s.accept() client_sock = res[0] client_addr = res[1] req = client_sock.recv(4096) print("Client:", client_addr) print("Request:") print(req) with open('index.html', 'r') as content: client_sock.send(content.read()) client_sock.close() print() search_result = regex.search(req) if search_result: # Modify these to match the form responses you are expecting incoming_network_name = search_result.group(1) incoming_network_pass = search_result.group(2) con = self.connection(incoming_network_name, incoming_network_pass) if con is True: # Modify this to match the config you are writing out d = { "network_name": incoming_network_name, "network_password": incoming_network_pass } with open("wifi.json", "w") as f: f.write(ujson.dumps(d)) set_connection = True except: print("Timeout") time.sleep_ms(1000) udps.close() ap.active(False)
import socket import network import machine import time mi_led=machine.Pin(0,machine.Pin.OUT) #configuramos el pin D3 mi_led.value(0) #encendemos el led. #-----configuramos la red mired=network.WLAN(network.AP_IF) mired.config(essid="prueba_de_red_local", authmode=network.AUTH_WPA_WPA2_PSK, password="******") mired.active(True) print('configuracion total: ',mired.ifconfig()) #........................ def abrir_socket(): s=socket.socket() #creamos el socket s.bind(("", 8266)) s.listen(1) #se deja el socket esperando a clientes cliente,a=s.accept() print("se ha conectado un cliente", cliente) print("Informacion adicional: ",a) while True: data=cliente.recv(1) #recibimos un byte. print(data[0]) #revisar que imprie data despues de cero? #ascci 1
# This file is executed on every boot (including wake-boot from deepsleep) #import esp #esp.osdebug(None) import micropython as mp # pylint: disable=import-error import system as sys import secret if __name__ == "__main__": import machine # pylint: disable=import-error sys.reset_cause = machine.reset_cause() sys.print_reset_cause() import network # pylint: disable=import-error sys.wlan0 = network.WLAN(network.STA_IF) sys.wlan0.active(True) sys.wlan0.connect(secret.WIFI_SSID, secret.WIFI_PASS) from app import app
import gc from uthread import thread from urandom import randrange from time import sleep import machine VERSION = "1" # Software version DB_VERSION = "1" # Database version DEFAULT_DEVICE_NAME = "pinger_test" import network MAC_ADDRESS = "".join("%02x" % d for d in network.WLAN().config('mac')) del (network) # Simulate nvram storge using flash # nvram is getting smacked WAY too often def storage(data=None): try: if data != None: with open('.config', 'w') as f: f.write(data) else: with open('.config') as f: data = f.read() f.close() except: pass
def getmac(): import network import ubinascii return ubinascii.hexlify(network.WLAN().config('mac'), ':').decode()
# This file is executed on every boot (including wake-boot from deepsleep) import esp esp.osdebug(None) import gc import network from utime import sleep_ms sta_if = network.WLAN(network.STA_IF) ap_if = network.WLAN(network.AP_IF) if not sta_if.isconnected(): print('connecting to network...') sta_if.active(True) sta_if.connect('Fischnetz', 'incubator') while not sta_if.isconnected(): pass ap_if.active(False) print('network config sta_if:', sta_if.active()) print('network config ap_if:', ap_if.active()) print('network config:', sta_if.ifconfig()) import webrepl webrepl.start() gc.collect()
import network import time def read_profiles(): with open("wifiman.conf") as f: lines = f.readlines() profiles = {} for line in lines: if line.find(":")>=0: ssid, password = line.strip("\n").split(":") profiles[ssid] = password return profiles wlan_sta = network.WLAN(network.STA_IF) def get_connection(): """return a working WLAN(STA_IF) instance or None""" # First check if there already is any connection: if wlan_sta.isconnected(): return wlan_sta connected = False try: # ESP connecting to WiFi takes time, wait a bit and try again: time.sleep(3) if wlan_sta.isconnected(): return wlan_sta # Read known network profiles from file profiles = read_profiles()
#con write() mandamos el dato al arduino uart.write(strRecv) """ Se inicializa un objeto UART para el envio de datos por serial, en este caso debido a que el ESP-01 solo tiene un pin TX, este se especifica como el pin 0 """ uart = UART(0, 115200) uart.init(115200, bits=8, parity=None, stop=1) """ Se habilita la conexion wifi para el ESP-01 con el objeto WLAN de network """ nic = network.WLAN(network.STA_IF) nic.active(True) while nic.isconnected(): #connect(), nos ayuda a conectarnos, se especifica #nombre de red y clave. nic.connect('SSID', 'PASSWORD') time.sleep(1) print(nic.isconnected()) print(nic.ifconfig()) """ Se inicializa un socket, necesario para que el esp escuche datos enviados por un codigo externo. """ s = socket.socket()
polarpin.value(0) # set to 1 for positive polarity # DATA STORAGE AND COUNTERS sendbuf = array('H', [720]) # 1440 byte buffer for calibration routine data = array( 'H', [0] * 4 ) # buffer for writing adc interrupt data from adc.read_timed() in calibration() and ADC_IT_poll() calibdata = array('H', [0] * 4) # buffer to store ADC data from calibadc count = 0 # counter for pulses read peakcount = 0 ratecounter = 0 # counter for rate measurements STATE = "STARTUP" # state variable for applying startup settings etc. ADC_STATE = "SingleDMA" # monitor state of ADC configs # SET UP WIRELESS ACCESS POINT wl_ap = network.WLAN(1) # init wlan object wl_ap.config(essid='PYBD') # set AP SSID wl_ap.config(channel=1) # set AP channel wl_ap.active(1) # enable the AP # LOOP UNTIL A CONNECTION IS RECEIVED while wl_ap.status('stations') == []: utime.sleep(1) # SET UP THE NETWORK SOCKET FOR UDP s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) s.bind(('', 8080)) # network listens on port 8080, any IP destipv4 = ('192.168.4.16', 8080) # destination for sending data print("SOCKET BOUND") #==================================================================================#
import machine #imports machine library import network #imports network library import socket #imports socket library import json ap = network.WLAN( network.AP_IF ) #Sets up an access point that allows other WiFi clients to connect to it ap.active(True) #Sets the access point to active ap.config(essid='ESP32-WIFI-NAMEa' ) #Sets up the name of the access point to any given string (essid) ap.config( authmode=3, password='******' ) #Setting the access point encryption type to WPA2-PSK and setting the access point password to a given string #Setting up pins as a variable that fetches all the inputs (the value read from the pin/whether it is on or off) of the listed pins, and saving them in a list pins = [machine.Pin(i, machine.Pin.IN) for i in ([15])] #html description #setting up the variable html as a document with type .html #html code for an html file. The <html> tag shows that the file is an html file #The <head> tag demarcates the head of the page #The <title> tag is for for formatting the text in the head as a title #The <body> tag is to demarcate the body of the file from the head #Inside the body, the <h1> tag demarcates a header inside the body #Creating a table with the name of the Pins in one column and the value of the corresponding pin in an adjacent column #All tags are closed with the corresponding </> tags html = """<!DOCTYPE html> <html> <head> <title>ESP32 Pins</title> </head>
def start_access_point(ssid, password): access_point = network.WLAN(network.AP_IF) access_point.active(True) access_point.config(essid=ssid, password=password, authmode=network.AUTH_WPA_WPA2_PSK) return access_point
# Returns the number of seconds, as an integer, since the Epoch, # assuming that underlying RTC is set and maintained as described above. # If an RTC is not set, this function returns number of seconds since a # port-specific reference point in time (for embedded boards without a # battery-backed RTC, usually since power up or reset). If you want to develop # portable MicroPython application, you should not rely on this function to # provide higher than second precision. # ------------------------- # Microsecond ticks elapsed target_host = "www.google.com" url = "http://%s" % target_host target_port = 80 # Create a station object to store our connection station = network.WLAN(network.STA_IF) # activate station station.active(True) station.scan() station.connect("Dunkin' Donuts Guest", "") while not station.isconnected(): utime.sleep(1) start = utime.ticks_us() r = str(reqst.get(url)) print(str(r)) #get link and try connection for a in r.split('"'): try: proto, dummy, host, path = a.split("/", 3)
#An idea to broadcast some promotional messages through continuous ssid renaming, fill the messages.txt with your messages import machine import time import network #set the messages file mess_file = 'messages.txt' #service function to generate the network name def essid_rename(message): ap_if.config(essid=message, authmode=network.AUTH_WPA_WPA2_PSK, password='******') ap_if.active(True) #setup the wireles interface ap_if = network.WLAN(network.AP_IF) file_handler = open(mess_file) messages = file_handler.read().split('\n') file_handler.close() for i in messages: data = i.split('\t') timing = int(data[0]) essid = str(data[1]) essid_rename(essid) time.sleep(timing)