def join_home_net(essid, password): global _attempts Pin(2, Pin.OUT).low() sta_if = network.WLAN(network.STA_IF) sta_if.active(True) if sta_if.active() and sta_if.isconnected(): import webrepl webrepl.stop() sta_if.disconnect() if not sta_if.isconnected(): sta_if.active(True) print('Attempting to connect to: "' + str(essid) + '"') sta_if.connect(essid, password) attempt_count = 0 while not sta_if.isconnected() and attempt_count < _attempts: time.sleep(1) attempt_count += 1 pass print('network config: ', sta_if.ifconfig()) if sta_if.isconnected(): Pin(2, Pin.OUT).high() return True else: Pin(2, Pin.OUT).low() sta_if.active(False) return False
def webreplHandle(req, resp): req.parse_qs() if (req.form['state'] == 'on'): webrepl.start() if (req.form['state'] == 'off'): webrepl.stop() yield from picoweb.jsonify(resp, {'help': 'webrepl?state=on/off'})
def web_repl(stop=False): import webrepl if stop: webrepl.stop() REPL[0] = False return if not REPL[0]: webrepl.start(password=cfg.get('DEBUG_PASS', 'python')) REPL[0] = True
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 reset(): """Stops webrepl before doing a reset""" import webrepl, machine, utime print("Resetting...") webrepl.stop() # a work-around for: https://github.com/micropython/micropython/issues/2635 # there is no rtc.init, so trying to set up the timer - this didn't work either rtc = machine.RTC() rtc.irq(trigger=rtc.ALARM0, wake=machine.DEEPSLEEP) rtc.alarm(rtc.ALARM0, 5000) utime.sleep_ms(3000) machine.reset()
def webrepl_start(self, active=True): """start webrepl if configured before, otherwise do nothing""" self.webrepl = None try: import webrepl if active: with open(MPyConfigBase.WEBREPL_CFG) as f: webrepl.start() self.webrepl = webrepl else: webrepl.stop() except Exception as ex: pass
def sleep(self, msg=None): import machine from sys import platform from utime import sleep_ms try: import webrepl except: webrepl = None LOG_FILENAME = "./log.txt" if msg is not None: logger.warning(msg) with open(LOG_FILENAME, 'a') as log_file: log_file.write(msg + "\n") if self.current_sensor is not None: self.current_sensor.stop() if self._current_state['params']['sleep'] < 1: # exit: stop the infinite loop of main & deep-sleep from sys import exit logger.info("Staying awake due to sleep parameter < 1.") if webrepl is not None: webrepl.start() # configure timer to issue reset, so the device will reboot and fetch a new shadow state TIME_BEFORE_RESET = 120000 # 3 minutes in milliseconds tim = machine.Timer(-1) # tim.init throws an OSError 261 after a soft reset; this is a work-around: try: tim.init(period=TIME_BEFORE_RESET, mode=machine.Timer.ONE_SHOT, callback=lambda t: machine.reset()) except Exception as e: logger.warning( "Exception '%s' on tim.init; No reset after a timer expiry.", e) exit(0) if webrepl is not None: webrepl.stop() logger.info("Going to sleep for %s seconds.", self._current_state['params']['sleep']) if platform == 'esp32': # multiply sleep time by approx 1000 (left shift by 10) machine.deepsleep(self._current_state['params']['sleep'] << 10) else: self.rtc.irq(trigger=self.rtc.ALARM0, wake=machine.DEEPSLEEP) self.rtc.alarm(self.rtc.ALARM0, self._current_state['params']['sleep'] << 10) machine.deepsleep()
def setup( name, password, reset=True ): global wifi_config if name != wifi_config.name or \ password != wifi_config.password: f=open("wifi_config.py", "w") f.write("name=\"%s\"\npassword=\"%s\"" % (name,password)) f.close() print("Updated wifi_config.") wifi_config.name = name wifi_config.password = password if reset: print("Resetting system in 3 seconds.") time.sleep(1) webrepl.stop() time.sleep(2) machine.reset() else: connect()
def checkWifiStatus(knownaps, wlan=None, conf=None, repl=True): """ """ badWifi = False # Check on the state of some things to see if we're really connected if (wlan is None) or (wlan.isconnected()) is False: badWifi = True else: # The board thinks we're connected, but it might be confused. # There might be a few different fail cases that end up here. # DHCP likely expired and didn't renew if wlan.ifconfig()[0] == "0.0.0.0": badWifi = True if badWifi is True: print("WiFi is no bueno!") # Redo! wlan = startWiFi() nearbyaps, wlan = scanWiFi(wlan) bestAP = None bestssid = None if knownaps is not None: bestAP = checkAPList(knownaps, nearbyaps) if bestAP != {}: bestssid = bestAP['ssid'] if bestssid is not None: # Attempt to actually connect conf = connectWiFi(wlan, bestAP, knownaps[bestssid]) if repl is True: webrepl.stop() time.sleep(0.5) webrepl.start() else: print("No Known Access Point Found!") else: print("WiFi is bueno!") return wlan, conf
from todo import Todo import utils import webrepl import network import time if __name__ == "__main__": try: utils.do_quick_reset() wlan_ap = network.WLAN(network.AP_IF) wlan_ap.active(False) if utils.try_connect_internet(): webrepl.stop() wlan_ap.active(False) time.sleep(0.3) target = Todo() target.run() # 业务逻辑执行成功,主板灯闪烁3次 utils.flash_board_led(3) else: wlan_ap.active(True) webrepl.start() # 如果网络未连接,主板灯常亮 utils.flash_board_led(off_time=-1) except KeyboardInterrupt: print("\nPress CTRL+D to reset device.")
def handleInterrupt(timer): global interruptCounter global save_flag interruptCounter = interruptCounter + 1 if interruptCounter == 1: timeserver = setting.get('timeserver') if timeserver == '': setting.set('timeserver', 'pool.ntp.org') webrepl.stop() RepUpdate.new(VBat) if interruptCounter <= 5: print('<= 5 sec') if adc.read() < 200: timer.deinit() wifi.do_nothing() wifi.do_sta() print('Push Message') led_blink(10, 200, 0) if wifi.wait_sta(15): try: import GenSasToken import AzurePublish import ubinascii import network mac = ubinascii.hexlify(network.WLAN().config('mac'),':').decode().upper() UserJson = setting.get('userjson') UserJson = UserJson.strip('\n') UserJson = UserJson.strip('\r') UserJson = UserJson.strip('\n') UserJson = UserJson.strip(' ') UserJson = UserJson.lstrip('{') UserJson = UserJson.rstrip('}') UserJson = UserJson.strip(' ') msg = '{"UniqueID": "' + mac + '"' if UserJson != '': msg += ',' + UserJson msg += '}' gc.collect() token = GenSasToken.now() gc.collect() encoded = AzurePublish.data(msg, token) except: encoded = 'ERROR' else: encoded = 'ERROR' if encoded != 'ERROR': try: dict = ujson.loads(encoded) dict = dict["desired"] setting.set('FWnumberNew', dict["FWnumber"]) setting.set('FWurl', dict["FWurl"]) except: print('ERROR TWIN MSG') led_blink(1, 1023, 0) else: print('ERROR Azure TX') led_blink(1, 0, 1023) time.sleep(2) led_blink(1, 0, 0) RepUpdate.update() shutdown(save_flag) if interruptCounter == 5: print('5 sec') led_blink(1, 200, 200) if interruptCounter == 10: print('10 sec') if adc.read() < 200: print('WEB AP ...') timer.deinit() wifi.do_nothing() wifi.do_ap() led_blink(1, 0, 200) time.sleep(2) try: import webserver webserver.start() except: print('WEB Server Crash') led_blink(1, 0, 0) shutdown() else: led_blink(3, 200, 200) if interruptCounter == 15: print('15 sec') if adc.read() < 200: print('WEB STA ...') timer.deinit() wifi.do_nothing() wifi.do_sta() led_blink(3, 0, 200) if wifi.wait_sta(15): try: import webserver webserver.start() except: print('WEB Server Crash') led_blink(1, 0, 0) shutdown() else: led_blink(10, 0, 511) print('Repair Time 120 sec') wifi.do_nothing() wifi.do_ap() wifi.do_sta() wifi.wait_sta(15) webrepl.start() if interruptCounter == 120: timer.deinit() print('120 sec') shutdown(False)
def stop(): webrepl.stop()
def webrepl_stop(): webrepl.stop()
def webrepl_stop(): import webrepl webrepl.stop()
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()
def start_webrepl(): if use_webrepl: webrepl.start() else: webrepl.stop()