async def main(): t1 = asyncio.create_task(task(1, 4, 100)) t2 = asyncio.create_task(task(2, 2, 250)) # test scheduling tasks, and calling sleep_ms micropython.heap_lock() print("start") await asyncio.sleep_ms(5) print("sleep") await asyncio.sleep_ms(350) print("finish") micropython.heap_unlock() # test writing to a stream, when the underlying stream is blocked s = asyncio.StreamWriter(TestStream(True), None) micropython.heap_lock() s.write(b"12") micropython.heap_unlock() # test writing to a stream, when the underlying stream is not blocked buf = bytearray(b"56") s = asyncio.StreamWriter(TestStream(False), None) micropython.heap_lock() s.write(b"34") s.write(buf) micropython.heap_unlock()
async def main(): sw1 = asyncio.StreamWriter(UART(1, 9600), {}) sw2 = asyncio.StreamWriter(UART( 1, 1200), {}) # ESP32S2 UART(0) is disabled (dedicated to REPL) barrier = Barrier(3) for n, sw in enumerate((sw1, sw2)): asyncio.create_task(sender(barrier, sw, n + 1)) await provider(barrier)
async def sender(): print("resetting") reset_pin.value(0) await asyncio.sleep(1) reset_pin.value(1) await asyncio.sleep(5) sreader = asyncio.StreamReader(uart) swriter = asyncio.StreamWriter(uart, {}) for cmd in cmds: print("sending %s" % cmd["send"]) await swriter.awrite(cmd['send'] + '\n') for line in cmd['expect'].insert(0, ): while True: await asyncio.sleep(1) print("waiting for %s" % line) res = await sreader.readline() # skip empty lines / unsolicited output if res == b"\r\n" or res == b'Call Ready\r\n' or res == b'+CPIN: READY\r\n' or res == b'SMS Ready\r\n': print("garbage line %s" % res) continue #TODO: regex... if res != line + b"\r\n": print('Error: Recieved % s, expected %s' % (res, line)) # throw error else: print("Success, received", res) # dispatch result break print("command %s excecuted successfully" % cmd["send"].replace('\r', '').replace("\n", '')) print("all commands executed successfully")
async def transmit(): # unreliable datagram protocol ("simplex") sock = usocket.socket(usocket.AF_INET, usocket.SOCK_DGRAM) # this should not get called using udp (no disconnections) but let's have it anyway def close(): # byebye sock.close() log.error('server disconnected') log.info('socket to {} on port {}'.format(host, port)) try: # get ipaddress serv = usocket.getaddrinfo(host, port)[0][-1] # open socket sock.connect(serv) except OSError as e: # tolerate exception and keep on going (wifi will reconnect asynchronously) log.error(e) return # identify ourselves uniquely import ubinascii # unique client id MACHINE_UID = ubinascii.hexlify(machine.unique_id()).decode('utf-8') log.debug('machine uid {}'.format(MACHINE_UID)) # attach writer and socket swriter = asyncio.StreamWriter(sock, {}) # sort of protocol header - we say hi telling our name and number ;) await swriter.awrite('\n' + ujson.dumps({ 'uid': MACHINE_UID, 'ver': VERSION })) # we need to be quick now # TODO: try without the catch (latency is a biatch) while True: try: # encode and send the actual payload on the (invisible) wire await swriter.awrite( ujson.dumps({ 't': utime.ticks_us(), 'c': imu.temperature, 'a': imu.acceleration, 'g': imu.gyro, 'm': imu.magnetic, 'f': { 'y': fuse.heading, 'p': fuse.pitch, 'r': fuse.roll } })) except Exception as e: # tolerate exception and keep on going (it's udp anyway) # TODO: this might flood out - remove when robustnes is proven log.error(e) return await asyncio.sleep_ms(20)
def __init__(self, uart_no=1): self.uart = UART(uart_no, baudrate=9600, rx=12, tx=13, timeout=10) self.loop = asyncio.get_event_loop() self.swriter = asyncio.StreamWriter(self.uart, {}) self.sreader = asyncio.StreamReader(self.uart) loop = asyncio.get_event_loop() loop.create_task(self._run())
async def run_client(self, c_sock, c_addr): self.socks.append(c_sock) c_sock.setblocking(False) sreader = asyncio.StreamReader(c_sock) swriter = asyncio.StreamWriter(c_sock, {'addr': c_addr}) self.swriters.append(swriter) print('Client connected', c_addr) await swriter.awrite(bytes([255, 252, 34])) await swriter.awrite(bytes([255, 251, 1])) await swriter.awrite(bytes(self.MSG_WELCOME, "utf8")) try: while True: data = await sreader.read() if data == b'': # connection closed by client raise OSError if b'\xFF' in data: # eat telnet command sequences continue if data == b'\r\x00': data = b'\r\n' print('Data', c_addr, data) #await swriter.awrite(res) # Echo back await self.broadcast(data) except OSError: pass print('Client disconnect', c_addr) c_sock.close() self.socks.remove(c_sock) self.swriters.remove(swriter)
async def _tcp_server(self, host, port, backlog): """TCP Server implementation. Opens socket for accepting connection and creates task for every new accepted connection """ addr = socket.getaddrinfo(host, port, 0, socket.SOCK_STREAM)[0][-1] sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.setblocking(False) sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) sock.bind(addr) sock.listen(backlog) try: while True: yield asyncio.IORead(sock) csock, caddr = sock.accept() csock.setblocking(False) # Start handler / keep it in the map - to be able to # shutdown gracefully - by close all connections self.processed_connections += 1 hid = id(csock) handler = self._handler(asyncio.StreamReader(csock), asyncio.StreamWriter(csock, {})) self.conns[hid] = handler self.loop.create_task(handler) # In case of max concurrency reached - temporary pause server: # 1. backlog must be greater than max_concurrency, otherwise # client will got "Connection Reset" # 2. Server task will be resumed whenever one active connection finished if len(self.conns) == self.max_concurrency: # Pause yield False except asyncio.CancelledError: return finally: sock.close()
async def run(): # Optional fast heartbeat to confirm nonblocking operation asyncio.create_task(heartbeat(100)) sock = socket.socket() def close(): sock.close() print('Server disconnect.') try: serv = socket.getaddrinfo(server, port)[0][-1] sock.connect(serv) except OSError as e: print('Cannot connect to {} on port {}'.format(server, port)) sock.close() return while True: sreader = asyncio.StreamReader(sock) swriter = asyncio.StreamWriter(sock, {}) data = ['value', 1] while True: try: swriter.write('{}\n'.format(ujson.dumps(data))) await swriter.drain() res = await sreader.readline() except OSError: close() return try: print('Received', ujson.loads(res)) except ValueError: close() return await asyncio.sleep(2) data[1] += 1
def __init__(self, uart_no=4): self.uart = UART(2, baudrate=9600, rx=16, tx=17) self.loop = asyncio.get_event_loop() self.swriter = asyncio.StreamWriter(self.uart, {}) self.sreader = asyncio.StreamReader(self.uart) loop = asyncio.get_event_loop() loop.create_task(self._run())
async def gps_test(): global gps, uart # For shutdown print('Initialising') # Adapt UART instantiation for other MicroPython hardware uart = pyb.UART(4, 9600, read_buf_len=200) # read_buf_len is precautionary: code runs reliably without it. sreader = asyncio.StreamReader(uart) swriter = asyncio.StreamWriter(uart, {}) timer = aswitch.Delay_ms(cb_timeout) sentence_count = 0 gps = as_rwGPS.GPS(sreader, swriter, local_offset=1, fix_cb=callback, fix_cb_args=(timer,), msg_cb = message_cb) await asyncio.sleep(2) await gps.command(as_rwGPS.DEFAULT_SENTENCES) print('Set sentence frequencies to default') #await gps.command(as_rwGPS.FULL_COLD_START) #print('Performed FULL_COLD_START') print('awaiting first fix') loop = asyncio.get_event_loop() loop.create_task(sat_test(gps)) loop.create_task(stats(gps)) loop.create_task(navigation(gps)) loop.create_task(course(gps)) loop.create_task(date(gps)) await gps.data_received(True, True, True, True) # all messages loop.create_task(change_status(gps, uart))
def main(): LED_PIN = config.CONFIG.get('led_pin', 13) pin = Pin(LED_PIN, Pin.OUT) pin.value(0) # Attempt to connect to Wifi network. wlan = wifimgr.get_connection() # Bind to UART 2 to handle RPC requests. uart = UART(2, baudrate=115200) uart_awriter = asyncio.StreamWriter(uart, {}) uart_areader = asyncio.StreamReader(uart) # Bind I2C connection for controlling motor drivers i2c_config = config.CONFIG.get('i2c', {}) i2c = I2C(scl=Pin(i2c_config.get('scl', 22)), sda=Pin(i2c_config.get('sda', 23)), freq=i2c_config.get('freq', 10000)) motor_ctrl = motor.GroveMotorControl(i2c) # Expose globals to RPC context context = globals().copy() # Expose locals to RPC context ([note MicroPython `locals()` caveat][1]) # # [1]: https://github.com/micropython/micropython/wiki/Differences#differences-by-design context.update(locals()) # Explicitly add local variables to context, since (see [here][1]): # # > MicroPython optimizes local variable handling and does not record or # > provide any introspection info for them, e.g. **locals() doesn't have # > entries for locals.** # # [1]: https://github.com/micropython/micropython/wiki/Differences#differences-by-design context['i2c'] = i2c context['motor_ctrl'] = motor_ctrl context['uart'] = uart context['wlan'] = wlan # Remove `rpc` module from context to avoid recursive reference in # `rpc.rpc()` function. rpc = context.pop('rpc', None) # Reclaim memory associated with any temporary allocations. gc.collect() loop = asyncio.get_event_loop() pin = Pin(LED_PIN, Pin.OUT) pin.value(1) # Start RPC task. loop.run_until_complete( rpc.rpc(uart_areader, uart_awriter, context=context)) pin.value(0) # Reclaim memory associated with any temporary allocations. gc.collect()
def __init__(self, uart_no = 4): self.uart = UART(uart_no, 9600) self.loop = asyncio.get_event_loop() self.swriter = asyncio.StreamWriter(self.uart, {}) self.sreader = asyncio.StreamReader(self.uart) loop = asyncio.get_event_loop() loop.create_task(self._run())
def __init__(self): DEVICE.__init__(self) self.sreader = asyncio.StreamReader(self.uart) self.swriter = asyncio.StreamWriter(self.uart, {}) self.data = b'' self.prompt_timeout = self.config['Ctd']['Prompt_Timeout'] self.warmup_interval = self.config['Warmup_Interval']
async def sender(): swriter = asyncio.StreamWriter(chan, {}) txdata = [0, 0] while True: await swriter.awrite(''.join((ujson.dumps(txdata), '\n'))) txdata[1] += 1 await asyncio.sleep_ms(1500)
def __init__(self, uart_no = 2, timeout=4000,rx=35,tx=21): self.uart = UART(2,baudrate=9600,rx=rx,tx=tx) self.timeout = timeout self.loop = asyncio.get_event_loop() self.swriter = asyncio.StreamWriter(self.uart, {}) self.sreader = asyncio.StreamReader(self.uart) self.delay = aswitch.Delay_ms() self.response = []
def _ensure_socket_connected(self) -> None: if self.command_socket is None: command_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) command_socket.settimeout(self.CONNECT_TIMEOUT) command_socket.connect((self.host, self.port)) command_socket.setblocking(0) self.command_socket = command_socket self.async_command_socket = uasyncio.StreamWriter(command_socket)
def __init__(self, uart_no=2, timeout=4000): self.uart = UART(uart_no, 9600) self.timeout = timeout self.swriter = asyncio.StreamWriter(self.uart, {}) self.sreader = asyncio.StreamReader(self.uart) self.delay = Delay_ms() self.response = [] asyncio.create_task(self._recv())
async def sender(): swriter = asyncio.StreamWriter(myiow, {}) count = 0 while True: count += 1 tosend = 'Wrote Hello MyIO {}\n'.format(count) await swriter.awrite(tosend.encode('UTF8')) await asyncio.sleep(2)
async def run_client(self, sock, cid, poller): self.socks.append(sock) sreader = asyncio.StreamReader(sock) swriter = asyncio.StreamWriter(sock, {}) print('Got connection from client', cid) try: is_get_request = True content_length = 0 print('Received from client {}'.format(cid)) while True: res = await sreader.readline() if res == b'': raise OSError print('{}'.format(res)) if 'POST' in res: is_get_request = False if 'Content-Length' in res: utf8Res = res.decode('UTF-8') content_length = int(utf8Res.split(':')[1]) if not res or res == b'\r\n': if not is_get_request: res_body = await sreader.read(content_length) body_dict = json.loads(res_body) for key in body_dict.keys(): set_value(key, body_dict.get(key)) break response = "" if is_get_request: hex_color = manager.led_color_hex hex_bg_color = manager.background_color_hex led_amount = manager.led_amount led_bits = manager.led_bits isxchecked = [''] * 6 isxchecked[manager.program_number - 1] = 'checked' response = html.format(\ color=hex_color, \ is1checked=isxchecked[0], \ is2checked=isxchecked[1], \ is3checked=isxchecked[2], \ is4checked=isxchecked[3], \ is5checked=isxchecked[4], \ is6checked=isxchecked[5], \ delay=manager.delay, \ background_color=hex_bg_color, \ led_amount = led_amount, \ led_bits = led_bits, \ delta_time = manager.delta_time \ ) else: response = "HTTP/1.1 204 No Content\n\r\n" await swriter.awrite(response) print('Client {} disconnect.'.format(cid)) sock.close() self.socks.remove(sock) poller.unregister(sock) except OSError: pass gc.collect()
def __init__(self): DEVICE.__init__(self) self.sreader = asyncio.StreamReader(self.uart) self.swriter = asyncio.StreamWriter(self.uart, {}) self.data = b'' self.warmup_interval = self.config['Warmup_Interval'] self.data_length = self.config['Data_Length'] self.string_label = self.config['String_Label'] self.records = 0
async def setup(): print('Initialising') uart = pyb.UART(4, 9600) sreader = asyncio.StreamReader(uart) swriter = asyncio.StreamWriter(uart, {}) gps = as_rwGPS.GPS(sreader, swriter, local_offset=1) await asyncio.sleep(2) await gps.baudrate(BAUDRATE) uart.init(BAUDRATE)
def __init__(self): DEVICE.__init__(self) self.sreader = asyncio.StreamReader(self.uart) self.swriter = asyncio.StreamWriter(self.uart, {}) self.data = b'' self.warmup_interval = self.config['Warmup_Interval'] self.fix = None self.fixed = timesync self.displacement = 0
def __init__(self): DEVICE.__init__(self) self.sreader = asyncio.StreamReader(self.uart) self.swriter = asyncio.StreamWriter(self.uart, {}) self.data = b'' self.break_timeout = self.config['Adcp']['Break_Timeout'] self.instrument_config = self.config['Adcp']['Instrument_Config'] self.deployment_config = self.config['Adcp']['Deployment_Config'] self.deployment_delay = self.config['Adcp']['Deployment_Delay']
async def receiver(self): sreader = asyncio.StreamReader(self.uart6) swriter = asyncio.StreamWriter(self.uart6, {}) while True: res = await sreader.read(16) print("recievd") m = Message(buf=res) print(m.buff) print(m.CRC) print(m.isOkay()) if m.isOkay(): print("is Okay") if m.comm_type == REQT_ACCELE: fsize = os.stat('PyBoard/record.dat')[6] print("reqt_accel") print(fsize) tm = Message(CONFI, REQT_ACCELE, fsize) await swriter.awrite(tm.buff) f = open('PyBoard/record.dat', 'rb') s = int(ceil(fsize / 4096)) for i in range(0, s): print(i) # pyb.delay(200) m = f.read(4096) await swriter.awrite(m) f.close() print("done") elif m.comm_type == REQT_WEIGHT: print("REQT_WEIGHT") weight = 1.0 self.queue.put_nowait(self.count3) print("s=" + str(self.queue.qsize())) tm = Message(CONFI, REQT_WEIGHT, weight) elif m.comm_type == START_ACCELE_REC: print("START_ACCEL_REC") rcd = open("PyBoard/record.dat", "w") lp = True while lp: tup = self.acc.readAccel() print(tup) rcd.write( str(tup[0]) + "," + str(tup[1]) + "," + str(tup[2]) + "\n") if self.uart6.any() != 0: res = await sreader.read(16) m = Message(buf=res) if m.isOkay( ) and m.mssg_type == COMM and m.comm_type == STOP_ACCELE_REC: lp = False tm = Message(CONFI, STOP_ACCELE_REC, 0) await swriter.awrite(tm.buff) print("stoped") rcd.close()
async def sender(): swriter = asyncio.StreamWriter(chan, {}) txdata = [0, 0] await swriter.awrite(''.join((ujson.dumps('this is a test 1'), '\n'))) await swriter.awrite(''.join((ujson.dumps('this is a test 2'), '\n'))) await swriter.awrite(''.join((ujson.dumps('this is a test 3'), '\n'))) while True: await swriter.awrite(''.join((ujson.dumps(txdata), '\n'))) txdata[0] += 1 await asyncio.sleep_ms(800)
def __init__(self, verbose): self.verbose = verbose self.cl = None # Client instance for server comms. # Instantiate a Pyboard Channel i2c = I2C(scl=Pin(0), sda=Pin(2)) # software I2C syn = Pin(5) ack = Pin(4) self.chan = asi2c.Responder(i2c, syn, ack) # Channel to Pyboard self.sreader = asyncio.StreamReader(self.chan) self.swriter = asyncio.StreamWriter(self.chan, {})
async def sender(device): ds = [0, 0] # Data object for transmission swriter = asyncio.StreamWriter(device, {}) while True: s = ''.join((ujson.dumps(ds), '\n')) swriter.write(s.encode()) # convert to bytes await swriter.drain() await asyncio.sleep(2) ds[0] += 1 # Record number ds[1] = device.t_last_ms()
def __init__(self, uart_no=2, timeout=4000): self.uart = UART(1, baudrate=9600, rx=12, tx=13) self.timeout = timeout self.loop = asyncio.get_event_loop() self.swriter = asyncio.StreamWriter(self.uart, {}) self.sreader = asyncio.StreamReader(self.uart) self.delay = aswitch.Delay_ms() self.response = [] loop = asyncio.get_event_loop() loop.create_task(self._recv())
async def sender(): swriter = asyncio.StreamWriter(myio, {}) await asyncio.sleep(5) count = 0 while True: count += 1 tosend = 'Wrote Hello MyIO {}\n'.format(count) await swriter.awrite(tosend.encode('UTF8')) # Once this has occurred reading stops. ioctl keeps being called with arg == 0 # which normally occurs once only after a read # IOWriteDone is never yielded: is this right? await asyncio.sleep(2)
async def sender(myiow): swriter = asyncio.StreamWriter(myiow, {}) await asyncio.sleep(1) count = 0 try: # Trap in outermost scope to catch cancellation of .sleep while True: count += 1 tosend = 'Wrote Hello MyIO {}\n'.format(count) await swriter.awrite(tosend.encode('UTF8')) await asyncio.sleep(2) except asyncio.CancelledError: print('Sender cancelled')