i wish to convert MQTT subscribe message sensor value to a string text so i been able to send telegram message thru the MQTT message publishing.
String message = "Distance 94"
String numberString = message.substring(13) // How long "Distance " is
if(numberString.toInt() > 80){
// do something
}
some one teach me this but it was not working,is there any more ways ?
#include <WiFi.h>
#include <PubSubClient.h>
#include <UniversalTelegramBot.h>
const char* ssid = "";
const char* password = "";
const char* mqttServer = "test.mosquitto.org";
const int mqttPort = 1883;
// ------- Telegram config ----------
#define BOT_TOKEN "" // your Bot Token (Get from Botfather)
#define chat_id "" // Chat ID of where you want the message to go (You can use
long Bot_lasttime;
int bulk_messages_mtbs = 10000; // testing to delay 6sec to detecting another distance and which message been sent .
WiFiClient espClient;
PubSubClient client(espClient);
UniversalTelegramBot bot(BOT_TOKEN, espClient);
String ipAddress = "";
volatile bool telegramButton1PressedFlag = false;
volatile bool telegramButton2PressedFlag = false;
void callback(char* topic, byte* payload, unsigned int length) {
Serial.print("Message arrived in topic: ");
Serial.println(topic);
Serial.println("Message");
for (int i = 0; i < length; i++) {
Serial.print((char)payload[i]);
}
Serial.println();
Serial.println("-----------------------");
}
void setup() {
Serial.begin(115200);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("Connected to the WiFi network");
client.setServer(mqttServer, mqttPort);
client.setCallback(callback);
while (!client.connected()) {
Serial.println("Connecting to MQTT...");
if (client.connect("ESP32Client")) {
Serial.println("connected Server");
} else {
Serial.print("failed with state ");
Serial.print(client.state());
delay(2000);
}
}
client.subscribe("testingdevice");
}
void sendTelegramMessage() {
String message = "testing 1";
if(bot.sendMessage(chat_id, message, "Markdown")){
Serial.println("TELEGRAM Message 1 Successfully sent");
}
telegramButton1PressedFlag = false;
}
void sendTelegramMessage2() {
String message2 = "testing 2";
if(bot.sendMessage(chat_id, message2, "Markdown")){
Serial.println("TELEGRAM Message 2 Successfully sent");
}
telegramButton2PressedFlag = false;
}
void loop() {
client.loop();
char topic;
String Message = "Distance 100";
String numberString = Message.substring(100); // How long "Distance " is
if(numberString.toInt() > 80){
Serial.println(numberString.toInt());
sendTelegramMessage();
delay(bulk_messages_mtbs);
Bot_lasttime = 0;
} else if(numberString.toInt() < 30) {
Serial.println(numberString.toInt());
sendTelegramMessage2();
delay(bulk_messages_mtbs);
Bot_lasttime = 0;
}
}
}