def __init__(self, server, port=61440): self.s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) self.addr = socket.getaddrinfo(server, port)[0][4] self.addr2 = socket.getaddrinfo('0.0.0.0', port)[0][4] self.s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) self.s.bind(self.addr2) # self.s.settimeout(3) self.s.connect(self.addr) log("open local port:" + str(port)) log("DEBUG MODE:"+ str(DEBUG)) self.server = server self.port = port
def request(method, url, json=None, timeout=None, headers=None): urlparts = url.split('/', 3) proto = urlparts[0] host = urlparts[2] urlpath = '' if len(urlparts) < 4 else urlparts[3] if proto == 'http:': port = 80 elif proto == 'https:': port = 443 else: raise OSError('Unsupported protocol: %s' % proto[:-1]) if ':' in host: host, port = host.split(':') port = int(port) if json is not None: content = ujson.dumps(json) content_type = CONTENT_TYPE_JSON else: content = None ai = usocket.getaddrinfo(host, port) addr = ai[0][4] sock = usocket.socket() if timeout is not None: assert SUPPORT_TIMEOUT, 'Socket does not support timeout' sock.settimeout(timeout) sock.connect(addr) if proto == 'https:': assert SUPPORT_SSL, 'HTTPS not supported: could not find ussl' sock = ussl.wrap_socket(sock) sock.write('%s /%s HTTP/1.0\r\nHost: %s\r\n' % (method, urlpath, host)) if headers is not None: for header in headers.items(): sock.write('%s: %s\r\n' % header) if content is not None: sock.write('content-length: %s\r\n' % len(content)) sock.write('content-type: %s\r\n' % content_type) sock.write('\r\n') sock.write(content) else: sock.write('\r\n') l = sock.readline() protover, status, msg = l.split(None, 2) # Skip headers while sock.readline() != b'\r\n': pass return Response(int(status), sock)
def download(url, local_name): proto, _, host, urlpath = url.split('/', 3) ai = usocket.getaddrinfo(host, 443) #print("Address infos:", ai) addr = ai[0][4] s = usocket.socket() #print("Connect address:", addr) s.connect(addr) if proto == "https:": s = ussl.wrap_socket(s) # 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": raise OSError() while 1: l = s.readline() if not l: raise OSError() if l == b'\r\n': break with open(local_name, "wb") as f: while 1: l = s.read(1024) if not l: break f.write(l)
def open_connection(host, port, ssl=False): if DEBUG and __debug__: log.debug("open_connection(%s, %s)", host, port) ai = _socket.getaddrinfo(host, port, 0, _socket.SOCK_STREAM) ai = ai[0] s = _socket.socket(ai[0], ai[1], ai[2]) s.setblocking(False) try: s.connect(ai[-1]) except OSError as e: if e.args[0] != uerrno.EINPROGRESS: raise if DEBUG and __debug__: log.debug("open_connection: After connect") yield IOWrite(s) # if __debug__: # assert s2.fileno() == s.fileno() if DEBUG and __debug__: log.debug("open_connection: After iowait: %s", s) if ssl: print("Warning: uasyncio SSL support is alpha") import ussl s.setblocking(True) s2 = ussl.wrap_socket(s) s.setblocking(False) return StreamReader(s, s2), StreamWriter(s2, {}) return StreamReader(s), StreamWriter(s, {})
def urlopen(url, data=None): if data: raise NotImplementedError("POST is not yet supported") 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) ai = usocket.getaddrinfo(host, 80) addr = ai[0][4] s = usocket.socket() s.connect(addr) s.send(b"GET /%s HTTP/1.0\r\nHost: %s\r\n\r\n" % (path, host)) l = s.readline() protover, status, msg = l.split(None, 2) status = int(status) #print(protover, status, msg) while True: l = s.readline() if not l or l == b"\r\n": break #print(line) if l.startswith(b"Transfer-Encoding:"): if b"chunked" in line: raise ValueError("Unsupported " + l) elif l.startswith(b"Location:"): raise NotImplementedError("Redirects not yet supported") return s
def main(use_stream=False): s = socket.socket() # Binding to all interfaces - server will be accessible to other hosts! ai = socket.getaddrinfo("0.0.0.0", 8080) print("Bind address info:", ai) addr = ai[0][-1] s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) s.bind(addr) s.listen(5) print("Listening, connect your browser to http://<this_host>:8080/") counter = 0 while True: res = s.accept() client_s = res[0] client_addr = res[1] print("Client address:", client_addr) print("Client socket:", client_s) print("Request:") if use_stream: # MicroPython socket objects support stream (aka file) interface # directly. print(client_s.read(4096)) client_s.write(CONTENT % counter) else: print(client_s.recv(4096)) client_s.send(CONTENT % counter) client_s.close() counter += 1 print()
def main(use_stream=True): s = _socket.socket() ai = _socket.getaddrinfo("google.com", 443) print("Address infos:", ai) addr = ai[0][-1] print("Connect address:", addr) s.connect(addr) s = ssl.wrap_socket(s) print(s) if use_stream: # Both CPython and MicroPython SSLSocket objects support read() and # write() methods. s.write(b"GET / HTTP/1.0\n\n") print(s.read(4096)) else: # MicroPython SSLSocket objects implement only stream interface, not # socket interface s.send(b"GET / HTTP/1.0\n\n") print(s.recv(4096)) s.close()
def url_open(url): global warn_ussl proto, _, host, urlpath = url.split('/', 3) ai = usocket.getaddrinfo(host, 443) #print("Address infos:", ai) addr = ai[0][4] s = usocket.socket(ai[0][0]) #print("Connect address:", addr) s.connect(addr) if proto == "https:": s = ussl.wrap_socket(s) if warn_ussl: print("Warning: %s SSL certificate is not validated" % host) warn_ussl = False # 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": print("Package not found") raise ValueError(status) while 1: l = s.readline() if not l: raise ValueError("Unexpected EOF") if l == b'\r\n': break return s
def __init__(self, host, port=HTTP_PORT): self.host = host self.port = int(port) addr_info = socket.getaddrinfo(host, port) self.addr = addr_info[0][-1] self.connected = False self.socket = socket.socket()
def open_http_socket(method, url, json=None, timeout=None, headers=None, urlencoded = None): urlparts = url.split('/', 3) proto = urlparts[0] host = urlparts[2] urlpath = '' if len(urlparts) < 4 else urlparts[3] if proto == 'http:': port = 80 elif proto == 'https:': port = 443 else: raise OSError('Unsupported protocol: %s' % proto[:-1]) if ':' in host: host, port = host.split(':') port = int(port) if json is not None: content = ujson.dumps(json) content_type = CONTENT_TYPE_JSON elif urlencoded is not None: content = urlencoded content_type = "application/x-www-form-urlencoded" else: content = None # ToDo: Handle IPv6 addresses if is_ipv4_address(host): addr = (host, port) else: ai = usocket.getaddrinfo(host, port) addr = ai[0][4] sock = None if proto == 'https:': sock = usocket.socket(usocket.AF_INET, usocket.SOCK_STREAM, usocket.SEC_SOCKET) else: sock = usocket.socket() sock.connect(addr) if proto == 'https:': sock.settimeout(0) # Actually make timeouts working properly with ssl sock.send('%s /%s HTTP/1.0\r\nHost: %s\r\n' % (method, urlpath, host)) if headers is not None: for header in headers.items(): sock.send('%s: %s\r\n' % header) if content is not None: sock.send('content-length: %s\r\n' % len(content)) sock.send('content-type: %s\r\n' % content_type) sock.send('\r\n') sock.send(content) else: sock.send('\r\n') return sock
def urlopen(url, data=None, method="GET"): if data is not None and method == "GET": method = "POST" try: proto, dummy, host, path = url.split("/", 3) except ValueError: proto, dummy, host = url.split("/", 2) path = "" if proto == "http:": port = 80 elif proto == "https:": import ussl port = 443 else: raise ValueError("Unsupported protocol: " + proto) if ":" in host: host, port = host.split(":", 1) port = int(port) ai = usocket.getaddrinfo(host, port) addr = ai[0][4] s = usocket.socket() s.connect(addr) if proto == "https:": s = ussl.wrap_socket(s, server_hostname=host) s.write(method) s.write(b" /") s.write(path) s.write(b" HTTP/1.0\r\nHost: ") s.write(host) s.write(b"\r\n") if data: s.write(b"Content-Length: ") s.write(str(len(data))) s.write(b"\r\n") s.write(b"\r\n") if data: s.write(data) l = s.readline() protover, status, msg = l.split(None, 2) status = int(status) #print(protover, status, msg) while True: l = s.readline() if not l or l == b"\r\n": break #print(l) if l.startswith(b"Transfer-Encoding:"): if b"chunked" in l: raise ValueError("Unsupported " + l) elif l.startswith(b"Location:"): raise NotImplementedError("Redirects not yet supported") return s
def __init__(self, client_id, server, port=0, ssl=False): if port == 0: port = 8883 if ssl else 1883 self.client_id = client_id self.sock = None self.addr = socket.getaddrinfo(server, port)[0][-1] self.ssl = ssl self.pid = 0 self.cb = None
def request(method, url, data=None, json=None, headers={}, stream=None): try: proto, dummy, host, path = url.split("/", 3) except ValueError: proto, dummy, host = url.split("/", 2) path = "" if proto == "http:": port = 80 elif proto == "https:": import ussl port = 443 else: raise ValueError("Unsupported protocol: " + proto) if ":" in host: host, port = host.split(":", 1) port = int(port) ai = usocket.getaddrinfo(host, port) addr = ai[0][4] s = usocket.socket() s.connect(addr) if proto == "https:": s = ussl.wrap_socket(s) s.write(b"%s /%s HTTP/1.0\r\n" % (method, path)) if not "Host" in headers: s.write(b"Host: %s\r\n" % host) if json is not None: assert data is None import ujson data = ujson.dumps(json) if data: s.write(b"Content-Length: %d\r\n" % len(data)) s.write(b"\r\n") if data: s.write(data) l = s.readline() protover, status, msg = l.split(None, 2) status = int(status) #print(protover, status, msg) while True: l = s.readline() if not l or l == b"\r\n": break #print(line) if l.startswith(b"Transfer-Encoding:"): if b"chunked" in line: raise ValueError("Unsupported " + l) elif l.startswith(b"Location:"): raise NotImplementedError("Redirects not yet supported") resp = Response(s) resp.status_code = status resp.reason = msg.rstrip() return resp
def start(self): """ Starts the LoRaWAN nano gateway. """ self._log('Starting LoRaWAN nano gateway with id: {}', self.id) # setup WiFi as a station and connect self.wlan = WLAN(mode=WLAN.STA) self._connect_to_wifi() # get a time sync self._log('Syncing time with {} ...', self.ntp_server) self.rtc.ntp_sync(self.ntp_server, update_period=self.ntp_period) while not self.rtc.synced(): utime.sleep_ms(50) self._log("RTC NTP sync complete") # get the server IP and create an UDP socket self.server_ip = usocket.getaddrinfo(self.server, self.port)[0][-1] self._log('Opening UDP socket to {} ({}) port {}...', self.server, self.server_ip[0], self.server_ip[1]) self.sock = usocket.socket(usocket.AF_INET, usocket.SOCK_DGRAM, usocket.IPPROTO_UDP) self.sock.setsockopt(usocket.SOL_SOCKET, usocket.SO_REUSEADDR, 1) self.sock.setblocking(False) # push the first time immediatelly self._push_data(self._make_stat_packet()) # create the alarms self.stat_alarm = Timer.Alarm(handler=lambda t: self._push_data(self._make_stat_packet()), s=60, periodic=True) self.pull_alarm = Timer.Alarm(handler=lambda u: self._pull_data(), s=25, periodic=True) # start the UDP receive thread self.udp_stop = False _thread.start_new_thread(self._udp_thread, ()) # initialize the LoRa radio in LORA mode self._log('Setting up the LoRa radio at {:.1f} Mhz using {}', self._freq_to_float(self.frequency), self.datarate) self.lora = LoRa( mode=LoRa.LORA, frequency=self.frequency, bandwidth=self.bw, sf=self.sf, preamble=8, coding_rate=LoRa.CODING_4_5, tx_iq=True ) # create a raw LoRa socket self.lora_sock = usocket.socket(usocket.AF_LORA, usocket.SOCK_RAW) self.lora_sock.setblocking(False) self.lora_tx_done = False self.lora.callback(trigger=(LoRa.RX_PACKET_EVENT | LoRa.TX_PACKET_EVENT), handler=self._lora_cb) self._log('LoRaWAN nano gateway online')
def time(): NTP_QUERY = bytearray(48) NTP_QUERY[0] = 0x1b addr = socket.getaddrinfo(host, 123)[0][-1] s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) s.settimeout(1) res = s.sendto(NTP_QUERY, addr) msg = s.recv(48) s.close() val = struct.unpack("!I", msg[40:44])[0] return val - NTP_DELTA
def main(): if len(sys.argv) != 3: help(1) if ":" in sys.argv[1] and ":" in sys.argv[2]: error("Operations on 2 remote files are not supported") if ":" not in sys.argv[1] and ":" not in sys.argv[2]: error("One remote file is required") if ":" in sys.argv[1]: op = "get" host, port, src_file = parse_remote(sys.argv[1]) dst_file = sys.argv[2] if os.path.isdir(dst_file): basename = src_file.rsplit("/", 1)[-1] dst_file += "/" + basename else: op = "put" host, port, dst_file = parse_remote(sys.argv[2]) src_file = sys.argv[1] if dst_file[-1] == "/": basename = src_file.rsplit("/", 1)[-1] dst_file += basename if 1: print(op, host, port) print(src_file, "->", dst_file) s = socket.socket() ai = socket.getaddrinfo(host, port) addr = ai[0][4] s.connect(addr) #s = s.makefile("rwb") websocket_helper.client_handshake(s) ws = websocket(s) import getpass passwd = getpass.getpass() login(ws, passwd) print("Remote WebREPL version:", get_ver(ws)) # Set websocket to send data marked as "binary" ws.ioctl(9, 2) if op == "get": get_file(ws, dst_file, src_file) elif op == "put": put_file(ws, src_file, dst_file) s.close()
def ntp(): # noqa ntp_query = bytearray(48) ntp_query[0] = 0x1b addr = socket.getaddrinfo('pool.ntp.org', 123)[0][-1] s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) s.settimeout(1) s.sendto(ntp_query, addr) msg = s.recv(48) s.close() val = struct.unpack("!I", msg[40:44])[0] return val - NTP_DELTA
def create_connection(addr, timeout=None, source_address=None): s = socket() #print("Address:", addr) ais = getaddrinfo(addr[0], addr[1]) #print("Address infos:", ais) for ai in ais: try: s.connect(ai[4]) return s except: pass
def update(file="main.py"): s = socket.socket() ai = socket.getaddrinfo("192.168.1.101", 8000) print("Address infos:", ai) addr = ai[0][-1] print("Connect address:", addr) s.connect(addr) s = s.makefile("rwb", 0) s.write(b"GET /{} HTTP/1.0\n\n".format(file)) open(file, "w").write(s.read())
def http_post(url): _, _, host, path = url.split('/', 3) addr = usocket.getaddrinfo(host, 80)[0][-1] s = usocket.socket() s.connect(addr) s.send(bytes('POST /%s HTTP/1.0\r\nHost: %s\r\n\r\n' % (path, host), 'utf8')) while True: data = s.recv(100) if data: print(str(data, 'utf8'), end='') else: break
def scan(): sock = usocket.socket(usocket.AF_INET, usocket.SOCK_DGRAM) try: if hasattr(sock, 'settimeout'): sock.settimeout(TIMEOUT) addrs = usocket.getaddrinfo(MCAST_IP, MCAST_PORT) sock.sendto(QUERY, addrs[0][4]) data, addr = sock.recvfrom(1024) return ujson.loads(data.decode('utf-8')) finally: sock.close()
def __init__(self, callback = None, websocket_handler = None, addr = ("0.0.0.0", 80), backlog = 3, ): self.callback = callback self.websocket_handler = websocket_handler self.websockets = [] self.s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.s.setblocking(False) self.s.bind( socket.getaddrinfo(addr[0], addr[1])[0][-1] ) self.s.listen(backlog)
def main(): s = socket.socket() # Bind to (allow to be connected on ) all interfaces. This means # this server will be accessible to other hosts on your local # network, and if your server has direct (non-firewalled) connection # to the Internet, then to anyone on the Internet. We bind to all # interfaces to let this example work easily on embedded MicroPython # targets, which you will likely access from another machine on your # local network. Take care when running this on an Internet-connected # machine though! Replace "0.0.0.0" with "127.0.0.1" if in doubt, to # make the server accessible only on the machine it runs on. ai = socket.getaddrinfo("0.0.0.0", 8080) print("Bind address info:", ai) addr = ai[0][-1] # A port on which a socket listened remains inactive during some time. # This means that if you run this sample, terminate it, and run again # you will likely get an error. To avoid this timeout, set SO_REUSEADDR # socket option. s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) s.bind(addr) s.listen(5) print("Listening, connect your browser to http://<this_host>:8080/") counter = 0 while True: res = s.accept() client_s = res[0] client_addr = res[1] print("Client address:", client_addr) print("Client socket:", client_s) # We assume here that .recv() call will read entire HTTP request # from client. This is usually true, at least on "big OS" systems # like Linux/MacOS/Windows. But that doesn't have to be true in # all cases, in particular on embedded systems, when there can # easily be "short recv", where it returns much less than requested # data size. That's why this example is called "simplistic" - it # shows that writing a web server in Python that *usually works* is # ten lines of code, and you can use this technique for quick hacks # and experimentation. But don't do it like that in production # applications - instead, parse HTTP request properly, as shown # by http_server.py example. req = client_s.recv(4096) print("Request:") print(req) client_s.send(CONTENT % counter) client_s.close() counter += 1 print()
def __init__(self, client_id, server, port=0, user=None, password=None, keepalive=0, ssl=False, ssl_params={}): if port == 0: port = 8883 if ssl else 1883 self.client_id = client_id self.sock = None self.addr = socket.getaddrinfo(server, port)[0][-1] self.ssl = ssl self.ssl_params = ssl_params self.pid = 0 self.cb = None self.user = user self.pswd = password self.keepalive = keepalive
def main(use_stream=False): s = socket.socket() # Binding to all interfaces - server will be accessible to other hosts! ai = socket.getaddrinfo("0.0.0.0", 8080) print("Bind address info:", ai) addr = ai[0][-1] #prepping LED pin p = Pin(2,Pin.OUT) # p.high() # time.sleep(1) # p.low() s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) s.bind(addr) s.listen(5) print("Listening, connect your browser to http://<this_host>:8080/") counter = 0 while True: res = s.accept() client_s = res[0] client_addr = res[1] print("Client address:", client_addr) print("Client socket:", client_s) print("Request:") if use_stream: # MicroPython socket objects support stream (aka file) interface # directly. #print(client_s.read(4096)) val = client_s.read(4096) print(val) client_s.write(CONTENT % counter) else: #print(client_s.recv(4096)) val = client_s.recv(4096) print(val) client_s.send(CONTENT % counter) if "GET /toggle" in val: print("Toggling!") p.high() time.sleep(1) p.low() machine.reset() client_s.close() counter += 1 print()
def main(micropython_optimize=False): s = socket.socket() # Binding to all interfaces - server will be accessible to other hosts! ai = socket.getaddrinfo("0.0.0.0", 8080) print("Bind address info:", ai) addr = ai[0][-1] s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) s.bind(addr) s.listen(5) print("Listening, connect your browser to http://<this_host>:8080/") counter = 0 while True: res = s.accept() client_sock = res[0] client_addr = res[1] print("Client address:", client_addr) print("Client socket:", client_sock) if not micropython_optimize: # To read line-oriented protocol (like HTTP) from a socket (and # avoid short read problem), it must be wrapped in a stream (aka # file-like) object. That's how you do it in CPython: client_stream = client_sock.makefile("rwb") else: # .. but MicroPython socket objects support stream interface # directly, so calling .makefile() method is not required. If # you develop application which will run only on MicroPython, # especially on a resource-constrained embedded device, you # may take this shortcut to save resources. client_stream = client_sock print("Request:") req = client_stream.readline() print(req) while True: h = client_stream.readline() if h == b"" or h == b"\r\n": break print(h) client_stream.write(CONTENT % counter) client_stream.close() if not micropython_optimize: client_sock.close() counter += 1 print()
def open_connection(host, port): log.debug("open_connection(%s, %s)", host, port) s = _socket.socket() s.setblocking(False) ai = _socket.getaddrinfo(host, port) addr = ai[0][4] try: s.connect(addr) except OSError as e: if e.args[0] != errno.EINPROGRESS: raise log.debug("open_connection: After connect") s = yield IOWrite(s) log.debug("open_connection: After iowait: %s", s) return StreamReader(s), StreamWriter(s)
def main(use_stream=True): s = socket.socket() # Binding to all interfaces - server will be accessible to other hosts! ai = socket.getaddrinfo("0.0.0.0", 8443) print("Bind address info:", ai) addr = ai[0][-1] s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) s.bind(addr) s.listen(5) print("Listening, connect your browser to https://<this_host>:8443/") counter = 0 while True: res = s.accept() client_s = res[0] client_addr = res[1] print("Client address:", client_addr) print("Client socket:", client_s) client_s = ssl.wrap_socket(client_s, server_side=True) print(client_s) print("Request:") if use_stream: # Both CPython and MicroPython SSLSocket objects support read() and # write() methods. # Browsers are prone to terminate SSL connection abruptly if they # see unknown certificate, etc. We must continue in such case - # next request they issue will likely be more well-behaving and # will succeed. try: req = client_s.readline() print(req) while True: h = client_s.readline() if h == b"" or h == b"\r\n": break print(h) if req: client_s.write(CONTENT % counter) except Exception as e: print("Exception serving request:", e) else: print(client_s.recv(4096)) client_s.send(CONTENT % counter) client_s.close() counter += 1 print()
def time(ms_accuracy=False): NTP_QUERY = bytearray(48) NTP_QUERY[0] = 0x1b addr = socket.getaddrinfo(host, 123)[0][-1] s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) s.settimeout(1) res = s.sendto(NTP_QUERY, addr) msg = s.recv(48) s.close() sec = struct.unpack("!I", msg[40:44])[0] - NTP_DELTA frac = struct.unpack("!I", msg[44:48])[0] * MILLIS_PER_SECOND >> 32 if ms_accuracy: return sec, frac return sec
def __init__(self, w, h, name = b'rfb', handler = RfbSession, addr = ('0.0.0.0', 5900), backlog = 3, ): self.w = w self.h = h self.name = name self.handler = handler self.sessions = [] self.s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.s.setblocking(False) self.s.bind( socket.getaddrinfo(addr[0],addr[1])[0][-1] ) self.s.listen(backlog)
def ping(host, count=1, timeout=1000, interval=10, quiet=False, size=64): # 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 = randint(0, 65535) 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_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("%u bytes from %s: icmp_seq=%u, ttl=%u, time=%f ms" % (len(resp), addr, seq, ttl, t_elapsed)) seqs.remove(seq) if len(seqs) == 0: finish = True break else: break if finish: break utime.sleep_ms(1) t += 1 # close sock.close() not quiet and print("%u packets transmitted, %u packets received" % (n_trans, n_recv)) return n_trans, n_recv
def request(method, url, data=None, json=None, headers={}, stream=None): perf = machine.Timer.Chrono() perf.start() try: proto, dummy, host, path = url.split("/", 3) except ValueError: proto, dummy, host = url.split("/", 2) path = "" except AttributeError as e: print(e) return if proto == "http:": port = 80 elif proto == "https:": import ussl port = 443 else: raise ValueError("Unsupported protocol: " + proto) if ":" in host: host, port = host.split(":", 1) port = int(port) prep_time = perf.read_ms() #ai = usocket.getaddrinfo(host, port, 0, usocket.SOCK_STREAM) ai = usocket.getaddrinfo(host, port) ai = ai[0] s = usocket.socket(ai[0], ai[1], ai[2]) s.setblocking(True) s.settimeout(5) sock_init_time = perf.read_ms() - prep_time try: s.connect(ai[-1]) sock_connect_time = perf.read_ms() - sock_init_time if proto == "https:": s = ussl.wrap_socket(s, server_hostname=host) sock_ssl_time = perf.read_ms() - sock_connect_time s.write(b"%s /%s HTTP/1.0\r\n" % (method, path)) if not "Host" in headers: s.write(b"Host: %s\r\n" % host) # Iterate over keys to avoid tuple alloc for k in headers: s.write(k) s.write(b": ") s.write(headers[k]) s.write(b"\r\n") if json is not None: assert data is None import ujson data = ujson.dumps(json) s.write(b"Content-Type: application/json\r\n") if data: s.write(b"Content-Length: %d\r\n" % len(data)) s.write(b"Connection: close\r\n") s.write(b"\r\n") sock_header_time = perf.read_ms() - sock_ssl_time if data: s.write(data) sock_data_time = perf.read_ms() - sock_header_time l = s.readline() if l is not None: l = l.split(None, 2) status = int(l[1]) reason = "" if len(l) > 2: reason = l[2].rstrip() else: print("No response") status = 0 reason = "" while True: l = s.readline() if not l or l == b"\r\n": break if l.startswith(b"Transfer-Encoding:"): if b"chunked" in l: raise ValueError("Unsupported " + l) elif l.startswith(b"Location:") and not 200 <= status <= 299: raise NotImplementedError("Redirects not yet supported") sock_response_time = perf.read_ms() - sock_data_time except OSError: s.close() raise print("Prep: {:.0f}ms Init: {:.0f}ms Connect: {:.0f}ms SSL: {:.0f}ms " "Header: {:.0f}ms Data: {:.0f}ms Response: {:.0f}ms ".format( prep_time, sock_init_time, sock_connect_time, sock_ssl_time, sock_header_time, sock_data_time, sock_response_time)) resp = Response(s) resp.status_code = status resp.reason = reason resp.close() return resp
def connect(self, clean_session=True, socket_timeout=-1): """ Establishes connection with the MQTT server. :param clean_session: Starts new session on true, resumes past session if false. :type clean_session: bool :param socket_timeout: -1 = default socket timeout, None - socket blocking, positive number - seconds to wait :type socket_timeout: int :return: Existing persistent session of the client from previous interactions. :rtype: bool """ self.sock = socket.socket() addr = socket.getaddrinfo(self.server, self.port)[0][-1] self.sock.connect(addr) self._sock_timeout(socket_timeout) if self.ssl: import ussl self.sock = ussl.wrap_socket(self.sock, **self.ssl_params) # Byte nr - desc # 1 - \x10 0001 - Connect Command, 0000 - Reserved # 2 - Remaining Length # PROTOCOL NAME (3.1.2.1 Protocol Name) # 3,4 - protocol name length len('MQTT') # 5-8 = 'MQTT' # PROTOCOL LEVEL (3.1.2.2 Protocol Level) # 9 - mqtt version 0x04 # CONNECT FLAGS # 10 - connection flags # X... .... = User Name Flag # .X.. .... = Password Flag # ..X. .... = Will Retain # ...X X... = QoS Level # .... .X.. = Will Flag # .... ..X. = Clean Session Flag # .... ...0 = (Reserved) It must be 0! # KEEP ALIVE # 11,12 - keepalive # 13,14 - client ID length # 15-15+len(client_id) - byte(client_id) premsg = bytearray(b"\x10\0\0\0\0\0") msg = bytearray(b"\0\x04MQTT\x04\0\0\0") sz = 10 + 2 + len(self.client_id) msg[7] = bool(clean_session) << 1 # Clean session = True, remove current session if bool(clean_session): self.rcv_pids.clear() if self.user is not None: sz += 2 + len(self.user) msg[7] |= 1 << 7 # User Name Flag if self.pswd is not None: sz += 2 + len(self.pswd) msg[7] |= 1 << 6 # # Password Flag if self.keepalive: assert self.keepalive < 65536 msg[8] |= self.keepalive >> 8 msg[9] |= self.keepalive & 0x00FF if self.lw_topic: sz += 2 + len(self.lw_topic) + 2 + len(self.lw_msg) msg[7] |= 0x4 | (self.lw_qos & 0x1) << 3 | (self.lw_qos & 0x2) << 3 msg[7] |= self.lw_retain << 5 plen = self._varlen_encode(sz, premsg, 1) self._write(premsg, plen) self._write(msg) self._send_str(self.client_id) if self.lw_topic: self._send_str(self.lw_topic) self._send_str(self.lw_msg) if self.user is not None: self._send_str(self.user) if self.pswd is not None: self._send_str(self.pswd) resp = self._read(4) if not (resp[0] == 0x20 and resp[1] == 0x02): # control packet type, Remaining Length == 2 raise MQTTException(29) if resp[3] != 0: if 1 <= resp[3] <= 5: raise MQTTException(20 + resp[3]) else: raise MQTTException(20, resp[3]) self.last_cpacket = ticks_ms() return resp[ 2] & 1 # Is existing persistent session of the client from previous interactions.
def request(method, url, data=None, json=None, headers={}, stream=None): try: proto, dummy, host, path = url.split("/", 3) except ValueError: proto, dummy, host = url.split("/", 2) path = "" if proto == "http:": port = 80 elif proto == "https:": import ussl port = 443 else: raise ValueError("Unsupported protocol: " + proto) if ":" in host: host, port = host.split(":", 1) port = int(port) ai = usocket.getaddrinfo(host, port) addr = ai[0][4] s = usocket.socket() s.connect(addr) if proto == "https:": s = ussl.wrap_socket(s) s.write(b"%s /%s HTTP/1.0\r\n" % (method, path)) if not "Host" in headers: s.write(b"Host: %s\r\n" % host) # Iterate over keys to avoid tuple alloc for k in headers: s.write(k) s.write(b": ") s.write(headers[k]) s.write(b"\r\n") if json is not None: assert data is None import ujson data = ujson.dumps(json) if data: s.write(b"Content-Length: %d\r\n" % len(data)) s.write(b"\r\n") if data: s.write(data) l = s.readline() protover, status, msg = l.split(None, 2) status = int(status) #print(protover, status, msg) while True: l = s.readline() if not l or l == b"\r\n": break #print(l) if l.startswith(b"Transfer-Encoding:"): if b"chunked" in l: raise ValueError("Unsupported " + l) elif l.startswith(b"Location:") and not 200 <= status <= 299: raise NotImplementedError("Redirects not yet supported") resp = Response(s) resp.status_code = status resp.reason = msg.rstrip() return resp
IPDOG = b'\x01' # CONFIG_END class ChallengeException(Exception): def __init__(self): pass class LoginException(Exception): def __init__(self): pass s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) addr = socket.getaddrinfo(server, 61440)[0][4] addr2 = socket.getaddrinfo('0.0.0.0', 61440)[0][4] s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) s.bind(addr2) # s.settimeout(3) s.connect(addr) SALT = '' tr = '' p1 = '' p2 = '' IS_TEST = True # specified fields based on version CONF = "/etc/drcom.conf" UNLIMITED_RETRY = False EXCEPTION = True
# test that socket.connect() on a non-blocking socket raises EINPROGRESS try: import usocket as socket except: import socket def test(peer_addr): s = socket.socket() s.setblocking(False) try: s.connect(peer_addr) except OSError as er: print(er.args[0] == 115) # 115 is EINPROGRESS s.close() if __name__ == "__main__": test(socket.getaddrinfo('micropython.org', 80)[0][-1])
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
async def connect(self, clean_session=True): if self.open(): self.status = 0 self.sock.setblocking(False) try: addr = socket.getaddrinfo(self.server, self.port) except Exception as e: log.debug("ERROR connect: {}".format(e)) return None await asyncio.sleep_ms(500) if len(addr) > 0: addr = addr[0][-1] else: log.debug("Addr: {}".format(addr)) return None log.debug("MQTT server: {}".format(addr)) try: self.sock.connect(addr) except OSError as e: if e.args[0] not in BUSY_ERRORS: log.debug("ERROR connect: {}".format(e)) return None await asyncio.sleep_ms(1000) premsg = bytearray(b"\x10\0\0\0\0\0") msg = bytearray(b"\x04MQTT\x04\x02\0\0") sz = 10 + 2 + len(self.client_id) msg[6] = clean_session << 1 if self.user is not None: sz += 2 + len(self.user) + 2 + len(self.pswd) msg[6] |= 0xC0 if self.keepalive: assert self.keepalive < 65536 msg[7] |= self.keepalive >> 8 msg[8] |= self.keepalive & 0x00FF i = 1 while sz > 0x7f: premsg[i] = (sz & 0x7f) | 0x80 sz >>= 7 i += 1 premsg[i] = sz await self.as_write(premsg, i + 2) await self.as_write(msg) await self.as_send_str(self.client_id) if self.user is not None: await self.as_send_str(self.user) await self.as_send_str(self.pswd) await asyncio.sleep_ms(300) resp = False try: resp = await self._as_read(4) except Exception as e: self.status = 0 log.debug("ERROR connect: {}".format(e)) return resp log.debug("Respt - {}".format(resp)) if resp and resp[1] == 2: self.status = 1 self.first_con = 1 log.debug("F12 connect: st:{} - fc{}".format(self.status, self.first_con ))
station.active(True) station.connect("Y2K killed millions", "foogledoogle") # this is my phone's SSID and password while (not station.isconnected()): pass print("Oh Yes! Get Connected") print("Connected to " + str(station.config('essid'))) # prints SSID Y2K killed millions print("MAC Address: " + str( ubinascii.hexlify(station.config('mac'), ':').decode())) # prints MAC address C4:85:08:49:57:37 print("IP Address: " + str(station.ifconfig()[0])) # prints IP address sock = socket.socket() address = socket.getaddrinfo(station.ifconfig()[0], 80)[0][-1] sock.bind(address) sock.listen(4) red_led_state = "ON" gre_led_state = "ON" but1_state = 'OFF' but2_state = 'OFF' while True: connection, address = sock.accept() get_str = connection.recv(1024) get_str = get_str[0:50] if "green_led=off" in get_str: gre_led.value(0)
def urlopen(url, data=None, method="GET"): if data is not None and method == "GET": method = "POST" try: proto, dummy, host, path = url.split("/", 3) except ValueError: proto, dummy, host = url.split("/", 2) path = "" if proto == "http:": port = 80 elif proto == "https:": import ussl port = 443 else: raise ValueError("Unsupported protocol: " + proto) if ":" in host: host, port = host.split(":", 1) port = int(port) print(host) print(port) ai = usocket.getaddrinfo(host, port) addr = ai[0][4] # print(addr) s = usocket.socket() # s.connect(usocket.getaddrinfo(host, port)[0][4]) s.connect(addr) if proto == "https:": s = ussl.wrap_socket(s) s.write(method) s.write(b" /") s.write(path) s.write(b" HTTP/1.0\r\nHost: ") s.write(host) s.write(b"\r\n") if data: s.write(b"Content-Length: ") s.write(str(len(data))) s.write(b"\r\n") s.write(b"\r\n") if data: s.write(data) l = s.readline() protover, status, msg = l.split(None, 2) status = int(status) #print(protover, status, msg) while True: l = s.readline() if not l or l == b"\r\n": break #print(l) if l.startswith(b"Transfer-Encoding:"): if b"chunked" in l: raise ValueError("Unsupported " + l) elif l.startswith(b"Location:"): raise NotImplementedError("Redirects not yet supported") return s
if not wlan.isconnected(): print('connecting to network...') wlan.connect('youarenot', 'mytrigger') while not wlan.isconnected(): pass print('Oh YES! Get connected') print('Connected to nope') #print('MAC Address: ', transfer(wlan.config('mac'))) print('network config:', wlan.ifconfig()[0]) do_connect() tim = Timer(0) print(esp32.hall_sensor()) print(esp32.raw_temperature()) counter = 0 addr = usocket.getaddrinfo('www.thingspeak.com',80)[0][-1] #mysocket = getSocket(type="TCP") #print('heelo'+ str(addr)) #s = usocket.socket() #s.connect(addr) #data = "field1="+str(esp32.hall_sensor())+"&field2="+str(esp32.raw_temperature()) #response = urequests.get('https://api.thingspeak.com/update?api_key=YO282TSJI25DUDBU&'+data) s = usocket.socket() def handleInterrupt(tim): global addr print(esp32.raw_temperature()) print(esp32.hall_sensor()) s = usocket.socket() s.connect(addr) addr = usocket.getaddrinfo('www.thingspeak.com',80)[0][-1] #s = usocket.socket()
def request(self, method, url, data=None, json=None, headers={}, stream=None): try: proto, dummy, host, path = url.split('/', 3) except ValueError: proto, dummy, host = url.split('/', 2) path = '' if proto == 'http:': port = 80 elif proto == 'https:': import ussl port = 443 else: raise ValueError('Unsupported protocol: ' + proto) if ':' in host: host, port = host.split(':', 1) port = int(port) ai = usocket.getaddrinfo(host, port, 0, usocket.SOCK_STREAM) ai = ai[0] s = usocket.socket(ai[0], ai[1], ai[2]) try: s.connect(ai[-1]) if proto == 'https:': s = ussl.wrap_socket(s, server_hostname=host) s.write(b'%s /%s HTTP/1.0\r\n' % (method, path)) if not 'Host' in headers: s.write(b'Host: %s\r\n' % host) # Iterate over keys to avoid tuple alloc for k in headers: s.write(k) s.write(b': ') s.write(headers[k]) s.write(b'\r\n') # add user agent s.write('User-Agent') s.write(b': ') s.write('MicroPython OTAUpdater') s.write(b'\r\n') if json is not None: assert data is None import ujson data = ujson.dumps(json) s.write(b'Content-Type: application/json\r\n') if data: s.write(b'Content-Length: %d\r\n' % len(data)) s.write(b'\r\n') if data: s.write(data) l = s.readline() # print(l) l = l.split(None, 2) status = int(l[1]) reason = '' if len(l) > 2: reason = l[2].rstrip() while True: l = s.readline() if not l or l == b'\r\n': break # print(l) if l.startswith(b'Transfer-Encoding:'): if b'chunked' in l: raise ValueError('Unsupported ' + l) elif l.startswith(b'Location:') and not 200 <= status <= 299: raise NotImplementedError('Redirects not yet supported') except OSError: s.close() raise resp = Response(s) resp.status_code = status resp.reason = reason return resp
alarm_time[2] += 5 machine.enable_irq(irq_state) reallocate() ip_addr = do_connect() print(ip_addr) # data format write(0x31, 0x01) # power ctl write(0x2D, 0x08) button_b.irq(trigger=Pin.IRQ_FALLING, handler=record) button_c.irq(trigger=Pin.IRQ_FALLING, handler=set_alarm) socket_addr = usocket.getaddrinfo(ip_addr[0], 80)[0][-1] s_listening = usocket.socket() s_listening.bind(socket_addr) s_listening.listen(5) s_listening.settimeout(0.5) print('listening on', socket_addr) letter_list = [] while True: for i in range(4000): if record_state == 1: x, y, _ = get_pos() letter_list.append([x, y]) time.sleep(0.05)
def request(method, url, data=None, json=None, headers=(), stream=None): try: proto, dummy, host, path = url.split("/", 3) except ValueError: proto, dummy, host = url.split("/", 2) path = "" if proto == "http:": port = 80 elif proto == "https:": import ussl port = 443 else: raise ValueError("Unsupported protocol: " + proto) if ":" in host: host, port = host.split(":", 1) port = int(port) ai = usocket.getaddrinfo(host, port, 0, usocket.SOCK_STREAM) ai = ai[0] s = usocket.socket(ai[0], ai[1], ai[2]) try: s.connect(ai[-1]) if proto == "https:": s = ussl.wrap_socket(s, server_hostname=host) s.write(b"%s /%s HTTP/1.0\r\n" % (method, path)) if not "Host" in headers: s.write(b"Host: %s\r\n" % host) # Iterate over keys to avoid tuple alloc for k in headers: s.write(k.encode() + b"\r\n") if json is not None: assert data is None import ujson data = ujson.dumps(json) s.write(b"Content-Type: application/json\r\n") if data: s.write(b"Content-Length: %d\r\n" % len(data)) s.write(b"\r\n") if data: s.write(data) l = s.readline() #print(l) l = l.split(None, 2) status = int(l[1]) reason = "" if len(l) > 2: reason = l[2].rstrip() while True: l = s.readline() if not l or l == b"\r\n": break #print(l) if l.startswith(b"Transfer-Encoding:"): if b"chunked" in l: raise ValueError("Unsupported " + l) elif l.startswith(b"Location:") and not 200 <= status <= 299: raise NotImplementedError("Redirects not yet supported") except OSError: s.close() raise resp = Response(s) resp.status_code = status resp.reason = reason return resp
def postBodyFromFile(url, headers, fileName): try: proto, dummy, host, path = url.split("/", 3) except ValueError: proto, dummy, host = url.split("/", 2) path = "" if proto == "https:": port = 443 else: raise ValueError("Unsupported protocol: " + proto) if ":" in host: host, port = host.split(":", 1) port = int(port) ai = usocket.getaddrinfo(host, port, 0, usocket.SOCK_STREAM) ai = ai[0] s = usocket.socket(ai[0], ai[1], ai[2]) try: s.connect(ai[-1]) s = wrap_socket(s, server_hostname=host) s.write(b"%s /%s HTTP/1.0\r\n" % ('POST', path)) if not "Host" in headers: s.write(b"Host: %s\r\n" % host) # Iterate over keys to avoid tuple alloc for k in headers: s.write(k) s.write(b": ") s.write(headers[k]) s.write(b"\r\n") size = mylib.getFileSize(fileName) if size is None: raise ValueError("FileSize is None") s.write(b"Content-Length: %d\r\n" % size) s.write(b"\r\n") with open(fileName, 'rb') as fp: while True: size = s.write(fp.read(BUFSIZE)) if size == 0: break l = s.readline() l = l.split(None, 2) status = int(l[1]) reason = "" if len(l) > 2: reason = l[2].rstrip() while True: l = s.readline() if not l or l == b"\r\n": break if l.startswith(b"Transfer-Encoding:"): if b"chunked" in l: raise ValueError("Unsupported " + l) elif l.startswith(b"Location:") and not 200 <= status <= 299: raise NotImplementedError("Redirects not yet supported") except OSError: s.close() raise resp = Response(s) resp.status_code = status resp.reason = reason return resp
import network import usocket as socket lan = network.LAN() while True: if (lan.ifconfig("dhcp") == True): break print(lan.ifconfig()) url = 'http://micropython.org/ks/test.html' _, _, host, path = url.split('/', 3) addr = socket.getaddrinfo(host, 80)[0][-1] s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.connect(addr) #nuvoton proxy server #s.connect(("10.254.239.51", 8080)) s.send(bytes('GET /%s HTTP/1.0\r\nHost: %s\r\n\r\n' % (path, host), 'utf8')) while True: data = s.recv(100) if data: print(str(data, 'utf8'), end='') else: break s.close()
def connect_SOC(self, host): self.cli_soc = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.cli_soc.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) soc_addr = socket.getaddrinfo(host, 8005)[0][-1] self.cli_soc.connect(soc_addr)
def urlopen(url, user=None, passwd=None, data=None, method="GET"): if data is not None and method == "GET": method = "POST" try: proto, dummy, host, path = url.split("/", 3) except ValueError: proto, dummy, host = url.split("/", 2) path = "" if proto == "http:": port = 80 elif proto == "https:": import ussl port = 443 else: raise ValueError("Unsupported protocol: " + proto) token = '' if (user is not None and passwd is not None): token = ubinascii.b2a_base64(b'%s:%s' % (user, passwd)).strip() #print(token) if ":" in host: host, port = host.split(":", 1) port = int(port) #print("HOST:", host, "PORT", port) ai = usocket.getaddrinfo(host, port) addr = ai[0][4] s = usocket.socket() s.connect(addr) if proto == "https:": s = ussl.wrap_socket(s) s.write(method) s.write(b" /") s.write(path) s.write(b" HTTP/1.0\r\nHost: ") s.write(host) s.write(b"\r\n") if (token): s.write(b"Authorization: Basic ") s.write(token) s.write(b"\r\n") s.write(b"Content-Type: application/json\r\n") if data: s.write(b"Content-Length: ") s.write(str(len(data))) s.write(b"\r\n") s.write(b"\r\n") if data: s.write(data) rcv_data = '' while True: newdata = s.recv(100) if newdata: rcv_data = rcv_data + newdata.decode("utf-8") else: break s.close() return rcv_data
# client_w.py Test poll object's response to two fault conditions under Unix and ESP8266 import usocket as socket import uasyncio as asyncio import uselect as select server_addr = socket.getaddrinfo('192.168.0.35', 8123)[0][-1] s = socket.socket() s.connect(server_addr) # Expect OSError if server down poller = select.poll() poller.register(s, select.POLLOUT) s.setblocking(False) success = False async def run(): global success ok = True try: while ok: res = poller.ipoll(10) for sock, ev in res: if ev & select.POLLOUT: r = sock.send(b'0123456789\n') print(ev, r) # On ESP8266 if another task closes the socket the poll object # never triggers. uasyncio expects it to trigger with POLLHUP or # (POLLOUT & POLLERR or POLLOUT & POLLHUP) # If server fails gets OSError on both platforms. else: # But on Unix socket closure produces ev == 32 print('Terminating event:', ev) # What is 32?? ok = False break
def request(method,url,data=None,json=None): try: proto, dummy, host, path = url.split('/', 3) except ValueError: proto, dummy, host = url.split('/', 2) path = "" if proto == 'http:': port = 80 elif proto == 'https:': import ussl port = 443 else: raise ValueError('Unsupported protocol: '+ proto) if ':' in host: host, port = host.split(':', 1) port = int(port) addr = usocket.getaddrinfo(host, port)[0][-1] s = usocket.socket() s.connect(addr) if proto == "https:": s = ussl.wrap_socket(s) s.write(b'%s /%s HTTP/1.0\r\nHost: %s\r\n' %(method,path,host)) if json is not None: assert data is None import ujson data = ujson.dumps(json) if data: s.write(b"Content-Length: %s\r\n" % str(len(data))) if json is not None: s.write(b"Content-Type: application/json\r\n") # print('json') pass elif data is not None: s.write(b"Content-Type: text/plain\r\n") # print('plain') s.write(b"\r\n") if data: s.write(data) # print(data) l = s.readline() protover, status, msg = l.split(None, 2) status = int(status) print(protover, status, msg) # while True: # l = s.readline() # if not l or l == b"\r\n": # break # #print(l) # if l.startswith(b"Transfer-Encoding:"): # if b"chunked" in l: # raise ValueError("Unsupported " + l) # elif l.startswith(b"Location:"): # raise NotImplementedError("Redirects not yet supported") # # resp = Response(s) # resp.status_code = status # resp.reason = msg.rstrip() time.sleep_ms(1) s.close()
def __init__( self, url, method, params={}, data={}, headers={}, cookies={}, auth=(), timeout=5, ): self.status_code = 0 self.headers = {} self.text = "" self.url = url [scheme, host, port, path, query_string] = urlparse(self.url) if auth and isinstance(auth, tuple) and len(auth) == 2: headers["Authorization"] = "Basic %s" % (b64encode( "%s:%s" % (auth[0], auth[1]))) if scheme == "http": addr = socket.getaddrinfo(host, int(port))[0][-1] s = socket.socket() s.settimeout(5) s.connect(addr) else: sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM, socket.IPPROTO_SEC) sock.settimeout(5) s = ssl.wrap_socket(sock) s.connect(socket.getaddrinfo(host, port)[0][4]) if params: enc_params = urlencode(params) path = path + "?" + enc_params.strip() header_string = "Host: %s\r\n" % host if headers: for k, v in headers.items(): header_string += "%s: %s\r\n" % (k, v) if cookies: for k, v in cookies.items(): header_string += "Cookie: %s=%s\r\n" % (k, quote_plus(v)) request = b"%s %s HTTP/1.0\r\n%s" % (method, path, header_string) if data: if isinstance(data, dict): enc_data = urlencode(data) if not headers.get("Content-Type"): request += "Content-Type: application/x-www-form-urlencoded\r\n" request += "Content-Length: %s\r\n\r\n%s\r\n" % ( len(enc_data), enc_data, ) elif isinstance(data, bytearray): request += b"Content-Length: %s\r\n\r\n%s\r\n" % (len(data), bytes(data)) elif isinstance(data, (bytes, str)): request += b"Content-Length: %s\r\n\r\n%s\r\n" % (len(data), data) else: raise Exception("data must by bytes, str, or bytearray") request += b"\r\n" s.send(request) while 1: recv = s.recv(1024) if len(recv) == 0: break self.text += recv.decode() s.close() self._parse_result()
def request(method, url, json=None, textMsg=None, binary=None, timeout=None, headers=None, contentType='application/text', debug=False): if debug: print(method, url) urlparts = url.split('/', 3) proto = urlparts[0] host = urlparts[2] urlpath = '' if len(urlparts) < 4 else urlparts[3] if proto == 'http:': port = 80 elif proto == 'https:': port = 443 else: raise OSError('Unsupported protocol: %s' % proto[:-1]) if ':' in host: host, port = host.split(':') port = int(port) if json is not None: content = ujson.dumps(json) content_type = CONTENT_TYPE_JSON elif textMsg is not None: content = textMsg content_type = contentType elif binary is not None: content = binary content_type = CONTENT_TYPE_BINARY else: content = None ai = usocket.getaddrinfo(host, port) addr = ai[0][4] #sock = connect(proto, addr, timeout) try: sock = connect(proto, addr, timeout) except OSError as oerr: print("OSError : %s" % oerr) raise oerr # try: # sock = connect(proto, addr, timeout) # except OSError as oerr: # print (oerr) # raise oerr # # DUMP TO CONSOLE DEBUG http_verb = '%s /%s HTTP/1.1' % (method, urlpath) http_content_type = '' if content is None else 'Content-Type: %s' % content_type http_host = 'Host: %s' % (host) http_headers = '' if headers is not None: http_headers = ''.join(': '.join(_) for _ in headers.items()) http_content_length = 'Content-Length: %s' % (len(content) if not content is None else 0) if content is None: sending = '{0}\r\n{1}\r\n{2}\r\n\r\n'.format(http_verb, http_host, http_headers) else: sending = '{0}\r\n{1}\r\n{2}\r\n{3}\r\n{4}\r\n\r\n'.format( http_verb, http_content_type, http_host, http_content_length, http_headers) if debug: print(sending) if not content is None: print(content) # START SENDING sock.send(sending) if not content is None: sock.send(content) l = sock.readline() if debug: print(l) protover, status, msg = l.split(None, 2) # Skip headers l = sock.readline() if debug: print(l) contentlength = 0 while l != b'\r\n': l = sock.readline() if debug: print(l) if l.startswith(b'Content-Length:'): dummy, contentlength = l.split(None, 1) if debug: print("Body size = ", int(contentlength)) if l.startswith(b'Transfer-Encoding: chunked'): if contentlength == 0: contentlength = -1 if debug: print("CHUNKED DATA !!") return Response(int(status), msg, sock, int(contentlength))
# Simple NTP client import time, pyb, network, usocket # AP info SSID = '' # Network SSID KEY = '' # Network key # Init wlan module and connect to network wlan = network.WINC() wlan.connect(SSID, key=KEY, security=wlan.WPA_PSK) # We should have a valid IP now via DHCP print(wlan.ifconfig()) # Get addr info via DNS addr = usocket.getaddrinfo("www.google.com", 80)[0][4] # Create a new socket and connect to addr client = usocket.socket(usocket.AF_INET, usocket.SOCK_STREAM) client.connect(addr) # Set timeout to 1s client.settimeout(1.0) # Send HTTP request and recv response client.send("GET / HTTP/1.0\r\n\r\n") print(client.recv(1024)) # Close socket client.close()
def __init__(self, client_id, server, port=1883): self.client_id = client_id self.sock = None self.addr = socket.getaddrinfo(server, port)[0][-1] self.pid = 0 self.cb = None
def start(self): """ Starts the LoRaWAN nano gateway. """ pycom.heartbeat(False) self._log('Starting LoRaWAN nano gateway with id: {}', self.id) # # setup WiFi as a station and connect # self.wlan = WLAN(mode=WLAN.STA) # self._connect_to_wifi() # setup LTE CATM1 connection self.lte = LTE(carrier="verizon") self._connect_to_LTE() # get a time sync self._log('Syncing time with {} ...', self.ntp_server) self.rtc.ntp_sync(self.ntp_server, update_period=self.ntp_period) while not self.rtc.synced(): utime.sleep_ms(50) self._log("RTC NTP sync complete") # get the server IP and create an UDP socket self.server_ip = usocket.getaddrinfo(self.server, self.port)[0][-1] self._log('Opening UDP socket to {} ({}) port {}...', self.server, self.server_ip[0], self.server_ip[1]) self.sock = usocket.socket(usocket.AF_INET, usocket.SOCK_DGRAM, usocket.IPPROTO_UDP) self.sock.setsockopt(usocket.SOL_SOCKET, usocket.SO_REUSEADDR, 1) self.sock.setblocking(False) # push the first time immediatelly self._push_data(self._make_stat_packet()) # create the alarms self.stat_alarm = Timer.Alarm( handler=lambda t: self._push_data(self._make_stat_packet()), s=60, periodic=True) self.pull_alarm = Timer.Alarm(handler=lambda u: self._pull_data(), s=25, periodic=True) # start the UDP receive thread self.udp_stop = False _thread.start_new_thread(self._udp_thread, ()) # initialize the LoRa radio in LORA mode self._log('Setting up the LoRa radio at {} Mhz using {}', self._freq_to_float(self.frequency), self.datarate) self.lora = LoRa(mode=LoRa.LORA, frequency=self.frequency, bandwidth=self.bw, sf=self.sf, preamble=8, coding_rate=LoRa.CODING_4_5, tx_iq=True) # create a raw LoRa socket self.lora_sock = usocket.socket(usocket.AF_LORA, usocket.SOCK_RAW) self.lora_sock.setblocking(False) self.lora_tx_done = False self.lora.callback(trigger=(LoRa.RX_PACKET_EVENT | LoRa.TX_PACKET_EVENT), handler=self._lora_cb) self._log('LoRaWAN nano gateway online')
try: ret = s.read(10) print("read:", ret is None) except OSError as er: dp(er) print("read:", False) # should not raise except ValueError as er: # CPython dp(er) print("read:", er.args[0] == "Read on closed or unwrapped SSL socket.") s.close() else: # fake it... print("connect:", True) if tls: print("wrap:", True) print("read:", True) if __name__ == "__main__": # these tests use a non-existent test IP address, this way the connect takes forever and # we can see EAGAIN/None (https://tools.ietf.org/html/rfc5737) print("--- Plain sockets to nowhere ---") test(socket.getaddrinfo("192.0.2.1", 80)[0][-1], False, False) print("--- SSL sockets to nowhere ---") # this test fails with AXTLS because do_handshake=False blocks on first read/write and # there it times out until the connect is aborted test(socket.getaddrinfo("192.0.2.1", 443)[0][-1], True, False) print("--- Plain sockets ---") test(socket.getaddrinfo("micropython.org", 80)[0][-1], False, True) print("--- SSL sockets ---") test(socket.getaddrinfo("micropython.org", 443)[0][-1], True, True)
state = False # TODO: The doorbell goes high but this button goes low EXPECTED_STATE = 1 IRQ_EDGE = Pin.IRQ_RISING # DOORBELL_TIME = 1000000 # 1s DOORBELL_TIME = 60000 # 60ms DOORBELL_TIMEOUT = 10000000 # 10s IRCCAT_HOST = "10.143.0.12" IRCCAT_PORT = 12345 # IRCCAT_HOST = "192.168.88.251" # IRCCAT_PORT = 8080 IRCCAT_ADDR = usocket.getaddrinfo(IRCCAT_HOST, IRCCAT_PORT)[0][-1] DOORBELL_MESSAGE = "BING BONG! Somebody's at the door!" STARTUP_MESSAGE = "The doorbell has entered the building" STARTUP_TIME_MS = 1000 # 1s # STARTUP_TIME_MS = 10000 # 10s in_startup = True def startupify(_): global in_startup in_startup = False print("Started up")
def request(method, url, data=None, json=None, headers={}, stream=None, params=None, files=None): _headers = {} _headers.update(headers) # url parse try: proto, dummy, host, path = url.split("/", 3) except ValueError: try: proto, dummy, host = url.split("/", 2) except ValueError: raise ValueError("Invalid URL") path = "" if proto == "http:": port = 80 elif proto == "https:": import ussl port = 443 else: raise ValueError("Unsupported protocol: " + proto) if ":" in host: host, port = host.split(":", 1) port = int(port) path = quote(path, safe='?,=,/,&') # if have params,urlencoded to URL if params: from urllib.parse import urlencode path = path + "?" path = path + urlencode(params) ai = usocket.getaddrinfo(host, port) addr = ai[0][4] s = usocket.socket() s.settimeout(5) s.connect(addr) if proto == "https:": s = ussl.wrap_socket(s,do_handshake=False) _headers['Host'] = host if data is not None: if isinstance(data, tuple): data = dict(data) if isinstance(data, dict): if not 'ujson' in globals(): import ujson data = urlencode(data) _headers['Content-Type'] = 'application/x-www-form-urlencoded;charset=utf-8' if json is not None: assert data is None if not 'ujson' in globals(): import ujson _headers['Content-Type'] = 'application/json' data = ujson.dumps(json) if files: boundary = '----WebKitFormBoundary'+hex(int(time.time())) _headers['Content-Type'] = "multipart/form-data; boundary=%s" % boundary _headers['Connection'] = "keep-alives" name = list(files.keys())[0] file_dir = files.get(name)[0] file_type = files.get(name)[1] file_size = os.stat(file_dir)[6] file_name = file_dir.split('/')[-1] file = open(file_dir, 'rb') content_disposition = b'Content-Disposition: form-data; name="%s"; filename="%s"\r\n' % ( name, file_name) content_type = b"Content-Type: %s\r\n" % file_type content_length = len(boundary)+4+len(content_disposition) + \ len(content_type)+2+file_size+len(boundary)+8 _headers['Content-Length'] = str(content_length) if data: _headers['Content-Length'] = str(len(data)) # Send Request Header s.write(b"%s /%s HTTP/1.0\r\n" % (method, path)) for k, v in _headers.items(): s.write('%s: %s\r\n' % (k, v)) # print('%s: %s\r\n' % (k, v), end='') # Partition s.write(b"\r\n") # Body if data: s.write(data) if files: # first boundary s.write(b"--%s\r\n" % boundary) s.write(content_disposition) s.write(content_type) s.write(b"\r\n") # file data for hex while True: _read = memoryview(file.read(1024*3)) if _read != b'': s.write(_read) else: break # end boundary s.write(b"\r\n--%s--\r\n" % boundary) file.close() l = s.readline() protover, status, msg = l.split(None, 2) status = int(status) #print(protover, status, msg) while True: l = s.readline() if not l or l == b"\r\n": break #print(l) if l.startswith(b"Transfer-Encoding:"): if b"chunked" in l: raise ValueError("Unsupported " + l) elif l.startswith(b"Location:") and not 200 <= status <= 299: raise NotImplementedError("Redirects not yet supported") resp = Response(s) resp.status_code = status resp.reason = msg.rstrip() return resp
wlan = network.WLAN(network.STA_IF) wlan.active(True) wlan.scan() if not wlan.isconnected(): import pwd wlan.connect(pwd.ssid, pwd.pwd) # connect to an AP while not wlan.isconnected(): pass print('network config:', wlan.ifconfig(),"\tconnected!") host_ip = "192.168.100.102" print("connecting to server with ip", host_ip,"...") #open socket import usocket sock = usocket.socket() addr = usocket.getaddrinfo(host_ip, 8082)[0][-1] sock.connect(addr) print("compressing data into json and sending it...") import ujson payload = ujson.dumps( [d.temperature(), d.humidity(), sensor.read()] ) sock.send(str(payload)) sock.close() print("\tYAY! success! sent:\n", payload) #bye bye print("going to deep sleep") # time.sleep(3) print("Zzzz.... execution took: ", time.ticks_diff(time.ticks_ms(), start))
def request(method, url, data=None, json=None, headers={}, stream=None, parse_headers=True): redir_cnt = 1 if json is not None: assert data is None import ujson data = ujson.dumps(json) while True: try: proto, dummy, host, path = url.split("/", 3) except ValueError: proto, dummy, host = url.split("/", 2) path = "" if proto == "http:": port = 80 elif proto == "https:": import ussl port = 443 else: raise ValueError("Unsupported protocol: " + proto) if ":" in host: host, port = host.split(":", 1) port = int(port) ai = usocket.getaddrinfo(host, port, 0, usocket.SOCK_STREAM) ai = ai[0] resp_d = None if parse_headers is not False: resp_d = {} s = usocket.socket(ai[0], ai[1], ai[2]) try: s.connect(ai[-1]) if proto == "https:": s = ussl.wrap_socket(s, server_hostname=host) s.write(b"%s /%s HTTP/1.0\r\n" % (method, path)) if not "Host" in headers: s.write(b"Host: %s\r\n" % host) # Iterate over keys to avoid tuple alloc for k in headers: s.write(k) s.write(b": ") s.write(headers[k]) s.write(b"\r\n") if json is not None: s.write(b"Content-Type: application/json\r\n") if data: s.write(b"Content-Length: %d\r\n" % len(data)) s.write(b"Connection: close\r\n\r\n") if data: s.write(data) l = s.readline() #print(l) l = l.split(None, 2) status = int(l[1]) reason = "" if len(l) > 2: reason = l[2].rstrip() while True: l = s.readline() if not l or l == b"\r\n": break #print(l) if l.startswith(b"Transfer-Encoding:"): if b"chunked" in l: raise ValueError("Unsupported " + l) elif l.startswith(b"Location:") and 300 <= status <= 399: if not redir_cnt: raise ValueError("Too many redirects") redir_cnt -= 1 url = l[9:].decode().strip() #print("redir to:", url) status = 300 break if parse_headers is False: pass elif parse_headers is True: l = l.decode() k, v = l.split(":", 1) resp_d[k] = v.strip() else: parse_headers(l, resp_d) except OSError: s.close() raise if status != 300: break resp = Response(s) resp.status_code = status resp.reason = reason if resp_d is not None: resp.headers = resp_d return resp