#include #include #include #include #include #include "certificate.h" #include "secrets.h" #define CERT mqtt_broker_cert #define MSG_BUFFER_SIZE (50) 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; bool isOn = false; #define MAIN_CHANNEL "main" #define RELAY_1 1 //-------------------------------------- // globals //-------------------------------------- #ifdef MQTT_TLS WiFiClientSecure wifiClient; #else WiFiClient wifiClient; #endif WiFiUDP ntpUDP; NTPClient timeClient(ntpUDP); PubSubClient mqttClient(wifiClient); void setup_wifi() { delay(10); Serial.println(); Serial.print("Connecting to "); Serial.println(ssid); WiFi.begin(ssid, password); Serial.println("start while"); while (WiFi.status() != WL_CONNECTED) { delay(50); Serial.print("."); } Serial.println("i am here 1"); timeClient.begin(); Serial.println("WiFi connected"); } 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]); } if (isOn) { digitalWrite(RELAY_1, HIGH); isOn = false; } else { digitalWrite(RELAY_1, LOW); isOn = true; } Serial.println(); } void connect() { while (!mqttClient.connected()) { 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(MAIN_CHANNEL); mqttClient.publish(MAIN_CHANNEL, ("Whaddup can i stay? ")); } else { Serial.print("failed, rc="); Serial.print(mqttClient.state()); Serial.println(" will try again in 5 seconds"); delay(5000); } } } void setup() { Serial.begin(9600); Serial.println("run setup"); setup_wifi(); Serial.println("finish setup_wifi"); pinMode(RELAY_1, OUTPUT); mqttClient.setServer(mqtt_server, mqtt_server_port); mqttClient.setCallback(callback); } void loop() { if (!mqttClient.connected()) { connect(); } mqttClient.loop(); timeClient.update(); }