-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathlib.rs
1877 lines (1749 loc) · 62.9 KB
/
lib.rs
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
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#![deny(missing_docs)]
//! Use monome devices (Grid or Arc) in rust.
use std::fmt;
use std::io;
use std::net::{IpAddr, Ipv4Addr, SocketAddr};
use std::sync::Arc;
use std::thread;
use std::time::{Duration, Instant};
use futures::future::Either;
use tokio::net::UdpSocket;
use tokio::prelude::*;
use tokio::timer::Delay;
use futures::sync::mpsc::{UnboundedReceiver, UnboundedSender};
use rosc::decoder::decode;
use rosc::encoder::encode;
use rosc::{OscMessage, OscPacket, OscType};
use crossbeam::queue::ArrayQueue;
use futures::*;
use log::*;
/// The default port at which serialosc is running.
pub const SERIALOSC_PORT: u16 = 12002;
/// Port from which this library will start searching for free port when needed.
const START_PORT: u16 = 10_000;
/// After this number of milliseconds without receiving a device info message from seriaolc, this
/// library considers all the devices to have been received.
const DEVICE_ENUMERATION_TIMEOUT_MS: u64 = 500;
/// From a x and y position, and a stride, returns the offset at which the element is in an array.
fn toidx(x: i32, y: i32, width: i32) -> usize {
(y * width + x) as usize
}
/// Returns an osc packet from a address and arguments
fn build_osc_message(addr: &str, args: Vec<OscType>) -> OscPacket {
let message = OscMessage {
addr: addr.to_owned(),
args,
};
OscPacket::Message(message)
}
fn new_bound_socket() -> UdpSocket {
let mut port = START_PORT;
loop {
let server_addr = format!("127.0.0.1:{}", port).parse().unwrap();
let bind_result = UdpSocket::bind(&server_addr);
match bind_result {
Ok(socket) => break socket,
Err(e) => {
warn!("bind error: {}", e.to_string());
if port == 0 {
panic!("Could not bind socket: port exhausted");
}
}
}
port += 1;
}
}
/// An enum filled when a device has been added or removed, along with its name.
#[derive(Debug)]
pub enum DeviceChangeEvent {
/// A device has been added on the host and recognized by serialosc, and is now available for use.
Added(String),
/// A device has been removed on the host and is now unavailable for use.
Removed(String),
}
#[derive(Debug)]
struct MonomeInfo {
port: Option<i32>,
host: Option<String>,
prefix: Option<String>,
id: Option<String>,
size: Option<(i32, i32)>,
rotation: Option<i32>,
}
impl MonomeInfo {
fn new() -> MonomeInfo {
MonomeInfo {
port: None,
host: None,
prefix: None,
id: None,
size: None,
rotation: None,
}
}
fn complete(&self) -> bool {
self.port.is_some()
&& self.host.is_some()
&& self.prefix.is_some()
&& self.id.is_some()
&& self.size.is_some()
&& self.rotation.is_some()
}
fn fill(&mut self, packet: OscPacket) {
match packet {
OscPacket::Message(message) => {
if message.addr.starts_with("/sys") {
let args = message.args;
if message.addr.starts_with("/sys/port") {
if let OscType::Int(port) = args[0] {
self.port = Some(port);
}
} else if message.addr.starts_with("/sys/host") {
if let OscType::String(ref host) = args[0] {
self.host = Some(host.to_string());
}
} else if message.addr.starts_with("/sys/id") {
if let OscType::String(ref id) = args[0] {
self.id = Some(id.to_string());
}
} else if message.addr.starts_with("/sys/prefix") {
if let OscType::String(ref prefix) = args[0] {
self.prefix = Some(prefix.to_string());
}
} else if message.addr.starts_with("/sys/rotation") {
if let OscType::Int(rotation) = args[0] {
self.rotation = Some(rotation);
}
} else if message.addr.starts_with("/sys/size") {
if let OscType::Int(x) = args[0] {
if let OscType::Int(y) = args[1] {
self.size = Some((x, y));
}
}
}
}
}
OscPacket::Bundle(_bundle) => {
error!("Bundle during setup!?");
}
}
}
}
/// `Transport` implements the network input and output to and from serialosc.
struct Transport {
/// The address at which serialoscd is reachable.
addr: SocketAddr,
/// This is the socket with with we send and receive to and from the device.
socket: UdpSocket,
/// This is the channel we use to forward the received OSC messages to the client object.
tx: Arc<ArrayQueue<Vec<u8>>>,
/// This is where Transport receives the OSC messages to send.
rx: UnboundedReceiver<Vec<u8>>,
}
impl Transport {
pub fn new(
device_addr: IpAddr,
device_port: u16,
socket: UdpSocket,
tx: Arc<ArrayQueue<Vec<u8>>>,
rx: UnboundedReceiver<Vec<u8>>,
) -> Transport {
let addr = SocketAddr::new(device_addr, device_port);
Transport {
addr,
socket,
tx,
rx,
}
}
}
impl Future for Transport {
type Item = ();
type Error = io::Error;
fn poll(&mut self) -> Poll<(), io::Error> {
loop {
match self.rx.poll() {
Ok(fut) => {
match fut {
Async::Ready(b) => {
// This happens when shutting down usually
if b.is_some() {
let _amt =
try_ready!(self.socket.poll_send_to(&b.unwrap(), &self.addr));
} else {
break;
}
}
Async::NotReady => {
break;
}
}
}
Err(e) => {
error!("Error on future::mpsc {:?}", e);
}
}
}
loop {
let mut buf = vec![0; 1024];
match self.socket.poll_recv(&mut buf) {
Ok(fut) => match fut {
Async::Ready(_ready) => match self.tx.push(buf) {
Ok(()) => {
continue;
}
Err(e) => {
error!("receive from monome, {:?}", e);
}
},
Async::NotReady => {
return Ok(Async::NotReady);
}
},
Err(e) => {
return Err(e);
}
}
}
}
}
/// The client object for a Monome grid device
pub struct Monome {
/// The name of this device
name: String,
/// The type of this device
device_type: MonomeDeviceType,
/// The port at which this device is running at
port: u16,
/// The host for this device (usually localhost)
host: String,
/// The ID of this device
id: String,
/// The prefix set for this device
prefix: String,
/// The current rotation for this device. This can be 0, 90, 180 or 270.
rotation: i32,
/// THe x and y size for this device.
size: (i32, i32),
/// A channel that allows receiving serialized OSC messages from a device.
q: Arc<ArrayQueue<Vec<u8>>>,
/// A channel that allows sending serialized OSC messages to a device.
tx: UnboundedSender<Vec<u8>>,
}
/// Whether a key press is going up or down
#[derive(Debug)]
pub enum KeyDirection {
/// The key has been released.
Up,
/// The key has been pressed.
Down,
}
/// An event received from a monome device. This can be either a key press or release, a tilt
/// event, an encoder rotation event, or an encoder press or release.
pub enum MonomeEvent {
/// A key press or release
GridKey {
/// The horizontal offset at which the key has been pressed.
x: i32,
/// The vertical offset at which the key has been pressed.
y: i32,
/// Whether the key has been pressed (`Down`), or released (`Up`).
direction: KeyDirection,
},
/// A update about the tilt of this device.
Tilt {
/// Which sensor sent this tilt update.
n: i32,
/// The pitch of this device.
x: i32,
/// The roll of this device.
y: i32,
/// The yaw of this device.
z: i32,
},
/// An encoder delta information
EncoderDelta {
/// Which encoder is sending the event.
n: usize,
/// The delta of this movement on this encoder.
delta: i32,
},
/// A key press on an encoder (only available on some older devices).
EncoderKey {
/// Which encoder is sending the event.
n: usize,
/// Whether the encoder key has been pressed (`Down`), or released (`Up`).
direction: KeyDirection,
},
}
/// Converts an to a Monome method argument to a OSC address fragment and suitable OscType,
/// performing an eventual conversion.
pub trait IntoAddrAndArgs<'a, B> {
/// Converts an to a Monome method argument to a OSC address fragment and suitable OscType,
/// performing an eventual conversion.
fn as_addr_frag_and_args(&self) -> (String, B);
}
/// Used to make a call with an intensity value, adds the `"level/"` portion in the address.
impl<'a> IntoAddrAndArgs<'a, OscType> for i32 {
fn as_addr_frag_and_args(&self) -> (String, OscType) {
("level/".to_string(), OscType::Int(*self))
}
}
/// Used to make an on/off call, converts to 0 or 1.
impl<'a> IntoAddrAndArgs<'a, OscType> for bool {
fn as_addr_frag_and_args(&self) -> (String, OscType) {
("".to_string(), OscType::Int(if *self { 1 } else { 0 }))
}
}
impl<'a> IntoAddrAndArgs<'a, Vec<OscType>> for &'a [u8; 64] {
fn as_addr_frag_and_args(&self) -> (String, Vec<OscType>) {
// TODO: error handling both valid: either 64 or more intensity values, or 8 masks
let mut osctype_vec = Vec::with_capacity(64);
for item in self.iter().map(|i| OscType::Int(i32::from(*i))) {
osctype_vec.push(item);
}
("level/".to_string(), osctype_vec)
}
}
impl<'a> IntoAddrAndArgs<'a, Vec<OscType>> for u8 {
fn as_addr_frag_and_args(&self) -> (String, Vec<OscType>) {
// TODO: error handling both valid: either 64 or more intensity values, or 8 masks
let mut osctype_vec = Vec::with_capacity(1);
osctype_vec.push(OscType::Int(i32::from(*self)));
("".to_string(), osctype_vec)
}
}
impl<'a> IntoAddrAndArgs<'a, Vec<OscType>> for &'a [u8; 8] {
fn as_addr_frag_and_args(&self) -> (String, Vec<OscType>) {
// TODO: error handling both valid: either 64 or more intensity values, or 8 masks
let mut osctype_vec = Vec::with_capacity(8);
for item in self.iter().map(|i| OscType::Int(i32::from(*i))) {
osctype_vec.push(item);
}
("".to_string(), osctype_vec)
}
}
/// Used to convert vectors of bools for on/off calls, packs into a 8-bit integer mask.
impl<'a> IntoAddrAndArgs<'a, Vec<OscType>> for &'a [bool; 64] {
fn as_addr_frag_and_args(&self) -> (String, Vec<OscType>) {
// TODO: error handling
assert!(self.len() >= 64);
let mut masks = [0 as u8; 8];
for i in 0..8 {
// for each row
let mut mask: u8 = 0;
for j in (0..8).rev() {
// create mask
let idx = toidx(j, i, 8);
mask = mask.rotate_left(1) | if self[idx] { 1 } else { 0 };
}
masks[i as usize] = mask;
}
let mut osctype_vec = Vec::with_capacity(8);
for item in masks.iter().map(|i| OscType::Int(i32::from(*i))) {
osctype_vec.push(item);
}
("".to_string(), osctype_vec)
}
}
/// A type of device, either Grid (of various size), Arc (with 2 or 4 encoders), or unknown.
#[derive(PartialEq, Clone)]
pub enum MonomeDeviceType {
/// The type for a monome grid.
Grid,
/// The type for a monome arc.
Arc,
/// Unknown device, please file an issue.
Unknown,
}
impl From<&str> for MonomeDeviceType {
fn from(string: &str) -> MonomeDeviceType {
if string.contains("arc") {
MonomeDeviceType::Arc
} else {
MonomeDeviceType::Grid
}
}
}
impl fmt::Display for MonomeDeviceType {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(
f,
"{}",
if *self == MonomeDeviceType::Grid {
"grid"
} else {
"arc"
}
)
}
}
impl fmt::Debug for MonomeDeviceType {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}", self)
}
}
#[derive(Debug)]
/// A struct with basic informations about a Monome device, available without having set it up
pub struct MonomeDevice {
/// Name of the device with serial number
name: String,
/// Device type
device_type: MonomeDeviceType,
/// Host of the serialosc this device is on.
addr: IpAddr,
/// Port at which this device is available
port: u16,
}
impl fmt::Display for MonomeDevice {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}: {} ({})", self.name, self.device_type, self.port)
}
}
impl MonomeDevice {
fn new(name: &str, device_type: &str, addr: IpAddr, port: u16) -> MonomeDevice {
MonomeDevice {
name: name.to_string(),
device_type: device_type.into(),
addr,
port,
}
}
/// Return the device type.
pub fn device_type(&self) -> MonomeDeviceType {
self.device_type.clone()
}
/// Return the device name.
pub fn name(&self) -> String {
self.name.clone()
}
/// The host on which this device is attached.
pub fn host(&self) -> IpAddr {
self.addr
}
/// Return the port on which this device is.
pub fn port(&self) -> u16 {
self.port
}
}
impl Monome {
/// Register for device added/removed notifications, on a non-standard serialosc port
///
/// # Arguments
///
/// * `serialosc_port`: the port on which serialosc is running
/// - `callback`: a function that is called whenever a device is added or removed.
///
/// # Example
///
/// Print a message, on a machine where serialosc runs on the machine at 192.168.1.12, on port
/// 1234.
///
/// ```no_run
/// # use monome::Monome;
/// # use monome::DeviceChangeEvent;
/// Monome::register_device_change_callback_with_host_and_port("192.168.1.12".parse().unwrap(), 1234, |event| {
/// match event {
/// DeviceChangeEvent::Added(id) => {
/// println!("Device {} added", id);
/// }
/// DeviceChangeEvent::Removed(id) => {
/// println!("Device {} removed", id);
/// }
/// }
/// });
/// ```
pub fn register_device_change_callback_with_host_and_port(
serialosc_addr: IpAddr,
serialosc_port: u16,
callback: fn(DeviceChangeEvent),
) {
let mut socket = new_bound_socket();
thread::spawn(move || {
let server_port = socket.local_addr().unwrap().port();
let addr = SocketAddr::new(serialosc_addr, serialosc_port);
let packet = build_osc_message(
"/serialosc/notify",
vec![
OscType::String("127.0.0.1".to_string()),
OscType::Int(i32::from(server_port)),
],
);
let mut bytes: Vec<u8>;
// True if we've received a add or remove message from serialosc recently, and we need
// to tell it to notify this program in the future.
// This is necessary, because other messages can be received on this socket, notably the
// undocumented /sys/connect and /sys/disconnect messages (without any arguments).
let mut need_notify_msg = true;
loop {
bytes = encode(&packet).unwrap();
if need_notify_msg {
socket = socket
.send_dgram(bytes, &addr)
.wait()
.map(|(s, _)| s)
.unwrap();
need_notify_msg = false;
}
socket = socket.recv_dgram(vec![0u8; 1024]).and_then(|(socket, data, _, _)| {
match decode(&data).unwrap() {
OscPacket::Message(message) => {
if message.addr.starts_with("/serialosc/add") {
need_notify_msg = true;
if let OscType::String(ref id) = message.args[0] {
callback(DeviceChangeEvent::Added(id.to_string()));
}
} else if message.addr.starts_with("/serialosc/remove") {
if let OscType::String(ref id) = message.args[0] {
need_notify_msg = true;
callback(DeviceChangeEvent::Removed(id.to_string()));
}
} else {
debug!("⇦ Unexpected message receive on device change event socket {:?}", &message);
}
}
_ => {
debug!("⇦ Could not decode {:?}", data);
}
}
Ok(socket)
})
.wait()
.map(|socket| socket)
.unwrap();
}
});
}
/// Register for device added/removed notifications, on the default serialosc port, when it runs
/// on localhost.
///
/// # Arguments
///
/// - `callback`: a function that is called whenever a device is added or removed.
///
/// # Example
///
/// ```no_run
/// # use monome::Monome;
/// # use monome::DeviceChangeEvent;
/// Monome::register_device_change_callback(|event| {
/// match event {
/// DeviceChangeEvent::Added(id) => {
/// println!("Device {} added", id);
/// }
/// DeviceChangeEvent::Removed(id) => {
/// println!("Device {} removed", id);
/// }
/// }
/// });
/// ```
pub fn register_device_change_callback(callback: fn(DeviceChangeEvent)) {
Monome::register_device_change_callback_with_host_and_port(
std::net::IpAddr::V4(<Ipv4Addr>::LOCALHOST),
SERIALOSC_PORT,
callback,
)
}
/// Register for device added/removed notifications, on the default serialosc port, passing in
/// the address at which serialoscd is reachable.
///
/// # Arguments
///
/// - `addr`: the address on which serialoscd is reachable.
/// - `callback`: a function that is called whenever a device is added or removed.
///
/// # Example
///
/// ```no_run
/// # use monome::Monome;
/// # use monome::DeviceChangeEvent;
/// Monome::register_device_change_callback_with_host("192.168.1.12".parse().unwrap(), |event| {
/// match event {
/// DeviceChangeEvent::Added(id) => {
/// println!("Device {} added", id);
/// }
/// DeviceChangeEvent::Removed(id) => {
/// println!("Device {} removed", id);
/// }
/// }
/// });
/// ```
pub fn register_device_change_callback_with_host(
addr: IpAddr,
callback: fn(DeviceChangeEvent),
) {
Monome::register_device_change_callback_with_host_and_port(addr, SERIALOSC_PORT, callback)
}
/// Register for device added/removed notifications, on the specific serialosc port, when
/// serialoscd is running on localhost.
///
/// # Arguments
///
/// - `port`: the port at which serialoscd is.
/// - `callback`: a function that is called whenever a device is added or removed.
///
/// # Example
///
/// ```no_run
/// # use monome::Monome;
/// # use monome::DeviceChangeEvent;
/// Monome::register_device_change_callback_with_port(12012, |event| {
/// match event {
/// DeviceChangeEvent::Added(id) => {
/// println!("Device {} added", id);
/// }
/// DeviceChangeEvent::Removed(id) => {
/// println!("Device {} removed", id);
/// }
/// }
/// });
/// ```
pub fn register_device_change_callback_with_port(port: u16, callback: fn(DeviceChangeEvent)) {
Monome::register_device_change_callback_with_host_and_port(
std::net::IpAddr::V4(<Ipv4Addr>::LOCALHOST),
port,
callback,
)
}
fn setup<S>(
prefix: S,
device: &MonomeDevice,
) -> Result<(MonomeInfo, UdpSocket, String, MonomeDeviceType, u16), String>
where
S: Into<String>,
{
let (name, device_type, port) = (
device.name.to_string(),
device.device_type.clone(),
device.port,
);
let addr = SocketAddr::new(device.host(), device.port());
let socket = new_bound_socket();
let server_port = socket.local_addr().unwrap().port();
let packet = build_osc_message("/sys/port", vec![OscType::Int(i32::from(server_port))]);
let bytes: Vec<u8> = encode(&packet).unwrap();
let socket = socket
.send_dgram(bytes, &addr)
.wait()
.map(|(s, _)| s)
.unwrap();
let local_addr = socket.local_addr().unwrap().ip();
let packet = build_osc_message("/sys/host", vec![OscType::String(local_addr.to_string())]);
let bytes: Vec<u8> = encode(&packet).unwrap();
let socket = socket
.send_dgram(bytes, &addr)
.wait()
.map(|(s, _)| s)
.unwrap();
let packet = build_osc_message("/sys/prefix", vec![OscType::String(prefix.into())]);
let bytes: Vec<u8> = encode(&packet).unwrap();
let socket = socket
.send_dgram(bytes, &addr)
.wait()
.map(|(s, _)| s)
.unwrap();
let packet = build_osc_message("/sys/info", vec![]);
let bytes: Vec<u8> = encode(&packet).unwrap();
let mut socket = socket
.send_dgram(bytes, &addr)
.wait()
.map(|(s, _)| s)
.unwrap();
let mut info = MonomeInfo::new();
// Loop until we've received all the /sys/info messages
let socket = loop {
socket = socket
.recv_dgram(vec![0u8; 1024])
.and_then(|(socket, data, _, _)| {
let packet = decode(&data).unwrap();
info.fill(packet);
Ok(socket)
})
.wait()
.map(|socket| socket)
.unwrap();
if info.complete() {
break socket;
}
};
Ok((info, socket, name, device_type, port))
}
/// Enumerate all monome devices on a non-standard serialosc port, on a specific host.
///
/// If successful, this returns a list of MonomeDevice, which contain basic informations about
/// the device: type, serial number, port allocated by serialosc.
///
/// # Arguments
///
/// * `serialosc_addr: the address of the host on which serialosc runs
/// * `serialosc_port`: the port on which serialosc is running
///
/// # Example
///
/// Enumerate and display all monome device on port 1234:
///
/// ```no_run
/// # use monome::Monome;
/// let enumeration = Monome::enumerate_devices_with_host_and_port("192.168.1.12".parse().unwrap(), 1234);
/// match enumeration {
/// Ok(devices) => {
/// for device in &devices {
/// println!("{}", device);
/// }
/// }
/// Err(e) => {
/// eprintln!("Error: {}", e);
/// }
/// }
/// ```
pub fn enumerate_devices_with_host_and_port(
serialosc_addr: IpAddr,
serialosc_port: u16,
) -> Result<Vec<MonomeDevice>, String> {
let socket = new_bound_socket();
let mut devices = Vec::<MonomeDevice>::new();
let server_port = socket.local_addr().unwrap().port();
let server_ip = socket.local_addr().unwrap().ip().to_string();
let packet = build_osc_message(
"/serialosc/list",
vec![
OscType::String(server_ip),
OscType::Int(i32::from(server_port)),
],
);
let bytes: Vec<u8> = encode(&packet).unwrap();
let addr = SocketAddr::new(serialosc_addr, serialosc_port);
let (mut socket, _) = socket.send_dgram(bytes, &addr).wait().unwrap();
// loop until we find the device list message. It can be that some other messages are
// received in the meantime, for example, tilt messages, or keypresses. Ignore them
// here. If no message have been received for 500ms, consider we have all the messages and
// carry on.
loop {
let fut = socket.recv_dgram(vec![0u8; 1024]).select2(Delay::new(
Instant::now() + Duration::from_millis(DEVICE_ENUMERATION_TIMEOUT_MS),
));
let task = tokio::runtime::current_thread::block_on_all(fut);
socket = match task {
Ok(Either::A(((s, data, _, _), _))) => {
socket = s;
let packet = decode(&data).unwrap();
match packet {
OscPacket::Message(message) => {
if message.addr == "/serialosc/device" {
let args = message.args;
if let [OscType::String(ref name), OscType::String(ref device_type), OscType::Int(port)] =
args.as_slice()
{
devices.push(MonomeDevice::new(
name,
device_type,
serialosc_addr,
(*port) as u16,
));
}
}
}
OscPacket::Bundle(_bundle) => {
eprintln!("Unexpected bundle received during setup");
}
};
socket
}
Ok(Either::B(_)) => {
// timeout
break;
}
Err(e) => {
panic!("{:?}", e);
}
};
}
Ok(devices)
}
/// Enumerate all monome devices on the standard port on which serialosc runs (12002).
///
/// If successful, this returns a list of MonomeDevice, which contain basic informations about
/// the device: type, serial number, port allocated by serialosc.
///
/// # Arguments
///
/// * `serialosc_port`: the port on which serialosc is running
///
/// # Example
///
/// Enumerate and display all monome device on port 1234:
///
/// ```no_run
/// # use monome::Monome;
/// let enumeration = Monome::enumerate_devices();
/// match enumeration {
/// Ok(devices) => {
/// for device in &devices {
/// println!("{}", device);
/// }
/// }
/// Err(e) => {
/// eprintln!("Error: {}", e);
/// }
/// }
/// ```
pub fn enumerate_devices() -> Result<Vec<MonomeDevice>, String> {
Monome::enumerate_devices_with_port(SERIALOSC_PORT)
}
/// Enumerate all monome devices on localhost, on a specific port.
///
/// If successful, this returns a list of MonomeDevice, which contain basic informations about
/// the device: type, serial number, port allocated by serialosc.
///
/// # Arguments
///
/// * `port`: the port serialoscd is bound to.
///
/// # Example
///
/// Enumerate and display all monome device running on default port at a specific address.
///
/// ```no_run
/// # use monome::Monome;
/// # let enumeration = Monome::enumerate_devices_with_port(12012);
/// match enumeration {
/// Ok(devices) => {
/// for device in &devices {
/// println!("{}", device);
/// }
/// }
/// Err(e) => {
/// eprintln!("Error: {}", e);
/// }
/// }
/// ```
pub fn enumerate_devices_with_port(port: u16) -> Result<Vec<MonomeDevice>, String> {
Monome::enumerate_devices_with_host_and_port(
std::net::IpAddr::V4(<Ipv4Addr>::LOCALHOST),
port,
)
}
/// Enumerate all monome devices on the standard port on which serialosc runs (12002), on a
/// specific address.
///
/// If successful, this returns a list of MonomeDevice, which contain basic informations about
/// the device: type, serial number, port allocated by serialosc.
///
/// # Arguments
///
/// * `addr: the address at which serialosc is reachable
///
/// # Example
///
/// Enumerate and display all monome device running on default port at a specific addr.
///
/// ```no_run
/// # use monome::Monome;
/// let enumeration = Monome::enumerate_devices_on_host("192.168.1.12".parse().unwrap());
/// match enumeration {
/// Ok(devices) => {
/// for device in &devices {
/// println!("{}", device);
/// }
/// }
/// Err(e) => {
/// eprintln!("Error: {}", e);
/// }
/// }
/// ```
pub fn enumerate_devices_on_host(host: IpAddr) -> Result<Vec<MonomeDevice>, String> {
Monome::enumerate_devices_with_host_and_port(host, SERIALOSC_PORT)
}
/// Sets up the "first" monome device, with a particular prefix. When multiple devices are
/// plugged in, it's unclear which one is activated, however this is rare.
///
/// # Arguments
///
/// * `prefix` - the prefix to use for this device and this application
///
/// # Example
///
/// Set up a monome, with a prefix of "/prefix":
///
/// ```no_run
/// # use monome::Monome;
/// let m = Monome::new("/prefix");
///
/// match m {
/// Ok(monome) => {
/// println!("{:?}", monome);
/// }
/// Err(s) => {
/// println!("Could not setup the monome: {}", s);
/// }
/// }
/// ```
pub fn new<S>(prefix: S) -> Result<Monome, String>
where
S: Into<String>,
{
Monome::new_with_port(prefix, SERIALOSC_PORT)
}
/// Sets up the "first" monome device, with a particular prefix and a non-standard port for
/// serialosc. When multiple devices are plugged in, it's unclear which one is activated,
/// however this is rare.
///
/// # Arguments
///
/// * `prefix` - the prefix to use for this device and this application
/// * `serialosc_port` - the port at which serialosc can be reached.
///
/// # Example
///
/// Set up a monome, with a prefix of "/prefix", and specify an explicit port on which
/// serialosc can be reached (here, the default of 12002):
///
/// ```no_run
/// # use monome::Monome;
/// let m = Monome::new_with_port("/prefix", 12002);
///
/// match m {
/// Ok(monome) => {
/// println!("{:?}", monome);
/// }
/// Err(s) => {
/// println!("Could not setup the monome: {}", s);
/// }
/// }
/// ```
pub fn new_with_port<S>(prefix: S, serialosc_port: u16) -> Result<Monome, String>
where
S: Into<String>,
{
let devices = Monome::enumerate_devices_with_port(serialosc_port)?;
if devices.is_empty() {
return Err("No devices detected".to_string());
}
Monome::from_device(&devices[0], prefix.into())
}
/// Get a monome instance on which to call commands, from a `MonomeDevice`.
///
/// # Arguments
///
/// * `device`: a `MonomeDevice` acquired through `enumerate_devices`.
/// * `prefix`: the prefix to use for this device and this application
///
/// # Example
///
/// ```no_run
/// # use monome::Monome;
/// let enumeration = Monome::enumerate_devices();
/// match enumeration {
/// Ok(devices) => {
/// for device in &devices {
/// println!("{}", device);
/// match Monome::from_device(device, "prefix") {
/// Ok(m) => {
/// println!("Monome setup:\n{}", m);
/// }
/// Err(e) => {