def run(timer): if not upgrade: print('Running sensors...') import wake wake.main() else: print('Upgrading...') import webrepl, iot iot.init_sta(False) iot.init_ap(True) webrepl.start()
def emergencyReact(state): global emergencyMode if state and not emergencyMode: emergencyMode = True cm.setAP(True) if "webREPL" not in sys.modules: import webrepl webrepl.start() elif not state and emergencyMode: emergencyMode = False cm.setAP(False) webrepl.stop()
def upload(stationid, password, tempf, humidity) : import socket try : #addr_info = socket.getaddrinfo(address, port) addr_info = socket.getaddrinfo("weatherstation.wunderground.com", 80) url = "/weatherstation/updateweatherstation.php?ID=%s&PASSWORD=%s&dateutc=now&tempf=%s&humidity=%s&softwaretype=ESP8266+DHT11&action=updateraw" % (stationid, password, tempf, humidity) addr = addr_info[0][-1] s = socket.socket() s.connect(addr) val = s.send(b"GET %s HTTP/1.0\r\nHost: weatherstation.wunderground.com\r\nUser-Agent: curl/7.43.0\r\nAccept: */*\r\n\r\n" % url) print("send val: %s" % val) print(s.read()) s.close() send_status("uploaded data") except Exception as E : print("An error occurred: %s" % E) #set_led_error(5) import webrepl webrepl.start() raise Exception("Failed to upload data to wunderground.com: %s" % E)
def web_server(): # from util.octopus import w, web_server printTitle("web_server start > ") from lib.microWebSrv import MicroWebSrv import os, webrepl from ubinascii import hexlify from util.wifi_connect import WiFiConnect if Env.wscExp8: from util.i2c_expander import Expander8 expander = Expander8() wc = WiFiConnect() led = None if io_conf.get('led') is None: led = led_init(None) elif io_conf.get('led') == 1: print("Led | ", end="") led = led_init() else: print("Led | ", end="") led = led_init(io_conf.get('led')) led.blink() @MicroWebSrv.route('/setup/wifi/networks.json') # GET def _httpHandlerWiFiNetworks(httpClient, httpResponse): nets = [[item[0], hexlify(item[1], ":"), item[2], item[3], item[4]] for item in wc.sta_if.scan()] httpResponse.WriteResponseJSONOk(nets) @MicroWebSrv.route('/setup/wifi/savednetworks.json') # GET def _httpHandlerWiFiNetworks(httpClient, httpResponse): wc.load_config() nets = [k for k, v in wc.config['networks'].items()] httpResponse.WriteResponseJSONOk(nets) @MicroWebSrv.route('/setup/wifi/network') # Get acutal network def _httpHandlerWiFiCreateNetwork(httpClient, httpResponse): content = None data = dict() sta_ssid = wc.sta_if.config("essid") sta_rssi = wc.sta_if.status("rssi") if wc.sta_if.isconnected() else 0 sta_connected = wc.sta_if.isconnected() sta_active = wc.sta_if.active() ap_ssid = wc.ap_if.config("essid") ap_connected = wc.ap_if.isconnected() ap_active = wc.ap_if.active() ap_stations = [ hexlify(sta[0], ":") for sta in wc.ap_if.status("stations") ] if wc.ap_if.active() else [] data["sta_if"] = { "active": sta_active, "connected": sta_connected, "ssid": sta_ssid, "rssi": sta_rssi } data["ap_if"] = { "active": ap_active, "connected": ap_connected, "ssid": ap_ssid, "stations": ap_stations } httpResponse.WriteResponseJSONOk(data) @MicroWebSrv.route('/setup/wifi/network', "POST") # Create new network def _httpHandlerWiFiCreateNetwork(httpClient, httpResponse): data = httpClient.ReadRequestContentAsJSON() responseCode = 500 content = None if len(data) < 1: responseCode = 400 content = "Missing ssid in request" httpResponse.WriteResponse(code=400, headers=None, contentType="text/plain", contentCharset="UTF-8", content=content) return ssid = data[0] psk = data[1] if len(data) > 1 else "" wc.add_network(ssid, psk) responseCode = 201 httpResponse.WriteResponse(code=responseCode, headers=None, contentType="text/plain", contentCharset="UTF-8", content=content) @MicroWebSrv.route('/setup/wifi/network', "PUT") # Update existing network def _httpHandlerWiFiUpdateNetwork(httpClient, httpResponse): data = httpClient.ReadRequestContentAsJSON() responseCode = 500 content = None print(data) if len(data) < 1: responseCode = 400 content = "Missing ssid in request" httpResponse.WriteResponse(code=400, headers=None, contentType="text/plain", contentCharset="UTF-8", content=content) return ssid = data[0] psk = data[1] if len(data) > 1 else "" print("Updating network {0}".format(data[0])) wc.add_network(ssid, psk) responseCode = 201 httpResponse.WriteResponse(code=responseCode, headers=None, contentType="text/plain", contentCharset="UTF-8", content=content) @MicroWebSrv.route('/setup/wifi/network', "DELETE") # Delete existing network def _httpHandlerWiFiDeleteNetwork(httpClient, httpResponse): data = httpClient.ReadRequestContentAsJSON() responseCode = 500 content = None if len(data) < 1: responseCode = 400 content = "Missing ssid in request" httpResponse.WriteResponse(code=400, headers=None, contentType="text/plain", contentCharset="UTF-8", content=content) return ssid = data[0] wc.remove_network(ssid) responseCode = 201 httpResponse.WriteResponse(code=responseCode, headers=None, contentType="text/plain", contentCharset="UTF-8", content=content) @MicroWebSrv.route('/setup/devices.json') # GET boards def _httpHandlerDevices(httpClient, httpResponse): from util.setup import devices httpResponse.WriteResponseJSONOk(devices) @MicroWebSrv.route('/esp/control_info.json') # GET info def _httpHandlerInfo(httpClient, httpResponse): infoDict = {} infoDict["deviceUID"] = Env.uID infoDict["deviceMAC"] = Env.MAC infoDict["freq"] = Env.freq infoDict["freeRAM"] = getFree() infoDict["freeFLASH"] = str( int(os.statvfs("/")[0]) * int(os.statvfs("/")[3])) ## infoJ = ujson.dumps(infoDict) httpResponse.WriteResponseJSONOk(infoDict) @MicroWebSrv.route('/esp/control/led', "POST") # Set LED def _httpHandlerSetDevice(httpClient, httpResponse): data = httpClient.ReadRequestContent() val = int(data) print("control/led call: " + str(val)) led.value(val) if Env.wscWS: if val == 2: ws.color(RED) if val == 3: ws.color(GREEN) if val == 4: ws.color(BLUE) if val == 5: ws.color(ORANGE) if val == 6: ws.color((128, 0, 128)) if val == 0: ws.color(BLACK) httpResponse.WriteResponseOk(None) @MicroWebSrv.route('/esp/control/pwm', "POST") # PWM - IOT/ Hydroponics LED def _httpLedPwmSet(httpClient, httpResponse): data = httpClient.ReadRequestContent() print("LED PWM Call: " + str(int(data))) if FET is None: httpResponse.WriteResponse( code=500, headers=None, contentType="text/plain", contentCharset="UTF-8", content="MFET is not defined, check setup()") return try: value = int(data) if value > 390: FET.freq(2000) else: FET.freq(300) FET.duty(value) except Exception as e: print("Exception: {0}".format(e)) raise finally: httpResponse.WriteResponseOk(None) httpResponse.WriteResponse(code=204, headers=None, contentType="text/plain", contentCharset="UTF-8", content=None) @MicroWebSrv.route('/esp/control/i2cexpander', "POST") # Set device def _httpHandlerSetI2CExpander(httpClient, httpResponse): from util.i2c_expander import neg data = httpClient.ReadRequestContent() print("i2cexpander.data: " + str(data) + str(bin(int(data)))) try: expander.write_8bit(neg(int(data))) except Exception as e: print("Exception: {0}".format(e)) raise finally: httpResponse.WriteResponseOk(None) @MicroWebSrv.route('/setup/device') # Get actual device def _httpHandlerGetDevice(httpClient, httpResponse): dev = "null" try: os.stat('config/device.json') with open('config/device.json', 'r') as f: dev = f.read() except: pass httpResponse.WriteResponseOk(contentType="application/json", content=dev) @MicroWebSrv.route('/setup/device', "POST") # Set device def _httpHandlerSetDevice(httpClient, httpResponse): data = httpClient.ReadRequestContent() with open('config/device.json', 'w') as f: f.write(data) httpResponse.WriteResponseOk(None) @MicroWebSrv.route('/setup/io') # Get IO configuration def _httpHandlerIOConfigGet(httpClient, httpResponse): from util.io_config import io_conf_file, io_menu_layout, get_from_file as get_io_config_from_file io_conf = get_io_config_from_file() config = [{ 'attr': item['attr'], 'descr': item['descr'], 'value': io_conf.get(item['attr'], None) } for item in io_menu_layout] httpResponse.WriteResponseJSONOk(config) @MicroWebSrv.route('/setup/io', "POST") # Set IO configuration def _httpHandlerIOConfigSet(httpClient, httpResponse): from ujson import dump as json_dump data = httpClient.ReadRequestContentAsJSON() if type(data['value']) is not int: httpResponse.WriteResponse(code=400, headers=None, contentType="text/plain", contentCharset="UTF-8", content="Value is not integer") return from util.io_config import io_conf_file, io_menu_layout, get_from_file as get_io_config_from_file io_conf = get_io_config_from_file() io_conf[data['attr']] = data['value'] with open(io_conf_file, 'w') as f: json_dump(io_conf, f) httpResponse.WriteResponseOk(None) @MicroWebSrv.route('/file_list') def _httpHandlerTestGet(httpClient, httpResponse): path = "/" if "path" in httpClient._queryParams: path = httpClient._queryParams["path"] if len(path) > 1 and path[-1] == '/': path = path[:-1] files = [ "{0}/".format(name) if os.stat(path + "/" + name)[0] & 0o170000 == 0o040000 else name for name in os.listdir(path) ] files.sort() content = ";".join(files) httpResponse.WriteResponseOk(headers=None, contentType="text/html", contentCharset="UTF-8", content=content) mws = MicroWebSrv(webPath='www/') # TCP port 80 and files in /flash/www mws.LetCacheStaticContentLevel = 0 mws.Start(threaded=True) # Starts server in a new thread getFree(True) webrepl.start() print("Web server started on http://{0}".format(wc.sta_if.ifconfig()[0])) return mws @MicroWebSrv.route('/esp/control/relay', "POST") def _httpRelaySet(httpClient, httpResponse): print("Relay Call") data = httpClient.ReadRequestContent() print(data) if RELAY is None: httpResponse.WriteResponse( code=500, headers=None, contentType="text/plain", contentCharset="UTF-8", content="RELAY is not defined, check setup()") return try: value = int(data) RELAY.value(value) except Exception as e: print("Exception: {0}".format(e)) raise finally: httpResponse.WriteResponseOk(None) httpResponse.WriteResponse(code=204, headers=None, contentType="text/plain", contentCharset="UTF-8", content=None)
def setup(): mainOctopus() print("Hello, this will help you initialize your ESP") print("ver: " + ver + " (c)octopusLAB") print("Press Ctrl+C to abort") # TODO improve this # prepare directory if 'config' not in uos.listdir(): uos.mkdir('config') run = True while run: sele = setupMenu() if sele == "x": print("Setup - exit >") time.sleep_ms(2000) print("all OK, press CTRL+D to soft reboot") run = False if sele == "si": #system_info() from util.sys_info import sys_info sys_info() if sele == "ds": print("Device setting:") print(" board_type | soc_type (system on the board)") i = 0 for di in devices: print(str(i) + ": " + str(di[0]) + " | " + str(di[1])) i = i + 1 print() sd = input("select: ") #print(str(devices[int(sd)])) print("> " + str(devices[int(sd)][0]) + " | " + str(devices[int(sd)][1])) dc = {} dc['board_type'] = str( devices[int(sd)][0] ) #input("Board type ('oLAB RobotBoard1' or 'oLAB IoTBoard1'): ") dc['soc_type'] = str(devices[int( sd)][1]) #input("SoC type ('esp32' or 'esp8266'): ") print("Writing to file config/device.json") with open('config/device.json', 'w') as f: ujson.dump(dc, f) # ujson.dump(wc, f, ensure_ascii=False, indent=4) if sele == "ios": print("I/O setting:") # io menu ioMenu() if sele == "iot": print("Testing I/O") from util import io_test io_test.all() if sele == "w": from util.wifi_connect import WiFiConnect w = WiFiConnect() sel_w = wifiMenu() if sel_w == "a": wifi_ssid = input("SSID: ") wifi_pass = input("PASSWORD: "******"r": wifi_ssid = input("SSID: ") w.remove_network(wifi_ssid) if sel_w == "s": print("Saved wifi networks") for k, v in w.config['networks'].items(): print("SSID: {0}".format(k)) if sele == "cw": print("Connect WiFi >") from util.wifi_connect import WiFiConnect w = WiFiConnect() if w.connect(): print("WiFi: OK") else: print("WiFi: Connect error, check configuration") if sele == "cl": print("Connect LAN >") import network lan = network.LAN(mdc=machine.Pin(23), mdio=machine.Pin(18), phy_type=network.PHY_LAN8720, phy_addr=1, clock_mode=network.ETH_CLOCK_GPIO17_OUT) lan.active(1) retry = 0 while not lan.isconnected() or lan.ifconfig()[0] is '0.0.0.0': retry += 1 time.sleep_ms(500) if retry > 20: break if lan.isconnected(): print("LAN: OK") else: print("LAN: Connect error, check cable or DHCP server") if sele == "mq": print("mqtt setup >") try: print() from util.mqtt import mqtt mqtt() except: print("Err.mqtt() or 'util.mqtt.py' does not exist") if sele == "st": print("Time setting >") rtc = machine.RTC() print(str(rtc.datetime())) setdatetime = input( "input 6 numbers - format: RRRRR,M,D,wd,h,m > ") + (",0,0") dt_str = setdatetime.split(",") print(str(dt_str)) dt_int = [int(numeric_string) for numeric_string in dt_str] rtc.init(dt_int) print(str(rtc.datetime())) if sele == "sd": shutil() deplUrl = "https://octopusengine.org/download/micropython/stable.tar" deploy(deplUrl) if sele == "sde": shutil() deplUrl = "https://octopusengine.org/download/micropython/examples.tar" deploy(deplUrl) if sele == "sdp": shutil() deplUrl = "http://iot.petrkr.net/olab/latest.tar" deploy(deplUrl) if sele == "sdo": shutil() deplUrl = "https://octopusengine.org/download/latest.tar" deploy(deplUrl) if sele == "sdh": shutil() deplUrl = "https://octopusengine.org/download/hydroponics.tar" deploy(deplUrl) if sele == "wr": print("under reconstruction <") import esp esp.osdebug(None) import webrepl webrepl.start()
#!/usr/bin/env python3 import usocket from machine import Pin, freq, reset from rfsocket import Esp8266Timings, RFSocket from webrepl import start freq(160000000) # unfortuneately, on lower settings it's almost unusable start() rf_pin = Pin(0, Pin.OUT) REMOTES = {} def remote(remote_id_str): remote_id = int(remote_id_str) if remote_id not in REMOTES: REMOTES[remote_id] = RFSocket(rf_pin, RFSocket.ANSLUT, remote_id=remote_id, timings=Esp8266Timings) return REMOTES[remote_id] def switch_on(remote_id_str, switch_num_str): switch_num = int(switch_num_str) r = remote(remote_id_str) r.on(switch_num) return r.status() def switch_off(remote_id_str, switch_num_str): switch_num = int(switch_num_str) r = remote(remote_id_str)
def console(): import webrepl webrepl.start()
def provision_routine(): #provisioning lcd.clear() lcd.putstr("Scanning") access_points_list = net_if.get_access_points() AP_FOUND = False for ap in access_points_list: if ap['ssid'] == cnf.ssid: lcd.move_to(0, 1) lcd.putstr(cnf.ssid + " found") sleep_ms(2000) lcd.clear() AP_FOUND = True break if AP_FOUND: network_connection_try_count = 5 lcd.putstr(cnf.ssid) lcd.move_to(0, 1) lcd.putstr("Connecting") while network_connection_try_count: if net_if.connect_to_ap(cnf.ssid, cnf.key): sleep_ms(750) lcd.clear() lcd.putstr(cnf.ssid) lcd.move_to(0, 1) lcd.putstr(net_if.station_interface.ifconfig()[0]) if net_if.station_interface.isconnected(): # Network services # Start webrepl when we get network connectivity print("Start Web REPL") webrepl.start() # Set time via ntp when we get internet connectivity print("NTP Sync time") ntptime.settime() break else: lcd.clear() lcd.putstr(cnf.ssid) lcd.move_to(0, 1) lcd.putstr("Connect Fail") sleep_ms(2000) lcd.move_to(0, 1) lcd.putstr(" ") lcd.move_to(0, 1) lcd.putstr("Retrying ") network_connection_try_count -= 1 lcd.putstr(str(network_connection_try_count)) sleep_ms(2000) if not net_if.station_interface.isconnected(): # Set Access Point essid, ip = net_if.start_access_point() lcd.clear() lcd.putstr(net_if.ap_interface.config('essid')) lcd.move_to(0, 1) lcd.putstr(net_if.ap_interface.ifconfig()[0]) # Run Web Server ws.ip = net_if.ap_interface.ifconfig()[0] ws.setup() ws_return_data = ws.runner(access_points_list) cnf.ssid = ws_return_data['ssid'] cnf.key = ws_return_data['network_key'] cnf.cloud_address = url_decode(ws_return_data['cloud_address']) cnf.save_config() sleep_ms(750) reset()
motors = motor.DCMotors(i2c) motors.brake(0) motors.brake(3) import Robot carro = Robot.Control(motors) # replserver boot code try: import usocket as socket except: import socket import os import webrepl webrepl.start(password='******') replpath = "webrepl-inlined.html.gz" s = socket.socket() ai = socket.getaddrinfo("0.0.0.0", 80) addr = ai[0][-1] s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) s.bind(addr) s.listen(5) def accept_handler(sock): res = sock.accept() print("Handling") client_s = res[0]
def start_webrepl(): if use_webrepl: webrepl.start() else: webrepl.stop()
# https://docs.micropython.org/en/latest/esp32/quickref.html#webrepl-web-browser-interactive-prompt # import webrepl_setup #and following on-screen instructions. After reboot, it will be available for connection. If you disabled automatic start-up on boot, you may run configured daemon on demand using: import webrepl webrepl.start() # or, start with a specific password webrepl.start(password='******')
# set response code and append RR resp = bytearray(m[:end+5]) # resp[2] = (resp[2]&0x01)|0x84 # is reply resp[3] &= 0x10 # AD for i in range(8, 12): # no auth or additional resp[i] = 0 rdatas = db.get((qname, qtype)) if not rdatas: #look for cname then rdatas = db.get((qname, b'\x00\x05')) qtype = b'\x00\x05' if not rdatas: #NXD resp[3] |= 0x03 # NXD else: resp[7] = len(rdatas) for rdata in rdatas: resp += b'\xC0\x0C' #always point to question for qname resp += qtype resp += b'\x00\x01' # IN resp += b'\x00\x00\x03\x84' #900S TTL resp += rdata s.sendto(resp, addr) except KeyboardInterrupt as e: from webrepl import start start() break except Exception as e: print("Exception: {0}".format(e), type(e)) sleep(2) reset()
def webpython(): webrepl.start()
utime.sleep(0.1) retry = retry - 1 print('wlan reply:', wlan.status(), ' at time:', utime.ticks_ms(), ' retry:', retry) return wlan.isconnected() def do_connect(): import network if not wlan.active(): wlan.active(True) if not wlan.isconnected(): print('connecting to network...') nets = wlan.scan() nets.sort(key=lambda ap: ap[3], reverse=True) for net in nets: print('Network found:', net[0].decode('UTF-8'), ' bssid:', ubinascii.hexlify(net[1]), ' sec:', decode_sec(net[4]), ' rssi:', net[3]) for sid, pwd in MY_LAN: if net[0].decode('UTF-8') == sid: # wlan.ifconfig(('192.168.1.12', '255.255.255.0', '192.168.1.1', '8.8.8.8')) #hardkoded data will save some time wlan.connect(net[0].decode('UTF-8'), pwd) if waitForConnection(): print('WLAN connection succeeded!') break print('network config:', wlan.ifconfig()) do_connect() webrepl.start(password=WEBREPL_PWD)
screen.fb.set_line_range_palette(122, 124, 0b1111100000000000, 0xffff) screen.fb.set_line_range_palette(124, 126, 0b0000011111000000, 0xffff) screen.fb.set_line_range_palette(126, 128, 0b1111111111000000, 0xffff) screen.print_line('Pretty colours!', 9) except: pass screen.print_line('Starting...', 0) gc.collect() wifi.auto_connect() gc.collect() webrepl.start(password='') gc.collect() screen.print_line('WebREPL started', 4) panel.start_panel() gc.collect() sys.path.append('/user') from lib import splash try: import main
def enableWebREPL(self): print( webrepl.start() )
def subMenuItemClicked(self): if self.getSubMenuID() == 0: if self.getSubMenuPage() == 1: if self.getCursor() == 3 and self.getOkButtonValue() == 0: self.slider(1, ' Contrast', minValue=0, maxValue=19, defaultVal=10) if self.getCursor() == 4 and self.getOkButtonValue() == 0: self.slider(2, ' brightness', minValue=0, maxValue=1023, defaultVal=512) if self.getCursor() == 5 and self.getOkButtonValue() == 0: txt1 = self.convertibleText(self.getCursor(), 2, self.subMenulcdSettings, 'backlight:OFF', 'backlight:ON') if txt1 == 'backlight:OFF': self.setSliderInfo(2, 1023) self.setLCDBacklightPWMduty(1023) if txt1 == 'backlight:ON': self.setSliderInfo(2, 1) self.setLCDBacklightPWMduty(1) if self.getCursor() == 6 and self.getOkButtonValue() == 0: txt2 = self.subMenulcdSettings[2] if txt2 == 'backlight:ON': self.subMenulcdSettings[2] = self.subMenulcdSettings[2].replace('backlight:ON', 'backlight:OFF') lcd.println(2, 5, 'backlight:OFF') self.setSliderInfo(2, 0) self.setLCDBacklightPWMduty(512) self.setSliderInfo(1, 0) self.lcdContrast(10) if self.getOkButtonValue() == 0: self.backToSubMenu() if self.getSubMenuPage() == 2: if self.getCursor() == 3 and self.getOkButtonValue() == 0: self.backToMainMenu() if self.getSubMenuID() == 1: if self.getSubMenuPage() == 1: if self.getCursor() == 3 and self.getOkButtonValue() == 0: repl = self.convertibleText(self.getCursor(), 0, self.subMenuWebrepl, 'stop', 'start') if repl == 'stop': webrepl.start() if repl == 'start': webrepl.stop() if self.getCursor() == 4 and self.getOkButtonValue() == 0: self.backToMainMenu() if self.getOkButtonValue() == 0: self.backToSubMenu() if self.getSubMenuID() == 2: if self.getSubMenuPage() == 1: if self.getCursor() == 5 and self.getOkButtonValue() == 0: self.slider(3, ' Sub3', minValue=0, maxValue=19, defaultVal=10) if self.getSubMenuPage() == 2: if self.getCursor() == 5 and self.getOkButtonValue() == 0: self.slider(4, ' Sub7', minValue=0, maxValue=19, defaultVal=10) if self.getOkButtonValue() == 0: self.backToMainMenu() if self.getSubMenuID() == 3: if self.getSubMenuPage() == 1: if self.getCursor() == 3 and self.getOkButtonValue() == 0: self.txSend('On\n\r') if self.getCursor() == 4 and self.getOkButtonValue() == 0: self.txSend('Off\n\r') if self.getCursor() == 5 and self.getOkButtonValue() == 0: self.backToMainMenu() if self.getOkButtonValue() == 0: self.backToSubMenu()
import time, math, ujson, network
# This file is executed on every boot (including wake-boot from deepsleep) #import esp #esp.osdebug(None) import secrets # Import secret data import webrepl webrepl.start() # Start the webREPL interface import network import esp esp.osdebug(0) # Debug messages import gc gc.collect() # Garbage collection # Set ssid and psk ssid = secrets.ssid passwd = secrets.psk # Start Access Point ap = network.WLAN(network.AP_IF) ap.active(True) # Configure AP with ssid, psk and WPA2 auth ap.config(essid=ssid, password=passwd, authmode=3)
def wait_connections(self, interface, sleeptime): # Main loop awaiting connections refresh30 = '<meta http-equiv="refresh" content="300">\r\n' redirect2 = '<meta http-equiv="refresh" content="2; url=/"/>\r\n' error404 = '404 - Error' while True: try: self.conn, self.addr = self.socket.accept() except KeyboardInterrupt: return except: continue try: req = self.conn.readline() except: continue # conn - socket to client // addr - clients address while True: h = self.conn.readline() if not h or h == b'\r\n': break # Some defaults that can be changed in progress code = 200 extension = 'h' refresh = '' # determine request method (GET / POST are supported) r = parse_request(req) if r == None: code = 404 content = error404 elif r['uri'] == b'/' or r['uri'] == b'/index': content = '<h2>%s %s</h2>' % (self.title, control.status()) elif r['uri'] == b'/on': content = '<h2>Switch %s</h2>' % control.switch_on() elif r['uri'] == b'/off': content = '<h2>Switch %s</h2>' % control.switch_off() elif r['uri'] == b'/temperature': content = cb_temperature() content = '' elif r['uri'] == b'/j': extension = 'j' content = cb_temperature_json() content = '' elif r['uri'] == b'/getconf': content = cb_getconf() elif b'/setconf' in r['uri']: if 'key' in r['args'] and 'value' in r['args']: content = cb_setconf(r['args']['key'], r['args']['value']) elif 'key' in r['args']: content = cb_setconf(r['args']['key'], None) else: content = cb_setconf(None, None) self.title = config.get_config('place') # just in case elif r['uri'] == b'/status': content = cb_status() elif r['uri'] == b'/webrepl': import webrepl webrepl.start() sleeptime = 299 # almost 5 minutes refresh = redirect2 code = 302 content = '<h2>Webrepl +5min</h2></div>' elif r['uri'] == b'/5min': sleeptime = 299 # almost 5 minutes refresh = redirect2 code = 302 content = '<h2>+5min</h2></div>' elif r['uri'] == b'/reboot': content = '<h2>Reboot</h2></div>' self.http_send(code, content, extension, redirect2) self.conn.close() machine.reset() elif r['file'] != b'': myfile = r['file'] code = 200 content = cb_open(myfile) else: code = 404 content = error404 # At end of loop just close socket and collect garbage self.http_send(code, content, extension, refresh) self.conn.close() gc.collect()
safeModeIndicatePin.on() print('*****') print('Booted into SAFE MODE') print('*****') sys.exit() def mem(label='mem'): print('--------------') print(label) import gc gc.collect() micropython.mem_info() webrepl.start(password='******') def setup_ap(): ap = network.WLAN(network.AP_IF) ap.active(True) ap.config(essid='E-SPrinkler', authmode=network.AUTH_WPA_WPA2_PSK, password="******") aws_client = None zone_scheduler = None ui_manager = None rtc_time = None
def do_connect(): connected = False sta_if = network.WLAN(network.STA_IF) sta_if.active(True) if (sta_if.isconnected()): connected = True if (connected == False): print("Trying TP-LINK_6F7BD8") sta_if.connect('TP-LINK_6F7BD8', 'xxxxxxxx') # print("Trying NETGEAR41_2GEXT") # sta_if.connect('NETGEAR41_2GEXT', 'xxxxxxxx') while not sta_if.isconnected(): pass if (sta_if.isconnected()): connected = True print('network config:', sta_if.ifconfig()) ap_if = network.WLAN(network.AP_IF) ap_if.active(True) ap_if.config(essid='PoolPumpESP') return connected while (do_connect() != True): pass webrepl.start() gc.collect()
def setup_network(cls) -> bool: # now see our prioritised list of networks and find the first available network try: with open(cls.config_file, "r") as f: config = json.loads(f.read()) cls.preferred_networks = config['known_networks'] cls.ap_config = config["access_point"] if config.get("schema", 0) != 2: log.warning( "Did not get expected schema [2] in JSON config.") except Exception as e: log.error("Failed to load config file, no known networks selected") cls.preferred_networks = [] return # set things up cls.webrepl_triggered = False # Until something wants it cls.wlan().active(True) # scan what’s available available_networks = [] cls.wlan().disconnect() for network in cls.wlan().scan(): ssid = network[0].decode("utf-8") bssid = network[1] strength = network[3] available_networks.append( dict(ssid=ssid, bssid=bssid, strength=strength)) # Sort fields by strongest first in case of multiple SSID access points available_networks.sort(key=lambda station: station["strength"], reverse=True) # Get the ranked list of BSSIDs to connect to, ranked by preference and strength amongst duplicate SSID candidates = [] for aPreference in cls.preferred_networks: for aNetwork in available_networks: if aPreference["ssid"] == aNetwork["ssid"]: connection_data = { "ssid": aNetwork["ssid"], "bssid": aNetwork[ "bssid"], # NB: One day we might allow collection by exact BSSID "password": aPreference["password"], "enables_webrepl": aPreference["enables_webrepl"] } candidates.append(connection_data) for new_connection in candidates: log.info("Attempting to connect to network {0}...".format( new_connection["ssid"])) # Micropython 1.9.3+ supports BSSID specification so let's use that if cls.connect_to(ssid=new_connection["ssid"], password=new_connection["password"], bssid=new_connection["bssid"]): log.info("Successfully connected {0}".format( new_connection["ssid"])) cls.webrepl_triggered = new_connection["enables_webrepl"] break # We are connected so don't try more # Check if we are to start the access point cls._ap_start_policy = cls.ap_config.get("start_policy", "never") should_start_ap = cls.wants_accesspoint() cls.accesspoint().active(should_start_ap) if should_start_ap: # Only bother setting the config if it WILL be active log.info("Enabling your access point...") cls.accesspoint().config(**cls.ap_config["config"]) cls.webrepl_triggered = cls.ap_config["enables_webrepl"] cls.accesspoint().active( cls.wants_accesspoint()) # It may be DEACTIVATED here # may need to reload the config if access points trigger it # start the webrepl according to the rules if cls.webrepl_triggered: webrepl.start() # return the success status, which is ultimately if we connected to managed and not ad hoc wifi. return cls.wlan().isconnected()
def main(): # Sets a flag in a file to force the device into work mode on ntext reboot oneFirstBit() cm.setAP(True) # Activate Access Point webrepl.start() # Activate webREPL
def webrepl(): import webrepl webrepl.start()
# This file is executed on every boot (including wake-boot from deepsleep) #import esp #esp.osdebug(None) import webrepl webrepl.start()
def webrepl_start(): webrepl.start()