Timeout for socket connect?

CircuitPython on hardware including Adafruit's boards, and CircuitPython libraries using Blinka on host computers.

Moderators: adafruit_support_bill, adafruit

Please be positive and constructive with your questions and comments.
Locked
User avatar
ishahak
 
Posts: 19
Joined: Thu Mar 02, 2023 2:21 am

Timeout for socket connect?

Post by ishahak »

On a board based on ESP32-S3, I'm using the following code to connect to a network:

Code: Select all

import socketpool
import wifi
import binascii
import time

ssid='ssssssss'
pw='pppppp'
mac = ':'.join(binascii.hexlify(wifi.radio.mac_address).decode('utf-8')[i:i+2] for i in range(0, 12, 2))
print("My MAC addr:", mac)

print("Available WiFi networks:")
rssi = -100
for network in wifi.radio.start_scanning_networks():
    if str(network.ssid) == ssid and network.rssi > rssi:
        rssi = network.rssi
    print(f'{network.ssid}\trssi:{network.rssi}\t ch:{network.channel}')
wifi.radio.stop_scanning_networks()
ok = False
for i in range(5):
    try:
        print(f"Connecting to {ssid} with rssi={rssi}")
        wifi.radio.connect(ssid, pw)
        ok = True
        break
    except Exception as e:
        print(f'Failed connecting #{i+1}, retrying...')
        time.sleep(0.5)
if ok:
    myip = wifi.radio.ipv4_address
    print('network IP:', myip)
Then I'm connecting to a server with this code:

Code: Select all

socket = socketpool.SocketPool(wifi.radio)
server_ip='192.168.31.10'  # some ip
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
    sock.connect((server_ip, 80))
except Exception as e:
    print("Connection Error:", e)
    
The problem is that if the server is not running (it is another python code which might fail...), the connect command is stuck for 20 seconds before returning an error.

Setting sock.settimeout(2) has no effect on connect. It is used by sock.recv_into.

So my question is: is there any way to set a timeout for the connection?

User avatar
mikeysklar
 
Posts: 14194
Joined: Mon Aug 01, 2016 8:10 pm

Re: Timeout for socket connect?

Post by mikeysklar »

The CLOSED socket settimeout bugs in the circuitpython github repo indicate that this might not be fully working. If you don't mind confirming with CP-8.2.0 beta and the current libs it would be helpful to have you open a new issue for this.

Locked
Please be positive and constructive with your questions and comments.

Return to “Adafruit CircuitPython”