Skip to content

Instantly share code, notes, and snippets.

@progress44
Created June 24, 2025 16:12
Show Gist options
  • Save progress44/b8a70a74a48a052f62f7a9f9b5b81e3e to your computer and use it in GitHub Desktop.
Save progress44/b8a70a74a48a052f62f7a9f9b5b81e3e to your computer and use it in GitHub Desktop.
#include <WiFi.h>
#include <NetworkClientSecure.h>
#include <WiFiClientSecure.h>
#include <ssl_client.h>
#include <esp_chip_info.h>
#include <PubSubClient.h>
#include "soc/soc.h"
#include "soc/rtc_cntl_reg.h"
void initialize() {
WRITE_PERI_REG(RTC_CNTL_BROWN_OUT_REG, 0);
}
// WiFi
const char *ssid = "Artemis"; // Enter your WiFi name
const char *password = "PASSWORD"; // Enter WiFi password
// Personal MQTT Broker
const int mqtt_port = 8883;
const char *mqtt_broker = "mqtt.tcp.progress44.com";
const char *topic = "hassio/bedroom/led/motion";
const char *mqtt_username = "hassio";
const char *mqtt_password = "PASSWORD";
const char *le_root_ca = "-----BEGIN CERTIFICATE-----\n"
"MIIFYDCCBEigAwIBAgIQQAF3ITfU6UK47naqPGQKtzANBgkqhkiG9w0BAQsFADA/\n"
"MSQwIgYDVQQKExtEaWdpdGFsIFNpZ25hdHVyZSBUcnVzdCBDby4xFzAVBgNVBAMT\n"
"DkRTVCBSb290IENBIFgzMB4XDTIxMDEyMDE5MTQwM1oXDTI0MDkzMDE4MTQwM1ow\n"
"TzELMAkGA1UEBhMCVVMxKTAnBgNVBAoTIEludGVybmV0IFNlY3VyaXR5IFJlc2Vh\n"
"cmNoIEdyb3VwMRUwEwYDVQQDEwxJU1JHIFJvb3QgWDEwggIiMA0GCSqGSIb3DQEB\n"
"AQUAA4ICDwAwggIKAoICAQCt6CRz9BQ385ueK1coHIe+3LffOJCMbjzmV6B493XC\n"
"ov71am72AE8o295ohmxEk7axY/0UEmu/H9LqMZshftEzPLpI9d1537O4/xLxIZpL\n"
"wYqGcWlKZmZsj348cL+tKSIG8+TA5oCu4kuPt5l+lAOf00eXfJlII1PoOK5PCm+D\n"
"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CwUAA4IBAQAKcwBslm7/DlLQrt2M51oGrS+o44+/yQoDFVDC\n"
"5WxCu2+b9LRPwkSICHXM6webFGJueN7sJ7o5XPWioW5WlHAQU7G75K/QosMrAdSW\n"
"9MUgNTP52GE24HGNtLi1qoJFlcDyqSMo59ahy2cI2qBDLKobkx/J3vWraV0T9VuG\n"
"WCLKTVXkcGdtwlfFRjlBz4pYg1htmf5X6DYO8A4jqv2Il9DjXA6USbW1FzXSLr9O\n"
"he8Y4IWS6wY7bCkjCWDcRQJMEhg76fsO3txE+FiYruq9RUWhiF1myv4Q6W+CyBFC\n"
"Dfvp7OOGAN6dEOM4+qR9sdjoSYKEBpsr6GtPAQw4dy753ec5\n"
"-----END CERTIFICATE-----";
const int pirMotionPin1 = 5;
const int pirMotionPin2 = 4;
unsigned lastMovementDetected;
bool motionDetected = false;
unsigned pirDelay = 20000;
// init wifi secure client
WiFiClientSecure espClient;
// WiFiClient wifiClient;
PubSubClient mqttClient(espClient);
char *client_id = "esp32-client-bedroom-led";
void toggleLED(unsigned int ms) {
// digitalWrite(LED_BUILTIN, HIGH);
delay(ms);
// digitalWrite(LED_BUILTIN, LOW);
}
/**************************************************************************
* WiFi_init
* - Connect to local SSID
**************************************************************************/
bool WiFi_init() {
int connAttempts = 0;
Serial.print("\r\nConnecting to: ");
Serial.println(ssid);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
toggleLED(500);
Serial.print(".");
if (connAttempts > 20) return false;
connAttempts++;
}
Serial.println(" OK");
return true;
}
/**************************************************************************
* WiFiClientSecure_init
* - Connect to local SSID
**************************************************************************/
bool testWiFiSecure() {
espClient.setCACert(le_root_ca);
const char *server = "www.howsmyssl.com";
const char *domain_name = "www.howsmyssl.com";
const char *fingerprint = "D0:E4:10:9B:6A:D8:C5:B2:8E:8A:AC:80:B8:EA:FC:A8:BA:F0:D3:D6";
Serial.println("\r\nStarting connection to server...");
if (!espClient.connect(server, 443))
Serial.println("Connection failed!");
else {
// if (!espClient.verify(fingerprint, domain_name)) {
// Serial.println("Could not verify certificate");
// espClient.stop();
// }
Serial.println("Connected to server!");
// Make a HTTP request:
espClient.println("GET https://www.howsmyssl.com/a/check HTTP/1.0");
espClient.println("Host: www.howsmyssl.com");
espClient.println("Connection: close");
espClient.println();
while (espClient.connected()) {
String line = espClient.readStringUntil('\n');
Serial.println(line);
if (line == "\r") {
Serial.println("headers received");
break;
}
}
// if there are incoming bytes available
// from the server, read them and print them:
while (espClient.available()) {
char c = espClient.read();
Serial.write(c);
}
espClient.stop();
}
}
/**************************************************************************
* MQTT_init
* - Connect/reconnect to WiFi
* - Subscribe to MQTT topics
***************************************************************************/
void MQTT_init() {
mqttClient.setServer(mqtt_broker, mqtt_port);
mqttClient.setCallback(mqttCallback);
while (!mqttClient.connected()) {
Serial.printf("The client %s connects to the public MQTT broker\n", client_id);
if (mqttClient.connect(client_id, mqtt_username, mqtt_password)) {
Serial.println("MQTT broker connected");
mqttClient.subscribe(topic);
} else {
Serial.print("failed with state ");
Serial.print(mqttClient.state());
toggleLED(2000);
}
}
}
void mqttCallback(char *topic, byte *payload, unsigned int length) {
Serial.print("Message arrived in topic: ");
Serial.println(topic);
Serial.print("Message:");
for (int i = 0; i < length; i++) {
Serial.print((char)payload[i]);
}
Serial.println();
Serial.println("-----------------------");
}
/**************************************************************************
* MQTT_recon
* - Reconnect MQTT client (if WiFi is connected)
***************************************************************************/
void MQTT_recon() {
while (!mqttClient.connected()) {
// Attempt to connect
if (!mqttClient.connect(client_id, mqtt_username, mqtt_password)) {
toggleLED(1000);
}
}
}
/**************************************************************************
* isrDetectMovement
* - interrupt routine called when the PIR detected movement.
**************************************************************************/
void IRAM_ATTR isrDetectMovement() {
Serial.println(">>>>>>>> movement detected");
if (millis() - lastMovementDetected > pirDelay && !motionDetected) {
motionDetected = true;
lastMovementDetected = millis();
}
}
void setup() {
int res = 0;
// Set up LED light
// Turn Led On then off
pinMode(LED_BUILTIN, OUTPUT);
toggleLED(1000);
// Set software serial baud to 115200;
Serial.begin(115200);
Serial.setDebugOutput(true);
// WRITE_PERI_REG(RTC_CNTL_BROWN_OUT_REG, 0); // disable brownout detector
if (WiFi_init()) { // Connected to WiFi
Serial.print("WiFi connected.\n - RSSI: ");
Serial.print(WiFi.RSSI());
Serial.print(" Local IP: ");
Serial.println(WiFi.localIP());
} else {
Serial.println("WiFi connection failed! \nRestarting in 10s...");
toggleLED(10000);
ESP.restart();
}
espClient.setCACert(le_root_ca);
// espClient.setInsecure();
// testing ssl
// testWiFiSecure();
// Connecting to a mqtt broker
MQTT_init();
// Show board info
boardInfo();
// Set up PIR Motion sensor
pinMode(pirMotionPin1, INPUT_PULLUP);
// pinMode(pirMotionPin2, INPUT_PULLUP);
attachInterrupt(digitalPinToInterrupt(pirMotionPin1), isrDetectMovement, HIGH);
attachInterrupt(digitalPinToInterrupt(pirMotionPin2), isrDetectMovement, HIGH);
}
void boardInfo() {
// Show board detail
esp_chip_info_t espInfo;
esp_chip_info(&espInfo);
Serial.print("\t- Nr of cores: ");
Serial.println(espInfo.cores);
Serial.print("\t- ESP Model: ");
Serial.println(espInfo.model);
Serial.print("\t- Revision: ");
Serial.println(espInfo.revision);
Serial.print("\t- IDF version: ");
Serial.println(esp_get_idf_version());
}
void movementDetected() {
Serial.println(">>>>>>>> detected movement logged");
// publish and subscribe
// throttle the publishing of the message
mqttClient.publish(topic, "on");
toggleLED(500);
// reset the value
mqttClient.publish(topic, "off");
motionDetected = false;
}
void loop() {
if (motionDetected) {
movementDetected();
motionDetected = false;
}
mqttClient.loop();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment