Python time.ticks_ms() Examples

The following are 30 code examples for showing how to use time.ticks_ms(). 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: L76GLNSV4   Author: andrethemac   File: L76GNSV4.py    License: MIT License 6 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
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 3
Project: UIFlow-Code   Author: m5stack   File: _encode.py    License: 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 4
Project: UIFlow-Code   Author: m5stack   File: m5mqtt.py    License: 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 5
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 6
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 7
Project: tinypico-micropython   Author: tinypico   File: main.py    License: 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 8
Project: tinypico-micropython   Author: tinypico   File: example.py    License: 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 9
Project: pysmartnode   Author: kevinkk525   File: rfpump.py    License: 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 10
Project: pysmartnode   Author: kevinkk525   File: rfpump.py    License: 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 11
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 12
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 13
Project: pysmartnode   Author: kevinkk525   File: remoteTemperature.py    License: 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 14
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 15
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 16
Project: MicroWebSrv2   Author: jczic   File: XAsyncSockets.py    License: MIT License 5 votes vote down vote up
def perf_counter() :
        return ticks_ms() / 1000

# ============================================================================
# ===( XAsyncSocketsPool )====================================================
# ============================================================================ 
Example 17
Project: L76GLNSV4   Author: andrethemac   File: L76GNSV4.py    License: MIT License 5 votes vote down vote up
def time_fixed(self):
        """how long till the last fix"""
        return int(time.ticks_ms()/1000) - self.timeLastFix 
Example 18
Project: L76GLNSV4   Author: andrethemac   File: L76GNSV4.py    License: MIT License 5 votes vote down vote up
def get_fix(self, force=True, debug=False, timeout=None):
        """look for a fix, use force to refix, returns true or false"""
        if force:
            self.fix = False
        if timeout is None:
            timeout = self.timeout
        self.chrono.reset()
        self.chrono.start()
        chrono_running = True

        while chrono_running and not self.fix:
            nmea_message = self._read_message(('RMC', 'VTG', 'GLL', 'GGA', 'GSA'), debug=debug)
            if nmea_message is not None:
                pm = fs = False
                try:
                    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.chrono.stop()
                        self.fix = True
                        self.timeLastFix = int(time.ticks_ms() / 1000) - self.timeLastFix
                        self.ttf = round(self.chrono.read())
                        self.Latitude = nmea_message['Latitude']
                        self.Longitude = nmea_message['Longitude']
                except:
                    pass
            if self.chrono.read() > timeout:
                chrono_running = False
        self.chrono.stop()
        if debug:
            print("fix in", self.chrono.read(), "seconds")
        return self.fix 
Example 19
Project: micropython-bmp180   Author: micropython-IMU   File: bmp180.py    License: MIT License 5 votes vote down vote up
def makegauge(self):
        '''
        Generator refreshing the raw measurments.
        '''
        delays = (5, 8, 14, 25)
        while True:
            self._bmp_i2c.writeto_mem(self._bmp_addr, 0xF4, bytearray([0x2E]))
            t_start = time.ticks_ms()
            while (time.ticks_ms() - t_start) <= 5: # 5mS delay
                yield None
            try:
                self.UT_raw = self._bmp_i2c.readfrom_mem(self._bmp_addr, 0xF6, 2)
            except:
                yield None
            self._bmp_i2c.writeto_mem(self._bmp_addr, 0xF4, bytearray([0x34+(self.oversample_setting << 6)]))
            t_pressure_ready = delays[self.oversample_setting]
            t_start = time.ticks_ms()
            while (time.ticks_ms() - t_start) <= t_pressure_ready:
                yield None
            try:
                self.MSB_raw = self._bmp_i2c.readfrom_mem(self._bmp_addr, 0xF6, 1)
                self.LSB_raw = self._bmp_i2c.readfrom_mem(self._bmp_addr, 0xF7, 1)
                self.XLSB_raw = self._bmp_i2c.readfrom_mem(self._bmp_addr, 0xF8, 1)
            except:
                yield None
            yield True 
Example 20
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 21
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 22
Project: UIFlow-Code   Author: m5stack   File: button.py    License: GNU General Public License v3.0 5 votes vote down vote up
def upDate(self):
        value = self.pin.value()
        state = self._eventLast ^ self._event
        if state:
            for i in state_list:
                if state & i:
                    if self._event & i:
                        self._eventTime[i] = 40
                    else:
                        self._eventTime[i] = 0
            self._eventLast = self._event

        for i in state_list:
            if self._eventTime[i] > 1:
                self._eventTime[i] -= 1
            elif self._eventTime[i] == 1:
                self._eventTime[i] = 0
                self._event &= ~i

        if value ^ self._valueLast:
            nowTime = time.ticks_ms()
            self._valueLast = value
            if not value:
                if nowTime - self._pressTime > self._dbtime:
                    if self._cbState & DOUBLEPRESS and nowTime - self._pressTime < self._doubleTime:
                        self._event |= DOUBLEPRESS
                    self._event |= PRESSWAIT
                self._pressTime = nowTime
            else:
                if nowTime - self._releaseTime> self._dbtime:
                    if self._cbState & LONGPRESS and nowTime - self._pressTime > self._holdTime:
                        self._event |= LONGPRESS
                    else:
                        self._event |= RELEASE
                self._releaseTime = nowTime 
Example 23
Project: UIFlow-Code   Author: m5stack   File: _joystick.py    License: GNU General Public License v3.0 5 votes vote down vote up
def _update(self):
        if time.ticks_ms() - self.time > 100:
            self.time = time.ticks_ms()
            try:
                self.value = self.i2c.readfrom(self._addr, 5)
            except:
                pass 
Example 24
Project: UIFlow-Code   Author: m5stack   File: time_ex.py    License: GNU General Public License v3.0 5 votes vote down vote up
def __init__(self, period, mode, callback):
        self.callback = callback
        self.nextTime = time.ticks_ms() + period
        self.period = period
        self.mode = mode
        self.dead = False 
Example 25
Project: UIFlow-Code   Author: m5stack   File: wifiCfg.py    License: GNU General Public License v3.0 5 votes vote down vote up
def reconnect(block=False):
	global _reconnectTime, _reconnectState
	if wlan_sta.isconnected():
		return True
		
	if time.ticks_ms() > _reconnectTime:
		if wlan_sta.isconnected():
			return True

		if _reconnectState == True:
			_reconnectState = False
			_reconnectTime = time.ticks_ms() + 1000
			print("disconnect, wait next ...")
			wlan_sta.disconnect()
			return False

		_reconnectTime = time.ticks_ms() + 15000
		_reconnectState = True

		if not wlan_sta.isconnected():
			wlan_sta.active(True)
			jdata = cfgRead('wifi')
			if jdata:
				wlan_sta.connect(jdata['ssid'], jdata['password'])
		return True
	else:
		return False 
Example 26
Project: UIFlow-Code   Author: m5stack   File: m5mqtt.py    License: GNU General Public License v3.0 5 votes vote down vote up
def _msg_deal(self, param):
        state, msg = self.mqtt.topic_get()
        if state == 0:
            pass
        elif state == 1:
            # receive req
            self.ping_out_time = time.ticks_ms() + 60000
        elif state == 2:
            self.ping_out_time = time.ticks_ms() + 60000
            topic = msg[0] if type(msg[0]) == str else msg[0].decode('utf-8')
            data = self.mqtt.topic_msg_get(msg[1])
            self._on_data(topic, data.decode()) 
Example 27
Project: UIFlow-Code   Author: m5stack   File: m5mqtt.py    License: GNU General Public License v3.0 5 votes vote down vote up
def _daemonTask(self):
        timeBegin = time.ticks_ms()
        while True:
            if time.ticks_ms() - timeBegin > 10000:
                timeBegin = time.ticks_ms()
                try:
                    if self.mqtt.ping():
                        self.ping_out_time = time.ticks_ms() + 2000
                    else:
                        self.mqttState = False
                        self.mqtt.lock_msg_rec()
                except:
                    self.mqttState = False
                    self.mqtt.lock_msg_rec()
  
            # ping ok, but not receive req
            if time.ticks_ms() > self.ping_out_time:
                self.mqttState = False
                self.mqtt.lock_msg_rec()
                          
            if self.mqttState == False:
                if wlan_sta.isconnected():
                    try:
                        self.mqtt.set_block(True)
                        self.mqtt.connect()
                        self.on_connect()
                        self.mqtt.set_block(False)
                        self.mqtt.unlock_msg_rec()
                        self.mqttState = True
                        self.ping_out_time = time.ticks_ms() + 60000
                    except Exception as e:
                        pass
                else:
                    reconnect()

            self._msg_deal(1)
            time.sleep_ms(100) 
Example 28
Project: UIFlow-Code   Author: m5stack   File: _joystick.py    License: GNU General Public License v3.0 5 votes vote down vote up
def _update(self):
        if time.ticks_ms() - self.time > 100:
            self.time = time.ticks_ms()
            try:
                self.value = self.i2c.readfrom(0x52, 3)
            except:
                pass 
Example 29
Project: esp32-weather-google-sheets   Author: artem-smotrakov   File: weather.py    License: MIT License 5 votes vote down vote up
def __init__(self, pin, interval, handler = None):
        self.last_measurement = time.ticks_ms()
        self.dht22 = dht.DHT22(machine.Pin(pin))
        self.interval = util.string_to_millis(interval)
        self.iterations = 0
        self.handler = handler

    # mesures temperature and humidity 
Example 30
Project: blynk-library-python   Author: vshymanskyy   File: event_VIRTUAL_READ.py    License: MIT License 5 votes vote down vote up
def v2_read_handler():
    # This widget will show some time in seconds..
    blynk.virtual_write(2, time.ticks_ms() // 1000)