Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

tpi_rs: add serial handlers #53

Merged
merged 6 commits into from
Oct 4, 2023
Merged
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
93 changes: 89 additions & 4 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
[workspace]
members = ["bmcd", "tpi_rs"]
resolver = "2"

[workspace.package]
version = "1.3.0"
Expand Down
23 changes: 16 additions & 7 deletions bmcd/src/into_legacy_response.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ use std::{borrow::Cow, fmt::Display};
pub enum LegacyResponse {
Success(Option<serde_json::Value>),
Error(StatusCode, Cow<'static, str>),
UartData(String),
}

impl LegacyResponse {
Expand Down Expand Up @@ -77,6 +78,7 @@ impl Display for LegacyResponse {
"{}",
s.as_ref().map(|json| json.to_string()).unwrap_or_default()
),
LegacyResponse::UartData(s) => write!(f, "{}", s),
LegacyResponse::Error(_, msg) => write!(f, "{}", msg),
}
}
Expand All @@ -94,19 +96,26 @@ pub type LegacyResult<T> = Result<T, LegacyResponse>;

impl From<LegacyResponse> for HttpResponse {
fn from(value: LegacyResponse) -> Self {
let (response, result) = match value {
let (response, result, is_uart) = match value {
LegacyResponse::Success(None) => {
(StatusCode::OK, serde_json::Value::String("ok".to_string()))
(StatusCode::OK, serde_json::Value::String("ok".to_string()), false)
}
LegacyResponse::Success(Some(body)) => (StatusCode::OK, body),
LegacyResponse::Success(Some(body)) => (StatusCode::OK, body, false),
LegacyResponse::UartData(d) => (StatusCode::OK, serde_json::Value::String(d), true),
LegacyResponse::Error(status_code, msg) => {
(status_code, serde_json::Value::String(msg.into_owned()))
(status_code, serde_json::Value::String(msg.into_owned()), false)
}
};

let msg = json!({
"response": [{ "result": result }]
});
let msg = if is_uart {
json!({
"response": [{ "uart": result }]
svenrademakers marked this conversation as resolved.
Show resolved Hide resolved
})
} else {
json!({
"response": [{ "result": result }]
})
};

HttpResponseBuilder::new(response).json(msg)
}
Expand Down
56 changes: 40 additions & 16 deletions bmcd/src/legacy.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ use nix::sys::statfs::statfs;
use serde_json::json;
use std::str::FromStr;
use tokio::sync::{mpsc, Mutex};
use tpi_rs::app::bmc_application::{BmcApplication, UsbConfig};
use tpi_rs::app::bmc_application::{BmcApplication, Encoding, UsbConfig};
use tpi_rs::middleware::{NodeId, UsbMode, UsbRoute};
type Query = web::Query<std::collections::HashMap<String, String>>;

Expand Down Expand Up @@ -78,8 +78,8 @@ async fn api_entry(bmc: web::Data<BmcApplication>, query: Query) -> impl Respond
("reset", true) => reset_node(bmc, query).await.into(),
("sdcard", true) => format_sdcard().into(),
("sdcard", false) => get_sdcard_info(),
("uart", true) => write_to_uart(bmc, query).into(),
("uart", false) => read_from_uart(bmc, query).into(),
("uart", true) => write_to_uart(bmc, query).await.into(),
("uart", false) => read_from_uart(bmc, query).await.into(),
("usb", true) => set_usb_mode(bmc, query).await.into(),
("usb", false) => get_usb_mode(bmc).await.into(),
_ => (
Expand Down Expand Up @@ -283,30 +283,54 @@ fn get_sdcard_fs_stat() -> anyhow::Result<(u64, u64)> {
Ok((total, free))
}

fn write_to_uart(bmc: &BmcApplication, query: Query) -> LegacyResult<()> {
async fn write_to_uart(bmc: &BmcApplication, query: Query) -> LegacyResult<()> {
let node = get_node_param(&query)?;
let Some(cmd) = query.get("cmd") else {
return Err(LegacyResponse::bad_request("Missing `cmd` parameter"));
};
let mut data = cmd.clone();

uart_write(bmc, node, cmd)
data.push_str("\r\n");

bmc.serial_write(node, data.as_bytes())
.await
.context("write over UART")
.map_err(Into::into)
}

fn uart_write(_bmc: &BmcApplication, _node: NodeId, _cmd: &str) -> anyhow::Result<()> {
todo!()
}

fn read_from_uart(bmc: &BmcApplication, query: Query) -> LegacyResult<()> {
async fn read_from_uart(bmc: &BmcApplication, query: Query) -> LegacyResult<LegacyResponse> {
let node = get_node_param(&query)?;
uart_read(bmc, node)
.context("read from UART")
.map_err(Into::into)
let enc = get_encoding_param(&query)?;
let data = bmc.serial_read(node, enc).await;

Ok(LegacyResponse::UartData(data))
}

fn uart_read(_bmc: &BmcApplication, _node: NodeId) -> anyhow::Result<()> {
todo!()
fn get_encoding_param(query: &Query) -> LegacyResult<Encoding> {
let Some(enc_str) = query.get("encoding") else {
return Ok(Encoding::Utf8);
};

match enc_str.as_str() {
"utf8" => Ok(Encoding::Utf8),
"utf16" | "utf16le" => Ok(Encoding::Utf16 {
little_endian: true,
}),
"utf16be" => Ok(Encoding::Utf16 {
little_endian: false,
}),
"utf32" | "utf32le" => Ok(Encoding::Utf32 {
little_endian: true,
}),
"utf32be" => Ok(Encoding::Utf32 {
little_endian: false,
}),
_ => {
let msg = "Invalid `encoding` parameter. Expected: utf8, utf16, utf16le, utf16be, \
utf32, utf32le, utf32be.";
Err(LegacyResponse::bad_request(msg))
}
}
}

async fn set_usb_mode(bmc: &BmcApplication, query: Query) -> LegacyResult<()> {
Expand Down Expand Up @@ -368,7 +392,7 @@ async fn handle_flash_request(
))?;

let size = u64::from_str(size)
.map_err(|_| LegacyResponse::bad_request("`lenght` parameter not a number"))?;
.map_err(|_| LegacyResponse::bad_request("`length` parameter is not a number"))?;

let peer: String = request
.connection_info()
Expand Down
1 change: 1 addition & 0 deletions bmcd/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@ async fn main() -> anyhow::Result<()> {
let tls6 = load_tls_configuration(&config.tls.private_key, &config.tls.certificate)?;

let bmc = Arc::new(BmcApplication::new().await?);
bmc.start_serial_workers().await;
run_event_listener(bmc.clone())?;
let flash_service = Data::new(Mutex::new(FlashService::new(bmc.clone())));
let bmc = Data::from(bmc);
Expand Down
1 change: 1 addition & 0 deletions tpi_rs/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ rockusb = { version = "0.1.1" }
rusb = "0.9.3"
rustpiboot = { git = "https://github.com/ruslashev/rustpiboot.git", rev="89e6497"}
serde = { version = "1.0.188", features = ["derive"] }
tokio-serial = { version = "5.4.4", features = ["rt", "codec"] }

anyhow.workspace = true
log.workspace = true
Expand Down
Loading