can send messages to server from cpp

This commit is contained in:
2024-11-05 12:54:51 +01:00
parent ce5412847f
commit 222b14b9e5
3 changed files with 21 additions and 8 deletions

View File

@@ -1,6 +1,7 @@
#include "MqttClient.h"
MqttClient::MqttClient(const std::string& address, const std::string& clientId, const std::string& username, const std::string& password)
//client_ is the connection
: client_(address, clientId), username_(username), password_(password), callback_(*this) {
client_.set_callback(callback_);
options.set_clean_session(true);
@@ -32,6 +33,16 @@ void MqttClient::subscribe(const std::string& topic, int qos) {
}
}
void MqttClient::publishMessage(const std::string& topic, const std::string& payload) {
try {
std::cout << "Publishing message: " << payload << std::endl;
client_.publish(topic, payload)->wait();
} catch (const mqtt::exception& exc) {
std::cerr << "Error: " << exc.what() << std::endl;
throw;
}
}
/// @brief Only needed when program doesnt keep itself alive
void MqttClient::run() {
// Keep the client running to receive messages
@@ -41,7 +52,7 @@ void MqttClient::run() {
}
void MqttClient::Callback::message_arrived(mqtt::const_message_ptr msg) {
//lock the variable, it automaticly unlocks when going out of scope
//lock the variable, it automaticly unlocks when going out of scope using lock_guard
std::lock_guard<std::mutex> lock(client_.messageMutex_);
client_.lastMessage_ = msg->to_string();
}
@@ -58,7 +69,7 @@ void MqttClient::Callback::delivery_complete(mqtt::delivery_token_ptr token) {
/// @return The last message received in a string
//std::string is the datatype of the return value
std::string MqttClient::getLastMessage() {
//lock the variable, it automaticly unlocks when going out of scope
//lock the variable, it automaticly unlocks when going out of scope using lock_guard
std::lock_guard<std::mutex> lock(messageMutex_);
return lastMessage_;
}

View File

@@ -13,6 +13,7 @@ public:
void subscribe(const std::string& topic, int qos = 1);
void run();
std::string getLastMessage();
void publishMessage(const std::string& topic, const std::string& payload);
private:
class Callback : public virtual mqtt::callback {

View File

@@ -24,12 +24,13 @@ void setup(){
int main(){
setup();
std::thread safety([&]() { robot.robotSafety(&message); });
while(true){
parseMQTT(readMQTT());
}
safety.join();
return 0;
// std::thread safety([&]() { robot.robotSafety(&message); });
// while(true){
// parseMQTT(readMQTT());
// }
// safety.join();
// return 0;
client.publishMessage("kobuki/data", "aaaa");
}
std::string readMQTT()