Skip to content

Instantly share code, notes, and snippets.

@betodealmeida
Created May 4, 2021 20:07
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save betodealmeida/393fdc27a9d74a3092521e2654666d16 to your computer and use it in GitHub Desktop.
Save betodealmeida/393fdc27a9d74a3092521e2654666d16 to your computer and use it in GitHub Desktop.
/*
1. Download and run https://raw.githubusercontent.com/esp8266/Arduino/master/libraries/ESP8266WiFi/examples/BearSSL_CertStore/certs-from-mozilla.py
2. Make sure the `certs.ar` file is in the `data/` directory in your project.
3. Download and install ESP8266LittleFS (see https://arduino-esp8266.readthedocs.io/en/latest/filesystem.html#uploading-files-to-file-system)
4. Run Tools > ESP8266 LittleFS Data Upload
5. Upload this sketch
/***************************************************
Adafruit MQTT Library ESP8266 Example
Must use ESP8266 Arduino from:
https://github.com/esp8266/Arduino
Works great with Adafruit's Huzzah ESP board & Feather
----> https://www.adafruit.com/product/2471
----> https://www.adafruit.com/products/2821
Adafruit invests time and resources providing this open source code,
please support Adafruit and open-source hardware by purchasing
products from Adafruit!
Written by Tony DiCola for Adafruit Industries.
MIT license, all text above must be included in any redistribution
****************************************************/
#include <ESP8266WiFi.h>
#include <CertStoreBearSSL.h>
#include <time.h>
#include <FS.h>
#include <LittleFS.h>
#include "Adafruit_MQTT.h"
#include "Adafruit_MQTT_Client.h"
#include "DHT.h"
/************************* WiFi Access Point *********************************/
#define WLAN_SSID "Estuary"
#define WLAN_PASS "XXX"
/************************* Adafruit.io Setup *********************************/
#define AIO_SERVER "mqtt.example.com"
#define AIO_SERVERPORT 8883 // use 8883 for SSL
#define AIO_USERNAME "srocto"
#define AIO_KEY "XXX"
/************************* Sensor configuration ******************************/
#define DHTPIN 14
#define DHTTYPE DHT22
DHT dht(DHTPIN, DHTTYPE);
/************************* Certificate configuration *************************/
// A single, global CertStore which can be used by all
// connections. Needs to stay live the entire time any of
// the WiFiClientBearSSLs are present.
BearSSL::CertStore certStore;
// Set time via NTP, as required for x.509 validation
void setClock() {
configTime(3 * 3600, 0, "pool.ntp.org", "time.nist.gov");
Serial.print("Waiting for NTP time sync: ");
time_t now = time(nullptr);
while (now < 8 * 3600 * 2) {
delay(500);
Serial.print(".");
now = time(nullptr);
}
Serial.println("");
struct tm timeinfo;
gmtime_r(&now, &timeinfo);
Serial.print("Current time: ");
Serial.print(asctime(&timeinfo));
}
/************ Global State (you don't need to change this!) ******************/
// Create an ESP8266 WiFiClient class to connect to the MQTT server.
//WiFiClient client;
// or... use WiFiClientSecure for SSL
//WiFiClientSecure *client;
BearSSL::WiFiClientSecure *client = new BearSSL::WiFiClientSecure();
// Setup the MQTT client class by passing in the WiFi client and MQTT server and login details.
Adafruit_MQTT_Client mqtt(client, AIO_SERVER, AIO_SERVERPORT, AIO_USERNAME, AIO_KEY);
/****************************** Feeds ***************************************/
// Setup a feed called 'photocell' for publishing.
// Notice MQTT paths for AIO follow the form: <username>/feeds/<feedname>
Adafruit_MQTT_Publish humidity = Adafruit_MQTT_Publish(&mqtt, AIO_USERNAME "/feeds/dht22/humidity");
Adafruit_MQTT_Publish temp_c = Adafruit_MQTT_Publish(&mqtt, AIO_USERNAME "/feeds/dht22/temp_c");
Adafruit_MQTT_Publish temp_f = Adafruit_MQTT_Publish(&mqtt, AIO_USERNAME "/feeds/dht22/temp_f");
Adafruit_MQTT_Publish heat_index_c = Adafruit_MQTT_Publish(&mqtt, AIO_USERNAME "/feeds/dht22/heat_index_c");
Adafruit_MQTT_Publish heat_index_f = Adafruit_MQTT_Publish(&mqtt, AIO_USERNAME "/feeds/dht22/heat_index_f");
// Setup a feed called 'onoff' for subscribing to changes.
//Adafruit_MQTT_Subscribe onoffbutton = Adafruit_MQTT_Subscribe(&mqtt, AIO_USERNAME "/feeds/onoff");
/*************************** Sketch Code ************************************/
// Bug workaround for Arduino 1.6.6, it seems to need a function declaration
// for some reason (only affects ESP8266, likely an arduino-builder bug).
void MQTT_connect();
void setup() {
Serial.begin(115200);
delay(10);
Serial.println(F("Adafruit MQTT demo"));
LittleFS.begin();
// Connect to WiFi access point.
Serial.println(); Serial.println();
Serial.print("Connecting to ");
Serial.println(WLAN_SSID);
WiFi.begin(WLAN_SSID, WLAN_PASS);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println();
Serial.println("WiFi connected");
Serial.println("IP address: "); Serial.println(WiFi.localIP());
setClock(); // Required for X.509 validation
int numCerts = certStore.initCertStore(LittleFS, PSTR("/certs.idx"), PSTR("/certs.ar"));
Serial.printf("Number of CA certs read: %d\n", numCerts);
if (numCerts == 0) {
Serial.printf("No certs found. Did you run certs-from-mozilla.py and upload the LittleFS directory before running?\n");
//return; // Can't connect to anything w/o certs!
client->setInsecure();
} else {
client->setCertStore(&certStore);
}
// Setup MQTT subscription for onoff feed.
//mqtt.subscribe(&onoffbutton);
dht.begin();
}
uint32_t x=0;
void loop() {
// Ensure the connection to the MQTT server is alive (this will make the first
// connection and automatically reconnect when disconnected). See the MQTT_connect
// function definition further below.
MQTT_connect();
// this is our 'wait for incoming subscription packets' busy subloop
// try to spend your time here
/*
Adafruit_MQTT_Subscribe *subscription;
while ((subscription = mqtt.readSubscription(5000))) {
if (subscription == &onoffbutton) {
Serial.print(F("Got: "));
Serial.println((char *)onoffbutton.lastread);
}
}
// Now we can publish stuff!
Serial.print(F("\nSending photocell val "));
Serial.print(x);
Serial.print("...");
if (! photocell.publish(x++)) {
Serial.println(F("Failed"));
} else {
Serial.println(F("OK!"));
}
*/
// Wait a few seconds between measurements.
delay(60000);
// Reading temperature or humidity takes about 250 milliseconds!
// Sensor readings may also be up to 2 seconds 'old' (its a very slow sensor)
float h = dht.readHumidity();
// Read temperature as Celsius (the default)
float t = dht.readTemperature();
// Read temperature as Fahrenheit (isFahrenheit = true)
float f = dht.readTemperature(true);
// Check if any reads failed and exit early (to try again).
if (isnan(h) || isnan(t) || isnan(f)) {
Serial.println(F("Failed to read from DHT sensor!"));
return;
}
// Compute heat index in Fahrenheit (the default)
float hif = dht.computeHeatIndex(f, h);
// Compute heat index in Celsius (isFahreheit = false)
float hic = dht.computeHeatIndex(t, h, false);
humidity.publish(h);
temp_c.publish(t);
temp_f.publish(f);
heat_index_c.publish(hic);
heat_index_f.publish(hif);
// ping the server to keep the mqtt connection alive
// NOT required if you are publishing once every KEEPALIVE seconds
/*
if(! mqtt.ping()) {
mqtt.disconnect();
}
*/
}
// Function to connect and reconnect as necessary to the MQTT server.
// Should be called in the loop function and it will take care if connecting.
void MQTT_connect() {
int8_t ret;
// Stop if already connected.
if (mqtt.connected()) {
return;
}
Serial.print("Connecting to MQTT... ");
uint8_t retries = 3;
while ((ret = mqtt.connect()) != 0) { // connect will return 0 for connected
Serial.println(mqtt.connectErrorString(ret));
Serial.println("Retrying MQTT connection in 5 seconds...");
mqtt.disconnect();
delay(5000); // wait 5 seconds
retries--;
if (retries == 0) {
// basically die and wait for WDT to reset me
while (1);
}
}
Serial.println("MQTT Connected!");
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment