How I can use the on_message function in scope inside the main function?

extern crate mosquitto_client as mosq;
use mosq::Mosquitto;

fn main() {
    let m = on_connect();
    let mut bonzo = m.subscribe("bonzo/#",0).expect("can't subscribe to bonzo");
    let mut frodo = m.subscribe("frodo/#",0).expect("can't subscribe to frodo");
    m.publish("bonzo/baggins", "hi".as_bytes(), 1, false).unwrap();
    m.publish("frodo/baggins", "hi".as_bytes(), 1, false).unwrap();
    on_message(&m, &mut bonzo, &mut frodo);
    m.loop_forever(200).expect("broken loop");

fn on_connect() -> mosq::Mosquitto {
    let m = Mosquitto::new("test");
    m.connect("",1883).expect("can't connect");

fn on_message(m: &mosq::Mosquitto, bonzo: &mut mosq::TopicMatcher<'_>, frodo: &mut mosq::TopicMatcher<'_>) {
    let mut mc = m.callbacks(());
    mc.on_message(|_,msg| {
        if ! msg.retained() {
            if bonzo.matches(&msg) {
                println!("bonzo {:?}",msg);
            } else
            if frodo.matches(&msg) {
                println!("frodo {:?}",msg);

When this code is executed no on_messages are printed eventhough I have published and subscribed? What is the problem?

I don't know. Try with a local mosquitto server instead of that online service.

Its ok I have managed to make everything work now.

Thanks for all your help.

1 Like

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.