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 all 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
85 changes: 85 additions & 0 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
31 changes: 20 additions & 11 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 @@ -83,6 +84,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 @@ -100,19 +102,26 @@ pub type LegacyResult<T> = Result<T, LegacyResponse>;

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

let msg = json!({
"response": [{ "result": result }]
});
let keyname = if is_uart { "uart" } else { "result" };

let msg = json! {{
"response": [{ keyname: result }]
}};

HttpResponseBuilder::new(response).json(msg)
}
Expand Down
68 changes: 48 additions & 20 deletions bmcd/src/legacy.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ use serde_json::json;
use std::ops::Deref;
use std::str::FromStr;
use tokio::sync::mpsc;
use tpi_rs::app::bmc_application::{BmcApplication, UsbConfig};
use tpi_rs::app::bmc_application::{BmcApplication, Encoding, UsbConfig};
use tpi_rs::middleware::{NodeId, UsbMode, UsbRoute};
use tpi_rs::utils::logging_sink;
type Query = web::Query<std::collections::HashMap<String, String>>;
Expand Down Expand Up @@ -72,7 +72,7 @@ async fn api_entry(bmc: web::Data<BmcApplication>, query: Query) -> impl Respond
};

let Some(ty) = query.get("type") else {
return LegacyResponse::bad_request("Missing `type` parameter")
return LegacyResponse::bad_request("Missing `type` parameter");
};

let bmc = bmc.as_ref();
Expand All @@ -89,8 +89,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 @@ -155,11 +155,15 @@ fn get_node_param(query: &Query) -> LegacyResult<NodeId> {
};

let Ok(node_num) = i32::from_str(node_str) else {
return Err(LegacyResponse::bad_request("Parameter `node` is not a number"));
return Err(LegacyResponse::bad_request(
"Parameter `node` is not a number",
));
};

let Ok(node) = node_num.try_into() else {
return Err(LegacyResponse::bad_request("Parameter `node` is out of range 0..3 of node IDs"));
return Err(LegacyResponse::bad_request(
"Parameter `node` is out of range 0..3 of node IDs",
));
};

Ok(node)
Expand Down Expand Up @@ -294,30 +298,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"));
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))
}
}
}

/// switches the USB configuration.
Expand Down Expand Up @@ -402,7 +430,7 @@ async fn handle_flash_request(
))?;

let size = u64::from_str(size)
.map_err(|_| LegacyResponse::bad_request("`length` 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 @@ -37,6 +37,7 @@ async fn main() -> anyhow::Result<()> {
init_logger();
let (tls, tls6) = load_config()?;
let bmc = Data::new(BmcApplication::new().await?);
bmc.start_serial_workers().await?;
run_event_listener(bmc.clone().into_inner())?;
let flash_service = Data::new(FlashService::new());
let authentication = Arc::new(LinuxAuthenticator::new("/api/bmc/authenticate").await?);
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
31 changes: 31 additions & 0 deletions tpi_rs/src/app/bmc_application.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,10 @@ use crate::middleware::firmware_update::{
use crate::middleware::persistency::app_persistency::ApplicationPersistency;
use crate::middleware::persistency::app_persistency::PersistencyBuilder;
use crate::middleware::power_controller::PowerController;
use crate::middleware::serial::SerialConnections;
use crate::middleware::usbboot;
use crate::middleware::{pin_controller::PinController, NodeId, UsbMode, UsbRoute};
use crate::utils::{string_from_utf16, string_from_utf32};
use anyhow::{ensure, Context};
use log::{debug, info, trace};
use serde::{Deserialize, Serialize};
Expand Down Expand Up @@ -34,12 +36,20 @@ pub enum UsbConfig {
Node(NodeId, UsbRoute),
}

/// Encodings used when reading from a serial port
pub enum Encoding {
Utf8,
Utf16 { little_endian: bool },
Utf32 { little_endian: bool },
}

#[derive(Debug)]
pub struct BmcApplication {
pub(super) pin_controller: PinController,
pub(super) power_controller: PowerController,
pub(super) app_db: ApplicationPersistency,
pub(super) nodes_on: AtomicBool,
serial: SerialConnections,
}

impl BmcApplication {
Expand All @@ -51,12 +61,14 @@ impl BmcApplication {
.register_key(USB_CONFIG, &UsbConfig::UsbA(NodeId::Node1))
.build()
.await?;
let serial = SerialConnections::new()?;

let instance = Self {
pin_controller,
power_controller,
app_db,
nodes_on: AtomicBool::new(false),
serial,
};

instance.initialize().await?;
Expand Down Expand Up @@ -290,4 +302,23 @@ impl BmcApplication {
Command::new("shutdown").args(["-r", "now"]).spawn()?;
Ok(())
}

pub async fn start_serial_workers(&self) -> anyhow::Result<()> {
Ok(self.serial.run().await?)
}

pub async fn serial_read(&self, node: NodeId, encoding: Encoding) -> anyhow::Result<String> {
let bytes = self.serial.read(node).await?;

let res = match encoding {
Encoding::Utf8 => String::from_utf8_lossy(&bytes).to_string(),
Encoding::Utf16 { little_endian } => string_from_utf16(&bytes, little_endian),
Encoding::Utf32 { little_endian } => string_from_utf32(&bytes, little_endian),
};
Ok(res)
}

pub async fn serial_write(&self, node: NodeId, data: &[u8]) -> anyhow::Result<()> {
Ok(self.serial.write(node, data).await?)
}
}
Loading
Loading