def run(self, host='0.0.0.0', port=5000, debug=False): """Start the web server. This function does not normally return, as the server enters an endless listening loop. The :func:`shutdown` function provides a method for terminating the server gracefully. :param host: The hostname or IP address of the network interface that will be listening for requests. A value of ``'0.0.0.0'`` (the default) indicates that the server should listen for requests on all the available interfaces, and a value of ``127.0.0.1`` indicates that the server should listen for requests only on the internal networking interface of the host. :param port: The port number to listen for requests. The default is port 5000. :param debug: If ``True``, the server logs debugging information. The default is ``False``. Example:: from microdot_asyncio import Microdot app = Microdot() @app.route('/') async def index(): return 'Hello, world!' app.run(debug=True) """ asyncio.run(self.start_server(host=host, port=port, debug=debug))
def run(): try: asyncio.run(killer()) except KeyboardInterrupt: print('Interrupted') finally: asyncio.new_event_loop()
def change(cls, cls_new_screen, *, forward=True, args=[], kwargs={}): init = cls.current_screen is None if init: Screen() # Instantiate a blank starting screen else: # About to erase an existing screen for entry in cls.current_screen.tasklist: if entry[1]: # To be cancelled on screen change entry[0].cancel() cs_old = cls.current_screen cs_old.on_hide() # Optional method in subclass if forward: if isinstance(cls_new_screen, ClassType): new_screen = cls_new_screen(*args, **kwargs) # Instantiate new screen else: raise ValueError( 'Must pass Screen class or subclass (not instance)') new_screen.parent = cs_old cs_new = new_screen else: cs_new = cls_new_screen # An object, not a class cls.current_screen = cs_new cs_new.on_open() # Optional subclass method cs_new._do_open(cs_old) # Clear and redraw cs_new.after_open() # Optional subclass method if init: try: asyncio.run(Screen.monitor()) # Starts and ends uasyncio finally: asyncio.new_event_loop() gc.collect()
async def main(duration): print("Flash LED's for {} seconds".format(duration)) leds = [pyb.LED(x) for x in range(1, 4)] # Initialise three on board LED's for x, led in enumerate(leds): # Create a task for each LED t = int((0.2 + x / 2) * 1000) asyncio.create_task(toggle(leds[x], t)) asyncio.run(killer(duration))
def enter(self, event, fsm): #加上打开json语句 print("sousvide setting temperature") # global rotary, rotary_sw, rotary_press_count, val_old, val_new, setpoint, arr, new_setpoint #读取温度设定 read_config() setpoint = float(setpoint) #xs 小数点后,会有误差 #zs整数 xs, zs = math.modf(setpoint) aa = int(zs / 10) #十位 bb = int(zs % 10) #个位 cc = int(10 * xs) #小数点后第一位 #dd=int(100*xs)%10#小数点后第二位 print("original num is:\n %.2f" % setpoint) #print("after :\n %d,%d,%d,%d" %(aa,bb,cc,dd)) #设定数组,初始化,为了以后方便,精度可扩展到小数点后两位 arr = array.array('b', []) arr.append(aa) #十位数 arr.append(bb) #个位 arr.append(cc) #小数点后第一位 #arr.append(dd)#小数点后第二位 print("enter setting temperature") asyncio.create_task(rotary_change_temp()) #修改十位 #修改个位 #修改小数点后第一位 #修改小数点后第二位 #存在setpoint这个值 asyncio.run(rotary_change_temp())
def enter(self, event, fsm): print("sousvide setting timer") global rotary, rotary_sw, rotary_press_count, val_old, val_new, countdown_timer, arr_t #打开json,读取温度设定 read_config() #change to minutes countdown_timer = int(countdown_timer) / 60 #时间格式:小时:分钟 hours = int(countdown_timer / 60) #小时,最大不超过9小时 mins = int(countdown_timer % 60) #分钟,最大不超过60 aa = int(mins / 10) #十位 bb = int(mins % 10) #个位 print("original num is:\n %.0f" % countdown_timer) #print("after :\n %d,%d,%d,%d" %(aa,bb,cc,dd)) #设定数组,初始化,为了以后方便,精度可扩展到小数点后两位 arr_t = array.array('b', []) arr_t.append(hours) #hours arr_t.append(aa) #mins,十位数 arr_t.append(bb) #mins,个位 print("enter setting temperature") asyncio.create_task(rotary_change_timer()) asyncio.run(rotary_change_timer())
def enter(self, event, fsm): global error, setpoint, temp, countdown_timer, cancel_sw, start_time, time_left, m_total, is_countdown_flag print("sousvide is going to count down") #程序开始时间 start_time = time.time() #计时精度够了 oled.fill(0) #清屏 oled.draw_chinese('倒计时', 0, 0) #oled.text(str(countdown_timer/60)+' Min',0,40) #白色线 #oled.hline( 0, 32, 128, 1) oled.show() while True: # 加热 #global error ,setpoint,temp,countdown_timer,cancel_sw,start_time #nonlocal time_left #countdown_timer # 计时设定时间 #time_left # 剩余时间,单位是浮点秒数 t1 = time.time() - start_time # 计时时间间隔,单位秒 #countdown_timer类型为str,要转换 time_left = float(countdown_timer) - t1 # 剩余时间 m_total, s = divmod(time_left, 60) # 获取分, 秒 h, m = divmod(m_total, 60) # 获取小时,分 if time_left > 0: # print("%02d:%02d:%02d" % (h, m, s)) 正常打印 #加热 #process() pro = asyncio.run(process()) # 显示剩余加热时间 show = asyncio.run(show_countdown()) #print("\n\r%02d:%02d:%02d\n" % (h, m, s),end="") # 每次把光标定位到行首,打印 else: print("\n计时结束") is_countdown_flag = 1
def __init__(self, pin, num_leds, address="0.0.0.0", port=8000): self.device_name = uos.uname()[0] self.pin = machine.Pin(pin, machine.Pin.OUT) # configure pin for leds self.np = neopixel.NeoPixel(self.pin, num_leds) # configure neopixel library self.address = address self.port = port self.animation_map = { "rainbow": self.rainbow, "rainbowChase": self.rainbowChase, "bounce": self.bounce, "chase": self.chase, "rgbFade": self.rgbFade, "altColors": self.altColors, "randomFill": self.randomFill, "fillFromMiddle": self.fillFromMiddle, "fillFromSides": self.fillFromSides, "fillStrip": self.fillStrip, "wipe": self.wipe, "sparkle": self.sparkle, "setStrip": self.setStrip, "setSegment": self.setSegment, "clear": self.clear, } self.running_anim = None self.statusLED = 5 uasyncio.run(self.startupAnimation())
async def main(duration): print("Flash LED's for {} seconds".format(duration)) leds = [Pin(12, 1), Pin(2, 1)] # Initialise 2 on board LED's for x, led in enumerate(leds): # Create a task for each LED t = int((0.2 + x / 2) * 1000) asyncio.create_task(toggle(leds[x], t)) asyncio.run(killer(duration))
def test(master=True): lcd = LCD(PINLIST, cols = 24) try: asyncio.run(run_master(lcd) if master else slave()) except KeyboardInterrupt: print('Interrupted') finally: asyncio.new_event_loop()
def demo(): test0() import logging logging._level = logging.DEBUG try: asyncio.run(test1()) finally: asyncio.new_event_loop()
def test(): try: asyncio.run(main()) except KeyboardInterrupt: print('Interrupted') finally: asyncio.new_event_loop() print('as_demos.auart.test() to run again.')
def test(duration=10): try: asyncio.run(main(duration)) except KeyboardInterrupt: print('Interrupted') finally: asyncio.new_event_loop() print('as_demos.aledflash.test() to run again.')
def queue_test(): printexp('''Running (runtime = 3s): Running foo() Waiting for slow process. Putting result onto queue I've seen starships burn off the shoulder of Orion... Time to die... ''', 3) asyncio.run(queue_go(3))
def main(): do_connect() timer = RelayTimer() try: uasyncio.run(timer.main()) except (Exception, KeyboardInterrupt) as e: timer.all_off() led.on() # OFF usys.print_exception(e)
def test(): print('Running encoder test. Press ctrl-c to teminate.') enc = Encoder(px, py, v=0, vmin=0, vmax=100, callback=cb) try: asyncio.run(main()) except KeyboardInterrupt: print('Interrupted') finally: asyncio.new_event_loop()
async def main(duration): print("Flash LED's for {} seconds".format(duration)) leds = [Pin(x) for x in [2, 13]] # Initialise three on board LED's asyncio.create_task(stats()) for x, led in enumerate(leds): # Create a task for each LED t = int((0.2 + x / 2) * 1000) led.init(Pin.OUT) asyncio.create_task(toggle(leds[x], t)) asyncio.run(killer(duration))
def test(): try: asyncio.run(adctest()) except KeyboardInterrupt: print('Interrupted') finally: asyncio.new_event_loop() print() print(st)
def run(): try: dns() httpServer() service = sensorservice.run() WSServer(callback=service.callback).run() uasyncio.run(blinker.blink()) except Exception as err: logger.error(err) raise err
def barrier_test(): printexp('''0 0 0 Synch 1 1 1 Synch 2 2 2 Synch 3 3 3 Synch 4 4 4 Synch ''') barrier = Barrier(3, callback, ('Synch', )) for _ in range(3): asyncio.create_task(report(barrier)) asyncio.run(killer(2))
def enter(self, event, fsm): global error, setpoint, temp, sleep_time, p, i, d, duty_min, duty_max, is_setpoint_flag, cancel_sw, show_task, pro_task print("sousvide begin heating") while True: #process() #show_temp() if ((float(setpoint) - float(temp)) < 0.1): is_setpoint_flag = 1 #cancel_sw.close_func(pressbreak) show_task = asyncio.run(show_temp()) pro_task = asyncio.run(process())
def looprun(): #try子句先执行, try: asyncio.run(killer()) #执行时是否出现异常。 except KeyboardInterrupt: print('Interrupted') ##退出try时总会执行 finally: asyncio.new_event_loop() print('loop runing')
def main(): #init ializing transactions dir if it does not already exist initTxnDir() if TESTING: #if testing, clean the dev board at each restart of board cleanP2tstDir() #initializes gui object and the 'main menu' gui = GUI() gui.screenMainMenu() uasyncio.run(loop())
def __init__(self, sensor_ctrl: SensorController, animation_ctrl: AnimationController): self._controller_sensor = sensor_ctrl self._controller_animation = animation_ctrl self.is_enabled = False self._animation_params = "" self.addr = socket.getaddrinfo(self.HOST, self.PORT)[0][-1] self.socket = None self.state = dict() asyncio.run(self.start())
def run(): clients = {'rx', 'tx'} # Expected clients apps = [App(name) for name in clients] # Accept 2 clients try: asyncio.run( server.run(clients, verbose=True, port=PORT, timeout=TIMEOUT)) except KeyboardInterrupt: print('Interrupted') finally: print('Closing sockets') server.Connection.close_all() asyncio.new_event_loop()
def run(): try: log.info('micropython p1 meter is starting...') fb.clear() asyncio.run(main(glb_mqtt_client)) finally: # status fb.clear(fb.RED) log.info("Clear async loop retained state") asyncio.new_event_loop() # Clear retained state reboot(10)
def barrier_test(): printexp( '''Running (runtime = 3s): 0 0 0 Synch 1 1 1 Synch 2 2 2 Synch 3 3 3 Synch 4 4 4 Synch 1 1 1 Synch 2 2 2 Synch 3 3 3 Synch 4 4 4 Synch ''', 3) asyncio.run(do_barrier_test())
def barrier_test1(): printexp( '''Running (runtime = 5s): report instance 0 waiting report instance 1 waiting report instance 2 waiting report instance 2 done report instance 1 done report instance 0 done my_coro running my_coro was cancelled. Exact report instance done sequence may vary, but 3 instances should report done before my_coro runs. ''', 5) asyncio.run(bart())
def request_raw(method, url, data=None, timeout=None): try: proto, dummy, host, path = url.split("/", 3) except ValueError: proto, dummy, host = url.split("/", 2) path = "" if proto != "http:": raise ValueError("Unsupported protocol: " + proto) try: host, port = host.split(":", 2) port = int(port) except ValueError: port = 80 if timeout: reader, writer = yield from asyncio.wait_for( asyncio.open_connection(host, port), timeout) else: reader, writer = yield from asyncio.run( asyncio.open_connection(host, port)) # Use protocol 1.0, because 1.1 always allows to use chunked transfer-encoding # But explicitly set Connection: close, even though this should be default for 1.0, # because some servers misbehave w/o it. content_length = '' if data is not None: content_length = "content-length: %i\r\n" % (len(data)) query = "%s /%s HTTP/1.0\r\nHost: %s:%i\r\n%sConnection: close\r\nUser-Agent: compat\r\n\r\n" % ( method, path, host, port, content_length) yield from writer.awrite(query.encode('latin-1')) if data: yield from writer.awrite(data) return reader
def __init__(self, host, port): self.host = host self.port = port self.loop = '' self.conncount = 0 self.funcs = { 'stop' : self.exit_server, 'quit' : self.quit, 'connect': self.perm_connect, 'upload': self.handle_upload, 'reset' : self.reset } print('Opening server on port {}'.format(port)) self.connections = {} self.duty_led = 800 run(self.mainrun(self.host, self.port))