Skip to content

Instantly share code, notes, and snippets.

@ccutch
Created July 20, 2018 21:48
Show Gist options
  • Save ccutch/40cd97d45a2ef304f20bcfa32cbbbebf to your computer and use it in GitHub Desktop.
Save ccutch/40cd97d45a2ef304f20bcfa32cbbbebf to your computer and use it in GitHub Desktop.
Mqtt subscriber and publisher in rust
extern crate mqttc;
extern crate netopt;
extern crate ws;
use mqttc::{PubOpt, PubSub};
use std::{thread, time};
static USERNAME: &'static str = "";
static PASSWORD: &'static str = "";
fn new_client() -> mqttc::Client {
use mqttc::{ClientOptions, ReconnectMethod};
use netopt::{NetworkOptions, SslContext};
// Using ssl network connection
let mut netopt = NetworkOptions::new();
let ssl = SslContext::default();
netopt.tls(ssl);
// Using credentials for client
let mut opts = ClientOptions::new();
opts.set_username(USERNAME.to_string());
opts.set_password(PASSWORD.to_string());
let timeout = time::Duration::from_secs(1_0000);
opts.set_reconnect(ReconnectMethod::ReconnectAfter(timeout));
opts.connect("178.128.184.101:8883", netopt).unwrap()
}
fn listen_for_messages() {
let mut client = new_client();
client.subscribe("+/outbound").ok();
loop {
match client.await() {
Ok(Some(message)) => println!("message = {:?}", message),
Err(_) | Ok(_) => (),
}
}
}
fn main() {
thread::spawn(listen_for_messages);
let mut client = new_client();
loop {
let mut line = String::new();
std::io::stdin().read_line(&mut line).ok();
line.pop();
let line = line.as_str();
client
.publish("my-device/outbound", line, PubOpt::at_least_once())
.ok();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment