def main(): global numPRs global ticks global colorsForNumPRs wdt = WDT(timeout=15000) while True: wdt.feed() # print(ticks) if wlan.mode() == WLAN.AP: drawErrorForTicks(ticks) ticks += 1 time.sleep_ms(13) continue # about every 10 s: if ticks % (800 // 2) == 0: print('load colors') colorsForNumPRs = loadSettings(select="colors") print('getting...') getAndPrintPRs() drawForTicks(ticks, numPRs) ticks += 1 time.sleep_ms(13)
async def wdt(self): from machine import WDT wdt = WDT() while True: wdt.feed() await sleep_ms(WDT_DELAY)
def wdt(): from machine import WDT from time import sleep wdt = WDT(timeout=10000) #10 seconds of hanging while True: wdt.feed() sleep(1)
class WDT(StatusModule): """ A status modue that uses the invocation of the status functions to feed a watchdog timer. """ def __init__(self): super(WDT, self).__init__() from machine import WDT as PYCOM_WDT self.wdt = PYCOM_WDT(timeout=1000*self.config().get("timeout")) def feed(self): self.wdt.feed() def status(self, type): self.feed() def log(self, level, message): self.feed() def test(self): self.feed() def measurement(self, bytearray, json): self.feed() def get_config_definition(): return ( "status_wdt", "This module is a watchdog using the status functions as a way too be fed.", ( ("timeout", "60", "Defines how many seconds to wait after the last status message occured until the device is reset.", ConfigFile.VariableType.uint), ) )
def main(): wdt = WDT(timeout=3000) homie = HomieDevice(settings) homie.add_node(Error()) # publish device and node properties homie.publish_properties() # subsribe to topics homie.subscribe_topics() while True: # reset the errors homie.errors = 0 # publish device data homie.publish_data() # feed wdt if we have no errors if not homie.errors: wdt.feed() utime.sleep(1)
def httpserver(fromcard = False, rootpath = '', watchdog = False): global webroot #logging.basicConfig(level=logging.ERROR) addr = get_address() if fromcard: from shields import microsd_shield sdcard = microsd_shield.MicroSD_Shield() sdcard.mount() webroot = '/sd/wwwroot' if rootpath: webroot = rootpath #uasyncio.set_debug(1) loop = uasyncio.get_event_loop() loop.create_task(uasyncio.start_server(serve_content, addr, 80, 20)) if watchdog: from machine import Pin, WDT wdt = WDT() wdt.feed() led = Pin(2, Pin.OUT) loop.create_task(heartbeat(wdt, led)) loop.run_forever() loop.close() if fromcard: sdcard.unmount() #httpserver()
async def heartbeat(): speed = 1500 led = Pin(2, Pin.OUT, value=1) wdt = WDT() while True: led.value(led.value() ^ 1) wdt.feed() await asyncio.sleep_ms(speed)
def __init__(self, led, period=5, max_count=10): self._max_count = max_count self.__alarm = Timer.Alarm(self._seconds_handler, period, periodic=True) self._led = led self._count = 0 self._wdt = WDT(timeout=period * 2 * 1000) # enable WDT with a timeout of 2*period seconds
class Publish: def __init__(self, publish_stack): configs = get_configs() self.ip = configs['broker_mqtt']['ip'] self.port = configs['broker_mqtt']['port'] self.user = configs['broker_mqtt']['user'] self.password = configs['broker_mqtt']['pass'] self.topic = bytes(configs['broker_mqtt']['topic'], "utf-8") self.uuid = configs['gateway']['uuid'] self.publish_stack = publish_stack self.wdt = WDT(timeout=1000 * 60 * 15) def connect(self): while True: try: while self.publish_stack.length() > 0: failed_send = False data = json.loads(self.publish_stack.get()) i = 1 while i < 9: try: if 'tries' in data: data.update({'tries': data['tries'] + 1}) else: data.update({'tries': 1}) if not 'gateway' in data: data.update({'gateway': {'uuid': self.uuid}}) c = MQTTClient(self.topic, self.ip, self.port, self.user, self.password) c.connect() c.publish(self.topic, json.dumps(data).encode()) c.disconnect() failed_send = False self.wdt.feed() break except Exception: i += 1 failed_send = True time.sleep(5) # no persistency for ack answer if failed_send and data['type'] != 'identification': self.publish_stack.write_buffer(json.dumps(data)) self.publish_stack.delete() # TODO: verify necessity of sleep here except Exception as e: self.publish_stack.delete() log("Publish-connect: {}".format(e)) time.sleep(5)
def reconfigure_watchdog(self, timeout_seconds=600): try: from machine import WDT watchdog_timeout = timeout_seconds watchdog_timeout_effective = watchdog_timeout * 1000 wdt = WDT(timeout=watchdog_timeout_effective) wdt.init(watchdog_timeout_effective) print('INFO: Reconfigured watchdog to {} seconds'.format(watchdog_timeout)) except: pass
class watchdog(object): def __init__(self, wdtimeout): #self._wdtimeout = wdtimeout+30000 print('Timeout', wdtimeout) self._watchdog = WDT(timeout=wdtimeout) def run(self): while True: self._watchdog.feed() print('reset timeout') yield 2
def start(self, interval=60): """ Begins to publish temperature data on an interval (in seconds). This function will not exit! Consider using deep sleep instead. :param interval: How often to publish temperature data (60s default) :type interval: int """ wdt = WDT() while True: self.publishTemperature() time.sleep(interval) wdt.feed()
def __init__(self, publish_stack): configs = get_configs() self.ip = configs['broker_mqtt']['ip'] self.port = configs['broker_mqtt']['port'] self.user = configs['broker_mqtt']['user'] self.password = configs['broker_mqtt']['pass'] self.topic = bytes(configs['broker_mqtt']['topic'], "utf-8") self.uuid = configs['gateway']['uuid'] self.publish_stack = publish_stack self.wdt = WDT(timeout=1000 * 60 * 15)
def start(self): if not self.enabled: log.info('Skipping watchdog timer (WDT)') return watchdog_timeout = self.timeout log.info('Starting the watchdog timer (WDT) with timeout {}ms'.format( watchdog_timeout)) from machine import WDT self.wdt = WDT(timeout=watchdog_timeout) # Feed Watchdog once. self.feed()
def __init__(self, id, frequency, datarate, ssid, password, server, port, ntp_server='pool.ntp.org', ntp_period=3600): self.id = id self.server = server self.port = port self.frequency = frequency self.datarate = datarate self.ssid = ssid self.password = password self.ntp_server = ntp_server self.ntp_period = ntp_period self.server_ip = None self.rxnb = 0 self.rxok = 0 self.rxfw = 0 self.dwnb = 0 self.txnb = 0 self.sf = self._dr_to_sf(self.datarate) self.bw = self._dr_to_bw(self.datarate) self.stat_alarm = None self.pull_alarm = None self.uplink_alarm = None self.wlan = None self.sock = None self.udp_stop = False self.udp_lock = _thread.allocate_lock() self.lora = None self.lora_sock = None self.rtc = machine.RTC() self.wdt = WDT(timeout=50000)
async def relay_loop(self, conns, deadline): max_timeout = 5005 wdt = None try: if self.uPK.WATCHDOG_TIMEOUT: from machine import WDT wdt = WDT(timeout=self.uPK.WATCHDOG_TIMEOUT) max_timeout = min(max_timeout, self.uPK.WATCHDOG_TIMEOUT // 2) except KeyboardInterrupt: raise except: pass await fuzzy_sleep_ms() try: pool = uPageKiteConnPool(conns, self) while pool.conns and self.keep_running and time.time() < deadline: if wdt: wdt.feed() self.uPK.GC_COLLECT() timeout_ms = min(max(100, (deadline - time.time()) * 1000), max_timeout) await fuzzy_sleep_ms() if await pool.process_io(self.uPK, int(timeout_ms)) is False: raise EofTunnelError('process_io returned False') if self.reconfig_flag: if self.uPK.info: self.uPK.info("Exiting relay_loop early: reconfiguration requested.") return False # Happy ending! return True except KeyboardInterrupt: raise except Exception as e: if self.uPK.debug: print_exc(e) self.uPK.debug('Oops, relay_loop: %s(%s)' % (type(e), e)) # We've fallen through to our unhappy ending, clean up for conn in conns: try: conn.close() except Exception as e: if self.uPK.debug: self.uPK.debug("Oops, close(%s): %s" % (conn, e)) return False
def __init__(self, debug=False): self.cfg = None self.rtc = RTC() self.debug = debug self.battery = Battery() # use this pin for debug self.wifi_pin = Pin("GP24", mode=Pin.IN, pull=Pin.PULL_UP) # Empty WDT object self.wdt = None if not debug: if not self.wifi_pin(): self.wdt = WDT(timeout=20000) self.sd = None else: from machine import SD try: self.sd = SD() mount(self.sd, '/sd') self.logfile = open("/sd/display.log", "a") except OSError: self.sd = None self.logfile = None self.epd = EPD() self.log("Time left on the alarm: %dms" % self.rtc.alarm_left()) # Don't flash when we're awake outside of debug heartbeat(self.debug)
def setupWifi(requireAp=True, requireSta=False): global ap global sta try: with open('wificonfig.json') as jsonFile: cfg = json.load(jsonFile) attemptSetup(cfg) except Exception as err: print("Problem with WIFI configuration", err) if (requireAp and (ap == None)) or (requireSta and (sta == None)): if (ap == None) and (sta == None): print("Neither WIFI AP or Station mode configured using defaults") cfg = {} attemptSetup(cfg) import os from machine import WDT # Give 5 minutes to configure WIFI before resetting and trying again # (handles case where access point happened to be down when this # system came up) WDT(timeout=300000) # No os.path in upython if "wificonfigserver.py" in os.listdir(): from wificonfigserver import runServer runServer() else: # Make an attempt to start up webrepl for # file transfer import webrepl webrepl.start()
def __initialise_watchdog(self): if self.__conf.get('connection_watchdog', True): self.__wifi_lte_watchdog = WDT( timeout=constants.__WDT_TIMEOUT_MILLISECONDS ) print('Initialized watchdog for WiFi and LTE connection with timeout {} ms'.format(constants.__WDT_TIMEOUT_MILLISECONDS)) # noqa else: print('Watchdog for WiFi and LTE was disabled, enable with "connection_watchdog": true in pybytes_config.json') # noqa
def __init__(self): self.wdt = WDT() self.adc = ADC(0) self.auto_tim = Timer(1) self.publish_tim = Timer(2) self.ping_fail = 0 self.ping_mqtt = 0 self.light_state = 0 self.light_intensity = 0 self.sensor_interrupt = 0 self.button_interrupt = 0 self.current_color = [255, 255, 255] self.auto_human = config.AUTO_HUMAN self.auto_sound = config.AUTO_SOUND self.auto_light = config.AUTO_LIGHT self.light_status = { "state": "OFF", "brightness": 100, "color": { "r": 255, "g": 255, "b": 255 }, "effetc": "" } self.np = NeoPixel(Pin(config.WS2812_PIN, Pin.OUT), config.WS2812_BIT) self.mqtt_client = MQTTClient(client_id=config.DEVICE_NAME, server=config.MQTT_SERVER, port=config.MQTT_PORT, user=config.MQTT_USER, password=config.MQTT_PASSWD, keepalive=60) self.mqtt_client.set_callback(self.sub_callback) self.mqtt_client.set_last_will(config.AVAILABILITY_TOPIC, "offline") self.human_sensor_1 = Pin(config.HUMAN_SENSOR_PIN_1, Pin.IN, Pin.PULL_UP) self.human_sensor_2 = Pin(config.HUMAN_SENSOR_PIN_2, Pin.IN, Pin.PULL_UP) self.human_sensor_3 = Pin(config.HUMAN_SENSOR_PIN_3, Pin.IN, Pin.PULL_UP) self.sound_sensor = Pin(config.SOUND_SENSOR_PIN, Pin.IN, Pin.PULL_UP) self.button = Pin(config.BUTTON_PIN, Pin.IN, Pin.PULL_UP)
def disconnect(self, keep_wifi=False, force=False): if self.__wifi_lte_watchdog is not None: self.__wifi_lte_watchdog = WDT(timeout=constants.__WDT_MAX_TIMEOUT_MILLISECONDS) print('Watchdog timeout has been increased to {} ms'.format(constants.__WDT_MAX_TIMEOUT_MILLISECONDS)) # noqa print_debug( 1, 'self.__connection_status={} | self.__network_type={}'.format( self.__connection_status, self.__network_type ) ) if (self.__connection_status == constants.__CONNECTION_STATUS_DISCONNECTED): # noqa print_debug(3, "Already disconnected") if (constants.__CONNECTION_STATUS_CONNECTED_MQTT_WIFI <= self.__connection_status <= constants.__CONNECTION_STATUS_CONNECTED_MQTT_LTE): # noqa print_debug(1, 'MQTT over WIFI||LTE... disconnecting MQTT') try: self.__connection.disconnect(force=force) self.__connection_status = constants.__CONNECTION_STATUS_DISCONNECTED # noqa except Exception as e: print("Error disconnecting: {}".format(e)) if (self.__connection_status == constants.__CONNECTION_STATUS_CONNECTED_LORA): # noqa print_debug(1, 'Connected over LORA... closing socket and saving nvram') # noqa try: self.__lora_socket.close() self.lora.nvram_save() except Exception as e: print("Error disconnecting: {}".format(e)) if (self.__connection_status == constants.__CONNECTION_STATUS_CONNECTED_SIGFOX): # noqa print_debug(1, 'Connected over SIGFOX... closing socket') try: self.__sigfox_socket.close() except Exception as e: print("Error disconnecting: {}".format(e)) if (self.__network_type == constants.__NETWORK_TYPE_WIFI and not keep_wifi): print_debug(1, 'Connected over WIFI... disconnecting') try: self.wlan.deinit() except Exception as e: print("Error disconnecting: {}".format(e)) if (self.__network_type == constants.__NETWORK_TYPE_LTE): print_debug(1, 'Connected over LTE... disconnecting') try: lte_cfg = self.__conf.get('lte') print_debug(1, 'lte.deinit(reset={})'.format(lte_cfg.get('reset', False))) # noqa self.lte.deinit(reset=lte_cfg.get('reset', False)) except Exception as e: print("Error disconnecting: {}".format(e)) self.__network_type = None self.__connection_status = constants.__CONNECTION_STATUS_DISCONNECTED
class Clock: def __init__(self, led, period=5, max_count=10): self._max_count = max_count self.__alarm = Timer.Alarm(self._seconds_handler, period, periodic=True) self._led = led self._count = 0 self._wdt = WDT(timeout=period * 2 * 1000) # enable WDT with a timeout of 2*period seconds def _seconds_handler(self, alarm): self._count += 1 print("Timer Alarm called : %s" % str(self._count)) self._led(1) self._wdt.feed() if self._count == self._max_count: print("Alarm canceled after %s calls" % str(self._max_count)) alarm.cancel() # stop counting
def init_wdt(): global timer0, wdt wdt = WDT(30) period = 5000 system_log.info( "Feeding dog service is running per {} millseconds".format(period)) timer0 = Timer(Timer.Timer0) timer0.start(period=period, mode=timer0.PERIODIC, callback=feed_dog)
def start(wdt=None): freq(80000000) # timer = Timer(2) print("iniciando...") print(wake_reason()) if wdt is None: wdt = WDT(timeout=240000) # Inicializa habilitación de los sensores de material particulado. hpma_pin = Pin(16, Pin.OUT) #Se?al de activaci?n de transistor pms_pin = Pin(4, Pin.OUT) #Se?al de activaci?n de transistor # hpma_pin.value(0) # pms_pin.value(0) # Configura buses de comunicación. uart = UART(2, baudrate=115200, rx=32, tx=17, timeout=1000) uart2 = UART(1, baudrate=9600, rx=33, tx=2, timeout=1000) i2c = I2C(sda=Pin(21, Pin.PULL_UP), scl=Pin(22, Pin.PULL_UP), freq=20000) spi = SPI(sck=Pin(14), mosi=Pin(13), miso=Pin(15)) cs = Pin(5, Pin.OUT) # Inicia logger. Interfaz para SD. logger = Logger(spi=spi, cs=cs) logger.success("Estacion inicializada") # Sincroniza NTP _time.setntp(logger=logger) #Crea publicadores publishers = [] for pub in config.publishers(logger): publishers.append( Publisher(host=pub["host"], token=pub["token"], port=pub["port"], format_=pub["format"], logger=logger, wdt=wdt)) attr = config.attributes() attr["version"] = VERSIONSW atrpub = dumps(attr) # print("iniciando timer") # timer.init(period=540000, mode=Timer.PERIODIC, callback=lambda t:readandpublish(None,uart, uart2, i2c, spi, logger, hpma_pin, pms_pin, publishers, atrpub)) # print("timer iniciado") readandpublish(None, uart, uart2, i2c, spi, logger, hpma_pin, pms_pin, publishers, atrpub) # Vuelve a intentar insertar las telemetrias pendientes desde la bd freq(240000000) for pub in publishers: pub.dbPublish(atrpub, uart, uart2, i2c, spi, logger, hpma_pin, pms_pin, publishers) logger.success("Ciclo de funcionamiento exitoso") logger.close() # state = disable_irq() # timer.deinit() return
def setup(): global wdt, sd, logger, AP, pin_relay_AP, pin_relay_LED, pin_switch_setupMode, pin_switch_RPi, wdt # Logger logging.basicConfig(level=logging.DEBUG) logger = logging.getLogger(__name__) logger.info('===========================') logger.info(' Starting CTLR ') logger.info('===========================') # HW Setup wdt = WDT(timeout=20 * 60 * 100) sd = SD() os.mount(sd, '/sd') pin_relay_AP = Pin('P20', mode=Pin.OUT, pull=Pin.PULL_DOWN) pin_relay_LED = Pin('P19', mode=Pin.OUT, pull=Pin.PULL_DOWN) pin_switch_setupMode = Pin('P9', mode=Pin.IN, pull=Pin.PULL_DOWN) pin_switch_RPi = Pin('P7', mode=Pin.OUT, pull=Pin.PULL_DOWN) # Network Setup # CHANGE AP IN pybytes_config.json! pbconfig = pybytes.get_config() AP = pbconfig['wifi']['ssid'] # WIFI Connection if AP == 'RUT230_7714': pin_relay_AP.value(1) wlan = WLAN(mode=WLAN.STA) while not wlan.isconnected(): nets = wlan.scan() for net in nets: if net.ssid == 'RUT230_7714': pybytes.connect_wifi() # # No Internet Case # wlan.ifconfig(config=('192.168.1.100', '255.255.255.0', '192.168.1.1', '8.8.8.8')) # wlan.connect('RUT230_7714', auth=(WLAN.WPA2, 'Ei09UrDg'), timeout=5000) # while not wlan.isconnected(): # machine.idle() # save power while waiting socket_svr.setup() # _thread.stack_size(16384) _thread.start_new_thread(socket_svr.accept_thread, ()) # UPDATE TIME BY GPS logger.info('GPS time fixing start...') shmGPSclock.update_RTC_from_GPS() socket_svr.var_lock.acquire() socket_svr.state = 1 socket_svr.var_lock.release() logger.info('GPS time fixing done...')
def start_watchdog(self): """ The WDT is used to restart the system when the application crashes and ends up into a non recoverable state. After enabling, the application must "feed" the watchdog periodically to prevent it from expiring and resetting the system. """ # https://docs.pycom.io/firmwareapi/pycom/machine/wdt.html if not self.settings.get('main.watchdog.enabled', False): log.info('Skipping watchdog timer (WDT)') return watchdog_timeout = self.settings.get('main.watchdog.timeout', 10000) log.info('Starting the watchdog timer (WDT) with timeout {}ms'.format( watchdog_timeout)) from machine import WDT self.wdt = WDT(timeout=watchdog_timeout) # Feed Watchdog once. self.wdt.feed()
def __init__(self): a = 0 while a <= 10: a = a + 1 print("REINICIO\n") self.timer = Timer(0) self.timer.init(period=1200000, mode=Timer.PERIODIC, callback=handleInterrupt) #Reset cada 20 mins self.wdt = WDT( timeout=100000 ) #Watchdog configurado para que si no se alimenta en 100 seg realimente self.p13 = Pin(13, Pin.IN) #Pin para interrumpir el main self.mac = ubinascii.hexlify(network.WLAN().config('mac'), ':').decode() print("Esto es la mac:", self.mac) # Scan for 10s (at 100% duty cycle) self.bt = BLE() self.lista_id = [] self.lista_rssi = []
def mainloop(): #main loop looking for and handling UIDs from chips wdt = WDT(timeout=10000) # enable watchdog with a timeout of 10 seconds global taps_pending global threadsswitch while True: uid_send = chipscan() if uid_send == "misread": negindication() elif uid_send == "no_chip": negindication() elif uid_send == "734D0185": setexternalrtc() else: tap = ("uid"+uid_send+"timestamp"+time_calc()) chiplog(tap) sendlock.acquire() taps_pending.append(tap) sendlock.release() print(tap) del tap del uid_send posindication() wdt.feed() time.sleep(0.1)
async def heartbeat(): await asyncio.sleep(30) speed = 125 led = Pin(LED, Pin.OUT, value=1) wdt = WDT() while True: led(0) wdt.feed() await asyncio.sleep_ms(speed) led(1) wdt.feed() await asyncio.sleep_ms(speed * 10)
def start(self): WDT(True) self.ntp_sync() if self.deepsleep(): loop = uasyncio.get_event_loop() for module_type in self.modules: if module_type == 'rtc': loop.run_until_complete( self.modules['rtc'].adjust_time(once=True)) machine.resetWDT() elif module_type == 'climate': loop.run_until_complete( self.modules['climate'].read(once=True)) machine.resetWDT() if self.online(): loop.run_until_complete( self.post_sensor_data(once=True)) machine.resetWDT() if self.modules['climate'].light: loop.run_until_complete( self.modules['climate'].adjust_light(once=True)) machine.resetWDT() if self.online(): if self.id.get('updates'): loop.run_until_complete(self.check_updates(once=True)) machine.resetWDT() if not self.id.get('disable_software_updates'): loop.run_until_complete( self.task_check_software_updates(once=True)) machine.resetWDT() if self.deepsleep(): if self._network: self._network.off() machine.deepsleep(self.deepsleep() * 60000) self.start_async()
def request(requests): s = socket.socket() s.setblocking(True) p = uselect.poll() p.register( s, uselect.POLLIN | uselect.POLLOUT | uselect.POLLHUP | uselect.POLLERR) try: wdt = WDT(timeout=10 * 1000) s.settimeout(1.0) s.connect(socket.getaddrinfo(CTLR_IPADDRESS, 6543)[0][-1]) logger.info('request: connected to the server...') wdt.feed() wdt.init(5 * 60 * 1000) response = s_handler(p, requests) logger.debug('request: finished. response={}'.format(response)) return response except socket.timeout: logger.debug('request: Timeout error occurred...') except: raise return
class Display(object): IMG_DIR = '/flash/imgs' def __init__(self, debug=False): self.cfg = None self.rtc = RTC() self.debug = debug self.battery = Battery() # use this pin for debug self.wifi_pin = Pin("GP24", mode=Pin.IN, pull=Pin.PULL_UP) # Empty WDT object self.wdt = None if not debug: if not self.wifi_pin(): self.wdt = WDT(timeout=20000) self.sd = None else: from machine import SD try: self.sd = SD() mount(self.sd, '/sd') self.logfile = open("/sd/display.log", "a") except OSError: self.sd = None self.logfile = None self.epd = EPD() self.log("Time left on the alarm: %dms" % self.rtc.alarm_left()) # Don't flash when we're awake outside of debug heartbeat(self.debug) def log(self, msg, end='\n'): time = "%d, %d, %d, %d, %d, %d" % self.rtc.now()[:-2] msg = time + ", " + msg if self.logfile: self.logfile.write(msg + end) print(msg, end=end) def feed_wdt(self): if self.wdt: self.wdt.feed() def connect_wifi(self): from network import WLAN if not self.cfg: raise ValueError("Can't initialise wifi, no config") self.log('Starting WLAN, attempting to connect to ' + ','.join(self.cfg.wifi.keys())) wlan = WLAN(0, WLAN.STA) wlan.ifconfig(config='dhcp') while not wlan.isconnected(): nets = wlan.scan() for network in nets: if network.ssid in self.cfg.wifi.keys(): self.log('Connecting to ' + network.ssid) self.feed_wdt() # just in case wlan.connect(ssid=network.ssid, auth=(network.sec, self.cfg.wifi[network.ssid])) while not wlan.isconnected(): idle() break self.feed_wdt() # just in case sleep_ms(2000) self.log('Connected as %s' % wlan.ifconfig()[0]) @staticmethod def reset_cause(): import machine val = machine.reset_cause() if val == machine.POWER_ON: return "power" elif val == machine.HARD_RESET: return "hard" elif val == machine.WDT_RESET: return "wdt" elif val == machine.DEEPSLEEP_RESET: return "sleep" elif val == machine.SOFT_RESET: return "soft" def set_alarm(self, now, json_metadata): import json json_dict = json.loads(json_metadata) # Now we know the time too self.rtc = RTC(datetime=now) list_int = json_dict["wakeup"][:6] time_str = ",".join([str(x) for x in list_int]) self.log("Setting alarm for " + time_str) self.rtc.alarm(time=tuple(list_int)) if self.rtc.alarm_left() == 0: self.log("Alarm failed, setting for +1 hour") self.rtc.alarm(time=3600000) del json def display_file_image(self, file_obj): towrite = 15016 max_chunk = 250 while towrite > 0: c = max_chunk if towrite > max_chunk else towrite buff = file_obj.read(c) self.epd.upload_image_data(buff, delay_us=2000) self.feed_wdt() towrite -= c self.epd.display_update() def display_no_config(self): self.log("Displaying no config msg") with open(Display.IMG_DIR + '/no_config.bin', 'rb') as pic: self.display_file_image(pic) def display_low_battery(self): self.log("Displaying low battery msg") with open(Display.IMG_DIR + '/low_battery.bin', 'rb') as pic: self.display_file_image(pic) def display_cannot_connect(self): self.log("Displaying no server comms msg") with open(Display.IMG_DIR + '/no_server.bin', 'rb') as pic: self.display_file_image(pic) def display_no_wifi(self): self.log("Displaying no wifi msg") with open(Display.IMG_DIR + '/no_wifi.bin', 'rb') as pic: self.display_file_image(pic) def check_battery_level(self): now_batt = 200 last_batt = self.battery.battery_raw() while now_batt > last_batt: sleep_ms(50) last_batt = now_batt self.feed_wdt() now_batt = self.battery.battery_raw() self.log("Battery value: %d (%d)" % (self.battery.value(), self.battery.battery_raw())) if not self.battery.safe(): self.log("Battery voltage (%d) low! Turning off" % self.battery.battery_raw()) self.feed_wdt() self.display_low_battery() return False else: self.log("Battery value: %d (%d)" % (self.battery.value(), self.battery.battery_raw())) return True def run_deepsleep(self): if not self.run(): # RTC wasn't set, try to sleep forever self.rtc.alarm(time=2000000000) # Set the wakeup (why do it earlier?) rtc_i = self.rtc.irq(trigger=RTC.ALARM0, wake=DEEPSLEEP) self.log("Going to sleep, waking in %dms" % self.rtc.alarm_left()) # Close files on the SD card if self.sd: self.logfile.close() self.logfile = None unmount('/sd') self.sd.deinit() # Turn the screen off self.epd.disable() if not self.wifi_pin(): # Basically turn off deepsleep() else: self.log("DEBUG MODE: Staying awake") pass # Do nothing, allow network connections in def run(self): woken = self.wifi_pin() self.epd.enable() if not self.check_battery_level(): return False try: self.epd.get_sensor_data() except ValueError: self.log("Can't communicate with display, flashing light and giving up") heartbeat(True) sleep_ms(15000) return True if self.rtc.alarm_left() > 0: self.log("Woken up but the timer is still running, refreshing screen only") self.epd.display_update() self.feed_wdt() return True try: self.cfg = Config.load(sd=self.sd) self.log("Loaded config") except (OSError, ValueError) as e: self.log("Failed to load config: " + str(e)) self.display_no_config() try: self.connect_wifi() except: pass # everything while True: sleep_ms(10) self.feed_wdt() self.feed_wdt() self.connect_wifi() content = b'' try: self.log("Connecting to server %s:%d" % (self.cfg.host, self.cfg.port)) c = Connect(self.cfg.host, self.cfg.port, debug=self.debug) self.feed_wdt() cause = Display.reset_cause() if woken: cause = "user" self.log("Reset cause: " + cause) if len(self.cfg.upload_path) > 0: temp = self.epd.get_sensor_data() # we read this already c.post(self.cfg.upload_path, battery=self.battery.value(), reset=cause, screen=temp) self.log("Fetching metadata from " + self.cfg.metadata_path) metadata = c.get_quick(self.cfg.metadata_path, max_length=1024, path_type='json') # This will set the time to GMT, not localtime self.set_alarm(c.last_fetch_time, metadata) self.feed_wdt() del metadata del self.battery self.log("Fetching image from " + self.cfg.image_path) self.epd.image_erase_frame_buffer() self.feed_wdt() length, socket = c.get_object(self.cfg.image_path) if length != 15016: raise ValueError("Wrong data size for image: %d" % length) self.feed_wdt() except (RuntimeError, ValueError, OSError) as e: self.log("Failed to get remote info: " + str(e)) self.display_cannot_connect() self.rtc.alarm(time=3600000) return True sleep_ms(1000) # How do we make the write to display more reliable? self.feed_wdt() self.log("Uploading to display") self.display_file_image(socket) c.get_object_done() # close off socket if self.cfg.src == "sd": # If we've got a working config from SD instead of flash self.log("Transferring working config") Config.transfer() self.log("SUCCESS") self.log("Finished. Mem free: %d" % gc.mem_free()) return True
self.time += self.period if self.time >= MAX_UPDATE_PERIOD: self.blynk.lcd_write(0, 0, 0, "Customer: ") self.blynk.lcd_write(0, 0, 1, config.CUSTOMER) self.blynk.lcd_write(7, 0, 0, "Serial: ") self.blynk.lcd_write(7, 0, 1, config.SERIAL) self._send_coins() self.time = 0 c_coins =[self.coins[2].count, self.coins[3].count] if self.prev_coins != c_coins: self.prev_coins = c_coins self.leds.coin_in() self._send_coins() wdt = WDT(timeout=WDT_TIMEOUT) wlan = WLAN(mode=WLAN.STA) connect_to_wlan(wlan) # the WDT will reset if this takes more than 15s wdt.feed() # set the current time (mandatory to validate certificates) RTC(datetime=(2015, 12, 12, 11, 30, 0, 0, None)) # initialize Blynk with SSL enabled blynk = BlynkLib.Blynk(BLYNK_AUTH, wdt=False, ssl=True) # register the main task s_task = MainTask(blynk, wdt, MAIN_TASK_PERIOD, COIN_INPUTS[config.COIN_10_CENT], COIN_INPUTS[config.COIN_20_CENT],