Problem gelöst, habe diesen Code gefunden von www.letscontrolit.com
Damit baut man einfach meine (ursprünglich) gewünschte Serial2MQTT Brücke auf.
#include <ESP8266WiFi.h>
#include <PubSubClient.h>
const char* ssid = "SSID";
const char* password = "PWD";
const char* mqtt_server = "192.168.XXX.XXX";
const char* topic_rx = "uart/rx";
const char* topic_tx = "uart/tx";
const byte numChars = 100;
char receivedChars[numChars]; // an array to store the received data
boolean newData = false;
WiFiClient espClient;
PubSubClient client(espClient);
void setup() {
pinMode(BUILTIN_LED, OUTPUT); // Initialize the BUILTIN_LED pin as an output
Serial.begin(9600);
setup_wifi();
client.setServer(mqtt_server, 1885);
client.setCallback(callback);
}
void setup_wifi() {
delay(10);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
}
}
void callback(char* topic, byte* payload, unsigned int length) {
for (int i = 0; i < length; i++) {
Serial.print((char)payload[i]);
}
Serial.println();
}
String macToStr(const uint8_t* mac)
{
String result;
for (int i = 0; i < 6; ++i) {
result += String(mac[i], 16);
if (i < 5)
result += ':';
}
return result;
}
void reconnect() {
String clientName;
clientName += "esp8266-";
uint8_t mac[6];
WiFi.macAddress(mac);
clientName += macToStr(mac);
clientName += "-";
clientName += String(micros() & 0xff, 16);
while (!client.connected()) {
if (client.connect((char*) clientName.c_str())) { // random client id
digitalWrite(BUILTIN_LED, LOW); // low = high, so this turns on the led
client.subscribe(topic_rx); // callback: mqtt bus -> arduino
} else {
digitalWrite(BUILTIN_LED, HIGH); // high = low, so this turns off the led
delay(5000);
}
}
}
void loop() {
if (!client.connected()) {
reconnect();
}
client.loop();
recvWithEndMarker();
showNewData();
}
void recvWithEndMarker() {
static byte ndx = 0;
char endMarker = '\n';
char rc;
while (Serial.available() > 0 && newData == false) {
rc = Serial.read();
if (rc != endMarker) {
receivedChars[ndx] = rc;
ndx++;
if (ndx >= numChars) {
ndx = numChars - 1;
}
}
else {
receivedChars[ndx] = '\0'; // terminate the string
ndx = 0;
newData = true;
}
}
}
void showNewData() {
if (newData == true) {
client.publish(topic_tx, receivedChars); // publish: arduino -> mqtt bus
newData = false;
}
}