sftool_lib/common/
ram_command.rs1use crate::common::debug_sequence::DebugSequenceReplacementInfo;
2use crate::common::serial_io::SerialIo;
3use crate::{Error, Result};
4use std::str::FromStr;
5use strum::{Display, EnumString};
6
7#[derive(EnumString, Display, Debug, Clone, PartialEq, Eq)]
9pub enum Command {
10 #[strum(to_string = "burn_erase_all 0x{address:08x}\r")]
11 EraseAll { address: u32 },
12
13 #[strum(to_string = "burn_verify 0x{address:08x} 0x{len:08x} 0x{crc:08x}\r")]
14 Verify { address: u32, len: u32, crc: u32 },
15
16 #[strum(to_string = "burn_erase 0x{address:08x} 0x{len:08x}\r")]
17 Erase { address: u32, len: u32 },
18
19 #[strum(to_string = "burn_erase_write 0x{address:08x} 0x{len:08x}\r")]
20 WriteAndErase { address: u32, len: u32 },
21
22 #[strum(to_string = "burn_write 0x{address:08x} 0x{len:08x}\r")]
23 Write { address: u32, len: u32 },
24
25 #[strum(to_string = "burn_read 0x{address:08x} 0x{len:08x}\r")]
26 Read { address: u32, len: u32 },
27
28 #[strum(to_string = "burn_reset\r")]
29 SoftReset,
30
31 #[strum(to_string = "burn_speed {baud} {delay}\r")]
32 SetBaud { baud: u32, delay: u32 },
33}
34
35#[derive(EnumString, Display, Debug, Clone, PartialEq, Eq)]
37pub enum Response {
38 #[strum(serialize = "OK")]
39 Ok,
40 #[strum(serialize = "Fail")]
41 Fail,
42 #[strum(serialize = "RX_WAIT")]
43 RxWait,
44}
45
46pub const RESPONSE_STR_TABLE: [&str; 3] = ["OK", "Fail", "RX_WAIT"];
48
49pub trait RamCommand {
51 fn command(&mut self, cmd: Command) -> Result<Response>;
52 fn send_data(&mut self, data: &[u8]) -> Result<Response>;
53
54 fn supports_debug_sequence_replacement(&mut self) -> Result<bool> {
57 Ok(false)
58 }
59
60 fn send_debug_sequence_replacement_info(
61 &mut self,
62 _info: &DebugSequenceReplacementInfo,
63 ) -> Result<Response> {
64 Ok(Response::Fail)
65 }
66
67 fn format_command(&self, cmd: &Command) -> String {
68 cmd.to_string()
69 }
70}
71
72pub trait DownloadStub {
74 fn download_stub(&mut self) -> Result<()>;
75}
76
77pub struct CommandConfig {
79 pub compat_mode: bool,
80 pub chunk_size: usize,
81 pub chunk_delay_ms: u64,
82}
83
84impl Default for CommandConfig {
85 fn default() -> Self {
86 Self {
87 compat_mode: false,
88 chunk_size: 256,
89 chunk_delay_ms: 10,
90 }
91 }
92}
93
94pub struct RamOps;
96
97pub fn is_sd_memory(memory_type: &str) -> bool {
98 let memory_type = memory_type.to_ascii_lowercase();
99 memory_type == "sd" || memory_type.starts_with("sd_")
100}
101
102impl RamOps {
103 const DEFAULT_TIMEOUT_MS: u128 = 4000;
104 const ERASE_ALL_TIMEOUT_MS: u128 = 30 * 1000;
105 const REPLACEMENT_INFO_TIMEOUT_MS: u128 = 2000;
106
107 pub fn send_command_and_wait_response(
109 io: &mut SerialIo<'_>,
110 cmd: Command,
111 command_str: &str,
112 memory_type: &str,
113 ) -> Result<Response> {
114 tracing::debug!("command: {:?}", cmd);
115
116 io.write_all(command_str.as_bytes())?;
118 io.flush()?;
119 let timeout = match cmd {
125 Command::EraseAll { .. } => Self::ERASE_ALL_TIMEOUT_MS,
126 _ => Self::DEFAULT_TIMEOUT_MS,
127 };
128 let timeout = if is_sd_memory(memory_type) {
129 timeout * 3
130 } else {
131 timeout
132 };
133
134 match cmd {
136 Command::SetBaud { .. } | Command::Read { .. } | Command::Erase { .. } => {
137 return Ok(Response::Ok);
138 }
139 _ => (),
140 }
141
142 Self::wait_for_response(io, timeout)
143 }
144
145 pub fn send_data_and_wait_response(
147 io: &mut SerialIo<'_>,
148 data: &[u8],
149 config: &CommandConfig,
150 ) -> Result<Response> {
151 if !config.compat_mode {
153 io.write_all(data)?;
154 io.flush()?;
155 } else {
156 for chunk in data.chunks(config.chunk_size) {
158 io.write_all(chunk)?;
159 io.flush()?;
160 io.sleep(std::time::Duration::from_millis(config.chunk_delay_ms))?;
161 }
162 }
163
164 Self::wait_for_response(io, Self::DEFAULT_TIMEOUT_MS)
165 }
166
167 pub fn send_debug_sequence_replacement_info(
170 io: &mut SerialIo<'_>,
171 data: &[u8],
172 memory_type: &str,
173 ) -> Result<Response> {
174 tracing::debug!("sending burn_info replacement table ({} bytes)", data.len());
175 io.write_all(b"burn_info\r")?;
176 io.flush()?;
177 io.sleep(std::time::Duration::from_millis(100))?;
178 io.write_all(data)?;
179 io.flush()?;
180
181 let timeout = if is_sd_memory(memory_type) {
182 Self::REPLACEMENT_INFO_TIMEOUT_MS * 3
183 } else {
184 Self::REPLACEMENT_INFO_TIMEOUT_MS
185 };
186 Self::wait_for_response(io, timeout)
187 }
188
189 fn wait_for_response(io: &mut SerialIo<'_>, timeout_ms: u128) -> Result<Response> {
191 let matched = io.wait_for_patterns(
192 &RESPONSE_STR_TABLE.map(str::as_bytes),
193 std::time::Duration::from_millis(timeout_ms as u64),
194 "RAM command response",
195 )?;
196 tracing::debug!(
197 "Response buffer: {:?}",
198 String::from_utf8_lossy(&matched.buffer)
199 );
200 Response::from_str(RESPONSE_STR_TABLE[matched.index])
201 .map_err(|e| Error::invalid_input(e.to_string()))
202 }
203
204 pub fn wait_for_shell_prompt(
206 io: &mut SerialIo<'_>,
207 prompt: &[u8],
208 retry_interval_ms: u64,
209 max_retries: u32,
210 ) -> Result<()> {
211 io.wait_for_prompt(
212 prompt,
213 std::time::Duration::from_millis(retry_interval_ms),
214 max_retries,
215 )
216 }
217}