Python time.ticks_ms() Examples

The following are 30 code examples of time.ticks_ms(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module time , or try the search function .
Example #1
Source File: L76GNSV4.py    From L76GLNSV4 with MIT License 7 votes vote down vote up
def fixed(self):
        """fixed yet? returns true or false"""
        nmea_message = self.lastmessage
        pm = fs = False
        if nmea_message != {}:
            if nmea_message['NMEA'][2:] in ('RMC', 'GLL'):  # 'VTG',
                pm = nmea_message['PositioningMode'] != 'N'
            if nmea_message['NMEA'][2:] in ('GGA',):  # 'GSA'
                fs = int(nmea_message['FixStatus']) >= 1
        if pm or fs:
            self.fix = True
            self.timeLastFix = int(time.ticks_ms() / 1000)
            self.Latitude = nmea_message['Latitude']
            self.Longitude = nmea_message['Longitude']
        else:
            self.fix = False
            self.timeLastFix = 0xffffffff
            self.Latitude = None
            self.Longitude = None
            self.ttf = -1
        return self.fix 
Example #2
Source File: main.py    From tinypico-micropython with MIT License 6 votes vote down vote up
def button_press_callback(pin):
    global last_button_press_time
    # block button press as software debounce
    if last_button_press_time < time.ticks_ms():
        
        # add 150ms delay between button presses... might be too much, we'll see!
        last_button_press_time = time.ticks_ms() + 150

        # If the pin is in the callback handler dictionary, call the appropriate function 
        if str(pin) in button_handlers:
            button_handlers[str(pin)]()
    # else:
    #     # print a debug message if button presses were too quick or a dounce happened
    #     print("Button Bounce - {}ms".format( ( last_button_press_time - time.ticks_ms() ) ) )

# Create all of the triggers for each button pointing to the single callback handler 
Example #3
Source File: weather.py    From esp32-weather-google-sheets with MIT License 6 votes vote down vote up
def check(self):
        current_time = time.ticks_ms()
        deadline = time.ticks_add(self.last_measurement, self.interval)
        if ((time.ticks_diff(deadline, current_time) <= 0) or (self.iterations == 0)):
            self.measure()
            self.iterations += 1
            self.last_measurement = current_time

# the following function, when added to the google sheet (Tools > Script editor) allows the
# formula uploaded in the "now" variable (see "measure(self)") to calculate a local timestamp
# from the epoch value loaded in column A of the inserted row
#
#function TIMESTAMP_TO_DATE(value) {
#  return new Date(value * 1000);
#}
# see the sheets.py file to set the ValueInputOption to USER_INPUT to avoid now string value being prefixed with a ' 
Example #4
Source File: example.py    From tinypico-micropython with MIT License 6 votes vote down vote up
def convert_accell_rotation( vec ):
    x_Buff = vec[0] # x
    y_Buff = vec[1] # y
    z_Buff = vec[2] # z

    global last_convert_time, convert_interval, roll, pitch

    # We only want to re-process the values every 100 ms
    if last_convert_time < time.ticks_ms():
        last_convert_time = time.ticks_ms() + convert_interval

        roll = math.atan2(y_Buff , z_Buff) * 57.3
        pitch = math.atan2((- x_Buff) , math.sqrt(y_Buff * y_Buff + z_Buff * z_Buff)) * 57.3

    # Return the current values in roll and pitch
    return ( roll, pitch )

# If we have found the LIS3DH 
Example #5
Source File: wifi_led.py    From pysmartnode with MIT License 6 votes vote down vote up
def _loop(self):
        mqtt = config.getMQTT()
        mqtt.registerWifiCallback(self._wifiChanged)
        mqtt.registerConnectedCallback(self._reconnected)
        await self._flash(500, 1)
        sta = network.WLAN(network.STA_IF)
        st = time.ticks_ms()
        while True:
            while self._next:
                await self._flash(*self._next.pop(0))
                await asyncio.sleep(1)
            if time.ticks_diff(time.ticks_ms(), st) > 60000:  # heartbeat
                st = time.ticks_ms()
                if sta.isconnected():
                    await self._flash(20, 1)
                    await asyncio.sleep_ms(250)
                    await self._flash(20, 1)
                else:
                    await self._flash(500, 3)
            await asyncio.sleep_ms(500) 
Example #6
Source File: bell.py    From pysmartnode with MIT License 6 votes vote down vote up
def __bell(self):
        while True:
            await self._event_bell
            diff = time.ticks_diff(time.ticks_ms(), self._last_activation)
            if diff > 10000:
                _log.error("Bell rang {!s}s ago, not activated ringing".format(diff / 1000))
                self._event_bell.clear()
                return
            else:
                on = await _mqtt.publish(self.topic(), "ON", qos=1, timeout=2,
                                         await_connection=False)
                await asyncio.sleep_ms(self._on_time)
                await _mqtt.publish(self.topic(), "OFF", qos=1, retain=True, await_connection=on)
                if config.RTC_SYNC_ACTIVE:
                    t = time.localtime()
                    await _mqtt.publish(_mqtt.getDeviceTopic("last_bell"),
                                        "{}-{:02d}-{:02d} {:02d}:{:02d}:{:02d}".format(t[0], t[1],
                                                                                       t[2], t[3],
                                                                                       t[4], t[5]),
                                        qos=1, retain=True, timeout=2, await_connection=False)
                self._event_bell.clear()
                if diff > 500:
                    _log.warn("Bell rang {!s}ms ago, activated ringing".format(diff)) 
Example #7
Source File: mqtt_as_timeout.py    From micropython-mqtt with MIT License 6 votes vote down vote up
def publish(self, topic, msg, retain=False, qos=0, timeout=None):
        task = None
        start = time.ticks_ms()
        while timeout is None or time.ticks_diff(time.ticks_ms(), start) < timeout:
            # Can't use wait_for because cancelling a wait_for would cancel _publishTimeout
            # Also a timeout in wait_for would cancel _publishTimeout without waiting for
            # the socket lock to be available, breaking mqtt protocol.
            if self._pub_task is None and task is None:
                task = asyncio.create_task(self._publishTimeout(topic, msg, retain, qos))
                self._pub_task = task
            elif task is not None:
                if self._pub_task != task:
                    return  # published
            await asyncio.sleep_ms(20)
        if task is not None:
            async with self.lock:
                task.cancel()
                return 
Example #8
Source File: __init__.py    From micropython-samples with MIT License 6 votes vote down vote up
def push_sorted(self, v, data):
        v.data = data

        if ticks_diff(data, ticks()) <= 0:
            cur = self.last
            if cur and ticks_diff(data, cur.data) >= 0:
                # Optimisation: can start looking from self.last to insert this item
                while cur.next and ticks_diff(data, cur.next.data) >= 0:
                    cur = cur.next
                v.next = cur.next
                cur.next = v
                self.last = cur
                return

        cur = self
        while cur.next and (not isinstance(cur.next.data, int) or ticks_diff(data, cur.next.data) >= 0):
            cur = cur.next
        v.next = cur.next
        cur.next = v
        if cur is not self:
            self.last = cur 
Example #9
Source File: remoteTemperature.py    From pysmartnode with MIT License 6 votes vote down vote up
def _remoteTemp(self, topic, msg, retain):
        if retain:
            # a retained temperature value is of no use
            return
        if type(msg) == dict:
            if "temperature" in msg:
                msg = msg["temperature"]
            else:
                log.error("Dictionary has unsupported values")
                return
        try:
            msg = float(msg)
        except Exception as e:
            log.error("Can't convert remote temperature to float: {!s}".format(e))
            return
        self.__time = time.ticks_ms()
        self.__temp = msg
        log.debug("Got remote temp {!s}°C".format(msg), local_only=True) 
Example #10
Source File: debug.py    From pysmartnode with MIT License 6 votes vote down vote up
def overwatch(coro_name, threshold, asyncr=False):
    def func_wrapper(coro):
        if asyncr is True:
            raise TypeError("overwatch does not support coroutines")
            # as it makes not sense. a freeze would trigger every coroutine
        else:
            def wrapper(*args, **kwargs):
                startt = time.ticks_ms()
                res = coro(*args, **kwargs)
                if str(type(res)) == "<class 'generator'>":
                    _log.error("Coroutine in sync overwatch")
                endt = time.ticks_ms()
                diff = time.ticks_diff(endt, startt)
                if diff > threshold:
                    _log.error("Coro {!s} took {!s}ms, threshold {!s}ms".format(coro_name, diff, threshold))
                return res

            return wrapper

    return func_wrapper 
Example #11
Source File: _encode.py    From UIFlow-Code with GNU General Public License v3.0 6 votes vote down vote up
def _update(self):
        if time.ticks_ms() - self.time > 100:
            self.time = time.ticks_ms()
            try:
                data = self.i2c.readfrom(self._addr, 2)
                if data[0] == 0:
                    pass
                elif data[0] > 127:
                    self.encode_value += data[0] - 256
                    self.dir = 1
                else:
                    self.encode_value += data[0]
                    self.dir = 0
                self.press = data[1]
            except:
                pass 
Example #12
Source File: rfpump.py    From pysmartnode with MIT License 6 votes vote down vote up
def _repeating(self):
        print("repeating started")
        self._repeating_mode = True
        try:
            while True:
                st = time.ticks_ms()
                await super().on_message(self._topic, "ON", False)
                while time.ticks_ms() - st < self._on_time * 1000:
                    await asyncio.sleep(1)
                await super().on_message(self._topic, "OFF", False)
                st = time.ticks_ms()
                while time.ticks_ms() - st < self._off_time * 1000:
                    await asyncio.sleep(1)
        except asyncio.CancelledError:
            print("repeating canceled")
            self._log.debug("_repeating canceled", local_only=True)
        except Exception as e:
            await self._log.asyncLog("error", "_repeating error: {!s}".format(e))
        finally:
            await super().on_message(self._topic, "OFF", False)
            self._repeating_mode = False
            print("repeating exited") 
Example #13
Source File: rfpump.py    From pysmartnode with MIT License 6 votes vote down vote up
def _wait_off(self):
        print("wait_off started")
        st = time.ticks_ms()
        try:
            while time.ticks_ms() - st < self._on_time * 1000:
                await asyncio.sleep(1)
        except asyncio.CancelledError:
            self._log.debug("_wait_off canceled", local_only=True)
            print("wait_off canceled")
            return
        except Exception as e:
            await self._log.asyncLog("error", "wait_off error: {!s}".format(e))
            return False
        finally:
            print("wait_off exited")
        await super().on_message(self._topic, "OFF", False) 
Example #14
Source File: m5mqtt.py    From UIFlow-Code with GNU General Public License v3.0 6 votes vote down vote up
def __init__(self, client_id, server, port, user=None, password=None, keepalive=300):
        if m5base.get_start() != 1:
            autoConnect(lcdShow=True)
            lcd.clear()
        else:
            raise ImportError('mqtt need download...')

        if user == '':
            user = None
        
        if password == '':
            password = None

        self.mqtt = MQTTClient(client_id, server, port, user, password, keepalive)
        self.mqtt.set_callback(self._on_data)
        try:
            self.mqtt.connect()
        except:
            lcd.clear()
            lcd.font(lcd.FONT_DejaVu24)
            lcd.setTextColor(lcd.RED)
            lcd.print('connect fail', lcd.CENTER, 100)
        self.topic_callback = {}
        self.mqttState = True
        self.ping_out_time = time.ticks_ms() + 60000 
Example #15
Source File: weather.py    From ulnoiot-upy with MIT License 5 votes vote down vote up
def get():
    global lasttime

    newtime = time.ticks_ms()
    if len(lastjson) < 20 or newtime - lasttime > 60000:  # nothing read yet or at least one minute pass
        r = urequest.urlopen(url)
        j = ujson.loads(r.read(2000))
        r.close()
        lasttime = newtime
    else:
        j = lastjson
    return j 
Example #16
Source File: debug.py    From pysmartnode with MIT License 5 votes vote down vote up
def _get_stuck(interval):
    # await asyncio.sleep_ms(10)
    print("Starting stuck")
    t = time.ticks_ms()
    while time.ticks_ms() - t < interval:
        pass
    print("Stop stuck")
    # await asyncio.sleep_ms(10)
    # print("end_stuck") 
Example #17
Source File: ds18x20.py    From ulnoiot-upy with MIT License 5 votes vote down vote up
def __init__(self, name, pin, on_change=None, filter=None):
        import onewire, ds18x20
        gc.collect()
        self.ds = ds18x20.DS18X20(onewire.OneWire(pin))
        self.roms = self.ds.scan()
        self.lasttime = time.ticks_ms()
        self.ds.convert_temp()
        self.temp_list = None
        Device.__init__(self, name, pin, on_change=on_change, filter=filter) 
Example #18
Source File: ds18x20.py    From ulnoiot-upy with MIT License 5 votes vote down vote up
def measure(self):
        newtime = time.ticks_ms()
        if newtime - self.lasttime < 0 or newtime - self.lasttime > DS18X20.MEASURE_DELAY:
            self.temp_list = []
            for rom in self.roms:
                self.temp_list.append(self.ds.read_temp(rom))
            if len(self.temp_list) == 1:
                self.temp_list = self.temp_list[0]
            self.ds.convert_temp()
            self.lasttime = newtime
        return self.temp_list 
Example #19
Source File: mfrc522.py    From ulnoiot-upy with MIT License 5 votes vote down vote up
def measure(self):
        now = time.ticks_ms()
        if time.ticks_diff(now, self.last_access) > self.access_interval:
            retval = b'0'  # Let's assume nothing is there
            try:
                (stat, tag_type) = self.request(_REQIDL)
                if stat == _OK:  # Something is there, so ignore this if not successfully read
                    retval = None

                    (stat, raw_uid) = self.anticoll()

                    if stat == _OK:
                        retval = str(tag_type).encode() + b' ' + ubinascii.hexlify(bytes(raw_uid))

                        if self.select_tag(raw_uid) == _OK:

                            data_read = False
                            for sector in range(0, self.datasize//12): # /16/3*4
                                if (sector+1) % 4 != 0:  # every 4th sector has only management info
                                    if self.auth(_AUTHENT1A, sector+4, self.key, raw_uid) == _OK:
                                        if not data_read:
                                            retval += b' '
                                        self._read(sector + 4, into=self.card_data_buf)
                                        retval += ubinascii.hexlify(self.card_data_buf)  # TODO: remove hexlify and do binary
                                        data_read = True
                                    else:
                                        print("MFRC522: authentication error")
                                        return None  # Not successfull read
                            self.stop_crypto1()
                            # TODO: think how to avoid this busy-waiting
                            print("MFRC522: read time " + str(time.ticks_diff(time.ticks_ms(), now)))
                        else:
                            print("MFRC522: Select failed")
                        _ = self.anticoll()  # prevent reading of empty
                        self.last_access = time.ticks_ms()  # TODO: check why this is necessary
            except Exception as e:
                print('Trouble in MFRC522. Got exception:', e)
                print('Retval so far:', retval)
            return retval
        return None  # didn't read 
Example #20
Source File: i2c_connector.py    From ulnoiot-upy with MIT License 5 votes vote down vote up
def measure(self):
        t = time.ticks_ms()
        # if self.suspend_start is not None \
        #        and time.ticks_diff(t,self.suspend_start) <= self.suspend_time:
        #    print("Bus access suspended.")
        if self.suspend_start is None \
                or time.ticks_diff(t, self.suspend_start) > self.suspend_time:
            self.suspend_start = None  # done waiting
            try:
                if self.msgq is not None:
                    self.port.writeto(self.addr, self.msgq)
                    self.msgq = None
                s = self.port.readfrom(self.addr, self.BUFFER_SIZE)
            except:
                print("Trouble accessing i2c.")
            else:
                if s[0] == 255 and s[1] == 255:  # illegal read
                    print("Got garbage, waiting 1s before accessing bus again.")
                    print("data:", s)
                    self.suspend_time = 1000  # take a break
                    self.suspend_start = time.ticks_ms();
                else:
                    count = s[0] * 256 + s[1]
                    if self.count != count:
                        l = s[2];
                        self.suspend_time = s[3];
                        # scale timer
                        if self.suspend_time & 128:
                            self.suspend_time = (self.suspend_time & 127) * 100
                            if self.suspend_time > 5000:  # should not happen
                                print("Garbage time -> waiting 1s before accessing bus again.")
                                print("data:", s)
                                self.suspend_time = 1000
                        if self.suspend_time > 0:
                            self.suspend_start = time.ticks_ms();
                            print("Bus suspend for", self.suspend_time, "ms requested.")
                        if l <= self.BUFFER_SIZE:  # discard if too big
                            self.count = count
                            self.current_value = s[4:4 + l]
                            return self.current_value
        return None 
Example #21
Source File: _htdht.py    From ulnoiot-upy with MIT License 5 votes vote down vote up
def __init__(self, name, pin, dht_dev, delay,
                 on_change=None, report_change=True,
                 filter=None):
        self.delay = delay
        import dht
        self.dht = dht_dev
        self.lasttime = time.ticks_ms()
        self.dht.measure()
        Device.__init__(self, name, pin, on_change=on_change,
                        getters={"temperature": self._get_t,
                                 "humidity": self._get_h},
                        report_change=report_change,
                        filter=filter) 
Example #22
Source File: ds18x20.py    From ulnoiot-upy with MIT License 5 votes vote down vote up
def measure(self):
        newtime = time.ticks_ms()
        if newtime - self.lasttime < 0 or newtime - self.lasttime > DS18X20.MEASURE_DELAY:
            self.temp_list = []
            for rom in self.roms:
                self.temp_list.append(self.ds.read_temp(rom))
            if len(self.temp_list) == 1:
                self.temp_list = self.temp_list[0]
            self.ds.convert_temp()
            self.lasttime = newtime
        return self.temp_list 
Example #23
Source File: debug.py    From pysmartnode with MIT License 5 votes vote down vote up
def _stability_log(interval):
    st = time.ticks_ms()
    while True:
        await asyncio.sleep(interval)
        st_new = time.ticks_ms()
        diff = time.ticks_diff(st_new, st) / 1000
        st = st_new
        _log.debug("Still online, diff to last log: {!s}".format(diff))
        if diff > 600 * 1.1 or diff < 600 * 0.9:
            _log.warn("Diff to last log not within 10%: {!s}, expected {!s}".format(diff, interval))
        gc.collect() 
Example #24
Source File: debug.py    From pysmartnode with MIT License 5 votes vote down vote up
def __interrupt(t):
    global interrupt_array
    interrupt_array[0] = interrupt_array[1]
    interrupt_array[1] = time.ticks_ms()
    print(interrupt_array[1], "inside interrupt") 
Example #25
Source File: remoteTemperature.py    From pysmartnode with MIT License 5 votes vote down vote up
def _remoteTempControl(self, heater, data):
        if self.__temp is not None:
            if time.ticks_ms() - self.__time < heater.getInterval() * 1000:
                data["current_temp"] = self.__temp
                # overwriting current_temp, if no remote temp received, internal temp is used
                log.debug("Using remote temperature {!s}°C".format(self.__temp), local_only=True)
        data["remote_temp"] = self.__temp
        data["remote_temp_time"] = self.__time
        # just in case a future plugin would like to use this 
Example #26
Source File: core.py    From pysmartnode with MIT License 5 votes vote down vote up
def _timer(self):
        self.__timer_time = time.ticks_ms()
        while True:
            while (time.ticks_ms() - self.__timer_time) < (self.__interval * 1000):
                await asyncio.sleep(1)
            self.__timer_time = time.ticks_ms()  # will also be set by _watch when resetting event
            log.debug("Reaction time reached", local_only=True)
            self.__event.set() 
Example #27
Source File: __init__.py    From pysmartnode with MIT License 5 votes vote down vote up
def _loop(self, interval):
        interval = interval * 1000
        t = time.ticks_ms()
        while not self._restore_done and time.ticks_diff(time.ticks_ms(), t) < 30000:
            await asyncio.sleep(1)
            # wait for network to finish so the old state can be restored, or time out (30s)
        if not self._restore_done:
            await _mqtt.unsubscribe(
                _mqtt.getDeviceTopic("{!s}{!s}/state".format(COMPONENT_NAME, self._count)), self)
            self._restore_done = True
            self.event.set()
        await asyncio.sleep(1)
        t = 0
        while True:
            while time.ticks_diff(time.ticks_ms(), t) < interval and not self.event.is_set():
                await asyncio.sleep_ms(100)
            if self.event.is_set():
                self.event.clear()
            async with self.lock:
                cur_temp = await self.temp_sensor.getValue(SENSOR_TEMPERATURE)
                try:
                    await self._modes[self.state[CURRENT_MODE]].trigger(self, cur_temp)
                except Exception as e:
                    _log.error(
                        "Error executing mode {!s}: {!s}".format(self.state[CURRENT_MODE], e))
                await _mqtt.publish(
                    _mqtt.getDeviceTopic("{!s}{!s}/state".format(COMPONENT_NAME, self._count)),
                    self.state, qos=1, retain=True, timeout=4)
            t = time.ticks_ms() 
Example #28
Source File: remoteSwitch.py    From pysmartnode with MIT License 5 votes vote down vote up
def off(self):
        """Turn switch off. Can be used by other components to control this component"""
        async with self.lock:
            t = time.ticks_ms()
            await _mqtt.publish(self._topic, "OFF", qos=1, timeout=self._timeout)
            while time.ticks_diff(time.ticks_ms(), t) < self._timeout * 1000:
                if t < self._state_time:  # received new state
                    return True if self._state is False else False
            return False  # timeout reached 
Example #29
Source File: remoteSwitch.py    From pysmartnode with MIT License 5 votes vote down vote up
def on(self):
        """Turn switch on. Can be used by other components to control this component"""
        async with self.lock:
            t = time.ticks_ms()
            await _mqtt.publish(self._topic, "ON", qos=1, timeout=self._timeout)
            while time.ticks_diff(time.ticks_ms(), t) < self._timeout * 1000:
                if t < self._state_time:  # received new state
                    return self._state
            return False  # timeout reached 
Example #30
Source File: remoteSwitch.py    From pysmartnode with MIT License 5 votes vote down vote up
def on_message(self, topic, msg, retain):
        """
        Standard callback to change the device state from mqtt.
        Can be subclassed if extended functionality is needed.
        """
        if msg in _mqtt.payload_on:
            self._state = True
            self._state_time = time.ticks_ms()
        elif msg in _mqtt.payload_off:
            self._state = False
            self._state_time = time.ticks_ms()
        else:
            raise TypeError("Payload {!s} not supported".format(msg))
        return False  # will not publish the requested state to mqtt as already done by on()/off()