peterhinch / micropython-samples

Assorted code ideas, unofficial MP FAQ, plus index to my other repositories.
MIT License
442 stars 91 forks source link

Detect socket close in ESP8266 #28

Closed wang0618 closed 1 year ago

wang0618 commented 1 year ago

I try to setup a TCP client by using socket module. I have trouble in detecting socket close. It seems ESP8266 don't support socket.settimeout() method, so I start to use the select module as the doc suggested.

However I found that sometime the event element returned by poll.poll() method is select.POLLIN (1) but the socket is not active actually. At this time, when I print the result of poll.poll(), I got [(<socket state=4 timeout=-1 incoming=0 off=0>, 1)].

I notice when the socket is active, the socket state is 3, so now I have to use the following code to detect socket close:

...  # init socket
cl.connect(addr)

poller = select.poll()
poller.register(cl, select.POLLIN)
while True:
    p = poller.poll(1000)  # time in milliseconds
    while not p:
        p = poller.poll(1_000)
    if 'state=3' not in str(p[0]):
        print('socket state error:', p)
        return
    ...  # read data from socket

I wonder if there are some more elegant way to detect socket close in ESP8266? Thanks in advance.

PS: I think it would be better to note which port is not support for socket.settimeout() method in doc.

peterhinch commented 1 year ago

I suggest you raise this in the forum as I'm afraid I don't know the answer to this.