[SOLVED] Pubsubclient: Missing first reading after connection timeout

I am using pubsubclient to report activity from an Arduino to an MQTT server. The issue I am having is that if the Arduino sits idle for some time (maybe 20 seconds or so), then I flip a switch (causing it to send a message to the server), the first time it doesn't register. However, if I flip the switch a bunch of times in short succession after, it registers them. It seems like it is discarding the first message after the timeout.

I've tried adding stuff to my code to reconnect if not connected or to republish if client.publish returns 0. Nothing is working.

The code is quite lengthy, so I am just including the pertinent parts. What can I do to troubleshoot / resolve this? Thanks!

Here's the instance declaration:

EthernetClient ethClient;
PubSubClient client(server, port, callback, ethClient);

Here's the 'reconnect' code:

boolean reconnect() { 
  if (client.connect(serialid, uid, pw)) {
    // Once connected, publish an announcement...
    Serial.println(client.publish("io/st", serialid));
    // ... and resubscribe
  return client.connected();

Here's the posting coding:

void postData() {

if(!client.connected()) {
  Serial.print("Reconnect: ");
  if (client.connect(serialid, uid, pw)){ 
    if (!client.publish(topicarray,msgarray)) {

I found the solution. My loop was missing:


I added that and it now works.