OPEnSLab-OSU / SSLClient

🔒Add SSL/TLS functionality to any Arduino library
https://openslab-osu.github.io/SSLClient/index.html
GNU General Public License v3.0
151 stars 46 forks source link

AWS MQTT ESP32 SIM800 TinyGSM #39

Open aneggi opened 3 years ago

aneggi commented 3 years ago

Firts of all, thanks a lot to contribute. :-)

I am trining to connecting to AWS IOT by MQTT. I am using Esp32 with SIM800L. To manage SIM800L I am using TinyGSM library. So I copied and paste your MQTT example, and tried with WIFI, and it works fine after some minor fix on the Ethernet library. Now I added TinyGSM and removed WiFi but I got an error...

Partial important code changing here:

TinyGsm modem(SerialAT);
TinyGsmClient transport(modem);

SSLClient ethClientSSL(transport, TAs, (size_t)TAs_NUM, A5);
PubSubClient mqtt(mqttServer, 8883, callback, ethClientSSL);

I got this error:

Initializing modem...
[8304] ### TinyGSM Version: 0.10.9
[8304] ### TinyGSM Compiled Module:  TinyGsmClientSIM800
[8617] ### Modem: SIMCOM SIM800L
[8617] ### Modem: SIMCOM SIM800L
1
[NET] Signal quality before GPRS ( >10 OK ): 0
Modem Info: SIM800 R14.18
[29070] ### Network time zone updated.
[29073] ### Network time and time zone updated.
[29074] ### Daylight savings time state updated.
Waiting for network... success
Network connected
Attempting MQTT connection...(SSLClient)(SSL_ERROR)(m_update_engine): Error reading bytes from m_client. Write Error: 
(SSLClient)(SSL_ERROR)(m_update_engine): 0
(SSLClient)(SSL_ERROR)(connected): Not connected because write error is set
(SSLClient)(SSL_ERROR)(m_print_ssl_error): SSL_CLIENT_WRITE_FAIL
(SSLClient)(SSL_WARN)(m_run_until): Terminating with write error: 
(SSLClient)(SSL_WARN)(m_run_until): 4
(SSLClient)(SSL_ERROR)(m_start_ssl): Failed to initlalize the SSL layer
(SSLClient)(SSL_ERROR)(m_print_br_error): Unknown error code: 0
failed, rc=-2 try again in 5 seconds
(SSLClient)(SSL_ERROR)(connected): Not connected because write error is set
(SSLClient)(SSL_ERROR)(m_print_ssl_error): SSL_CLIENT_WRITE_FAIL
Attempting MQTT connection...(SSLClient)(SSL_ERROR)(connected): Not connected because write error is set
(SSLClient)(SSL_ERROR)(m_print_ssl_error): SSL_CLIENT_WRITE_FAIL
(SSLClient)(SSL_ERROR)(connected): Not connected because write error is set
(SSLClient)(SSL_ERROR)(m_print_ssl_error): SSL_CLIENT_WRITE_FAIL

Am I doing something bad when I use that "transport(modem)" in this way? There is any way to find where is the error?

HebertWP commented 3 years ago

i'm doing the same, now my code is in class so it' leatle diferente, but is essentially the same, here are some part of the code: before void setup()

    serialAT_ = new HardwareSerial(1);
    modem_ = new TinyGsm(*serialAT_);
    clientnoSSL_ = new TinyGsmClient(*modem_);
    client_ = new SSLClient(*clientnoSSL_, TAs, (size_t)TAs_NUM, 27, 1, SSLClient::DebugLevel::SSL_WARN);
    mqtt_ = new PubSubClient(END_POINT_AWS, 8883, *client_);

in void setup()

    serialAT_->begin(9600, SERIAL_8N1, txPin_, rxPin_);
    mqtt_->setBufferSize(20000);
    client_->setMutualAuthParams(*mTLS);
    this->checkGPS_GPRS();

i have some problem with random internet lost, that i'm working on, now it's lost the connect with mqtt server some times, but with this code i'm able to reconnect automatic, by call this function in loop to : "Note: it's in first version yet, so there is a loot of unnecessary print codes "

void checkGPS_GPRS()
{
    if (!modem_->getGPS(&lat, &lon))
        modem_->enableGPS();
    if (!modem_->isGprsConnected())
    {
        if (carrier_ == TIM)
        {
            modem_->gprsConnect(apnNameTim, apnUserTim, apnPswdTim);
            Serial.printf("TIM\r\n");
        }
        else if (carrier_ == VIVO)
            modem_->gprsConnect(apnNameVivo, apnUserVivo, apnPswdVivo);
        delay(1000);
    }else
        Serial.printf("Modem connected\r\n");

      if (!mqtt_->connected())
    {
        Serial.print("Attempting MQTT connection...\r\n");
        if (mqtt_->connect("ESP32-1"))
        {
            Serial.println("connected!!!!!!!!!!!!");
        }
        else
        {
            Serial.print("failed, rc=");
            Serial.println(mqtt_->state());
            client_->flush();
            delay(5000);
        }
    }
    else
    {
        Serial.printf("MQTT connected\r\n");
        if (client_->connected())
            while (client_->available() != 0)
                client_->read();
        mqtt_->loop();
        client_->flush();
    }
}

And i'm using SIM868

prototypicalpro commented 3 years ago

Hello @aneggi! It looks like TinyGSM is failing to read from the modem, which might be intended behavior but I'm not sure. Could you enable diagnostics in TinyGSM and post your logs with that?

HebertWP commented 3 years ago

@aneggi In my case the library is working fine, can you test this code?, in your module, i mad it direct from example, i pretend test it with SIM7000G before try put this example direct in library, but it will take at lest a month to arrive from china in Brasil.

/*
  Connect to AWS IOT using SSLClient and Tinygsm Mdoule
   AWS_Root_CA.h is the trust anchor created using the Root CA from:
   https://www.amazontrust.com/repository/AmazonRootCA1.pem
   You can re-create it again using the python file present 
   in SSLClient/tools/pycert_bearssl/pycert_bearssl.py
   python pycert_bearssl.py convert --no-search <certificate PEM file>
   refer: https://github.com/OPEnSLab-OSU/SSLClient/issues/17#issuecomment-700143405

  Circuit:
   Ethernet shield WIZ850io:
   Power     2
   RX        16
   TX        4

  created 12 Abril 2021
  by Hebert Wandick Parreira, with EnthermetAWSIotExample as base, from Ram Rohit Gannavarapu
*/

// Select your modem:
// #define TINY_GSM_MODEM_SIM800
#define TINY_GSM_MODEM_SIM868

#include <Arduino.h>
#include <TinyGsmClient.h>
#include <SSLClient.h>
#include <PubSubClient.h>
#include "AWS_Root_CA.h" // This file is created using AmazonRootCA1.pem from https://www.amazontrust.com/repository/AmazonRootCA1.pem

#define THING_NAME "Teste"
#define MQTT_PACKET_SIZE 1024

#define APN_NAME "timbrasil.br"
#define APN_USER "tim"
#define APN_PSWD "tim"

void MQTTPublish(const char *topic, char *payload);
void updateThing();

static const char my_cert[] PROGMEM = R"KEY(
-----BEGIN CERTIFICATE-----
MIIDWjCCAkKgAwIBAgIVAMHgCQgsOQkBcsHxTbOkHUyHT2TYMA0GCSqGSIb3DQEB
CwUAME0xSzBJBgNVBAsMQkFtYXpvbiBXZWIgU2VydmljZXMgTz1BbWF6b24uY29t
IEluYy4gTD1TZWF0dGxlIFNUPVdhc2hpbmd0b24gQz1VUzA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AvHlsEq5PR9any/c9FMCgYEArAVNBJCfiL6wZeLkFSFd
IN+PbV6U6CM4l3mSAjfJiVFUM/pJnT0BxfRMrbtBJVZXlestCoysrWVE8lJ4v5ba
QHB8cPTTyVN/g2AOcBogBj9+Z8JIBMvuoPHkc2BThqle+d5MAQa84PN76mI4MFH2
mNCVpWPxgBfUi25liJ0xLjUCgYEAi0hEzJsH9JkE8BxwAX5oVoZgtGJk+j2naCY6
wLPAG00PszzSvg8WpILdMNB30HzTj1X9+5uqNaCh+v05cXdp0Ww0223i7tmi0rEs
9it6b+pnVaj+YYtaS7bLkUkTem84v0B4UVCPRSBM5R+q42JsX6bsc1jujl/m1lQS
3XQY9qUCgYEA0/55H4LquKMdWEGEXaYIHVbRkn2aFeCYWfQ9IV8tbPHOjtSO36xM
/0ekepaqH0ddR/k2dIsg2veMC69PM+ujAKGsS1KV7Acu8TubPrjS+i8YgyByrKV6
SfMuFy7oA+381pMvf39Hu8DoalPshnF2qFAiaTBJGG2p/1Rep9zCULQ=
-----END RSA PRIVATE KEY-----
)KEY";

SSLClientParameters mTLS = SSLClientParameters::fromPEM(my_cert, sizeof my_cert, my_key, sizeof my_key);

const char *mqttServer = "xxfdgfdsuptm3-ats.iot.us-east-1.amazonaws.com";
const char publishShadowUpdate[] = "$aws/things/" THING_NAME "/shadow/update";
char publishPayload[MQTT_PACKET_SIZE];
char *subscribeTopic[5] =
    {
        "$aws/things/" THING_NAME "/shadow/update/accepted",
        "$aws/things/" THING_NAME "/shadow/update/rejected",
        "$aws/things/" THING_NAME "/shadow/update/delta",
        "$aws/things/" THING_NAME "/shadow/get/accepted",
        "$aws/things/" THING_NAME "/shadow/get/rejected"};

void callback(char *topic, byte *payload, unsigned int length)
{
    Serial.print("Message arrived [");
    Serial.print(topic);
    Serial.print("] ");
    for (int i = 0; i < length; i++)
    {
        Serial.print((char)payload[i]);
    }
    Serial.println();
}

const uint8_t pwrPin = 2;
const int8_t txPin = 4;
const int8_t rxPin = 16;

HardwareSerial serialAT(1);
TinyGsm modem(serialAT);
TinyGsmClient ethClient(modem);
SSLClient ethClientSSL(ethClient, TAs, (size_t)TAs_NUM, 36); //using GPIO36 as float point
PubSubClient mqtt(mqttServer, 8883, callback, ethClientSSL);

void reconnect()
{
    while (!mqtt.connected())
    {
        Serial.print("Attempting MQTT connection...");
        if (mqtt.connect("arduinoClient"))
        {
            Serial.println("connected");
            for (int i = 0; i < 5; i++)
            {
                //        Serial.println(subscribeTopic[i]);
                mqtt.subscribe(subscribeTopic[i]);
            }
            Serial.println("Started updateThing ");
            updateThing();
            Serial.println("Done updateThing ");
        }
        else
        {
            Serial.print("failed, rc=");
            Serial.print(mqtt.state());
            Serial.println(" try again in 5 seconds");
            delay(5000);
        }
    }
}

void setup()
{

    // Open serial communications and wait for port to open:
    serialAT.begin(9600, SERIAL_8N1, txPin, rxPin);
    Serial.begin(115200);
    pinMode(pwrPin, OUTPUT);
    digitalWrite(pwrPin, LOW);
    while (!Serial)
    {
        ; // wait for serial port to connect. Needed for native USB port only
    }

    ethClientSSL.setMutualAuthParams(mTLS);
    mqtt.setBufferSize(MQTT_PACKET_SIZE);

    // start the GSM connection:
    if (!modem.testAT())
    {
        Serial.printf("Turning on Modem\r\n");
        digitalWrite(pwrPin, HIGH);
        delay(3000);
        digitalWrite(pwrPin, LOW);
        delay(3000);
    }
    modem.restart();
    modem.gprsConnect(APN_NAME, APN_USER, APN_PSWD);
    if (modem.waitForNetwork())
        Serial.printf("NetWork Ok\r\n");
    else
        Serial.printf("NetWork Faill\r\n");
    // print your local IP address:
    Serial.print("My IP address: ");
    Serial.println(modem.localIP());
}

void loop()
{
    if (!mqtt.connected())
    {
        reconnect();
    }
    mqtt.loop();
}

void updateThing()
{
    strcpy(publishPayload, "{\"state\": {\"reported\": {\"powerState\":\"ON\"}}}");
    MQTTPublish(publishShadowUpdate, publishPayload);
}

void MQTTPublish(const char *topic, char *payload)
{
    mqtt.publish(topic, payload);
    Serial.print("Published [");
    Serial.print(topic);
    Serial.print("] ");
    Serial.println(payload);
}
woodlist commented 3 years ago

Trash away your SIM800L. It is not accommodated for SSL using and targeted to China's market. Just inquire your modem for SSL feature by AT command. Instead, use SIM800C at least.

woodlist commented 3 years ago

Hello @aneggi! It looks like TinyGSM is failing to read from the modem, which might be intended behavior but I'm not sure. Could you enable diagnostics in TinyGSM and post your logs with that?

I should report that the TinyGSM works perfect on ESP32 platform (namely Al-thinker ESP32-CAM and stand alone SIM800C)

woodlist commented 3 years ago

Copy/Paste from my terminal (interaction log with www.google.com Searching with "Arduino" keyword):

Log ```console 23:51:35.647 -> Waiting for network... 23:51:35.682 -> GPRS status: connected 23:51:35.682 -> Local IP:10.104.69.90 23:51:41.667 -> Connected to GPRS 23:51:41.667 -> 23:51:41.667 -> Starting connection to server... 23:51:44.557 -> connected to server 23:51:45.781 -> HTTP/1.1 200 OK 23:51:45.781 -> Content-Type: text/html; charset=ISO-8859-1 23:51:45.781 -> Date: Fri, 16 Apr 2021 19:51:34 GMT 23:51:45.781 -> Expires: -1 23:51:45.781 -> Cache-Control: private, max-age=0 23:51:45.781 -> P3P: CP="This is not a P3P policy! See g.co/p3phelp for more info." 23:51:45.781 -> Server: gws 23:51:45.781 -> X-XSS-Protection: 0 23:51:45.781 -> X-Frame-Options: SAMEORIGIN 23:51:45.781 -> Set-Cookie: 1P_JAR=2021-04-16-19; expires=Sun, 16-May-2021 19:51:34 GMT; path=/; domain=.google.com; Secure 23:51:45.815 -> Set-Cookie: CGIC=; expires=Wed, 13-Oct-2021 19:51:34 GMT; path=/complete/search; domain=.google.com; HttpOnly 23:51:45.815 -> Set-Cookie: CGIC=; expires=Wed, 13-Oct-2021 19:51:34 GMT; path=/search; domain=.google.com; HttpOnly 23:51:45.815 -> Set-Cookie: NID=213=cv87kXlxnl_tO_ceOd121c3gaRX-Y1_-ji9k6sph52WQcEBqah4aoCZRJmpxfq4_iqO_ue4gBs6l6BLF_kTEZuVG_cUmQUf39M1IGO5WnDhJzuxcggTO3Yhvqtls4Bj15IU_5OkVAe0wPvE9udNlllrW0AzbrpWmDmNsrs_xnpA; expires=Sat, 16-Oct-2021 19:51:34 GMT; path=/; domain=.google.com; HttpOnly 23:51:45.849 -> Alt-Svc: h3-29=":443"; ma=2592000,h3-T051=":443"; ma=2592000,h3-Q050=":443"; ma=2592000,h3-Q046=":443"; ma=2592000,h3-Q043=":443"; ma=2592000,quic=":443"; ma=2592000; v="46,43" 23:51:45.849 -> Accept-Ranges: none 23:51:45.849 -> Vary: Accept-Encoding 23:51:45.849 -> Connection: close 23:51:45.849 -> Transfer-Encoding: chunked 23:51:45.849 -> 23:51:45.849 -> 30ba 23:51:45.849 -> arduino - Google Որոնում
23:51:50.044 -> 177c 23:51:50.044 ->
23:51:54.267 -> 8000 23:51:54.267 ->
Open-source electronic prototyping platform enabling users to create interactive electronic objects.

People also ask

Arduino

Arduino՝ համակարգչային և ծրագրային ապահովման ապրանքային նշան, պարզ ավտոմատացման համակարգերի և ռոբոտների ստեղծման համար, որոնք նախատեսված են ոչ պրոֆեսիոնալ օգտվողների համար։ 23:51:56.822 -> Ծրագրային մասը բաղկացած է անվճար ծրագրային խմբագրիչից ՝ ծրագրեր գրելու և... Wikipedia
Գրված է՝՝ C, C++, ՋավաՍկրիպտ և Ասսեմբլեր լեզու
Arduino՝ համակարգչային և ծրագրային ապահովման ապրանքային նշան, պարզ ավտոմատացման⸮...
Arduino is an open-source hardware and software company, project and user community that designs and manufactures single-board microcontrollers and⸮... 23:51:59.646 -> Arduino IDEArduino UnoArduino NanoCategory:Arduino 23:52:00.020 -> 23:52:00.020 -> CPU: Atmel AVR (8-bit), ARM Cortex-M0+ (32-bit), ARM Cortex-M3 (32-bit), Intel Quark (x86) (32-bit) 23:52:00.428 -> Memory: SRAM
Arduino consists of both a physical programmable circuit board (often referred to as a microcontroller) and a piece of software, or IDE (Integrated Development⸮...
Arduino is an open-source physical computing platform based on a simple i/o board and a development environment that implements the Processing/Wiring⸮...
26 հոկ, 2011 թ.Arduino is a low-cost microcontroller board that lets even a novice do really amazing things. You can connect an Arduino to all kinds of sensors,⸮...
ԳրելԶանգահարել. Arduino միկրոկոնտրոլլերների և մոդուլների, համալրող սարքերի վաճառք և⸮...
23:52:06.855 -> 57a9 23:52:06.855 -> 23:52:25.707 -> 0 23:52:25.707 -> 23:52:26.081 -> (SSLClient)(SSL_WARN)(connected): Socket was dropped unexpectedly (this can be an alternative to closing the connection) 23:52:26.081 -> 23:52:26.081 -> disconnecting from server. ```
RupeshPilania commented 3 years ago

@aneggi I have tested this library with some minor changes. Connection was stable till 5 hours at 2 messages per second publishing rate. Observation: Frequent ssl errors were seen on one network(Vodafone) operator. SSL connection worked without any interruption for another network(Idea) for 5-6 hours. It might be due to network problems also. Tested with ESP-32-CAM and ESP-32 Dev kit with and without FreeRTOS on SIM800L. I had done few changes:

  1. Started from AWS IoT Ethernet example and changed EthernetClient with GSMClient
  2. Changed buffer size from 2048 to the defined macro https://github.com/OPEnSLab-OSU/SSLClient/issues/46, to get rid of ssl warning Discarded unread data to favor a write operation.
  3. Added flush after publishing/subscribing Here is my code:
    
    TinyGsm modem(serialAT);
    TinyGsmClient ethClient(modem);
    SSLClient ethClientSSL(ethClient, TAs, (size_t)TAs_NUM, 36,SSLClient::SSL_INFO);
    void reconnect()
    {
    while (!mqtt.connected()/*&& modem.isGprsConnected()*/)
    {
        Serial.print("Attempting MQTT connection...");
        if (mqtt.connect("arduinoClient"))
        {
            Serial.println("connected");
            for (int i = 0; i < 6; i++)
            {
                //        Serial.println(subscribeTopic[i]);
                mqtt.subscribe(subscribeTopic[i]);
                if (ethClientSSL.available()) { ethClientSSL.flush(); }
            }
            Serial.println("Started updateThing ");
            updateThing();
            Serial.println("Done updateThing ");
        }
        else
        {
            Serial.print("failed, rc=");
            Serial.print(mqtt.state());
            Serial.println(" try again in 5 seconds");
          //  if (ethClientSSL.available()) { ethClientSSL.flush(); }
            delay(5000);
        }
    }
    }

void updateThing() { strcpy(publishPayload, "{\"state\": {\"reported\": {\"powerState\":\"ON\"}}}"); MQTTPublish(publishShadowUpdate, publishPayload); }

void MQTTPublish(const char topic, char payload) {

mqtt.publish(topic, payload);
if (ethClientSSL.available()) { ethClientSSL.flush(); }
Serial.print("Published [ ");
Serial.print(++i);
Serial.print(" ");
Serial.print(topic);
Serial.print("] ");
Serial.println(payload);

}

void gsm() { static int uptime = 0; static int last,now; if (!modem.isGprsConnected()) { Serial.println("GPRS disconnected!"); Serial.print(F("Connecting to ")); Serial.print(APN_NAME); if (!modem.gprsConnect(APN_NAME, APN_USER, APN_PSWD)) { Serial.println(" fail"); delay(10000); return; } if (modem.isGprsConnected()) { Serial.println("GPRS reconnected"); } } if (!mqtt.connected()) { uptime = millis(); i = 0; if (ethClientSSL.available()) { ethClientSSL.flush(); } reconnect(); } mqtt.loop();
now = millis(); if(now-last>10000){ char msg[25] = {0}; sprintf(msg,"uptime: %d", (millis()-uptime)/1000);
MQTTPublish("GsmClientConnected", msg);
last = now;
}

}

void gsm_setup() {

// Open serial communications and wait for port to open:
serialAT.begin(115200, SERIAL_8N1, txPin, rxPin);
Serial.begin(115200);
pinMode(pwrPin, OUTPUT);
pinMode(RELAY1, OUTPUT);
pinMode(RELAY2, OUTPUT);
digitalWrite(pwrPin, LOW);
 digitalWrite(RELAY1, LOW);
  digitalWrite(RELAY2, LOW);
while (!Serial)
{
    ; // wait for serial port to connect. Needed for native USB port only
}

ethClientSSL.setMutualAuthParams(mTLS);
mqtt.setBufferSize(MQTT_PACKET_SIZE);

// start the GSM connection:
if (!modem.testAT())
{
    Serial.printf("Turning on Modem\r\n");
    digitalWrite(pwrPin, HIGH);
    delay(3000);
    digitalWrite(pwrPin, LOW);
    delay(3000);
}
modem.restart();
modem.gprsConnect(APN_NAME, APN_USER, APN_PSWD);
if (modem.waitForNetwork())
    Serial.printf("NetWork Ok\r\n");
else
    Serial.printf("NetWork Faill\r\n");
// print your local IP address:
Serial.print("My IP address: ");
Serial.println(modem.localIP());

}

adfo0 commented 2 years ago

Hi @RupeshPilania. How has your experience with this library and the module been so far? Have you had any new problems ?

I am working with a similar module and most of the time it works fine, but I run into some problems sometimes and the module does not connect again.

Could you tell me if you have had similar problems and how I could face them. Thank you

07:46:59.982 -> (SSLClient)(SSL_ERROR)(connected): Not connected because write error is set
07:46:59.982 -> (SSLClient)(SSL_ERROR)(m_print_ssl_error): SSL_CLIENT_CONNECT_FAIL
07:47:15.029 -> (SSLClient)(SSL_ERROR)(connect): Failed to connect using m_client. Are you connected to the internet?
07:47:20.052 -> (SSLClient)(SSL_ERROR)(connected): Not connected because write error is set
07:47:20.052 -> (SSLClient)(SSL_ERROR)(m_print_ssl_error): SSL_CLIENT_CONNECT_FAIL
07:47:55.500 -> (SSLClient)(SSL_ERROR)(m_run_until): SSL internals timed out! This could be an internal error, bad data sent from the server, or data being discarded due to a buffer overflow. If you are using Ethernet, did you modify the library properly (see README)?
07:47:55.500 -> (SSLClient)(SSL_ERROR)(connected): Not connected because write error is set
07:47:55.500 -> (SSLClient)(SSL_ERROR)(m_print_ssl_error): SSL_BR_WRITE_ERROR
07:47:55.500 -> (SSLClient)(SSL_ERROR)(m_start_ssl): Failed to initlalize the SSL layer
07:47:55.500 -> (SSLClient)(SSL_ERROR)(m_print_br_error): Unknown error code: 0
RupeshPilania commented 2 years ago

Hi @adfo0 My connection is very stable now. I had tested it for 24 hours with AWS. Yes, I face these errors sometimes, probably due to poor network, but I am able to re-connect within few attempts. Also please check if your gprs is connected before running mqtt loop every time. Try to run mqtt loop as frequent as possible, avoid adding delays in loop. If you are using FreeRTOS, then you will see frequent errors if mqtt task priority is low. I had used separate cores for each task on ESP-32 to avoid this problem.

biswaKL commented 2 years ago

Could you tell me if you have had similar problems and how I could face them. Thank you

Use these after Post:

        ethClientSSL.flush();
        ethClientSSL.clearWriteError();