def check_OTA_update(): # Configuration (if you are looking for the server pubkey: it's in the OTA class) #TODO: Change server URL and Pubkey to non-testing versions SERVER_URL = "ota.iot.wheelmap.pro" SERVER_PORT = 80 NBIOT_APN = "iot.1nce.net" NBIOT_BAND = None #None = autoscan NBIOT_ATTACH_TIMEOUT = 15 * 60 #seconds NBIOT_CONNECT_TIMEOUT = 15 * 60 #seconds WATCHDOG_TIMEOUT = 15 * 60 * 1000 #milliseconds #setup watchdog wdt = machine.WDT(timeout=WATCHDOG_TIMEOUT) wdt.feed() #initialize ota object variable for proper exception handling ota = None try: # # Setup Wifi OTA # from ota_wifi_secrets import WIFI_SSID, WIFI_PW # ota = WiFiOTA(WIFI_SSID, # WIFI_PW) # Setup NB-IoT OTA print("Initializing LTE") lte = LTE() lte.reset() lte.init() ota = NBIoTOTA(lte, NBIOT_APN, NBIOT_BAND, NBIOT_ATTACH_TIMEOUT, NBIOT_CONNECT_TIMEOUT) #start the update itself print("Current version: ", ota.get_current_version()) ota.connect(url=SERVER_URL, port=SERVER_PORT) ota.update() # the update did not fail, proceed to check file integrity n = ota.check_stored_files() if n > 0: print("%d corrupted files detected and reloaded! Rebooting ..." % n) time.sleep(0.5) machine.reset() except Exception as e: raise (e) #let top level loop handle exception finally: if ota is not None: ota.clean_up() # before leaving, set watchdog to large value, so we don't interfere # with code in main.py (wdt can never be disabled after use) wdt = machine.WDT(timeout=10 * 24 * 60 * 60 * 1000) wdt.feed()
def test_wdt_init_call(self): # Pycom firmware raises if you attempt to give the timeout as positional with self.assertRaises(TypeError): wdt = machine.WDT(1000 * 60 * 60) with self.assertRaises(TypeError): wdt = machine.WDT(timeout=None) # Correct usage wdt = machine.WDT(timeout=1000 * 60 * 60) wdt.init(1000 * 60 * 60)
def reset(led): import machine wdt = machine.WDT() wdt.feed() while True: led(not led()) sleep_ms(250)
def reset(led): import machine wdt = machine.WDT() wdt.feed() led(0) machine.reset()
def main(): print('Device UP!') wdt = machine.WDT() wdt.feed() sensor = ESPSensors(pin=config['dht_pin'], sensor_type=['t', 'h'], sensor_model=config['dht_model']) sensor.set_name(config['device_name']) sensor.set_expire_after_seconds(int(config['sleep_time_sec']) + 10) sensor.register_sensor() wdt.feed() wlan = wlan_connect(config['wifi_ssid'], config['wifi_passwd'], config['net_ip'], config['net_mask'], config['net_gw'], config['net_dns']) print(wlan.ifconfig()) wdt.feed() templates = sensor.get_template() discover_topics = sensor.get_discover_topic() values = sensor.get_value() print(values) json_attributes = { 'name': config['device_name'], 'ip_address': wlan.ifconfig()[0] } mqtt_client = MQTTClient(config['device_name'], server=config['mqtt_server'], port=1883, user=bytearray(config['mqtt_user'], 'utf-8'), password=bytearray(config['mqtt_password'], 'utf-8')) mqtt_client.connect() for s_type in ['temperature', 'humidity']: lwt_topic = templates[s_type]['availability_topic'] mqtt_client.set_last_will(lwt_topic, 'offline', retain=True) wdt.feed() mqtt_client.publish(bytearray(lwt_topic), bytearray('online'), retain=True) wdt.feed() mqtt_client.publish(bytearray(discover_topics[s_type]), bytearray(dumps(templates[s_type])), retain=True, qos=0) wdt.feed() mqtt_client.publish(bytearray(templates[s_type]['state_topic']), bytearray(str(values[s_type])), retain=True, qos=0) wdt.feed() mqtt_client.publish(bytearray( templates[s_type]['json_attributes_topic']), bytearray(dumps(json_attributes)), retain=True, qos=0) wdt.feed() mqtt_client.disconnect()
async def senddata(pinSensor, text, deviceKey): wdt = machine.WDT(timeout=60000) wdt.feed() data = await zmeraj(pinSensor, text) await uaiohttpclient.run(method="POST", url="http://" + config.TB_URL + ":8080/api/v1/" + deviceKey + "/telemetry", data="{\"tmp\": " + str(data) + "}")
def __init__(self , global_data , wd_timeout_ms = WATCHDOG_TIMEOUT_MS) : #print ("Watchdog: init") self.global_data = global_data self.active_interval_ms = 2000 self.active_next_ms = self.global_data.active_next_ms (300) self.wdt = machine.WDT (timeout=wd_timeout_ms)
async def run_wdt(): wdt = machine.WDT(timeout=120000) print("WDT RUN") while True: wdt.feed() # gc.collect() print("WDT RESET") await asyncio.sleep(30)
def _feed_task(): global feeding feeding = time.ticks_ms() wdt = machine.WDT(0, 5000) while True: if time.ticks_diff(time.ticks_ms(), feeding) < timeout: wdt.feed() await asyncio.sleep(1)
def show(tft): # https://github.com/loboris/MicroPython_ESP32_psRAM_LoBo/wiki/machine#machinewdtenable start_time = time.time() _ = machine.WDT(False) mandelbrot( tft, width=TFT_WIDTH, height=TFT_HEIGHT, left=const(-2), right=0.5, top=const(1.25), bottom=const(0), iterations=const(40), ) _ = machine.WDT(True) duration = time.time() - start_time print("rendered in %.1f sec." % duration)
def start_wdt(timeout=30000): if not wdt_disabled(): print("Starting WDT...") wdt = machine.WDT(timeout=timeout) else: print("WDT disabled") wdt = None return wdt
def wlan_connect(wifi_ssid, wifi_passwd, net_ip, net_mask, net_gw, net_dns): wdt = machine.WDT() wlan = network.WLAN(network.STA_IF) if not wlan.active(): wlan.active(True) wlan.ifconfig((net_ip, net_mask, net_gw, net_dns)) if not wlan.isconnected(): wlan.connect(wifi_ssid, wifi_passwd) t = 0 while not wlan.isconnected() and t <= 3000: wdt.feed() machine.idle() t += 1 return wlan
def run(): global tstump (t, h, p, v, vs, msg) = measure() vbat = v if FAKE_SLEEP: print("No watchdog") else: wdt = machine.WDT(timeout=int(DEEP_SLEEP + DEEP_SLEEP / 2) * 1000) while True: tstump = '%s-%.2d-%.2d %.2d:%.2d:%.2d' % time.localtime()[0:6] if POSITIONING != 'NO': position() (t, h, p, v, vs, msg) = measure() print("TZ: %s LONGITUDE: %s" % (cfg['tz'], cfg['longitude'])) dat = update_data([ t, h, p, v, vs, paz.duty(), palt.duty(), machine.wake_reason(), msg ]) try: config = { "sleep": DEEP_SLEEP, "fake_sleep": FAKE_SLEEP, "ts_cfg": tstump, "Vsun": LVL_SUNPIN } print("Publish config: %s %s" % (MY_ID, config)) me.send_publish('weather/%s/config' % MY_ID, json.dumps(config)) dat.reverse() print("Publish id: %s Length:%s" % (MY_ID, len(dat))) for line in dat: me.send_publish('weather/' + MY_ID, json.dumps(to_dict(line))) except Exception as e: print("Publish exception: %s" % e) stime = DEEP_SLEEP - (time.time() - lib.boot_time) if stime < 0: stime = 1 elif stime > DEEP_SLEEP: stime = DEEP_SLEEP if FAKE_SLEEP: stime = stime / 20 print("Fake sleep for %s sec" % stime) time.sleep(stime) lib.boot_time = time.time() else: print('Deepsleep for %s sec.' % stime) wdt.feed() machine.deepsleep(stime * 1000) print()
def start(mqtt, config): global wdt, timeout, safemode, revert, allok # Re-init WDT with configured timeout timeout = config.get("timeout", 300) wdt = machine.WDT(timeout=timeout * 1000) log.info("WDT updated with %d seconds timeout", timeout) # Init feeder config import __main__ safemode = __main__.safemode revert = config.get("revert", True) allok = config.get("allok", 300) * 1000 __main__.GLOBALS()["watchdog"] = sys.modules["watchdog"] # Feeder starts once we're connected mqtt.on_init(init(mqtt.client, config["prefix"]))
def __init__(self): self.wdt = machine.WDT(timeout=WATCHDOG_TIMEOUT_MS) self.wdt.feed() self.state = None self.states = {} self.lastError = None self.failedBackend_Communications = 0 self.timeStateLog = [] self.sensorOverThresholdFlag = False self.system = None # set all necessary time values self.intervalForInactivityEventS = FIRST_INTERVAL_INACTIVITY_S self.startTime = 0 log.info("\033[0;35m[Core] Initializing magic... \033[0m ✨ ") log.info("[Core] Hello, I am %s", ubinascii.hexlify(machine.unique_id()))
def perform_software_update(): global HTTP_CLIENT if not HTTP_CLIENT: HTTP_CLIENT = HttpClient() machine.WDT() manage_memory() version_data = load_version() device_type = get_device_type() srv_url = updates_url() srv_index = load_srv_json('index', srv_url=srv_url) machine.resetWDT() srv_versions = load_srv_json('devices', srv_url=srv_url) machine.resetWDT() if srv_index: for path, entry in srv_index.items(): if 'devices_types' in entry and 'base' not in entry[ 'devices_types'] and device_type not in entry[ 'devices_types']: continue if path in version_data['files'] and version_data['files'][ path] == entry['hash']: continue local_path = entry['path'] if 'path' in entry else path print(local_path) ensure_file_path(local_path) file_url = srv_url + 'software/' + path print(file_url) while version_data['files'].get(path) != entry['hash']: if HTTP_CLIENT.get_to_file(file_url, 'file_buf'): try: uos.remove(local_path) except OSError: pass uos.rename('file_buf', local_path) if version_data['hash']: version_data['hash'] = None version_data['files'][path] = entry['hash'] save_version(version_data) print('complete') machine.resetWDT() version_data['hash'] = srv_versions[device_type] version_data['update'] = False save_version(version_data) machine.reset()
def run(): global hours if FAKE_SLEEP: print("No watchdog") else: wdt = machine.WDT(timeout=int(DEEP_SLEEP+DEEP_SLEEP/2)) while True: tt = time.gmtime() hours = tt[3] + tt[4] * (1/60) + tz if hours>4 and hours<20: if POSITIONING == 'SCAN': scan() elif POSITIONING == 'ADOPT': az = az_adopt() time.sleep(1) alt = altitude() time.sleep(1) else: az = azimuth() time.sleep(1) alt = altitude() time.sleep(1) (t, h, p, v, vs, msg) = measure() print("HOSTPORT: %s TZ: %s LONGITUDE: %s" % (hostport, tz, longitude)) msg = msg + ( ' AZ:%s' % paz.duty() ) + (' ALT:%s' % palt.duty()) message = 'WakeReason:%s' % machine.wake_reason() + ( msg if msg else '' ) dat = update_data([t, h, p, v, vs, message]) try: print("Post my_id: %s Length:%s" % (MY_ID, len(dat))) res = urequests.post('http://%s/id/%s' % (hostport, MY_ID), json={'measures':dat}) except Exception as e: print("POST exception: %s" % str(e)) if FAKE_SLEEP : sleeptime = float(DEEP_SLEEP/10000) print("Fake sleep for %s sec" % sleeptime) time.sleep(sleeptime) else: print('Deepsleep for %s sec.' % str(DEEP_SLEEP/1000)) wdt.feed() machine.deepsleep(DEEP_SLEEP) print()
def main(): screen.reset() # https://github.com/loboris/MicroPython_ESP32_psRAM_LoBo/wiki/machine#machinewdtenable machine.WDT(False) start_time = time.time() mandelbrot( screen, width=screen.width, height=screen.height, left=const(-2), right=0.5, top=const(1.25), bottom=const(-1.25), iterations=const(40), ) duration = time.time() - start_time print("rendered in %.1f sec." % duration)
def __init__(self): """Init""" machine.WDT(True) self.tft = self.initDisplay() self.tft.clear() self.encoder_state_machine = RotaryIRQ(25, 26, min_val=0, max_val=2, reverse=True, range_mode=Rotary.RANGE_WRAP) self.encoder_grinder_time = None self.run = True self.update_display = True self.print_s = 0.0 self.encoder_value = 0 self.state = 0 self.state_old = 0 self.edit_state = False self.cup = Cup() self.single_sec = machine.nvs_getint("single_sec") self.double_sec = machine.nvs_getint("double_sec") self.cps = machine.nvs_getint("cps") self.seconds = 0.1 self.edit_cps = False self.pin_start = machine.Pin(33, mode=machine.Pin.IN, pull=machine.Pin.PULL_DOWN, handler=self.__startGrinding, trigger=machine.Pin.IRQ_HILEVEL, acttime=0, debounce=500000) self.pin_menu = machine.Pin(27, mode=machine.Pin.IN, pull=machine.Pin.PULL_DOWN, handler=self.setCPS, trigger=machine.Pin.IRQ_FALLING, acttime=0, debounce=500000) self.pin_out = machine.Pin(32, mode=machine.Pin.INOUT) self.pin_out.value(False)
from network_controller import NetworkController from lenfer_device import LenferDevice from utils import manage_memory, load_json LOOP = uasyncio.get_event_loop() LOG = logging.getLogger("Main") async def wdt_feed(): await uasyncio.sleep(10) machine.resetWDT() LOOP.create_task(wdt_feed()) machine.WDT(True) NETWORK_CONTROLLER = NetworkController() if NETWORK_CONTROLLER.online(): software_version = load_json('version.json') if software_version and software_version['update']: from software_update import perform_software_update perform_software_update() machine.reset() manage_memory() DEVICE = LenferDevice(NETWORK_CONTROLLER) manage_memory()
import time import machine import ubinascii import sys from network import WLAN from network import Bluetooth import usocket as socket from pysense import Pysense from LIS2HH12 import LIS2HH12 from SI7006A20 import SI7006A20 from LTR329ALS01 import LTR329ALS01 from MPL3115A2 import MPL3115A2,ALTITUDE,PRESSURE from secrets import WIFISSID, WIFIPASS wdt = machine.WDT(timeout=300000) py = Pysense() mp = MPL3115A2(py,mode=ALTITUDE) # Returns height in meters. Mode may also be set to PRESSURE, returning a value in Pascals si = SI7006A20(py) lt = LTR329ALS01(py) li = LIS2HH12(py) bt = Bluetooth() bt.set_advertisement(name="pycom") bt.advertise(True) while True: wdt.feed() bt.start_scan(10) while bt.isscanning():
def _wdt_reset(): machine.WDT(0, 2)
import machine t = machine.WDT(0, 5) # init wdt 0, timeout 5s t.feed() # feed it t.delete() # close it
def init(timeout): global _wdt #pylint: disable=global-statement if _wdt is None: _wdt = machine.WDT(timeout=timeout)
async def run_wdt(): wdt = machine.WDT(timeout=60000) print("WDT RUN") while True: wdt.feed() await asyncio.sleep(20)
import network, time, machine wlan = network.WLAN(network.STA_IF) wlan.active(True) if wlan.isconnected(): print("No WiFi Connection") # code to handle the problem ... print("Connecting to Wifi ... ") wlan.connect('EE49-2.4', '122Hesse', 5000) #wlan.connect('Next time for sure though', 'Dontworryaboutit', 5000) for _ in range(1000): if wlan.isconnected(): print("Connected to WiFi!") break time.sleep_ms(100) if not wlan.isconnected(): print("Unable to connect to WiFi") wlan.disconnect() machine.WDT(False) rtc = machine.RTC() rtc.ntp_sync(server="pool.ntp.org") for _ in range(100): if rtc.synced(): break time.sleep_ms(100) if rtc.synced(): print(time.strftime("%c", time.localtime())) else: print("Unable to get ntp time")
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 _oled.fill(0) _oled.show() # DS18B20 new if _config.get_value('sensors', 'ds1820', 'enabled'): owPin = _config.get_value('sensors', 'ds1820', 'pin')
def __init__(self, my_id, server, port=8123, ssid='', pw='', timeout=2000, conn_cb=None, conn_cb_args=None, verbose=False, led=None, wdog=False): self._my_id = '{}{}'.format(my_id, '\n') # Ensure >= 1 newline self._server = server self._ssid = ssid self._pw = pw self._port = port self._to = timeout # Client and server timeout self._tim_ka = timeout // 4 # Keepalive interval self._concb = conn_cb self._concbargs = () if conn_cb_args is None else conn_cb_args self._verbose = verbose self._led = led if wdog: if platform == 'pyboard': self._wdt = machine.WDT(0, 20000) def wdt(): def inner(feed=0): # Ignore control values if not feed: self._wdt.feed() return inner self._feed = wdt() else: def wdt(secs=0): timer = machine.Timer(-1) timer.init(period=1000, mode=machine.Timer.PERIODIC, callback=lambda t: self._feed()) cnt = secs run = False # Disable until 1st feed def inner(feed=WDT_CB): nonlocal cnt, run, timer if feed == 0: # Fixed timeout cnt = secs run = True elif feed < 0: # WDT control/callback if feed == WDT_CANCEL: timer.deinit() # Permanent cancellation elif feed == WDT_CB and run: # Timer callback and is running. cnt -= 1 if cnt <= 0: machine.reset() return inner self._feed = wdt(20) else: self._feed = lambda x: None self._sta_if = network.WLAN(network.STA_IF) ap = network.WLAN(network.AP_IF) # create access-point interface ap.active(False) # deactivate the interface self._sta_if.active(True) gc.collect() if platform == 'esp8266': import esp # Improve connection integrity at cost of power consumption. esp.sleep_type(esp.SLEEP_NONE) self._evfail = asyncio.Event() # Set by any comms failure self._evok = asyncio.Event() # Set by 1st successful read self._s_lock = asyncio.Lock() # For internal send conflict. self._w_lock = asyncio.Lock() # For .write rate limit self._last_wr = utime.ticks_ms() self._lineq = Queue(20) # 20 entries self.connects = 0 # Connect count for test purposes/app access self._sock = None self._acks_pend = ASetByte() # ACKs which are expected to be received gc.collect() asyncio.create_task(self._run())
config_FTP_USER = '******' config_FTP_PASSWORD = '******' config_WEB_USER = '******' config_WEB_PASSWORD = '******' config_ERROR = True if config_AP_ON_TIME_SEC < 120: config_AP_ON_TIME_SEC = 120 _ftp = Server() _ftp.deinit() _web = WebServer(config_WEB_USER, config_WEB_PASSWORD) if not config_ERROR and (len(config.MB_TCP_IP) > 0): _wdt = machine.WDT(timeout=20000) _status_ap_enabled_once = False _status_mb_got_request = False _modbus = ModbusTCP() print('ModbusTCP created') _modbus_process = _modbus_tcp_process pycom.heartbeat(False) pycom.rgbled(0x00ff00) #_modbus_process() start_ms = time.ticks_ms() while True:
async def wdt_feeder(): wdt = machine.WDT(timeout=WDT_TIMEOUT) while True: await asyncio.sleep_ms(WDT_TIMEOUT // 3) wdt.feed()