-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathmain.rs
307 lines (261 loc) · 8.97 KB
/
main.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
use anyhow::{bail, Context, Result};
use bose_dfu::device_ids::{identify_device, DeviceCompat, DeviceMode, UsbId};
use bose_dfu::dfu_file::parse as parse_dfu_file;
use bose_dfu::protocol::{download, ensure_idle, enter_dfu, leave_dfu, read_info_field};
use clap::Parser;
use hidapi::{DeviceInfo, HidApi, HidDevice};
use log::{info, warn};
use std::io::Read;
use std::path::Path;
use thiserror::Error;
#[derive(Parser, Debug)]
#[command(version, about)]
enum Opt {
/// List all connected Bose HID devices (vendor ID 0x05a7)
List,
/// Get information about a specific device not in DFU mode
Info {
#[command(flatten)]
spec: DeviceSpec,
},
/// Put a device into DFU mode
EnterDfu {
#[command(flatten)]
spec: DeviceSpec,
},
/// Take a device out of DFU mode
LeaveDfu {
#[command(flatten)]
spec: DeviceSpec,
},
/// Write firmware to a device in DFU mode
Download {
#[command(flatten)]
spec: DeviceSpec,
file: std::path::PathBuf,
#[arg(short, long)]
wildcard_fw: bool,
},
/// Print metadata about a firmware file, no device needed
FileInfo { file: std::path::PathBuf },
}
#[derive(Parser, Debug)]
struct DeviceSpec {
/// USB serial number
#[arg(short)]
serial: Option<String>,
/// USB product ID as an unprefixed hex string (only matches vendor ID 05a7)
#[arg(short, value_parser = parse_pid)]
pid: Option<u16>,
/// Proceed with operation even if device is untested or might be in wrong mode
#[arg(short, long)]
force: bool,
/// Required device mode (derived automatically from chosen subcommand)
#[arg(skip)]
required_mode: Option<DeviceMode>,
}
fn parse_pid(src: &str) -> Result<u16, std::num::ParseIntError> {
u16::from_str_radix(src, 16)
}
fn main() -> Result<()> {
env_logger::Builder::from_env(
env_logger::Env::new()
.filter_or("BOSE_DFU_LOG", "info")
.write_style("BOSE_DFU_LOG_STYLE"),
)
.format_timestamp(None)
.init();
let mode = Opt::parse();
let api = HidApi::new()?;
match mode {
Opt::List => list_cmd(&api),
Opt::Info { spec } => {
let spec = DeviceSpec {
required_mode: Some(DeviceMode::Normal),
..spec
};
let (dev, info) = spec.get_device(&api)?;
use bose_dfu::protocol::InfoField::*;
println!("USB serial: {}", info.serial_number().unwrap_or("INVALID"));
println!("HW serial: {}", read_info_field(&dev, SerialNumber)?);
println!("Device model: {}", read_info_field(&dev, DeviceModel)?);
println!(
"Current firmware: {}",
read_info_field(&dev, CurrentFirmware)?
);
}
Opt::EnterDfu { spec } => {
let spec = DeviceSpec {
required_mode: Some(DeviceMode::Normal),
..spec
};
enter_dfu(&spec.get_device(&api)?.0)?;
info!("Note that device may take a few seconds to change mode");
}
Opt::LeaveDfu { spec } => {
let spec = DeviceSpec {
required_mode: Some(DeviceMode::Dfu),
..spec
};
let (dev, _) = spec.get_device(&api)?;
ensure_idle(&dev)?;
leave_dfu(&dev)?;
}
Opt::Download {
spec,
file,
wildcard_fw,
} => {
let spec = DeviceSpec {
required_mode: Some(DeviceMode::Dfu),
..spec
};
let (dev, info) = spec.get_device(&api)?;
download_cmd(&dev, info, &file, wildcard_fw)?
}
Opt::FileInfo { file: path } => {
let mut file = std::fs::File::open(path)?;
let suffix = parse_dfu_file(&mut file)?;
println!(
"For USB ID: {:04x}:{:04x}",
suffix.vendor_id, suffix.product_id
);
match suffix.has_valid_crc() {
true => println!("CRC: valid ({:#010x})", suffix.expected_crc),
false => println!(
"CRC: INVALID (expected {:#010x}, actual {:#010x})",
suffix.expected_crc, suffix.actual_crc
),
}
}
};
Ok(())
}
fn list_cmd(hidapi: &HidApi) {
for dev in hidapi.device_list() {
let dev_id = UsbId {
vid: dev.vendor_id(),
pid: dev.product_id(),
};
let state = identify_device(dev_id, dev.usage_page());
if let DeviceCompat::Incompatible = state {
continue;
}
println!(
"{} {} {} [{}]",
dev_id,
dev.serial_number().unwrap_or("INVALID"),
dev.product_string().unwrap_or("INVALID"),
state,
);
}
}
fn download_cmd(dev: &HidDevice, info: &DeviceInfo, path: &Path, wildcard_fw: bool) -> Result<()> {
let mut file = std::fs::File::open(path)?;
let suffix = parse_dfu_file(&mut file)?;
suffix.ensure_valid_crc()?;
let dev_id = UsbId {
vid: info.vendor_id(),
pid: info.product_id(),
};
if !suffix.vendor_id.matches(dev_id.vid) || !suffix.product_id.matches(dev_id.pid) {
bail!(
"this file is not for the selected device: file for {:04x}:{:04x}, device is {}",
suffix.vendor_id,
suffix.product_id,
dev_id
);
}
if suffix.vendor_id.0.is_none() || suffix.product_id.0.is_none() {
warn!(
"Update's USB ID ({:04x}:{:04x}) is incomplete; can't guarantee it's for this device",
suffix.vendor_id, suffix.product_id,
);
if !wildcard_fw {
bail!("to write firmware with an incomplete USB ID, you must pass -w");
}
} else {
info!("Update verified to be for selected device");
}
ensure_idle(dev)?;
info!("Beginning firmware download; it may take several minutes; do not unplug device");
download(dev, &mut file.by_ref().take(suffix.payload_length))?;
Ok(())
}
impl DeviceSpec {
/// If we match the given device, return a [DeviceRisks] with details on the match. Otherwise,
/// return [None].
fn match_dev(&self, device: &DeviceInfo) -> Option<DeviceRisks> {
let dev_id = UsbId {
vid: device.vendor_id(),
pid: device.product_id(),
};
let (untested, mode) = match identify_device(dev_id, device.usage_page()) {
DeviceCompat::Compatible(mode) => (false, mode),
DeviceCompat::Untested(mode) => (true, mode),
DeviceCompat::Incompatible => return None,
};
let ambiguous_mode = match self.required_mode {
None => false,
Some(_) if mode == DeviceMode::Unknown => true,
Some(req_mode) if mode == req_mode => false,
_ => return None,
};
if let Some(x) = self.pid {
if dev_id.pid != x {
return None;
}
}
if let Some(ref x) = self.serial {
if device.serial_number() != Some(x) {
return None;
}
}
Some(DeviceRisks {
untested,
ambiguous_mode,
})
}
fn get_device<'a>(&self, hidapi: &'a HidApi) -> Result<(HidDevice, &'a DeviceInfo)> {
let mut candidates = hidapi
.device_list()
.filter_map(|d| self.match_dev(d).map(|r| (d, r)));
match candidates.next() {
None => Err(MatchError::NoDevices.into()),
Some((dev, risks)) => {
if candidates.next().is_some() {
return Err(MatchError::MultipleDevices.into());
}
if risks.untested {
warn!("Device has not been tested with bose-dfu; by proceeding, you risk damaging it");
}
if risks.ambiguous_mode {
warn!(
"Cannot determine device's mode; command may damage devices not in {} mode",
self.required_mode.unwrap()
);
}
if (risks.untested || risks.ambiguous_mode) && !self.force {
bail!("to use an untested or ambiguous-mode device, you must pass -f");
}
dev.open_device(hidapi)
.map(|open| (open, dev))
.context("failed to open device; do you have permission?")
}
}
}
}
#[derive(Copy, Clone, Debug)]
struct DeviceRisks {
/// The device has not been tested, and bose-dfu might brick it.
untested: bool,
/// The running command needs a specific mode, and we're not sure the device is in that mode.
ambiguous_mode: bool,
}
#[derive(Error, Debug)]
enum MatchError {
#[error("no devices match specification")]
NoDevices,
#[error("multiple devices match specification")]
MultipleDevices,
}