Skip to content

Commit

Permalink
Tolerate some non-utf8 data when detecting boot mode over serial
Browse files Browse the repository at this point in the history
My ESP32-WROOM is sending some non-utf8 data just after reset, causing boot
mode detection to fail.

This commit uses `String::from_utf8_lossy` to ignore these bytes.

Tested on macOS, boards: ESP32-WROOM-32, ESP32-WROOM-32D, ESP32-C3-MINI-1,
ESP32-C3-12F.
  • Loading branch information
kcking committed Feb 3, 2024
1 parent 8f43cc4 commit 49fbde9
Show file tree
Hide file tree
Showing 2 changed files with 9 additions and 8 deletions.
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
- Fixed a missed `flush` call that may be causing communication errors (#521)
- Fix "SHA-256 comparison failed: [...] attempting to boot anyway..." (#567)
- Windows: Update RST/DTR order to avoid issues.
- Tolerate non-utf8 data in boot detection (#573)

### Changed
- Created `FlashData`, `FlashDataBuilder` and `FlashSettings` structs to reduce number of input arguments in some functions (#512, #566)
Expand Down
16 changes: 8 additions & 8 deletions espflash/src/connection/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,6 @@
use std::{
io::{BufWriter, Write},
iter::zip,
str::from_utf8,
thread::sleep,
time::Duration,
};
Expand Down Expand Up @@ -156,7 +155,7 @@ impl Connection {
return Ok(());
}
let mut download_mode: bool = false;
let mut boot_mode: &str = "";
let mut boot_mode = String::new();
let mut boot_log_detected = false;
let mut buff: Vec<u8>;
if self.before_operation != ResetBeforeOperation::NoReset {
Expand All @@ -174,18 +173,19 @@ impl Connection {
)));
}

let read_slice = from_utf8(&buff[..read_bytes as usize]).map_err(|err| {
debug!("Error: {}", err);
Error::InvalidSerialRead
})?;
let read_slice = String::from_utf8_lossy(&buff[..read_bytes as usize]).into_owned();

let pattern = Regex::new(r"boot:(0x[0-9a-fA-F]+)(.*waiting for download)?").unwrap();

// Search for the pattern in the read data
if let Some(data) = pattern.captures(read_slice) {
if let Some(data) = pattern.captures(&read_slice) {
boot_log_detected = true;
// Boot log detected
boot_mode = data.get(1).map(|m| m.as_str()).unwrap_or_default();
boot_mode = data
.get(1)
.map(|m| m.as_str())
.unwrap_or_default()
.to_string();
download_mode = data.get(2).is_some();

// Further processing or printing the results
Expand Down

0 comments on commit 49fbde9

Please sign in to comment.