Skip to Content
Technical Articles
Author's profile photo Jan Reichert

Connect an ESP32 to SAP Leonardo IoT

As the year comes to an end and a lot of you have some free time you might spend on some hacking, I want to share with you how you can connect some cheap hardware to SAP Leonardo IoT.

In this tutorial I’ll show you how to connect an ESP32. A developer board which you can buy for less than 10€, connect to a lot of different sensors and actors and use for nice demos. For the tutorial I assume that you know how to model Things in Leonardo IoT and therefore purely focus on the hardware part. If you’ve never used Leonardo IoT before I would recommend to first do two other tutorials: Create a Simple IoT Device Model and Create a Thing Model and Bind to Device.

As described in those two tutorials you should first model a Thing which matches the sensors you want to use.

 

Prepare your certificate

After you have created the model and instantiated a device you can download the certificate in pem format.

And copy the secret.

Now we need to convert the certificates, so that our ESP32 can handle them. Therefore, you need openssl.

After openssl is installed open a command line and navigate to the folder where your certificate is stored. Enter the command

openssl rsa -in <CertificateName>.pem -out key_full.pem

It will ask you for the pass phrase. Paste the secret you copied in the step before and press enter. Afterwards a new file key_full.pem is created. This is the private key for our device.

In the next step we will format the certificate:

openssl x509 -in <CertificateName>.pem -out cert_full.pem

This command will create a file called cert_full.pem.

 

Set up an ESP32 project

To set up a new project I will use Visual Studio Code, you can also use the Arduino IDE or any other IDE which supports ESP32. There are a lot of tutorials available for the different IDEs in combination with ESP32.

First of all, we have to install Platform IO within Visual Studio Code:

After you have installed Platform IO you can create a new Project:

The last step before we can start coding is to install a MQTT library:

 

 

Implement your MQTT Client

Next you can open the main.cpp file in Visual Studio Code and paste the following code:

#include <SPI.h>
  
#include <WiFiClientSecure.h>
 
#include <MQTTClient.h>

const char* ssid     = "<YourSSID>";
const char* password = "<YourWiFiPW>";
 
WiFiClientSecure espClient;
MQTTClient client;
 
const char* mqtt_server = "<YourIoTServiceInstance>.eu10.cp.iot.sap";
const char* ca_cert = \
"-----BEGIN CERTIFICATE-----\n" \
"MIIElDCCA3ygAwIBAgIQAf2j627KdciIQ4tyS8+8kTANBgkqhkiG9w0BAQsFADBh\n" \
"MQswCQYDVQQGEwJVUzEVMBMGA1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AMCowKAYIKwYBBQUHAgEWHGh0dHBzOi8v\n" \
"d3d3LmRpZ2ljZXJ0LmNvbS9DUFMwHQYDVR0OBBYEFA+AYRyCMWHVLyjnjUY4tCzh\n" \
"xtniMB8GA1UdIwQYMBaAFAPeUDVW0Uy7ZvCj4hsbw5eyPdFVMA0GCSqGSIb3DQEB\n" \
"CwUAA4IBAQAjPt9L0jFCpbZ+QlwaRMxp0Wi0XUvgBCFsS+JtzLHgl4+mUwnNqipl\n" \
"5TlPHoOlblyYoiQm5vuh7ZPHLgLGTUq/sELfeNqzqPlt/yGFUzZgTHbO7Djc1lGA\n" \
"8MXW5dRNJ2Srm8c+cftIl7gzbckTB+6WohsYFfZcTEDts8Ls/3HB40f/1LkAtDdC\n" \
"2iDJ6m6K7hQGrn2iWZiIqBtvLfTyyRRfJs8sjX7tN8Cp1Tm5gr8ZDOo0rwAhaPit\n" \
"c+LJMto4JQtV05od8GiG7S5BNO98pVAdvzr508EIDObtHopYJeS4d60tbvVS3bR0\n" \
"j6tJLp07kzQoH3jOlOrHvdPJbRzeXDLz\n" \
"-----END CERTIFICATE-----\n";
 
 
const char* cert = \
<YourCert>;


const char* key = \
<YourPrivateKey>;


void connect() {
  Serial.print("\nconnecting...");
    while (!client.connect("<DeviceAlternateId>", false)) {
      Serial.print(".");
        delay(2000);
      }
  Serial.println("\nconnected!");
}
 
void setup()
{
  Serial.begin(9600);
  SPI.begin();
  
  WiFi.begin(ssid, password);
  while (WiFi.status() != WL_CONNECTED) {
    Serial.print(".");
    delay(1000);
  }
  Serial.println("connected...yeey :)");
 
  espClient.setCACert(ca_cert);
  espClient.setCertificate(cert);
  espClient.setPrivateKey(key);
 
  client.begin(mqtt_server, 8883, espClient);
  connect();
}
 
 
void loop()
{
  if (!client.connected()) {
    connect();
  } 
 
  const char *cstr = "{\"sensorAlternateId\": \"<SensorAlternateId>\", \"capabilityAlternateId\": \"<CabailityAlternateId>\", \"measures\": [{ \"<Property>\": \"<Value>\" } ]}";
  client.publish("measures/<DeviceAlternateId>", cstr);
  Serial.println("Message sent");

  delay(5000);	
}

Replace everything in <> (e.g. <SensorAlternateId>), except the certificate and private key, with your specific information, coming from your WiFi and IoT Service instance.

Next you can go back to your command line tool and finish the preparation of your certificates. Use the following command:

cat *full.pem | sed -e 's/\(.*\)/\"\1\\n\" \\/g'

This will only work on UNIX based systems and will add a ” to the begin of each row and a \n” \ to the end (if you don’t have a UNIX based system you can do the adjustments manually). The result should look like this:

Now you can copy the certificate and the private key and paste it to your code and save the file.

 

Upload the code to your ESP32

Connect your ESP32 via USB to your computer. Next you can click the small upload icon in the lower left corner of Visual Studio Code. You should see some upload information. After the upload has finished click on the connector icon.

Now you should see the console log of your ESP32:

.........connected...yeey :)

connecting...
connected!
Message sent

And the sensor values in Leonardo IoT.

 

Next Steps

Now you have successfully and securely connected your ESP32 to SAP Leonardo IoT. And that was the hardest part. As a next step I would propose to connect one of the many available sensors out there and send some real data. No worries there are tons of great tutorials how to connect different sensors to your ESP32.

 

Happy hacking and a good start into 2020!

Assigned Tags

      8 Comments
      You must be Logged on to comment or reply to a post.
      Author's profile photo Abhishek Chowdhury
      Abhishek Chowdhury

      Thanks for the informative post !

      In your example the steps are as follows:-

      1. create cert_full.pem (this is the complete certificate with the private key included)
      2. This pem is then broken into two variables in your arduino code <const char* cert> and <const char* key>.
      3. So, I dont have unix and instead of the manually editing the cert_full.pem can i export the pem to a .CER/DER format and copy the contents ?
      Author's profile photo Jan Reichert
      Jan Reichert
      Blog Post Author

      Hi Abishek,

      Honestly I don't know if that's possible. You need to check the library [1] I'm using in my blog if you can also use those formats. But I'm sure there is also a way in Windows to adjust the certificate string accordingly.

       

      [1] https://github.com/espressif/arduino-esp32/tree/master/libraries/WiFiClientSecure

      Author's profile photo Marcin Nowak
      Marcin Nowak

      Hi!

      I try to use the code. The publishing fails. I get the error using method lastError(). It is -1, which means LWMQTT_BUFFER_TOO_SHORT.

      Do you have any idea, where is the problem?

      Author's profile photo Marcin Nowak
      Marcin Nowak

      The solution is to initialize MQTTClient object with bigger buffer.

      MQTTClient mqttClient(256);
      Author's profile photo Rene Vigl
      Rene Vigl

      Hi Jan,

      thanks for the awsome blog. With it I was able to connect an ESP32 a year ago
      I also connected an ESP8266 successfully based on your coding

      But now I'm working on a new project where I have to use an ESP32 and I'm unable to connect the ESP32 with the cloud.

      I noticed, that SAP changed their Certificate for the SCP, so I changed the ca_cert with the new certificate

      But unfortunatly that changed nothing
      I even generated a new certificated for the device, but it won't connect.

      The MQTTClient library you're using has the function lastError()
      this gives me an error message of -3 which stands for LWMQTT_NETWORK_FAILED_CONNECT

      So have you any idea what I'm missing?

      Best Regards

      PS. the ESP8266 is able to connect after the Certificate change

      Author's profile photo Jan Reichert
      Jan Reichert
      Blog Post Author

      Hi Rene,

      Sorry, I think I have not connected an ESP32 since I've written this blog. So I'm not sure why it is not working anymore.

      If you find a solution it would be great to share this here with the community.

      Regards Jan

      Author's profile photo Jay Adnure
      Jay Adnure

      Hi Rene Vigl,

      Were you able to solve the CA certificate issue? If so please share how you did it.

       

      Kr,

      Jay

      Author's profile photo Rene Vigl
      Rene Vigl

      Hi Jay,

      i used the wrong certificate and therfore i was unable to connect (i still don't know why the esp8266 is still working)
      there are multiple certificates in the "certificate path" and i don't remember which one i use at the moment but ths certificate works

      const char ca_cert[] PROGMEM  = R"EOF(
      -----BEGIN CERTIFICATE-----
      MIIE6jCCA9KgAwIBAgIQCjUI1VwpKwF9+K1lwA/35DANBgkqhkiG9w0BAQsFADBh
      MQswCQYDVQQGEwJVUzEVMBMGA1UEChMMRGlnaUNlcnQgSW5jMRkwFwYDVQQLExB3
      d3cuZGlnaWNlcnQuY29tMSAwHgYDVQQDExdEaWdpQ2VydCBHbG9iYWwgUm9vdCBD
      QTAeFw0yMDA5MjQwMDAwMDBaFw0zMDA5MjMyMzU5NTlaME8xCzAJBgNVBAYTAlVT
      MRUwEwYDVQQKEwxEaWdpQ2VydCBJbmMxKTAnBgNVBAMTIERpZ2lDZXJ0IFRMUyBS
      U0EgU0hBMjU2IDIwMjAgQ0ExMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKC
      AQEAwUuzZUdwvN1PWNvsnO3DZuUfMRNUrUpmRh8sCuxkB+Uu3Ny5CiDt3+PE0J6a
      qXodgojlEVbbHp9YwlHnLDQNLtKS4VbL8Xlfs7uHyiUDe5pSQWYQYE9XE0nw6Ddn
      g9/n00tnTCJRpt8OmRDtV1F0JuJ9x8piLhMbfyOIJVNvwTRYAIuE//i+p1hJInuW
      raKImxW8oHzf6VGo1bDtN+I2tIJLYrVJmuzHZ9bjPvXj1hJeRPG/cUJ9WIQDgLGB
      Afr5yjK7tI4nhyfFK3TUqNaX3sNk+crOU6JWvHgXjkkDKa77SU+kFbnO8lwZV21r
      eacroicgE7XQPUDTITAHk+qZ9QIDAQABo4IBrjCCAaowHQYDVR0OBBYEFLdrouqo
      qoSMeeq02g+YssWVdrn0MB8GA1UdIwQYMBaAFAPeUDVW0Uy7ZvCj4hsbw5eyPdFV
      MA4GA1UdDwEB/wQEAwIBhjAdBgNVHSUEFjAUBggrBgEFBQcDAQYIKwYBBQUHAwIw
      EgYDVR0TAQH/BAgwBgEB/wIBADB2BggrBgEFBQcBAQRqMGgwJAYIKwYBBQUHMAGG
      GGh0dHA6Ly9vY3NwLmRpZ2ljZXJ0LmNvbTBABggrBgEFBQcwAoY0aHR0cDovL2Nh
      Y2VydHMuZGlnaWNlcnQuY29tL0RpZ2lDZXJ0R2xvYmFsUm9vdENBLmNydDB7BgNV
      HR8EdDByMDegNaAzhjFodHRwOi8vY3JsMy5kaWdpY2VydC5jb20vRGlnaUNlcnRH
      bG9iYWxSb290Q0EuY3JsMDegNaAzhjFodHRwOi8vY3JsNC5kaWdpY2VydC5jb20v
      RGlnaUNlcnRHbG9iYWxSb290Q0EuY3JsMDAGA1UdIAQpMCcwBwYFZ4EMAQEwCAYG
      Z4EMAQIBMAgGBmeBDAECAjAIBgZngQwBAgMwDQYJKoZIhvcNAQELBQADggEBAHer
      t3onPa679n/gWlbJhKrKW3EX3SJH/E6f7tDBpATho+vFScH90cnfjK+URSxGKqNj
      OSD5nkoklEHIqdninFQFBstcHL4AGw+oWv8Zu2XHFq8hVt1hBcnpj5h232sb0HIM
      ULkwKXq/YFkQZhM6LawVEWwtIwwCPgU7/uWhnOKK24fXSuhe50gG66sSmvKvhMNb
      g0qZgYOrAKHKCjxMoiWJKiKnpPMzTFuMLhoClw+dj20tlQj7T9rxkTgl4ZxuYRiH
      as6xuwAwapu3r9rxxZf+ingkquqTgLozZXq8oXfpf2kUCwA/d5KxTVtzhwoT0JzI
      8ks5T1KESaZMkE4f97Q=
      -----END CERTIFICATE-----
      )EOF";

      Hopfully this helps you

      Best regards Rene