#include <WiFi.h>
#include <PubSubClient.h>
#include <string>
#include <iostream>
#include "SPI.h"
#include "Adafruit_GFX.h"
#include "Adafruit_ILI9341.h"
/* für PS-RAM-Einstellungen
platformio.ini: // ? muss hinzugefügt werden in Platformio.ini
build_flags = -DBOARD_HAS_PSRAM
-DCONFIG_SPIRAM_USE_MALLOC
-mfix-esp32-psram-cache-issue */
#define TFT_DC 2
#define TFT_CS 15
#define rand 7
Adafruit_ILI9341 tft = Adafruit_ILI9341(TFT_CS, TFT_DC);
// #define width 240
// #define hight 320
const char *ssid = "Wokwi-GUEST"; // Enter your Wi-Fi name
const char *password = ""; // Enter Wi-Fi password
// --------------------- function definitions -----------------------------
void callback(char *topic, byte *payload, unsigned int length);
void reconnect();
void maske (void);
void temperature (int);
void humidity (int);
void diverses ();
void farbpixel ();
// MQTT Broker: https://docs.emqx.com/en/cloud/latest/connect_to_deployments/esp32.html
const char *mqtt_broker = "broker.emqx.io";
const char *topic = "emqx/topic/esp32/"; // = SENDING / transmitting data-topic
const char *mqtt_username = "emqx"; // "emqx"
const char *mqtt_password = "public"; // "public"
const int mqtt_port = 1883;
const int mqtt_pause = 500; // give time to communicate (client - broker)
String client_id = ""; // Identifikation des esp32 am mqtt-broker
char *topic_message = "bli-bla-blu";
String mqttMessageReceived = "";
WiFiClient wifiClient; // WiFi-Client definition -> is handed over
PubSubClient mqttclient(wifiClient); // to MQTT=PubSubClient "mqttclient"
// AsyncMqttClient mqttclient;
// --------------------------- setup ---------------------------
void setup() {
Serial.begin(115200); // Set software serial baud to 115200;
WiFi.begin(ssid, password); // Connecting to a WiFi network
Serial.print("Connecting to WiFi...");
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println(""); Serial.println("Connected to the Wi-Fi network");
Serial.print("IP address: "); Serial.println(WiFi.localIP());
mqttclient.setServer(mqtt_broker, mqtt_port); //connecting to a mqtt broker
mqttclient.setCallback(callback); // "callback" = function for message output
while (!mqttclient.connected()) {
client_id = mqtt_username;
// String client_id = "esp32-mqttclient-"; // now global defined
client_id += String(WiFi.macAddress());
Serial.printf("The mqttclient %s connects to the public MQTT broker\n", client_id.c_str());
if (mqttclient.connect(client_id.c_str(), mqtt_username, mqtt_password)) {
Serial.printf("Public EMQX MQTT broker connected\n\n");
Serial.printf("client_id %s\n", client_id.c_str());
Serial.printf("WiFi MAC : %s\n", WiFi.macAddress().c_str()); // ---- c_str()
Serial.printf("mqttclient.state() %d\n\n", mqttclient.state());
Serial.printf("WiFi.status() %d\n\n", WiFi.status());
} else {
Serial.print("failed with state ");
Serial.print(mqttclient.state());
delay(2000);
}
mqttclient.subscribe(topic); // 1. subscription to topic, REsubscription in reconnect()
}
// ili9341 setup
tft.begin();
}
// ------------------------ global variables --------------------
const long timetowait = 5000;
long lastMsg = 0;
// --------------------- main / loop() function ----------------
void loop() {
long now = millis();
if (now - lastMsg > timetowait) {
lastMsg = now;
// code to handle within the mqtt-loop
if (!mqttclient.connected()) { reconnect(); }
// loop() checks input & output buffer and triggers action
// loop() sends data received in buffer -> mqttclient.publish,
// triggers actions=callback depending on the received data -> mqttclient.subscibe
mqttclient.loop();
// value convertion:
// dtostrf(float_value, min_width, num_digits_after_decimal, where_to_store_string);
// dtostrf(value_float, 6,2, value_char);
// integer to string:
// itoa(-31596,char_array,10); //(integer, char_array, base)#
// itoa: int = 2 Byte == nur für 4 Stellen geeignet
// ltoa (value_int, value_char, 4);
// -------------- Publish and subscribe --------------
mqttclient.publish(topic, topic_message); // publishing data
mqttclient.subscribe(topic); // receiving data
Serial.print("Message arrived in topic: ");
Serial.print(topic);
Serial.print(". Message: "); Serial.println (mqttMessageReceived);
delay(mqtt_pause); // give time to communicate (mqttclient - broker)
}
delay(4000);
}
// -------------------- end main / loop() -------------------------
// -------------------- callback function ------------------------
void callback(char* topic, byte* payload, unsigned int length) {
String messageTemp;
for (int i = 0; i < length; i++) {
messageTemp += (char)payload[i];
}
mqttMessageReceived = messageTemp;
}
/*
Message consists of: topic, payload.
topic: separated with "/", home/office/lamp (home = top-level, ...)
payload: value, can be everything, "text", true, json { temp: 33, pressure: 400 }
Topic QualityOfService Callback
__________________________________________ ________________ _____________
"channels/1393455/subscribe/fields/field2" 0 "showmessage"
on_connect: This function is called when the MQTT mqttclient receives a CONNACK = connection acknowledged.
on_subscribe: This function is called when the mqttclient receives a SUBACK = subscription has
been successfully completed.
on_message: This function is called when the mqttclient receives a PUBLISH message from the MQTT server.
Whenever the MQTT server publishes a message, based on the subscriptions for the mqttclient,
this function will be called.
The...
*/
// -------------------- mqtt reconnect --------------------------------
void reconnect() {
while (!mqttclient.connected()) { // Loop until we're reconnected
// String client_id = mqtt_username;
// client_id += String(WiFi.macAddress());
Serial.print (client_id); Serial.print(" Attempting MQTT connection ...");
// Serial.printf("The mqttclient %s connects to the MQTT broker\n", client_id);
// if (mqttclient.connect(client_id.c_str(), mqtt_username, mqtt_password)) {
if (mqttclient.connect(mqtt_username)) {
Serial.println("connected"); // connection existent
// Subscribe
mqttclient.subscribe(topic); // topic selection = subscribe
} else {
Serial.print("failed, rc=");
Serial.print(mqttclient.state());
Serial.println(" try again in 5 seconds");
delay(5000);
}
}
}
void farbpixel () {
// Farbpixel random am gesamten Bildschirm
int ROT = 255, GRUEN = 255, BLAU = 255;
tft.fillScreen(ILI9341_BLACK);
for (int i = 0; i < 7000; i ++)
{
int PixelX = random(1, tft.width());
int PixelY = random(1, tft.height());
tft.drawPixel(PixelX, PixelY, tft.color565(random(ROT),random(GRUEN),random(BLAU)));
delay(5);
}
delay(2000);
}
// --------- diverses -----------
void diverses (void) {
int i, j=1;
tft.fillScreen(ILI9341_BLACK);
tft.setCursor(rand, 120);
tft.setTextColor(ILI9341_RED);
tft.setTextSize(3);
tft.println("Hello ESP32");
tft.setCursor(rand, 160);
tft.setTextColor(ILI9341_GREEN);
tft.setTextSize(2);
tft.println("I can do SPI :-)");
delay(2000);
// Textsize ---------------------------
tft.fillScreen(ILI9341_BLACK);
tft.setTextColor(ILI9341_WHITE);
tft.setCursor(0,rand);
for (i=0;i<6;i++) {
// tft.setCursor(0,i);
tft.setTextSize(i);
tft.print("textsize ");
tft.println(i);
delay(2000);
}
// display size -----------------------
tft.setTextSize(1);
tft.fillScreen(ILI9341_YELLOW);
tft.setTextColor(ILI9341_BLUE);
tft.println(String(tft.width()));
tft.println(String(tft.height()));
delay(2000);
}
// Aufbau der Bildschirmmaske -------------
void maske (void)
{
int i, dicke=4;
tft.setRotation(1);
tft.fillScreen(ILI9341_CYAN);
tft.setTextColor(ILI9341_MAGENTA);
for (i=1;i<dicke;i++) {
tft.drawRoundRect(rand+i, rand+i, (tft.width()-2*rand)-2*i, (tft.height()-2*rand)-2*i, rand/2, ILI9341_RED);
tft.drawRoundRect(2*rand+i, 2*rand+i, (tft.width()-4*rand)-2*i, (tft.height()-4*rand)-2*i, rand/2, ILI9341_BLACK);
}
tft.setTextSize(3);
tft.setCursor(30,35);
tft.println("Parameter");
tft.setCursor(30,60);
tft.println("der Hauptmaske:");
for (i=1;i<dicke;i++)
tft.drawLine(20, 100+i, tft.width()-20, 100+i, ILI9341_BLACK);
tft.setTextSize(2);
tft.setCursor(4*rand,120);
tft.println("Temperatur:");
tft.setCursor(4*rand,150);
tft.println("Luftfeuchte:");
tft.setCursor(4*rand,180);
tft.print("Luftdruck:");
}
// void temperature (int);
// void humidity (int);