Do I have to explicitly call Spark.connect() every time I call client.stop()? [Solved]

I have an application that will have to connect to my server every time the sensor is triggered, and after processing I’d call client.stop() to disconnect from it. However, do I have to explicitly call Spark.connect() to reconnect to Spark Cloud, or is that handled automatically (provided system_mode = AUTOMATIC)

And is it wise to client.connect() and client.stop() inside loop()?

I have an app that scrapes weather data from a Yahoo weather feed page and displays it. The logic for this app is very simple in loop:

  • If the client has data available to read, call the read data handler and parser.

  • If the client is not connected, call client.stop().

  • If enough time has gone by to reload the web data (5 minutes in my case), then call client.stop() (just in case) and then client.connect() and do the HTTP GET request, flushing the client received data buffer immediately after sending the request with client.flush() to get rid of any old data.

This has been working well for many months–the only change I have made recently to improve it is that if my web page parser fails and the display data is empty, wait 1 minute and try again. I reflash this code all the time since this is what my development core runs when I am not actively working on something else, so it is always up to date. This all runs in the default mode of automatic.

So no, I don’t think Spark.connect() and TCPClient are related at all, and yes, I call client.connect() and stop() in loop all the time with no problems.

2 Likes

@bko that's helpful. In my case, it's a kind of chat room so I won't be having the core to client.read() from the server, but rather have the chat socket make a POST request to a Spark.function and send with that the data to be executed.

However, could I beg for elaboration on what you were saying? It sounds like while the core is connected to a server as a client, it is also still connected to the Spark Cloud.

So the Spark cloud connection code is run when your code exits loop() and before it goes around again and re-runs loop(). There are times when your code is blocking for a long time, such as when you use delay(20000); that the cloud connection is also serviced. But if you code blocks for a long time without using delay(), then you need to call the Spark cloud service function (Spark.process()) yourself. The cloud connection has a a timeout and if it goes off, then it tries to reconnect.

That is why my code treats loop() as a kind of task dispatcher.

1 Like

@bko crystal! Many thanks!