1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
use std::os::raw::{c_int,c_char};
use std::ffi::{CStr,CString};
use std::error;
use std::fmt;
use std::path::Path;
use std::time::{Duration,Instant};
use std::fmt::{Display,Debug};
use std::ptr::null;
use std::sync::atomic::{AtomicUsize, Ordering, ATOMIC_USIZE_INIT};
static INSTANCES: AtomicUsize = ATOMIC_USIZE_INIT;
pub mod sys;
use sys::*;
#[derive(Debug)]
pub struct Error {
text: String,
errcode: i32,
connect: bool,
}
impl Display for Error {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f,"{}",self.text)
}
}
pub type Result<T> = ::std::result::Result<T,Error>;
impl Error {
pub fn new(msg: &str, rc: c_int) -> Error {
Error{text: format!("{}: {}",msg,mosq_strerror(rc)), errcode: rc, connect: false}
}
pub fn new_connect(rc: c_int) -> Error {
Error{text: connect_error(rc).into(), errcode: rc, connect: true}
}
fn result(call: &str, rc: c_int) -> Result<()> {
if rc != 0 {
Err(Error::new(call,rc))
} else {
Ok(())
}
}
pub fn error(&self) -> i32 {
self.errcode
}
}
impl error::Error for Error {
fn description(&self) -> &str {
&self.text
}
}
fn cs(s: &str) -> CString {
CString::new(s).expect("Text contained nul bytes")
}
fn cpath(p: &Path) -> CString {
cs(p.to_str().expect("Non UTF-8 filename"))
}
pub struct MosqMessage {
msg: *const Message,
owned: bool
}
use std::mem;
#[link(name = "c")]
extern {
fn malloc(size: usize) -> *mut u8;
}
impl MosqMessage {
fn new(msg: *const Message, clone: bool) -> MosqMessage {
if clone {
unsafe {
let m = malloc(mem::size_of::<Message>()) as *mut Message;
mosquitto_message_copy(m,msg);
MosqMessage{msg:m,owned:true}
}
} else {
MosqMessage{msg:msg, owned:false}
}
}
fn msg_ref(&self) -> &Message {
unsafe { &*self.msg }
}
pub fn topic(&self) -> &str {
unsafe { CStr::from_ptr(self.msg_ref().topic).to_str().expect("Topic was not UTF-8") }
}
pub fn payload(&self) -> &[u8] {
let msg = self.msg_ref();
unsafe {
::std::slice::from_raw_parts(
msg.payload,
msg.payloadlen as usize
)
}
}
pub fn text(&self) -> &str {
::std::str::from_utf8(self.payload()).expect("Payload was not UTF-8")
}
pub fn qos(&self) -> u32 {
self.msg_ref().qos as u32
}
pub fn retained(&self) -> bool {
if self.msg_ref().retain > 0 {true} else {false}
}
}
impl Debug for MosqMessage {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
let this = self.msg_ref();
write!(f,"{}: mid {} len {} qos {} retain {}",self.topic(),
this.mid, this.payloadlen, this.qos, this.retain)
}
}
impl Clone for MosqMessage {
fn clone(&self) -> Self {
MosqMessage::new(self.msg,true)
}
}
impl Drop for MosqMessage {
fn drop(&mut self) {
if self.owned {
unsafe { mosquitto_message_free(&self.msg) };
}
}
}
pub struct TopicMatcher<'a> {
sub: CString,
pub mid: i32,
mosq: &'a Mosquitto,
}
impl <'a>TopicMatcher<'a> {
fn new(sub: CString, mid: i32, mosq: &'a Mosquitto) -> TopicMatcher<'a> {
TopicMatcher{sub: sub, mid: mid, mosq: mosq}
}
pub fn matches(&self, msg: &MosqMessage) -> bool {
let mut matched: u8 = 0;
unsafe {
mosquitto_topic_matches_sub(self.sub.as_ptr(),msg.msg_ref().topic, &mut matched);
}
if matched > 0 {true} else {false}
}
fn receive(&self, millis: i32, just_one: bool) -> Result<Vec<MosqMessage>> {
let t = Instant::now();
let wait = Duration::from_millis(millis as u64);
let mut mc = self.mosq.callbacks(Vec::new());
mc.on_message(|data,msg| {
if self.matches(&msg) {
data.push(MosqMessage::new(msg.msg,true));
}
});
while t.elapsed() < wait {
self.mosq.do_loop(millis)?;
if just_one && mc.data.len() > 0 {
break;
}
}
if mc.data.len() > 0 {
let mut res = Vec::new();
::std::mem::swap(&mut mc.data, &mut res);
Ok(res)
} else {
Err(Error::new("receive",MOSQ_ERR_TIMEOUT))
}
}
pub fn receive_many(&self, millis: i32) -> Result<Vec<MosqMessage>> {
self.receive(millis,false)
}
pub fn receive_one(&self, millis: i32) -> Result<MosqMessage> {
self.receive(millis,true).map(|mut v| v.remove(0))
}
}
pub struct Version {
pub major: u32,
pub minor: u32,
pub revision: u32
}
impl Display for Version {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f,"{}.{}.{}",self.minor,self.major,self.revision)
}
}
pub fn version() -> Version {
let mut major: c_int = 0;
let mut minor: c_int = 0;
let mut revision: c_int = 0;
unsafe { mosquitto_lib_version(&mut major,&mut minor,&mut revision); }
Version{major: major as u32,minor: minor as u32,revision: revision as u32}
}
pub struct Mosquitto {
mosq: *const Mosq,
owned: bool,
}
impl Mosquitto {
pub fn new(id: &str) -> Mosquitto {
Mosquitto::new_session(id, true)
}
pub fn new_session(id: &str, clean_session: bool) -> Mosquitto {
if INSTANCES.fetch_add(1, Ordering::SeqCst) == 0 {
unsafe { mosquitto_lib_init(); }
}
let mosq = unsafe {
mosquitto_new(cs(id).as_ptr(),if clean_session {1} else {0},null())
};
Mosquitto{
mosq: mosq,
owned: true
}
}
pub fn callbacks<'a,T>(&'a self, data: T) -> Callbacks<'a,T> {
Callbacks::new(self,data)
}
pub fn connect(&self, host: &str, port: u32) -> Result<()> {
Error::result("connect",unsafe {
mosquitto_connect(self.mosq,cs(host).as_ptr(),port as c_int,0)
})
}
pub fn connect_wait(&self, host: &str, port: u32, millis: i32) -> Result<()> {
self.connect(host,port)?;
let t = Instant::now();
let wait = Duration::from_millis(millis as u64);
let mut callback = self.callbacks(MOSQ_CONNECT_ERR_TIMEOUT);
callback.on_connect(|data, rc| {
*data = rc;
});
loop {
self.do_loop(millis)?;
if callback.data == MOSQ_CONNECT_ERR_OK {
return Ok(())
};
if t.elapsed() > wait {
break;
}
}
Err(Error::new_connect(callback.data))
}
pub fn threaded(&self) {
unsafe { mosquitto_threaded_set(self.mosq,1); }
}
pub fn reconnect(&self) -> Result<()> {
Error::result("reconnect",unsafe {
mosquitto_reconnect(self.mosq)
})
}
pub fn reconnect_delay_set(&self,delay: u32, delay_max: u32, exponential_backoff: bool) -> Result<()> {
Error::result("delay_set",unsafe {
mosquitto_reconnect_delay_set(self.mosq,
delay as c_int,
delay_max as c_int,
exponential_backoff as u8
)})
}
pub fn subscribe<'a>(&'a self, sub: &str, qos: u32) -> Result<TopicMatcher<'a>> {
let mut mid: c_int = 0;
let sub = cs(sub);
let rc = unsafe { mosquitto_subscribe(self.mosq,&mut mid,sub.as_ptr(),qos as c_int) };
if rc == 0 {
Ok(TopicMatcher::new(sub,mid,self))
} else {
Err(Error::new("subscribe",rc))
}
}
pub fn unsubscribe(&self, sub: &str) -> Result<i32> {
let mut mid = 0;
let rc = unsafe { mosquitto_unsubscribe(self.mosq,&mut mid, cs(sub).as_ptr()) };
if rc == 0 {
Ok(mid as i32)
} else {
Err(Error::new("unsubscribe",rc))
}
}
pub fn publish(&self, topic: &str, payload: &[u8], qos: u32, retain: bool) -> Result<i32> {
let mut mid = 0;
let rc = unsafe { mosquitto_publish(
self.mosq,&mut mid, cs(topic).as_ptr(),
payload.len() as c_int,payload.as_ptr(),
qos as c_int, if retain {1} else {0}
)};
if rc == 0 {
Ok(mid as i32)
} else {
Err(Error::new("publish",rc))
}
}
pub fn will_set(&self, topic: &str, payload: &[u8], qos: u32, retain: bool) -> Result<()> {
Error::result("will_set",unsafe { mosquitto_will_set(
self.mosq, cs(topic).as_ptr(),
payload.len() as c_int,payload.as_ptr(),
qos as c_int, if retain {1} else {0}
)})
}
pub fn will_clear(&self) -> Result<()> {
Error::result("will_clear",unsafe {
mosquitto_will_clear(self.mosq)
})
}
pub fn publish_wait(&self, topic: &str, payload: &[u8], qos: u32, retain: bool, millis: i32) -> Result<i32> {
let our_mid = self.publish(topic,payload,qos,retain)?;
let t = Instant::now();
let wait = Duration::from_millis(millis as u64);
let mut callback = self.callbacks(0);
callback.on_publish(|data, mid| {
*data = mid;
});
loop {
self.do_loop(millis)?;
if callback.data == our_mid {
return Ok(our_mid)
};
if t.elapsed() > wait {
break;
}
}
Err(Error::new("publish",MOSQ_ERR_UNKNOWN))
}
pub fn disconnect(&self) -> Result<()> {
Error::result("disconnect",unsafe {
mosquitto_disconnect(self.mosq)
})
}
pub fn do_loop(&self, timeout: i32) -> Result<()> {
Error::result("do_loop",unsafe {
mosquitto_loop(self.mosq,timeout as c_int,1)
})
}
pub fn loop_forever(&self, timeout: i32) -> Result<()> {
Error::result("loop_forever",unsafe {
mosquitto_loop_forever(self.mosq,timeout as c_int,1)
})
}
pub fn loop_until_disconnect(&self, timeout: i32) -> Result<()> {
if let Err(e) = self.loop_forever(timeout) {
if e.error() == sys::MOSQ_ERR_NO_CONN {
Ok(())
} else {
Err(e)
}
} else {
Ok(())
}
}
pub fn tls_set<P1,P2,P3>(&self, cafile: P1, certfile: P2, keyfile: P3, passphrase: Option<&str>) -> Result<()>
where P1: AsRef<Path>, P2: AsRef<Path>, P3: AsRef<Path> {
Error::result("tls_set",unsafe {
let callback = if let Some(passphrase) = passphrase {
PASSWORD_PTR = cs(passphrase).into_raw();
PASSWORD_SIZE = passphrase.len();
true
} else {
false
};
mosquitto_tls_set(self.mosq,
cpath(cafile.as_ref()).as_ptr(),null() as *const c_char,
cpath(certfile.as_ref()).as_ptr(),cpath(keyfile.as_ref()).as_ptr(),
if callback {Some(mosq_password_callback)} else {None}
)
})
}
pub fn tls_psk_set(&self, psk: &str, identity: &str, ciphers: Option<&str>) -> Result<()> {
Error::result("tls_psk_set",unsafe {
let cipher;
let cipher_ptr = if let Some(ciphers) = ciphers {
cipher = cs(ciphers);
cipher.as_ptr()
} else {
null() as *const c_char
};
mosquitto_tls_psk_set(self.mosq,cs(psk).as_ptr(),cs(identity).as_ptr(),cipher_ptr)
})
}
}
static mut PASSWORD_PTR: *const c_char = 0 as *const c_char;
static mut PASSWORD_SIZE: usize = 0;
use std::ptr;
extern fn mosq_password_callback(buf: *mut c_char, _size: c_int, _rwflag: c_int, _userdata: *mut Data)->c_int {
unsafe {
ptr::copy(PASSWORD_PTR, buf, PASSWORD_SIZE+1);
PASSWORD_SIZE as c_int
}
}
unsafe impl Send for Mosquitto {}
unsafe impl Sync for Mosquitto {}
impl Clone for Mosquitto {
fn clone(&self) -> Mosquitto {
Mosquitto{
mosq: self.mosq,
owned: false
}
}
}
impl Drop for Mosquitto {
fn drop(&mut self) {
if self.owned {
unsafe { mosquitto_destroy(self.mosq); }
if INSTANCES.fetch_sub(1, Ordering::SeqCst) == 1 {
unsafe {mosquitto_lib_init();}
}
}
}
}
pub struct Callbacks<'a,T> {
message_callback: Option<Box<Fn(&mut T,MosqMessage) + 'a>>,
connect_callback: Option<Box<Fn(&mut T,i32) + 'a>>,
publish_callback: Option<Box<Fn(&mut T,i32) + 'a>>,
subscribe_callback: Option<Box<Fn(&mut T,i32) + 'a>>,
unsubscribe_callback: Option<Box<Fn(&mut T,i32) + 'a>>,
disconnect_callback: Option<Box<Fn(&mut T,i32) + 'a>>,
log_callback: Option<Box<Fn(&mut T,u32,&str) + 'a>>,
mosq: &'a Mosquitto,
init: bool,
pub data: T,
}
impl <'a,T> Callbacks<'a,T> {
pub fn new(mosq: &Mosquitto, data: T) -> Callbacks<T> {
Callbacks {
message_callback: None,
connect_callback: None,
publish_callback: None,
subscribe_callback: None,
unsubscribe_callback: None,
disconnect_callback: None,
log_callback: None,
mosq: mosq,
init: false,
data: data
}
}
pub fn mosq(&self) -> &Mosquitto {
self.mosq
}
fn initialize(&mut self) {
if ! self.init {
self.init = true;
let pdata: *const Callbacks<T> = &*self;
unsafe {
mosquitto_user_data_set(self.mosq.mosq, pdata as *const Data);
};
}
}
pub fn on_message<C: Fn(&mut T,MosqMessage) + 'a>(&mut self, callback: C) {
self.initialize();
unsafe {mosquitto_message_callback_set(self.mosq.mosq,mosq_message_callback::<T>);}
self.message_callback = Some(Box::new(callback));
}
pub fn on_connect<C: Fn(&mut T,i32) + 'a>(&mut self, callback: C) {
self.initialize();
unsafe {mosquitto_connect_callback_set(self.mosq.mosq,mosq_connect_callback::<T>);}
self.connect_callback = Some(Box::new(callback));
}
pub fn on_publish<C: Fn(&mut T,i32) + 'a>(&mut self, callback: C) {
self.initialize();
unsafe {mosquitto_publish_callback_set(self.mosq.mosq,mosq_publish_callback::<T>);}
self.publish_callback = Some(Box::new(callback));
}
pub fn on_subscribe<C: Fn(&mut T,i32) + 'a>(&mut self, callback: C) {
self.initialize();
unsafe {mosquitto_subscribe_callback_set(self.mosq.mosq,mosq_subscribe_callback::<T>);}
self.subscribe_callback = Some(Box::new(callback));
}
pub fn on_unsubscribe<C: Fn(&mut T,i32) + 'a>(&mut self, callback: C) {
self.initialize();
unsafe {mosquitto_unsubscribe_callback_set(self.mosq.mosq,mosq_unsubscribe_callback::<T>);}
self.unsubscribe_callback = Some(Box::new(callback));
}
pub fn on_disconnect<C: Fn(&mut T,i32) + 'a>(&mut self, callback: C) {
self.initialize();
unsafe {mosquitto_disconnect_callback_set(self.mosq.mosq,mosq_disconnect_callback::<T>);}
self.disconnect_callback = Some(Box::new(callback));
}
pub fn on_log<C: Fn(&mut T,u32,&str) + 'a>(&mut self, callback: C) {
self.initialize();
unsafe {mosquitto_log_callback_set(self.mosq.mosq,mosq_log_callback::<T>);}
self.log_callback = Some(Box::new(callback));
}
}
impl <'a,T>Drop for Callbacks<'a,T> {
fn drop(&mut self) {
unsafe {
mosquitto_user_data_set(self.mosq.mosq, null() as *const Data);
}
}
}
macro_rules! callback_ref {
($data:expr,$T:ident) =>
{
unsafe {&mut *($data as *mut Callbacks<$T>)}
}
}
extern fn mosq_connect_callback<T>(_: *const Mosq, data: *mut Data, rc: c_int) {
if data.is_null() { return; }
let this = callback_ref!(data,T);
if let Some(ref callback) = this.connect_callback {
callback(&mut this.data, rc as i32);
}
}
extern fn mosq_publish_callback<T>(_: *const Mosq, data: *mut Data, rc: c_int) {
if data.is_null() { return; }
let this = callback_ref!(data,T);
if let Some(ref callback) = this.publish_callback {
callback(&mut this.data, rc as i32);
}
}
extern fn mosq_message_callback<T>(_: *const Mosq, data: *mut Data, message: *const Message) {
if data.is_null() { return; }
let this = callback_ref!(data,T);
if let Some(ref callback) = this.message_callback {
callback(&mut this.data, MosqMessage::new(message,false));
}
}
extern fn mosq_subscribe_callback<T>(_: *const Mosq, data: *mut Data, rc: c_int) {
if data.is_null() { return; }
let this = callback_ref!(data,T);
if let Some(ref callback) = this.subscribe_callback {
callback(&mut this.data, rc as i32);
}
}
extern fn mosq_unsubscribe_callback<T>(_: *const Mosq, data: *mut Data, rc: c_int) {
if data.is_null() { return; }
let this = callback_ref!(data,T);
if let Some(ref callback) = this.unsubscribe_callback {
callback(&mut this.data, rc as i32);
}
}
extern fn mosq_disconnect_callback<T>(_: *const Mosq, data: *mut Data, rc: c_int) {
if data.is_null() { return; }
let this = callback_ref!(data,T);
if let Some(ref callback) = this.disconnect_callback {
callback(&mut this.data, rc as i32);
}
}
extern fn mosq_log_callback<T>(_: *const Mosq, data: *mut Data, level: c_int, text: *const c_char) {
if data.is_null() { return; }
let this = callback_ref!(data,T);
let text = unsafe { CStr::from_ptr(text).to_str().expect("log text was not UTF-8") };
if let Some(ref callback) = this.log_callback {
callback(&mut this.data, level as u32, text);
}
}