Python usocket.SOCK_DGRAM Examples

The following are 11 code examples of usocket.SOCK_DGRAM(). 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: mqtt_as.py    From micropython-mqtt with MIT License 6 votes vote down vote up
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 #2
Source File: mqtt_as.py    From microhomie with MIT License 6 votes vote down vote up
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 #3
Source File: mqtt.py    From micropython-mqtt with MIT License 5 votes vote down vote up
def get_time(self):
        if not self.isconnected():
            return 0
        res = await self.wan_ok()
        if not res:
            return 0  # No internet connectivity.
        # connectivity check is not ideal. Could fail now... FIXME
        # (date(2000, 1, 1) - date(1900, 1, 1)).days * 24*60*60
        NTP_DELTA = 3155673600
        host = "pool.ntp.org"
        NTP_QUERY = bytearray(48)
        NTP_QUERY[0] = 0x1b
        t = 0
        async with self.lock:
            addr = socket.getaddrinfo(host, 123)[0][-1]  # Blocks 15s if no internet
            s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
            s.setblocking(False)
            try:
                s.connect(addr)
                await self._as_write(NTP_QUERY, 48, s)
                await asyncio.sleep(2)
                msg = await self._as_read(48, s)
                val = struct.unpack("!I", msg[40:44])[0]
                t = val - NTP_DELTA
            except OSError:
                pass
            s.close()

        if t < 16 * 365 * 24 * 3600:
            t = 0
        self.dprint('Time received: ', t)
        return t 
Example #4
Source File: ntp.py    From esp32-weather-google-sheets with MIT License 5 votes vote down vote up
def time(host = 'pool.ntp.org', port=123):
    NTP_QUERY = bytearray(48)
    NTP_QUERY[0] = 0x1b
    NTP_DELTA = 2208988800 # 1970-01-01 00:00:00
    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 
Example #5
Source File: main.py    From uPyEcho with Apache License 2.0 5 votes vote down vote up
def init_socket(self):
        ok = True
        self.ip = "239.255.255.250"
        self.port = 1900
        try:
            # This is needed to join a multicast group
            self.mreq = struct.pack("4sl", inet_aton(self.ip), INADDR_ANY)
            # Set up server socket
            self.ssock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
            self.ssock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
            try:
                self.ssock.bind(("", self.port))
            except Exception as e:
                dbg("WARNING: Failed to bind %s:%d: %s", (self.ip, self.port, e))
                ok = False
            try:
                dbg(
                    "IP: "
                    + str(socket.IPPROTO_IP)
                    + " IP_ADD_MEMBERSHIP: "
                    + str(socket.IP_ADD_MEMBERSHIP)
                    + " mreq: "
                    + str(self.mreq)
                )
                self.ssock.setsockopt(
                    socket.IPPROTO_IP, socket.IP_ADD_MEMBERSHIP, self.mreq
                )
            except Exception as e:
                dbg("WARNING: Failed to join multicast group!: " + str(e))
                ok = False

        except Exception as e:
            dbg("Failed to initialize UPnP sockets!")
            return False
        if ok:
            dbg("Listening for UPnP broadcasts") 
Example #6
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 #7
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 #8
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 #9
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 #10
Source File: udp.py    From pysmartnode with MIT License 5 votes vote down vote up
def socket(af=usocket.AF_INET):
    s = usocket.socket(af, usocket.SOCK_DGRAM)
    s.setblocking(False)
    return s 
Example #11
Source File: main.py    From uPyEcho with Apache License 2.0 4 votes vote down vote up
def respond_to_search(self, destination, search_target):
        dbg("Responding to search for %s" % self.get_name())
        date_str = format_timetuple_and_zone(clock.gmtime(), "GMT")
        location_url = self.root_url % {
            "ip_address": self.ip_address,
            "port": self.port,
        }
        message = (
            "HTTP/1.1 200 OK\r\n"
            "CACHE-CONTROL: max-age=86400\r\n"
            "DATE: %s\r\n"
            "EXT:\r\n"
            "LOCATION: %s\r\n"
            'OPT: "http://schemas.upnp.org/upnp/1/0/"; ns=01\r\n'
            "01-NLS: %s\r\n"
            "SERVER: %s\r\n"
            "ST: %s\r\n"
            "USN: uuid:%s::%s\r\n"
            "X-User-Agent: redsonic\r\n\r\n"
            % (
                date_str,
                location_url,
                self.uuid,
                self.server_version,
                search_target,
                self.persistent_uuid,
                search_target,
            )
        )

        if self.other_headers:
            for header in self.other_headers:
                message += "%s\r\n" % header
        message += "\r\n"

        try:
            temp_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
            temp_socket.sendto(message, destination)
            temp_socket.close()
            gc.collect()
        except Exception as e:
            dbg("Got problem to send response %s" % str(e))