def __init__(self, adc): self._adc = adc self._lower = 0 self._upper = 65535 self._pol = True self._last = None self._sreader = asyncio.StreamReader(self)
def __init__(self, uart, lock, event=None): self._uart = uart # accepts a uart object self._sreader = asyncio.StreamReader(uart) self._lock = lock self._event = event self._timestamp = None self._invalidateMeasurements()
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)
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 receiver(device): global missed msg = 'Missed record count: {:3d} (local) {:3d} (remote).' tmsg = 'Uptime: {:7.2f}hrs Outages: {:3d}' smsg = '{} statistics. Timeouts: RX {} TX {} Received packets: All {} Non-duplicate data {}' sreader = asyncio.StreamReader(device) x = 0 last = None # Record no. of last received data while True: res = await sreader.readline() # Can return b'' if res: green.toggle() try: dat = ujson.loads(res) except ValueError: # Extremely rare case of data corruption. See docs. print('JSON error', res) else: print('Received record no: {:5d} text: {:s}'.format( dat[0], dat[3])) if last is not None and (last + 1) != dat[0]: missed += 1 last = dat[0] x += 1 x %= 20 if not x: print(msg.format(missed, dat[1])) print(tmsg.format((time.time() - tstart) / 3600, outages)) if isinstance(dat[2], list): print(smsg.format('Remote', *dat[2])) local_stats = device.stats() if isinstance(local_stats, list): print(smsg.format('Local', *local_stats))
def WSReader(reader, writer): webkey = None while 1: line = yield from reader.readline() print(line) if not line: raise ValueError() if line == b"\r\n": break if line.startswith(b'Sec-WebSocket-Key'): webkey = line.split(b":", 1)[1] webkey = webkey.strip() if not webkey: raise ValueError("Not a websocker request") respkey = make_respkey(webkey) await writer.awrite(b"""\ HTTP/1.1 101 Switching Protocols\r Upgrade: websocket\r Connection: Upgrade\r Sec-WebSocket-Accept: """) await writer.awrite(respkey) # This will lead to "<key>\n\r\n" being written. Not exactly # "\r\n\r\n", but browsers seem to eat it. await writer.awrite("\r\n") # await writer.awrite("\r\n\r\n") print("Finished websocket handshake") ws = websocket.websocket(reader.ios) print("uasyncio.StreamReader(reader.ios, ws)") rws = uasyncio.StreamReader(reader.ios, ws) return rws
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())
def __init__(self, uart, lock, set_pin=None, reset_pin=None, interval_passive_mode=None, event=None, active_mode=True, eco_mode=True, assume_sleeping=True): self._uart = uart # accepts a uart object self._set_pin = set_pin if set_pin is not None: set_pin.value(1) self._reset_pin = reset_pin if reset_pin is not None: reset_pin.value(1) self._active = True self._active_mode = active_mode # passive mode will be set on first wakeUp() in _read() self._eco_mode = eco_mode # only works with passive mode as sleep is not possible in active_mode self._sreader = asyncio.StreamReader(uart) self._interval_passive_mode = interval_passive_mode or 60 # in case someone forgets to set it if self._eco_mode and self._active_mode is False and self._interval_passive_mode < WAIT_AFTER_WAKEUP + 5: self._error( "interval_passive_mode can't be less than DEVICE_WAKEUP_TIME of {!s}s".format(WAIT_AFTER_WAKEUP + 5)) self._interval_passive_mode = 60 self._event = event self._lock = lock self._timestamp = None self._sleeping_state = assume_sleeping # assume sleeping on start by default self._invalidateMeasurements() self._callback = None # can be a short coroutine too; no args given asyncio.get_event_loop().create_task(self._read())
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()
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))
async def log_kml(fn='/sd/log.kml', interval=10): yellow.on() # Waiting for data uart = pyb.UART(4, 9600, read_buf_len=200) # Data on X2 sreader = asyncio.StreamReader(uart) gps = as_GPS.AS_GPS(sreader, fix_cb=toggle_led) await gps.data_received(True, True, True, True) yellow.off() with open(fn, 'w') as f: f.write(str_start) while not sw.value(): f.write(gps.longitude_string(as_GPS.KML)) f.write(',') f.write(gps.latitude_string(as_GPS.KML)) f.write(',') f.write(str(gps.altitude)) f.write('\r\n') blue.toggle() for _ in range(interval * 10): await asyncio.sleep_ms(100) if sw.value(): break f.write(str_end) red.off() green.on()
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())
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 _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 poller(stream): sreader = asyncio.StreamReader(stream) i = 0 while True: await scheduling.wait() #and await disconnect.wait() b = await sreader.read(1) if b: try: b.decode('utf-8') except UnicodeError: await asyncio.sleep(0) continue if (b == dfl.ESC_CHAR.encode() and stream.__class__.__name__ == 'UART' and not session.logging): i += 1 if i > 2: asyncio.create_task(session.login(m, stream)) session.logging = True elif (b == b'\x1b' and (stream.__class__.__name__ == 'UART' and session.loggedin or stream.__class__.__name__ == 'USB_VCP') and not menu.interactive): asyncio.create_task(menu.main(m, stream, devs)) m.set(b) # Passes ESC to menu. menu.interactive = True else: m.set(b) i = 0 await asyncio.sleep_ms(100)
def WSReader(reader, writer): webkey = None while 1: l = yield from reader.readline() #print(l) if not l: raise ValueError() if l == b"\r\n": break if l.startswith(b'Sec-WebSocket-Key'): webkey = l.split(b":", 1)[1] webkey = webkey.strip() if not webkey: raise ValueError("Not a websocker request") respkey = make_respkey(webkey) await writer.awrite(b"""\ HTTP/1.1 101 Switching Protocols\r Upgrade: websocket\r Connection: Upgrade\r Sec-WebSocket-Accept: """) await writer.awrite(respkey) await writer.awrite("\r\n\r\n") #print("Finished webrepl handshake") ws = websocket.websocket(reader.ios) rws = uasyncio.StreamReader(reader.ios, ws) return rws
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")
def __init__(self, pin_nr): self._uart = UART(2, 115200, rx=pin_nr) self._uart.init(txbuf=1024, rxbuf=1024, timeout=11, timeout_char=11) self._sreader = asyncio.StreamReader(self._uart) self._request_url = "https://api.cliffords.nu" self._wlan = network.WLAN(network.STA_IF) #self._wdt = WDT(timeout=20000) self._id = 0
async def receiver(): sreader = asyncio.StreamReader(uart) while True: nmea = await sreader.readline() #print('Recieved', nmea.rstrip().decode("utf-8")) if nmea.startswith('$GPRMC'): dic = {nmea[:7]: nmea.rstrip().decode('utf-8')} print(dic)
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 receiver(myior): sreader = asyncio.StreamReader(myior) try: while True: res = await sreader.readline() print('Received', res) except asyncio.CancelledError: print('Receiver cancelled')
async def receiver(myior): sreader = asyncio.StreamReader(myior) try: while True: res = await sreader.readline() print('Received', res) except asyncio.TimeoutError: print('Receiver timeout')
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 = []
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 receiver(): ureader = asyncio.StreamReader(s) frame = Frame() while True: res = await ureader.read(1) if res is not None: # pass # print(hexlify(res)) frame.append(res)
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)
async def receiver(): sreader = asyncio.StreamReader(chan) for _ in range(5): # Test flow control res = await sreader.readline() print('Received', ujson.loads(res)) await asyncio.sleep(4) while True: res = await sreader.readline() print('Received', ujson.loads(res))
async def receiver(): global done with open('test_io_starve.py', 'rb') as f: sreader = asyncio.StreamReader(f) while True: await asyncio.sleep(0.1) res = await sreader.readline() # Didn't get there with the original problem this test shows done = True