Beispiel #1
0
    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
Beispiel #2
0
def main():
    btn = machine.Pin(5, machine.Pin.IN, machine.Pin.PULL_UP)
    led = machine.Pin(2, machine.Pin.OUT) #D4
    if btn.value():
        led.value(1)
        sta_if = network.WLAN(network.STA_IF)
        if not sta_if.isconnected():
            sta_if.active(True)
            sta_if.connect('ESL_Lab1', 'wifi@esl')
            while not sta_if.isconnected():
                pass
            led.value(0)
            dhtValue = dht.DHT22(machine.Pin(4))
            dhtValue.measure()
            led.value(1)
            c = MQTTClient(CLIENT_ID, SERVER)
            c.connect()
            DHTbuff = "%.2f,%.2f" % (dhtValue.humidity(), dhtValue.temperature())
            c.publish(TOPIC, DHTbuff)
            led.value(0)
            time.sleep(3)
            # print ("Data temp : "+str(dhtValue.temperature())+" humidity : "+str(dhtValue.humidity()))
            rtc = machine.RTC()
            rtc.irq(trigger=rtc.ALARM0, wake=machine.DEEPSLEEP)
            rtc.alarm(rtc.ALARM0, 2000)
            machine.deepsleep()
def deep_sleep(msecs) :
  # configure RTC.ALARM0 to be able to wake the device
  rtc = machine.RTC()
  rtc.irq(trigger=rtc.ALARM0, wake=machine.DEEPSLEEP)

  # set RTC.ALARM0 to fire after X milliseconds (waking the device)
  rtc.alarm(rtc.ALARM0, msecs)

  # put the device to sleep
  machine.deepsleep()
def sleep(duration=0, status=False):
    # Not working for Disobey 2020 as the pins are not in the RTC domain
    machine.RTC().wake_on_ext0(pin=machine.Pin(25), level=0)
    #machine.RTC().wake_on_ext1([machine.Pin(5, machine.Pin.IN, machine.Pin.PULL_UP)], 0)
    #---
    if (duration >= 86400000):  #One day
        duration = 0
    if status:
        if duration < 1:
            term.header(True, "Sleeping until touch button is pressed!")
        else:
            term.header(True, "Sleeping for " + str(duration) + "ms...")
    time.sleep(0.05)
    machine.deepsleep(duration)
    def run(self):
        helper = TinyIPFIX_Helper_Functions()
        template_rec_set = self.create_template_record_set()
        template_i = self.variable_dict["template_i"]
        data_i = self.variable_dict["data_i"]
        set_list = self.variable_dict["data_records_set_list"]
        self.data_records_set_list = []
        for s in set_list:
            self.data_records_set_list.append(bytes(s, 'utf-8'))

        # to correct timing (actually data and template are sent less ofthen than sleep time):
        # -> t = time.time()
        # -> elapsed = time.time() - t
        # alternative method would be to calculate sleeptime every time instead of using gcd
        while True:
            if template_i == 0:
                template_i = self.template_measure_interval
                template_to_send = self.create_template_message(
                    template_rec_set)
                self.send(template_to_send)
                print('sent template message: {}\n'.format(template_to_send))
            if data_i == 0:
                data_i = self.data_measure_interval
                data_bytes = self.create_data_records_set(
                ).data_records_set_to_byte()
                self.data_records_set_list.append(data_bytes)
                print('created data record: {}\n'.format(data_bytes))
                if len(self.data_records_set_list
                       ) >= self.data_sets_per_message:
                    data_message_bytes = helper.aggregate_bytes(
                        0, 0, self.receive_sequence_number(0),
                        *self.data_records_set_list)
                    self.send(data_message_bytes)
                    print('sent data message: {}\n'.format(data_message_bytes))
                    self.data_records_set_list = []

            sleep_time = min(data_i, template_i)
            template_i -= sleep_time
            data_i -= sleep_time

            self.variable_dict["template_i"] = template_i
            self.variable_dict["data_i"] = data_i
            self.variable_dict[
                "data_records_set_list"] = self.data_records_set_list
            self.variable_dict["sequence_number"] = self.sequence_number
            f = open("variables.json", "w")
            f.write(ujson.dumps(self.variable_dict))
            f.close()
            print(self.sequence_number)
            machine.deepsleep(sleep_time * 1000)
def enter_deep_sleep(secs):
    # For some weird reason, my Wemos D1 does not wake up from deepsleep
    """
    Ensure that pin RST & D0 are connected!
    """
    # configure RTC.ALARM0 to be able to wake the device
    rtc = machine.RTC()
    rtc.irq(trigger=rtc.ALARM0, wake=machine.DEEPSLEEP)
    # set RTC.ALARM0 to fire after Xseconds, waking the device
    sleep_timeout = secs * 1000
    rtc.alarm(rtc.ALARM0, sleep_timeout)
    print("Sleep for %d sec" % sleep_timeout)
    # put the device to sleep
    machine.deepsleep()
Beispiel #7
0
def sleep(duration=0, status=False):
    if not device.configureWakeupSource():
        print("No wakeup source available, rebooting...")
        reboot()
        return
    if (duration >= 86400000):  #One day
        duration = 0
    if status:
        if duration < 1:
            term.header(True, "Sleeping until a touch button is pressed!")
        else:
            term.header(True, "Sleeping for " + str(duration) + "ms...")
    device.prepareForSleep()
    machine.deepsleep(duration)
Beispiel #8
0
def sleep(duration=0, status=False):
	import time, os, badge
	#machine.RTC().wake_on_ext0(pin = machine.Pin(34), level = 0) # MPR121 interrupt
	#machine.RTC().wake_on_ext1([machine.Pin(5, machine.Pin.IN, machine.Pin.PULL_UP)], 0)
	if (duration >= 86400000): #One day
		duration = 0
	if status:
		import term
		if duration < 1:
			term.header(True, "Sleeping until a touch button is pressed!")
		else:
			term.header(True, "Sleeping for "+str(duration)+"ms...")
	time.sleep(0.05)
	machine.deepsleep(duration)
Beispiel #9
0
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()
Beispiel #10
0
    def hibernate(self, interval, lightsleep=False, deepsleep=False):
        """

        :param interval:
        :param lightsleep:  (Default value = False)
        :param deepsleep:  (Default value = False)

        """

        #logging.enable_logging()

        if deepsleep:

            # Prepare and invoke deep sleep.
            # https://docs.micropython.org/en/latest/library/machine.html#machine.deepsleep

            log.info('Preparing deep sleep')

            # Set wake up mode.
            self.set_wakeup_mode()

            # Invoke deep sleep.
            log.info('Entering deep sleep for {} seconds'.format(interval))
            #self.terminal.stop()
            machine.deepsleep(int(interval * 1000))

        else:

            # Adjust watchdog for interval.
            self.watchdog.adjust_for_interval(interval)

            # Invoke light sleep.
            # https://docs.micropython.org/en/latest/library/machine.html#machine.sleep
            # https://docs.micropython.org/en/latest/library/machine.html#machine.lightsleep
            #
            # As "machine.sleep" seems to be a noop on Pycom MicroPython,
            # we will just use the regular "time.sleep" here.
            # machine.sleep(int(interval * 1000))
            machine.idle()

            if lightsleep:
                log.info(
                    'Entering light sleep for {} seconds'.format(interval))
                machine.sleep(int(interval * 1000))

            else:
                # Normal wait.
                log.info('Waiting for {} seconds'.format(interval))
                time.sleep(interval)
Beispiel #11
0
def main():
    global wl_net
    # Initialize wireless network
    if not wl_net:
        wl_net = init_wifi()

    # Initialize DHT
    sensor = dht.DHT22(machine.Pin(4))

    # Main loop to read temp and send it
    # Read the temperature
    sensor.measure()
    temp = sensor.temperature() * 9.0 / 5.0 + 32.0
    humid = sensor.humidity()
    print('v1.2: Temp / Humid = {:2} / {:2}'.format(temp, humid))

    # Send it through MQTT
    mqtt_c = MQTTClient(MQ_CLIENT,
                        MQ_BROKER_IP,
                        user=MQ_USER,
                        password=MQ_PASSWORD)
    mqtt_c.connect()

    json_array = {
        "temp": "{}".format(temp),
        "hum": "{}".format(humid),
    }

    import ujson

    #    {"source":"TV (0)","pvr_status":"NONE","powerstate":"Normal","tv_mode":"Cable (1)","volume":"7","channel_number":"45","channel_name":"Nat Geo HD","program_name":"Personaje ale nazismului","resolution":"1920x1080","error":false}

    mqtt_c.publish(MQ_TOPIC.encode('utf-8'),
                   ujson.dumps(json_array),
                   retain=True)

    mqtt_c.disconnect()

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

    # set RTC.ALARM0 to fire after 10 seconds (waking the device)
    rtc.alarm(rtc.ALARM0, 10000)  # For debugging, 10 seconds
    # rtc.alarm(rtc.ALARM0, 1000 * DELAY_MLOOP)  # Default: 60 seconds
    # Make sure that the Node MCU has pin D0 (L15) wired to RST (R3)

    # put the device to sleep
    machine.deepsleep()
Beispiel #12
0
    def subscription_callback(self, topic, message):
        if (type(topic) is bytes):
            topic = topic.decode("utf-8")
        self.paused = False
        self.last_update = ticks_ms()
        s = topic.split("/")

        if "color" in topic:
            logger.log("Color update")
            data = json.loads(message)
            self.renderer.update_animation(data)
            self.ping()

        elif "sync" in topic:
            logger.log("sync request")
            pass

        elif "poke" in topic:
            logger.log("Poke request")
            self.connect()

        elif "update" in topic:
            if len(s) == 1 or (len(s) > 1 and s[1] == self.id):
                logger.log("Firmware Update")
                self.view.off()
                self.broker.disconnect()
                self.updater.check_for_update_to_install_during_next_reboot()
                logger.log("checked")
                reset()

        elif "config" in topic:
            if len(s) == 1 or (len(s) > 1 and s[1] == self.id):
                logger.log("config update")
                provider.update_config(message)

        elif "sleep" in topic:
            if len(s) == 1 or (len(s) > 1 and s[1] == self.id):
                logger.log("sleeping")
                self.view.off()
                data = json.loads(message)
                deepsleep(data["seconds"] * 1000)

        elif "restart" in topic:
            if len(s) == 1 or (len(s) > 1 and s[1] == self.id):
                self.view.off()
                logger.log("restarting")
                reset()
        else:
            logger.log("unknown command")
def start_sleeping(sleepTime=0):
    term.header(True, "Going to sleep...")

    rgb.clear()
    rgb.scrolltext('ZzZz')
    time.sleep(3)

    if (sleepTime >= 86400000):  # One day
        sleepTime = 0
    if (sleepTime < 1):
        print("Sleeping until A-button is pressed...")
    else:
        print("Sleeping for " + str(sleepTime) + "ms...")
    time.sleep(0.1)
    machine.deepsleep(sleepTime)
    def go_to_sleep(event: MainControllerEvent) -> None:
        """
        Go to deep sleep.
        """
        # Resets flag before sleep
        config.cfg.printed_time = False
        config.cfg.got_sensor_data = False
        config.cfg.published_to_cloud = False
        config.cfg.save()

        logging.debug("sleep({})".format(event.data))
        ms = int(event.data['ms'])
        if ms <= 0:
            ms = 10
        machine.deepsleep(ms)
def init(milliseconds):
	import machine
	"""
	# If this is deployed on ESP8266, uncomment this block
	# to enable real time clock & interrupts for the ESP8266
	# configure RTC.ALARM0 to be able to wake the device
	rtc = machine.RTC()
	rtc.irq(trigger=rtc.ALARM0, wake=machine.DEEPSLEEP)

	# set RTC.ALARM0 to fire after X seconds (waking the device)
	rtc.alarm(rtc.ALARM0, milliseconds)
	"""
	# put the device to sleep
	# we'll also need to power off the sensors at some point too.
	machine.deepsleep(milliseconds)
def finito():
    print("Exiting...")
    # configure RTC.ALARM0 to be able to wake the device
    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 some milliseconds (waking the device)
    rtc.alarm(rtc.ALARM0, 140000)  #148000 (4min 48 sek: 297000
    time.sleep(2)
    # put the device to sleep
    machine.deepsleep()
Beispiel #17
0
def deepsleep():
    """Go into deep sleep mode. GPIO16 (D0) must be connected to RST
    (RST)."""

    # wait some time before going into deesleep mode - otherwise no
    # intervention possible when problems occur.
    time.sleep(5)
    rtc = machine.RTC()
    rtc.irq(trigger=rtc.ALARM0, wake=machine.DEEPSLEEP)
    # set alarm time (in ms)
    print("setting alarm for RTC", config.DEEPSLEEP_TIME)
    rtc.alarm(rtc.ALARM0, config.DEEPSLEEP_TIME)
    # sleep
    print("starting deep sleep...")
    machine.deepsleep()
def deep_sleep_esp(msecs):
    try:
        # configure RTC.ALARM0 to be able to wake the device
        timer = machine.Timer(-1)
        timer.init(period=15000,
                   mode=machine.Timer.ONE_SHOT,
                   callback=lambda t: esp.deepsleep(10000000))

        # set RTC.ALARM0 to fire after X milliseconds (waking the device)
        rtc = machine.RTC()
        rtc.alarm(rtc.ALARM0, msecs)

        # put the device to sleep
        machine.deepsleep()
    except Exception as e:
        print(e)
Beispiel #19
0
def PowerFailCb(logger):
    power_fail = Pin(POWER_FAIL_PIN)
    if debouncedPFSignal(power_fail) == 1:
        #stopTasksButLora() # save power by leaving all non essential tasks ASAP
        pycom.nvs_set(POWER_FAIL_STATE, MODE_POWER_FAIL)
        unixLocalTime= time.time() + time.timezone()
        pycom.nvs_set(POWER_FAIL_TS, unixLocalTime)
        currentAlarmLoraMessageToSend = buildPFAlarmMessage(unixLocalTime)
        lora_queue_immediate_semaphore.acquire(0)
        rand=int(getRandom() * 2000) # 0-2000 value
        time.sleep_ms(rand) # just randow m wait of 3s
        LoraQueueImmediate.put(currentAlarmLoraMessageToSend)
        lora_queue_immediate_semaphore.acquire(1,2) # wait 2s max for msg to be sent by the Lora task
        time.sleep_ms(WAIT_TIME_BEFORE_SLEEP) # time for the LoRA MAC layer to send that message
        rand=int(getRandom() * 20) # 0-20 value
        machine.deepsleep((WAKEUP_DELAY+rand)*1000) # GO TO SLEEP NOW AND PRESERVE POWER
def seconds_handler(alarm):
    global connection_time
    global timeFlag

    file = open('/flash/sleepTimes.json', 'r')
    parsedx = ujson.load(file)
    file.close()
    timeFlag = parsedx['timers']['timeFlag']
    connection_time = parsedx['timers']['connection_time']
    sleep_time = parsedx['timers']['sleep_time']
    if timeFlag == False:
        print("Alarma desactivada")
        alarm.cancel()
    elif timeFlag == True:
        print("Pasaron: " +str(connection_time)+" segundos")
        machine.deepsleep(sleep_time*1000)
Beispiel #21
0
def main():
    do_connect_mqtt(server, client_id)
    # do_publish(topic2, msg)
    flags_modem_isOn = True
    global start
    while True:
        b.tick()

        if b.isPress():
            start = time.ticks_ms()
        elif flags_modem_isOn and time.ticks_diff(time.ticks_ms(),
                                                  start) > timeout:
            flags_modem_isOn = machine.deepsleep()

        if b.isDouble():
            print("Button pressed double ")
            if not flags_modem_isOn:
                do_connect()
                do_connect_mqtt(server, client_id)
                flags_modem_isOn = True
            do_publish(topic2, msg)

        if b.isSingle():
            print("Button pressed Single ")
            if not flags_modem_isOn:
                do_connect()
                do_connect_mqtt(server, client_id)
                flags_modem_isOn = True
            do_publish(topic1, msg)
    c.disconnect()
Beispiel #22
0
def main():
    mode_sw = Pin(MODE_SW_PIN, Pin.IN)
    service_mode = mode_sw.value() == 0
    if service_mode:
        return
    station = init_wlan_station()
    open_networks = find_open_networks(station)
    station.active(False)
    if open_networks:
        print("Open wifi networks:")
        for network in open_networks:
            print(network)
        blink_user_led(1, len(open_networks))
    else:
        print("No open wifi networks found.")
    deepsleep()
Beispiel #23
0
def deepsleep():

    print('Going into deepsleep for {seconds} seconds...'.format(
        seconds=config.LOG_INTERVAL))

    # RTC = Real Time Clock
    rtc = machine.RTC()

    # Setup the machine to wake up from a deep sleep mode when the alarm goes off
    rtc.irq(trigger=rtc.ALARM0, wake=machine.DEEPSLEEP)

    # Set the alarm to go off within the setup interval
    rtc.alarm(rtc.ALARM0, config.LOG_INTERVAL * 1000)

    # Enters deep sleep mode
    machine.deepsleep()
Beispiel #24
0
async def sleep():
    """ pushes the device into a deep sleep mode  """
    from machine import RTC, DEEPSLEEP, deepsleep

    await asyncio.sleep(3)

    print('.... in deep sleep zzZz')
    # configure RTC.ALARM0 to be able to wake the device
    rtc = RTC()
    rtc.irq(trigger=rtc.ALARM0, wake=DEEPSLEEP)

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

    # put the device to sleep
    deepsleep()
Beispiel #25
0
    def initialize(self, notify=True):
        '''
        Initialize App.
        '''
        self.connect_to_network(notify=notify)
        if not self.connected:
            return

        self.device_auth = DeviceAuth.from_file(SAVED_LOCATION)
        if not self.device_auth or self.device_auth.authorized == False:
            #  Initialize auth
            self.device_auth = DeviceAuth(
                client_id=CLIENT_ID,
                client_secret=CLIENT_SECRET,
                discovery_endpoint=DISCOVERY_ENDPOINT,
                scopes=SCOPES,
                saved_location=SAVED_LOCATION)

            self.device_auth.discover()
            self.authorizing = True
            self.device_auth.authorize()
            user_code = self.device_auth.user_code
            verification_url = self.device_auth.verification_url
            current_attempt = 0
            max_attempts = 20
            while not self.device_auth.authorized and current_attempt < max_attempts:
                messages = [
                    '%s to continue' % (verification_url),
                    'Attempt %s of %s' % (current_attempt + 1, max_attempts)
                ]
                self._notify(user_code, messages=messages)
                self.device_auth.check_authorization_complete(max_attempts=1)
                time.sleep(5)  # Sleep duration in seconds.
                current_attempt += 1

            if not self.device_auth.authorized:
                message = 'Unable to authorize the application.'
                self._error(message=message)
                return

        if notify:
            self._notify('Syncing', messages=['Updating calendar events'])

        self.build_calendar_ui()
        print('Entering deep sleep.')
        machine.deepsleep(REFRESH_INTERVAL * 60 * 1000)
Beispiel #26
0
def process(line):
    try:
        words = line.split()
        command = words[0][0]
        if command == "s":
            set_speed(int(words[1]))
        elif command == "r":
            reverse()
        elif command == "c":
            set_color(bytes(map(int, words[1:4])))
        elif command == "p":
            machine.deepsleep()
        else:
            # `repr` converts non-printing characters to hex escapes or '\n' etc.
            print("Ignoring: {}".format(repr(line)))
    except Exception as e:
        sys.print_exception(e)
Beispiel #27
0
def sleep(sleep_type, sleep_time=60000):
    if sleep_type == "deepsleep":
        print("Putting device into {0} for {1} seconds".format(
            sleep_type, sleep_time / 1000))
        if sleep_time:
            rtc = machine.RTC()
            rtc.irq(trigger=rtc.ALARM0,
                    wake=getattr(machine, sleep_type.upper()))
            rtc.alarm(rtc.ALARM0, sleep_time)

        machine.deepsleep()
    if sleep_type == "idle":
        machine.idle()
    if sleep_type == "sleep":
        machine.sleep()
    if sleep_type == "wait":
        time.sleep(sleep_time / 1000)
Beispiel #28
0
    def run(self, no_except=True):
        """Run the system manager synchronously.

        This allows all watch management activities to handle in the
        normal execution context meaning any exceptions and other problems
        can be observed interactively via the console.
        """
        global free

        if self._scheduling:
            print('Watch already running in the background')
            return

        if not self.app:
            self.switch(self.quick_ring[0])
            if watch.free:
                gc.collect()
                free = gc.mem_free()

        # Reminder: wasptool uses this string to confirm the device has
        # been set running again.
        print('Watch is running, use Ctrl-C to stop')

        if not no_except:
            # This is a simplified (uncommented) version of the loop
            # below
            while True:
                self._tick()
                machine.deepsleep()

        while True:
            try:
                self._tick()
            except KeyboardInterrupt:
                raise
            except Exception as e:
                # Only print the exception if the watch provides a way to do so!
                if 'print_exception' in dir(watch):
                    watch.print_exception(e)
                self.switch(CrashApp(e))

            # Currently there is no code to control how fast the system
            # ticks. In other words this code will break if we improve the
            # power management... we are currently relying on not being able
            # to stay in the low-power state for very long.
            machine.deepsleep()
Beispiel #29
0
    def now(self):
        """Rotina a ser chamada no boot.py.
        0 - coleta temperatura e publica
        1 - fica em loop ate que seja publicado que pode dormir
        2 - faz a rotina de dormir. Dorme no intervalo definido em self.SLEEP_TIME
        3 - quando der o timeout, acorda, coleta, envia e repete.
        """
        size = 0
        print("Estabelecendo conexao de rede...")
        while size < 11:
            try:
                size = len(self.sta_if.ifconfig()[0])
                time.sleep_ms(80)
            except:
                size = 0

        print("setting callback...")
        self.myMQTT.set_callback(self.sub_cb)
        print("connecting for...")
        self.myMQTT.connect()

        print("Subscribe for sleep...")
        self.myMQTT.subscribe(b'freezer/sleep')
        print("Publishing termometer status")
        self.myMQTT.publish(b'freezer/termometro', b'ON')
        # coleta e publica temperatura...
        print("Coletando temperatura e publicando...")
        t = self.tasks()

        # ...aguarda por ordem de dormir...
        print("Aguardando ordem para dormir...")
        self.waiting()
        if self.DO_SLEEP:
            self.myMQTT.publish("freezer/termometro", "OFF")
            print("Dormindo. Ate logo.")
            # ...inicia processo de deepsleep.
            self.DO_SLEEP = False
            rtc = machine.RTC()
            rtc.irq(trigger=rtc.ALARM0, wake=machine.DEEPSLEEP)

            # wake up after...
            rtc.alarm(rtc.ALARM0, self.SLEEP_TIME)

            # sleep
            machine.deepsleep()
Beispiel #30
0
def timer_and_scale(write_to_google_sheet=0, sleep=0):

    oled_i2c = init_spi_oled()
    hx711 = init_weight()
    sheet = initialize_google_sheets()
    ntptime.settime()
    polling_interval = 0.1  # how often to check if magnet is on
    sleep_after_seconds = 600  # time after which esp32 goes to sleep if not used

    idle_time = 0
    write_to_oled_with_font(oled_i2c, 'Espresso32', freesans20)

    while 1:
        time.sleep(polling_interval)
        idle_time += polling_interval
        # hx711.tare()
        if (idle_time > sleep_after_seconds) and (sleep):
            write_to_oled_with_font(oled_i2c, 'Going to sleep...', freesans20)
            time.sleep(5)
            t = init_sleep()
            # machine.lightsleep()
            machine.deepsleep()

        if start_timer_external_hall():
            print("Starting timer")
            start_time = get_localtime_as_string()
            num_seconds = 0
            start_weight_reading = round(get_weight(hx711), 2)
            time_weight_pairs = []
            time_weight_pairs.append([start_time, 0, 0])
            while not stop_timer_external_hall():
                time.sleep(1)
                num_seconds += 1
                weight = round(get_weight(hx711) - start_weight_reading, 2)
                time_weight_pairs.append([start_time, num_seconds, weight])
                print(num_seconds)
                print(weight)
                # write_to_oled(oled_i2c, str(num_seconds)+ 'sec')
                write_to_oled_with_font(
                    oled_i2c,
                    str(num_seconds) + 'sec\n' + str(weight) + 'g', arial28)
            print("timer stopped")
            if write_to_google_sheet and (num_seconds > 5):
                sheet.append_values(time_weight_pairs)
            idle_time = 0
Beispiel #31
0
 async def watcher(self):
     while True:
         now = time.ticks_ms()
         diff = time.ticks_diff(now, self.last_activity_ms)
         #print("Diff {}".format(time.ticks_diff(self.last_activity_ms, now)))
         if self.keypad_service.command and diff > env.CANCEL_COMMAND_SEC * 1000:
             self.keypad_service.clear_command()
         if diff > env.DEEP_SLEEP_SEC * 1000:
             print("Preparing deep sleep...")
             self.keypad_service.prepare_deep_sleep()
             self.led_service.prepare_deep_sleep()
             machine.Pin(env.PIN_NO_BEEP, machine.Pin.IN,
                         machine.Pin.PULL_DOWN)
             await logger.adebug("Entering deep sleep...")
             print("Entering deep sleep...")
             machine.deepsleep()
         await asyncio.sleep(1)
         print("Tick " + str(diff / 1000))
    def __exit__(self, exc_type, exc_val, exc_tb):
        if exc_type == KeyboardInterrupt:
            _logger.info(
                "KeyboardInterrupt detected. Extending WDT (%d ms) and exiting to REPL.",
                REPL_WDT_MS)
            global wdt
            wdt.init(REPL_WDT_MS)
            sys.exit()
            return False

        if exc_val:
            _logger.exc(exc_val, "Uncaught exception at MainWrapper top level")

        _logger.warning(
            "MainWrapper last resort. Don't know what else to do. Going to sleep for a while (%d ms).",
            LAST_RESORT_DEEPSLEEP_MS)
        machine.deepsleep(LAST_RESORT_DEEPSLEEP_MS)
        return False
    def _update(self, state_machine):
        try:
            if state_machine.lastError:
                log.error("Last error: {}".format(state_machine.lastError))

            # try to send the error message
            event = ({
                'properties.variables.lastError': {
                    'value': state_machine.lastError if state_machine.lastError is not None else "unknown",
                    'sentAt': formated_time()}
            })
            state_machine.system.send_emergency_event(event)

            state_machine.system.sim.deinit()
            state_machine.system.lte.deinit(detach=True, reset=True)

        finally:
            time.sleep(3)
            machine.deepsleep(1)  # this will wakeup with reset in the main again
Beispiel #34
0
def main(server=SERVER):
    #c = MQTTClient(CLIENT_ID, server)
    # Subscribed messages will be delivered to this callback
    c.set_callback(sub_cb)
    #c.connect()
    mqttconnect()
    c.subscribe(TOPIC)
    print("Connected to {}, subscribed to {} topic".format(server, TOPIC))

    try:
        while 1:
            #micropython.mem_info()
            c.check_msg()
            sleep(5)
            if state == 1:
                print('going to deepsleep')
                deepsleep(10000)
    finally:
        c.disconnect()
Beispiel #35
0
def set_deepSleep(millisec):
    rtc = machine.RTC()
    rtc.irq(trigger=rtc.ALARM0, wake=machine.DEEPSLEEP)
    rtc.alarm(rtc.ALARM0, millisec)
    machine.deepsleep()
Beispiel #36
0
def lo_power():
    from machine import Pin, deepsleep
    for pin in dir(Pin.board):
        p = Pin(pin)
        p.init(Pin.IN, pull=Pin.PULL_DOWN, alt=-1)
    deepsleep()
# configure it as uplink only
s.setsockopt(socket.SOL_SIGFOX, socket.SO_RX, False)

pycom.heartbeat(False)
ow = OneWire(Pin('G17'))
temp = DS18X20(ow)


temp.start_convertion()
time.sleep(1)
result = temp.read_temp_async()
wlan = WLAN(mode=WLAN.STA)
nets = wlan.scan()
nets = sorted(nets,  key=lambda x:x.rssi,  reverse=True)
wifi = []

print(str(result))
pycom.rgbled(0x003300)
s.send(str(result))
pycom.rgbled(0x000000)

if len(nets) >= 2:
    wifi = nets[0].bssid + nets[1].bssid
    print(wifi)
    pycom.rgbled(0x003300)
    s.send(wifi.decode())
    pycom.rgbled(0x000000)

machine.deepsleep(60*1000*10)
Beispiel #38
0
def sleep(seconds):
	rtc = machine.RTC()
	rtc.irq(trigger=rtc.ALARM0, wake=machine.DEEPSLEEP)
	rtc.alarm(rtc.ALARM0, seconds * 1000)
	machine.deepsleep()
Beispiel #39
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()