1#[macro_use]
2extern crate log;
3
4use std::{
5 fs::File,
6 io::*,
7 path::PathBuf,
8 sync::{
9 Arc,
10 atomic::{AtomicBool, Ordering},
11 },
12 thread,
13 time::{Duration, Instant},
14};
15
16mod crc;
17mod ymodem;
18
19macro_rules! dbg {
20 ($($arg:tt)*) => {{
21 debug!("$ {}", &std::fmt::format(format_args!($($arg)*)));
22 }};
23}
24
25const CTRL_C: u8 = 0x03;
26const INT_STR: &str = "<INTERRUPT>";
27const INT: &[u8] = INT_STR.as_bytes();
28
29pub struct UbootShell {
30 pub tx: Option<Box<dyn Write + Send>>,
31 pub rx: Option<Box<dyn Read + Send>>,
32 perfix: String,
33}
34
35impl UbootShell {
36 pub fn new(tx: impl Write + Send + 'static, rx: impl Read + Send + 'static) -> Result<Self> {
38 let mut s = Self {
39 tx: Some(Box::new(tx)),
40 rx: Some(Box::new(rx)),
41 perfix: "".to_string(),
42 };
43 s.wait_for_shell()?;
44 debug!("shell ready, perfix: `{}`", s.perfix);
45 Ok(s)
46 }
47
48 fn rx(&mut self) -> &mut Box<dyn Read + Send> {
49 self.rx.as_mut().unwrap()
50 }
51
52 fn tx(&mut self) -> &mut Box<dyn Write + Send> {
53 self.tx.as_mut().unwrap()
54 }
55
56 fn wait_for_interrupt(&mut self) -> Result<Vec<u8>> {
57 let mut tx = self.tx.take().unwrap();
58
59 let ok = Arc::new(AtomicBool::new(false));
60
61 let tx_handle = thread::spawn({
62 let ok = ok.clone();
63 move || {
64 while !ok.load(Ordering::Acquire) {
65 let _ = tx.write_all(&[CTRL_C]);
66 thread::sleep(Duration::from_millis(20));
67 }
68 tx
69 }
70 });
71 let mut history: Vec<u8> = Vec::new();
72 let mut interrupt_line: Vec<u8> = Vec::new();
73 debug!("wait for interrupt");
74 loop {
75 match self.read_byte() {
76 Ok(ch) => {
77 history.push(ch);
78
79 if history.last() == Some(&b'\n') {
80 let line = history.trim_ascii_end();
81 dbg!("{}", String::from_utf8_lossy(line));
82 let it = line.ends_with(INT);
83 if it {
84 interrupt_line.extend_from_slice(line);
85 }
86 history.clear();
87 if it {
88 ok.store(true, Ordering::Release);
89 break;
90 }
91 }
92 }
93
94 Err(ref e) if e.kind() == ErrorKind::TimedOut => {
95 continue;
96 }
97 Err(e) => {
98 return Err(e);
99 }
100 }
101 }
102
103 self.tx = Some(tx_handle.join().unwrap());
104
105 Ok(interrupt_line)
106 }
107
108 fn clear_shell(&mut self) -> Result<()> {
109 let _ = self.read_to_end(&mut vec![]);
110 Ok(())
111 }
112
113 fn wait_for_shell(&mut self) -> Result<()> {
114 let mut line = self.wait_for_interrupt()?;
115 debug!("got {}", String::from_utf8_lossy(&line));
116 line.resize(line.len() - INT.len(), 0);
117 self.perfix = String::from_utf8_lossy(&line).to_string();
118 self.clear_shell()?;
119 Ok(())
120 }
121
122 fn read_byte(&mut self) -> Result<u8> {
123 let mut buff = [0u8; 1];
124 let time_out = Duration::from_secs(5);
125 let start = Instant::now();
126
127 loop {
128 match self.rx().read_exact(&mut buff) {
129 Ok(_) => return Ok(buff[0]),
130 Err(e) => {
131 if e.kind() == ErrorKind::TimedOut {
132 if start.elapsed() > time_out {
133 return Err(std::io::Error::new(
134 std::io::ErrorKind::TimedOut,
135 "Timeout",
136 ));
137 }
138 } else {
139 return Err(e);
140 }
141 }
142 }
143 }
144 }
145
146 pub fn wait_for_reply(&mut self, val: &str) -> Result<String> {
147 let mut reply = Vec::new();
148 let mut display = Vec::new();
149 debug!("wait for `{}`", val);
150 loop {
151 let byte = self.read_byte()?;
152 reply.push(byte);
153 display.push(byte);
154 if byte == b'\n' {
155 dbg!("{}", String::from_utf8_lossy(&display).trim_end());
156 display.clear();
157 }
158
159 if reply.ends_with(val.as_bytes()) {
160 dbg!("{}", String::from_utf8_lossy(&display).trim_end());
161 break;
162 }
163 }
164 Ok(String::from_utf8_lossy(&reply)
165 .trim()
166 .trim_end_matches(&self.perfix)
167 .to_string())
168 }
169
170 pub fn cmd_without_reply(&mut self, cmd: &str) -> Result<()> {
171 self.tx().write_all(cmd.as_bytes())?;
172 self.tx().write_all("\n".as_bytes())?;
173 self.tx().flush()?;
174 Ok(())
177 }
178
179 pub fn cmd(&mut self, cmd: &str) -> Result<String> {
180 info!("cmd: {cmd}");
181 self.cmd_without_reply(cmd)?;
182 let perfix = self.perfix.clone();
183 let res = self
184 .wait_for_reply(&perfix)?
185 .trim_end()
186 .trim_end_matches(self.perfix.as_str().trim())
187 .trim_end()
188 .to_string();
189 Ok(res)
190 }
191
192 pub fn set_env(&mut self, name: impl Into<String>, value: impl Into<String>) -> Result<()> {
193 self.cmd(&format!("setenv {} {}", name.into(), value.into()))?;
194 Ok(())
195 }
196
197 pub fn env(&mut self, name: impl Into<String>) -> Result<String> {
198 let name = name.into();
199 let s = self.cmd(&format!("echo ${}", name))?;
200 let sp = s
201 .split("\n")
202 .filter(|s| !s.trim().is_empty())
203 .collect::<Vec<_>>();
204 let s = sp
205 .last()
206 .ok_or(Error::new(
207 ErrorKind::NotFound,
208 format!("env {} not found", name),
209 ))?
210 .to_string();
211 Ok(s)
212 }
213
214 pub fn env_int(&mut self, name: impl Into<String>) -> Result<usize> {
215 let name = name.into();
216 let line = self.env(&name)?;
217 debug!("env {name} = {line}");
218
219 parse_int(&line).ok_or(Error::new(
220 ErrorKind::InvalidData,
221 format!("env {name} is not a number"),
222 ))
223 }
224
225 pub fn loady(
226 &mut self,
227 addr: usize,
228 file: impl Into<PathBuf>,
229 on_progress: impl Fn(usize, usize),
230 ) -> Result<String> {
231 self.cmd_without_reply(&format!("loady {:#x}", addr,))?;
232 let crc = self.wait_for_load_crc()?;
233 let mut p = ymodem::Ymodem::new(crc);
234
235 let file = file.into();
236 let name = file.file_name().unwrap().to_str().unwrap();
237
238 let mut file = File::open(&file).unwrap();
239
240 let size = file.metadata().unwrap().len() as usize;
241
242 p.send(self, &mut file, name, size, |p| {
243 on_progress(p, size);
244 })?;
245 let perfix = self.perfix.clone();
246 self.wait_for_reply(&perfix)
247 }
248
249 fn wait_for_load_crc(&mut self) -> Result<bool> {
250 let mut reply = Vec::new();
251 loop {
252 let byte = self.read_byte()?;
253 reply.push(byte);
254 print_raw(&[byte]);
255
256 if reply.ends_with(b"C") {
257 return Ok(true);
258 }
259 let res = String::from_utf8_lossy(&reply);
260 if res.contains("try 'help'") {
261 panic!("{}", res);
262 }
263 }
264 }
265}
266
267impl Read for UbootShell {
268 fn read(&mut self, buf: &mut [u8]) -> Result<usize> {
269 self.rx().read(buf)
270 }
271}
272
273impl Write for UbootShell {
274 fn write(&mut self, buf: &[u8]) -> Result<usize> {
275 self.tx().write(buf)
276 }
277
278 fn flush(&mut self) -> Result<()> {
279 self.tx().flush()
280 }
281}
282
283fn parse_int(line: &str) -> Option<usize> {
284 let mut line = line.trim();
285 let mut radix = 10;
286 if line.starts_with("0x") {
287 line = &line[2..];
288 radix = 16;
289 }
290 u64::from_str_radix(line, radix).ok().map(|o| o as _)
291}
292
293fn print_raw(buff: &[u8]) {
294 #[cfg(target_os = "windows")]
295 print_raw_win(buff);
296 #[cfg(not(target_os = "windows"))]
297 stdout().write_all(buff).unwrap();
298}
299
300#[cfg(target_os = "windows")]
301fn print_raw_win(buff: &[u8]) {
302 use std::sync::Mutex;
303 static PRINT_BUFF: Mutex<Vec<u8>> = Mutex::new(Vec::new());
304
305 let mut g = PRINT_BUFF.lock().unwrap();
306
307 g.extend_from_slice(buff);
308
309 if g.ends_with(b"\n") {
310 let s = String::from_utf8_lossy(&g[..]);
311 println!("{}", s.trim());
312 g.clear();
313 }
314}