Skip to content

Commit

Permalink
wip
Browse files Browse the repository at this point in the history
  • Loading branch information
mattjperez committed Jan 3, 2025
1 parent e63c84b commit c7b1b2e
Showing 1 changed file with 96 additions and 71 deletions.
167 changes: 96 additions & 71 deletions micro-rdk/src/common/ota.rs
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,7 @@ use crate::esp32::esp_idf_svc::{
sys::{esp_ota_get_next_update_partition, esp_partition_t},
};
use async_io::Timer;
use futures_lite::FutureExt;
use http_body_util::{BodyExt, Empty};
use hyper::{body::Bytes, client::conn::http2, Request};
use once_cell::sync::Lazy;
Expand Down Expand Up @@ -120,6 +121,15 @@ pub(crate) enum ConfigError {
Other(String),
}

/// used to differentiate between no-frame and a timeout
#[derive(Error, Debug)]
enum FrameError {
#[error("unreachable: file a bug ticket if surfaced")]
NoOp,
#[error("resolving next frame took longer than {0} seconds")]
Timeout(usize),
}

#[allow(dead_code)]
#[derive(Error, Debug)]
pub(crate) enum OtaError {
Expand All @@ -129,6 +139,8 @@ pub(crate) enum OtaError {
ConfigError(#[from] ConfigError),
#[error(transparent)]
NetworkError(#[from] hyper::Error),
#[error(transparent)]
StalledDownload(#[from] FrameError),
#[error("{0}")]
UpdateError(String),
#[error("failed to initialize ota process")]
Expand Down Expand Up @@ -313,7 +325,6 @@ impl<S: OtaMetadataStorage> OtaService<S> {
Ok(connection) => {
match connection.await {
Ok(io) => {
// TODO(RSDK-9617): add timeout for stalled download
match http2::Builder::new(self.exec.clone())
.max_frame_size(16_384) // lowest configurable
.timer(H2Timer)
Expand Down Expand Up @@ -411,84 +422,98 @@ impl<S: OtaMetadataStorage> OtaService<S> {
let mut got_info = false;

log::info!("writing new firmware to address `{:#x}`", self.address,);
let mut stream = response.into_data_stream();

loop {
match stream.next().ok_or(FrameError::NoOp).or(async {
async_io::Timer::after(Duration::from_secs(30)).await;
Err(FrameError::Timeout(30))
}).await {
Ok(frame) => {
let data = frame.expect();

total_downloaded += data.len();

if !got_info {
if total_downloaded < SIZEOF_APPDESC {
log::error!("initial frame too small to retrieve esp_app_desc_t");
} else {
#[cfg(feature = "esp32")]
{
log::info!("verifying new ota firmware");
let mut loader = EspFirmwareInfoLoader::new();
loader
.load(&data)
.map_err(|e| OtaError::InvalidFirmware(e.to_string()))?;
let new_fw = loader
.get_info()
.map_err(|e| OtaError::InvalidFirmware(e.to_string()))?;
log::debug!(
"current firmware app description: {:?}",
running_fw_info
);
log::debug!("new firmware app description: {:?}", new_fw);
}
#[cfg(not(feature = "esp32"))]
{
log::debug!("deserializing app header");
if let Ok(decoded) = bincode::decode_from_slice::<
EspAppDesc,
bincode::config::Configuration,
>(
&data[..SIZEOF_APPDESC],
bincode::config::standard(),
) {
log::debug!("{:?}", decoded.0);
}
}
got_info = true;
}
}

while let Some(next) = response.frame().await {
let frame = next.map_err(|e| OtaError::Other(e.to_string()))?;
if !frame.is_data() {
return Err(OtaError::Other(
"download contained non-data frame".to_string(),
));
}

// Err variant returns the original frame, not an impl Error
let data = frame
.into_data()
.map_err(|_| OtaError::Other("failed to get data from frame".to_string()))?;
total_downloaded += data.len();
if data.len() + nwritten > self.max_size {
log::error!("file is larger than expected, aborting");
#[cfg(feature = "esp32")]
update_handle
.abort()
.map_err(|e| OtaError::AbortError(format!("{:?}", e)))?;
return Err(OtaError::InvalidImageSize(
data.len() + nwritten,
self.max_size,
));
}

if !got_info {
if total_downloaded < SIZEOF_APPDESC {
log::error!("initial frame too small to retrieve esp_app_desc_t");
} else {
// TODO(RSDK-9271) add async writer for ota
#[cfg(feature = "esp32")]
{
log::info!("verifying new ota firmware");
let mut loader = EspFirmwareInfoLoader::new();
loader
.load(&data)
.map_err(|e| OtaError::InvalidFirmware(e.to_string()))?;
let new_fw = loader
.get_info()
.map_err(|e| OtaError::InvalidFirmware(e.to_string()))?;
log::debug!("current firmware app description: {:?}", running_fw_info);
log::debug!("new firmware app description: {:?}", new_fw);
}
update_handle
.write(&data)
.map_err(|e| OtaError::WriteError(e.to_string()))?;
#[cfg(not(feature = "esp32"))]
{
log::debug!("deserializing app header");
if let Ok(decoded) = bincode::decode_from_slice::<
EspAppDesc,
bincode::config::Configuration,
>(
&data[..SIZEOF_APPDESC], bincode::config::standard()
) {
log::debug!("{:?}", decoded.0);
let _n = update_handle
.write(&data)
.await
.map_err(|e| OtaError::WriteError(e.to_string()))?;
// TODO change back to 'n' after impl async writer
nwritten += data.len();
log::info!(
"updating next OTA partition at {:#x}: {}/{} bytes written",
self.address,
nwritten,
file_len
);
}
Err(e) => {
match e {
// no further frames to be processed
FrameError::NoOp => break,
FrameError::Timeout(s) => {
// close resources
//return larger error
return Err(OtaError::StalledDownload(e));
}
}
got_info = true;
}
}

if data.len() + nwritten > self.max_size {
log::error!("file is larger than expected, aborting");
#[cfg(feature = "esp32")]
update_handle
.abort()
.map_err(|e| OtaError::AbortError(format!("{:?}", e)))?;
return Err(OtaError::InvalidImageSize(
data.len() + nwritten,
self.max_size,
));
}

// TODO(RSDK-9271) add async writer for ota
#[cfg(feature = "esp32")]
update_handle
.write(&data)
.map_err(|e| OtaError::WriteError(e.to_string()))?;
#[cfg(not(feature = "esp32"))]
let _n = update_handle
.write(&data)
.await
.map_err(|e| OtaError::WriteError(e.to_string()))?;
// TODO change back to 'n' after impl async writer
nwritten += data.len();
log::info!(
"updating next OTA partition at {:#x}: {}/{} bytes written",
self.address,
nwritten,
file_len
);
}

drop(conn);
Expand Down

0 comments on commit c7b1b2e

Please sign in to comment.