def controller(*args): from controller import KLS_S TARGET_RPS = 8 PRINT_STATUS_EVERY = 5 # seconds global RUNNING, controller_data controller = KLS_S() count = max_work_t = 0 min_work_t = 100000000 loop_time = 1000 // TARGET_RPS next_print_fps_t = time.ticks_add(time.ticks_ms(), PRINT_STATUS_EVERY * 1000) while RUNNING: next_frame_t = time.ticks_add(time.ticks_ms(), loop_time) controller_data = v = controller.refresh() sleep_to_next_t = time.ticks_diff(next_frame_t, time.ticks_ms()) min_work_t, max_work_t = min(max_work_t, loop_time - sleep_to_next_t), max(min_work_t, loop_time - sleep_to_next_t) count += 1 time.sleep_ms(sleep_to_next_t) if time.ticks_diff(next_print_fps_t, time.ticks_ms()) <= 0: print('- CTRLR - RPS: {}, min-max time per frame: {}-{}/{}ms, comm ok:{} err:{}'.format(count / PRINT_STATUS_EVERY, min_work_t, max_work_t, loop_time, v.comm_ok, v.comm_err)) next_print_fps_t = time.ticks_add(time.ticks_ms(), PRINT_STATUS_EVERY * 1000) count = max_work_t = 0 min_work_t = 100000000 print('Controller thread exited')
def datastore_(*args): import datastore1 as ds TARGET_RPS = 0.033 # every 30 seconds PRINT_STATUS_EVERY = 40 # seconds global RUNNING, ds_data ds_data = ds.DataStore(buckets=['statsA']) start_t = time.ticks_ms() run_time = 0 count = max_work_t = 0 min_work_t = 100000000 loop_time = int(1000 // TARGET_RPS) next_print_fps_t = time.ticks_add(time.ticks_ms(), PRINT_STATUS_EVERY * 1000) while RUNNING: next_frame_t = time.ticks_add(time.ticks_ms(), loop_time) ds_data.persist('statsA') sleep_to_next_t = time.ticks_diff(next_frame_t, time.ticks_ms()) min_work_t, max_work_t = min(max_work_t, loop_time - sleep_to_next_t), max(min_work_t, loop_time - sleep_to_next_t) time.sleep_ms(sleep_to_next_t) count += 1 if time.ticks_diff(next_print_fps_t, time.ticks_ms()) <= 0: print('- DATASTORE - RPS: {}, min-max time per frame: {}-{}/{}ms'.format(count / PRINT_STATUS_EVERY, min_work_t, max_work_t, loop_time)) next_print_fps_t = time.ticks_add(time.ticks_ms(), PRINT_STATUS_EVERY * 1000) count = max_work_t = 0 min_work_t = 100000000
def check(self): # first, check if the switch status has changed # if yes, turn on/off pumps accordingly switch_status = self.switch_pin.value() if self.switch_status != switch_status: self.switch_status = switch_status if switch_status == 1: self.turn_on() else: self.turn_off() self.watering_ended = time.ticks_ms() # next, exit if the switch is on if switch_status == 1: return # then, if the pumps are off, check if it's time to turn them on current_time = time.ticks_ms() if self.pump_status == 0: deadline = time.ticks_add(self.watering_ended, self.interval) if time.ticks_diff(deadline, current_time) <= 0: self.turn_on() self.watering_started = current_time else: # finally, if the pumps are on, check if it's time to turn them off deadline = time.ticks_add(self.watering_started, self.duration) if time.ticks_diff(deadline, current_time) <= 0: self.turn_off() self.watering_ended = current_time
def repeat( self ): assert self.TimePeriod > 2, "Start not invoked yet" assert not self.running, "Can't repeat running timer" # self.TimeStart= time.ticks_add( self.TimeStart, self.TimePeriod ) self.TimeEnd = time.ticks_add( self.TimeStart, self.TimePeriod ) self.running = True self._md_add_timer()
def screen_main(*args): from screen import Screen20x4 TARGET_RPS = 8 PRINT_STATUS_EVERY = 5 # seconds global RUNNING, controller_data, bms_data, ds_data, calc_data screen = Screen20x4() count = max_work_t = 0 min_work_t = 100000000 loop_time = 1000 // TARGET_RPS count = 0 calc_data = {'uptime': 0, 'power': 0, 'energy_count': 0} mark_t = time.ticks_ms() while RUNNING: ctrl_f = controller_data.alive() bms_f = bms_data.alive() ds_f = ds_data.alive() screen.draw_connecting(ctrl_f, bms_f, ds_f, count) if ctrl_f and bms_f and ds_f: break else: time.sleep(1) count += 1 time.sleep(1) screen.lcd.clear() next_print_fps_t = time.ticks_add(time.ticks_ms(), PRINT_STATUS_EVERY * 1000) while RUNNING: next_frame_t = time.ticks_add(time.ticks_ms(), loop_time) screen.draw_main(controller_data, bms_data, calc_data) sleep_to_next_t = time.ticks_diff(next_frame_t, time.ticks_ms()) min_work_t, max_work_t = min(max_work_t, loop_time - sleep_to_next_t), max(min_work_t, loop_time - sleep_to_next_t) time.sleep_ms(sleep_to_next_t) count += 1 if count % 10 == 0: # every 10 iterations tt = time.ticks_ms() calc_data['uptime'] = calc_data.get('uptime', 0) + time.ticks_diff(mark_t, tt) / 1000 mark_t = tt # distance travel if time.ticks_diff(next_print_fps_t, time.ticks_ms()) <= 0: print('- SCRN - RPS: {}, min-max time per frame: {}-{}/{}ms'.format(count / PRINT_STATUS_EVERY, min_work_t, max_work_t, loop_time)) next_print_fps_t = time.ticks_add(time.ticks_ms(), PRINT_STATUS_EVERY * 1000) count = max_work_t = 0 min_work_t = 100000000 print('Screen thread exited')
def main() -> None: # Initialization can = CAN(SPI(cs=23)) # Configuration if can.reset() != ERROR.ERROR_OK: print("Can not reset for MCP2515") return if can.setBitrate(CAN_SPEED.CAN_250KBPS, CAN_CLOCK.MCP_8MHZ) != ERROR.ERROR_OK: print("Can not set bitrate for MCP2515") return if can.setNormalMode() != ERROR.ERROR_OK: print("Can not set normal mode for MCP2515") return # Prepare frames data = b"\x12\x34\x56\x78\x9A\xBC\xDE\xF0" # type: bytes sff_frame = CANFrame(can_id=0x7FF, data=data) sff_none_data_frame = CANFrame(can_id=0x7FF) err_frame = CANFrame(can_id=0x7FF | CAN_ERR_FLAG, data=data) eff_frame = CANFrame(can_id=0x12345678 | CAN_EFF_FLAG, data=data) eff_none_data_frame = CANFrame(can_id=0x12345678 | CAN_EFF_FLAG) rtr_frame = CANFrame(can_id=0x7FF | CAN_RTR_FLAG) rtr_with_eid_frame = CANFrame(can_id=0x12345678 | CAN_RTR_FLAG | CAN_EFF_FLAG) rtr_with_data_frame = CANFrame(can_id=0x7FF | CAN_RTR_FLAG, data=data) frames = [ sff_frame, sff_none_data_frame, err_frame, eff_frame, eff_none_data_frame, rtr_frame, rtr_with_eid_frame, rtr_with_data_frame, ] # Read all the time and send message in each second end_time, n = time.ticks_add(time.ticks_ms(), 1000), -1 # type: ignore while True: error, iframe = can.readMessage() if error == ERROR.ERROR_OK: print("RX {}".format(iframe)) if time.ticks_diff(time.ticks_ms(), end_time) >= 0: # type: ignore end_time = time.ticks_add(time.ticks_ms(), 1000) # type: ignore n += 1 n %= len(frames) error = can.sendMessage(frames[n]) if error == ERROR.ERROR_OK: print("TX {}".format(frames[n])) else: print("TX failed with error code {}".format(error))
def thWait(): deadline = time.ticks_ms() while True: while time.ticks_diff(deadline, time.ticks_ms()) > 0: yield True cnt = (yield False) deadline = time.ticks_add(time.ticks_ms(), cnt)
def check(self): current_time = time.ticks_ms() deadline = time.ticks_add(self.last_measurement, self.interval) if self.last_measurement is None or time.ticks_diff( deadline, current_time) <= 0: self.measure() self.last_measurement = current_time
def run(dt=20): while True: market_europrice, market_usdprice = price_check() #print ("Market price is euro", market_europrice, ", usd", market_usdprice) print ("Market price is €{0:7.2f} (${1:7.2f})".format(market_europrice,market_usdprice)) # repeat refresh OLED wit wait-symbol (| <-> -), which needs fill(0) now = time.ticks_ms() # Calculate deadline for operation and test for it delta = dt*1000 deadline = time.ticks_add(now, delta) isToggle = True row = 30 leftover = time.ticks_diff(deadline, time.ticks_ms()) while leftover > 0: oled.fill(0)# blank displayOnOLED(market_europrice, market_usdprice) if isToggle: oled.text('-', 0, row) isToggle = False else: oled.text('|', 0, row) isToggle = True oled.show() time.sleep(0.5) leftover = time.ticks_diff(deadline, time.ticks_ms())
def idle(dt, row=26): now = time.ticks_ms() # Calculate deadline for operation and test for it delta = dt * 1000 stepx = delta // oled.width deadline = time.ticks_add(now, delta) dcol = stepx // oled.width #print("now:", now) #print("deadline:", deadline) #print("stepx:", stepx) col = 0 i = 0 leftover = time.ticks_diff(deadline, time.ticks_ms()) while leftover > 0: oled.text('. ', col, row) oled.show() # check if col needs to be incremented... i = i + 1 #print("i:", i) #print("leftover", leftover) # increment col in leftover/127 steps if leftover % 127: col = col + 1 #print("col:", col) time.sleep(0.01) leftover = time.ticks_diff(deadline, time.ticks_ms())
def do_later(time_delta_s, callback, id=None): delta = int(time_delta_s * 1000) later = time.ticks_add(time.ticks_ms(), delta) if id is None: id = hash((hash(callback), later)) _timestack[id] = (later, callback) return id
def refresh(self): # Seeing if it's time to do work yet: next_read = time.ticks_add(self.last_read, self._read_every_ms) time_till_next_work = time.ticks_diff(next_read, time.ticks_ms()) # print("time_till_next_work: %s" % time_till_next_work) if time_till_next_work <= 0: # Log rotation: if self.last_rotate is None or (time.ticks_diff(time.ticks_ms(), self.last_rotate) / 1000) > self._rotate_period: self.rotate() # Reading: self.read_all() # print("%.4f,%.4f,%.4f,%.4f" % ( # self.sensors["in"].voltage_buffer.latest(), # self.sensors["out"].voltage_buffer.latest(), # self.sensors["in"].current_buffer.latest(), # self.sensors["out"].current_buffer.latest(), # )) #Logging: self.reads_since_last_log += 1 if self.reads_since_last_log >= self._log_every_x_reads: self.log_all() self.reads_since_last_log = 0 return time_till_next_work
def _setExpireTimeout(self, timeoutSec): try: if timeoutSec and timeoutSec > 0: self._expire_time_millis = ticks_add(ticks_ms(), timeoutSec * 1000) except: raise XAsyncSocketException( '"timeoutSec" is incorrect to set expire timeout.')
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
def sleep(self, duration): current = time.ticks_ms() elapsed = time.ticks_add(current, duration) once = duration == 0 while once or time.ticks_diff(elapsed, current) >= 0: if not self.future is None: overrun = time.ticks_diff(self.future, current) if overrun <= 0: while overrun <= -1000: overrun += 1000 self.time_ += 1 self.future = time.ticks_add(current,(1000 + overrun)) self.time_ += 1 if once: once = False else: time.sleep_ms(10) current = time.ticks_ms()
def tick(delay): global _tick delay = int(delay * 1000) now = time.ticks_ms() _tick = time.ticks_add(_tick, delay) diff = time.ticks_diff(_tick, now) if diff < 0: _tick = now diff = 0 time.sleep_ms(diff)
def run(self): last_time_us = time.ticks_us() while self.period_ms > 0: # time to sleep, minus empirical offset to correct static error this_time_us = time.ticks_add(last_time_us, 1000 * self.period_ms) dt_us = time.ticks_diff(this_time_us, time.ticks_us()) - 130 time.sleep_us(dt_us) now_us = time.ticks_us() self.callback(self, time.ticks_diff(now_us, last_time_us), dt_us) last_time_us = now_us
async def blinkLed(self, led, frequency, durationMs): start = time.ticks_ms() end = start state = False while time.ticks_add(end, -start) < durationMs: self.board.pixel(led[0], led[1], state) self.board.show() await asyncio.sleep_ms(frequency) state = not state end = time.ticks_ms()
def sleep(self, milli_sec): finish = time.ticks_ms() if milli_sec > 0: finish = time.ticks_add(finish, milli_sec) while milli_sec <= 0 or time.ticks_diff(finish, time.ticks_ms()) > 0: if self._rq.read_digital() == 0: self._read_keys() if milli_sec <= 0: break time.sleep_us(50)
def distance_mm(self): times_up = time.ticks_add(time.ticks_us(), 10) self.trig.value(1) while time.ticks_diff(times_up, time.ticks_us()) > 0: pass self.trig.value(0) pulse = machine.time_pulse_us(self.echo, 1, 2000000) if pulse > 0: pulse = (pulse * 340) / 2000 return pulse
async def _update_data_async(self): while True: # call child callback self.update_data() # TODO ISO8601 # self.property_interval.value = "PT{:1.3f}S".format(self.interval) self.property_interval.value = "{:1.3f}".format(self.interval) # We don't simply wait the update interval, as it can change while waiting. last_update = ticks_ms() wait_till = ticks_add(last_update, int(self.interval * 1000.0)) while ticks_diff(ticks_ms(), wait_till) < 0: if self.interval_changed: self.interval_changed = False wait_till = ticks_add(last_update, int(self.interval * 1000)) sleep_for = min(int(self.interval_short * 1000.0), ticks_diff(wait_till, ticks_ms())) await asyncio.sleep_ms(sleep_for)
def update_position(self): if time.ticks_ms() > self.pos_debounce: # print(self.button_up.value(), self.button_down.value(), self.position) self.pos_debounce = time.ticks_add(time.ticks_ms(), self.debounce_ms) if self.button_up.value() == 0 and self.button_down.value() == 0: return self.position elif self.button_up.value() == 0 and self.position < 6: self.position += 1 elif self.button_down.value() == 0 and self.position > 1: self.position -= 1 return self.position
def start( self, Period ): assert Period > 2, "Time period is too small" # assert Period < 1000000000, "Time period is too large" # if self.running: self.stop() # self.TimePeriod= Period self.TimeStart = time.ticks_ms() self.TimeEnd = time.ticks_add( self.TimeStart, self.TimePeriod ) self.running = True self.finishNow = False self._md_add_timer()
def setMode(self, mode: int) -> int: self.modifyRegister(REGISTER.MCP_CANCTRL, CANCTRL_REQOP, mode) endTime = time.ticks_add(time.ticks_ms(), 10) # type: ignore modeMatch = False while time.ticks_diff(time.ticks_ms(), endTime) < 0: # type: ignore newmode = self.readRegister(REGISTER.MCP_CANSTAT) newmode &= CANSTAT_OPMOD modeMatch = newmode == mode if modeMatch: break return ERROR.ERROR_OK if modeMatch else ERROR.ERROR_FAIL
def bms(*args): import bms TARGET_RPS = 2 PRINT_STATUS_EVERY = 5 # seconds _DEVICE_MAC = b'\xa4\xc1\x38\xec\x23\xd5' # FedeBatt #_DEVICE_MAC = b'\xa4\xc1\x38\x07\x28\x9d' # V1.1 global RUNNING, bms_data comm = bms.JBD_BMS_BLE(_DEVICE_MAC) bms = bms.JBD_BMS_PROTOCOL(comm) count = max_work_t = 0 min_work_t = 100000000 loop_time = 1000 // TARGET_RPS next_print_fps_t = time.ticks_add(time.ticks_ms(), PRINT_STATUS_EVERY * 1000) while RUNNING: next_frame_t = time.ticks_add(time.ticks_ms(), loop_time) bms_data = v = bms.refresh() sleep_to_next_t = time.ticks_diff(next_frame_t, time.ticks_ms()) min_work_t, max_work_t = min(max_work_t, loop_time - sleep_to_next_t), max(min_work_t, loop_time - sleep_to_next_t) count += 1 time.sleep_ms(sleep_to_next_t) if time.ticks_diff(next_print_fps_t, time.ticks_ms()) <= 0: print('- BMS - RPS: {}, min-max time per frame: {}-{}/{}ms, comm ok:{} err:{}'.format(count / PRINT_STATUS_EVERY, min_work_t, max_work_t, loop_time, v.comm_ok, v.comm_err)) next_print_fps_t = time.ticks_add(time.ticks_ms(), PRINT_STATUS_EVERY * 1000) count = max_work_t = 0 min_work_t = 100000000 comm.disconnect() print('BMS thread exited')
def beatPerMinute(self, beat, on): self.beat = beat self.fingerPresent = on if self.fingerPresent: # finger is on if self.beating == False: self.beating = True # calculate the time to wait in between pulses pulse = int( (60 * 1000) / beat ) self.deadline = time.ticks_add(time.ticks_ms(), pulse) print("d:", self.deadline, "pulse:", pulse) timer = Timer(0) # timer id is in range 0-3 timer.init(period=80, mode=Timer.PERIODIC, callback=self.pulseTimer) else: self.deadline = time.ticks_ms()
def _time_str(t): global _hour_ticks, _hour if _hour_ticks is None or ticks_diff(t, _hour_ticks) > TICKS_PER_HOUR: tm = time() if tm < TIME_2020: # we don't know the time return str(t%100000000) tm = localtime(tm) _hour = tm[3] _hour_ticks = ticks_add(t, -(((tm[4] * 60) + tm[5]) * 1000)) dt = ticks_diff(t, _hour_ticks) return "%02d:%02d:%02d.%03d" % ( _hour, (dt // 60000) % 60, # minutes (dt // 1000) % 60, # seconds dt % 1000, # millis )
def connect(self, forceWifiReset=True): ''' Args: timeout (uint): maximum in milliseconds to wait for a connection Returns: DISCONNECTED if the connection failed, ALREADY_CONNECTED if the connection was already active and is still valid, RECONNECTED if the connection had to be re-established ''' sta_if = network.WLAN(network.STA_IF) maxWaitTime = time.ticks_add(time.ticks_ms(), self.timeout) if (forceWifiReset): self.status = WIFI_DISCONNECTED sta_if.disconnect() elif (not sta_if.isconnected()): self.status = WIFI_DISCONNECTED if (self.status == WIFI_DISCONNECTED): if (self.ledStatusPin is not None): #Blink to inform that we are going to connect for b in range(10): if ((b % 2) == 1): self.ledStatusPin.off() else: self.ledStatusPin.on() time.sleep_ms(100) self.ledStatusPin.on() ap = network.WLAN(network.AP_IF) ap.active(True) print('Connecting to network...') sta_if.active(True) sta_if.connect(wifi_secrets.WIFI_ESSID, wifi_secrets.WIFI_PASS) self.status = WIFI_RECONNECTED while not sta_if.isconnected(): time.sleep_ms(100) if (time.ticks_diff(time.ticks_ms(), maxWaitTime) > 0): print('Failed to connect to the network...') self.status = WIFI_DISCONNECTED break if (self.status == WIFI_RECONNECTED): if (self.ledStatusPin is not None): self.ledStatusPin.off() print('Network config:', sta_if.ifconfig()) #Required for multicast to work! ap.active(False) elif (self.status == WIFI_RECONNECTED): self.status = WIFI_ALREADY_CONNECTED return self.status
def display(byte, col_time, COL_INDEX, GPIO_REG, GPIO_EN, GPIO_CLR, ALL_LEDS): '''Displays Text on POVPi''' if COL_INDEX < 90: cleared = ALL_LEDS - byte col_timeout = time.ticks_add(time.ticks_cpu(), col_time * 4) if byte == 0: machine.mem32[GPIO_REG + GPIO_CLR] ^= ALL_LEDS else: machine.mem32[GPIO_REG + GPIO_CLR] ^= cleared machine.mem32[GPIO_REG + GPIO_EN] ^= byte while time.ticks_diff(col_timeout, time.ticks_cpu()) >= 0: pass machine.mem32[GPIO_REG + GPIO_CLR] ^= ALL_LEDS return COL_INDEX + 1 else: machine.mem32[GPIO_REG + GPIO_CLR] ^= ALL_LEDS return COL_INDEX
def _reset(self, alarm=None): now = time.ticks_ms() for addr, node in self._nodes.items(): if node._reset_next != None and time.ticks_diff( node._reset_next, now) >= 0: print("_reset", node._unit_addr) node._reset_next = time.ticks_add( now, node._reset_trial * 5000 + (machine.rng() % 5000)) if node._reset_trial < 30: node._reset_trial += 1 self._reset_timeout = Timer.Alarm(self._reset, 5) node._reset_session = crypto.getrandbits(64) self._send_with_session(node, node._reset_session, _MSG_RST_1, None) return Timer.Alarm(self._reset, 2)