def run(self): # select call used cause time.sleep loads CPU up to 100% with small polling time select.select([], [], [], WAIT_SEC) timers_intervals = [curr_timer.run() for curr_timer in Timer.timers.values() if not curr_timer.stopped] if not timers_intervals and self.no_timers_err: raise TimerError('Running timers not found') return timers_intervals
def _pass_through(self, device): """Forwards device uart to board uart. Params: device(obj) """ device.init_uart() tx = "" while True: if not self.board.interactive: device.deinit_uart() return False r, w, x = uselect.select( [self.board.usb, self.board.uart, device.uart], [], [], 0) for _ in r: if _ == self.board.usb or _ == self.board.uart: byte = ord(_.read(1)) if byte == 8: # [BACKSPACE] Backs to previous menu. device.deinit_uart() return True elif byte == 13: # [CR] Forwards cmds to device. tx += chr(byte) device.uart.write(tx) tx = "" else: tx += chr(byte) print(chr(byte), end="") elif _ == device.uart: print("{}".format(chr(_.readchar())), end="") """r, w, x = uselect.select(self.board.input, [], [], 0)
def set_mode(self, timeout): """ Prints out welcome message. """ print("##################################################\r\n" + "# #\r\n" + "# WELCOME TO PYBUOYCONTROLLER V1.1 #\r\n" + "# #\r\n" + "##################################################\r\n" + "[ESC] INTERACTIVE MODE\r\n" + "[DEL] FILE TRANSFER MODE") t0 = utime.time() while True: t1 = utime.time() - t0 if t1 > timeout: break print("ENTER YOUR CHOICE WITHIN {} SECS".format(timeout - t1), end="\r") r, w, x = uselect.select(self.input, [], [], 0) if r: byte = r[0].read(1) if byte == b"\x1b": # ESC self.interactive = True print("") return True elif byte == b"\x1b[3~": # DEL self.connected = True print("") return True print("") return False
def handle_connections(self, timeout=1): if not self._sock: raise Exception("Tried to access a None Socket.") readables, writeables, exceptionals = select.select( self._inputs, [], self._inputs, timeout) for readable in readables: if readable is self._sock: # The server is able to accept a remote connection print("Accepting new connection...") remote, addr = readable.accept() remote.setblocking(True) self._inputs.append(remote) stomp_connection = STOMPConnection(remote) self._connections[id(remote)] = stomp_connection print("Client connection established: {}".format(addr)) else: # The client has sent data stomp_connection = self._connections[id(readable)] stomp_connection.recv() stomp_connection.handle_frames() if stomp_connection.isclosed(): self._inputs.remove(readable) readable.close() del self._connections[id(readable)] for writable in writeables: print("writable: {}".format(writable)) for exceptional in exceptionals: print("exceptional: {}".format(exceptional)) exceptional.close() self._inputs.remove(exceptional)
def handle_question(self, q, answer_callback, fast=False, retry_count=3): collect() p = bytearray(len(q) + 12) pack_into("!HHHHHH", p, 0, 1, 0, 1, 0, 0, 0, 0) p[12:] = q self._pending_question = q self._answer_callback = answer_callback self.answered = False try: for i in range(retry_count): if self.answered: break self.sock.sendto(p, (MDNS_ADDR, MDNS_PORT)) timeout = ticks_ms() + (250 if fast else 1000) while not self.answered: sel_time = ticks_diff(timeout, ticks_ms()) if sel_time <= 0: break (rr, _, _) = select([self.sock], [], [], sel_time / 1000.0) if rr: self.process_waiting_packets() finally: self._pending_question = None self._answer_callback = None
def monitorWiFi(): sta = network.WLAN(network.STA_IF) sta.active(False) sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) sock.bind(("127.0.0.1", 20001)) packet = wifi.packet() count = 0 channel = 1 lasttime = time.ticks_ms() print("Starting sniffer....") sta.sniffer(ch=channel) in_socks = [sock] while (True): tt = time.ticks_ms() ts = int(tt) - int(lasttime) if int(ts) >= int(1000): print(channel,count) channel = ((channel + 1) % 15) if channel == 0: channel = 1 sta.set_channel(channel) count = 0 lasttime = time.ticks_ms() inputready, outputready, exceptready = uselect.select(in_socks, [], [], 1) for temp in inputready: count = count + 1 temp_packet = temp.recv(4096)
def serve(self): readable, _, _ = uselect.select(self.sock_list, [], [], 0.001) for s in readable: if s is self.sock: client_socket, address = self.sock.accept() self.sock_list.append(client_socket) print("Connection from", address) else: method, target, content_length = self.parse_method(s) print("Reqeust for ", target, method) if target in self.endpoints: supported_methods = self.endpoints[target] if method in supported_methods: callback = supported_methods[method] print("Handling", method, "for endpoint", target) if method == "POST" or method == "PUT": while True: header = s.readline().decode("utf-8") if header == "" or header == "\r\n": break content = s.read(content_length).decode("utf-8") callback(s, content) else: callback(s) else: print("illegal method", method, "for endpoint", target) s.send(b'HTTP/1.0 405 Method Not Allowed' + self.headers + b'\r\n\r\n') s.close() self.sock_list.remove(s)
def flush_stdin(): key = 1 while key is not None: list = uselect.select([sys.stdin], [], [], 0.01) if list[0]: key = sys.stdin.read(1) else: key = None
def _event_select(events): """Perform a select() over all the Events provided, returning the ones ready to be fired. Only WaitableEvents (including SleepEvents) matter here; all other events are ignored (and thus postponed). """ # Gather waitables and wakeup times. waitable_to_event = {} rlist, wlist, xlist = [], [], [] earliest_wakeup = None for event in events: if isinstance(event, SleepEvent): if not earliest_wakeup: earliest_wakeup = event.wakeup_time else: earliest_wakeup = min(earliest_wakeup, event.wakeup_time) elif isinstance(event, WaitableEvent): r, w, x = event.waitables() rlist += r wlist += w xlist += x for waitable in r: waitable_to_event[('r', waitable)] = event for waitable in w: waitable_to_event[('w', waitable)] = event for waitable in x: waitable_to_event[('x', waitable)] = event # If we have a any sleeping threads, determine how long to sleep. if earliest_wakeup: timeout = max(earliest_wakeup - Time.time(), 0.0) else: timeout = None # Perform select() if we have any waitables. if rlist or wlist or xlist: rready, wready, xready = select.select(rlist, wlist, xlist, timeout) else: rready, wready, xready = (), (), () if timeout: time.sleep(timeout) # Gather ready events corresponding to the ready waitables. ready_events = set() for ready in rready: ready_events.add(waitable_to_event[('r', ready)]) for ready in wready: ready_events.add(waitable_to_event[('w', ready)]) for ready in xready: ready_events.add(waitable_to_event[('x', ready)]) # Gather any finished sleeps. for event in events: if isinstance(event, SleepEvent) and event.time_left() == 0.0: ready_events.add(event) return ready_events
def _check_activity(self, timeout): """Checks for user activity. Params: timeout(int): seconds """ while True: r, w, x = uselect.select(self.input, [], [], timeout) if not r: self.active = False return
def _getc(self, size, timeout=1): """Reads bytes from serial. Params: size(int): num of bytes timeout(int) Returns: given data or None """ r, w, e = uselect.select([self.uart], [], [], timeout) if r: return self.uart.read(size) else: return
def _putc(self, data, timeout=1): """Writes bytes to serial. Params: data(bytes) timeout(int) Returns: written data or None """ r, w, e = uselect.select([], [self.uart], [], timeout) if w: return self.uart.write(data) else: return
def server_connect(server_socket): r, _, __, = select.select((server_socket, ), (), (), 0.02) if r: for _ in r: client, client_addr = server_socket.accept() try: request_return = None print("\nConnected to client at {}".format(client_addr)) request = client.recv(4096) print(request) print() if "app.js" in request: try: with open("app.js", 'rb') as infile: response_body = infile.read() except OSError: response_body = b"alert('No JS found')" response_header = b"HTTP/1.1 200 OK\nContent-Type: application/javascript\r\n\r\n" elif "style.css" in request: try: with open("style.css", 'rb') as infile: response_body = infile.read() except OSError: response_body = b"body { background: blue; height: 100vh; width: 100vw; }" response_header = b"HTTP/1.1 200 OK\nContent-Type: text/css\r\n\r\n" elif "GET /?" in request: # response_body = b"Ok, all good." request_return = parse_request(request) response_body = return_homepage() response_header = b"HTTP/1.1 200 OK\nContent-Type: text/html\r\n\r\n" else: response_body = return_homepage() response_header = b"HTTP/1.1 200 OK\nContent-Type: text/html\r\n\r\n" # print(response_header + response_body) client.send(response_header) client.sendall(response_body) client.close() return request_return except OSError as e: print(e) else: return None
def recvfrom(self, size): if self.TIMEOUT: self.ssock.setblocking(0) ready = select.select([self.ssock], [], [], self.TIMEOUT)[0] else: self.ssock.setblocking(1) ready = True try: if ready: return self.ssock.recvfrom(size) else: return False, False except Exception as e: dbg(e) return False, False
def run_server(self): print('listening on', self.addr) while True: r, w, err = select((self.s, ), (), (), 1) if r: for readable in r: cl, addr = self.s.accept() print('received request from addr' + str(addr)) try: self.client_handler(cl) except OSError as e: print(e) pass elif err: print(err) sleep(1)
def poll(self, timeout=100): if self.use_poll: ready = self.poller.poll(timeout) else: ready = [] if len(self.targets) > 0: (rlist, wlist, xlist) = select.select(self.targets.keys(), [], [], timeout) ready = [(x, None) for x in rlist] for one_ready in ready: target = self.targets.get(one_ready[0].fileno(), None) dbg("Targets %s" % str(self.targets.keys())) if target: #dbg("get socket with fileno: %s" % str(one_ready[0].fileno()) + " len: %s" % len(one_ready) + " selected: %s " % str(target.fileno()) ) # update time target.do_read(one_ready[0])
def web_app_loop(): global LED_OFF_HOUR, LED_OFF_MINUTE while True: # select for sync control input from web and btn press r, w, err = select.select((s, ), (), (), 0.1) if r: for readable in r: try: conn, addr = s.accept() print('Got a connection from %s' % str(addr)) request = conn.recv(1024) if not request: continue request = str(request) led_txt = request.split()[1] led_from = request.find('/?from=') if led_txt == '/?led=0': set_perc_pwm(0) elif led_txt == '/?led=1': set_perc_pwm(1) elif led_txt == '/?led=5': set_perc_pwm(5) elif led_txt == '/?led=50': set_perc_pwm(50) elif led_txt == '/?led=100': set_perc_pwm(100) elif led_from == 6: LED_OFF_HOUR = led_txt[led_txt.find("from") + 5:].split("%3A")[0] LED_OFF_MINUTE = led_txt[led_txt.find("from") + 5:].split("%3A")[1] response = web_page() conn.send('HTTP/1.1 200 OK\n') conn.send('Content-Type: text/html\n') conn.send('Connection: close\n\n') conn.sendall(response) conn.close() except OSError as e: pass btn_check() timer_check()
def login(self, attempts): """Prompts user for authentication. Params: attempts(int): allowed login attempts """ self.authenticating = True self.loggedin = False self.loggedout = False for i in range(attempts): rx = "" char = "" utime.sleep_ms(250) print("ENTER PASSWORD:"******"") while True: r, w, x = uselect.select(self.input, [], [], 10) if r: byte = r[0].read(1) if byte == b"\r": if rx[len(rx) - len(self.passwd):] == self.passwd: _thread.start_new_thread(self._expire, (self.timeout, )) self.loggedin = True print("") return elif i < attempts - 1: print("\n\rTRY AGAIN.") break else: print("\n\rAUTH FAILED.") break else: try: rx += chr(ord(byte)) # Discharge wrong chars. except: print("\n\rUNEXPECTED CHAR {}.".format( byte)) # DEBUG else: print("\n\rAUTH TIMEOUT.") break print("") self.loggedout = True return
def handle(self, sock, event, others): # server doesn't spawn other sockets, so only respond to its own socket if sock is not self.sock: return # check the DNS question, and respond with an answer try: self.sock.setblocking(0) ready = select.select([self.sock], [], [], 0.1) if ready[0] == False: return data, sender = sock.recvfrom(1024) request = DNSQuery(data) #print("Sending {:s} -> {:s}".format(request.domain, self.ip_addr)) sock.sendto(request.answer(self.ip_addr), sender) # help MicroPython with memory management del request gc.collect() except Exception as e: print("DNS server exception:", e)
async def ainput(prompt=""): """This method implements an asyncronous version of Python's builtin input() function. It watches the sys.stdin buffer to see if there is data available. If so, it reads it. If the character is a newline, the built string is returned. The sys.stdout.write() calls are required so that whatever application is attached to the REPL can see the characters that the user is typing. """ sys.stdout.write(prompt) input_text = "" while True: while select.select([sys.stdin], [], [], 0.01)[0]: char = sys.stdin.read(1) if char == '\n': sys.stdout.write('\n') return input_text else: sys.stdout.write(char) input_text += char await asyncio.sleep(0.01)
def process_waiting_packets(self): while True: try: readers, _, _ = select([self.sock], [], [], 0) except Exception as e: print( "> mDnsServer.process_waiting_packets error: {}".format(e)) if not readers: break buf, addr = self.sock.recvfrom(MAX_PACKET_SIZE) if buf and addr[0] != self.ip: try: self.process_packet(memoryview(buf), addr) del buf except IndexError as e: print( "> Index error processing packet; probably malformed data: {}" .format(e)) except Exception as e: print("> Error processing packet: {}".format(e))
def url_open(url): """ copied from micropython-lib - library upip """ print("url=%s" % url) proto, _, host, urlpath = url.split('/', 3) host, port = host.split(":", 2) try: s = usocket.socket() # s.bind((config.OTA["bind_ip"], 1415)) ai = usocket.getaddrinfo(host, port) print("ai = %r" % ai) print("ai[0][-1] = %s" % (ai[0][-1], )) except OSError as e: fatal("Unable to resolve %s:%s (no Internet?)" % host, port, e) try: print("set noblocking") s.setblocking(False) # poller = uselect.poll() # poller.register(s, uselect.POLLIN) try: err = s.connect(ai[0][-1]) print("after connect, err=%s" % err) except OSError as e: print("Catched OSError", e) if e.args[0] != 115: # EINPROGRESS raise print("EINPROGRESS, good") __, ssocks, __ = uselect.select( [], [s], [], 3) # wait only three seconds for connecting to repo if not ssocks: raise CheckTimeoutError("could not connect") s.setblocking(True) # MicroPython rawsocket module supports file interface directly s.write("GET /%s HTTP/1.0\r\nHost: %s\r\n\r\n" % (urlpath, host)) l = s.readline() protover, status, msg = l.split(None, 2) if status != b"200": if status == b"404" or status == b"301": raise NotFoundError("URL not found") raise ValueError(status) while 1: l = s.readline() if not l: raise ValueError("Unexpected EOF in HTTP headers") if l == b'\r\n': break except Exception as e: print("Exception in url_open", e) import sys sys.print_exception(e) s.close() raise e return s
def ping(address, repeat=5, interval=10, timeout=3000, size=64, silent=False, sock=None): host = usocket.getaddrinfo(address, 1)[0][-1][0] icmp = icmp_packet(size) sockfd = usocket.socket(usocket.AF_INET, usocket.SOCK_RAW, 1) sockfd.setblocking(0) sockfd.settimeout(timeout / 1000) sockfd.connect((host, 1)) if not silent: pinging = "PING: %s" % host print(pinging) if sock: sock.send(pinging.encode("utf-8") + b"\r\n") seqs = list(range(1, repeat + 1)) c = 1 t = 0 transmitted = 0 recieved = 0 complete = False while t < timeout: if t == interval and c <= repeat: icmp[0].checksum = 0 icmp[0].seq = c icmp[0].timestamp = utime.ticks_us() icmp[0].checksum = checksum(icmp[1]) if sockfd.send(icmp[1]) == size: transmitted += 1 t = 0 else: seqs.remove(c) c += 1 while not complete: sockets, _, _ = uselect.select([sockfd], [], [], 0) if sockets: response = sockets[0].recv(4069) rpointer = memoryview(response) rheader = uctypes.struct(uctypes.addressof(rpointer[20:]), icmp[2], uctypes.BIG_ENDIAN) seq = rheader.seq if rheader.type == 0 and rheader.id == icmp[0].id and ( seq in seqs): elapsed = (utime.ticks_us() - rheader.timestamp) / 1000 ttl = ustruct.unpack('>B', rpointer[8:9])[0] recieved += 1 if not silent: s = seq l = len(response) pong = "PONG - %d: %u bytes | ttl: %u (%f ms)" % ( s, l, ttl, elapsed) print(pong) if sock: sock.send(pong.encode("utf-8") + b"\r\n") seqs.remove(seq) if len(seqs) <= 0: complete = True else: break utime.sleep_ms(1) t += 1 sockfd.close() return recieved
parse_4 = ' '.join(parse_3) message = (" " * tile) + parse_4 message_list.insert(0, message) message_list.pop() response = html client_obj.send(response) client_obj.close() def display(s): for c in range(len(s) * 8): device.fill(0) device.text(s, -c, 0) device.show() time.sleep(0.05) while True: r, w, err = select.select((server, ), (), (), 1) if r: for readable in r: client, client_addr = server.accept() try: client_handler(client) except OSError as e: pass display(message_list[0])
def ping(host, count=4, timeout=5000, interval=10, quiet=False, size=64, rtn=True, loop=False, int_loop=800): import utime import uselect import uctypes import usocket import ustruct import urandom from sys import platform import gc from array import array # prepare packet assert size >= 16, "pkt size too small" pkt = b'Q'*size pkt_desc = { "type": uctypes.UINT8 | 0, "code": uctypes.UINT8 | 1, "checksum": uctypes.UINT16 | 2, "id": uctypes.UINT16 | 4, "seq": uctypes.INT16 | 6, "timestamp": uctypes.UINT64 | 8, } # packet header descriptor h = uctypes.struct(uctypes.addressof(pkt), pkt_desc, uctypes.BIG_ENDIAN) h.type = 8 # ICMP_ECHO_REQUEST h.code = 0 h.checksum = 0 if platform == 'esp8266': h.id = urandom.getrandbits(16) else: h.id = urandom.randint(0, 65535) h.seq = 1 time_data = array("f", (0 for _ in range(0))) # init socket sock = usocket.socket(usocket.AF_INET, usocket.SOCK_RAW, 1) sock.setblocking(0) sock.settimeout(timeout/1000) addr = usocket.getaddrinfo(host, 1)[0][-1][0] # ip address sock.connect((addr, 1)) not quiet and print("PING %s (%s): %u data bytes" % (host, addr, len(pkt))) seq_loop = -1 try: if loop: n_trans = 0 n_recv = 0 while True: gc.collect() utime.sleep_ms(int_loop) count = 1 seq_loop += 1 seqs = list(range(1, count+1)) # [1,2,...,count] c = 1 t = 0 finish = False while t < timeout: if t == interval and c <= count: # send packet h.checksum = 0 h.seq = c h.timestamp = utime.ticks_us() h.checksum = checksum(pkt) if sock.send(pkt) == size: n_trans += 1 t = 0 # reset timeout else: seqs.remove(c) if loop: count += 1 seqs.append(count) c += 1 # recv packet while 1: socks, _, _ = uselect.select([sock], [], [], 0) if socks: resp = socks[0].recv(4096) resp_mv = memoryview(resp) h2 = uctypes.struct(uctypes.addressof( resp_mv[20:]), pkt_desc, uctypes.BIG_ENDIAN) # TODO: validate checksum (optional) seq = h2.seq # 0: ICMP_ECHO_REPLY if h2.type == 0 and h2.id == h.id and (seq in seqs): t_elapsed = (utime.ticks_us()-h2.timestamp) / 1000 ttl = ustruct.unpack('!B', resp_mv[8:9])[0] # time-to-live n_recv += 1 not quiet and print("{} bytes from {}: icmp_seq={} ttl={} time={:.3f} ms".format( len(resp), addr, seq_loop, ttl, t_elapsed)) time_data.append(t_elapsed) seqs.remove(seq) if len(seqs) == 0: finish = True break else: break if finish: break utime.sleep_ms(1) t += 1 else: seqs = list(range(1, count+1)) # [1,2,...,count] c = 1 t = 0 n_trans = 0 n_recv = 0 finish = False while t < timeout: if t == interval and c <= count: # send packet h.checksum = 0 h.seq = c h.timestamp = utime.ticks_us() h.checksum = checksum(pkt) if sock.send(pkt) == size: n_trans += 1 t = 0 # reset timeout else: seqs.remove(c) if loop: count += 1 seqs.append(count) c += 1 # recv packet while 1: socks, _, _ = uselect.select([sock], [], [], 0) if socks: resp = socks[0].recv(4096) resp_mv = memoryview(resp) h2 = uctypes.struct(uctypes.addressof( resp_mv[20:]), pkt_desc, uctypes.BIG_ENDIAN) # TODO: validate checksum (optional) seq = h2.seq # 0: ICMP_ECHO_REPLY if h2.type == 0 and h2.id == h.id and (seq in seqs): t_elapsed = (utime.ticks_us()-h2.timestamp) / 1000 ttl = ustruct.unpack('!B', resp_mv[8:9])[0] # time-to-live n_recv += 1 not quiet and print("{} bytes from {}: icmp_seq={} ttl={} time={:.3f} ms".format( len(resp), addr, seq, ttl, t_elapsed)) time_data.append(t_elapsed) seqs.remove(seq) if loop: count += 1 seqs.append(count) utime.sleep_ms(int_loop) if len(seqs) == 0: finish = True break else: break if finish: if not loop: break utime.sleep_ms(1) t += 1 sock.close() if not quiet: print('--- {} ping statistics ---'.format(host)) print("{} packets transmitted, {} packets received, {:.1f}% packet loss".format( n_trans, n_recv, (1-(n_recv/n_trans))*100)) print("round-trip min/avg/max/stddev = {:.2f}/{:.2f}/{:.2f}/{:.2f} ms".format(min(time_data),sum(time_data)/len(time_data),max(time_data), stddev(time_data))) gc.collect() if rtn: return (n_trans, n_recv) except KeyboardInterrupt: # close sock.close() gc.collect() if not quiet: print('^C') print('--- {} ping statistics ---'.format(host)) print("{} packets transmitted, {} packets received, {:.1f}% packet loss".format( n_trans, n_recv, (1-(n_recv/n_trans))*100)) print("round-trip min/avg/max/stddev = {:.2f}/{:.2f}/{:.2f}/{:.2f} ms".format(min(time_data),sum(time_data)/len(time_data),max(time_data), stddev(time_data))) if rtn: return (n_trans, n_recv) except Exception as e: print(e)
def main(self): key_buff = [27] # Reads last char received board = False # Board menu flag devices = False # Device list flag device = False # Device menu flag while True: if not self.board.interactive: # if back received or timeout occurred backs to scheduled mode self.board.enable_interrupts() return r, w, x = uselect.select(self.board.input, [], [], 0) if r: try: byte = ord(r[0].read(1)) # Reads from main UART key_buff.append( byte ) # Appends char to the command buffer, needed for multiple char commands except: pass else: # Checks for command completion if key_buff: # prints out menu on command received only if not board: if not devices: if not device: if 27 in key_buff: board = True self._board_menu() else: if 49 in key_buff: self.device.toggle() self._device_menu(self.device) elif 50 in key_buff: if self._pass_through(self.device): self._device_menu(self.device) elif 51 in key_buff: self.board.operational = True self.device.main() self.board.operational = False elif 52 in key_buff: self.get_config(self.device) elif 8 in key_buff: device = False devices = True utils.delete_device() self._devices_menu() elif 27 in key_buff: self._device_menu(device) else: if chr(key_buff[0]) in self.device_list: devices = False device = True device = utils.create_device( self.device_list[chr(key_buff[0])]) self._device_menu(device) elif 8 in key_buff: devices = False board = True self._board_menu() elif 27 in key_buff: self._devices_menu() else: if 27 in key_buff: board = True self._board_menu() elif 8 in key_buff: print("") self.board.interactive = False #return DEBUG elif 49 in key_buff: board = False devices = True self._devices_menu() elif 50 in key_buff: self._get_data_files() elif 51 in key_buff: self._get_event_table() key_buff = []
def ping(host, count=4, timeout=5000, interval=10, quiet=False, size=64): import utime import uselect import uctypes import usocket import ustruct import urandom # prepare packet assert size >= 16, "pkt size too small" pkt = b'Q' * size pkt_desc = { "type": uctypes.UINT8 | 0, "code": uctypes.UINT8 | 1, "checksum": uctypes.UINT16 | 2, "id": uctypes.UINT16 | 4, "seq": uctypes.INT16 | 6, "timestamp": uctypes.UINT64 | 8, } # packet header descriptor h = uctypes.struct(uctypes.addressof(pkt), pkt_desc, uctypes.BIG_ENDIAN) h.type = 8 # ICMP_ECHO_REQUEST h.code = 0 h.checksum = 0 h.id = urandom.getrandbits(16) h.seq = 1 # init socket sock = usocket.socket(usocket.AF_INET, usocket.SOCK_RAW, 1) sock.setblocking(0) sock.settimeout(timeout / 1000) addr = usocket.getaddrinfo(host, 1)[0][-1][0] # ip address sock.connect((addr, 1)) not quiet and print("PING %s (%s): %u data bytes" % (host, addr, len(pkt))) seqs = list(range(1, count + 1)) # [1,2,...,count] c = 1 t = 0 n_trans = 0 n_recv = 0 finish = False while t < timeout: if t == interval and c <= count: # send packet h.checksum = 0 h.seq = c h.timestamp = utime.ticks_us() h.checksum = checksum(pkt) if sock.send(pkt) == size: n_trans += 1 t = 0 # reset timeout else: seqs.remove(c) c += 1 # recv packet while 1: socks, _, _ = uselect.select([sock], [], [], 0) if socks: resp = socks[0].recv(4096) resp_mv = memoryview(resp) h2 = uctypes.struct(uctypes.addressof(resp_mv[20:]), pkt_desc, uctypes.BIG_ENDIAN) # TODO: validate checksum (optional) seq = h2.seq if h2.type == 0 and h2.id == h.id and ( seq in seqs): # 0: ICMP_ECHO_REPLY t_elasped = (utime.ticks_us() - h2.timestamp) / 1000 ttl = ustruct.unpack('!B', resp_mv[8:9])[0] # time-to-live n_recv += 1 not quiet and print( "%u bytes from %s: icmp_seq=%u, ttl=%u, time=%f ms" % (len(resp), addr, seq, ttl, t_elasped)) seqs.remove(seq) if len(seqs) == 0: finish = True break else: break if finish: break utime.sleep_ms(1) t += 1 # close sock.close() ret = (n_trans, n_recv) not quiet and print("%u packets transmitted, %u packets received" % (n_trans, n_recv)) return (n_trans, n_recv)
def ping(host, count=4, timeout=5000, interval=1000, quiet=False, size=64): raise Exception('Unsupported! Leaks memory!') # print('ping') import utime import uselect import uctypes import usocket import ustruct import machine # round up fractional values interval = max(1, int(interval)) # avoid count==0 count = max(count, 1) # prepare packet assert size >= 16, "pkt size too small" pkt = b'Q' * size pkt_desc = { "type": uctypes.UINT8 | 0, "code": uctypes.UINT8 | 1, "checksum": uctypes.UINT16 | 2, "id": uctypes.UINT16 | 4, "seq": uctypes.INT16 | 6, "timestamp": uctypes.UINT64 | 8, } # packet header descriptor h = uctypes.struct(uctypes.addressof(pkt), pkt_desc, uctypes.BIG_ENDIAN) h.type = 8 # ICMP_ECHO_REQUEST h.code = 0 h.checksum = 0 h.id = machine.rng() h.seq = 1 # init socket sock = usocket.socket(usocket.AF_INET, 3, 1) # usocket.SOCK_RAW, 1) sock.setblocking(0) sock.settimeout(timeout / 1000) addr = usocket.getaddrinfo(host, 1)[0][-1][0] # ip address sock.connect((addr, 1)) not quiet and print("PING %s (%s): %u data bytes" % (host, addr, len(pkt))) seqs = list(range(1, count + 1)) # [1,2,...,count] c = 1 t = 0 n_trans = 0 n_recv = 0 time_s = 0 finish = False # print('ping2') while t < timeout: if t == interval and c <= count: # send packet h.checksum = 0 h.seq = c h.timestamp = utime.ticks_us() h.checksum = _checksum(pkt) if sock.send(pkt) == size: n_trans += 1 t = 0 # reset timeout else: seqs.remove(c) c += 1 # recv packet while 1: socks, _, _ = uselect.select([sock], [], [], 0) if socks: resp = socks[0].recv(4096) resp_mv = memoryview(resp) h2 = uctypes.struct(uctypes.addressof(resp_mv[20:]), pkt_desc, uctypes.BIG_ENDIAN) # TODO: validate checksum (optional) seq = h2.seq if h2.type == 0 and h2.id == h.id and ( seq in seqs): # 0: ICMP_ECHO_REPLY t_elasped = (utime.ticks_us() - h2.timestamp) / 1000 ttl = ustruct.unpack('!B', resp_mv[8:9])[0] # time-to-live n_recv += 1 not quiet and print( "%u bytes from %s: icmp_seq=%u, ttl=%u, time=%.2f ms" % (len(resp), addr, seq, ttl, t_elasped)) time_s += t_elasped seqs.remove(seq) if len(seqs) == 0: finish = True break else: break if finish: break #utime.sleep_ms(1) t += 1 sock.close() loss = 0 try: loss = (n_trans - n_recv) / n_trans * 100 except: pass avg_ms = 0 try: avg_ms = time_s / n_recv except: pass ret = (n_trans, n_recv, loss, avg_ms) not quiet and print( "%u packets transmitted, %u packets received, %.2f%% packet loss, %.2f ms avg" % ret) return ret
# test select.poll on UDP sockets try: import usocket as socket, uselect as select except ImportError: try: import socket, select except ImportError: print("SKIP") raise SystemExit s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) s.bind(socket.getaddrinfo("127.0.0.1", 8000)[0][-1]) poll = select.poll() # UDP socket should not be readable poll.register(s, select.POLLIN) print(len(poll.poll(0))) # UDP socket should be writable poll.modify(s, select.POLLOUT) print(poll.poll(0)[0][1] == select.POLLOUT) # same test for select.select, but just skip it if the function isn't available if hasattr(select, "select"): r, w, e = select.select([s], [], [], 0) assert not r and not w and not e
#Setup Socket WebServer s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.setblocking(0) s.bind(('', 80)) s.listen(5) while True: #def tempo(): #try: #tempo() #except: r, w, err = select.select ((s,), (), (), 1) if r: for readable in r: conn, addr = s.accept() print("Got a connection from %s" % str(addr)) conn.settimeout(5) try: Client_handler(conn) except OSError as e: pass # LED2.value(1) # time.sleep(1) #do_something_else()