Skip to content

Commit

Permalink
[MQTT] Publish a simple text
Browse files Browse the repository at this point in the history
  • Loading branch information
MrVyM committed Nov 30, 2023
1 parent a456681 commit 2b6d4bc
Show file tree
Hide file tree
Showing 3 changed files with 20 additions and 12 deletions.
2 changes: 1 addition & 1 deletion .env
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
MQTT_MAIN_TOPIC=robot
MQTT_CLIENT_NAME=Wall-e
MQTT_SERVER=127.0.0.1:1883
MQTT_SERVER=localhost:1883
SPEED_LIMIT_MIN=42
SPEED_LIMIT_MAX=42
WHEEL_DIAMETER=42
Expand Down
3 changes: 2 additions & 1 deletion src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ use std::time::Duration;

const FREQUENCY: f64 = 200.0;

#[allow(dead_code)]
fn heartbeat() {
println!("Heartbeat !");
}
Expand All @@ -24,7 +25,7 @@ fn main() {
.add_systems(Startup, hello_world)
.add_systems(Startup, print_arg)
.add_systems(Startup, connect_every_broker)
.add_systems(Update, heartbeat)
// .add_systems(Update, heartbeat)
.add_plugins(ScheduleRunnerPlugin::run_loop(Duration::from_secs_f64(
1.0 / FREQUENCY,
)))
Expand Down
27 changes: 17 additions & 10 deletions src/mqtt/mod.rs
Original file line number Diff line number Diff line change
@@ -1,11 +1,12 @@
use rumqttc::{Client, Connection, MqttOptions, QoS};
use std::thread;
use std::time::Duration;

use crate::cli::ressources::Args;
use bevy::prelude::*;

#[derive(Component)]
struct ClientConnection(Client, Connection);
struct ClientConnection(Connection);

// NOTE: Implement sync for the derive Component
// Could be useful to find a better solution
Expand All @@ -26,13 +27,19 @@ pub fn connect_every_broker(mut commands: Commands, args: Res<Args>) {
fn connect_client(client_name: String, broker: &str) -> ClientConnection {
let args = broker.split(':').collect::<Vec<&str>>();
println!("Connecting to {} with {} port", args[0], args[1]);
let mut mqtt_options = MqttOptions::new(client_name, args[0], args[1].parse::<u16>().unwrap());
mqtt_options.set_keep_alive(Duration::from_secs(5));

let (mut client, connection) = Client::new(mqtt_options, 10);
client.subscribe("hello/world", QoS::AtLeastOnce).unwrap();
client
.publish("hello/world", QoS::AtLeastOnce, false, "test")
.unwrap();
ClientConnection(client, connection)
let mqtt_options = MqttOptions::new(client_name, args[0], args[1].parse::<u16>().unwrap());
let (client, mut connection) = Client::new(mqtt_options, 10);
thread::spawn(move || publish(client));
for _ in connection.iter().enumerate() {}
ClientConnection(connection)
}

fn publish(mut client: Client) {
client.subscribe("hello/world", QoS::AtMostOnce).unwrap();
let payload = "coucou";
let qos = QoS::AtLeastOnce;

client.publish("hello/world", qos, true, payload).unwrap();

thread::sleep(Duration::from_secs(1));
}

0 comments on commit 2b6d4bc

Please sign in to comment.