Skip to main content

sftool_lib/sf32lb56/
mod.rs

1//! SF32LB56 芯片特定实现模块
2
3pub mod erase_flash;
4pub mod ram_command;
5pub mod read_flash;
6pub mod reset;
7pub mod sifli_debug;
8pub mod speed;
9pub mod write_flash;
10
11use crate::common::serial_io::is_cancelled_io_error;
12use crate::common::serial_io::{for_tool, sleep_with_cancel};
13use crate::common::sifli_debug::{
14    ChipFrameFormat, RecvError, START_WORD, SifliDebug, SifliUartCommand, SifliUartResponse,
15    common_debug,
16};
17use crate::progress::{
18    EraseFlashStyle, EraseRegionStyle, ProgressOperation, ProgressStatus, StubStage,
19};
20use crate::sf32lb56::ram_command::DownloadStub;
21use crate::{Result, SifliTool, SifliToolBase, SifliToolTrait};
22use serialport::SerialPort;
23use std::io::{BufReader, Read};
24use std::time::Duration;
25
26// Define SF32LB56FrameFormat here to avoid import issues
27pub struct SF32LB56FrameFormat;
28
29impl ChipFrameFormat for SF32LB56FrameFormat {
30    fn create_header(len: u16) -> Vec<u8> {
31        let mut header = vec![];
32        header.extend_from_slice(&START_WORD);
33        // SF32LB56 uses big-endian for data length
34        header.extend_from_slice(&len.to_be_bytes());
35        // SF32LB56 adds 4-byte timestamp (fixed to 0)
36        header.extend_from_slice(&[0x00, 0x00, 0x00, 0x00]);
37        // Channel number fixed to 0x10
38        header.push(0x10);
39        // CRC fixed to 0x00
40        header.push(0x00);
41        // reserved field (2 bytes, fixed to 0x00)
42        header.extend_from_slice(&[0x00, 0x00]);
43        header
44    }
45
46    fn parse_frame_header<R: Read>(
47        reader: &mut BufReader<R>,
48    ) -> std::result::Result<usize, RecvError> {
49        // 读取长度 (2字节) - SF32LB56 uses big-endian
50        let mut length_bytes = [0; 2];
51        if let Err(e) = reader.read_exact(&mut length_bytes) {
52            if is_cancelled_io_error(&e) {
53                return Err(RecvError::Cancelled);
54            }
55            tracing::error!("Failed to read length bytes: {}", e);
56            return Err(RecvError::InvalidHeaderLength);
57        }
58
59        let payload_size = u16::from_be_bytes(length_bytes) as usize;
60
61        // 读取时间戳 (4字节) - SF32LB56 specific
62        let mut timestamp_bytes = [0; 4];
63        if let Err(e) = reader.read_exact(&mut timestamp_bytes) {
64            if is_cancelled_io_error(&e) {
65                return Err(RecvError::Cancelled);
66            }
67            tracing::error!("Failed to read timestamp bytes: {}", e);
68            return Err(RecvError::InvalidHeaderChannel);
69        }
70
71        // 读取通道和CRC (2字节)
72        let mut channel_crc = [0; 2];
73        if let Err(e) = reader.read_exact(&mut channel_crc) {
74            if is_cancelled_io_error(&e) {
75                return Err(RecvError::Cancelled);
76            }
77            tracing::error!("Failed to read channel and CRC bytes: {}", e);
78            return Err(RecvError::InvalidHeaderChannel);
79        }
80
81        // SF32LB56: Read 2-byte reserved field
82        let mut reserved_bytes = [0; 2];
83        if let Err(e) = reader.read_exact(&mut reserved_bytes) {
84            if is_cancelled_io_error(&e) {
85                return Err(RecvError::Cancelled);
86            }
87            tracing::error!("Failed to read reserved bytes: {}", e);
88            return Err(RecvError::ReadError(e));
89        }
90
91        Ok(payload_size)
92    }
93
94    fn encode_command_data(command: &SifliUartCommand) -> Vec<u8> {
95        let mut send_data = vec![];
96        match command {
97            SifliUartCommand::Enter => {
98                let temp = [0x41, 0x54, 0x53, 0x46, 0x33, 0x32, 0x05, 0x21];
99                send_data.extend_from_slice(&temp);
100            }
101            SifliUartCommand::Exit => {
102                let temp = [0x41, 0x54, 0x53, 0x46, 0x33, 0x32, 0x18, 0x21];
103                send_data.extend_from_slice(&temp);
104            }
105            SifliUartCommand::MEMRead { addr, len } => {
106                send_data.push(0x40);
107                send_data.push(0x72);
108                // SF32LB56 uses big-endian for address and length
109                send_data.extend_from_slice(&addr.to_be_bytes());
110                send_data.extend_from_slice(&len.to_be_bytes());
111            }
112            SifliUartCommand::MEMWrite { addr, data } => {
113                send_data.push(0x40);
114                send_data.push(0x77);
115                // SF32LB56 uses big-endian for address and data length
116                send_data.extend_from_slice(&addr.to_be_bytes());
117                send_data.extend_from_slice(&(data.len() as u16).to_be_bytes());
118                for d in data.iter() {
119                    send_data.extend_from_slice(&d.to_be_bytes());
120                }
121            }
122        }
123        send_data
124    }
125
126    fn decode_response_data(data: &[u8]) -> u32 {
127        // SF32LB56 uses big-endian
128        u32::from_be_bytes([data[0], data[1], data[2], data[3]])
129    }
130
131    // SF32LB56 specific address mapping function
132    fn map_address(addr: u32) -> u32 {
133        let mut l_addr = addr;
134        if (0xE0000000..0xF0000000).contains(&addr) {
135            l_addr = (addr & 0x0fffffff) | 0xF0000000;
136            // l_addr = addr
137        } else if (0x00400000..=0x0041FFFF).contains(&addr) {
138            // L_RAM
139            l_addr += 0x20000000;
140        } else if (0x20C00000..=0x20C1FFFF).contains(&addr) {
141            // L_RAM
142            l_addr -= 0x00800000;
143        } else if (0x20000000..=0x200C7FFF).contains(&addr) {
144            // H_RAM
145            l_addr += 0x0A000000;
146        } else if (0x20800000..=0x20BFFFFF).contains(&addr) {
147            // H_RAM
148            l_addr -= 0x20800000;
149        } else if (0x10000000..=0x1FFFFFFF).contains(&addr) {
150            // EXT_MEM
151            l_addr += 0x50000000;
152        }
153        l_addr
154    }
155}
156
157pub struct SF32LB56Tool {
158    pub base: SifliToolBase,
159    pub port: Box<dyn SerialPort>,
160    pub debug_sequence_replacement_supported: Option<bool>,
161}
162
163// 为 SF32LB56Tool 实现 Send 和 Sync
164unsafe impl Send for SF32LB56Tool {}
165unsafe impl Sync for SF32LB56Tool {}
166
167// SifliDebug trait implementation for SF32LB56Tool
168impl SifliDebug for SF32LB56Tool {
169    fn debug_command(&mut self, command: SifliUartCommand) -> Result<SifliUartResponse> {
170        common_debug::debug_command_impl::<SF32LB56Tool, SF32LB56FrameFormat>(self, command)
171    }
172
173    fn debug_read_word32(&mut self, addr: u32) -> Result<u32> {
174        common_debug::debug_read_word32_impl::<SF32LB56Tool, SF32LB56FrameFormat>(self, addr)
175    }
176
177    fn debug_write_word32(&mut self, addr: u32, data: u32) -> Result<()> {
178        common_debug::debug_write_word32_impl::<SF32LB56Tool, SF32LB56FrameFormat>(self, addr, data)
179    }
180
181    fn debug_write_memory(&mut self, addr: u32, data: &[u8]) -> Result<()> {
182        common_debug::debug_write_memory_impl::<SF32LB56Tool, SF32LB56FrameFormat>(self, addr, data)
183    }
184
185    fn debug_write_core_reg(&mut self, reg: u16, data: u32) -> Result<()> {
186        common_debug::debug_write_core_reg_impl::<SF32LB56Tool, SF32LB56FrameFormat>(
187            self, reg, data,
188        )
189    }
190
191    fn debug_step(&mut self) -> Result<()> {
192        common_debug::debug_step_impl::<SF32LB56Tool, SF32LB56FrameFormat>(self)
193    }
194
195    fn debug_run(&mut self) -> Result<()> {
196        common_debug::debug_run_impl::<SF32LB56Tool, SF32LB56FrameFormat>(self)
197    }
198
199    fn debug_halt(&mut self) -> Result<()> {
200        common_debug::debug_halt_impl::<SF32LB56Tool, SF32LB56FrameFormat>(self)
201    }
202}
203
204impl SF32LB56Tool {
205    /// 执行全部flash擦除的内部方法
206    pub fn internal_erase_all(&mut self, address: u32) -> Result<()> {
207        use ram_command::{Command, RamCommand};
208
209        let progress = self.progress();
210        let spinner = progress.create_spinner(ProgressOperation::EraseFlash {
211            address,
212            style: EraseFlashStyle::Addressed,
213        });
214
215        // 发送擦除所有命令
216        let _ = self.command(Command::EraseAll { address });
217
218        let mut io = for_tool(self);
219        io.wait_for_pattern(
220            b"OK",
221            Duration::from_millis(30_000),
222            &format!("erasing flash at 0x{:08X}", address),
223        )?;
224
225        spinner.finish(ProgressStatus::Success);
226
227        Ok(())
228    }
229
230    /// 执行区域擦除的内部方法
231    pub fn internal_erase_region(&mut self, address: u32, len: u32) -> Result<()> {
232        use ram_command::{Command, RamCommand};
233
234        let progress = self.progress();
235        let spinner = progress.create_spinner(ProgressOperation::EraseRegion {
236            address,
237            len,
238            style: EraseRegionStyle::HexLength,
239        });
240
241        // 发送擦除区域命令
242        let _ = self.command(Command::Erase { address, len });
243
244        let mut io = for_tool(self);
245        io.wait_for_pattern(
246            b"OK",
247            Duration::from_millis(30_000),
248            &format!("erasing region at 0x{:08X}", address),
249        )?;
250
251        spinner.finish(ProgressStatus::Success);
252
253        Ok(())
254    }
255
256    pub fn attempt_connect(&mut self) -> Result<()> {
257        use crate::common::sifli_debug::{SifliUartCommand, SifliUartResponse};
258
259        let infinite_attempts = self.base.connect_attempts <= 0;
260        let mut remaining_attempts = if infinite_attempts {
261            None
262        } else {
263            Some(self.base.connect_attempts)
264        };
265        loop {
266            if self.base.before.requires_reset() {
267                // 使用RTS引脚复位
268                let mut io = for_tool(self);
269                io.write_request_to_send(true)?;
270                io.sleep(Duration::from_millis(100))?;
271                io.write_request_to_send(false)?;
272                io.sleep(Duration::from_millis(100))?;
273            }
274            let value: Result<()> = match self.debug_command(SifliUartCommand::Enter) {
275                Ok(SifliUartResponse::Enter) => Ok(()),
276                _ => Err(std::io::Error::other("Failed to enter debug mode").into()),
277            };
278            // 如果有限重试,检查是否还有机会
279            if let Some(ref mut attempts) = remaining_attempts {
280                if *attempts == 0 {
281                    break; // 超过最大重试次数则退出循环
282                }
283                *attempts -= 1;
284            }
285
286            let progress = self.progress();
287            let spinner = progress.create_spinner(ProgressOperation::Connect);
288
289            // 尝试连接
290            match value {
291                Ok(_) => {
292                    spinner.finish(ProgressStatus::Success);
293                    return Ok(());
294                }
295                Err(_) => {
296                    spinner.finish(ProgressStatus::Retry);
297                    sleep_with_cancel(&self.base.cancel_token, Duration::from_millis(500))?;
298                }
299            }
300        }
301        Err(std::io::Error::other("Failed to connect to the chip").into())
302    }
303
304    pub fn download_stub_impl(&mut self) -> Result<()> {
305        use crate::common::sifli_debug::SifliUartCommand;
306        use crate::ram_stub::load_stub_file;
307        use probe_rs::MemoryMappedRegister;
308        use probe_rs::architecture::arm::core::armv7m::{Aircr, Demcr};
309        use probe_rs::architecture::arm::core::registers::cortex_m::{PC, SP};
310
311        let progress = self.progress();
312        let spinner = progress.create_spinner(ProgressOperation::DownloadStub {
313            stage: StubStage::Start,
314        });
315
316        // 0.0 HCPU Unconditional halt
317        self.debug_halt()?;
318        //  0.1 HPSYS_AON->ISSR->LP_ACTIVE
319        let mut data = self.debug_read_word32(0x4004_0028)?;
320        if data & 0x20 != 0 {
321            data = 0xa05f0003;
322            // LCPU Halt
323            self.debug_write_word32(0x3000_EDF0, data)?;
324        }
325
326        // 1. reset and halt
327        //    1.1. reset_catch_set
328        let demcr = self.debug_read_word32(Demcr::get_mmio_address() as u32)?;
329        let mut demcr = Demcr(demcr);
330        demcr.set_vc_corereset(true);
331        self.debug_write_word32(Demcr::get_mmio_address() as u32, demcr.into())?;
332
333        // 1.2. reset_system
334        let mut aircr = Aircr(0);
335        aircr.vectkey();
336        aircr.set_sysresetreq(true);
337        let _ = self.debug_write_word32(Aircr::get_mmio_address() as u32, aircr.into()); // MCU已经重启,不一定能收到正确回复
338        sleep_with_cancel(
339            &self.base.cancel_token,
340            std::time::Duration::from_millis(10),
341        )?;
342
343        // 1.3. Re-enter debug mode
344        self.debug_command(SifliUartCommand::Enter)?;
345
346        // 1.4. halt
347        self.debug_halt()?;
348
349        // 1.5. reset_catch_clear
350        let demcr = self.debug_read_word32(Demcr::get_mmio_address() as u32)?;
351        let mut demcr = Demcr(demcr);
352        demcr.set_vc_corereset(false);
353        self.debug_write_word32(Demcr::get_mmio_address() as u32, demcr.into())?;
354
355        sleep_with_cancel(
356            &self.base.cancel_token,
357            std::time::Duration::from_millis(100),
358        )?;
359        // 2. Download stub - 支持外部 stub 文件
360        let chip_memory_key = format!("sf32lb56_{}", self.base.memory_type);
361        let stub = match load_stub_file(self.base.external_stub_path.as_deref(), &chip_memory_key) {
362            Ok(s) => s,
363            Err(e) => {
364                spinner.finish(ProgressStatus::NotFound);
365                return Err(e.into());
366            }
367        };
368
369        let packet_size = if self.base.compat { 256 } else { 64 * 1024 };
370
371        let mut addr = 0x2006_7000;
372        let mut data = &stub.data[..];
373        while !data.is_empty() {
374            let chunk = &data[..std::cmp::min(data.len(), packet_size)];
375            self.debug_write_memory(addr, chunk)?;
376            addr += chunk.len() as u32;
377            data = &data[chunk.len()..];
378        }
379
380        // 3. run ram stub
381        // 3.1. set SP and PC
382        let sp = u32::from_le_bytes(
383            stub.data[0..4]
384                .try_into()
385                .expect("slice with exactly 4 bytes"),
386        );
387        let pc = u32::from_le_bytes(
388            stub.data[4..8]
389                .try_into()
390                .expect("slice with exactly 4 bytes"),
391        );
392        self.debug_write_core_reg(PC.id.0, pc)?;
393        self.debug_write_core_reg(SP.id.0, sp)?;
394
395        // 3.2. run
396        self.debug_run()?;
397
398        spinner.finish(ProgressStatus::Success);
399
400        Ok(())
401    }
402}
403
404impl SifliTool for SF32LB56Tool {
405    fn create_tool(base: SifliToolBase) -> Box<dyn SifliTool> {
406        let mut port = serialport::new(&base.port_name, 1000000)
407            .timeout(Duration::from_secs(5))
408            .open()
409            .unwrap();
410        port.write_request_to_send(false).unwrap();
411        std::thread::sleep(Duration::from_millis(100));
412
413        let mut tool = Box::new(Self {
414            base,
415            port,
416            debug_sequence_replacement_supported: None,
417        });
418        if tool.base.before.should_download_stub() {
419            tool.download_stub().expect("Failed to download stub");
420        }
421        tool
422    }
423}
424
425impl SifliToolTrait for SF32LB56Tool {
426    fn port(&mut self) -> &mut Box<dyn SerialPort> {
427        &mut self.port
428    }
429
430    fn base(&self) -> &SifliToolBase {
431        &self.base
432    }
433
434    fn set_speed(&mut self, baud: u32) -> Result<()> {
435        use crate::speed::SpeedTrait;
436        SpeedTrait::set_speed(self, baud)
437    }
438
439    fn soft_reset(&mut self) -> Result<()> {
440        use crate::reset::Reset;
441        Reset::soft_reset(self)
442    }
443}