Skip to content

Commit

Permalink
Randomize local port used for Particle connection
Browse files Browse the repository at this point in the history
It's a good idea to randomize the port used, otherwise a rebooted Oak
will try and reconnect on the same port, which may result in a long
delay if the connection was not closed before the reboot, as mentioned
by @jldeon here:

digistump#54 (comment)

I believe I have observed this issue in practice on a few occasions,
where it would take exactly five seconds for the first data to come
through the connection, which seems too constant to be a random delay.
As the read timeout in blocking_receive() is 2 s, this is obviously
problematic.

As most users will be behind routers running NAT, it will be the router
settings, rather than the Particle server settings, that affect how
reconnections from the same source port are treated.
  • Loading branch information
kh90909 committed Jun 16, 2016
1 parent bc8042b commit 3a41c68
Showing 1 changed file with 8 additions and 0 deletions.
8 changes: 8 additions & 0 deletions cores/oak/OakParticle/particle_core.cpp
Expand Up @@ -2570,6 +2570,14 @@ void remove_event_handlers(const char* event_name)

bool particleConnect(){
uint8_t max_connect_tries = 3;
// Generate a random local port number, to avoid issues with
// previous connections left hanging on the server
// register used is apparently a RNG, see:
// http://esp8266-re.foogod.com/wiki/Random_Number_Generator
uint16_t local_port = ESP8266_DREG(0x20E44);
// Avoid using low port numbers, 4k is probably overkill, but it doesn't matter.
if(local_port < 4096) local_port += 4096;
pClient.setLocalPortStart((uint16_t)local_port);
if(deviceConfig->server_address_type == 1){
while(!pClient.connect(deviceConfig->server_address_domain,SPARK_SERVER_PORT) && max_connect_tries > 0){
max_connect_tries--;
Expand Down

0 comments on commit 3a41c68

Please sign in to comment.