I am running local HTTP server that will return current UTC time in milliseconds as a response of get method.
I am trying the below logic to get the timestamp and syncing it on my particle argon every one hour. But it gets proper response sometimes and remaining time getting -1 as response and time sync fails. Kindly provide the suggestions and fixes.
To find out what’s going on, you could first check response.body for its string value before unconditionally converting it into a numeric value.
That might give you some clue of what may be going on. We don’t know what your time server sends in these cases.
You could also enable logging in the HttpClient library to give you some extra insight. response.status == -1 indicates that there was some other issue
see the implementation of the request() function
This is either named wrongly and should be named one hour or there should be a factor of 24 for the hours in day. Maybe this is debugging code?
I certainly agree with @ScruffR that blindly accepting the response body is not a good idea. I am also not sure using toInt() will work well since you want an unsigned representation there.
You have a waitFor(WiFi.ready,60000); in your code already.
If that returns false you already know that the connection attempt timed out, so any subsequent WiFi action will be futile anyway. In that case you could either skip the rest of the function entirely or give it another try.
BTW, you never call Particle.connect() hence I don't see the need for Particle.disconnect() in your code
You also have that entire block ...
... three times - once in each and every code path.
So it is unconditional and hence should be kept out of the conditional paths and be placed only once in the common path.