diff --git a/ecu-esp32/src/wifi.rs b/ecu-esp32/src/wifi.rs index e97ef45..7d3eae7 100644 --- a/ecu-esp32/src/wifi.rs +++ b/ecu-esp32/src/wifi.rs @@ -38,7 +38,7 @@ use esp_storage::FlashStorage; use embassy_net::Stack; -use log::{warn,info}; +use log::{warn, info, error}; use crate::mdns; @@ -107,6 +107,7 @@ pub async fn start_wifi(spawner: &Spawner, let rng = Rng::new(); let seed = (rng.random() as u64) << 32 | rng.random() as u64; + // Init network stack let (stack, runner) = embassy_net::new( wifi_interface, @@ -239,37 +240,54 @@ async fn write_ota(ota : &mut Ota>, sock: &mut embassy_net::tcp::TcpSocket<'_>, len: u32) { let mut buf = [0u8; 4096]; + let mut buf_offset = 0; - ota.ota_begin(len, 0); + if let Err(e) = ota.ota_begin(len, 0) { + error!("ota_begin faled {:?}", e); + return; + } let mut len = len; while len > 0 { - match sock.read(&mut buf).await { + match sock.read(&mut buf[buf_offset..]).await { + Ok(0) => { + info!("unexpected eof on read"); + break; + } Ok(chunksize) => { - info!("writing {} bytes, {} remaining", chunksize, len); - let res = ota.ota_write_chunk(&buf[0..chunksize]); - if res == Ok(true) { - info!("eof on write, remaining bytes = {} ", len); - - if ota.ota_flush(false, false).is_ok() { // ignore crc, no rollback - Timer::after_millis(1000).await; - esp_hal::system::software_reset(); - } - } - // let progress = (ota.get_ota_progress() * 100.0) as u8; - // log::info!("progress: {}%", progress); - len = len - (chunksize as u32); - }, + // info!("read {} at {}, {} remaining", chunksize, buf_offset, len); + buf_offset += chunksize; + len -= chunksize as u32; + } Err(x) => { warn!("error reading ota image: {:?}", x); break; } - } + } + if buf_offset == 4096 { + info!("{} remaining", len); + if let Err(_) = ota.ota_write_chunk(&buf) { + break; + } + buf_offset = 0; + }; + if len <= 0 { + if let Err(_) = ota.ota_write_chunk(&buf[0..buf_offset]) { + break; + } + }; } if len == 0 { info!("wrote all bytes"); + if ota.ota_flush(false, false).is_ok() { // ignore crc, no rollback + info!("write {:?}", sock.write(b"BYE\n").await); + let _ = sock.flush().await; + sock.close(); + Timer::after_millis(1000).await; + esp_hal::system::software_reset(); + } } else { - warn!("stream ended early, was expecting another {} bytes", len); + warn!("stream ended early or flash failed with {} bytes left", len); } } @@ -308,9 +326,6 @@ async fn run_tcp_handler(stack : Stack<'_>, flash_peripheral: esp_hal::periphera let len = u32::from_be_bytes(len_bytes); info!("reading {} bytes", len); write_ota(&mut ota, &mut socket, len).await; - info!("write {:?}", socket.write(b"BYE\n").await); - socket.flush().await; - socket.close(); }, b"KEY0" => { info!("sessionkey");