Python usocket.socket() Examples
The following are 30
code examples of usocket.socket().
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example.
You may also want to check out all available functions/classes of the module
usocket
, or try the search function
.
Example #1
Source File: thingspeak.py From Micropython with MIT License | 9 votes |
def main(use_stream=True): while True: d.measure() data = b"api_key="+ API_KEY + "&field1=" + str(d.temperature()) + "&field2=" + str(d.humidity()) s = _socket.socket() ai = _socket.getaddrinfo(HOST, 443) addr = ai[0][-1] s.connect(addr) s = ssl.wrap_socket(s) s.write("POST /update HTTP/1.0\r\n") s.write("Host: " + HOST + "\r\n") s.write("Content-Length: " + str(len(data)) + "\r\n\r\n") s.write(data) print(s.read(128)) s.close() time.sleep(60)
Example #2
Source File: main.py From uPyEcho with Apache License 2.0 | 7 votes |
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])
Example #3
Source File: mqtt.py From upython-aq-monitor with MIT License | 6 votes |
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 self.lw_topic = None self.lw_msg = None self.lw_qos = 0 self.lw_retain = False
Example #4
Source File: simple.py From UIFlow-Code with GNU General Public License v3.0 | 6 votes |
def socket_connect(self): if self.sock is not None: self.sock.close() try: self.sock = socket.socket() addr = socket.getaddrinfo(self.server, self.port) if addr == []: if self.addr_save: try: self.socket_connect(self.addr_save) return except: raise OSError('addr get fail') addr = addr[0][-1] self.addr_save = addr self.sock.connect(addr) return True except OSError: return False
Example #5
Source File: mqtt_as.py From micropython-mqtt with MIT License | 6 votes |
def wan_ok(self, packet=b'$\x1a\x01\x00\x00\x01\x00\x00\x00\x00\x00\x00\x03www\x06google\x03com\x00\x00\x01\x00\x01'): if not self.isconnected(): # WiFi is down return False length = 32 # DNS query and response packet size s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) s.setblocking(False) s.connect(('8.8.8.8', 53)) await asyncio.sleep(1) try: await self._as_write(packet, sock=s) await asyncio.sleep(2) res = await self._as_read(length, s) if len(res) == length: return True # DNS response size OK except OSError: # Timeout on read: no connectivity. return False finally: s.close() return False
Example #6
Source File: __init__.py From micropython-async with MIT License | 6 votes |
def readexactly(self, n): buf = b"" while n: yield IORead(self.polls) # socket may become unreadable inbetween # subsequent readline may return None res = self.ios.read(n) # returns none if socket not readable vs no data b'' if res is None: if DEBUG and __debug__: log.debug('WARNING: socket write returned type(None)') # socket may be in HUP or ERR state, so loop back ask poller continue else: if not res: # All done break buf += res n -= len(res) yield IOReadDone(self.polls) return buf
Example #7
Source File: sock_nonblock.py From micropython-async with MIT License | 6 votes |
def __init__(self, server, port): # On ESP32 need to submit WiFi credentials self._sta_if = network.WLAN(network.STA_IF) self._sta_if.active(True) # Note that the following blocks, potentially for seconds, owing to DNS lookup self._addr = socket.getaddrinfo(server, port)[0][-1] self._sock = socket.socket() self._sock.setblocking(False) try: self._sock.connect(addr) except OSError as e: if e.args[0] not in BUSY_ERRORS: raise if ESP32: # Revolting kludge :-( loop = asyncio.get_event_loop() loop.create_task(self._idle_task())
Example #8
Source File: simple.py From UIFlow-Code with GNU General Public License v3.0 | 6 votes |
def subscribe(self, topic, qos=0): assert self.cb is not None, "Subscribe callback is not set" self.sock.setblocking(True) pkt = bytearray(b"\x82\0\0\0") self.pid += 1 struct.pack_into("!BH", pkt, 1, 2 + 2 + len(topic) + 1, self.pid) #print(hex(len(pkt)), hexlify(pkt, ":")) self.sock.write(pkt) self._send_str(topic) self.sock.write(qos.to_bytes(1, "little")) # print("simple --> wait socket msg") while 1: op = self.wait_msg() if op == 0x90: resp = self.sock.read(4) #print(resp) assert resp[1] == pkt[2] and resp[2] == pkt[3] if resp[3] == 0x80: raise MQTTException(resp[3]) # print("simple --> wait socket finish") return
Example #9
Source File: __init__.py From micropython-async with MIT License | 6 votes |
def readline(self): if DEBUG and __debug__: log.debug("StreamReader.readline()") buf = b"" while True: yield IORead(self.polls) # socket may become unreadable inbetween # subsequent readline may return None res = self.ios.readline() if res is None: if DEBUG and __debug__: log.debug('WARNING: socket read returned type(None)') # socket may be in HUP or ERR state, so loop back and ask poller continue else: if not res: break buf += res if buf[-1] == 0x0a: break if DEBUG and __debug__: log.debug("StreamReader.readline(): %s", buf) yield IOReadDone(self.polls) return buf
Example #10
Source File: userver.py From micropython-async with MIT License | 6 votes |
def run(self, loop, port=8123): addr = socket.getaddrinfo('0.0.0.0', port, 0, socket.SOCK_STREAM)[0][-1] s_sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # server socket s_sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) s_sock.bind(addr) s_sock.listen(5) self.socks = [s_sock] # List of current sockets for .close() print('Awaiting connection on port', port) poller = select.poll() poller.register(s_sock, select.POLLIN) client_id = 1 # For user feedback while True: res = poller.poll(1) # 1ms block if res: # Only s_sock is polled c_sock, _ = s_sock.accept() # get client socket loop.create_task(self.run_client(c_sock, client_id)) client_id += 1 await asyncio.sleep_ms(200)
Example #11
Source File: __init__.py From uPyCam with Apache License 2.0 | 6 votes |
def start_server(client_coro, host, port, backlog=10): if DEBUG and __debug__: log.debug("start_server(%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) s.setsockopt(_socket.SOL_SOCKET, _socket.SO_REUSEADDR, 1) s.bind(ai[-1]) s.listen(backlog) while True: if DEBUG and __debug__: log.debug("start_server: Before accept") yield IORead(s) if DEBUG and __debug__: log.debug("start_server: After iowait") s2, client_addr = s.accept() s2.setblocking(False) if DEBUG and __debug__: log.debug("start_server: After accept: %s", s2) extra = {"peername": client_addr} yield client_coro(StreamReader(s2), StreamWriter(s2, extra))
Example #12
Source File: umqtt.py From pyaiot with BSD 3-Clause "New" or "Revised" License | 6 votes |
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 self.lw_topic = None self.lw_msg = None self.lw_qos = 0 self.lw_retain = False
Example #13
Source File: __init__.py From pysmartnode with MIT License | 6 votes |
def start_server(client_coro, host, port, backlog=10): if DEBUG and __debug__: log.debug("start_server(%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) s.setsockopt(_socket.SOL_SOCKET, _socket.SO_REUSEADDR, 1) s.bind(ai[-1]) s.listen(backlog) while True: if DEBUG and __debug__: log.debug("start_server: Before accept") yield IORead(s) if DEBUG and __debug__: log.debug("start_server: After iowait") s2, client_addr = s.accept() s2.setblocking(False) if DEBUG and __debug__: log.debug("start_server: After accept: %s", s2) extra = {"peername": client_addr} yield client_coro(StreamReader(s2), StreamWriter(s2, extra))
Example #14
Source File: microdot.py From microdot with MIT License | 6 votes |
def run(self, host='0.0.0.0', port=5000, debug=False): self.debug = debug s = socket.socket() ai = socket.getaddrinfo(host, port) addr = ai[0][-1] if self.debug: # pragma: no cover print('Starting {mode} server on {host}:{port}...'.format( mode=concurrency_mode, host=host, port=port)) s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) s.bind(addr) s.listen(5) while True: sock, addr = s.accept() create_thread(self.dispatch_request, sock, addr)
Example #15
Source File: __init__.py From microdot with MIT License | 6 votes |
def start_server(client_coro, host, port, backlog=10): if DEBUG and __debug__: log.debug("start_server(%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) s.setsockopt(_socket.SOL_SOCKET, _socket.SO_REUSEADDR, 1) s.bind(ai[-1]) s.listen(backlog) while True: if DEBUG and __debug__: log.debug("start_server: Before accept") yield IORead(s) if DEBUG and __debug__: log.debug("start_server: After iowait") s2, client_addr = s.accept() s2.setblocking(False) if DEBUG and __debug__: log.debug("start_server: After accept: %s", s2) extra = {"peername": client_addr} yield client_coro(StreamReader(s2), StreamWriter(s2, extra))
Example #16
Source File: server.py From micropython-iot with MIT License | 6 votes |
def go(cls, to_secs, data, verbose, c_sock, s_sock, expected): client_id, init_str = data.split('\n', 1) verbose and print('Got connection from client', client_id) if cls._server_sock is None: # 1st invocation cls._server_sock = s_sock cls._expected.update(expected) if client_id in cls._conns: # Old client, new socket if cls._conns[client_id].status(): print('Duplicate client {} ignored.'.format(client_id)) c_sock.close() else: # Reconnect after failure cls._conns[client_id]._reconnect(c_sock) else: # New client: instantiate Connection Connection(to_secs, c_sock, client_id, init_str, verbose) # Server-side app waits for a working connection
Example #17
Source File: client.py From esp8266 with BSD 2-Clause "Simplified" License | 6 votes |
def __init__(self, socket, owner) : self.socket = socket self.owner = owner try : line = readline(self.socket) (version, status, _rest) = line.split(None, 2) self.version = version self.status = int(status) self.headers = {} while True: line = readline(self.socket) if not line or line == '\r\n' : break else : (h, v) = HTTPResponse._parse_header(line) self.headers[h] = v except Exception as e : logging.info("Error reading response: {}", e) self.owner.close() raise
Example #18
Source File: client_r.py From micropython-samples with MIT License | 6 votes |
def run(): global success ok = True try: while ok: res = poller.ipoll(10) for sock, ev in res: if ev & select.POLLIN: r = sock.readline() print(ev, r) # A server outage prints 1, b'' forever on ESP8266 or Unix. # If killer closes socket on ESP8266 ev is always 1, # on Unix get ev == 32 # Never see 9 or 17 (base 10) which are the error responses expected by uasyncio # (POLLIN & POLLERR or POLLIN & POLLHUP) else: # The only way I can make it work (on Unix) is to quit on 32 print('Terminating event:', ev) # What is 32?? ok = False break await asyncio.sleep(0) except OSError: print('Got OSError') # Never happens success = True # Detected socket closure or error by OSError or event
Example #19
Source File: client_w.py From micropython-samples with MIT License | 6 votes |
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 await asyncio.sleep(1) await asyncio.sleep(0) except OSError: print('Got OSError') # Happens on ESP8266 if server fails success = True # Detected socket closure or error by OSError or event
Example #20
Source File: __init__.py From micropython-samples with MIT License | 6 votes |
def open_connection(host, port): try: import usocket as socket except ImportError: import socket ai = socket.getaddrinfo(host, port)[0] # TODO this is blocking! s = socket.socket() s.setblocking(False) ss = Stream(s) try: s.connect(ai[-1]) except OSError as er: if er.args[0] != 115: # EINPROGRESS raise er yield _io_queue.queue_write(s) return ss, ss # Class representing a TCP stream server, can be closed and used in "async with"
Example #21
Source File: server.py From micropython-samples with MIT License | 6 votes |
def run(timeout, nconns=10, verbose=False): addr = socket.getaddrinfo('0.0.0.0', PORT, 0, socket.SOCK_STREAM)[0][-1] s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) socks.append(s) s.bind(addr) s.listen(nconns) verbose and print('Awaiting connection.') while True: yield asyncio.IORead(s) # Register socket for polling conn, addr = s.accept() conn.setblocking(False) try: idstr = await readline(conn, timeout) verbose and print('Got connection from client', idstr) socks.append(conn) Connection.go(int(idstr), timeout, verbose, conn) except OSError: if conn is not None: conn.close() # A Connection persists even if client dies (minimise object creation). # If client dies Connection is closed: .close() flags this state by closing its # socket and setting .conn to None (.ok() == False).
Example #22
Source File: __init__.py From micropython-samples with MIT License | 6 votes |
def start_server(client_coro, host, port, backlog=10): if DEBUG and __debug__: log.debug("start_server(%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) s.setsockopt(_socket.SOL_SOCKET, _socket.SO_REUSEADDR, 1) s.bind(ai[-1]) s.listen(backlog) while True: if DEBUG and __debug__: log.debug("start_server: Before accept") yield IORead(s) if DEBUG and __debug__: log.debug("start_server: After iowait") s2, client_addr = s.accept() s2.setblocking(False) if DEBUG and __debug__: log.debug("start_server: After accept: %s", s2) extra = {"peername": client_addr} yield client_coro(StreamReader(s2), StreamWriter(s2, extra))
Example #23
Source File: client.py From esp8266 with BSD 2-Clause "Simplified" License | 5 votes |
def connect(self) : if not self.connected : self.socket.connect(self.addr) self.connected = True
Example #24
Source File: client.py From esp8266 with BSD 2-Clause "Simplified" License | 5 votes |
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()
Example #25
Source File: __init__.py From microhomie with MIT License | 5 votes |
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, {})
Example #26
Source File: mqtt.py From upython-aq-monitor with MIT License | 5 votes |
def connect(self, clean_session=True): self.sock = socket.socket() self.sock.connect(self.addr) if self.ssl: import ussl self.sock = ussl.wrap_socket(self.sock, **self.ssl_params) msg = bytearray(b"\x10\0\0\x04MQTT\x04\x02\0\0") msg[1] = 10 + 2 + len(self.client_id) msg[9] = clean_session << 1 if self.user is not None: msg[1] += 2 + len(self.user) + 2 + len(self.pswd) msg[9] |= 0xC0 if self.keepalive: assert self.keepalive < 65536 msg[10] |= self.keepalive >> 8 msg[11] |= self.keepalive & 0x00FF if self.lw_topic: msg[1] += 2 + len(self.lw_topic) + 2 + len(self.lw_msg) msg[9] |= 0x4 | (self.lw_qos & 0x1) << 3 | (self.lw_qos & 0x2) << 3 msg[9] |= self.lw_retain << 5 self.sock.write(msg) #print(hex(len(msg)), hexlify(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) self._send_str(self.pswd) resp = self.sock.read(4) assert resp[0] == 0x20 and resp[1] == 0x02 if resp[3] != 0: raise MQTTException(resp[3]) return resp[2] & 1
Example #27
Source File: __init__.py From microhomie with MIT License | 5 votes |
def remove_writer(self, sock): if DEBUG and __debug__: log.debug("remove_writer(%s)", sock) try: self.poller.unregister(sock) self.objmap.pop(id(sock), None) except OSError as e: # StreamWriter.awrite() first tries to write to a socket, # and if that succeeds, yield IOWrite may never be called # for that socket, and it will never be added to poller. So, # ignore such error. if e.args[0] != uerrno.ENOENT: raise
Example #28
Source File: client.py From esp8266 with BSD 2-Clause "Simplified" License | 5 votes |
def send(self, data) : self.socket.write(data)
Example #29
Source File: blynklib_mp.py From lib-python with MIT License | 5 votes |
def _get_socket(self): try: self._state = self.CONNECTING self._socket = socket.socket() self._socket.connect(socket.getaddrinfo(self.server, self.port)[0][-1]) self._set_socket_timeout(self.SOCK_TIMEOUT) self.log('Connected to server') except Exception as g_exc: raise BlynkError('Server connection failed: {}'.format(g_exc))
Example #30
Source File: client.py From esp8266 with BSD 2-Clause "Simplified" License | 5 votes |
def putrequest(self, method, url) : self.socket.write(method) self.socket.write(b' /') self.socket.write(url) self.socket.write(b' HTTP/1.0\r\nHost: ') self.socket.write(self.host) self.socket.write(b'\r\n')