Skip to main content

sftool_lib/common/
ram_command.rs

1use 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/// 通用的RAM命令枚举,可在不同芯片间复用
8#[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/// 通用的命令响应枚举
36#[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
46/// 响应字符串查找表
47pub const RESPONSE_STR_TABLE: [&str; 3] = ["OK", "Fail", "RX_WAIT"];
48
49/// RAM命令处理trait,定义了发送命令和数据的接口
50pub trait RamCommand {
51    fn command(&mut self, cmd: Command) -> Result<Response>;
52    fn send_data(&mut self, data: &[u8]) -> Result<Response>;
53
54    /// Whether the connected RAM patch supports `burn_info`. The default keeps
55    /// legacy and non-Debug-IP chips on their existing raw write path.
56    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
72/// Stub下载trait,定义了下载stub的接口
73pub trait DownloadStub {
74    fn download_stub(&mut self) -> Result<()>;
75}
76
77/// 命令处理的配置参数
78pub 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
94/// 通用的RAM操作处理器,包含可复用的逻辑
95pub 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    /// 发送命令并等待响应的通用实现
108    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        // 发送命令
117        io.write_all(command_str.as_bytes())?;
118        io.flush()?;
119        // 在macOS上,FTDI的驱动似乎不高兴我们清除输入缓冲区,这可能会导致后续要发送的内容被截断
120        // 因此这个地方我们不再需要清理缓冲区,应该在后续的操作中滤除掉额外的信息
121        // port.clear(serialport::ClearBuffer::All)?;
122
123        // 确定超时时间
124        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        // 某些命令直接返回成功,不等待响应
135        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    /// 发送数据并等待响应的通用实现
146    pub fn send_data_and_wait_response(
147        io: &mut SerialIo<'_>,
148        data: &[u8],
149        config: &CommandConfig,
150    ) -> Result<Response> {
151        // 根据配置发送数据
152        if !config.compat_mode {
153            io.write_all(data)?;
154            io.flush()?;
155        } else {
156            // 兼容模式:分块发送
157            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    /// Sends the `burn_info` command followed by the fixed-size replacement
168    /// table expected by the new 52X/56X/57X RAM patches.
169    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    /// 等待响应的通用实现
190    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    /// 等待shell提示符的通用实现
205    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}