def __init__(self, state):
        led = None if reset_cause() == DEEPSLEEP_RESET else StatusLED(config.LED)
            
        wifi.connect(secrets.WIFI_NAME, secrets.WIFI_PASSWORD, led=led)

        if wifi.is_connected():
            print(wifi.mac(), wifi.ip(), wifi.rssi())
            
            mqtt = MQTT(config.NAME, secrets, uid = UID, led=led)

            opt = dict(exp_aft = config.FREQ * 2.5)

            mqtt.add('Temp', Temperature, **opt).set_state(state['temp'])

            mqtt.add('Humid', Humidity, **opt).set_state(state['humid'])

            mqtt.set_attr("freq", config.FREQ)

            mqtt.do_pub_cfg = reset_cause() != DEEPSLEEP_RESET or ticks_us() % 10 == 0
        
            mqtt.connect()
            sleep(1)
            
            mqtt.pub_state()
            sleep(5)
            
            mqtt.discon()
            sleep(5)
Beispiel #2
0
    def protect():
        """ Checks if the battery level is sufficient, and checks the number of brownout reset. 
			If the battery is too low, we enter indefinite deep sleep to protect the battery """
        # Can only be done once at boot before start the camera and sd card
        batteryLevel = Battery.getLevel()

        # If the battery is too low
        if batteryLevel > 5:
            batteryProtect = False
        # If the battery level can't be read
        elif batteryLevel < 0:
            # If the reset is due to insufficient battery
            if machine.reset_cause() == machine.BROWNOUT_RESET:
                batteryProtect = True
            else:
                batteryProtect = False
        else:
            batteryProtect = True

        brownoutCounter = 0
        # If the reset can probably due to insufficient battery
        if machine.reset_cause() == machine.BROWNOUT_RESET:
            try:
                file = open("brownout.txt", "r")
                val = file.read()
                brownoutCounter = int(val) + 1
            except Exception as err:
                print(useful.exception(err))

        try:
            file = open("brownout.txt", "w")
            file.write("%d" % brownoutCounter)
            file.flush()
            file.close()
        except Exception as err:
            print(useful.exception(err))

        # If the battery level seems sufficient
        if batteryProtect == False:
            # if the number of consecutive brownout resets is too high
            if brownoutCounter > 10:
                # Battery too low, save the battery status
                file = open("battery.txt", "w")
                file.write(
                    "Too many brownout reset with battery level at %d %%" %
                    batteryLevel)
                file.flush()
                file.close()
                batteryProtect = True

        # Case the battery has not enough current and must be protected
        if batteryProtect:
            print("#####################################")
            print("# DEEP SLEEP TO PROTECT THE BATTERY #")
            print("#####################################")
            machine.deepsleep()
        else:
            # Set the wake up on PIR detection
            Battery.setPinWakeUp()
Beispiel #3
0
def main():
    logging.debug("=== MAIN START ===")

    # Increase stack size per thread this increases micropython recursion depth
    _thread.stack_size(8192 * 2)

    # Read and parse configuration from config.json
    utils.init()

    controller = MainController()

    # Check if configuration via access point has to be started
    if not config.cfg.ap_config_done or wake_reason() == PIN_WAKE:
        logging.debug("AP_DONE: {}, wake_reason: {}".format(
            config.cfg.ap_config_done, wake_reason()))
        logging.debug("SSID: {}, Password: {}".format(config.cfg.ssid,
                                                      config.cfg.password))
        if config.cfg.ssid != 'ssid' and config.cfg.password != 'password':
            logging.debug("SSID and password aren't default. Try to connect")
            pass
        else:
            logging.debug("=== Entering configuration mode ===")

            event = MainControllerEvent(
                MainControllerEventType.CONFIGURE_ACCESS_POINT)
            controller.add_event(event)

    logging.debug("Main loop")
    # If the device is powered on, then actual time from NTP server must be downloaded

    if reset_cause() == HARD_RESET or reset_cause(
    ) == PWRON_RESET or reset_cause() == SOFT_RESET:
        event = MainControllerEvent(MainControllerEventType.TEST_CONNECTION)
        controller.add_event(event)

    # Print actual time
    event = MainControllerEvent(MainControllerEventType.PRINT_TIME)
    controller.add_event(event)

    # Read temperature and humidity from the sensor and return the data as JSON
    event = MainControllerEvent(MainControllerEventType.GET_SENSOR_DATA)
    controller.add_event(event)

    # Connect to WIFI and publish JSON with data to AWS via MQTT
    event = MainControllerEvent(MainControllerEventType.PUBLISH_DATA)
    controller.add_event(event)

    # Good night!
    event = MainControllerEvent(MainControllerEventType.GO_TO_SLEEP,
                                callback=None,
                                ms=config.cfg.data_publishing_period_in_ms)
    controller.add_event(event)

    controller.perform()
Beispiel #4
0
async def wakereason(state):
    """ determines the waking reaspn """
    from machine import reset_cause, DEEPSLEEP_RESET, WDT_RESET

    if reset_cause() == DEEPSLEEP_RESET:
        print('woken from deep sleep')
        state.emit('deepsleepwake')

    elif reset_cause() == WDT_RESET:
        print('woken from watch dog reset')
        state.emit('watchdogwake')

    else:
        print('woken by hard reset')
        state.emit('resetwake')
Beispiel #5
0
    def __init__(self):
        self.settings = Settings()
        self.credentials = Credentials()
        self.display = Display()
        self.networkManager = NetworkManager()

        self.previous_hour1 = self.previous_hour2 = -1
        self.previous_minute1 = self.previous_minute2 = -1
        self.previous_second2 = self.previous_count = -1

        self.loop = get_event_loop()

        rst_cause = reset_cause()

        if rst_cause in [PWRON_RESET, SOFT_RESET]:
            self.power_on_reset_wkfl()
        elif rst_cause in [HARD_RESET]:
            self.hard_reset_wkfl()
        elif rst_cause == DEEPSLEEP_RESET:
            self.deepsleep_reset_wkfl()
        else:
            self.other_reset_wkfl()

        self.loop.run_forever()
        self.loop.close()
Beispiel #6
0
def check_reset():
    if machine.reset_cause() == machine.DEEPSLEEP_RESET:
        log.debug("(%s)", "woke from deep sleep")
        return 2
    else:
        log.debug("(%s)", "woke from hard reset")
        return 4
Beispiel #7
0
def main():
    esp.osdebug(None)
    common.set_adc_mode(common.ADC_MODE_VCC)
    vcc = machine.ADC(1).read()
    machine_id = ubinascii.hexlify(machine.unique_id()).decode("utf-8")
    print("Main function, VCC={}, hw_id={}".format(vcc, machine_id))
    if machine.reset_cause() == machine.DEEPSLEEP_RESET:
        init_stepper(from_deep_sleep=True)
    else:
        init_stepper(from_deep_sleep=False)
    if wifi.connect(ssid, password):
        print("Starting webrepl")
        if webrepl.listen_s is None:
            webrepl.start()
        else:
            print("Webrepl already started")
        # settime()
        client_id = wifi.station.config("dhcp_hostname")
        topic_sub = "iot/micro/" + client_id
        topic_pub = "iot/sonoff/" + client_id
        result = mqtt.connect(client_id,
                              mqtt_server,
                              topic_sub,
                              topic_pub,
                              user=mqtt_user,
                              password=mqtt_pass)
        if result == 'restart':
            print("Restarting due to connectivity error")
        else:
            print("Unknown action {}".format(result))
    else:
        print("Wifi did not connect")
    restart_and_reconnect()
Beispiel #8
0
def start_deep_sleep(sleep_time=60):
    # check if the device woke from a deep sleep
    if machine.reset_cause() == machine.DEEPSLEEP_RESET:
        print('woke from a deep sleep')

    # put the device to sleep for 60 seconds
    machine.deepsleep(sleep_time * 1000)
Beispiel #9
0
def boot():
    # Check reason for reset - only update if power on reset
    if machine.reset_cause() == machine.PWRON_RESET:
        download_and_install_updates_if_available()

    # Start the main application
    start()
Beispiel #10
0
    def setup(self):
        self.setup_therm_tristate()
        self.setup_temp(self.config['temp_sensor'])

        # Reset antitamper (ignore) if booting from poweroff
        if machine.reset_cause() in (0, 1) and self.is_tampered():
            self.reset_tampered()
def VerifyLastRunCompleted(flag, timestamp, ERRORFILE):
    if not flag:
        import machine
        from cycle_machine import WriteError

        WriteError(ERRORFILE, 'Reset cause: %s'
                % machine.reset_cause(), timestamp)
Beispiel #12
0
def deep_main():
    if machine.reset_cause() == machine.DEEPSLEEP_RESET:
        print('Woke from a deep sleep...')

    debug = config['runtime']['debug']

    if config:
        moisture_pin, temp_humid_pin = setup()
        sleep_time = config['runtime']['sleep_time_sec']

        while True:
            start_time = time()
            run(moisture_pin, temp_humid_pin)
            elapsed_time = time() - start_time
            new_sleep_time = sleep_time - elapsed_time

            if debug:
                print('Debug mode sleep time: {}'.format(sleep_time))
                if elapsed_time < sleep_time:
                    sleep(new_sleep_time)
            else:
                rtc = machine.RTC()
                rtc.irq(trigger=rtc.ALARM0, wake=machine.DEEPSLEEP)
                sleep_time_ms = 1000 * new_sleep_time
                rtc.alarm(rtc.ALARM0, sleep_time_ms)
                machine.deepsleep()
Beispiel #13
0
 def setup(self):
     dp = machine.Pin(self.config['dht']['pin'])
     self.dht = dht.DHT22(dp)
     # ntc_cfg = self.config['temp_sensor']
     # self.adc_cal = machine.Pin(ntc_cfg['adc_cal_pin'], machine.Pin.OUT, value=0)
     # self.ntc = NTC(pin=ntc_cfg['adc_pin'],
     #                ntc_nom_r=ntc_cfg['ntc_nom_r'],
     #                ntc_nom_t=ntc_cfg['ntc_nom_t'],
     #                ntc_bcoeff=ntc_cfg['ntc_bcoeff'],
     #                vdiv_r2=ntc_cfg['ntc_div_r2'],
     #                t_offset=ntc_cfg['ntc_offset'],
     #                cal_pin=self.adc_cal, cal_duty=2.76/3.3,
     #                samples=15, samples_delay_us=3000)
     oled_cfg = self.config['oled']
     # noinspection PyArgumentList
     spi = machine.SPI(oled_cfg['spi_bus_id'],
                       baudrate=6 * 1024 * 1024,
                       polarity=0,
                       phase=0)
     oled_resume_mode = self.lowpower_phase or machine.reset_cause(
     ) not in (0, 1, 6)
     self.oled = SSD1306_SPI_custom(oled_cfg['width'],
                                    oled_cfg['height'],
                                    spi=spi,
                                    dc=machine.Pin(oled_cfg['dc_pin']),
                                    res=machine.Pin(oled_cfg['res_pin']),
                                    cs=machine.Pin(oled_cfg['cs_pin']),
                                    resume_mode=oled_resume_mode)
     self.oled.contrast(0)
     if not oled_resume_mode:
         self.oled.text('BOOTING', 36, 28)
         self.oled.show()
         self.oled.fill(0)
Beispiel #14
0
    def store_scan(self, scan):
        # Check if we already did a scan too recently.
        now = time.time()
        if (now - self.last_scan_time) < MIN_STORE_TIME:
            # Nothing to do.
            return
        self.last_scan_time = now

        # Seek to end of file
        self.data_file.seek(0,2)
        
        def store_info(info):
            # Store binary info.
            self.data_file.write(info)
            self.data_file.write(b"\n")
            
        store_info(b'machine-' + hex_str(machine.unique_id()))
        store_info(b'time-%d' % (now, ))
        if self.reset:
            store_info(b'reset-%d' % (machine.reset_cause()))
            self.reset = False
            
        for s in scan:
            bssid = s[1]
            strength = s[3]
            store_info(b'ap-%s-%d' % (hex_str(bssid), strength))
        store_info(b'eom')
        # Make sure data are written.
        self.data_file.flush()
def getResetCause():
    try:
        reset_cause = machine.reset_cause()
        debug(
            "Reset cause: " + str(reset_cause) + " - Sleeping secs: " +
            str(globalVars.deepSleepSec), "v")
        try:
            globalVars.deepSleepSec = pycom.nvs_get('deepSleepSecs')
        except BaseException as ea:
            checkError("Error getting flash value of", ea)
        if globalVars.deepSleepSec == 0:
            debug("Coming from other reasons", "v")
            BeepBuzzer(1)
        elif globalVars.deepSleepSec > 0:
            pycom.nvs_set('deepSleepSecs', 0)
            globalVars.deepSleepSec = 0
            if synchronizeRTC():
                globalVars.flag_rtc_syncro = True

            BeepBuzzer(0.2)
        else:
            debug("Another reason for the reset", "v")
            BeepBuzzer(1)
    except BaseException as e:
        checkError("Error getting reset cause", e)
Beispiel #16
0
    def store_scan(self, scan):
        # Check if we already did a scan too recently.
        now = time.time()
        if (now - self.last_scan_time) < MIN_STORE_TIME:
            # Nothing to do.
            return
        self.last_scan_time = now

        # Seek to end of file
        self.data_file.seek(0, 2)

        def store_info(info):
            # Store binary info.
            self.data_file.write(info)
            self.data_file.write(b"\n")

        store_info(b'machine-' + hex_str(machine.unique_id()))
        store_info(b'time-%d' % (now, ))
        if self.reset:
            store_info(b'reset-%d' % (machine.reset_cause()))
            self.reset = False

        for s in scan:
            bssid = s[1]
            strength = s[3]
            store_info(b'ap-%s-%d' % (hex_str(bssid), strength))
        store_info(b'eom')
        # Make sure data are written.
        self.data_file.flush()
Beispiel #17
0
def pymet(wdt):
    # Get result cause
    reset_cause = machine.reset_cause()
    print("Reset cause:", reset_cause)

    watchdog = Watchdog(wdt, reset_cause)

    # Initialise sensors
    wind_pin = machine.Pin(WIND_ADC_PIN)
    wind_sensor = WindSensor(wind_pin, 10)

    ow_pin = machine.Pin(TEMP_ONEWIRE_PIN)
    fan_pin = machine.Pin(TEMP_FAN_PIN, machine.Pin.OUT)
    temperature_sensor = TemperatureSensor(ow_pin, fan_pin)
    temperature_sensor.scan()

    # Create sensor task
    sensor_led = Led(BLUE_LED_PIN)
    mqtt = MQTTClient("metsensor", MQTT_SERVER)

    metsensor = MetSensor(temperature_sensor, wind_sensor, sensor_led, mqtt,
                          watchdog)

    timer = machine.Timer(-1)
    metsensor.start(timer)

    print("Press CTRL-C to exit...")
    try:
        while 1:
            time.sleep(1)
    except KeyboardInterrupt:
        timer.deinit()

    return metsensor
Beispiel #18
0
def send_error(server_ip=None, server_port=80):
    if server_ip is None:
        write_error("server_ip not in configuration file")
        return
    reset = machine.reset_cause()
    url = "http://" + str(server_ip) + ":" + str(server_port) + "/error"
    pb_headers = {'Content-Type': 'application/json'}

    errors = []
    try:
        with open("error.log") as logf:
            while True:
                error = logf.readline()
                if error == '':
                    break
                errors.append(error)
        logf = open("error.log", "w")
        logf.close()
    except OSError as e:
        write_error(e)
        pass
    try:
        if len(errors) > 0:
            data = ujson.dumps({
                'reset_code': reset,
                'error_count': len(errors),
                'error': errors
            })
        if len(errors) == 0:
            data = ujson.dumps({'reset_code': reset, 'error_count': 0})
        urequests.post(url, headers=pb_headers, json=data)
    except Exception as e:
        write_error(e)
        pass
Beispiel #19
0
 def __init__(self, hub):
     # Note, ESP8266 chip real-time clock will overflow every 7h45m
     hour = localtime()[3]
     print('hour', hour)
     self.do_pub_cfg = hour == 0 or reset_cause() != DEEPSLEEP_RESET
     print('do_pub_cfg', self.do_pub_cfg)
     hub.internet = hub.get('internet') or hub.water or self.do_pub_cfg
    def __init__(self, device_type, node_number, data_measure_interval,
                 template_measure_interval, data_sets_per_message):

        if (machine.reset_cause() == machine.DEEPSLEEP_RESET):
            f = open("variables.json", "r")
            self.variable_dict = ujson.loads(f.read())
            f.close()
            self.sequence_number = self.variable_dict["sequence_number"]
            self.node_number = node_number
            self.rtc = RTC()

            if (device_type == 'esp32'):
                self.tx = 17
                self.rx = 16
                self.xbee_power_pin = machine.Pin(18, machine.Pin.OUT)
                self.xbee_power_pin.value(1)
                self.xbee_clear_to_send = machine.Pin(19, machine.Pin.IN)
            elif (device_type == 'superb'):
                self.tx = 32
                self.rx = 33
                self.xbee_power_pin = machine.Pin(22, machine.Pin.OUT)
                self.xbee_power_pin.value(1)
                self.xbee_clear_to_send = machine.Pin(23, machine.Pin.IN)
            else:
                raise Exception("Device Type not known")

            self.data_measure_interval = data_measure_interval
            self.template_measure_interval = template_measure_interval
            self.data_sets_per_message = data_sets_per_message
            self.data_records_set_list = self.variable_dict[
                "data_records_set_list"]

        else:
            self.set_clock()
            self.sequence_number = 0
            self.node_number = node_number

            if (device_type == 'esp32'):
                self.tx = 17
                self.rx = 16
                self.xbee_power_pin = machine.Pin(18, machine.Pin.OUT)
                self.xbee_power_pin.value(1)
                self.xbee_clear_to_send = machine.Pin(19, machine.Pin.IN)
            elif (device_type == 'superb'):
                self.tx = 32
                self.rx = 33
                self.xbee_power_pin = machine.Pin(22, machine.Pin.OUT)
                self.xbee_power_pin.value(1)
                self.xbee_clear_to_send = machine.Pin(23, machine.Pin.IN)
            else:
                raise Exception("Device Type not known")

            self.variable_dict = {}
            self.data_measure_interval = data_measure_interval
            self.template_measure_interval = template_measure_interval
            self.data_sets_per_message = data_sets_per_message
            self.variable_dict["template_i"] = 0
            self.variable_dict["data_i"] = data_measure_interval
            self.variable_dict["data_records_set_list"] = []
Beispiel #21
0
    def __init__(self, state):
        print(wifi.uid())

        if reset_cause() != DEEPSLEEP_RESET:
            status_led.slow_blink()
        wifi.connect(secrets.WIFI_NAME, secrets.WIFI_PASSWORD)
        status_led.off()

        mqtt = MQTT(config.NAME, secrets, uid=UID)

        opt = dict(exp_aft=config.FREQ * 2.5)

        if 'temp' in state:
            from home_assistant.sensors.temperature import Temperature
            mqtt.add('Temp', Temperature, **opt).set_state(state['temp'])

        if 'humid' in state:
            from home_assistant.sensors.humidity import Humidity
            mqtt.add('Humid', Humidity, **opt).set_state(state['humid'])

        if 'lux' in state:
            from home_assistant.sensors.illuminance import Illuminance
            mqtt.add('Lux', Illuminance, **opt).set_state(state['lux'])

        if 'analog' in state:
            mqtt.add('Analog', Sensor, unit="%", icon="mdi:gauge",
                     **opt).set_state(state['analog'])

        if 'battery' in state:
            from home_assistant.sensors.battery import Battery
            mqtt.add('Battery', Battery, key='bat',
                     **opt).set_state(state['battery'])
            mqtt.set_attr('battery', state['battery'])

        mqtt.set_attr("freq", config.FREQ)

        if wifi.is_connected():
            if reset_cause() != DEEPSLEEP_RESET:
                status_led.fast_blink()
            mqtt.connect()
            sleep(1)
            mqtt.pub_state()
            status_led.off()
            sleep(5)
            mqtt.discon()
            sleep(5)
Beispiel #22
0
def boot():
    # check if the device woke from a deep sleep
    # (A software reset does not change the reset cause)
    if reset_cause() == DEEPSLEEP_RESET:
        print('woke from a deep sleep')

    while True:
        start()
Beispiel #23
0
def datalog():
    f = open("pqp_datalog.csv", "a")
    data = h.get_datehour() + "; "
    data += t.get_temp() + "; "
    data += str(machine.reset_cause()) + "; "
    data += str(c.get_battery()) + "; " + "\n"
    f.write(data)
    f.close()
Beispiel #24
0
def main():
    if machine.reset_cause() == machine.HARD_RESET:
        io.off()
    elif machine.reset_cause() == machine.SOFT_RESET:
        pass  # impossible in this version
    else:
        if not io.powered():  # bike not powered on startup; was motion wakeup
            io.off()  # nothing should be on, but ok...
            deepsleep()

    loop.create_task(task_ecu())
    loop.create_task(task_gear_indicator())
    loop.run_until_complete(
        await_pwroff())  # wait for poweroff (bike shutdown)

    # -> bike powered off
    io.off()
    deepsleep()
Beispiel #25
0
def init_display(reset_cause=None):
    if reset_cause is None:
        reset_cause = machine.reset_cause()
    if reset_cause in (machine.PWRON_RESET, machine.HARD_RESET):
        print("Doing hard HW reset")
        lcd.pwron_init()
    elif reset_cause in (machine.WDT_RESET, machine.DEEPSLEEP_RESET, machine.SOFT_RESET):
        print("Doing soft HW bringup")
        lcd.pwron_init()
def run():
    try:
        if machine.reset_cause() == machine.DEEPSLEEP_RESET:
            connect_wifi()
            call_webhook()
    except Exception as exc:
        sys.print_exception(exc)
        show_error()
    machine.deepsleep()
Beispiel #27
0
def main():
    if machine.reset_cause() == machine.HARD_RESET:
        ctrl.off()
    elif machine.reset_cause() == machine.SOFT_RESET:  # this must be a webapp reset, so start it again
        start_net()
    else:
        tmr = tms()
        while ctrl.switch_pressed():  # wait for switch to be released. NC = remains on until timeout
            if tdiff(tms(), tmr) > _SW_PWRUP_TIMEOUT:  # break light flash switch NC or hold down long for special fun
                start_net()
                break
        else:  # not pressed long enough
            if not ctrl.powered():  # bike not powered on startup; was motion wakeup
                ctrl.off()  # nothing should be on, but ok...
                deepsleep()

    while True:
        if ctrl.powered():  # bike (and maybe network) running
            loop.create_task(task_ecu())
            loop.create_task(task_ctrl())
            loop.run_until_complete(await_pwroff())  # wait for poweroff (bike shutdown)

            # -> bike powered off

            # only required if net started afterwards, so no wrong data is displayed:
            reset_loop()  # clear ecu and ctrl task as these are not required now
            ctrl.clear()
            ecu.reset()

            if ctrl.switch_pressed():  # switch held down during shutdown
                start_net(ctrl.mode * 60 if ctrl.mode > 0 else _NET_DEFAULT_ACTIVE_TIME)  # will only set tmr if alr active
            elif ctrl.mode == 10:
                ctrl.off()
                return  # to console
            else:
                if not net.stay_on():
                    ctrl.off()
                    net.stop()  # stop running network (explicitly kick clients), we want to deepsleep
                    deepsleep()
                else:  # stay_on time not over -> reschedule task
                    loop.create_task(task_net())

        # -> only network running, should stay on (and check for powerup meanwhile)
        loop.run_until_complete(await_pwron())
Beispiel #28
0
def run():
    if machine.reset_cause() == machine.HARD_RESET:
        io.off()
        show_logo()
    elif machine.reset_cause() == machine.SOFT_RESET:  # this must be a webapp reset, so start it again
        start_net()
        show_logo()
    else:
        tmr = tms()
        while io.switch_pressed():  # wait for switch to be released. NC = remains on until timeout
            if tdiff(tms(), tmr) > _SW_PWRUP_TIMEOUT:  # brakelight flash switch NC or hold down long for special fun
                start_net()
                break
        else:  # BLF switch not pressed (or long enough)
            if not io.powered():  # bike not powered on startup; was motion wakeup
                io.off()  # nothing should be on, but ok...
                deepsleep()
            else:
                show_logo()

    while True:
        if io.powered():  # bike (and maybe network) running
            loop.create_task(task_ctrl.run())  # first start display
            loop.create_task(task_ecu())
            loop.run_until_complete(await_pwroff())  # wait for poweroff (bike shutdown)

            # -> bike powered off

            # only required if net started afterwards, so no wrong data is displayed:
            reset_loop()  # clear ecu and ctrl task as these are not required now
            io.clear()
            ecu.reset()

            if io.switch_pressed():  # switch held down during shutdown
                start_net()
            elif not net.stay_on():
                io.off()
                net.stop()  # stop running network (explicitly kick clients), we want to deepsleep
                deepsleep()
            else:  # stay_on time not over -> reschedule task
                loop.create_task(task_net())

        # -> only network running, should stay on (and check for powerup meanwhile)
        loop.run_until_complete(await_pwron())
Beispiel #29
0
def delayed_go():
    if machine.reset_cause() == 2:
        # Crash?
        # Go immediately
        return go()
        
    for i in range(15,0,-1):
        print("Will start main activity in %d seconds" % (i,))
        time.sleep(1)
    return go()
Beispiel #30
0
def boot():
    # check if the device woke from a deep sleep
    # (A software reset does not change the reset cause)
    if reset_cause() == DEEPSLEEP_RESET:
        print('woke from a deep sleep')

    # download_and_install_update_if_available()

    while True:
        start()
Beispiel #31
0
    def runtime_setup(self):
        self.ensure_adc_mode()

        self.lowpower_phase = machine.reset_cause() in (
            machine.DEEPSLEEP_RESET, 2)
        print('Reset cause', machine.reset_cause())
        print('Booted in {} phase'.format(
            'lowpower' if self.lowpower_phase else 'normal'))

        if not self.lowpower_phase:
            self.get_requests()

        self.load_config()
        self.load_state(restore=True)

        esp.sleep_type(esp.SLEEP_LIGHT)
        network.WLAN(network.AP_IF).active(False)  # Disable AP

        self.setup()
Beispiel #32
0
def run():
    try:
        if machine.reset_cause() == machine.DEEPSLEEP_RESET:
            connect_wifi()
            temperature, humidity = get_temperature_and_humidity()
            log_data(temperature, humidity)
    except Exception as exc:
        sys.print_exception(exc)
        show_error()
    machine.deepsleep()
Beispiel #33
0
 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"
Beispiel #34
0
def main():
    log.log("Starting main")
    log.log("machine.reset_cause = ", machine.reset_cause())
    global blueled
    blueled = machine.Pin(2, machine.Pin.OUT)
    set_clock_from_file()
    # If there is a AP active, let's turn it off.
    network.WLAN(network.AP_IF).active(False)
    # Now activate the STA interface.
    sta_if = network.WLAN(network.STA_IF)
    sta_if.active(True)
    log.log("Interfaces active")
    # In case we are already connected, disconnect.
    sta_if.disconnect()
    try:
        mainloop(sta_if)
    except Exception as e:
        log.log("Unexpected exception:", e)
    log.log("Bye bye")
    log.flush()
    time.sleep(10)
    machine.reset()
Beispiel #35
0
#btn_in = Pin('GP17', mode=Pin.IN, pull=Pin.PULL_UP)


# Connect to my WiFi
import machine
from network import WLAN
wlan = WLAN() 					# get current object, without changing the mode

# Settings for TP-LINK home network
KEY = ''
IP = '192.168.1.253'			# WiPy Fixed IP address
GATEWAY = '192.168.1.1'			# IP address of gateway
DNS = '192.168.1.1'				# IP address of DNS
NETMASK = '255.255.255.0'		# Netmask for this subnet

if machine.reset_cause() != machine.SOFT_RESET:
	print('Switching to Wifi Device Mode')
	wlan.init(WLAN.STA)
	wlan.ifconfig(config=(IP, NETMASK, GATEWAY, DNS))
	
if not wlan.isconnected():
	print('Attempting to connect to WiFi', end=' ')
	nets = wlan.scan()
	for net in nets:
		if net.ssid == 'Robotmad':
			KEY = 'mou3se43'
			break
		elif net.ssid == 'CoderDojo':
			KEY = 'coderdojo'
			break
	if KEY != '':
# lead to some odd effects in time dependent applications.
# Note also that pyboard firmware briefly flashes the green LED on all wakeups.

import pyb, upower, machine

tamper = upower.Tamper()
wkup = upower.wakeup_X1()
tamper.setup(level=0, freq=16, samples=2, edge=False)  # A level of zero triggers
# upower.tamper.setup(level = 1, edge = True) # Falling edge trigger. You must supply a pullup resistor.
rtc = pyb.RTC()

leds = tuple(pyb.LED(x) for x in range(1, 4))  # rgy
for led in leds:
    led.off()

reason = machine.reset_cause()  # Why have we woken?
if reason == machine.PWRON_RESET or reason == machine.HARD_RESET:  # first boot
    rtc.datetime((2016, 8, 6, 4, 13, 0, 0, 0))  # Code to run on 1st boot only
    upower.savetime()
    if upower.bkpram_ok():  # backup RAM holds valid data
        leds[2].on()  # Y only
    else:  # No backup battery, data is garbage
        for led in leds:
            led.on()  # RGY == 1st boot
elif reason == machine.DEEPSLEEP_RESET:
    reason = upower.why()
    if reason == "WAKEUP":  # green and yellow on timer wakeup
        leds[1].on()
        leds[2].on()
        upower.savetime()
    elif reason == "TAMPER":  # red
Beispiel #37
0
import machine, micropython

# configure RTC.ALARM0 to be able to wake the device
micropython.alloc_emergency_exception_buf(100)
rtc = machine.RTC()
rtc.irq(trigger=rtc.ALARM0, wake=machine.DEEPSLEEP)

# check if the device woke from a deep sleep
if machine.reset_cause() == machine.DEEPSLEEP_RESET:
    print('woke from a deep sleep')

# set RTC.ALARM0 to fire after 10 seconds (waking the device)
rtc.alarm(rtc.ALARM0, 5000)

# put the device to sleep
machine.deepsleep()
Beispiel #38
0
wifi = WLAN()

print(machine)
machine.idle()
print(machine.freq() == (80000000,))
print(machine.unique_id() == wifi.mac())

machine.main('main.py')

rand_nums = []
for i in range(0, 100):
    rand = machine.rng()
    if rand not in rand_nums:
        rand_nums.append(rand)
    else:
        print('RNG number repeated')
        break

for i in range(0, 10):
    machine.idle()

print("Active")

print(machine.reset_cause() >= 0)
print(machine.wake_reason() >= 0)

try:
    machine.main(123456)
except:
    print('Exception')