0

I'm using MQTT over ESP8266 and SIM800, they both work fine.

I need to change dinamically, between WiFi and GPRS, depending on WiFi availability.

My problem is, I cannot dinamically change PubSubClient, it just won't work.

A simplified example of what I've done:

TinyGsm SIM800(Serial);
TinyGsmClient GPRSclient(SIM800);
WiFiClient WiFiclient;    

if(WiFi.status()!=WL_CONNECTED){
  USE_GPRS=1;
  PubSubClient mqtt(GPRSclient);
}
if(WiFi.status()==WL_CONNECTED){
  USE_GPRS=0;
  PubSubClient mqtt(WiFiclient);
}
Pedro Mancuso
  • 31
  • 1
  • 5
  • Define "it just won't work". What errors do you get? – hardillb May 04 '21 at 20:26
  • @hardillb , thanks in advance. It just won't swap, with no errors or alerts shown. The PubSubClient defined before setup will remain static.... If I set WiFi as PubSubClient on startup, then I won't be able to PubSub via GPRS, same situation otherway, no errors, delays or warnings, the desired change is not implemented....the line would appear to be skippedd or so... – Pedro Mancuso May 04 '21 at 21:08
  • your mqtt object dies when it leaves the scope of "if" code block. You need to use global variable instead of local one for it to live through "if" code block. you can either copy local object defined in the block into global one or use global pointer variable and assign it via ```glb_mqtt = new PubSubClient(WifiClient or GPRSClient)``` – Maxim Sagaydachny May 06 '21 at 18:45

1 Answers1

1

I am using GSM and WiFi together. I was required to make objects on the basis of the condition of whether a WiFi or Cellular connection was available. This worked for me:

  • Make global:

    PubSubClient *mqttClient = NULL;

  • Then make new anywhere:

    mqttClient = new PubSubClient(gsmClient); or

    mqttClient = new PubSubClient(wifiClient);