Python usocket.getaddrinfo() Examples

The following are 30 code examples of usocket.getaddrinfo(). 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 vote down vote up
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: sock_nonblock.py    From micropython-async with MIT License 6 votes vote down vote up
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 #3
Source File: mqtt.py    From upython-aq-monitor with MIT License 6 votes vote down vote up
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: server.py    From micropython-samples with MIT License 6 votes vote down vote up
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 #5
Source File: __init__.py    From microdot with MIT License 6 votes vote down vote up
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 #6
Source File: __init__.py    From micropython-samples with MIT License 6 votes vote down vote up
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 #7
Source File: microdot.py    From microdot with MIT License 6 votes vote down vote up
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 #8
Source File: umqtt.py    From pyaiot with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
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 #9
Source File: __init__.py    From pysmartnode with MIT License 6 votes vote down vote up
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 #10
Source File: userver.py    From micropython-async with MIT License 6 votes vote down vote up
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: simple.py    From UIFlow-Code with GNU General Public License v3.0 6 votes vote down vote up
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 #12
Source File: __init__.py    From microhomie with MIT License 6 votes vote down vote up
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 #13
Source File: __init__.py    From uPyCam with Apache License 2.0 6 votes vote down vote up
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: uclient.py    From micropython-async with MIT License 5 votes vote down vote up
def run():
    sock = socket.socket()
    def close():
        sock.close()
        print('Server disconnect.')
    try:
        serv = socket.getaddrinfo(server, port)[0][-1]
        sock.connect(serv)
    except OSError as e:
        print('Cannot connect to {} on port {}'.format(server, port))
        sock.close()
        return
    while True:
        sreader = asyncio.StreamReader(sock)
        swriter = asyncio.StreamWriter(sock, {})
        data = ['value', 1]
        while True:
            try:
                await swriter.awrite('{}\n'.format(ujson.dumps(data)))
                res = await sreader.readline()
            except OSError:
                close()
                return
            try:
                print('Received', ujson.loads(res))
            except ValueError:
                close()
                return
            await asyncio.sleep(2)
            data[1] += 1 
Example #15
Source File: mqtt_as.py    From microhomie with MIT License 5 votes vote down vote up
def connect(self):
        if not self._has_connected:
            await self.wifi_connect()  # On 1st call, caller handles error
            # Note this blocks if DNS lookup occurs. Do it once to prevent
            # blocking during later internet outage:
            self._addr = socket.getaddrinfo(self.server, self.port)[0][-1]
        self._in_connect = True  # Disable low level ._isconnected check
        clean = self._clean if self._has_connected else self._clean_init
        try:
            await self._connect(clean)
        except Exception:
            self.close()
            raise
        self.rcv_pids.clear()
        # If we get here without error broker/LAN must be up.
        self._isconnected = True
        self._in_connect = False  # Low level code can now check connectivity.
        loop = asyncio.get_event_loop()
        loop.create_task(self._wifi_handler(True))  # User handler.
        if not self._has_connected:
            self._has_connected = True  # Use normal clean flag on reconnect.
            loop.create_task(
                self._keep_connected())  # Runs forever unless user issues .disconnect()

        loop.create_task(self._handle_msg())  # Tasks quit on connection fail.
        loop.create_task(self._keep_alive())
        if self.DEBUG:
            loop.create_task(self._memory())
        loop.create_task(self._connect_handler(self))  # User handler.

    # Launched by .connect(). Runs until connectivity fails. Checks for and
    # handles incoming messages. 
Example #16
Source File: __init__.py    From micropython-async with MIT License 5 votes vote down vote up
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 #17
Source File: __init__.py    From pysmartnode with MIT License 5 votes vote down vote up
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 #18
Source File: blynklib_mp.py    From lib-python with MIT License 5 votes vote down vote up
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 #19
Source File: __init__.py    From microhomie with MIT License 5 votes vote down vote up
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 #20
Source File: __init__.py    From uPyCam with Apache License 2.0 5 votes vote down vote up
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 #21
Source File: __init__.py    From microdot with MIT License 5 votes vote down vote up
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 #22
Source File: client.py    From esp8266 with BSD 2-Clause "Simplified" License 5 votes vote down vote up
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 #23
Source File: __init__.py    From micropython-samples with MIT License 5 votes vote down vote up
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 #24
Source File: client_w.py    From micropython-samples with MIT License 5 votes vote down vote up
def __init__(self, timeout, loop):
        self.timeout = timeout
        self.led = Pin(2, Pin.OUT, value = 1)
        self._sta_if = network.WLAN(network.STA_IF)
        self._sta_if.active(True)
        self.server = socket.getaddrinfo(SERVER, PORT)[0][-1]  # server read
        self.evfail = asyn.Event(100)
        self.lock = asyn.Lock(100)  # 100ms pause
        self.connects = 0  # Connect count
        self.sock = None
        loop.create_task(self._run(loop))

    # Make an attempt to connect to WiFi. May not succeed. 
Example #25
Source File: __init__.py    From micropython-samples with MIT License 5 votes vote down vote up
def _serve(self, cb, host, port, backlog):
        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)
        s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        s.bind(ai[-1])
        s.listen(backlog)
        self.task = cur_task
        # Accept incoming connections
        while True:
            try:
                yield _io_queue.queue_read(s)
            except CancelledError:
                # Shutdown server
                s.close()
                return
            s2, addr = s.accept()
            s2.setblocking(False)
            s2s = Stream(s2, {'peername': addr})
            create_task(cb(s2s, s2s))

# Helper function to start a TCP stream server, running as a new task
# TODO could use an accept-callback on socket read activity instead of creating a task 
Example #26
Source File: server.py    From micropython-iot with MIT License 5 votes vote down vote up
def run(expected, verbose=False, port=8123, timeout=2000):
    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(len(expected) + 2)
    verbose and print('Awaiting connection.', port)
    poller = select.poll()
    poller.register(s_sock, select.POLLIN)
    to_secs = timeout / 1000  # ms -> secs
    while True:
        res = poller.poll(1)  # 1ms block
        if res:  # Only s_sock is polled
            c_sock, _ = s_sock.accept()  # get client socket
            c_sock.setblocking(False)
            try:
                data = await _readid(c_sock, to_secs)
            except OSError:
                c_sock.close()
            else:
                Connection.go(to_secs, data, verbose, c_sock, s_sock,
                              expected)
        await asyncio.sleep(0.2)


# 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 .sock to None (.status() == False). 
Example #27
Source File: ntptime.py    From micropy-cli with MIT License 5 votes vote down vote up
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

# There's currently no timezone support in MicroPython, so
# utime.localtime() will return UTC time (as if it was .gmtime()) 
Example #28
Source File: ntptime.py    From micropy-cli with MIT License 5 votes vote down vote up
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

# There's currently no timezone support in MicroPython, so
# utime.localtime() will return UTC time (as if it was .gmtime()) 
Example #29
Source File: ntptime.py    From micropy-cli with MIT License 5 votes vote down vote up
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

# There's currently no timezone support in MicroPython, so
# utime.localtime() will return UTC time (as if it was .gmtime()) 
Example #30
Source File: ntptime.py    From micropy-cli with MIT License 5 votes vote down vote up
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

# There's currently no timezone support in MicroPython, so
# utime.localtime() will return UTC time (as if it was .gmtime())