Arduino with both WiFi and Ethernet connection

My custom arduino 1284p based PCB shown below, has an ESP-07s module as well as a wired Ethernet connection in addition to an RS485 link. (PCB not fully populated)

The basic function of the project is to measure load current from 4 channels of AC load.
It will be housed in a din-rail mounted box and installed inside the house distribution box.
The measured loads will be sent via MQTT to home assistant.

The idea is to use either Ethernet connection or WiFi depending whats available.
Obviously if Ethernet is available it should have priority over wifi.
My question is how to accommodate both in the sketch and chose to channel data to whatever link is available.

So, trying to setup the clients to service MQTT:


EthernetClient ethClient;
WiFiClient wifiClient;

PubSubClient client(wifiClient);

//OR

PubSubClient client(ethClient);

//then in void setup() 

   client.setServer(mqttServer, 1883);

   client.setClient( wifiClient);  

  //OR
  
 client.setClient( ethClient);  

  client.setCallback(callback);

It looks like the above cannot coexist.

How can they be configured "on the fly" depending on which link is available?
Same applies with client.publish() commands...

and what is the problem?

you can have PubSubClient client; without the parameter
and it looks like you can switch the Client object with setClient any time

How can I have both ? This is declared before setup()

PubSubClient client(wifiClient);

//OR

PubSubClient client(ethClient);

please see the updated comment

PubSubClient client_wifi(wifiClient);
PubSubClient client_eth(ethClient);

And later in your code use client_eth or client_wifi as you need:

client_eth.setServer(mqttServer, 1883);
client_wifi.setClient(wifiClient);  

Thanks for your input.

if (!client.connected()) {
    //now = millis();
    if (millis() - lastReconnectAttempt > 5000){
     lastReconnectAttempt = millis();
       if (mqttReconnect()) {
        lastReconnectAttempt = 0;
      }
    }
  } else { 
  client.loop();
  }
}

So above reference to client, should be either client_wifi or client_eth ?

Thanks!
hmm Interesting... i will try that!

Yes.

Did you design and fabricate a custom PCB without first building up a breadboard and developing working code for it?

Yes i did exactly that.
I rarely use breadboards. At this level of complexity, they never work!
All my components including the mcu are SMT.
Besides, i have now enough hardware experience to avoid hardware mistakes most of the time. In any case i prefer to redesign the pcb in case of a mistake that cant be fixed otherwise.

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.