Skip to content

umqtt: Make umqtt socket non-blocking by default. #33

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

Merged
merged 1 commit into from
Oct 21, 2022
Merged
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
14 changes: 9 additions & 5 deletions arduino_iot_cloud/umqtt.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,10 +27,12 @@
import usocket as socket
import ustruct as struct
import ulogging as logging
import uselect as select
except ImportError:
import socket
import struct
import logging
import select
from arduino_iot_cloud.ussl import wrap_socket


Expand Down Expand Up @@ -90,7 +92,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=5.0):
addr = socket.getaddrinfo(self.server, self.port)[0][-1]

if self.sock is not None:
Expand All @@ -99,11 +101,13 @@ def connect(self, clean_session=True):

try:
self.sock = socket.socket()
self.sock.settimeout(timeout)
self.sock = wrap_socket(self.sock, **self.ssl_params)
self.sock.connect(addr)
except Exception:
self.sock.close()
self.sock = socket.socket()
self.sock.settimeout(timeout)
self.sock.connect(addr)
self.sock = wrap_socket(self.sock, **self.ssl_params)

Expand Down Expand Up @@ -214,9 +218,8 @@ def subscribe(self, topic, qos=0):
# messages processed internally.
def wait_msg(self):
res = self.sock.read(1)
if res == b"" or res is None:
if res is None or res == b"":
return None
self.sock.setblocking(True)
if res == b"\xd0": # PINGRESP
sz = self.sock.read(1)[0]
assert sz == 0
Expand Down Expand Up @@ -246,5 +249,6 @@ def wait_msg(self):
# If not, returns immediately with None. Otherwise, does
# the same processing as wait_msg.
def check_msg(self):
self.sock.setblocking(False)
return self.wait_msg()
r, w, e = select.select([self.sock], [], [], 0.05)
if (len(r)):
return self.wait_msg()