diff --git a/arduino/MQTT/MQTT.ino b/arduino/MQTT/MQTT.ino index 89d7765..575e917 100644 --- a/arduino/MQTT/MQTT.ino +++ b/arduino/MQTT/MQTT.ino @@ -1,113 +1,160 @@ -// Board: WiFiduino - -#include -// #include +#include #include -#include "arduino_secrets.h" #include +#include +#include +#include "certificate.h" +#include "secrets.h" -///////please enter your sensitive data in the Secret tab/arduino_secrets.h -char ssid[] = VITRINE_SSID; // your network SSID -char password[] = VITRINE_WIFI_PASS; // your network password +#define CERT mqtt_broker_cert +#define MSG_BUFFER_SIZE (50) -WiFiClient espClient; -MqttClient mqttClient(espClient); -PubSubClient mqtt_client(espClient); +//-------------------------------------- +// config (edit here before compiling) +//-------------------------------------- +// #define MQTT_TLS // uncomment this define to enable TLS transport +// #define MQTT_TLS_VERIFY // uncomment this define to enable broker certificate verification +const char* ssid = VITRINE_SSID; +const char* password = VITRINE_WIFI_PASS; +const char* mqtt_server = "mqtt.klank.school"; // eg. your-demo.cedalo.cloud or 192.168.1.11 +const uint16_t mqtt_server_port = 7000; // or 8883 most common for tls transport +const char* mqttUser = MQTT_ARDUINO_USERNAME; +const char* mqttPassword = MQTT_ARDUINO_PASS; +const char* mqttTopicIn = "esp-8266-in"; +const char* mqttTopicOut = "esp-8266-out"; -const char broker[] = "mqtt.klank.school"; -int port = 8883; -const char topic[] = "real_unique_topic"; -const char topic2[] = "real_unique_topic_2"; -const char topic3[] = "real_unique_topic_3"; -const char *mqtt_topic = "emqx/esp8266/led"; // -const char *mqtt_username = MQTT_ARDUINO_USERNAME; -const char *mqtt_password = MQTT_ARDUINO_PASS; +const char* rootCACertificate = R"( +-----BEGIN CERTIFICATE----- +MIIDvTCCAqWgAwIBAgIUIjMIFwrRWBr9z0lTWa7CQ0GcKV0wDQYJKoZIhvcNAQEL +BQAwdDELMAkGA1UEBhMCTkwxFTATBgNVBAgMDFp1aWQtSG9sbGFuZDESMBAGA1UE +BwwJUm90dGVyZGFtMRQwEgYDVQQKDAtLbGFua3Nja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bxd2s9/nPWPXk5YZryCvWvEHof23dE81OfVLaGYGdzL4ys5UiEWd/X8jP +1Q== +-----END CERTIFICATE----- +)"; + +//-------------------------------------- +// globals +//-------------------------------------- +#ifdef MQTT_TLS + WiFiClientSecure wifiClient; +#else + WiFiClient wifiClient; +#endif +WiFiUDP ntpUDP; +NTPClient timeClient(ntpUDP); +PubSubClient mqttClient(wifiClient); + +//-------------------------------------- +// function setup_wifi called once +//-------------------------------------- +void setup_wifi() { + + delay(10); + Serial.println(); + Serial.print("Connecting to "); + Serial.println(ssid); -void setup() { - //Initialize serial and wait for port to open: - Serial.begin(9600); - while (!Serial) { - ; // wait for serial port to connect. Needed for native USB port only - } - // attempt to connect to Wifi network: - Serial.print("Attempting to connect to SSID: "); - // WiFi.mode(WIFI_STA); WiFi.begin(ssid, password); while (WiFi.status() != WL_CONNECTED) { delay(500); - Serial.println(". stil not"); + Serial.print("."); } + timeClient.begin(); - Serial.println("You're connected to the network"); - Serial.println(); +#ifdef MQTT_TLS + #ifdef MQTT_TLS_VERIFY + // X509List *cert = new X509List(CERT); + // wifiClient.setTrustAnchors(cert); + wifiClient.setTrustAnchors(new BearSSL::X509List(rootCACertificate)); - Serial.print("Attempting to connect to the MQTT broker: "); - Serial.println(broker); + #else + wifiClient.setInsecure(); + #endif +#endif - while (!mqtt_client.connected()) { - String client_id = "esp8266-client-" + String(WiFi.macAddress()); - Serial.printf("Connecting to MQTT Broker as %s.....\n", client_id.c_str()); - if (mqtt_client.connect(client_id.c_str(), mqtt_username, mqtt_password)) { - Serial.println("Connected to MQTT broker"); - mqtt_client.subscribe(mqtt_topic); - // Publish message upon successful connection - mqtt_client.publish(mqtt_topic, "Hi EMQX I'm ESP8266 ^^"); - } else { - Serial.print("Failed to connect to MQTT broker, rc="); - Serial.print(mqtt_client.state()); - Serial.println(" try again in 5 seconds"); - delay(5000); - } - } - - Serial.println("You're connected to the MQTT broker!"); - Serial.println(); - - // set the message receive callback - mqttClient.onMessage(onMqttMessage); - - Serial.print("Subscribing to topic: "); - Serial.println(topic); - Serial.println(); - - // subscribe to a topic - mqttClient.subscribe(topic); - mqttClient.subscribe(topic2); - mqttClient.subscribe(topic3); - - // topics can be unsubscribed using: - // mqttClient.unsubscribe(topic); - - Serial.print("Topic: "); - Serial.println(topic); - Serial.print("Topic: "); - Serial.println(topic2); - Serial.print("Topic: "); - Serial.println(topic3); - - Serial.println(); + Serial.println("WiFi connected"); } +//-------------------------------------- +// function callback called everytime +// if a mqtt message arrives from the broker +//-------------------------------------- +void callback(char* topic, byte* payload, unsigned int length) { + Serial.print("Message arrived on topic: '"); + Serial.print(topic); + Serial.print("' with payload: "); + for (unsigned int i = 0; i < length; i++) { + Serial.print((char)payload[i]); + } + Serial.println(); + + String myCurrentTime = timeClient.getFormattedTime(); + mqttClient.publish(mqttTopicOut,("ESP8266: Cedalo Mosquitto is awesome. ESP8266-Time: " + myCurrentTime).c_str()); +} + +//-------------------------------------- +// function connect called to (re)connect +// to the broker +//-------------------------------------- +void connect() { + while (!mqttClient.connected()) { + + // Serial.println("The last error was"); + // Serial.println(wifiClient.getLastSSLError(NULL)); + + + Serial.print("Attempting MQTT connection..."); + String clientId = "ESP8266Client-"; + clientId += String(random(0xffff), HEX); + if (mqttClient.connect(clientId.c_str(), mqttUser, mqttPassword)) { + Serial.println("connected"); + mqttClient.subscribe(mqttTopicIn); + } else { + Serial.print("failed, rc="); + Serial.print(mqttClient.state()); + Serial.println(" will try again in 5 seconds"); + delay(5000); + } + } +} + +//-------------------------------------- +// main arduino setup fuction called once +//-------------------------------------- +void setup() { + Serial.begin(115200); + setup_wifi(); + mqttClient.setServer(mqtt_server, mqtt_server_port); + mqttClient.setCallback(callback); +} + +//-------------------------------------- +// main arduino loop fuction called periodically +//-------------------------------------- void loop() { - // call poll() regularly to allow the library to receive MQTT messages and - // send MQTT keep alive which avoids being disconnected by the broker - mqttClient.poll(); -} - -void onMqttMessage(int messageSize) { - // we received a message, print out the topic and contents - Serial.println("Received a message with topic '"); - Serial.print(mqttClient.messageTopic()); - Serial.print("', length "); - Serial.print(messageSize); - Serial.println(" bytes:"); - - // use the Stream interface to print the contents - while (mqttClient.available()) { - Serial.print((char)mqttClient.read()); + if (!mqttClient.connected()) { + connect(); } - Serial.println(); - Serial.println(); -} \ No newline at end of file + + mqttClient.loop(); + timeClient.update(); +} diff --git a/arduino/MQTT/certificate.h b/arduino/MQTT/certificate.h new file mode 100644 index 0000000..3f61cdf --- /dev/null +++ b/arduino/MQTT/certificate.h @@ -0,0 +1,27 @@ +// (re)place the trusted X509 certificate for the tls connection below +// default below: Let's Encrypt R3 +const char mqtt_broker_cert[] PROGMEM = R"( +-----BEGIN CERTIFICATE----- +MIIDvTCCAqWgAwIBAgIUIjMIFwrRWBr9z0lTWa7CQ0GcKV0wDQYJKoZIhvcNAQEL +BQAwdDELMAkGA1UEBhMCTkwxFTATBgNVBAgMDFp1aWQtSG9sbGFuZDESMBAGA1UE +BwwJUm90dGVyZGFtMRQwEgYDVQQKDAtLbGFua3NjaG9vbDENMAsGA1UECwwETVFU +VDEVMBMGA1UEAwwMa2xhbmsuc2Nob29sMB4XDTI0MTAyODExMjUwMFoXDTI1MTAy +ODExMjUwMFoweTELMAkGA1UEBhMCTkwxFTATBgNVBAgMDFp1aWQtSG9sbGFuZDES +MBAGA1UEBwwJUm90dGVyZGFtMRQwEgYDVQQKDAtLbGFua3NjaG9vbDENMAsGA1UE +CwwETVFUVDEaMBgGA1UEAwwRbXF0dC5rbGFuay5zY2hvb2wwggEiMA0GCSqGSIb3 +DQEBAQUAA4IBDwAwggEKAoIBAQDHiV7tLQdZg9qztSXYujw1dqL9lpqy5nDCkm8/ +Sd9wOh6SBMm65LvcJb3YBpoPfI6hwwOI+XcWsGiTTuOiCM3EemVYXkcc0VCjbgzn +FZ3Ld4s1jpXy+EgDaNhXXfFpREzStDOcRrmnIm5iHRiKdWAWeJTmYas915jzTCrk +ibhW9Qd9WZstxdccpjBWnB4X6uSMOeGdunAifTY8vVLQtaBlAqyoPbZk1ELbqKaz +zBso34euvKoPCPs8nkFR/RpLNStuOTVC8g+uCQ8nIgNlXpftvjMHvBsoq7ZdICRI +jx9uW4U0y2kEF7d3P9eLl07uJjxHhurB/J/kJHm5qc4tVcOXAgMBAAGjQjBAMB0G +A1UdDgQWBBRjQ4b5y5mEeidokSMz0pRetgNuRTAfBgNVHSMEGDAWgBR0e8d1l8aw +EGSdl1/vBUgQcmlV7jANBgkqhkiG9w0BAQsFAAOCAQEAaK8rrSeqLJIAr3v+GAdJ +yGqWK9qpJgXEbxYiuIj0pSejpDX3609qvyy7YEDUqLTu44ulZmrgGfrWAXg6Boms +CpBGybNNd7oYhcGJdSCURt2EgjkEP0eCVXo02l4JDrnaNvsBt9OhEVvNSFRxblyE +UmUTWeMh27T1/ioHeQpLIBf2BPOJZrMGeQGNfYujbtd8F4VQmGcOcfGsPhbvsaFR +dUut/VtKBnifKmZ/6afbmHHBUW6IjxTXBm8J0PrY9H5SR/Y7hEvbshlETFO5djMZ +6mmitx2Bxd2s9/nPWPXk5YZryCvWvEHof23dE81OfVLaGYGdzL4ys5UiEWd/X8jP +1Q== +-----END CERTIFICATE----- +)"; \ No newline at end of file diff --git a/arduino/MQTT/secrets.h b/arduino/MQTT/secrets.h new file mode 100644 index 0000000..71f40a9 --- /dev/null +++ b/arduino/MQTT/secrets.h @@ -0,0 +1,4 @@ +#define VITRINE_SSID ""; +#define VITRINE_WIFI_PASS "" +#define MQTT_ARDUINO_USERNAME "" +#define MQTT_ARDUINO_PASS "" \ No newline at end of file