alkonosst / SSLClientESP32

SSLClient - generic secure client Arduino library using mbedtls
GNU General Public License v3.0
6 stars 4 forks source link

Connect to AWS-IOT Server failed #14

Closed weekroom closed 5 months ago

weekroom commented 7 months ago

Description Error: When I used SSLClientESP32@^2.0.3 -> TinyGSM -> SIM7020C to connect to aws-iot, the server connection failed. Connect to a31klw4qph0psl-ats.iot.us-east-2.amazonaws.com [10144][E][ssl_lib_client.cpp: 168] start_ssl_client () : Failed to connect to the server! [10144][E][SSLClientESP32.cpp: 121] connect () : start_ssl_client: -2 I have no problem debugging relevant certificates, server ip, port, device id parameters in MQTTFX successfully. Now I don't know whether it is the problem that sslclientesp32 does not support tls1.2 or more or other reasons.

1f266e3707d2f1c62f4ef9b6c2595e0 const char MQTT_BROKER[]="a31klw4qph0psl-ats.iot.us-east-2.amazonaws.com";

define MQTT_PORT 8883 //端口号

define UPLOAD_INTERVAL 10000

const char mqtt_devid[]="44a8c4fe642442f19c71ac54ec18d20d"; //client id

define mqtt_pubid "fr" //用户名

//鉴权信息

define mqtt_password "vv" //鉴权信息

int postMsgId = 0; //记录已经post了多少条 //信息模板 //这是post上传数据使用的模板

define ONENET_POST_BODY_FORMAT "{\"id\":%d,\"dp\":%s}"

//接收下发属性设置主题 //接收设备属性获取命令主题

define ONENET_TOPIC_GET "$sys/cmd/request/+"

//设备上发数据主题

define ONENET_TOPIC_POST "$sys/dp/post/json"

//设备同步命令响应

define ONENET_TOPIC_CMD "$sys/cmd/response/"

int num=0; const char rootca_data[]="-----BEGIN CERTIFICATE-----\n" "MIIDQTCCAimgAwIBAgITBmyfz5m/jAo54vB4ikPmljZbyjANBgkqhkiG9w0BAQsF\n" "ADA5MQswCQYDVQQGEwJVUzEPMA0GA1UEChMGQW1hem9uMRkwFwYDVQQDExBBbWF6\n" "b24gUm9vdCBDQSAxMB4XDTE1MDUyNjAwMDAwMFoXDTM4MDExNzAwMDAwMFowOTEL\n" "MAkGA1UEBhMCVVMxDzANBgNVBAoTBkFtYXpvbjEZMBcGA1UEAxMQQW1hem9uIFJv\n" "b3QgQ0EgMTCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBALJ4gHHKeNXj\n" "ca9HgFB0fW7Y14h29Jlo91ghYPl0hAEvrAIthtOgQ3pOsqTQNroBvo3bSMgHFzZM\n" "9O6II8c+6zf1tRn4SWiw3te5djgdYZ6k/oI2peVKVuRF4fn9tBb6dNqcmzU5L/qw\n" "IFAGbHrQgLKm+a/sRxmPUDgH3KKHOVj4utWp+UhnMJbulHheb4mjUcAwhmahRWa6\n" "VOujw5H5SNz/0egwLX0tdHA114gk957EWW67c4cX8jJGKLhD+rcdqsq08p8kDi1L\n" "93FcXmn/6pUCyziKrlA4b9v7LWIbxcceVOF34GfID5yHI9Y/QCB/IIDEgEw+OyQm\n" "jgSubJrIqg0CAwEAAaNCMEAwDwYDVR0TAQH/BAUwAwEB/zAOBgNVHQ8BAf8EBAMC\n" "AYYwHQYDVR0OBBYEFIQYzIU07LwMlJQuCFmcx7IQTgoIMA0GCSqGSIb3DQEBCwUA\n" "A4IBAQCY8jdaQZChGsV2USggNiMOruYou6r4lK5IpDB/G/wkjUu0yKGX9rbxenDI\n" "U5PMCCjjmCXPI6T53iHTfIUJrU6adTrCC2qJeHZERxhlbI1Bjjt/msv0tadQ1wUs\n" "N+gDS63pYaACbvXy8MWy7Vu33PqUXHeeE6V/Uq2V8viTO96LXFvKWlJbYK8U90vv\n" "o/ufQJVtMVT8QtPHRh8jrdkPSHCa2XV4cdFyQzR1bldZwgJcJmApzyMZFo6IQ6XU\n" "5MsI+yMRQ+hDKXJioaldXgjUkK642M4UwtBV8ob2xJNDd2ZhwLnoQdeXeGADbkpy\n" "rqXRfboQnoZsG4q5WTP468SQvvG5\n" "-----END CERTIFICATE-----\n"; const char certificate_data[]= "-----BEGIN CERTIFICATE-----\n" "MIIDWTCCAkGgAwIBAgIUeM9VMqlYN68Lk7Fsxhvoa+PZ4LcwDQYJKoZIhvcNAQEL\n" "BQAwTTFLM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zp4SN6qwHBf0Ok3QvvAoGBAOm3\n" "tVawAerq12XuNkwoKuCbS+P+zIY4dGgT0Wcdpf34mAvejeCF0IkxJHV7YHLz3rJg\n" "V6KPJ+24P86qE67ODswZyBntMCf+QgTcbms5YC+AM/6Fqn47et4Vn5uMpNtYOzao\n" "xMrB0G/Ajs6dZQaMYXkjQ/vI/8/UgG9a8ClbGSPNAoGANAWWF7kXReHHj2JeeAFY\n" "f7cGDPV4BJP/bPgWbonP4PegDV6Nng6NtUImwwCToqvdNq7dm2Mi3ahDXKq9ny33\n" "S1XrQbH74Ex6lal1tPjwj6IPr9xxXBsuM2MkEcM+YC/STbFU5EfIxtWL1X497ygN\n" "Lj07ka7Wf/8XpCrDVxU1YPcCgYA8os/mVLW6qAEITfxCV+1/5mqTFWkkrYLt+a5L\n" "bXLCaHuyIKR4it8mqNxHqqHEUScG6l3yK+f1EedkC9YddRJ7u3ih2Vq0FZA1SKdR\n" "JEqjKETVFQK9y1q+QafuKFghHEwIi1K7M/uK8s9aJZWvVD55uj+KFITh+8TynwpO\n" "AHeORQKBgQC6cxbJYxGMcaOBAhidRyZIMz6CplMBT1FpP4UtSWK7NmVBEyTE7LDn\n" "QSveTmvt9E6Ag+QcL4UxfV9wfxWJHXPl8DIZo13nYDyt3iflgc0qUrBeRPvPXgUG\n" "cVxYYC3afV0QZJwcg3TzlSoohKnoTKtykxp7bF+AtWrgJoU0CggrsA==\n" "-----END RSA PRIVATE KEY-----\n"; uint32_t lastReconnectAttempt = 0;

TinyGsm modem(SerialAT, 0);

TinyGsmClient tcpClient(modem); SSLClientESP32 ssl_client(&tcpClient); PubSubClient mqttClient(ssl_client);void setup() { M5.begin(true, false, true); SPIFFS.begin(); Serial.println(">>ATOM DTU NB MQTT TEST"); SerialAT.begin(SIM7020_BAUDRATE, SERIAL_8N1, ATOM_DTU_SIM7020_RX, ATOM_DTU_SIM7020_TX); M5.dis.fillpix(0x0000ff); nbConnect(); log("rootca_data:"+String(rootca_data)); log("certificate_data:"+String(certificate_data)); log("privatekey_data:"+String(privatekey_data)); ssl_client.setCACert(rootca_data); ssl_client.setCertificate(certificate_data); ssl_client.setPrivateKey(privatekey_data); mqttClient.setCallback(mqttCallback);

}

void loop() { static unsigned long timer = 0;

if (!mqttClient.connected()) {
    log(">>MQTT NOT CONNECTED");
    log(mqttClient.state());
    // Reconnect every 10 seconds
    M5.dis.fillpix(0xff0000);
    uint32_t t = millis();
    if (t - lastReconnectAttempt > 10000L) {
        lastReconnectAttempt = t;
        if (mqttConnect()) {
            lastReconnectAttempt = 0;
        }
    }
    delay(100);
}
if (millis() >= timer) {
    timer = millis() + UPLOAD_INTERVAL;
    //mqttClient.publish(MQTT_U_TOPIC, "hello");  // 发送数据
    if (mqttClient.connected())
    {

      //先拼接出json字符串
      char param[120];
      char jsonBuf[178];
      sprintf(param, "{\"num\":[{\"v\":%d}]}",num); //我们把要上传的数据写在param里

      postMsgId += 1;
      num+=1;
      if(num>256){
        num=0;
      }
      sprintf(jsonBuf, ONENET_POST_BODY_FORMAT, postMsgId, param);

      log("public the data:"); 
      log(jsonBuf);
      log("\n");
      //client.publish("$dp", (uint8_t *)msg_buf, 3+strlen(msgJson));
      mqttClient.publish(ONENET_TOPIC_POST, jsonBuf);
      //发送数据到主题
      delay(500);

    }
}
M5.dis.fillpix(0x00ff00);
mqttClient.loop();
delay(200);

}

void mqttCallback(char topic, byte payload, unsigned int len) { char info[len + 1]; // 增加一个位置用于存放 null 终止字符 memcpy(info, payload, len); info[len] = '\0'; // 添加 null 终止符 log("Message arrived:"+String(info)); log("Topic received: " + String(topic)); // 打印接收到的主题 const char *success = "ok";

  // 提取主题中的参数
char *param = strstr(topic, "request/") + strlen("request/");

log("paramStart: " + String(param));
if (param != NULL ) {
    log("Extracted Parameter: " + String(param));
    // 构建新的主题
    char newTopic[200];
    sprintf(newTopic, "%s%s", ONENET_TOPIC_CMD, param);
    log("New Topic: " + String(newTopic));
    mqttClient.publish(newTopic, success);
    log(success);
} else {
    log("Parameter extraction failed.");
}

}

bool mqttConnect(void) { log("Connecting to "); log(MQTT_BROKER);

mqttClient.setServer(MQTT_BROKER, MQTT_PORT);               
bool status =mqttClient.connect(mqtt_devid); 
if (status == false) {
    int errorCode = mqttClient.state();
    log("MQTT Connection failed with error code: " + String(errorCode));
    return false;
}
log("MQTT CONNECTED!");
//mqttClient.publish(MQTT_U_TOPIC, "NB MQTT CLIENT ONLINE");
//mqttClient.subscribe(MQTT_D_TOPIC);
mqttClient.subscribe(ONENET_TOPIC_GET);
return mqttClient.connected();

}

void nbConnect(void) { unsigned long start = millis(); log("Initializing modem..."); while (!modem.init()) { log("waiting...." + String((millis() - start) / 1000) + "s"); };

start = millis();
log("Waiting for network...");
while (!modem.waitForNetwork()) {
    log("waiting...." + String((millis() - start) / 1000) + "s");
}
log("success");

}

heydan98 commented 5 months ago

Hello there. I found some repos that use sim 7600 and sim7080 to connect to aws, but there are no projects using sim 7020. Please let me know if sim7020 supports aws or not and have you fixed that error?

weekroom commented 5 months ago

@heydan98 sim7020 currently does not support the connection to aws, because the AT command to connect to a long URL will fail, which is a drawback of the AT command

heydan98 commented 5 months ago

Thank you very much. I cried a lot when I couldn't find a solution to this problem. Really thank you. P/s: Do you have any way to send data using sim7020 to thingsboard or any other database?

weekroom commented 5 months ago

@heydan98 I've only tried to access some iot platforms in China, thingsboard hasn't.

heydan98 commented 5 months ago

@weekroom Can you tell me if I change to using sim7080, will I be able to connect and send data to aws iot?

weekroom commented 5 months ago

@heydan98 You can refer to here https://github.com/govorox/SSLClient/tree/master/examples/Esp32-platformIO/t-call-esp32-sim800l-aws

heydan98 commented 5 months ago

I just tried to use sim 7080 to connect to aws but after setting the certificate I still can't connect. Can you tell me where I did wrong. Here is my AT log: [260589] Requesting current network time [260610] Year: 2024 Month: 6 Day: 21 [260611] Hour: 17 Minute: 20 Second: 58 [260611] Timezone: 7.00 [260611] Retrieving time again as a string [260632] Current Network Time: 24/06/21,17:20:58+28 Checking the status of network bearer ... Network bearer is not activated Activating network bearer ... Activation in progress, waiting for network response... Network bearer is activated successfully ! ............................................................................Step 8 start to write the root CA, device certificate and device private key to the modem INITFS SUCCESS AT+CFSINIT

Writing:1189 overage:0 Wirte done!!! INITFS SUCCESS AT+CFSINIT

Writing:1225 overage:0 Wirte done!!! INITFS SUCCESS AT+CFSINIT

Writing:1680 overage:0 Wirte done!!! Step 8 done ! ............................................................................Step 9 start to configure the TLS/SSL parameters AT+SMCONF?

+SMCONF:

CLIENTID: "Raspi"

URL: "a3rzyndk1wefwy.iot.us-west-2.amazonaws.com",8883

KEEPTIME: 60

USERNAME: ""

PASSWORD: ""

CLEANSS: 1

QOS: 1

TOPIC: ""

MESSAGE: ""

RETAIN: 0

SUBHEX: 0

ASYNCMODE: 0

OK

SSL with root CA and device certificate set up successfully! AT+SMSSL?

+SMSSL: 1,"rootCA.pem","deviceCert.crt"

OK

Step 9 done ! ............................................................................Step 10 start to connect AWS IOT Core Connecting to AWS IOT Core ... [323317] ### Unhandled: +APP PDP: 0,ACTIVE AT+SMCONN No valid response, retrying connect ...

Connect failed

weekroom commented 4 months ago

@heydan98 Your log doesn't seem to work quite like my sim7028. Try adding build_flags = -DCORE_DEBUG_LEVEL=3 to platform.ini. Can also consult the https://github.com/govorox/SSLClient/issues/71 here