Secure ESP32 IoT Integration with Google Cloud IoT Core

The ESP32 microcontrollerArquitetura ESP32: SoC dual-core, subsistemas RF integradosArquitetura ESP32: SoC dual-core, subsistemas RF integradosDiscover the ESP32’s dual-core prowess and integrated RF subsystems for efficient, innovative IoT applications—from smart homes to industrial sensors., with its robust connectivity options, is widely used in IoT development. Google Cloud IoT Core provides a fully managed service for securely connecting, managing, and ingesting data from IoT devices at scale. This guide combines JWT authentication, MQTT communication, and telemetry transmission into a comprehensive workflow for ESP32 developersHybrid Cloud/Edge Architectures: ESP32 with AWS GreengrassHybrid Cloud/Edge Architectures: ESP32 with AWS GreengrassDiscover our comprehensive guide to integrating ESP32 with AWS Greengrass. Master hybrid cloud/edge solutions, security and practical IoT applications..

By the end of this article, you’ll understand how to:

Table of Contents🔗

1. JWT Authentication Overview

2. Setting Up Google Cloud IoT CoreConnecting ESP32 to Cloud Services via Wi-FiConnecting ESP32 to Cloud Services via Wi-FiDiscover how to connect your ESP32 to AWS, Azure, and Google Cloud using secure Wi-Fi. This guide covers setup, error handling, and low power strategies.

3. Generating and Signing JWTs on the ESP32Setting Up ESP32 as a Wi-Fi Access PointSetting Up ESP32 as a Wi-Fi Access PointMaster ESP32 AP configuration with our step-by-step guide. Set up a secure, local IoT network using practical code examples and optimization tips.

4. Connecting to Google Cloud IoT CoreConnecting ESP32 to Cloud Services via Wi-FiConnecting ESP32 to Cloud Services via Wi-FiDiscover how to connect your ESP32 to AWS, Azure, and Google Cloud using secure Wi-Fi. This guide covers setup, error handling, and low power strategies. via MQTT

5. Transmitting TelemetryReal-Time Data Streaming over LTE: Video and Telemetry with ESP32Real-Time Data Streaming over LTE: Video and Telemetry with ESP32Discover a comprehensive guide to real-time LTE streaming with ESP32 and SIM7000G for video and telemetry in robust IoT applications. Data Efficiently

6. Handling Errors and DebuggingConnecting ESP32 to Cloud Services via Wi-FiConnecting ESP32 to Cloud Services via Wi-FiDiscover how to connect your ESP32 to AWS, Azure, and Google Cloud using secure Wi-Fi. This guide covers setup, error handling, and low power strategies.

7. Security Best PracticesSetting Up Wi-Fi Station Mode on ESP32Setting Up Wi-Fi Station Mode on ESP32Master the ESP32 Wi-Fi Station Mode with our guide featuring configuration steps, error handling, and power-saving tips for effective IoT projects.

8. Real-World Use CaseZigbee Over-the-Air (OTA) Firmware Updates with ESP32 CoordinatorsZigbee Over-the-Air (OTA) Firmware Updates with ESP32 CoordinatorsSecure your IoT network with OTA firmware upgrades using an ESP32 coordinator. Our guide details firmware setup, packaging, security, and troubleshooting.: Smart Agriculture Monitoring

9. Troubleshooting Common IssuesZigbee Over-the-Air (OTA) Firmware Updates with ESP32 CoordinatorsZigbee Over-the-Air (OTA) Firmware Updates with ESP32 CoordinatorsSecure your IoT network with OTA firmware upgrades using an ESP32 coordinator. Our guide details firmware setup, packaging, security, and troubleshooting.

10. Conclusion

JWT Authentication Overview🔗

JSON Web Tokens (JWTs) are a compact, URL-safe method for secure device authentication. They consist of:

Setting Up Google Cloud IoT Core🔗

1. Create a Project: Use the Google Cloud Console to create a new project.

2. Enable APIs: Activate Cloud IoTSigfox Message Encoding: Packing Sensor Data into 12-byte PayloadsSigfox Message Encoding: Packing Sensor Data into 12-byte PayloadsLearn efficient data encoding techniques for Sigfox's constrained 12-byte payloads. Discover bitwise operations, structured encoding & CBOR strategies. Core and Cloud Pub/Sub.

3. Create a Registry: Group devices under a registry (e.g., by region or function).

4. Register Your ESP32Setting Up ESP32 as a Wi-Fi Access PointSetting Up ESP32 as a Wi-Fi Access PointMaster ESP32 AP configuration with our step-by-step guide. Set up a secure, local IoT network using practical code examples and optimization tips.: Add the device to the registry and upload its public key.

5. Generate Keys: Use OpenSSLAWS IoT Core with ESP32: X.509 Certificates and Shadow UpdatesAWS IoT Core with ESP32: X.509 Certificates and Shadow UpdatesLearn to securely connect ESP32 to AWS IoT Core using X.509 certificates and device shadows, with step-by-step instructions and best practices. to create an RSA key pair. Store the private key securely on the ESP32.

Generating and Signing JWTs on the ESP32🔗

Use the mbedTLS library for cryptographic operations.

#include <ArduinoJson.h>
#include <mbedtls/pk.h>
#include <mbedtls/md.h>
String createJWT(String projectId, String privateKey, int expirationSec) {
  // Header
  StaticJsonDocument<64> headerDoc;
  headerDoc["alg"] = "RS256";
  headerDoc["typ"] = "JWT";
  String headerStr;
  serializeJson(headerDoc, headerStr);
  // Payload
  StaticJsonDocument<256> payloadDoc;
  payloadDoc["iat"] = time(nullptr);
  payloadDoc["exp"] = time(nullptr) + expirationSec;
  payloadDoc["aud"] = projectId;
  String payloadStr;
  serializeJson(payloadDoc, payloadStr);
  // Base64 encode header and payload
  String encodedHeader = base64Encode(headerStr);
  String encodedPayload = base64Encode(payloadStr);
  String toSign = encodedHeader + "." + encodedPayload;
  // Sign with private key
  mbedtls_pk_context pk;
  mbedtls_pk_init(&pk);
  mbedtls_pk_parse_key(&pk, (const unsigned char*)privateKey.c_str(), privateKey.length() + 1, NULL, 0);
  unsigned char signature[512];
  size_t sigLen = 0;
  mbedtls_md_context_t ctx;
  mbedtls_md_init(&ctx);
  mbedtls_md_setup(&ctx, mbedtls_md_info_from_type(MBEDTLS_MD_SHA256), 1);
  mbedtls_md_starts(&ctx);
  mbedtls_md_update(&ctx, (const unsigned char*)toSign.c_str(), toSign.length());
  mbedtls_md_finish(&ctx, signature);
  mbedtls_md_free(&ctx);
  mbedtls_pk_free(&pk);
  // Combine components
  String encodedSig = base64Encode(signature, sigLen);
  return encodedHeader + "." + encodedPayload + "." + encodedSig;
}

Connecting to Google Cloud IoT Core via MQTT🔗

Configure the ESP32Setting Up ESP32 as a Wi-Fi Access PointSetting Up ESP32 as a Wi-Fi Access PointMaster ESP32 AP configuration with our step-by-step guide. Set up a secure, local IoT network using practical code examples and optimization tips. to use MQTT over TLS:

#include <WiFiClientSecure.h>
#include <MQTTClient.h>
WiFiClientSecure net;
MQTTClient client(512);
const char* googleRootCA = R"(-----BEGIN CERTIFICATE-----
MIIDX...Google Root CA...3AwDQYJKoZIhvcNAQELBQAwLg
-----END CERTIFICATE-----)";
void connectToCloudIoT() {
  net.setCACert(googleRootCA);
  client.begin("mqtt.googleapis.com", 8883, net);
  String clientId = "projects/PROJECT_ID/locations/REGION/registries/REGISTRY_ID/devices/DEVICE_ID";
  String jwt = createJWT("PROJECT_ID", PRIVATE_KEY, 3600);
  while (!client.connect(clientId.c_str(), "unused", jwt.c_str())) {
    Serial.print(".");
    delay(1000);
  }
  Serial.println("Connected!");
}

Transmitting Telemetry Data Efficiently🔗

Publish sensor dataSigfox Message Encoding: Packing Sensor Data into 12-byte PayloadsSigfox Message Encoding: Packing Sensor Data into 12-byte PayloadsLearn efficient data encoding techniques for Sigfox's constrained 12-byte payloads. Discover bitwise operations, structured encoding & CBOR strategies. to the /devices/{device-id}/events topic using JSON or Protocol BuffersReal-Time Data Streaming over LTE: Video and Telemetry with ESP32Real-Time Data Streaming over LTE: Video and Telemetry with ESP32Discover a comprehensive guide to real-time LTE streaming with ESP32 and SIM7000G for video and telemetry in robust IoT applications.:

void sendTelemetry(float temp, float humidity) {
  StaticJsonDocument<200> doc;
  doc["temp"] = temp;
  doc["humidity"] = humidity;
  char buffer[200];
  serializeJson(doc, buffer);
  String topic = "/devices/" + String(deviceId) + "/events";
  client.publish(topic.c_str(), buffer);
}
  • Optimization Tips:
  • Use QoS 1 for guaranteed delivery.
  • Batch data to reduce connection overhead.

Handling Errors and Debugging🔗

IssueSolution
JWT ExpiredRegenerate token before exp time.
MQTT DisconnectsImplement auto-reconnect logic.
SSL Handshake FailuresVerify root CA certificate.
void loop() {
  if (!client.connected()) {
    connectToCloudIoT();
  }
  client.loop();
}

Security Best Practices🔗

1. Secure Key Storage: Use ESP32 flash encryptionConnecting ESP32 to Cloud Services via Wi-FiConnecting ESP32 to Cloud Services via Wi-FiDiscover how to connect your ESP32 to AWS, Azure, and Google Cloud using secure Wi-Fi. This guide covers setup, error handling, and low power strategies. or hardware secure elements (e.g., ATECC608A).

2. Key Rotation: Follow Google’s guidelines to rotate keys periodically.

3. JWT Lifetime: Limit token validity to 1 hour or less.

4. Cloud Monitoring: Enable Cloud Logging and Alerting for anomaly detection.

Real-World Use Case: Smart Agriculture Monitoring🔗

Scenario: A farm uses ESP32 devicesPeer-to-Peer NFC Communication Between ESP32 DevicesPeer-to-Peer NFC Communication Between ESP32 DevicesDiscover how to set up NFC P2P communication on ESP32 devices. Our tutorial covers hardware, software integration, and practical security measures. with soil moisture sensors.

Implementation:

1. ESP32sSetting Up ESP32 as a Wi-Fi Access PointSetting Up ESP32 as a Wi-Fi Access PointMaster ESP32 AP configuration with our step-by-step guide. Set up a secure, local IoT network using practical code examples and optimization tips. generate JWTs using hardware-secured keys.

2. Data is transmitted every 15 minutes via MQTTConnecting ESP32 to Cloud Services via Wi-FiConnecting ESP32 to Cloud Services via Wi-FiDiscover how to connect your ESP32 to AWS, Azure, and Google Cloud using secure Wi-Fi. This guide covers setup, error handling, and low power strategies..

3. Cloud Functions analyze data and trigger irrigation.

Results:

  • 30% reduction in water usage.
  • Real-time alerts for abnormal soil conditions.

Troubleshooting Common Issues🔗

1. WiFiImplementing Over-the-Air (OTA) Updates via Wi-Fi on ESP32Implementing Over-the-Air (OTA) Updates via Wi-Fi on ESP32Learn how to implement secure and reliable OTA updates on ESP32 for enhanced IoT performance, easy updates, and rollback capability without physical access. Connectivity:

2. JWT Validation Failures:

  • Verify private/public key pairs match.
  • Check system time synchronization (use NTP).

3. MQTT TimeoutsAWS IoT Core with ESP32: X.509 Certificates and Shadow UpdatesAWS IoT Core with ESP32: X.509 Certificates and Shadow UpdatesLearn to securely connect ESP32 to AWS IoT Core using X.509 certificates and device shadows, with step-by-step instructions and best practices.:

Conclusion🔗

Integrating ESP32 with Google Cloud IoT CoreConnecting ESP32 to Cloud Services via Wi-FiConnecting ESP32 to Cloud Services via Wi-FiDiscover how to connect your ESP32 to AWS, Azure, and Google Cloud using secure Wi-Fi. This guide covers setup, error handling, and low power strategies. via JWT authentication enables scalable, secure IoT deployments. By following this guide, you can efficiently transmit telemetry data, handle errors gracefully, and adhere to critical security practices. Use the provided code snippets and real-world insights to accelerate your IoT projects.

Prerequisites

Additional Resources

Author: Marcelo V. Souza - Engenheiro de Sistemas e Entusiasta em IoT e Desenvolvimento de Software, com foco em inovação tecnológica.

References🔗

Share article

Related Articles