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
use std::fmt::{self, Debug, Formatter};
use binread::{BinRead, BinReaderExt};
use modular_bitfield::prelude::*;
use crate::axis::*;
#[derive(BitfieldSpecifier, Debug)]
pub enum ControllerType {
Disconnected = 0,
Normal = 1,
Wavebird = 2,
Invalid = 3,
}
impl Default for ControllerType {
fn default() -> Self {
Self::Disconnected
}
}
#[bitfield]
#[derive(BinRead, Debug, Default, Copy, Clone, PartialEq)]
#[br(map = Self::from_bytes)]
pub struct ControllerStatus {
pub unk: bool,
pub unk2: bool,
pub has_rumble: bool,
pub unk3: bool,
pub controller_type: ControllerType,
padding: B2
}
#[bitfield]
#[derive(BinRead, Debug, Default)]
#[br(map = Self::from_bytes)]
pub struct Buttons {
pub a: bool,
pub b: bool,
pub x: bool,
pub y: bool,
pub dpad_left: bool,
pub dpad_right: bool,
pub dpad_down: bool,
pub dpad_up: bool,
pub start: bool,
pub z: bool,
pub right_trigger: bool,
pub left_trigger: bool,
pub padding: B4,
}
#[derive(BinRead, Debug, Default)]
pub struct Stick {
pub x: SignedAxis,
pub y: SignedAxis,
}
impl Stick {
pub fn raw(&self) -> (u8, u8) {
(self.x.raw(), self.y.raw())
}
pub fn coords(&self) -> (f32, f32) {
(self.x.float(), self.y.float())
}
pub fn coords_centered(&self, center: (u8, u8)) -> (f32, f32) {
(self.x.float_centered(center.0), self.y.float_centered(center.1))
}
}
#[derive(BinRead, Debug, Default)]
pub struct Triggers {
pub left: UnsignedAxis,
pub right: UnsignedAxis,
}
#[derive(BinRead, Default)]
pub struct Controller {
pub status: ControllerStatus,
pub buttons: Buttons,
pub left_stick: Stick,
pub right_stick: Stick,
pub triggers: Triggers,
}
impl Controller {
pub fn connected(&self) -> bool {
match self.status.controller_type() {
ControllerType::Normal | ControllerType::Wavebird => true,
ControllerType::Disconnected | ControllerType::Invalid => false,
}
}
}
impl Debug for Controller {
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
if self.connected() {
f.debug_struct("Controller")
.field("status", &self.status)
.field("buttons", &self.buttons)
.field("left_stick", &self.left_stick)
.field("right_stick", &self.right_stick)
.field("triggers", &self.triggers)
.finish()
} else {
f.write_str("Controller(Disconnected)")
}
}
}
#[derive(BinRead, Debug)]
pub enum Packet {
#[br(magic = 0x21u8)]
ControllerInfo {
ports: [Controller; 4],
},
Unknown(u8),
}
impl Packet {
pub fn parse(buffer: [u8; 37]) -> Self {
let mut reader = std::io::Cursor::new(&buffer[..]);
let packet: Packet = reader.read_ne().unwrap();
packet
}
}