The use of the ESP8266 in the world of IoT

User avatar
By CestLaGalere
#87034 I have a remote device that after a time (set parameter) checks to see if there are any parameter updates or new firmware to be downloaded.

If I make one call to httpclient.begin the httpclient.GET() / httpclient.getString() to get a file, the subsequent mqtt publish works fine, if I make two calls, to read two different files, the mqtt publish fails (or rather all return values indicate success but the message does not get published) I have looked but can find no httpclient examples that read more than one file - unsure what the syntax is - do I need 2x begin() or is there another call?
Thanks

I have cut down my code to reproduce this issue:
Code: Select allvoid loop() {
  ReconnectMqtt(3);
  PublishSwitchState();
 
  if (loopCount > 10) {
    loopCount = 0;

    DisconnectMqtt();

    HTTPClient httpClient;
    httpClient.setTimeout(2000);

    String paramURL = (String) "/" + fwName + "_" + MqttClientname + ".txt";
    bool beginResult = httpClient.begin(wifiClient, FwServer, 80, paramURL, false);
    int httpCode;
    httpCode = httpClient.GET();
    if (httpCode == 200) {
      String paramLines = httpClient.getString();
      Serial.println("read " + paramURL);
    }
    httpClient.end();

    if (digitalRead(D3) == LOW) {
      // make second call to read another file - will cause the publishInfo() to not publish
      String fwURL = (String) "/" + fwName + ".txt";
      beginResult = httpClient.begin(_wifiClient, FwServer, 80, fwURL, false);
      httpCode = httpClient.GET();

      if (httpCode == 200) {
        String newFWVersion = httpClient.getString();
        Serial.println("read " + fwURL);
      }

      httpClient.end();
    }

    ReconnectMqtt(3);
    PublishInfo();

    DEBUG_MSG("Result %d\n", (int) beginResult);
  }

  _mqttClient.loop();
  loopCount++;
  delay(1000);
}


for completeness the other functions are:
Code: Select all
void DisconnectMqtt() {
  DEBUG_MSG("Disconnecting from MQTT ");
  if (!_mqttClient.connected()) {
    DEBUG_MSG("not connected\n");
    return;
  }

  _mqttClient.disconnect();
}


void ReconnectMqtt(int retryCount) {
  if (_mqttClient.connected())
    return;

  int retry = 0;

  while (!_mqttClient.connect(MqttClientname.c_str(), MqttUsername.c_str(), MqttPassword.c_str()) && retry < retryCount) {
    retry++;
    ConnectionErrorCount++;
    DEBUG_MSG("%d.", _mqttClient.state());
    delay(5000);
  }

  if (!_mqttClient.connected()) {
    Serial.println((String) F("mqtt connect failed, rc=") + _mqttClient.state());
    return;
  }

  // Subscribe to all topics
  DEBUG_MSG(" connected\n");
  ConnectionErrorCount = 0;

  String mqttSwitchCommandTopic = MqttTopicPrefix + (String) "/#";
  DEBUG_MSG("Subscribing to %s\n", mqttSwitchCommandTopic.c_str());
  if (_mqttClient.subscribe(mqttSwitchCommandTopic.c_str(), 1))
    ConnectionErrorCount = 0;
  else
    ConnectionErrorCount++;
}