added mqtt connection safety

This commit is contained in:
ishak jmilou.ishak
2025-01-08 14:15:06 +01:00
parent 361c17fbdb
commit 4bf3cd6d37

View File

@@ -17,6 +17,7 @@ void parseMQTT(std::string message);
void CapnSend();
void reconnectKobuki();
void monitorKobukiConnection();
void monitorMQTTConnection();
// ip, clientID, username, password
MqttClient client("ws://145.92.224.21/ws/", "KobukiRPI", "rpi",
"rpiwachtwoordofzo"); // create a client object
@@ -32,15 +33,16 @@ void setup() {
client.connect();
client.subscribe("home/commands");
// std::thread monitorThread(monitorKobukiConnection);
// monitorThread.detach();
std::thread monitorThread(monitorKobukiConnection);
std::thread mqttMonitorThread(monitorMQTTConnection);
mqttMonitorThread.detach();
monitorThread.detach();
}
int main() {
setup();
// reconnectKobuki();
reconnectKobuki();
// std::thread connectionMonitor(monitorKobukiConnection);
std::thread image(CapnSend);
std::thread safety([&]() { robot.robotSafety(&message); });
std::thread sendMqtt([&]() { sendKobukiData(robot.parser.data); });
@@ -57,29 +59,40 @@ int main() {
image.join();
}
// void reconnectKobuki() {
// unsigned char *null_ptr(0);
// while (true) {
// if (robot.startCommunication("/dev/ttyUSB0", true, null_ptr) != -1) {
// std::cout << "Kobuki opnieuw verbonden!" << std::endl;
// break; // Verlaat de loop als de verbinding succesvol is
// } else {
// std::cerr << "Kobuki niet verbonden. Probeer opnieuw over 3 seconden..." << std::endl;
// std::this_thread::sleep_for(std::chrono::seconds(3));
// }
// }
// }
void reconnectKobuki() {
unsigned char *null_ptr(0);
while (true) {
if (robot.startCommunication("/dev/ttyUSB0", true, null_ptr) != -1) {
std::cout << "Kobuki opnieuw verbonden!" << std::endl;
break; // Verlaat de loop als de verbinding succesvol is
} else {
std::cerr << "Kobuki niet verbonden. Probeer opnieuw over 3 seconden..." << std::endl;
std::this_thread::sleep_for(std::chrono::seconds(3));
}
}
}
// void monitorKobukiConnection() {
// while (true) {
// // Check regelmatig of de verbinding actief is
// if (!robot.isConnected()) {
// std::cerr << "Kobuki verbinding verloren. Reconnectie starten..." << std::endl;
// reconnectKobuki();
// }
// std::this_thread::sleep_for(std::chrono::seconds(5)); // Check iedere 5 seconden
// }
// }
void monitorKobukiConnection() {
while (true) {
// Check regelmatig of de verbinding actief is
if (!robot.isConnected()) {
std::cerr << "Kobuki verbinding verloren. Reconnectie starten..." << std::endl;
reconnectKobuki();
}
std::this_thread::sleep_for(std::chrono::seconds(5)); // Check iedere 5 seconden
}
}
void monitorMQTTConnection() {
while (true) {
if (!client.isConnected()) { // Controleer of de client nog verbonden is
std::cerr << "MQTT verbinding verloren. Probeer opnieuw te verbinden..." << std::endl;
client.connect();
client.subscribe("home/commands");
}
std::this_thread::sleep_for(std::chrono::seconds(5)); // Controleer iedere 5 seconden
}
}
std::string readMQTT() {