-
Notifications
You must be signed in to change notification settings - Fork 136
/
Copy pathreset.rs
366 lines (302 loc) · 11 KB
/
reset.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
//! Most of this module is copied from `esptool.py` (https://github.com/espressif/esptool/blob/a8586d02b1305ebc687d31783437a7f4d4dbb70f/esptool/reset.py)
#[cfg(unix)]
use std::{io, os::fd::AsRawFd};
use std::{thread::sleep, time::Duration};
use log::debug;
use serialport::SerialPort;
use strum::{Display, EnumIter, EnumString, VariantNames};
#[cfg(unix)]
use libc::ioctl;
use crate::{
command::{Command, CommandType},
connection::{Connection, Port, USB_SERIAL_JTAG_PID},
error::Error,
flasher::FLASH_WRITE_SIZE,
};
/// Default time to wait before releasing the boot pin after a reset
const DEFAULT_RESET_DELAY: u64 = 50; // ms
/// Amount of time to wait if the default reset delay does not work
const EXTRA_RESET_DELAY: u64 = 500; // ms
/// Some strategy for resting a target device
pub trait ResetStrategy {
fn reset(&self, serial_port: &mut Port) -> Result<(), Error>;
fn set_dtr(&self, serial_port: &mut Port, level: bool) -> Result<(), Error> {
serial_port.write_data_terminal_ready(level)?;
Ok(())
}
fn set_rts(&self, serial_port: &mut Port, level: bool) -> Result<(), Error> {
serial_port.write_request_to_send(level)?;
Ok(())
}
#[cfg(unix)]
fn set_dtr_rts(
&self,
serial_port: &mut Port,
dtr_level: bool,
rts_level: bool,
) -> Result<(), Error> {
let fd = serial_port.as_raw_fd();
let mut status: i32 = 0;
match unsafe { ioctl(fd, libc::TIOCMGET, &status) } {
0 => (),
_ => return Err(io::Error::last_os_error().into()),
}
if dtr_level {
status |= libc::TIOCM_DTR
} else {
status &= !libc::TIOCM_DTR
}
if rts_level {
status |= libc::TIOCM_RTS
} else {
status &= !libc::TIOCM_RTS
}
match unsafe { ioctl(fd, libc::TIOCMSET, &status) } {
0 => (),
_ => return Err(io::Error::last_os_error().into()),
}
Ok(())
}
}
/// Classic reset sequence, sets DTR and RTS sequentially.
#[derive(Debug, Clone, Copy)]
pub struct ClassicReset {
delay: u64,
}
impl ClassicReset {
pub fn new(extra_delay: bool) -> Self {
let delay = if extra_delay {
EXTRA_RESET_DELAY
} else {
DEFAULT_RESET_DELAY
};
Self { delay }
}
}
impl ResetStrategy for ClassicReset {
fn reset(&self, serial_port: &mut Port) -> Result<(), Error> {
debug!(
"Using Classic reset strategy with delay of {}ms",
self.delay
);
self.set_rts(serial_port, false)?;
self.set_dtr(serial_port, false)?;
self.set_rts(serial_port, true)?;
self.set_dtr(serial_port, true)?;
self.set_rts(serial_port, true)?; // EN = LOW, chip in reset
self.set_dtr(serial_port, false)?; // IO0 = HIGH
sleep(Duration::from_millis(100));
self.set_rts(serial_port, false)?; // EN = HIGH, chip out of reset
self.set_dtr(serial_port, true)?; // IO0 = LOW
sleep(Duration::from_millis(self.delay));
self.set_rts(serial_port, false)?;
self.set_dtr(serial_port, false)?; // IO0 = HIGH, done
Ok(())
}
}
/// UNIX-only reset sequence with custom implementation, which allows setting
/// DTR and RTS lines at the same time.
#[cfg(unix)]
#[derive(Debug, Clone, Copy)]
pub struct UnixTightReset {
delay: u64,
}
#[cfg(unix)]
impl UnixTightReset {
pub fn new(extra_delay: bool) -> Self {
let delay = if extra_delay {
EXTRA_RESET_DELAY
} else {
DEFAULT_RESET_DELAY
};
Self { delay }
}
}
#[cfg(unix)]
impl ResetStrategy for UnixTightReset {
fn reset(&self, serial_port: &mut Port) -> Result<(), Error> {
debug!(
"Using UnixTight reset strategy with delay of {}ms",
self.delay
);
self.set_dtr_rts(serial_port, false, false)?;
self.set_dtr_rts(serial_port, true, true)?;
self.set_dtr_rts(serial_port, false, true)?; // IO = HIGH, EN = LOW, chip in reset
sleep(Duration::from_millis(100));
self.set_dtr_rts(serial_port, true, false)?; // IO0 = LOW, EN = HIGH, chip out of reset
sleep(Duration::from_millis(self.delay));
self.set_dtr_rts(serial_port, false, false)?; // IO0 = HIGH, done
self.set_dtr(serial_port, false)?; // Needed in some environments to ensure IO0 = HIGH
Ok(())
}
}
/// Custom reset sequence, which is required when the device is connecting via
/// its USB-JTAG-Serial peripheral.
#[derive(Debug, Clone, Copy)]
pub struct UsbJtagSerialReset;
impl ResetStrategy for UsbJtagSerialReset {
fn reset(&self, serial_port: &mut Port) -> Result<(), Error> {
debug!("Using UsbJtagSerial reset strategy");
self.set_rts(serial_port, false)?;
self.set_dtr(serial_port, false)?; // Idle
sleep(Duration::from_millis(100));
self.set_rts(serial_port, false)?;
self.set_dtr(serial_port, true)?; // Set IO0
sleep(Duration::from_millis(100));
self.set_rts(serial_port, true)?; // Reset. Calls inverted to go through (1,1) instead of (0,0)
self.set_dtr(serial_port, false)?;
self.set_rts(serial_port, true)?; // RTS set as Windows only propagates DTR on RTS setting
sleep(Duration::from_millis(100));
self.set_rts(serial_port, false)?;
self.set_dtr(serial_port, false)?;
Ok(())
}
}
/// Reset the target device
pub fn reset_after_flash(serial: &mut Port, pid: u16) -> Result<(), serialport::Error> {
sleep(Duration::from_millis(100));
if pid == USB_SERIAL_JTAG_PID {
serial.write_data_terminal_ready(false)?;
sleep(Duration::from_millis(100));
serial.write_request_to_send(true)?;
serial.write_data_terminal_ready(false)?;
serial.write_request_to_send(true)?;
sleep(Duration::from_millis(100));
serial.write_request_to_send(false)?;
} else {
serial.write_request_to_send(true)?;
sleep(Duration::from_millis(100));
serial.write_request_to_send(false)?;
}
Ok(())
}
/// Reset sequence for hard resetting the chip.
pub fn hard_reset(serial_port: &mut Port, pid: u16) -> Result<(), Error> {
debug!("Using HardReset reset strategy");
// Using esptool HardReset strategy (https://github.com/espressif/esptool/blob/3301d0ff4638d4db1760a22540dbd9d07c55ec37/esptool/reset.py#L132-L153)
// leads to https://github.com/esp-rs/espflash/issues/592 in Windows, using `reset_after_flash` instead works fine for all platforms.
// We had similar issues in the past: https://github.com/esp-rs/espflash/pull/157
reset_after_flash(serial_port, pid)?;
Ok(())
}
/// Perform a soft reset of the device.
pub fn soft_reset(
connection: &mut Connection,
stay_in_bootloader: bool,
is_stub: bool,
) -> Result<(), Error> {
debug!("Using SoftReset reset strategy");
if !is_stub {
if stay_in_bootloader {
// ROM bootloader is already in bootloader
return Ok(());
} else {
// 'run user code' is as close to a soft reset as we can do
connection.with_timeout(CommandType::FlashBegin.timeout(), |connection| {
let size: u32 = 0;
let offset: u32 = 0;
let blocks: u32 = size.div_ceil(FLASH_WRITE_SIZE as u32);
connection.command(Command::FlashBegin {
size,
blocks,
block_size: FLASH_WRITE_SIZE.try_into().unwrap(),
offset,
supports_encryption: false,
encrypt: false,
})
})?;
connection.with_timeout(CommandType::FlashEnd.timeout(), |connection| {
connection.write_command(Command::FlashEnd { reboot: false })
})?;
}
} else if stay_in_bootloader {
// Soft resetting from the stub loader will re-load the ROM bootloader
connection.with_timeout(CommandType::FlashBegin.timeout(), |connection| {
let size: u32 = 0;
let offset: u32 = 0;
let blocks: u32 = size.div_ceil(FLASH_WRITE_SIZE as u32);
connection.command(Command::FlashBegin {
size,
blocks,
block_size: FLASH_WRITE_SIZE.try_into().unwrap(),
offset,
supports_encryption: false,
encrypt: false,
})
})?;
connection.with_timeout(CommandType::FlashEnd.timeout(), |connection| {
connection.write_command(Command::FlashEnd { reboot: true })
})?;
} else {
// Running user code from stub loader requires some hacks in the stub loader
connection.with_timeout(CommandType::RunUserCode.timeout(), |connection| {
connection.command(Command::RunUserCode)
})?;
}
Ok(())
}
/// Construct a sequence of reset strategies based on the OS and chip.
///
/// Returns a [Vec] containing one or more reset strategies to be attempted
/// sequentially.
#[allow(unused_variables)]
pub fn construct_reset_strategy_sequence(
port_name: &str,
pid: u16,
mode: ResetBeforeOperation,
) -> Vec<Box<dyn ResetStrategy>> {
// USB-JTAG/Serial mode
if pid == USB_SERIAL_JTAG_PID || mode == ResetBeforeOperation::UsbReset {
return vec![Box::new(UsbJtagSerialReset)];
}
// USB-to-Serial bridge
#[cfg(unix)]
if cfg!(unix) && !port_name.starts_with("rfc2217:") {
return vec![
Box::new(UnixTightReset::new(false)),
Box::new(UnixTightReset::new(true)),
Box::new(ClassicReset::new(false)),
Box::new(ClassicReset::new(true)),
];
}
// Windows
vec![
Box::new(ClassicReset::new(false)),
Box::new(ClassicReset::new(true)),
]
}
#[cfg_attr(feature = "cli", derive(clap::ValueEnum))]
#[derive(
Debug, Default, Clone, Copy, PartialEq, Eq, Display, EnumIter, EnumString, VariantNames,
)]
#[non_exhaustive]
#[strum(serialize_all = "lowercase")]
pub enum ResetBeforeOperation {
/// Uses DTR & RTS serial control lines to try to reset the chip into
/// bootloader mode.
#[default]
DefaultReset,
/// Skips DTR/RTS control signal assignments and just start sending a serial
/// synchronisation command to the chip.
NoReset,
/// Skips DTR/RTS control signal assignments and also skips the serial
/// synchronization command.
NoResetNoSync,
/// Reset sequence for USB-JTAG-Serial peripheral
UsbReset,
}
#[cfg_attr(feature = "cli", derive(clap::ValueEnum))]
#[derive(
Debug, Default, Clone, Copy, PartialEq, Eq, Display, EnumIter, EnumString, VariantNames,
)]
#[non_exhaustive]
pub enum ResetAfterOperation {
/// The DTR serial control line is used to reset the chip into a normal boot
/// sequence.
#[default]
HardReset,
/// Leaves the chip in the serial bootloader, no reset is performed.
NoReset,
/// Leaves the chip in the stub bootloader, no reset is performed.
NoResetNoStub,
}