Device.onconnect runs multiple times upon Build and Run

Everything was working fine until I noticed my server log was showing multiple executions of the device.onconnect function. I’m using PubNub in my project, so this results in a broadcast happeing 2-3 times each rebuild, which messes things up on the other end.

Has anyone encountered this bug?

CODE:

`device.onconnect(function() {
  server.log("Device CONNECTED to agent.");
  // Publish Connection
  pubNub.publish("iPlugComm", { 
      deviceID = impID,
      deviceName = "Agent-"+impID,
      deviceMode = "Slave",
      deviceMessage = "Imp Agent Restarted",
      deviceAction = "null",
  });
});`

This shows as being executed multiple times in my log…

LOG:

`	------------------- RESTART CYCLE ------------------
2015-10-30 21:30:42 UTC-3	[Agent]	Agent Loaded. Agent URL: https://agent.electricimp.com/#############
2015-10-30 21:30:42 UTC-3	[Agent]	imp id = 23584e7838a609ee
2015-10-30 21:30:42 UTC-3	[Agent]	----------------------------------------------------
2015-10-30 21:30:42 UTC-3	[Agent]	
2015-10-30 21:30:42 UTC-3	[Agent]	Device CONNECTED to agent.
2015-10-30 21:30:42 UTC-3	[Agent]	COMM on channel '(null : (nil))' from (null : (nil)): (null : (nil)).
2015-10-30 21:30:42 UTC-3	[Agent]	Published data at 14462514422868620
2015-10-30 21:30:42 UTC-3	[Agent]	COMM on channel 'iPlugComm' from Agent-23584e7838a609ee: Imp Agent Restarted.
2015-10-30 21:30:42 UTC-3	[Agent]	Device CONNECTED to agent.
2015-10-30 21:30:42 UTC-3	[Agent]	Published data at 14462514424138347
2015-10-30 21:30:42 UTC-3	[Agent]	COMM on channel 'iPlugComm' from Agent-23584e7838a609ee: Imp Agent Restarted.
2015-10-30 21:30:42 UTC-3	[Status]	Device connected
2015-10-30 21:30:42 UTC-3	[Device]	IMP Device Started`

Two of them are quite normal; the agent restarts first, and gets given an onconnect as the device is connected. Then, as you’ve pressed build & run, the device reboots and that reconnection causes a second event.

Essentially it’s the difference between the speed of rebooting an agent and rebooting a device that you’re seeing. You could maintain your own concept of online in the agent so you suppressed multiple events if you needed to?