def __init__(self, pin): self.pin = pin # Should be initialised for input with pullup self._open_func = False self._close_func = False self.switchstate = self.pin.value() # Get initial state loop = asyncio.get_event_loop() loop.create_task(self.switchcheck()) # Thread runs forever
def __init__(self, controller = "XPT2046", asyn = False, *, confidence = 5, margin = 50, delay = 10, calibration = None): if PCB_VERSION == 1: self.pin_clock = pyb.Pin("Y8", pyb.Pin.OUT_PP) self.pin_clock.value(0) self.pin_d_out = pyb.Pin("Y7", pyb.Pin.OUT_PP) self.pin_d_in = pyb.Pin("Y6", pyb.Pin.IN) self.pin_irq = pyb.Pin("Y5", pyb.Pin.IN) else: self.pin_clock = pyb.Pin("X11", pyb.Pin.OUT_PP) self.pin_clock.value(0) self.pin_d_out = pyb.Pin("X12", pyb.Pin.OUT_PP) self.pin_d_in = pyb.Pin("Y1", pyb.Pin.IN) self.pin_irq = pyb.Pin("Y2", pyb.Pin.IN) # set default values self.ready = False self.touched = False self.x = 0 self.y = 0 self.buf_length = 0 cal = TOUCH.DEFAULT_CAL if calibration is None else calibration self.asynchronous = False self.touch_parameter(confidence, margin, delay, cal) if asyn: self.asynchronous = True import uasyncio as asyncio loop = asyncio.get_event_loop() loop.create_task(self._main_thread())
async def start(self, slow_platform=False): data = await self.read_coro() loop = asyncio.get_event_loop() if len(data) == 2 or (self.expect_ts and len(data) == 3): loop.create_task(self._update_nomag(slow_platform)) else: loop.create_task(self._update_mag(slow_platform))
def setup(): loop = asyncio.get_event_loop() tft = TFT_G("SSD1963", "LB04301", LANDSCAPE) touch = TOUCH("XPT2046", True, confidence = 50, margin = 50) # (-3886,-0.1287,-3812,-0.132,-3797,-0.07685,-3798,-0.07681)) tft.backlight(100) # light on: remove this line if you don't have backlight control hardware Screen.setup(tft, touch)
async def buttoncheck(self): loop = asyncio.get_event_loop() if self._long_func: longdelay = Delay_ms(self._long_func, self._long_args) if self._double_func: doubledelay = Delay_ms() while True: state = self.rawstate() # State has changed: act on it now. if state != self.buttonstate: self.buttonstate = state if state: # Button is pressed if self._long_func and not longdelay.running(): # Start long press delay longdelay.trigger(Pushbutton.long_press_ms) if self._double_func: if doubledelay.running(): launch(self._double_func, self._double_args) else: # First click: start doubleclick timer doubledelay.trigger(Pushbutton.double_click_ms) if self._true_func: launch(self._true_func, self._true_args) else: # Button release if self._long_func and longdelay.running(): # Avoid interpreting a second click as a long push longdelay.stop() if self._false_func: launch(self._false_func, self._false_args) # Ignore state changes until switch has settled await asyncio.sleep_ms(Pushbutton.debounce_ms)
def trigger(self, duration): # Update end time loop = asyncio.get_event_loop() self.tstop = loop.time() + duration if not self._running: # Start a thread which stops the delay after its period has elapsed loop.create_task(self.killer()) self._running = True
async def killer(self): loop = asyncio.get_event_loop() while self.tstop > loop.time(): # Must loop here: might be retriggered await asyncio.sleep_ms(self.tstop - loop.time()) if self._running and self.func is not None: launch(self.func, self.args) # Execute callback self._running = False
async def test_task(): if switch.value() == 1: print('Calibrate. Push switch when done.') await fuse.calibrate(lambda : not switch.value()) print('Mag bias vector: ', fuse.magbias) await fuse.start() # Start the update task loop = asyncio.get_event_loop() loop.create_task(display())
def __init__(self, pin): self.pin = pin # Initialise for input self._true_func = False self._false_func = False self._double_func = False self._long_func = False self.sense = pin.value() # Convert from electrical to logical value self.buttonstate = self.rawstate() # Initial state loop = asyncio.get_event_loop() loop.create_task(self.buttoncheck()) # Thread runs forever
async def lcd_task(): print('Running test...') if switch.value() == 1: lcd[0] = "Calibrate. Push switch" lcd[1] = "when done" await asyncio.sleep_ms(100) # Let LCD coro run await fuse.calibrate(lambda : not switch.value()) print(fuse.magbias) await fuse.start() # Start the update task loop = asyncio.get_event_loop() loop.create_task(display())
def setup(self): self.cfg = self.load() import uasyncio as asyncio async def task(): while True: await asyncio.sleep(self.cfg['interval']) try: self.ddnsupdate() except: logger.error('update failed') loop = asyncio.get_event_loop() loop.create_task(task())
def run(self, host="127.0.0.1", port=8081, debug=False, lazy_init=False): self.debug = int(debug) self.init() if not lazy_init: for app in self.mounts: app.init() loop = asyncio.get_event_loop() if debug: print("* Running on http://%s:%s/" % (host, port)) loop.create_task(asyncio.start_server(self._handle, host, port)) loop.run_forever() loop.close()
def __init__(self): super().__init__() # Label common attributes labels = { 'width' : 70, 'fontcolor' : WHITE, 'border' : 2, 'fgcolor' : RED, 'bgcolor' : (0, 40, 0), 'font' : font14, } # Static labels Label((90, 0), font = font10, value = 'Flashing buttons') Label((90, 18), font = font10, value = '(RH responds to long press)') Label((244, lr(1) + 5), font = font10, value = 'Reset radio button') Label((244, lr(2) + 5), font = font10, value = 'Reset checkbox') Label((244, lr(3) + 5), font = font10, value = 'Disable rb, checkbox') Label((370, 243), font = font14, value = 'Quit') # Dynamic labels self.lstlbl = [] for n in range(4): self.lstlbl.append(Label((400, lr(n)), **labels)) # Flashing buttons (RH one responds to long press) IconButton((10, lr(0)), icon_module = flash, flash = 1.0, callback = self.callback, args = ('A', 0)) IconButton((50, lr(0)), icon_module = flash, flash = 1.0, callback = self.callback, args = ('Short', 0), lp_callback = self.callback, lp_args = ('Long', 0), onrelease = False) # Quit button IconButton((420, 240), icon_module = radiobutton, callback = self.quit) # Radio buttons rb = IconRadioButtons(callback = self.callback) rb0 = rb.add_button((10, lr(1)), icon_module = radiobutton, args = ('1', 1)) rb.add_button((50, lr(1)), icon_module = radiobutton, args = ('2', 1)) rb.add_button((90, lr(1)), icon_module = radiobutton, args = ('3', 1)) rb.add_button((130, lr(1)), icon_module = radiobutton, args = ('4', 1)) # Checkbox cb = IconButton((10, lr(2)), icon_module = threestate, toggle = True, callback = self.cbcb, args =(2,)) # Traffic light state change button IconButton((10, lr(4)), icon_module = traffic, toggle = True) # Reset buttons IconButton((200, lr(1)), icon_module = radiobutton, callback = self.rb_cancel, args = (rb, rb0)) IconButton((200, lr(2)), icon_module = radiobutton, callback = self.cb_cancel, args = (cb,)) # Switch sw = IconButton((10, lr(3)), icon_module = iconswitch, callback = self.cbswitch, toggle = True, args = (3,)) # Disable Checkbox IconButton((200, lr(3)), icon_module = checkbox, toggle = True, callback = self.cb_en_dis, args =((cb, rb, sw),)) # Gauge ig = IconGauge((80, lr(5)), icon_module = gauge) loop = asyncio.get_event_loop() loop.create_task(self.mainthread(ig))
async def switchcheck(self): loop = asyncio.get_event_loop() while True: state = self.pin.value() if state != self.switchstate: # State has changed: act on it now. self.switchstate = state if state == 0 and self.close_func: launch(self._close_func, self._close_args) elif state == 1 and self._open_func: launch(self._open_func, self._open_args) # Ignore further state changes until switch has settled await asyncio.sleep_ms(Switch.debounce_ms)
def __init__(self): super().__init__() Label((0, 0), font = font14, value = 'Green dial runs only') Label((0, 30), font = font14, value = 'when screen is visible') Label((0, 120), font = font14, value = "Yellow dial's value is") Label((0, 150), font = font14, value = 'computed continuously.') self.dial1 = Dial((350, 10), fgcolor = GREEN, border = 2, pointers = (0.9, 0.7)) self.dial2 = Dial((350, 120), fgcolor = YELLOW, border = 2, pointers = (0.9, 0.7)) self.pause = False # asyncio can't pause coros so handle at application level loop = asyncio.get_event_loop() loop.create_task(self.mainthread(self.dial1, True)) loop.create_task(self.mainthread(self.dial2)) fwdbutton(0, 242, BackScreen) backbutton(390, 242)
def __init__(self): super().__init__() # Common args for the labels labels = { 'width' : 70, 'fontcolor' : WHITE, 'border' : 2, 'fgcolor' : RED, 'bgcolor' : (0, 40, 0), } # Common arguments for all three sliders table = {'fontcolor' : WHITE, 'legends' : ('0', '5', '10'), 'cb_end' : self.slide_release, } self.led = LED((420, 0), border = 2) meter1 = Meter((320, 0), font=font10, legends=('0','5','10'), pointercolor = YELLOW, fgcolor = GREEN) meter2 = Meter((360, 0), font=font10, legends=('0','5','10'), pointercolor = YELLOW) btnquit = Button((390, 240), font = font14, callback = self.quit, fgcolor = RED, text = 'Quit', shape = RECTANGLE, width = 80, height = 30) # Create labels x = 230 lstlbl = [] for n in range(3): lstlbl.append(Label((x, 40 + 60 * n), font = font10, **labels)) # Sliders x = 10 self.slave1 = HorizSlider((x, 100), font = font10, fgcolor = GREEN, cbe_args = ('Slave1',), cb_move = self.slave_moved, cbm_args = (lstlbl[1],), **table) self.slave2 = HorizSlider((x, 160), font = font10, fgcolor = GREEN, cbe_args = ('Slave2',), cb_move = self.slave_moved, cbm_args = (lstlbl[2],), **table) master = HorizSlider((x, 40), font = font10, fgcolor = YELLOW, cbe_args = ('Master',), cb_move = self.master_moved, slidecolor=RED, border = 2, cbm_args = (lstlbl[0],), value=0.5, **table) # On/Off toggle: enable/disable bs = ButtonList(self.cb_en_dis) self.lst_en_dis = [self.slave1, btnquit] button = bs.add_button((280, 240), font = font14, fontcolor = BLACK, height = 30, width = 90, fgcolor = GREEN, shape = RECTANGLE, text = 'Disable', args = (True,)) button = bs.add_button((280, 240), font = font14, fontcolor = BLACK, height = 30, width = 90, fgcolor = RED, shape = RECTANGLE, text = 'Enable', args = (False,)) # Threads to test meters loop = asyncio.get_event_loop() loop.create_task(self.testmeter(meter1)) loop.create_task(self.testmeter(meter2))
def run(self, host="127.0.0.1", port=8081, debug=False, lazy_init=False, log=None): if log is None and debug >= 0: import ulogging log = ulogging.getLogger("picoweb") if debug > 0: log.setLevel(ulogging.DEBUG) self.log = log gc.collect() self.debug = int(debug) self.init() if not lazy_init: for app in self.mounts: app.init() loop = asyncio.get_event_loop() if debug > 0: print("* Running on http://%s:%s/" % (host, port)) loop.create_task(asyncio.start_server(self._handle, host, port)) loop.run_forever() loop.close()
def run(self, debug=False): if debug: import logging logging.basicConfig(level=logging.DEBUG) loop = asyncio.get_event_loop() this = self @asyncio.coroutine def serve(reader, writer): yield from this.serve(reader, writer) loop.call_soon(asyncio.start_server( client_coro=serve, host=self._bind_addr, port=self._port, backlog=self._backlog )) loop.run_forever() loop.close()
def __init__(self, controller="XPT2046", asyn=False, *, confidence=5, margin=50, delay=10, calibration=None, spi = None): if spi is None: self.spi = SPI(-1, baudrate=1000000, sck=Pin("X12"), mosi=Pin("X11"), miso=Pin("Y2")) else: self.spi = spi self.recv = bytearray(3) self.xmit = bytearray(3) # set default values self.ready = False self.touched = False self.x = 0 self.y = 0 self.buf_length = 0 cal = TOUCH.DEFAULT_CAL if calibration is None else calibration self.asynchronous = False self.touch_parameter(confidence, margin, delay, cal) if asyn: self.asynchronous = True import uasyncio as asyncio loop = asyncio.get_event_loop() loop.create_task(self._main_thread())
def test_client_server(self): '''Simple client-server echo test''' sockaddr = ('127.0.0.1', 8080) l = get_event_loop() async def echo_server(reader, writer): data = await reader.readline() await writer.awrite(data) await writer.aclose() async def echo_client(line, result): await sleep_ms(10) # Allow server to get up reader, writer = await open_connection(*sockaddr) await writer.awrite(line) data = await reader.readline() await writer.aclose() result.append(data) # capture response result = [] l.create_task(start_server(echo_server, *sockaddr)) l.run_until_complete(echo_client(b'Hello\r\n', result)) self.assertEqual(result[0], b'Hello\r\n')
import uasyncio import machine from tools.battery import Battery machine.freq(240000000) # Can only be done once at boot before start the camera and sd card onBattery = Battery.isActivated() # If the power supply is the mains if onBattery == False: from tools import useful isPinWakeUp = False # Create asyncio loop loop = uasyncio.get_event_loop() # Html pages loader def pageLoader(): # The html pages only loaded when the connection of http server is done # This reduces memory consumption if the server is not used import webpage from server.httpserver import HttpServer try: # Welcome page (can be suppressed) from welcome import welcomePage except ImportError as err: pass try:
def launch(func, tup_args): res = func(*tup_args) if isinstance(res, type_gen): loop = asyncio.get_event_loop() loop.create_task(res)
def __init__(self, uart_no = 2, timeout=4000): self.uart = UART(uart_no, 9600, timeout=timeout) self.loop = asyncio.get_event_loop() self.deadline = None self.result = ''
def calibrate(req, resp): loop = uasyncio.get_event_loop() loop.create_task(app.black.calibrate_motor()) yield from json_response(resp, position=app.black.motor.position)
def register(self) : loop = uasyncio.get_event_loop() loop.create_task(self.loop()) self.state = TaskBase.RUNNING return self
def launch(func, tup_args): res = func(*tup_args) if isinstance(res, type_coro): loop = asyncio.get_event_loop() loop.create_task(res)
def _reconnect(self): # Schedule a reconnection if not underway. if self._isconnected: self._isconnected = False self.close() loop = asyncio.get_event_loop() loop.create_task(self._wifi_handler(False)) # User handler.
def barrier_test(): loop = asyncio.get_event_loop() for _ in range(3): loop.create_task(report()) loop.run_until_complete(killer(2)) loop.close()
def event_test(lp=True): # Option to use low priority scheduling loop = asyncio.get_event_loop() loop.run_until_complete(run_event_test(lp))
def main(): loop = uasyncio.get_event_loop() loop.create_task(check_button()) loop.create_task(update_leds()) loop.run_forever()
def start_get_stuck(interval=5000): asyncio.get_event_loop().create_task(_get_stuck(interval))
def stability_log(interval=600): asyncio.get_event_loop().create_task(_stability_log(interval)) asyncio.get_event_loop().create_task(_interrupt(600))
wlan.append(line) line=f.readline().strip().split() if machine.wake_reason()[0] not in [4,6]:#Soft reset # this should help reconnecting... not sure whether it works or not # configuration below MUST match your home router settings!! print('configure wlan') sta.ifconfig(('192.168.178.35', '255.255.255.0', '192.168.178.1', '8.8.8.8')) timeout=5000 #5 seconds if not sta.isconnected(): # try all wlans from the file # todo: scan first and check which can be seen for pw in wlan: start = time.ticks_ms() while not sta.isconnected(): if time.ticks_diff(time.ticks_ms(), start) > timeout: break sta.connect(*pw) print('connecting to wlan, ip is {}'.format(sta.ifconfig()[0])) await asyncio.sleep(1) else: break if not sta.isconnected(): #todo: start station mode pass print('starting telnet...') network.telnet.start() asyncio.get_event_loop().create_task(connect())
def run_event_loop(): import uasyncio print("Running event loop... (^C to exit)") uasyncio.get_event_loop().run_forever()
def resume() : uasyncio.get_event_loop().run_forever()
def start_managing(cls): loop = asyncio.get_event_loop() loop.create_task(cls.manage()) # Schedule ASAP
async def test_task(): await fuse.start() # Start the update task loop = asyncio.get_event_loop() loop.create_task(display())
def test(): MQTTlink.will('result', 'client died') init['user_start'] = start mqtt_link = MQTTlink(init) # No. of user tasks loop = asyncio.get_event_loop() loop.run_forever()
def async_dht(): print('async_dht') loop = asyncio.get_event_loop() loop.create_task(await_dht()) loop.run_until_complete(async_dht_done())
def test(): loop = asyncio.get_event_loop() ls = LedService() # do adhoc blink, twice green loop.create_task(ls.blick(0, 1, 0, 2)) loop.run_until_complete(killer(ls)) # Run for 10s
async def main(): global app # For finally clause loop = asyncio.get_event_loop() loop.set_exception_handler(_handle_exception) app = App(verbose=True) await app.start()
def start(self): loop = asyncio.get_event_loop() loop.create_task(self.consumer()) loop.create_task(self.producer()) self.run = True
def start(): gc.collect() loop = uasyncio.get_event_loop() loop.create_task(_ntpd()) loop.create_task(_gc()) loop.run_forever()
def __init__(self, i2c, pin, pinack, verbose=True): super().__init__(i2c, pinack, pin, verbose, self.rxbufsize) loop = asyncio.get_event_loop() loop.create_task(self._run())
async def _loop(self): await asyncio.sleep(1) d = float("inf") if self._intpb == -1 else (self._intpb / self._intrd) i = d + 1 # so first reading gets published pbc = None try: while True: # d recalculated in loop so _intpb and _intrd can be changed during runtime d = float("inf") if self._intpb == -1 else (self._intpb / self._intrd) pb = i >= d i = 1 if pb else i + 1 t = time.ticks_ms() while self._reading: # wait when sensor is read because of a getValue(no_stale=True) request await asyncio.sleep_ms(50) self._reading = True await self._read() self._reading = False if self._event: self._event.set() if pb: if pbc is not None: asyncio.cancel(pbc) vals = 0 # counting sensor_types which have a topic as those get published separately for tp in self._values: if tp[5] is not None: vals += 1 vals = vals or 1 # if no type has a topic, one is still used to publish sl = self._intrd * 1000 - time.ticks_diff( time.ticks_ms(), t) if sl / 1000 > 5 * vals: # if enough time is left until next reading then await publishing values # (5 seconds per unique sensor_type) await self._publishValues() else: # otherwise start task to publish values which might get canceled if # it can't finish until next publish is requested. pbc = self._publishValues() asyncio.get_event_loop().create_task(pbc) # sleep until the sensor should be read again. Using loop with 100ms makes # changing the read interval during runtime possible with a reaction time of 100ms. while True: sl = self._intrd * 1000 - time.ticks_diff( time.ticks_ms(), t) sl = 100 if sl > 100 else sl if sl > 0 else 0 # sleeping with 0 lets other coros run in between await asyncio.sleep_ms(sl) if sl == 0: # sleeping done break except asyncio.CancelledError: if pbc is not None: asyncio.cancel(pbc) raise except NotImplementedError: raise except Exception as e: if config.DEBUG: import sys sys.print_exception(e) await self._log.asyncLog("critical", "Exception in component loop:", e)
from uasyncio import get_event_loop import network _CONFIG_FILE = "netconf.json" # this file must contain, hostname, password, known networks, port (...) _OBJS = ('ecu', 'io') # all non-private vars in these objects will be monitored and sent to clients on update _WS_INACT_TO = 14 # client is closed when no message (incl PING!) received for _ s (>= WS_SYN_INTERVAL) _AP_CONF = ('192.168.0.1', '255.255.255.0', '192.168.0.1', '') # ip, subnet, gateway, dns _HTML_INDEX = "/html/index.html" # None = unused _HTML_404 = "/404.html" # None = unused # global because both NetServer and NetClient need access _stay_on_for = 0 # chip is expected to remain on even if bike powered off for this time _stay_on_tmr = tms() # in respect to this timer (set on network start) loop = get_event_loop() # current event loop (same as in main()) def read_cfg(key=None): # key can be specified for a single entry, otherwise returns all data try: with open(_CONFIG_FILE, 'r') as f: dat = json.loads(f.read()) if key is not None: return dat[key] return dat except KeyError: return None def write_cfg(dat): # dat = data dict (format must be exactly of type see json file) with open(_CONFIG_FILE, 'w') as f:
def populate(self, curve): loop = asyncio.get_event_loop() loop.create_task(self.acquire(curve))
int_err_count += 1 if int_err_count >= config.CONFIG['INT_CRIT_ERR']: client.disconnect() wifi.wlan.disconnect() machine.reset() if int_err_count >= config.CONFIG['INT_MAX_ERR']: print("Internet reconnect") client.disconnect() wifi.wlan.disconnect() wifi.activate() except Exception as error: print("Error in Internet connection: [Exception] %s: %s" % (type(error).__name__, error)) mqtt_reconnect() try: loop = asyncio.get_event_loop() loop.create_task(check_message()) loop.create_task(check_internet()) loop.create_task(mqtt_check()) loop.run_forever() except Exception as e: print("Error: [Exception] %s: %s" % (type(e).__name__, e)) time.sleep(60) machine.reset() # client.disconnect()
def named_test(): loop = asyncio.get_event_loop() loop.run_until_complete(run_named_test(loop))
def run_forever(self): if RTC().memory() == b"webrepl": RTC().memory(b"") else: loop = get_event_loop() loop.run_until_complete(self.run())
def cancel_test(): loop = asyncio.get_event_loop() loop.run_until_complete(run_cancel_test(loop))
def scheduleSubscribe(self, topic, qos=0, check_retained_state_topic=True): asyncio.get_event_loop().create_task( self.subscribe(topic, qos, check_retained_state_topic))
def semaphore_test(bounded=False): loop = asyncio.get_event_loop() loop.run_until_complete(run_sema_test(bounded))
async def main(): asyncio.create_task(wdt_feeder()) asyncio.create_task(urpc_server.async_serve(uart, READINTO_BUFFER_SIZE)) asyncio.get_event_loop().run_forever()
global cnt #s = "Hello.\r\n" s = "Hello. %07d\r\n" % cnt cnt += 1 yield from reader.read() yield from writer.awrite("HTTP/1.0 200 OK\r\n\r\n") try: yield from writer.awrite(s) yield from writer.awrite(s * 100) yield from writer.awrite(s * 400000) yield from writer.awrite("=== END ===") yield from writer.close() except OSError as e: if e.args[0] == errno.EPIPE: print("EPIPE") elif e.args[0] == errno.ECONNRESET: print("ECONNRESET") else: raise import logging logging.basicConfig(level=logging.INFO) #logging.basicConfig(level=logging.DEBUG) signal.signal(signal.SIGPIPE, signal.SIG_IGN) loop = asyncio.get_event_loop() mem_info() loop.call_soon(asyncio.start_server(serve, "0.0.0.0", 8081, backlog=100)) loop.run_forever() loop.close()
def ack_test(): loop = asyncio.get_event_loop() loop.create_task(run_ack()) loop.run_until_complete(ack_coro(10))