1 extern crate sdl2;
2
main() -> Result<(), String>3 fn main() -> Result<(), String> {
4 let sdl_context = sdl2::init()?;
5 let joystick_subsystem = sdl_context.joystick()?;
6 let haptic_subsystem = sdl_context.haptic()?;
7
8 let available = joystick_subsystem.num_joysticks()
9 .map_err(|e| format!("can't enumerate joysticks: {}", e))?;
10
11 println!("{} joysticks available", available);
12
13 // Iterate over all available joysticks and stop once we manage to open one.
14 let joystick_index = (0..available).find_map(|id| match joystick_subsystem.open(id) {
15 Ok(c) => {
16 println!("Success: opened \"{}\"", c.name());
17 Some(id)
18 },
19 Err(e) => {
20 println!("failed: {:?}", e);
21 None
22 },
23 }).expect("Couldn't open any joystick");
24
25 let mut haptic = haptic_subsystem.open_from_joystick_id(joystick_index)
26 .map_err(|e| e.to_string())?;
27
28 for event in sdl_context.event_pump()?.wait_iter() {
29 use sdl2::event::Event;
30
31 match event {
32 Event::JoyAxisMotion{ axis_idx, value: val, .. } => {
33 // Axis motion is an absolute value in the range
34 // [-32768, 32767]. Let's simulate a very rough dead
35 // zone to ignore spurious events.
36 let dead_zone = 10_000;
37 if val > dead_zone || val < -dead_zone {
38 println!("Axis {} moved to {}", axis_idx, val);
39 }
40 }
41 Event::JoyButtonDown{ button_idx, .. } =>{
42 println!("Button {} down", button_idx);
43 haptic.rumble_play(0.5, 500);
44 },
45 Event::JoyButtonUp{ button_idx, .. } =>
46 println!("Button {} up", button_idx),
47 Event::JoyHatMotion{ hat_idx, state, .. } =>
48 println!("Hat {} moved to {:?}", hat_idx, state),
49 Event::Quit{..} => break,
50 _ => (),
51 }
52 }
53
54 Ok(())
55 }
56