Python time.ticks_diff() Examples

The following are 30 code examples for showing how to use time.ticks_diff(). These examples are extracted from open source projects. 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 check out the related API usage on the sidebar.

You may also want to check out all available functions/classes of the module time , or try the search function .

Example 1
Project: micropython-mqtt   Author: peterhinch   File: mqtt_as_timeout.py    License: 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 2
Project: esp32-weather-google-sheets   Author: artem-smotrakov   File: weather.py    License: 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 3
Project: micropython-samples   Author: peterhinch   File: __init__.py    License: 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 4
Project: pysmartnode   Author: kevinkk525   File: wifi_led.py    License: 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 5
Project: pysmartnode   Author: kevinkk525   File: bell.py    License: 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 6
Project: pysmartnode   Author: kevinkk525   File: debug.py    License: 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 7
Project: micropython-stm-lib   Author: SpotlightKid   File: spimaster.py    License: MIT License 5 votes vote down vote up
def timeit():
        spi = SpiMaster(1, baudrate=int(pyb.freq()[3] / 16))
        start = ticks_ms()

        for i in range(2 ** 10):
            spi.write_data(b'abcdefgh' * 4)
            spi.read_data()

        print("Millisecond ticks elapsed: %i" % ticks_diff(ticks_ms(), start)) 
Example 8
Project: uPyLoader   Author: BetaRavener   File: download.py    License: MIT License 5 votes vote down vote up
def _read_timeout(cnt, timeout_ms=2000):
    time_support = "ticks_ms" in dir(time)
    s_time = time.ticks_ms() if time_support else 0
    data = sys.stdin.read(cnt)
    if len(data) != cnt or (time_support and time.ticks_diff(time.ticks_ms(), s_time) > timeout_ms):
        return None
    return data 
Example 9
Project: uPyLoader   Author: BetaRavener   File: upload.py    License: MIT License 5 votes vote down vote up
def _read_timeout(cnt, timeout_ms=2000):
    time_support = "ticks_ms" in dir(time)
    s_time = time.ticks_ms() if time_support else 0
    data = sys.stdin.read(cnt)
    if len(data) != cnt or (time_support and time.ticks_diff(time.ticks_ms(), s_time) > timeout_ms):
        return None
    return data 
Example 10
Project: kmk_firmware   Author: KMKfw   File: kmktime.py    License: GNU General Public License v3.0 5 votes vote down vote up
def ticks_diff(new, old):
    if USE_UTIME:
        return time.ticks_diff(new, old)
    else:
        return new - old 
Example 11
Project: micropython-fusion   Author: micropython-IMU   File: deltat.py    License: MIT License 5 votes vote down vote up
def __init__(self, timediff):
        if timediff is None:
            self.expect_ts = False
            if is_micropython:
                self.timediff = lambda start, end : time.ticks_diff(start, end)/1000000
            else:
                raise ValueError('You must define a timediff function')
        else:
            self.expect_ts = True
            self.timediff = timediff
        self.start_time = None 
Example 12
Project: micropython-fusion   Author: micropython-IMU   File: fusion_r_asyn.py    License: MIT License 5 votes vote down vote up
def TimeDiff(start, end):
        return time.ticks_diff(start, end)/1000000 
Example 13
Project: micropython-fusion   Author: micropython-IMU   File: fusion_r_syn.py    License: MIT License 5 votes vote down vote up
def TimeDiff(start, end):
        return time.ticks_diff(start, end)/1000000 
Example 14
Project: pysmartnode   Author: kevinkk525   File: ecMeter.py    License: MIT License 5 votes vote down vote up
def ppm(self, publish=True, timeout=5):
        if time.ticks_diff(time.ticks_ms(), self._time) > 5000:
            await self._read(publish, timeout)
        return self._ppm 
Example 15
Project: pysmartnode   Author: kevinkk525   File: mqtt.py    License: MIT License 5 votes vote down vote up
def _subscribeTopics(self, start: int = 0):
        _log.debug("_subscribeTopics, start", start, local_only=True)
        try:
            for i, sub in enumerate(self._subs):
                # do not iter by range(start,length(_subs)) as _subs could get bigger while itering
                if i < start:
                    continue  # iter until start position reached
                t = sub[0]
                if self.isDeviceTopic(t):
                    t = self.getRealTopic(t)
                if len(sub) == 4:  # requested retained state topic
                    self._sub_retained = True
                    # if coro gets canceled in the process, the state topic will be checked
                    # the next time _subscribeTopic runs after the reconnect
                    _log.debug("_subscribing", t[:-4], local_only=True)
                    await self._preprocessor(super().subscribe, t[:-4], 1)  # subscribe state topic
                    ts = time.ticks_ms()  # start timer after successful subscribe otherwise
                    # it might time out before subscribe has even finished.
                    while time.ticks_diff(time.ticks_ms(), ts) < 4000 and self._sub_retained:
                        # wait 4 seconds for answer
                        await asyncio.sleep_ms(100)
                    if self._sub_retained is True:  # no state message received
                        self._subs[i] = sub[:3]
                        self._sub_retained = False
                        _log.debug("Unsubscribing state topic", t[:-4], "in _subsscribeTopics",
                                   local_only=True)
                        await self._preprocessor(super().unsubscribe, t[:-4],
                                                 await_connection=False)
                _log.debug("_subscribing", t, local_only=True)
                await self._preprocessor(super().subscribe, t, 1)
                # no timeouts because _subscribeTopics will get canceled when connection is lost
        finally:
            # remove pending unsubscribe requests
            for sub in self.__unsub_tmp:
                self._subs.remove(sub)
                self.__unsub_tmp = []
            self._sub_coro = None 
Example 16
Project: pysmartnode   Author: kevinkk525   File: mqtt.py    License: MIT License 5 votes vote down vote up
def awaitSubscriptionsDone(self, timeout=None, await_connection=True):
        start = time.ticks_ms()
        while timeout is None or time.ticks_diff(time.ticks_ms(), start) < timeout * 1000:
            if not await_connection and not self._isconnected:
                return False
            if self._sub_coro is None:
                return True  # all topics subscribed.
            await asyncio.sleep_ms(50)
        return False  # timeout 
Example 17
Project: pysmartnode   Author: kevinkk525   File: mqtt.py    License: MIT License 5 votes vote down vote up
def _preprocessor(self, coroutine, *args, timeout=None, await_connection=True):
        coro = None
        start = time.ticks_ms()
        i = 0 if len(args) == 4 else 1  # 0: publish, 1:(un)sub
        try:
            while timeout is None or time.ticks_diff(time.ticks_ms(), start) < timeout * 1000:
                if not await_connection and not self._isconnected:
                    return False
                if self._ops_coros[i] is coro is None:
                    coro = self._operationTimeout(coroutine, *args, i=i)
                    asyncio.get_event_loop().create_task(coro)
                    self._ops_coros[i] = coro
                elif coro:
                    if self._ops_coros[i] != coro:
                        return True  # published
                await asyncio.sleep_ms(20)
            _log.debug("timeout on", "(un)sub" if i else "publish", args, local_only=True)
            self.__timedout += 1
        except asyncio.CancelledError:
            raise  # the caller should be cancelled too
        finally:
            if coro and self._ops_coros[i] == coro:
                async with self.lock:
                    asyncio.cancel(coro)
                return False
            # else: returns value during process
        return False 
Example 18
Project: pysmartnode   Author: kevinkk525   File: timeit.py    License: MIT License 5 votes vote down vote up
def timeitAsync(f):
    async def new_func(*args, **kwargs):
        gen = f(*args, **kwargs)
        myname = str(gen).split(' ')[2]
        t = time.ticks_us()
        result = await gen
        delta = time.ticks_diff(time.ticks_us(), t)
        print('[Time] Coroutine {}: {:6.3f}ms'.format(myname, delta / 1000))
        return result

    return new_func 
Example 19
Project: pysmartnode   Author: kevinkk525   File: sensor.py    License: MIT License 5 votes vote down vote up
def getValue(self, sensor_type, publish=True, timeout: float = 5, max_age: float = None):
        """
        Return last sensor reading of type "sensor_type".
        Only reads sensor if no loop is reading it periodically unless no_stale is True.
        If a loop is active, it will return the last read value which will be
        at most <self._intrd> old.
        Params publish and timeout will only have an effect if no loop is active or no_stale True.
        :param sensor_type: str representation of the sensor_type.
        :param publish: if value should be published if sensor has to be read for returned value
        :param timeout: timeout for publishing the value
        :param max_age: Specify how old the value can be. If it is older, the sensor will be read again.
        Makes long intervals possible with other components that rely on having a "live" sensor reading.
        :return: float or whatever the sensor_type has as a standard, None if no value available
        """
        self._checkType(sensor_type)
        if max_age:
            if time.ticks_diff(time.ticks_ms(), self._values[sensor_type][-2]) / 1000 > max_age:
                max_age = True
            else:
                max_age = False
        if max_age or self._intrd == -1:
            if self._reading:  # if currently reading, don't read again as value will be "live"
                while self._reading:
                    await asyncio.sleep_ms(100)
            else:
                self._reading = True
                await self._read()
                self._reading = False
            if publish:
                await self._publishValues(timeout=timeout)
        return self._values[sensor_type][-1] 
Example 20
Project: pysmartnode   Author: kevinkk525   File: safety_off.py    License: MIT License 5 votes vote down vote up
def _wait_off(self, component_off):
        print("wait_off started")
        st = time.ticks_ms()
        try:
            while time.ticks_diff(time.ticks_ms(), st) < self._on_time * 1000:
                await asyncio.sleep(0.2)
        except asyncio.CancelledError:
            print("wait_off canceled")
        finally:
            self._coro = None  # prevents cancelling the cancelled coro
            await component_off()
            print("wait_off exited") 
Example 21
Project: pysmartnode   Author: kevinkk525   File: remoteSwitch.py    License: 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 22
Project: pysmartnode   Author: kevinkk525   File: remoteSwitch.py    License: 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 23
Project: pysmartnode   Author: kevinkk525   File: __init__.py    License: 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 24
Project: pysmartnode   Author: kevinkk525   File: debug.py    License: MIT License 5 votes vote down vote up
def _interrupt(interval):  # interval in sec
    import machine
    timer = machine.Timer(1)
    global interrupt_array
    interrupt_array = [time.ticks_ms(), time.ticks_ms()]
    timer.init(period=interval * 1000, mode=machine.Timer.PERIODIC, callback=__interrupt)
    _log.debug("Interrupt initialized")
    while True:
        await asyncio.sleep(interval)
        if time.ticks_diff(interrupt_array[1], interrupt_array[0]) > interval * 1.1 * 1000:
            _log.warn(
                "Interrupt has difference of {!s}".format(time.ticks_diff(interrupt_array[1], interrupt_array[0]))) 
Example 25
Project: pysmartnode   Author: kevinkk525   File: debug.py    License: 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 26
Project: ulnoiot-upy   Author: ulno   File: i2c_connector.py    License: 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 27
Project: ulnoiot-upy   Author: ulno   File: hcsr04.py    License: MIT License 5 votes vote down vote up
def measure(self):
        if ticks_diff(ticks_ms(), self._last_measured) > self.INTERVAL:
            new_dist = self._measure()
            self._last_measured = ticks_ms()
            if abs(new_dist - self.distance) >= self.precision:
                self.distance = new_dist
        return self.distance 
Example 28
Project: ulnoiot-upy   Author: ulno   File: hcsr04.py    License: MIT License 5 votes vote down vote up
def _send_pulse_and_wait(self):
        # Send the pulse to trigger and listen on echo pin.
        # We use the method `machine.time_pulse_us()` to
        # get the microseconds until the echo is received.
        self.trigger_pin.value(0)  # Stabilize the sensor
        sleep_us(5)
        self.trigger_pin.on()
        # Send a 10us pulse.
        sleep_us(10)
        self.trigger_pin.off()
        # try:
        #     pulse_time = machine.time_pulse_us(self.echo_pin, 1, self.echo_timeout_us)
        #     return pulse_time
        # except OSError as ex:
        #     if ex.args[0] == 110: # 110 = ETIMEDOUT
        #         return -1 # out of range
        #     raise ex

        start = ticks_us()
        while not self.echo_pin():
            t = ticks_us()
            if ticks_diff(t, start) > self.echo_timeout_us:
                print("HCR04: timeout")
                return -1
        start = ticks_us()
        while self.echo_pin():
            t = ticks_us()
            if ticks_diff(t, start) > self.echo_timeout_us:
                print("HCR04: timeout")
                return -1
        delta = ticks_diff(ticks_us(), start)
        return delta 
Example 29
Project: ulnoiot-upy   Author: ulno   File: mfrc522.py    License: 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 30
Project: ulnoiot-upy   Author: ulno   File: servo.py    License: MIT License 5 votes vote down vote up
def measure(self):
        if self.turn_start is not None:  # turn in process
            current = time.ticks_ms()
            if time.ticks_diff(current, self.turn_start) >= self.turn_time_ms:
                if len(self.angle_list) > 0:
                    self._trigger_next_turn()
                else:
                    self._release()
        return self.angle_list