source-pr / source (pull_request) Successful in 13s
The reference server answers the real ALKH contract from a fixed machine description, so the whole OS path can run on a development host and a backend author has a concrete example of every opcode. It serves detection, frequency, fan, temperature and power over one socket. Power was the missing measurement: a power target could not regulate because the HAL had no way to report watts, so READ_POWER joins the verbs behind CAP_POWER. With it, --boot against the reference server settles the loop at 623 MHz for a 2400 W target (4 W per MHz in the model) instead of holding at the boot frequency. Fan mapping stays opt-in for --boot (ALKANE_FAN_FANS/ALKANE_FAN_ZONES) because it perturbs the machine and takes minutes.
692 lines
23 KiB
Rust
692 lines
23 KiB
Rust
// SPDX-License-Identifier: MIT
|
|
//! Versioned local wire contract between Alkane OS and an SDK hardware backend.
|
|
|
|
use crate::detect::{
|
|
ChipModel, DetectionBackend, EepromState, Envelope, ProbeOutcome, PsuCapability,
|
|
};
|
|
use crate::HardwareBackend;
|
|
use std::fmt;
|
|
use std::io::{self, Read, Write};
|
|
use std::net::Shutdown;
|
|
use std::os::fd::{AsRawFd, FromRawFd, OwnedFd};
|
|
use std::os::unix::ffi::OsStrExt;
|
|
use std::os::unix::net::UnixStream;
|
|
use std::path::Path;
|
|
use std::time::{Duration, Instant};
|
|
|
|
const MAGIC: [u8; 4] = *b"ALKH";
|
|
const VERSION: u8 = 1;
|
|
const RESPONSE: u16 = 1;
|
|
const HEADER_LEN: usize = 16;
|
|
const MAX_PAYLOAD: usize = 4096;
|
|
const IO_TIMEOUT: Duration = Duration::from_secs(2);
|
|
|
|
const SEND_FRAME: u8 = 1;
|
|
const RECEIVE_FRAME: u8 = 2;
|
|
const SET_CHAIN_RESET: u8 = 3;
|
|
const SET_FAN_TARGET: u8 = 4;
|
|
const READ_TEMPERATURE: u8 = 5;
|
|
const SET_PSU_ENABLED: u8 = 6;
|
|
const CAPABILITIES: u8 = 7;
|
|
const PROBE_CHAIN: u8 = 8;
|
|
const READ_EEPROM: u8 = 9;
|
|
const IDENTIFY_PSU: u8 = 10;
|
|
const SET_CHAIN_FREQUENCY: u8 = 11;
|
|
const READ_POWER: u8 = 12;
|
|
|
|
/// Backend feature bits reported by `CAPABILITIES`.
|
|
pub const CAP_CHAIN_PROBE: u32 = 1 << 0;
|
|
pub const CAP_EEPROM: u32 = 1 << 1;
|
|
pub const CAP_PSU_IDENTITY: u32 = 1 << 2;
|
|
pub const CAP_FREQUENCY: u32 = 1 << 3;
|
|
pub const CAP_POWER: u32 = 1 << 4;
|
|
|
|
const PROBE_IDENTIFIED: u8 = 0;
|
|
const PROBE_SILENT: u8 = 1;
|
|
const PROBE_GARBLED: u8 = 2;
|
|
|
|
const EEPROM_PRESENT: u8 = 0;
|
|
const EEPROM_ABSENT: u8 = 1;
|
|
const EEPROM_INVALID: u8 = 2;
|
|
|
|
#[cfg(not(target_os = "linux"))]
|
|
compile_error!("Alkane HAL sockets require Linux");
|
|
|
|
#[cfg(target_os = "linux")]
|
|
mod sys {
|
|
pub use std::ffi::{c_char as CChar, c_int as CInt, c_void as CVoid};
|
|
pub type SaFamily = u16;
|
|
pub type SocklenT = u32;
|
|
|
|
pub const AF_UNIX: CInt = 1;
|
|
pub const SOCK_STREAM: CInt = 1;
|
|
pub const SOCK_NONBLOCK: CInt = 0x800;
|
|
pub const SOCK_CLOEXEC: CInt = 0x80000;
|
|
pub const SOL_SOCKET: CInt = 1;
|
|
pub const SO_ERROR: CInt = 4;
|
|
pub const POLLOUT: i16 = 4;
|
|
pub const EAGAIN: CInt = 11;
|
|
pub const EISCONN: CInt = 106;
|
|
pub const EINPROGRESS: CInt = 115;
|
|
|
|
#[repr(C)]
|
|
pub struct SockaddrUn {
|
|
pub sun_family: SaFamily,
|
|
pub sun_path: [CChar; 108],
|
|
}
|
|
|
|
#[repr(C)]
|
|
pub struct PollFd {
|
|
pub fd: CInt,
|
|
pub events: i16,
|
|
pub revents: i16,
|
|
}
|
|
|
|
extern "C" {
|
|
pub fn socket(domain: CInt, socket_type: CInt, protocol: CInt) -> CInt;
|
|
pub fn connect(fd: CInt, address: *const CVoid, length: SocklenT) -> CInt;
|
|
pub fn poll(fds: *mut PollFd, count: usize, timeout_ms: CInt) -> CInt;
|
|
pub fn getsockopt(
|
|
fd: CInt,
|
|
level: CInt,
|
|
name: CInt,
|
|
value: *mut CVoid,
|
|
length: *mut SocklenT,
|
|
) -> CInt;
|
|
}
|
|
}
|
|
|
|
#[derive(Debug)]
|
|
pub enum HalError {
|
|
Io(io::Error),
|
|
Protocol(&'static str),
|
|
Device(u8),
|
|
FrameTooLong,
|
|
InvalidFanPercent,
|
|
}
|
|
|
|
impl fmt::Display for HalError {
|
|
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
|
match self {
|
|
Self::Io(error) => write!(f, "HAL I/O: {error}"),
|
|
Self::Protocol(message) => write!(f, "HAL protocol: {message}"),
|
|
Self::Device(code) => write!(f, "HAL device error: {code}"),
|
|
Self::FrameTooLong => f.write_str("HAL frame exceeds the wire limit"),
|
|
Self::InvalidFanPercent => f.write_str("HAL fan target exceeds 100 percent"),
|
|
}
|
|
}
|
|
}
|
|
|
|
impl std::error::Error for HalError {}
|
|
|
|
impl From<io::Error> for HalError {
|
|
fn from(error: io::Error) -> Self {
|
|
Self::Io(error)
|
|
}
|
|
}
|
|
|
|
/// Local client for the privileged board backend supplied by the SDK image.
|
|
pub struct HalClient {
|
|
stream: UnixStream,
|
|
sequence: u32,
|
|
poisoned: bool,
|
|
}
|
|
|
|
impl HalClient {
|
|
fn poison(&mut self) {
|
|
self.poisoned = true;
|
|
let _ = self.stream.shutdown(Shutdown::Both);
|
|
}
|
|
|
|
pub fn connect(path: impl AsRef<Path>) -> Result<Self, HalError> {
|
|
let stream = connect_until(path.as_ref(), Instant::now() + IO_TIMEOUT)?;
|
|
Self::from_stream(stream)
|
|
}
|
|
|
|
pub fn from_stream(stream: UnixStream) -> Result<Self, HalError> {
|
|
stream.set_read_timeout(Some(IO_TIMEOUT))?;
|
|
stream.set_write_timeout(Some(IO_TIMEOUT))?;
|
|
Ok(Self {
|
|
stream,
|
|
sequence: 0,
|
|
poisoned: false,
|
|
})
|
|
}
|
|
|
|
fn exchange(&mut self, opcode: u8, payload: &[u8]) -> Result<Vec<u8>, HalError> {
|
|
if self.poisoned {
|
|
return Err(HalError::Protocol("connection is unusable"));
|
|
}
|
|
if payload.len() > MAX_PAYLOAD {
|
|
return Err(HalError::FrameTooLong);
|
|
}
|
|
let result = self.exchange_inner(opcode, payload);
|
|
if let Err(ref error) = result {
|
|
if !matches!(error, HalError::Device(_)) {
|
|
self.poison();
|
|
// A backend power lease must expire on disconnect. Reusing a
|
|
// desynchronized stream could silently discard an off request.
|
|
}
|
|
}
|
|
result
|
|
}
|
|
|
|
fn exchange_inner(&mut self, opcode: u8, payload: &[u8]) -> Result<Vec<u8>, HalError> {
|
|
let deadline = Instant::now() + IO_TIMEOUT;
|
|
self.sequence = self.sequence.wrapping_add(1);
|
|
let sequence = self.sequence;
|
|
let mut header = [0_u8; HEADER_LEN];
|
|
header[..4].copy_from_slice(&MAGIC);
|
|
header[4] = VERSION;
|
|
header[5] = opcode;
|
|
header[8..12].copy_from_slice(&sequence.to_le_bytes());
|
|
header[12..16].copy_from_slice(&(payload.len() as u32).to_le_bytes());
|
|
write_all_until(&mut self.stream, &header, deadline)?;
|
|
write_all_until(&mut self.stream, payload, deadline)?;
|
|
|
|
read_exact_until(&mut self.stream, &mut header, deadline)?;
|
|
if header[..4] != MAGIC || header[4] != VERSION || header[5] != opcode {
|
|
return Err(HalError::Protocol("response identity mismatch"));
|
|
}
|
|
if u16::from_le_bytes([header[6], header[7]]) != RESPONSE {
|
|
return Err(HalError::Protocol("response flag missing"));
|
|
}
|
|
if u32::from_le_bytes(header[8..12].try_into().unwrap()) != sequence {
|
|
return Err(HalError::Protocol("response sequence mismatch"));
|
|
}
|
|
let length = u32::from_le_bytes(header[12..16].try_into().unwrap()) as usize;
|
|
if !(1..=MAX_PAYLOAD).contains(&length) {
|
|
return Err(HalError::Protocol("invalid response length"));
|
|
}
|
|
let mut body = vec![0_u8; length];
|
|
read_exact_until(&mut self.stream, &mut body, deadline)?;
|
|
if body[0] != 0 {
|
|
if !matches!(body[0], 1..=3) || body.len() != 1 {
|
|
return Err(HalError::Protocol("invalid error response"));
|
|
}
|
|
return Err(HalError::Device(body[0]));
|
|
}
|
|
Ok(body[1..].to_vec())
|
|
}
|
|
|
|
fn empty_reply(&mut self, opcode: u8, payload: &[u8]) -> Result<(), HalError> {
|
|
if !self.exchange(opcode, payload)?.is_empty() {
|
|
self.poison();
|
|
return Err(HalError::Protocol("unexpected response data"));
|
|
}
|
|
Ok(())
|
|
}
|
|
}
|
|
|
|
fn timeout_error() -> io::Error {
|
|
io::Error::new(io::ErrorKind::TimedOut, "HAL operation timed out")
|
|
}
|
|
|
|
fn remaining(deadline: Instant) -> io::Result<Duration> {
|
|
deadline
|
|
.checked_duration_since(Instant::now())
|
|
.filter(|duration| !duration.is_zero())
|
|
.ok_or_else(timeout_error)
|
|
}
|
|
|
|
fn write_all_until(stream: &mut UnixStream, mut data: &[u8], deadline: Instant) -> io::Result<()> {
|
|
while !data.is_empty() {
|
|
stream.set_write_timeout(Some(remaining(deadline)?))?;
|
|
match stream.write(data) {
|
|
Ok(0) => {
|
|
return Err(io::Error::new(
|
|
io::ErrorKind::WriteZero,
|
|
"HAL socket closed",
|
|
))
|
|
}
|
|
Ok(count) => data = &data[count..],
|
|
Err(error) if error.kind() == io::ErrorKind::Interrupted => continue,
|
|
Err(error) => return Err(error),
|
|
}
|
|
}
|
|
Ok(())
|
|
}
|
|
|
|
fn read_exact_until(
|
|
stream: &mut UnixStream,
|
|
mut data: &mut [u8],
|
|
deadline: Instant,
|
|
) -> io::Result<()> {
|
|
while !data.is_empty() {
|
|
stream.set_read_timeout(Some(remaining(deadline)?))?;
|
|
match stream.read(data) {
|
|
Ok(0) => {
|
|
return Err(io::Error::new(
|
|
io::ErrorKind::UnexpectedEof,
|
|
"HAL socket closed",
|
|
))
|
|
}
|
|
Ok(count) => data = &mut data[count..],
|
|
Err(error) if error.kind() == io::ErrorKind::Interrupted => continue,
|
|
Err(error) => return Err(error),
|
|
}
|
|
}
|
|
Ok(())
|
|
}
|
|
|
|
fn connect_until(path: &Path, deadline: Instant) -> io::Result<UnixStream> {
|
|
let bytes = path.as_os_str().as_bytes();
|
|
let max_path =
|
|
std::mem::size_of::<sys::SockaddrUn>() - std::mem::offset_of!(sys::SockaddrUn, sun_path);
|
|
if bytes.is_empty() || bytes.len() >= max_path || bytes.contains(&0) {
|
|
return Err(io::Error::new(
|
|
io::ErrorKind::InvalidInput,
|
|
"invalid HAL socket path",
|
|
));
|
|
}
|
|
let raw = unsafe {
|
|
sys::socket(
|
|
sys::AF_UNIX,
|
|
sys::SOCK_STREAM | sys::SOCK_NONBLOCK | sys::SOCK_CLOEXEC,
|
|
0,
|
|
)
|
|
};
|
|
if raw < 0 {
|
|
return Err(io::Error::last_os_error());
|
|
}
|
|
let fd = unsafe { OwnedFd::from_raw_fd(raw) };
|
|
let mut address: sys::SockaddrUn = unsafe { std::mem::zeroed() };
|
|
address.sun_family = sys::AF_UNIX as sys::SaFamily;
|
|
for (destination, source) in address.sun_path.iter_mut().zip(bytes) {
|
|
*destination = *source as sys::CChar;
|
|
}
|
|
let length =
|
|
(std::mem::offset_of!(sys::SockaddrUn, sun_path) + bytes.len() + 1) as sys::SocklenT;
|
|
loop {
|
|
let result = unsafe {
|
|
sys::connect(
|
|
fd.as_raw_fd(),
|
|
&address as *const _ as *const sys::CVoid,
|
|
length,
|
|
)
|
|
};
|
|
if result == 0 {
|
|
break;
|
|
}
|
|
let error = io::Error::last_os_error();
|
|
if error.raw_os_error() == Some(sys::EISCONN) {
|
|
break;
|
|
}
|
|
if !matches!(
|
|
error.raw_os_error(),
|
|
Some(sys::EINPROGRESS) | Some(sys::EAGAIN)
|
|
) {
|
|
return Err(error);
|
|
}
|
|
let mut poll_fd = sys::PollFd {
|
|
fd: fd.as_raw_fd(),
|
|
events: sys::POLLOUT,
|
|
revents: 0,
|
|
};
|
|
let wait = remaining(deadline)?.as_millis().min(i32::MAX as u128) as i32;
|
|
let polled = unsafe { sys::poll(&mut poll_fd, 1, wait.max(1)) };
|
|
if polled < 0 {
|
|
let error = io::Error::last_os_error();
|
|
if error.kind() == io::ErrorKind::Interrupted {
|
|
continue;
|
|
}
|
|
return Err(error);
|
|
}
|
|
if polled == 0 {
|
|
return Err(timeout_error());
|
|
}
|
|
let mut socket_error: sys::CInt = 0;
|
|
let mut socket_error_len = std::mem::size_of_val(&socket_error) as sys::SocklenT;
|
|
if unsafe {
|
|
sys::getsockopt(
|
|
fd.as_raw_fd(),
|
|
sys::SOL_SOCKET,
|
|
sys::SO_ERROR,
|
|
&mut socket_error as *mut _ as *mut sys::CVoid,
|
|
&mut socket_error_len,
|
|
)
|
|
} < 0
|
|
{
|
|
return Err(io::Error::last_os_error());
|
|
}
|
|
if socket_error != 0 {
|
|
return Err(io::Error::from_raw_os_error(socket_error));
|
|
}
|
|
if error.raw_os_error() == Some(sys::EINPROGRESS) {
|
|
break;
|
|
}
|
|
}
|
|
let stream = UnixStream::from(fd);
|
|
stream.set_nonblocking(false)?;
|
|
Ok(stream)
|
|
}
|
|
|
|
impl HalClient {
|
|
/// Feature mask advertised by the backend. Old backends reject the opcode, which surfaces as
|
|
/// a protocol error rather than a silent zero.
|
|
pub fn capabilities(&mut self) -> Result<u32, HalError> {
|
|
let body = self.exchange(CAPABILITIES, &[])?;
|
|
let bytes: [u8; 4] = body
|
|
.try_into()
|
|
.map_err(|_| HalError::Protocol("invalid capability response"))?;
|
|
Ok(u32::from_le_bytes(bytes))
|
|
}
|
|
|
|
fn require(&mut self, capability: u32) -> Result<(), HalError> {
|
|
if self.capabilities()? & capability == 0 {
|
|
return Err(HalError::Protocol("backend lacks a detection capability"));
|
|
}
|
|
Ok(())
|
|
}
|
|
|
|
pub fn probe_chain(&mut self, chain: u8, attempt: u8) -> Result<ProbeOutcome, HalError> {
|
|
self.require(CAP_CHAIN_PROBE)?;
|
|
let body = self.exchange(PROBE_CHAIN, &[chain, attempt])?;
|
|
if body.len() != 4 {
|
|
self.poison();
|
|
return Err(HalError::Protocol("invalid probe response"));
|
|
}
|
|
let chips = u16::from_le_bytes([body[2], body[3]]);
|
|
match body[0] {
|
|
PROBE_IDENTIFIED => match chip_from_wire(body[1]) {
|
|
Some(chip) => Ok(ProbeOutcome::Identified { chip, chips }),
|
|
None => {
|
|
self.poison();
|
|
Err(HalError::Protocol("unknown chip identifier"))
|
|
}
|
|
},
|
|
PROBE_SILENT => Ok(ProbeOutcome::Silent),
|
|
PROBE_GARBLED => Ok(ProbeOutcome::Garbled),
|
|
_ => {
|
|
self.poison();
|
|
Err(HalError::Protocol("invalid probe outcome"))
|
|
}
|
|
}
|
|
}
|
|
|
|
pub fn read_eeprom(&mut self, chain: u8) -> Result<EepromState, HalError> {
|
|
self.require(CAP_EEPROM)?;
|
|
let body = self.exchange(READ_EEPROM, &[chain])?;
|
|
match body.first().copied() {
|
|
Some(EEPROM_ABSENT) if body.len() == 1 => Ok(EepromState::Absent),
|
|
Some(EEPROM_INVALID) if body.len() == 1 => Ok(EepromState::Invalid),
|
|
Some(EEPROM_PRESENT) if body.len() > 1 => {
|
|
let model = std::str::from_utf8(&body[1..])
|
|
.map_err(|_| HalError::Protocol("invalid EEPROM model text"))?;
|
|
Ok(EepromState::Present {
|
|
model: model.to_owned(),
|
|
})
|
|
}
|
|
_ => {
|
|
self.poison();
|
|
Err(HalError::Protocol("invalid EEPROM response"))
|
|
}
|
|
}
|
|
}
|
|
|
|
/// Apply a chain frequency in MHz. The backend owns the PLL write; the OS owns the decision.
|
|
pub fn set_chain_frequency(&mut self, chain: u8, mhz: u16) -> Result<(), HalError> {
|
|
self.require(CAP_FREQUENCY)?;
|
|
let mut payload = [0_u8; 3];
|
|
payload[0] = chain;
|
|
payload[1..].copy_from_slice(&mhz.to_le_bytes());
|
|
self.empty_reply(SET_CHAIN_FREQUENCY, &payload)
|
|
}
|
|
|
|
/// Measured DC input power in watts, when the board can read its PSU.
|
|
pub fn read_power_w(&mut self) -> Result<u16, HalError> {
|
|
self.require(CAP_POWER)?;
|
|
let body = self.exchange(READ_POWER, &[])?;
|
|
if body.len() != 2 {
|
|
self.poison();
|
|
return Err(HalError::Protocol("invalid power response"));
|
|
}
|
|
Ok(u16::from_le_bytes([body[0], body[1]]))
|
|
}
|
|
|
|
pub fn identify_psu(&mut self) -> Result<PsuCapability, HalError> {
|
|
self.require(CAP_PSU_IDENTITY)?;
|
|
let body = self.exchange(IDENTIFY_PSU, &[])?;
|
|
let name_len = *body
|
|
.first()
|
|
.ok_or(HalError::Protocol("empty PSU response"))? as usize;
|
|
if body.len() != name_len + 1 + 10 {
|
|
self.poison();
|
|
return Err(HalError::Protocol("invalid PSU response"));
|
|
}
|
|
let name = std::str::from_utf8(&body[1..1 + name_len])
|
|
.map_err(|_| HalError::Protocol("invalid PSU name"))?
|
|
.to_owned();
|
|
let at = 1 + name_len;
|
|
let word = |offset: usize| u16::from_le_bytes([body[at + offset], body[at + offset + 1]]);
|
|
Ok(PsuCapability {
|
|
name,
|
|
envelope: Envelope {
|
|
v_min_mv: word(0),
|
|
v_max_mv: word(2),
|
|
f_min_mhz: word(4),
|
|
f_max_mhz: word(6),
|
|
},
|
|
max_dc_watts: word(8),
|
|
})
|
|
}
|
|
}
|
|
|
|
impl DetectionBackend for HalClient {
|
|
type Error = HalError;
|
|
|
|
fn probe(&mut self, chain: u8, attempt: u8) -> Result<ProbeOutcome, Self::Error> {
|
|
self.probe_chain(chain, attempt)
|
|
}
|
|
|
|
fn eeprom(&mut self, chain: u8) -> Result<EepromState, Self::Error> {
|
|
self.read_eeprom(chain)
|
|
}
|
|
|
|
fn identify_psu(&mut self) -> Result<Option<PsuCapability>, Self::Error> {
|
|
self.identify_psu().map(Some)
|
|
}
|
|
}
|
|
|
|
impl crate::fanmap::FanProbe for HalClient {
|
|
type Error = HalError;
|
|
|
|
fn set_fan(&mut self, fan: u8, pwm: u8) -> Result<(), Self::Error> {
|
|
self.set_fan_target(fan, pwm)
|
|
}
|
|
|
|
fn read_zone(&mut self, zone: u8) -> Result<i32, Self::Error> {
|
|
self.read_temperature_mc(zone)
|
|
}
|
|
}
|
|
|
|
fn chip_from_wire(value: u8) -> Option<ChipModel> {
|
|
match value {
|
|
1 => Some(ChipModel::Bm1362),
|
|
2 => Some(ChipModel::Bm1366),
|
|
3 => Some(ChipModel::Bm1368),
|
|
4 => Some(ChipModel::Bm1370),
|
|
5 => Some(ChipModel::Bm1398),
|
|
_ => None,
|
|
}
|
|
}
|
|
|
|
impl HardwareBackend for HalClient {
|
|
type Error = HalError;
|
|
|
|
fn send_frame(&mut self, chain: u8, frame: &[u8]) -> Result<(), Self::Error> {
|
|
if frame.len() > MAX_PAYLOAD - 3 {
|
|
return Err(HalError::FrameTooLong);
|
|
}
|
|
let mut body = Vec::with_capacity(frame.len() + 3);
|
|
body.push(chain);
|
|
body.extend_from_slice(&(frame.len() as u16).to_le_bytes());
|
|
body.extend_from_slice(frame);
|
|
self.empty_reply(SEND_FRAME, &body)
|
|
}
|
|
|
|
fn receive_frame(&mut self, chain: u8, frame: &mut [u8]) -> Result<usize, Self::Error> {
|
|
if frame.len() > MAX_PAYLOAD - 3 {
|
|
return Err(HalError::FrameTooLong);
|
|
}
|
|
let mut request = [0_u8; 3];
|
|
request[0] = chain;
|
|
request[1..].copy_from_slice(&(frame.len() as u16).to_le_bytes());
|
|
let body = self.exchange(RECEIVE_FRAME, &request)?;
|
|
if body.len() < 2 {
|
|
self.poison();
|
|
return Err(HalError::Protocol("missing receive length"));
|
|
}
|
|
let count = u16::from_le_bytes([body[0], body[1]]) as usize;
|
|
if count > frame.len() || body.len() != count + 2 {
|
|
self.poison();
|
|
return Err(HalError::Protocol("invalid received frame size"));
|
|
}
|
|
frame[..count].copy_from_slice(&body[2..]);
|
|
Ok(count)
|
|
}
|
|
|
|
fn set_chain_reset(&mut self, chain: u8, asserted: bool) -> Result<(), Self::Error> {
|
|
self.empty_reply(SET_CHAIN_RESET, &[chain, u8::from(asserted)])
|
|
}
|
|
|
|
fn set_fan_target(&mut self, fan: u8, percent: u8) -> Result<(), Self::Error> {
|
|
if percent > 100 {
|
|
return Err(HalError::InvalidFanPercent);
|
|
}
|
|
self.empty_reply(SET_FAN_TARGET, &[fan, percent])
|
|
}
|
|
|
|
fn read_temperature_mc(&mut self, sensor: u8) -> Result<i32, Self::Error> {
|
|
let body = self.exchange(READ_TEMPERATURE, &[sensor])?;
|
|
let bytes: [u8; 4] = match body.try_into() {
|
|
Ok(bytes) => bytes,
|
|
Err(_) => {
|
|
self.poison();
|
|
return Err(HalError::Protocol("invalid temperature response"));
|
|
}
|
|
};
|
|
Ok(i32::from_le_bytes(bytes))
|
|
}
|
|
|
|
fn set_psu_enabled(&mut self, enabled: bool) -> Result<(), Self::Error> {
|
|
let result = self.empty_reply(SET_PSU_ENABLED, &[u8::from(enabled)]);
|
|
if !enabled && result.is_err() {
|
|
self.poison();
|
|
}
|
|
result
|
|
}
|
|
}
|
|
|
|
#[cfg(test)]
|
|
mod tests {
|
|
use super::*;
|
|
use crate::fanmap::FanProbe;
|
|
use std::os::unix::net::UnixStream;
|
|
|
|
fn mock_backend(mut server: UnixStream) {
|
|
loop {
|
|
let mut header = [0_u8; 16];
|
|
if server.read_exact(&mut header).is_err() {
|
|
return;
|
|
}
|
|
let opcode = header[5];
|
|
let sequence = [header[8], header[9], header[10], header[11]];
|
|
let length = u32::from_le_bytes(header[12..16].try_into().unwrap()) as usize;
|
|
let mut payload = vec![0_u8; length];
|
|
if length > 0 && server.read_exact(&mut payload).is_err() {
|
|
return;
|
|
}
|
|
let body: Vec<u8> = match opcode {
|
|
CAPABILITIES => {
|
|
let mut body = vec![0_u8];
|
|
body.extend_from_slice(
|
|
&(CAP_CHAIN_PROBE
|
|
| CAP_EEPROM
|
|
| CAP_PSU_IDENTITY
|
|
| CAP_FREQUENCY
|
|
| CAP_POWER)
|
|
.to_le_bytes(),
|
|
);
|
|
body
|
|
}
|
|
PROBE_CHAIN => vec![0, PROBE_IDENTIFIED, 1, 126, 0],
|
|
READ_EEPROM => {
|
|
let mut body = vec![0, EEPROM_PRESENT];
|
|
body.extend_from_slice(b"BHB42601");
|
|
body
|
|
}
|
|
IDENTIFY_PSU => {
|
|
let name = b"APW12";
|
|
let mut body = vec![0_u8];
|
|
body.push(name.len() as u8);
|
|
body.extend_from_slice(name);
|
|
for word in [1200_u16, 1600, 0, 1000, 3600] {
|
|
body.extend_from_slice(&word.to_le_bytes());
|
|
}
|
|
body
|
|
}
|
|
SET_FAN_TARGET | SET_CHAIN_FREQUENCY => vec![0],
|
|
READ_POWER => {
|
|
let mut body = vec![0_u8];
|
|
body.extend_from_slice(&0_u16.to_le_bytes());
|
|
body
|
|
}
|
|
READ_TEMPERATURE => {
|
|
let mut body = vec![0_u8];
|
|
body.extend_from_slice(&42_000_i32.to_le_bytes());
|
|
body
|
|
}
|
|
_ => vec![1],
|
|
};
|
|
let mut out = [0_u8; 16];
|
|
out[..4].copy_from_slice(&MAGIC);
|
|
out[4] = VERSION;
|
|
out[5] = opcode;
|
|
out[6..8].copy_from_slice(&RESPONSE.to_le_bytes());
|
|
out[8..12].copy_from_slice(&sequence);
|
|
out[12..16].copy_from_slice(&(body.len() as u32).to_le_bytes());
|
|
if server.write_all(&out).is_err() || server.write_all(&body).is_err() {
|
|
return;
|
|
}
|
|
}
|
|
}
|
|
|
|
#[test]
|
|
fn detection_verbs_round_trip_over_the_wire() {
|
|
let (client_stream, server_stream) = UnixStream::pair().expect("socket pair");
|
|
let server = std::thread::spawn(move || mock_backend(server_stream));
|
|
let mut client = HalClient::from_stream(client_stream).expect("client");
|
|
|
|
assert_eq!(
|
|
client.capabilities().expect("capabilities"),
|
|
CAP_CHAIN_PROBE | CAP_EEPROM | CAP_PSU_IDENTITY | CAP_FREQUENCY | CAP_POWER
|
|
);
|
|
match client.probe_chain(0, 0).expect("probe") {
|
|
ProbeOutcome::Identified { chip, chips } => {
|
|
assert_eq!(chip, ChipModel::Bm1362);
|
|
assert_eq!(chips, 126);
|
|
}
|
|
other => panic!("unexpected probe outcome: {other:?}"),
|
|
}
|
|
assert_eq!(
|
|
client.read_eeprom(0).expect("eeprom"),
|
|
EepromState::Present {
|
|
model: "BHB42601".into()
|
|
}
|
|
);
|
|
let psu = client.identify_psu().expect("psu");
|
|
assert_eq!(psu.name, "APW12");
|
|
assert_eq!(psu.envelope.v_min_mv, 1200);
|
|
assert_eq!(psu.envelope.v_max_mv, 1600);
|
|
assert_eq!(psu.max_dc_watts, 3600);
|
|
|
|
client.set_chain_frequency(2, 512).expect("set frequency");
|
|
client.set_fan(1, 60).expect("set fan");
|
|
assert_eq!(client.read_zone(2).expect("read zone"), 42_000);
|
|
|
|
drop(client);
|
|
server.join().expect("server thread");
|
|
}
|
|
}
|