Python utime.ticks_ms() Examples
The following are 30
code examples of utime.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
utime
, or try the search function
.
Example #1
Source File: thingflow.py From thingflow-python with Apache License 2.0 | 6 votes |
def run_forever(self): assert len(self.intervals)>0 while True: output_things = self._get_tasks() start_ts = utime.ticks_ms() for pub in output_things: pub._observe() if not pub.__connections__: self._remove_task(pub) if len(self.intervals)==0: break end_ts = utime.ticks_ms() if end_ts > start_ts: self._advance_time(int(round((end_ts-start_ts)/10))) sleep = self._get_next_sleep_interval() utime.sleep_ms(sleep*10) now = utime.ticks_ms() self._advance_time(int(round((now-end_ts)/10)) if now>=end_ts else sleep)
Example #2
Source File: client.py From micropython-iot with MIT License | 6 votes |
def _send(self, d): # Write a line to socket. async with self._s_lock: start = utime.ticks_ms() while d: try: ns = self._sock.send(d) # OSError if client closes socket except OSError as e: err = e.args[0] if err == errno.EAGAIN: # Would block: await server read await asyncio.sleep_ms(100) else: self._verbose and print('_send fail. Disconnect') self._evfail.set() return False # peer disconnect else: d = d[ns:] if d: # Partial write: pause await asyncio.sleep_ms(20) if utime.ticks_diff(utime.ticks_ms(), start) > self._to: self._verbose and print('_send fail. Timeout.') self._evfail.set() return False self._last_wr = utime.ticks_ms() return True
Example #3
Source File: eddystone.py From uble with MIT License | 6 votes |
def adcread(chan): # 16 temp 17 vbat 18 vref assert chan >= 16 and chan <= 18, 'Invalid ADC channel' start = utime.ticks_ms() timeout = 100 stm.mem32[stm.RCC + stm.RCC_APB2ENR] |= 0x100 # enable ADC1 clock.0x4100 stm.mem32[stm.ADC1 + stm.ADC_CR2] = 1 # Turn on ADC stm.mem32[stm.ADC1 + stm.ADC_CR1] = 0 # 12 bit if chan == 17: stm.mem32[stm.ADC1 + stm.ADC_SMPR1] = 0x200000 # 15 cycles stm.mem32[stm.ADC + 4] = 1 << 23 elif chan == 18: stm.mem32[stm.ADC1 + stm.ADC_SMPR1] = 0x1000000 stm.mem32[stm.ADC + 4] = 0xc00000 else: stm.mem32[stm.ADC1 + stm.ADC_SMPR1] = 0x40000 stm.mem32[stm.ADC + 4] = 1 << 23 stm.mem32[stm.ADC1 + stm.ADC_SQR3] = chan stm.mem32[stm.ADC1 + stm.ADC_CR2] = 1 | (1 << 30) | (1 << 10) # start conversion while not stm.mem32[stm.ADC1 + stm.ADC_SR] & 2: # wait for EOC if utime.ticks_diff(utime.ticks_ms(), start) > timeout: raise OSError('ADC timout') data = stm.mem32[stm.ADC1 + stm.ADC_DR] # clear down EOC stm.mem32[stm.ADC1 + stm.ADC_CR2] = 0 # Turn off ADC return data
Example #4
Source File: mqtt_as.py From micropython-mqtt with MIT License | 6 votes |
def broker_up(self): # Test broker connectivity if not self.isconnected(): return False tlast = self.last_rx if ticks_diff(ticks_ms(), tlast) < 1000: return True try: await self._ping() except OSError: return False t = ticks_ms() while not self._timeout(t): await asyncio.sleep_ms(100) if ticks_diff(self.last_rx, tlast) > 0: # Response received return True return False
Example #5
Source File: mqtt_as.py From micropython-mqtt with MIT License | 6 votes |
def _as_write(self, bytes_wr, length=0, sock=None): if sock is None: sock = self._sock if length: bytes_wr = bytes_wr[:length] t = ticks_ms() while bytes_wr: if self._timeout(t) or not self.isconnected(): raise OSError(-1) try: n = sock.write(bytes_wr) except OSError as e: # ESP32 issues weird 119 errors here n = 0 if e.args[0] not in BUSY_ERRORS: raise if n: t = ticks_ms() bytes_wr = bytes_wr[n:] await asyncio.sleep_ms(_SOCKET_POLL_DELAY)
Example #6
Source File: mqtt_as.py From micropython-mqtt with MIT License | 6 votes |
def _as_read(self, n, sock=None): # OSError caught by superclass if sock is None: sock = self._sock data = b'' t = ticks_ms() while len(data) < n: if self._timeout(t) or not self.isconnected(): raise OSError(-1) try: msg = sock.read(n - len(data)) except OSError as e: # ESP32 issues weird 119 errors here msg = None if e.args[0] not in BUSY_ERRORS: raise if msg == b'': # Connection closed by host raise OSError(-1) if msg is not None: # data received data = b''.join((data, msg)) t = ticks_ms() self.last_rx = ticks_ms() await asyncio.sleep_ms(_SOCKET_POLL_DELAY) return data
Example #7
Source File: sock_nonblock.py From micropython-async with MIT License | 6 votes |
def _as_read(self, n): sock = self._sock data = b'' t = ticks_ms() while len(data) < n: esp32_pause() # Necessary on ESP32 or we can time out. if self._timeout(t) or not self._sta_if.isconnected(): raise OSError(-1) try: msg = sock.read(n - len(data)) except OSError as e: # ESP32 issues weird 119 errors here msg = None if e.args[0] not in BUSY_ERRORS: raise if msg == b'': # Connection closed by host (?) raise OSError(-1) if msg is not None: # data received data = b''.join((data, msg)) t = ticks_ms() # reset timeout await asyncio.sleep_ms(_SOCKET_POLL_DELAY) return data # Write a buffer
Example #8
Source File: cantest.py From micropython-async with MIT License | 6 votes |
def run_cancel_test6(loop): for name in ('complete', 'cancel me'): loop.create_task(asyn.NamedTask(name, cant60, name)()) loop.create_task(asyn.Cancellable(cant61)()) await asyncio.sleep(4.5) print('Cancelling task \"{}\". 1.5 secs latency.'.format(name)) await asyn.NamedTask.cancel(name) await asyncio.sleep(7) name = 'cancel wait' loop.create_task(asyn.NamedTask(name, cant60, name)()) await asyncio.sleep(0.5) print('Cancelling task \"{}\". 1.5 secs latency.'.format(name)) t = time.ticks_ms() await asyn.NamedTask.cancel('cancel wait', nowait=False) print('Was cancelled in {} ms'.format(time.ticks_diff(time.ticks_ms(), t))) print('Cancelling cant61') await asyn.Cancellable.cancel_all() print('Done')
Example #9
Source File: server.py From micropython-samples with MIT License | 6 votes |
def readline(s, timeout): line = b'' start = utime.ticks_ms() while True: if line.endswith(b'\n'): if len(line) > 1: return line line = b'' start = utime.ticks_ms() # A blank line is just a keepalive await asyncio.sleep_ms(100) # See note above d = s.readline() if d == b'': raise OSError if d is not None: line = b''.join((line, d)) if utime.ticks_diff(utime.ticks_ms(), start) > timeout: raise OSError
Example #10
Source File: color96.py From micropython-nano-gui with MIT License | 6 votes |
def multi_fields(t): print('multi_fields') refresh(ssd, True) # Clear any prior image nfields = [] dy = wri.height + 6 y = 2 col = 15 width = wri.stringlen('99.99') for txt in ('X:', 'Y:', 'Z:'): Label(wri, y, 0, txt) # Use wri default colors nfields.append(Label(wri, y, col, width, bdcolor=None)) # Specify a border, color TBD y += dy end = utime.ticks_add(utime.ticks_ms(), t * 1000) while utime.ticks_diff(end, utime.ticks_ms()) > 0: for field in nfields: value = int.from_bytes(uos.urandom(3),'little')/167772 overrange = None if value < 70 else YELLOW if value < 90 else RED field.value('{:5.2f}'.format(value), fgcolor = overrange, bdcolor = overrange) refresh(ssd) utime.sleep(1) Label(wri, 0, 64, ' OK ', True, fgcolor = RED) refresh(ssd) utime.sleep(1)
Example #11
Source File: color15.py From micropython-nano-gui with MIT License | 6 votes |
def multi_fields(t): print('Dynamic labels.') refresh(ssd, True) # Clear any prior image nfields = [] dy = wri.height + 6 y = 2 col = 15 width = wri.stringlen('99.99') for txt in ('X:', 'Y:', 'Z:'): Label(wri, y, 0, txt) # Use wri default colors nfields.append(Label(wri, y, col, width, bdcolor=None)) # Specify a border, color TBD y += dy end = utime.ticks_add(utime.ticks_ms(), t * 1000) while utime.ticks_diff(end, utime.ticks_ms()) > 0: for field in nfields: value = int.from_bytes(uos.urandom(3),'little')/167772 overrange = None if value < 70 else YELLOW if value < 90 else RED field.value('{:5.2f}'.format(value), fgcolor = overrange, bdcolor = overrange) refresh(ssd) utime.sleep(1) Label(wri, 0, 64, ' OK ', True, fgcolor = RED) refresh(ssd) utime.sleep(1)
Example #12
Source File: lamp.py From esp8266 with BSD 2-Clause "Simplified" License | 6 votes |
def perform(self) : current_tick = utime.ticks_ms() if not self.initial_tick : self.initial_tick = current_tick else : x = utime.ticks_diff(current_tick, self.initial_tick) if x == 0 : pass elif 0 < x : rgb = self.get_color(x) if rgb != self.prev_rgb : if self.verbose : logging.info("Lamp: setting color to {} from x={}", rgb, x) self.fill_pixels(rgb) self.prev_rgb = rgb else : # wrap around; start over logging.info("Lamp: tick wrap") self.initial_tick = current_tick return True
Example #13
Source File: client_w.py From micropython-samples with MIT License | 6 votes |
def readline(self): line = b'' start = utime.ticks_ms() while True: if line.endswith(b'\n'): if len(line) > 1: return line line = b'' start = utime.ticks_ms() # Blank line is keepalive self.led(not self.led()) await asyncio.sleep_ms(100) # nonzero wait seems empirically necessary d = self.sock.readline() if d == b'': raise OSError if d is not None: line = b''.join((line, d)) if utime.ticks_diff(utime.ticks_ms(), start) > self.timeout: raise OSError
Example #14
Source File: bmx280.py From uPySensors with Apache License 2.0 | 6 votes |
def _gauge(self): now = utime.ticks_ms() if utime.ticks_diff(now, self._last_read_ts) > self._new_read_ms: self._last_read_ts = now r = self._t_os + (self._p_os << 3) + (1 << 6) self._write(BMX280_REGISTER_CONTROL, r) utime.sleep_ms(100) # TODO calc sleep if self._chip_id == 0x58: d = self._read(BMX280_REGISTER_DATA, 6) # read all data at once (as by spec) self._p_raw = (d[0] << 12) + (d[1] << 4) + (d[2] >> 4) self._t_raw = (d[3] << 12) + (d[4] << 4) + (d[5] >> 4) else: d = self._read(BMX280_REGISTER_DATA, 8) # read all data at once (as by spec) self._p_raw = (d[0] << 12) + (d[1] << 4) + (d[2] >> 4) self._t_raw = (d[3] << 12) + (d[4] << 4) + (d[5] >> 4) self._h_raw = (d[6] << 8) + d[7] self._t_fine = 0 self._t = 0 self._h = 0 self._p = 0
Example #15
Source File: ms_timer_test.py From micropython-async with MIT License | 5 votes |
def timer_test(n): timer = ms_timer.MillisecTimer() while True: t = utime.ticks_ms() await timer(30) print(n, utime.ticks_diff(utime.ticks_ms(), t)) await asyncio.sleep(0.5 + n/5)
Example #16
Source File: rtc_time.py From micropython-async with MIT License | 5 votes |
def ticks_ms(): dt = rtc.datetime() return ((dt[3] - 1)*86400000 + dt[4]*3600000 + dt[5]*60000 + dt[6]*1000 + int(dt[7] / 1000))
Example #17
Source File: time.py From Adafruit_Blinka with MIT License | 5 votes |
def monotonic(): """A monotonically increasing time in seconds. No defined start time.""" # Assumes that monotonic is called more frequently than the wraparound of micropython's # utime.ticks_ms() global _prev_ticks_ms, _total_ms # pylint: disable=global-statement ticks_ms = utime.ticks_ms() _total_ms += utime.ticks_diff(ticks_ms, _prev_ticks_ms) _prev_ticks_ms = ticks_ms return _total_ms * 0.001
Example #18
Source File: aswitch.py From micropython-async with MIT License | 5 votes |
def trigger(self, duration=0): # Update end time self._running = True if duration <= 0: duration = self.duration tn = time.ticks_add(time.ticks_ms(), duration) # new end time self.verbose and self._tstop is not None and self._tstop > tn \ and print("Warning: can't reduce Delay_ms time.") # Start killer if can allocate and killer is not running sk = self.can_alloc and self._tstop is None # The following indicates ._killer is running: it will be # started either here or in ._run self._tstop = tn if sk: # ._killer stops the delay when its period has elapsed self.loop.create_task(self._killer())
Example #19
Source File: sr_init.py From micropython-async with MIT License | 5 votes |
def initiator_task(channel): while True: so = ['test', 0, 0] for x in range(4): # Test full duplex by sending 4 in succession so[1] = x channel.send(so) await asyncio.sleep_ms(0) while True: # Receive the four responses si = await channel.await_obj() # Deal with queue if si is None: print('Timeout: restarting.') return print('initiator received', si) if si[1] == 3: # received last one break while True: # At 2 sec intervals send an object and get response await asyncio.sleep(2) print('sending', so) channel.send(so) tim = ticks_ms() so = await channel.await_obj() # wait for response duration = ticks_diff(ticks_ms(), tim) if so is None: print('Timeout: restarting.') return print('initiator received', so, 'timing', duration)
Example #20
Source File: aswitch.py From micropython-async with MIT License | 5 votes |
def _killer(self): twait = time.ticks_diff(self._tstop, time.ticks_ms()) while twait > 0: # Must loop here: might be retriggered await asyncio.sleep_ms(twait) if self._tstop is None: break # Return if stop() called during wait twait = time.ticks_diff(self._tstop, time.ticks_ms()) if self._running and self.func is not None: launch(self.func, self.args) # Timed out: execute callback self._tstop = None # killer not running self._running = False # timer is stopped
Example #21
Source File: aremote.py From micropython-async with MIT License | 5 votes |
def _run(self): while True: await self._ev_start # Wait until data collection has started # Compensate for asyncio latency latency = ticks_diff(ticks_ms(), self._ev_start.value()) await asyncio.sleep_ms(self.block_time - latency) # Data block should have ended self._decode() # decode, clear event, prepare for new rx, call cb # Pin interrupt. Save time of each edge for later decode.
Example #22
Source File: core.py From pysmartnode with MIT License | 5 votes |
def time(self): return time.ticks_ms()
Example #23
Source File: delay_ms.py From micropython-tft-gui with MIT License | 5 votes |
def _timer(self, restart): if restart: # Restore cached end time self._tstop = self._tsave try: twait = ticks_diff(self._tstop, ticks_ms()) while twait > 0: # Must loop here: might be retriggered await asyncio.sleep_ms(twait) twait = ticks_diff(self._tstop, ticks_ms()) if self._func is not None: # Timed out: execute callback self._retrn = launch(self._func, self._args) finally: self._tsave = self._tstop # Save in case we restart. self._tstop = None # timer is stopped
Example #24
Source File: delay_ms.py From micropython-tft-gui with MIT License | 5 votes |
def trigger(self, duration=0): # Update end time now = ticks_ms() if duration <= 0: # Use default set by constructor duration = self._duration self._retrn = None is_running = self() tstop = self._tstop # Current stop time # Retriggering normally just updates ._tstop for ._timer self._tstop = ticks_add(now, duration) # Identify special case where we are bringing the end time forward can = is_running and duration < ticks_diff(tstop, now) if not is_running or can: schedule(self._do_trig, can)
Example #25
Source File: bluenrg_ms.py From uble with MIT License | 5 votes |
def hci_wait_event(self, evtcode=0, subevtcode=0, timeout=1000, retry=5): """ Wait for event and filter it if needed """ # Maximum timeout is 1 seconds start = utime.ticks_ms() while utime.ticks_diff(utime.ticks_ms(), start) <= min(timeout, 1000): event = self.read(retry=retry) if self.hci_verify(event) and isinstance(event, (bytearray, bytes)): hci_uart = HCI_UART.from_buffer(event) if hci_uart.pkt_type == HCI_EVENT_PKT: hci_evt = HCI_EVENT.from_buffer(hci_uart.data) if not evtcode and not subevtcode: return hci_evt if subevtcode: if hci_evt.evtcode in (EVT_LE_META_EVENT, EVT_VENDOR): if hci_evt.subevtcode == subevtcode: return hci_evt else: raise ValueError("unexpected subevtcode") if evtcode: if hci_evt.evtcode == evtcode: return hci_evt else: raise ValueError("unexpected evtcode") else: raise TypeError("not HCI_EVENT_PKT") else: continue
Example #26
Source File: bluenrg_ms.py From uble with MIT License | 5 votes |
def run(self, callback=None, callback_time=1000): """ BLE event loop Note: This function call __start__() when invoked and __stop__() when KeyboardInterrupt, StopIteration or an Exception is raised. __process__() called whenever there is an event to be processed """ try: self.__start__() start = utime.ticks_ms() while True: event = self.read(retry=5) if self.hci_verify(event): self.__process__(event) # user defined periodic callback if callable(callback) and utime.ticks_diff( utime.ticks_ms(), start) >= callback_time: callback() start = utime.ticks_ms() except (KeyboardInterrupt, StopIteration) as ex: raise ex except Exception as ex: raise ex finally: self.__stop__()
Example #27
Source File: core.py From microdot with MIT License | 5 votes |
def time(self): return time.ticks_ms()
Example #28
Source File: controller.py From esp8266 with BSD 2-Clause "Simplified" License | 5 votes |
def get_stats(self) : return { 'gcd': self.gcd.stats(), 'ntpd': self.ntpd.stats(), 'lamp': self.lamp.stats(), 'scheduler': self.scheduler.stats(), 'uptime_ms': utime.ticks_diff(utime.ticks_ms(), self.start_ms) }
Example #29
Source File: controller.py From esp8266 with BSD 2-Clause "Simplified" License | 5 votes |
def __init__(self, path='/neolamp.json'): self.path = path self.config = core.util.load_json(path if core.util.exists(path) else Controller.DEFAULT_CONFIG_PATH) self.gcd = core.task.Gcd().register() self.ntpd = core.task.Ntpd().register() self.tzd = neolamp.tz.Timezoned().register() self.lamp = neolamp.lamp.Lamp(self.config["pin"], self.config["num_pixels"], self.config['color_specs']["black"]).register() self.clear() self.scheduler = neolamp.scheduler.Scheduler(self.lamp, self.tzd, [], self.config['color_specs']).register() self.set_mode(self.config['mode'], init=True) self.start_ms = utime.ticks_ms()
Example #30
Source File: benchmark.py From micropython-samples with MIT License | 5 votes |
def main(quit=True): global t c = MQTTClient(CLIENT_ID, SERVER) # Subscribed messages will be delivered to this callback c.set_callback(sub_cb) c.connect() c.subscribe(TOPIC, qos = QOS) print("Connected to %s, subscribed to %s topic" % (SERVER, TOPIC)) n = 0 pubs = 0 try: while 1: n += 1 if not n % 100: t = ticks_ms() c.publish(TOPIC, str(pubs).encode('UTF8'), retain = False, qos = QOS) c.wait_msg() pubs += 1 if not pubs % 100: print('echo received in max {} ms min {} ms'. format(maxt, mint)) if quit: return sleep(0.05) c.check_msg() finally: c.disconnect()