ESP8266 and _thread

General discussions and questions abound development of code with MicroPython that is not hardware specific.
Target audience: MicroPython Users.
Post Reply
radders
Posts: 6
Joined: Mon Feb 04, 2019 4:41 pm

ESP8266 and _thread

Post by radders » Mon Feb 04, 2019 4:46 pm

Hello,

I can't find out if _thread has been built into the ESP8266 yet.

I just downloaded the latest firmware (esp8266-20190125-v1.10.bin),
yet when I execute
import _thread
I get an error message
ImportError: no module named '_thread'

Please help!

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

Re: ESP8266 and _thread

Post by pythoncoder » Tue Feb 05, 2019 8:45 am

ESP8266 is probably too RAM-limited to support threading. Consider using uasyncio instead: this is much more efficient and better suited to platforms with restricted RAM.
Peter Hinch

radders
Posts: 6
Joined: Mon Feb 04, 2019 4:41 pm

Re: ESP8266 and _thread

Post by radders » Tue Feb 05, 2019 8:58 am

Thank you.

I open a socket, and wait for incoming data using socket.receive().

The issue I have is that this method blocks, preventing me from sending data to the same socket until the receive completes.

I was hoping to create 2 threads, one for receive and one for sending. How can uasyncio help in this case?

Regards, Dave

User avatar
Roberthh
Posts: 1398
Joined: Sat May 09, 2015 4:13 pm
Location: Rhineland, Europe

Re: ESP8266 and _thread

Post by Roberthh » Tue Feb 05, 2019 9:11 am

In the esp8266 (and ESP32) socket module there is a proprietary method to register a handler, which is called whenever something happens with the socket. It is called like:

socket.setsockopt(socket.SOL_SOCKET, 20, my_event_handler)

my_event_handler() is a function, which has as argument the socket which cause the event, whcih could e.g. be connect request or data being received or the socket being closed. This way, you can make your receive socket non-blocking.
Since this method is also used by Webrepl (it was invented for that), you cannot use webrepl at the same time.

radders
Posts: 6
Joined: Mon Feb 04, 2019 4:41 pm

Re: ESP8266 and _thread

Post by radders » Tue Feb 05, 2019 9:16 am

Brilliant! Thank you.

Will read up on that.

Dave

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

Re: ESP8266 and _thread

Post by pythoncoder » Wed Feb 06, 2019 11:48 am

radders wrote:
Tue Feb 05, 2019 8:58 am
...
I was hoping to create 2 threads, one for receive and one for sending. How can uasyncio help in this case?...
It is possible to put the sockets into nonblocking mode to enable concurrent I/O. Some care is required as the socket send and recv methods can handle partial data. Given that recv must return immediately it can only return the data which is available at that moment in time. A similar contingency exists with send: it may only send a part of the data.
Peter Hinch

Post Reply