Current Lua downloadable firmware will be posted here

User avatar
By alex_g
#64562 Hi

I've started doing some wifi programming with my NodeMCU, and I noticed that some functions are asynchronous, i.e. return immediately.

For instance, I have written a getbestsignal() function which I pass as a callback to wifi.sta.getap(), and this searches for which available APs are known, and then picks the one with the strongest signal to use. However, wifi.sta.getap() is asynchronous, so if I place any code after its call, it invariably gets executed before getap() is finished doing its thing.

The only way I know of getting around this at the moment is nesting the subsequent functions within the caller, to ensure the correct calling order. I think this may be useful to a limited degree, but I have some doubts about overdoing it. I mean should wifi.sta.config() really be nested inside getbestsignal() which in turn is nested inside wifi,sta,getap()? And then wifi.sta.eventMonStart() nested inside that??? Won't it get impractical at some stage? If the functions are large, won't it upset the watchdog eventually?

So what I want to know, is what is considered to be the best practice when running slightly more involved connecting routines? Nothing too fancy, but certainly monitoring available APs, monitoring progress on connection, switching to a different AP if the current one disconnects (usually due to weak signal). Is there any kind of write-up or tutorial available?

Also is there any functionality (which I am not aware of) which will cause the system to wait for some event before proceeding to evaluate a subsequent function call? For instance wait for a variable to be assigned a value?

Many thanks in advance for any hints, tips or pointers. I should add that I've never done any wifi programming/connectivity before, so there may be some bog-standard solution/approach to the problem. If so, I would not be aware of it, so please bear with me on any "clangers" I may emit ;)

TIA
User avatar
By devsaurus
#64570 I think you're on the right track with callbacks and stuff.
Very much of this is covered in the FAQ: http://nodemcu.readthedocs.io/en/master ... loper-faq/

If you want to mitigate excessive nesting of callbacks to achieve a cleaner structure or for any other reason, then use node.task.post() at an appropriate level.
User avatar
By alex_g
#64598 Thank you, sir, I don't know how I overlooked the FAQ, it is indeed all explained very well in there!

The node.task.post() suggestion looks very handy too. Much obliged.
It looks like the end result will be a lot neater than what I initially 'feared'...