Skip to content

Supported socket timeout #237

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 14 additions & 1 deletion umqtt.simple/umqtt/simple.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import usocket as socket
import ustruct as struct
from ubinascii import hexlify
import uselect

class MQTTException(Exception):
pass
Expand All @@ -26,6 +27,7 @@ def __init__(self, client_id, server, port=0, user=None, password=None, keepaliv
self.lw_msg = None
self.lw_qos = 0
self.lw_retain = False
self.poller = uselect.poll()

def _send_str(self, s):
self.sock.write(struct.pack("!H", len(s)))
Expand All @@ -52,7 +54,7 @@ def set_last_will(self, topic, msg, retain=False, qos=0):
self.lw_qos = qos
self.lw_retain = retain

def connect(self, clean_session=True):
def connect(self, clean_session=True, timeout=None):
self.sock = socket.socket()
addr = socket.getaddrinfo(self.server, self.port)[0][-1]
self.sock.connect(addr)
Expand Down Expand Up @@ -83,6 +85,11 @@ def connect(self, clean_session=True):
i += 1
premsg[i] = sz

if timeout: # Checking output availability
self.poller.register(self.sock, uselect.POLLOUT)
if not poller.poll(timeout):
raise OSError("Connection request timed out")

self.sock.write(premsg, i + 2)
self.sock.write(msg)
#print(hex(len(msg)), hexlify(msg, ":"))
Expand All @@ -93,6 +100,12 @@ def connect(self, clean_session=True):
if self.user is not None:
self._send_str(self.user)
self._send_str(self.pswd)

if timeout: # Checking input availability
self.poller.modify(self.sock, uselect.POLLIN)
if not poller.poll(timeout):
raise OSError("Connection response timed out")

resp = self.sock.read(4)
assert resp[0] == 0x20 and resp[1] == 0x02
if resp[3] != 0:
Expand Down