/********************************************
* 18 Mar 2021 FG
*
* Code für das Senden von MQTT Nachrichten mittels
* client.publish("mein Topic", "meine Nachricht")
* Wobei "mein Topic" für unser Demo "workshop" lauten
* sollte
*
*********************************************/
#include <ESP8266WiFi.h>
#include <PubSubClient.h>
byte ledPin=D8;
long timestamp = 0;
// KONFIGURATION DES INTERNET-ZUGANGS
// ============================================
const char* ssid = "FRITZ!Box Fon WLAN 7360";
const char* password = "...";
String clientId = "ESP8266Client-Box01-";
// ============================================
const char* mqtt_server = "62.75.187.126";
const char* myTobic = "workshop";
WiFiClient espClient;
void callback(char* topic, byte* payload, unsigned int length) {
}
PubSubClient client(espClient);
unsigned long lastMsg = 0;
#define MSG_BUFFER_SIZE (50)
char msg[MSG_BUFFER_SIZE];
int value = 0;
void setup_wifi() {
delay(10);
// We start by connecting to a WiFi network
Serial.println();
Serial.print("Connecting to ");
Serial.println(ssid);
WiFi.mode(WIFI_STA);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
randomSeed(micros());
Serial.println("");
Serial.println("WiFi connected");
Serial.println("IP address: ");
Serial.println(WiFi.localIP());
}
void reconnect() {
// Loop until we're reconnected
while (!client.connected()) {
Serial.print("Attempting MQTT connection...");
if (client.connect(clientId.c_str())) {
Serial.println("connected. now subscribing...");
client.subscribe("LED");
String sendThis = clientId + ": connecting...";
client.publish(myTobic, sendThis.c_str());
} else {
Serial.print("failed, rc=");
Serial.print(client.state());
Serial.println(" try again in 5 seconds");
// Wait 5 seconds before retrying
delay(5000);
}
}
}
void setup() {
clientId += String(random(0xffff), HEX);
pinMode(D3, INPUT_PULLUP); // Hier den Taster anschließen
pinMode(D8, OUTPUT);
digitalWrite(D8, LOW);
Serial.begin(9600);
setup_wifi();
client.setServer(mqtt_server, 1883);
client.setCallback(callback);
}
/*********************************************************
*
* Code oberhalb der Loop-Funktion bitte nicht verändern bis
* auf die Konfigurationsparameter des Internets
*
**********************************************************/
void loop() {
if (!client.connected()) {
reconnect();
}
client.loop();
}