use std::collections::HashMap;
use std::time::Duration;
use crate::update_workflow::{self, WorkflowError};
use super::{Attributes, ClientAuthorization, Hawkbit, HawkbitOptions};
const DEFAULT_URL: &str = "https://localhost:8443";
const DEFAULT_TENANT: &str = "default";
const DEFAULT_HANDLE_CANCEL: bool = true;
const DEFAULT_HANDLE_CONFIG: bool = true;
const DEFAULT_POLLING_INTERVAL_SECS: Duration = Duration::from_secs(300);
const DEFAULT_TIMEOUT_SECS: Duration = Duration::from_secs(30);
pub struct HawkbitBuilder {
url: String,
tenant: String,
controller: String,
authorization: ClientAuthorization,
options: HawkbitOptions,
}
impl HawkbitBuilder {
pub fn new() -> Self {
HawkbitBuilder {
url: DEFAULT_URL.to_string(),
tenant: DEFAULT_TENANT.to_string(),
controller: String::new(),
authorization: ClientAuthorization::None,
options: HawkbitOptions {
handle_cancel: DEFAULT_HANDLE_CANCEL,
handle_config: DEFAULT_HANDLE_CONFIG,
default_polling_interval: DEFAULT_POLLING_INTERVAL_SECS,
server_cert: None,
client_cert: None,
attributes_script: Attributes::Default,
timeout: DEFAULT_TIMEOUT_SECS,
},
}
}
pub fn with_config(
&mut self,
config: &HashMap<String, String>,
) -> Result<&mut Self, WorkflowError> {
self.url = update_workflow::get_config(config, "sota_hawkbit_url")?;
self.tenant = update_workflow::get_config(config, "sota_tenant")?;
self.controller = update_workflow::get_config(config, "sota_target_id")?;
let auth_mode = update_workflow::get_config(config, "sota_auth_mode")?;
self.authorization = match auth_mode.to_lowercase().as_str() {
"gateway" => ClientAuthorization::GatewayToken(update_workflow::get_config(
config,
"sota_auth_token",
)?),
"target" => ClientAuthorization::TargetToken(update_workflow::get_config(
config,
"sota_auth_token",
)?),
_ => ClientAuthorization::None,
};
self.options.default_polling_interval = Duration::from_secs(
update_workflow::get_config_as_u64(config, "sota_default_polling_interval_sec")?,
);
self.options.server_cert = config.get("sota_server_cert").cloned();
self.options.client_cert = config.get("sota_client_cert").cloned();
if let Some(script) = config.get("sota_attributes_script") {
self.options.attributes_script = Attributes::Script(script.clone());
}
self.options.timeout = update_workflow::get_config_as_u64(config, "download_timeout_sec")
.map(Duration::from_secs)
.unwrap_or(DEFAULT_TIMEOUT_SECS);
Ok(self)
}
pub fn attributes(&mut self, attr: Attributes) -> &mut Self {
self.options.attributes_script = attr;
self
}
pub async fn build(&self) -> Result<Hawkbit, WorkflowError> {
Hawkbit::new(
&self.url,
&self.tenant,
&self.controller,
self.authorization.clone(),
self.options.clone(),
)
.await
.map_err(|e| {
WorkflowError::ExecutionFailed(format!("Failed to create Hawkbit client: {e}"))
})
}
}
impl Default for HawkbitBuilder {
fn default() -> Self {
Self::new()
}
}