Losing data sent before deep sleep?

General discussions and questions abound development of code with MicroPython that is not hardware specific.
Target audience: MicroPython Users.
Post Reply
larsks
Posts: 22
Joined: Mon Feb 13, 2017 5:27 pm

Losing data sent before deep sleep?

Post by larsks » Sun Dec 20, 2020 3:50 am

Originally posted to the esp8266 board, but all the traffic appears to be here...

It appears (with MicroPython on esp8266) that 'socket.write' and/or other socket operations have an asynchronous component, the impact of which is that even though both 'socket.write' and 'socket.close' have been called *and returned successfully*, data written to the socket is not actually sent to the peer.

If one halts the board immediately after sending data (e.g., by entering a deepsleep state), that data is lost.

For example, the following code will fail to transmit a message to a server:

Code: Select all

import machine
import network
import socket
import time

rtc = machine.RTC()


def wait_for_connection():
    iface = network.WLAN(network.STA_IF)
    print('waiting for wifi')
    while not iface.isconnected():
        machine.idle()
    print('wifi connected')


def deepsleep(duration):
    rtc.irq(trigger=rtc.ALARM0, wake=machine.DEEPSLEEP)
    rtc.alarm(rtc.ALARM0, duration)

    print('sleeping')
    machine.deepsleep()


wait_for_connection()

sock = socket.socket()
sock.connect(('192.168.1.200', 4321))

sock.write('this is a test\n')
sock.close()

deepsleep(5000)
If I add a 'time.sleep(1)' before the call to 'deepsleep(5000)', the data is transmitted as expected:

Code: Select all

sock.close()

time.sleep(1)
deepsleep(5000)
Is there a way to (a) make sockets synchronous, or (b) explicitly wait until the data has been sent?

User avatar
pythoncoder
Posts: 5956
Joined: Fri Jul 18, 2014 8:01 am
Location: UK
Contact:

Re: Losing data sent before deep sleep?

Post by pythoncoder » Sun Dec 20, 2020 9:57 am

As you doubtless know, socket.write() with a blocking socket is supposed to be synchronous. If you check the return value, it should equal the length of the message. As far as MicroPython is concerned, the message has been sent. What may be going on is that actual transmission is performed by the Espressif runtime which is something of a black box.

If this is correct you'd need to delve into the Espressif interface spec.
Peter Hinch
Index to my micropython libraries.

Post Reply