arduino-libraries / ArduinoBearSSL

Port of BearSSL to Arduino
MIT License
86 stars 49 forks source link

infinite while loop fix write() and clientWrite() #2

Closed Rocketct closed 6 years ago

Rocketct commented 6 years ago

Reimplemented return logic in BearSSLClient::write() and BearSSLClient::clientWrite() in order to avoid infinite loop in https://github.com/Rocketct/ArduinoBearSSL/blob/master/src/bearssl/ssl_io.c#L279 when networking error happend in low level client(GSMClient)

Rocketct commented 6 years ago

yes the following sketch reproduce the problem, is a simplified version without of the one that i use:

#include <MQTTClient.h>
#include "MKRNBIoT.h"
#include "arduino_secrets.h"
#include <ArduinoBearSSL.h>

#define GPRS_APN "22210"
#define PINNUMBER ""
void connect();

GSMClient net;
GPRS gprs;
GSM gsmAccess(true);
GSMScanner scannerNetworks;

BearSSLClient SSLClient(net);
MQTTClient mqttclient;

const int publishInterval = 5000;
unsigned long lastMillis = 0;

float lastMeasure;

unsigned long getTime() {
  return gsmAccess.getTime();
}

void setup() //This code is executed once
{
  //Peripheral Initialization
  Serial.begin(115200);          

  connect();
}

void connect() {
  Serial.print("Connecting to GSM networks");
  boolean connected = false;
  while (!connected) {
    if ((gsmAccess.begin(PINNUMBER) == GSM_READY) &&
        (gprs.attachNBIoT(GPRS_APN) == GPRS_READY)) {
      connected = true;
    } else {
      Serial.println("Not connected");
      delay(1000);
    }
  }
  Serial.println("\nConnected!\n");
  ArduinoBearSSL.onGetTime(getTime);

  Serial.println("Connecting to MQTT");
  mqttclient.begin(MQTT_URL, 8883, SSLClient);
  while (!mqttclient.connect(MQTT_ID, MQTT_USR, MQTT_PWD)) {
    Serial.println("Not connected");
    delay(1000);
  }
  Serial.println("\nConnected!\n");
}

unsigned long int i = 0;
void loop() //This code is looped forever
{

  if (!mqttclient.connected()) {
    connect();
  }
  mqttclient.loop();

  // publish a message roughly every second.
  if (millis() - lastMillis > publishInterval) {
    lastMillis = millis();

    publishLevel(i%10);   

  }
}

bool publishLevel(int level) {
  char stringToPublish[100];
  snprintf(stringToPublish, 100, "%s%d%s",
           "{\"data\": {\"level\":\"",
           level,
           "\"}}");

  return publish(String (stringToPublish));
}

bool publish(String (stringToPublish)) {

  if (mqttclient.publish(MQTT_MEASURES, stringToPublish)) {
    Serial.print("Published: ");
    Serial.println(stringToPublish);
    return true;
  }
  else {
    Serial.println("Failed");
    mqttclient.disconnect();
    return false;
  }
}