TCP Client Facade/Wrapper Class

I saw in an oldish forum thread that trying to call TCPClient.connect() from a threaded function will not work on the electron (but for some reason will work on the photon?). I suppose this means that you have to call the TCPClient.connect() from the main loop function (which means the main loop will be blocked while this happens).

Would it be possible to write a facade/wrapper class for the TCPClient? Lets call it TCPWrapper for example, containing a TCPClient tcpClient member object. Could I have functions such as TCPWrapper::connect() which checks if a boolean TCPWrapper::tcpBusy is set to true, and if so blocks until false, at which point we set the boolean to true , then call TCPWrapper::tcpClient.connect(), then set the boolean to false and return the result?

The same sort of thing will be written for all the necessary functions of TCPClient like write, read etc. Basically if any other thread/function etc is already doing something with the tcpClient the wrapper function will block the caller until nothing is using the tcpClient.

I’m hoping this will allow me to call all the wrapper functions from any thread.

Is this possible or is there some intrinsic thing about the class in spark_wiring_tcpclient.h that doesn’t allow this?

I’m currently halfway through writing it, but I’m concerned that some indeterminate error will pop up and it will be because of some intrinsic RTOS/ Particle OS thing which is quite hard to debug on the electron.

I think you should be able to use threaded connect from the Electron if you use SYSTEM_THREAD(ENABLED). If I recall correctly, the reason asynctcpclient didn’t work is that I set the stack size too small. 2048 bytes is not enough, but something larger may work. The loop thread stack is 6K, so the appropriate size is probably somewhere between those values.

Okay great. The structure of my code is:
Singleton called UbidotsMqtt.
member pointer of UbidotsMqtt called *TCPConnection (which gets instantiated at runtime with new).
then the *TCPConnection class has a member object TCPClient.

The UbidotsMqtt singleton has a worker thread which tries to maintain the tcp connection by checking if TCPConnection->connected() (wrapper function) and then calling TCPConnection.connect() (wrapper function) etc.

So the TCPConnection object (and as such the TCPClient object) doesn’t get created in the stack of the worker thread if I’m not mistaken. So the worker thread stack of the UbidotsMqtt singleton can be a normal size if I’m not mistaken?

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.