Vendor asic-rs 0.8.1 (280 crates, offline builds) + wxWidgets 3.3.3 (pristine + patch queue); UI spec + ADR-0003; M1 on asic-rs

This commit is contained in:
2026-09-15 10:41:00 -06:00
parent 6dc77e8eb0
commit a2b65bb47f
16427 changed files with 6972976 additions and 3 deletions
+436
View File
@@ -0,0 +1,436 @@
use std::{
fmt::Display,
net::IpAddr,
pin::Pin,
str::FromStr,
sync::{Arc, Mutex},
};
use crate::{
factory::MinerFactory as MinerFactory_Base,
python::{
miner::Miner,
typing::{
CancelAction, PyAsyncIterator, PyAwaitable, abortable_future_into_py_with_cancel,
future_into_py,
},
},
};
use asic_rs_core::traits::miner::Miner as MinerTrait;
use asic_rs_pydantic::py_to_string;
use futures::{Stream, StreamExt};
use pyo3::{
exceptions::{PyConnectionError, PyRuntimeError, PyStopAsyncIteration, PyValueError},
prelude::*,
types::PyType,
};
type MinerStream = Pin<Box<dyn Stream<Item = Box<dyn MinerTrait>> + Send>>;
type MinerStreamWithIp = Pin<Box<dyn Stream<Item = (IpAddr, Option<Box<dyn MinerTrait>>)> + Send>>;
enum StreamState<S> {
Ready(S),
InUse,
Closed,
}
struct StreamLease<S> {
state: Arc<Mutex<StreamState<S>>>,
stream: Option<S>,
}
impl<S> StreamLease<S> {
fn take(state: Arc<Mutex<StreamState<S>>>) -> PyResult<Self> {
let stream = {
let mut guard = state
.lock()
.map_err(|_| PyRuntimeError::new_err("stream state lock poisoned"))?;
match std::mem::replace(&mut *guard, StreamState::InUse) {
StreamState::Ready(stream) => stream,
StreamState::InUse => {
return Err(PyRuntimeError::new_err("stream is already being polled"));
}
StreamState::Closed => {
*guard = StreamState::Closed;
return Err(PyStopAsyncIteration::new_err("stream complete"));
}
}
};
Ok(Self {
state,
stream: Some(stream),
})
}
fn stream_mut(&mut self) -> PyResult<&mut S> {
self.stream
.as_mut()
.ok_or_else(|| PyRuntimeError::new_err("stream lease missing stream"))
}
fn store(mut self, state: StreamState<S>) -> PyResult<()> {
self.stream = None;
let mut guard = self
.state
.lock()
.map_err(|_| PyRuntimeError::new_err("stream state lock poisoned"))?;
if matches!(*guard, StreamState::Closed) && matches!(state, StreamState::Ready(_)) {
return Ok(());
}
*guard = state;
Ok(())
}
fn store_ready(mut self) -> PyResult<()> {
let stream = self
.stream
.take()
.ok_or_else(|| PyRuntimeError::new_err("stream lease missing stream"))?;
self.store(StreamState::Ready(stream))
}
fn close(self) -> PyResult<()> {
self.store(StreamState::Closed)
}
}
impl<S> Drop for StreamLease<S> {
fn drop(&mut self) {
if self.stream.is_some()
&& let Ok(mut guard) = self.state.lock()
{
*guard = StreamState::Closed;
}
}
}
fn close_stream_state<S>(state: &Arc<Mutex<StreamState<S>>>) {
let _previous = {
let Ok(mut guard) = state.lock() else {
return;
};
std::mem::replace(&mut *guard, StreamState::Closed)
};
}
fn close_stream_on_cancel<S: Send + 'static>(state: Arc<Mutex<StreamState<S>>>) -> CancelAction {
Box::new(move || close_stream_state(&state))
}
#[pyclass]
pub struct PyMinerStream {
inner: Arc<Mutex<StreamState<MinerStream>>>,
}
impl PyMinerStream {
fn new(inner: MinerStream) -> Self {
Self {
inner: Arc::new(Mutex::new(StreamState::Ready(inner))),
}
}
}
#[pymethods]
impl PyMinerStream {
pub fn __aiter__(slf: PyRef<Self>) -> PyRef<Self> {
slf
}
pub fn __anext__<'py>(&self, py: Python<'py>) -> PyResult<Bound<'py, PyAny>> {
let inner = self.inner.clone();
let cancel_inner = inner.clone();
abortable_future_into_py_with_cancel(
py,
async move {
let mut lease = StreamLease::take(inner)?;
match lease.stream_mut()?.next().await {
Some(miner) => {
let miner = Miner::from(miner);
lease.store_ready()?;
Ok(miner)
}
None => {
lease.close()?;
Err(PyStopAsyncIteration::new_err("stream complete"))
}
}
},
Some(close_stream_on_cancel(cancel_inner)),
)
}
}
#[pyclass]
pub struct PyMinerStreamWithIP {
inner: Arc<Mutex<StreamState<MinerStreamWithIp>>>,
}
impl PyMinerStreamWithIP {
fn new(inner: MinerStreamWithIp) -> Self {
Self {
inner: Arc::new(Mutex::new(StreamState::Ready(inner))),
}
}
}
#[pymethods]
impl PyMinerStreamWithIP {
pub fn __aiter__(slf: PyRef<Self>) -> PyRef<Self> {
slf
}
pub fn __anext__<'py>(&self, py: Python<'py>) -> PyResult<Bound<'py, PyAny>> {
let inner = self.inner.clone();
let cancel_inner = inner.clone();
abortable_future_into_py_with_cancel(
py,
async move {
let mut lease = StreamLease::take(inner)?;
match lease.stream_mut()?.next().await {
Some((ip, miner_opt)) => {
let item = (ip, miner_opt.map(Miner::new));
lease.store_ready()?;
Ok(item)
}
None => {
lease.close()?;
Err(PyStopAsyncIteration::new_err("stream complete"))
}
}
},
Some(close_stream_on_cancel(cancel_inner)),
)
}
}
/// Python handle for miner discovery and construction.
///
/// A `MinerFactory` stores the IP addresses to scan plus discovery tuning such
/// as concurrency and timeouts. Methods that add ranges return `self`, so calls
/// can be chained before awaiting `scan()`.
#[pyclass(module = "asic_rs")]
pub(crate) struct MinerFactory {
inner: Arc<MinerFactory_Base>,
}
impl MinerFactory {
fn from_inner_result<E: Display>(inner: Result<MinerFactory_Base, E>) -> PyResult<Self> {
inner
.map(|inner| Self {
inner: Arc::new(inner),
})
.map_err(|e| PyValueError::new_err(e.to_string()))
}
fn update_inner<'py>(
mut slf: PyRefMut<'py, Self>,
update: impl FnOnce(MinerFactory_Base) -> MinerFactory_Base,
) -> PyRefMut<'py, Self> {
let inner = Arc::<MinerFactory_Base>::make_mut(&mut slf.inner).clone();
slf.inner = Arc::new(update(inner));
slf
}
fn try_update_inner<'py, E: Display>(
mut slf: PyRefMut<'py, Self>,
update: impl FnOnce(MinerFactory_Base) -> Result<MinerFactory_Base, E>,
) -> PyResult<PyRefMut<'py, Self>> {
let inner = Arc::<MinerFactory_Base>::make_mut(&mut slf.inner).clone();
slf.inner = Arc::new(update(inner).map_err(|e| PyValueError::new_err(e.to_string()))?);
Ok(slf)
}
}
#[pymethods]
impl MinerFactory {
/// Create an empty factory.
///
/// Use `get_miner(ip)` for a known address, or add a range with
/// `from_subnet`, `from_octets`, `from_range`, or the matching `with_*`
/// methods before calling `scan()`.
#[new]
pub fn new() -> Self {
Self {
inner: Arc::new(MinerFactory_Base::new()),
}
}
/// Create a factory populated from a CIDR subnet.
///
/// Example: `MinerFactory.from_subnet("192.168.1.0/24")`.
#[classmethod]
pub fn from_subnet(_cls: &Bound<'_, PyType>, subnet: String) -> PyResult<Self> {
Self::from_inner_result(MinerFactory_Base::from_subnet(&subnet))
}
/// Append all addresses from a CIDR subnet and return this factory.
pub fn with_subnet<'py>(
slf: PyRefMut<'py, Self>,
subnet: &str,
) -> PyResult<PyRefMut<'py, Self>> {
Self::try_update_inner(slf, |inner| inner.with_subnet(subnet))
}
/// Create a factory from four IPv4 octet selectors.
///
/// Each octet may be a number or a string range such as `"1-254"`.
#[classmethod]
#[pyo3(signature = (octet1: "str | int", octet2: "str | int", octet3: "str | int", octet4: "str | int") -> "MinerFactory")]
pub fn from_octets(
_cls: &Bound<'_, PyType>,
octet1: &Bound<'_, PyAny>,
octet2: &Bound<'_, PyAny>,
octet3: &Bound<'_, PyAny>,
octet4: &Bound<'_, PyAny>,
) -> PyResult<Self> {
let octet1 = py_to_string(octet1)?;
let octet2 = py_to_string(octet2)?;
let octet3 = py_to_string(octet3)?;
let octet4 = py_to_string(octet4)?;
Self::from_inner_result(MinerFactory_Base::from_octets(
&octet1, &octet2, &octet3, &octet4,
))
}
/// Append addresses generated from four IPv4 octet selectors.
#[pyo3(signature = (octet1: "str | int", octet2: "str | int", octet3: "str | int", octet4: "str | int") -> "MinerFactory")]
pub fn with_octets<'py>(
slf: PyRefMut<'py, Self>,
octet1: &Bound<'_, PyAny>,
octet2: &Bound<'_, PyAny>,
octet3: &Bound<'_, PyAny>,
octet4: &Bound<'_, PyAny>,
) -> PyResult<PyRefMut<'py, Self>> {
let octet1 = py_to_string(octet1)?;
let octet2 = py_to_string(octet2)?;
let octet3 = py_to_string(octet3)?;
let octet4 = py_to_string(octet4)?;
Self::try_update_inner(slf, |inner| {
inner.with_octets(&octet1, &octet2, &octet3, &octet4)
})
}
/// Create a factory from an IPv4 range string.
///
/// Example: `MinerFactory.from_range("192.168.1.1-254")`.
#[classmethod]
pub fn from_range(_cls: &Bound<'_, PyType>, range: String) -> PyResult<Self> {
Self::from_inner_result(MinerFactory_Base::from_range(&range))
}
/// Append addresses generated from an IPv4 range string.
pub fn with_range<'py>(slf: PyRefMut<'py, Self>, range: &str) -> PyResult<PyRefMut<'py, Self>> {
Self::try_update_inner(slf, |inner| inner.with_range(range))
}
/// Set the maximum number of addresses scanned concurrently.
///
/// This also caps active TCP connectivity probes across the scan.
pub fn with_concurrent_limit<'py>(
slf: PyRefMut<'py, Self>,
limit: usize,
) -> PyResult<PyRefMut<'py, Self>> {
Ok(Self::update_inner(slf, |inner| {
inner.with_concurrent_limit(limit)
}))
}
/// Set the maximum seconds spent identifying and constructing a miner.
pub fn with_identification_timeout_secs<'py>(
slf: PyRefMut<'py, Self>,
timeout_secs: u64,
) -> PyResult<PyRefMut<'py, Self>> {
Ok(Self::update_inner(slf, |inner| {
inner.with_identification_timeout_secs(timeout_secs)
}))
}
/// Set the timeout, in seconds, for quick connectivity probes.
pub fn with_connectivity_timeout_secs<'py>(
slf: PyRefMut<'py, Self>,
timeout_secs: u64,
) -> PyResult<PyRefMut<'py, Self>> {
Ok(Self::update_inner(slf, |inner| {
inner.with_connectivity_timeout_secs(timeout_secs)
}))
}
/// Set connectivity retries after the initial attempt.
///
/// Each address is probed at least once. Retries use bounded exponential
/// backoff and remain inside the initial scan's concurrency bound.
pub fn with_connectivity_retries<'py>(
slf: PyRefMut<'py, Self>,
retries: u32,
) -> PyResult<PyRefMut<'py, Self>> {
Ok(Self::update_inner(slf, |inner| {
inner.with_connectivity_retries(retries)
}))
}
/// Enable or disable quick TCP port checks before miner identification.
pub fn with_port_check<'py>(
slf: PyRefMut<'py, Self>,
enabled: bool,
) -> PyResult<PyRefMut<'py, Self>> {
Ok(Self::update_inner(slf, |inner| {
inner.with_port_check(enabled)
}))
}
/// Await a scan of all queued addresses and return every supported miner.
///
/// Unsupported hosts are skipped. Raises `ValueError` when no addresses have
/// been queued or when the scan setup is invalid.
pub fn scan<'a>(&self, py: Python<'a>) -> PyResult<PyAwaitable<Vec<Miner>>> {
let inner = Arc::clone(&self.inner);
future_into_py(py, async move {
let miners = inner.scan().await;
match miners {
Ok(miners) => Ok(miners.into_iter().map(Miner::from).collect::<Vec<Miner>>()),
Err(e) => Err(PyValueError::new_err(e.to_string())),
}
})
}
/// Return an async iterator over miners as soon as they are found.
pub fn scan_stream<'py>(&self, py: Python<'py>) -> PyResult<PyAsyncIterator<Miner>> {
let inner = Arc::clone(&self.inner);
Bound::new(py, PyMinerStream::new(inner.scan_stream()))
.map(Bound::into_any)
.map(PyAsyncIterator::new)
}
/// Return an async iterator of `(ip, miner)` for every scanned address.
///
/// The miner value is `None` when the IP did not identify as a supported
/// ASIC miner.
pub fn scan_stream_with_ip<'py>(
&self,
py: Python<'py>,
) -> PyResult<PyAsyncIterator<(IpAddr, Option<Miner>)>> {
let inner = Arc::clone(&self.inner);
Bound::new(py, PyMinerStreamWithIP::new(inner.scan_stream_with_ip()))
.map(Bound::into_any)
.map(PyAsyncIterator::new)
}
/// Identify and construct a miner at a known IP address.
///
/// Returns `None` when the address does not respond as a supported miner.
/// Raises `ConnectionError` for discovery errors.
pub fn get_miner<'a>(
&self,
py: Python<'a>,
ip: String,
) -> PyResult<PyAwaitable<Option<Miner>>> {
let inner = Arc::clone(&self.inner);
future_into_py(py, async move {
let miner = inner.get_miner(IpAddr::from_str(&ip)?).await;
match miner {
Ok(Some(miner)) => Ok(Some(Miner::from(miner))),
Ok(None) => Ok(None),
Err(e) => Err(PyConnectionError::new_err(e.to_string())),
}
})
}
}
+266
View File
@@ -0,0 +1,266 @@
use std::{
net::IpAddr,
pin::Pin,
sync::{Arc, Mutex},
};
use crate::{
listener::MinerListener as MinerListenerBase,
python::{
miner::Miner,
typing::{CancelAction, PyAsyncIterator, abortable_future_into_py_with_cancel},
},
};
use asic_rs_core::traits::miner::Miner as MinerTrait;
use async_stream::stream;
use futures::Stream;
use pyo3::{
exceptions::{PyRuntimeError, PyStopAsyncIteration},
prelude::*,
};
use tokio_stream::StreamExt;
type ListenerMinerStream =
Pin<Box<dyn Stream<Item = anyhow::Result<Option<Box<dyn MinerTrait>>>> + Send>>;
type ListenerIpStream = Pin<Box<dyn Stream<Item = anyhow::Result<Option<IpAddr>>> + Send>>;
enum StreamState<S> {
Ready(S),
InUse,
Closed,
}
struct StreamLease<S> {
state: Arc<Mutex<StreamState<S>>>,
stream: Option<S>,
}
impl<S> StreamLease<S> {
fn take(state: Arc<Mutex<StreamState<S>>>) -> PyResult<Self> {
let stream = {
let mut guard = state
.lock()
.map_err(|_| PyRuntimeError::new_err("stream state lock poisoned"))?;
match std::mem::replace(&mut *guard, StreamState::InUse) {
StreamState::Ready(stream) => stream,
StreamState::InUse => {
return Err(PyRuntimeError::new_err("stream is already being polled"));
}
StreamState::Closed => {
*guard = StreamState::Closed;
return Err(PyStopAsyncIteration::new_err("stream complete"));
}
}
};
Ok(Self {
state,
stream: Some(stream),
})
}
fn stream_mut(&mut self) -> PyResult<&mut S> {
self.stream
.as_mut()
.ok_or_else(|| PyRuntimeError::new_err("stream lease missing stream"))
}
fn store(mut self, state: StreamState<S>) -> PyResult<()> {
self.stream = None;
let mut guard = self
.state
.lock()
.map_err(|_| PyRuntimeError::new_err("stream state lock poisoned"))?;
if matches!(*guard, StreamState::Closed) && matches!(state, StreamState::Ready(_)) {
return Ok(());
}
*guard = state;
Ok(())
}
fn store_ready(mut self) -> PyResult<()> {
let stream = self
.stream
.take()
.ok_or_else(|| PyRuntimeError::new_err("stream lease missing stream"))?;
self.store(StreamState::Ready(stream))
}
fn close(self) -> PyResult<()> {
self.store(StreamState::Closed)
}
}
impl<S> Drop for StreamLease<S> {
fn drop(&mut self) {
if self.stream.is_some()
&& let Ok(mut guard) = self.state.lock()
{
*guard = StreamState::Closed;
}
}
}
fn close_stream_state<S>(state: &Arc<Mutex<StreamState<S>>>) {
let _previous = {
let Ok(mut guard) = state.lock() else {
return;
};
std::mem::replace(&mut *guard, StreamState::Closed)
};
}
fn close_stream_on_cancel<S: Send + 'static>(state: Arc<Mutex<StreamState<S>>>) -> CancelAction {
Box::new(move || close_stream_state(&state))
}
fn miner_stream(listener: Arc<MinerListenerBase>) -> ListenerMinerStream {
Box::pin(stream! {
let mut inner = listener.listen().await;
while let Some(item) = inner.next().await {
yield item;
}
})
}
fn ip_stream(listener: Arc<MinerListenerBase>) -> ListenerIpStream {
Box::pin(stream! {
let mut inner = listener.listen_ip_only().await;
while let Some(item) = inner.next().await {
yield item;
}
})
}
#[pyclass]
struct PyListenerMinerStream {
inner: Arc<Mutex<StreamState<ListenerMinerStream>>>,
}
impl PyListenerMinerStream {
fn new(inner: ListenerMinerStream) -> Self {
Self {
inner: Arc::new(Mutex::new(StreamState::Ready(inner))),
}
}
}
#[pymethods]
impl PyListenerMinerStream {
pub fn __aiter__(slf: PyRef<Self>) -> PyRef<Self> {
slf
}
pub fn __anext__<'py>(&self, py: Python<'py>) -> PyResult<Bound<'py, PyAny>> {
let inner = self.inner.clone();
let cancel_inner = inner.clone();
abortable_future_into_py_with_cancel(
py,
async move {
let mut lease = StreamLease::take(inner)?;
loop {
match lease.stream_mut()?.next().await {
Some(Ok(Some(miner))) => {
let miner = Miner::from(miner);
lease.store_ready()?;
return Ok(miner);
}
Some(Ok(None)) => continue,
Some(Err(error)) => {
lease.close()?;
return Err(PyRuntimeError::new_err(error.to_string()));
}
None => {
lease.close()?;
return Err(PyStopAsyncIteration::new_err("stream complete"));
}
}
}
},
Some(close_stream_on_cancel(cancel_inner)),
)
}
}
#[pyclass]
struct PyListenerIpStream {
inner: Arc<Mutex<StreamState<ListenerIpStream>>>,
}
impl PyListenerIpStream {
fn new(inner: ListenerIpStream) -> Self {
Self {
inner: Arc::new(Mutex::new(StreamState::Ready(inner))),
}
}
}
#[pymethods]
impl PyListenerIpStream {
pub fn __aiter__(slf: PyRef<Self>) -> PyRef<Self> {
slf
}
pub fn __anext__<'py>(&self, py: Python<'py>) -> PyResult<Bound<'py, PyAny>> {
let inner = self.inner.clone();
let cancel_inner = inner.clone();
abortable_future_into_py_with_cancel(
py,
async move {
let mut lease = StreamLease::take(inner)?;
loop {
match lease.stream_mut()?.next().await {
Some(Ok(Some(ip))) => {
lease.store_ready()?;
return Ok(ip);
}
Some(Ok(None)) => continue,
Some(Err(error)) => {
lease.close()?;
return Err(PyRuntimeError::new_err(error.to_string()));
}
None => {
lease.close()?;
return Err(PyStopAsyncIteration::new_err("stream complete"));
}
}
}
},
Some(close_stream_on_cancel(cancel_inner)),
)
}
}
/// Python listener for miner broadcast packets.
#[pyclass(module = "asic_rs")]
pub(crate) struct MinerListener {
inner: Arc<MinerListenerBase>,
}
#[pymethods]
impl MinerListener {
/// Create a listener for supported miner broadcast packets.
#[new]
pub fn new() -> Self {
Self {
inner: Arc::new(MinerListenerBase::new()),
}
}
/// Return an async iterator over miners as broadcast packets arrive.
pub fn listen<'py>(&self, py: Python<'py>) -> PyResult<PyAsyncIterator<Miner>> {
Bound::new(
py,
PyListenerMinerStream::new(miner_stream(self.inner.clone())),
)
.map(Bound::into_any)
.map(PyAsyncIterator::new)
}
/// Return an async iterator over miner IP addresses as broadcast packets arrive.
pub fn listen_ip_only<'py>(&self, py: Python<'py>) -> PyResult<PyAsyncIterator<IpAddr>> {
Bound::new(py, PyListenerIpStream::new(ip_stream(self.inner.clone())))
.map(Bound::into_any)
.map(PyAsyncIterator::new)
}
}
+896
View File
@@ -0,0 +1,896 @@
use std::{net::IpAddr, path::PathBuf, sync::Arc, time::Duration};
use super::typing::{PyAwaitable, future_into_py};
use asic_rs_core::data::collector::DataField;
use asic_rs_core::{
config::{
fan::FanConfig, pools::PoolGroupConfig as PoolGroup, preset::PresetInfo,
scaling::ScalingConfig, temperature::TemperatureConfig, timezone::TimezoneConfig,
tuning::TuningConfig,
},
data::{
board::BoardData,
device::{HashAlgorithm, MinerHardware},
fan::FanData,
firmware::{FirmwareImage, FirmwareStats},
hashrate::HashRate,
message::MinerMessage,
miner::{MinerData, TuningTarget},
operating_state::OperatingState,
pool::PoolGroupData,
},
traits::{auth::MinerAuth, miner::Miner as MinerTrait},
};
use measurements::Power;
use pyo3::{
exceptions::{PyRuntimeError, PyValueError},
prelude::*,
};
use tokio::sync::RwLock;
/// Python handle for one supported ASIC miner.
///
/// A `Miner` is returned by `MinerFactory.get_miner`, `scan`, or scan streams.
/// Data and control methods are awaitable. Capability properties named
/// `supports_*` describe whether the current miner/firmware supports a control
/// or config operation before it is called.
#[pyclass(module = "asic_rs")]
pub(crate) struct Miner {
inner: Arc<RwLock<Box<dyn MinerTrait>>>,
}
impl Miner {
pub fn new(inner: Box<dyn MinerTrait>) -> Self {
Self {
inner: Arc::new(RwLock::new(inner)),
}
}
fn with_miner<T>(&self, py: Python<'_>, f: impl FnOnce(&dyn MinerTrait) -> T + Send) -> T
where
T: Send,
{
py.detach(|| {
let inner = self.inner.blocking_read();
f(inner.as_ref())
})
}
fn apply_auth(&mut self, auth: MinerAuth) -> PyResult<()> {
Arc::get_mut(&mut self.inner)
.ok_or_else(|| PyRuntimeError::new_err("cannot set auth while miner is in use"))?
.get_mut()
.set_auth(auth);
Ok(())
}
}
impl From<Box<dyn MinerTrait>> for Miner {
fn from(inner: Box<dyn MinerTrait>) -> Self {
Self::new(inner)
}
}
fn parse_optional_duration(value: Option<&Bound<'_, PyAny>>) -> PyResult<Option<Duration>> {
let Some(value) = value else {
return Ok(None);
};
if value.is_none() {
return Ok(None);
}
if let Ok(duration) = value.extract::<Duration>() {
return Ok(Some(duration));
}
if let Ok(seconds) = value.extract::<f64>()
&& seconds.is_finite()
&& seconds >= 0.0
{
return Ok(Some(Duration::from_secs_f64(seconds)));
}
Err(PyValueError::new_err(
"expected datetime.timedelta, non-negative seconds, or None",
))
}
pub(crate) struct FirmwarePath(PathBuf);
impl<'a, 'py> pyo3::FromPyObject<'a, 'py> for FirmwarePath {
type Error = pyo3::PyErr;
const INPUT_TYPE: pyo3::inspect::PyStaticExpr =
pyo3::type_hint_identifier!("_typeshed", "StrOrBytesPath");
fn extract(obj: pyo3::Borrowed<'a, 'py, PyAny>) -> Result<Self, Self::Error> {
obj.extract::<PathBuf>().map(Self)
}
}
#[pymethods]
impl Miner {
fn __repr__(&self, py: Python<'_>) -> String {
self.with_miner(py, |miner| {
let device_info = miner.get_device_info();
format!(
"{} {} ({}): {}",
device_info.make,
device_info.model,
device_info.firmware,
miner.get_ip(),
)
})
}
/// IP address of this miner.
#[getter]
fn ip(&self, py: Python<'_>) -> IpAddr {
self.with_miner(py, |miner| miner.get_ip())
}
/// Miner model name.
#[getter]
fn model(&self, py: Python<'_>) -> String {
self.with_miner(py, |miner| miner.get_device_info().model)
}
/// Miner manufacturer or make.
#[getter]
fn make(&self, py: Python<'_>) -> String {
self.with_miner(py, |miner| miner.get_device_info().make)
}
/// Firmware name or family used by this miner.
#[getter]
fn firmware(&self, py: Python<'_>) -> String {
self.with_miner(py, |miner| miner.get_device_info().firmware)
}
/// Hash algorithm mined by this device.
#[getter]
fn algo(&self, py: Python<'_>) -> HashAlgorithm {
self.with_miner(py, |miner| miner.get_device_info().algo)
}
/// Expected hardware shape for this miner model.
#[getter]
fn hardware(&self, py: Python<'_>) -> MinerHardware {
self.with_miner(py, |miner| miner.get_device_info().hardware)
}
/// Expected number of hashboards, when known.
#[getter]
fn expected_hashboards(&self, py: Python<'_>) -> Option<u8> {
self.with_miner(py, |miner| miner.get_expected_hashboards())
}
/// Expected total number of chips, when known.
#[getter]
fn expected_chips(&self, py: Python<'_>) -> Option<u16> {
self.with_miner(py, |miner| miner.get_expected_chips())
}
/// Expected number of fans, when known.
#[getter]
fn expected_fans(&self, py: Python<'_>) -> Option<u8> {
self.with_miner(py, |miner| miner.get_expected_fans())
}
/// Whether this miner supports changing the fault light state.
#[getter]
fn supports_set_fault_light(&self, py: Python<'_>) -> bool {
self.with_miner(py, |miner| miner.supports_set_fault_light())
}
/// Whether this miner supports setting a power limit.
#[getter]
fn supports_set_power_limit(&self, py: Python<'_>) -> bool {
self.with_miner(py, |miner| miner.supports_set_power_limit())
}
/// Whether this miner supports setting a manual tuning percent.
#[getter]
fn supports_set_tuning_percent(&self, py: Python<'_>) -> bool {
self.with_miner(py, |miner| miner.supports_set_tuning_percent())
}
/// Whether this miner exposes named autotune/overclock presets.
#[getter]
fn supports_presets(&self, py: Python<'_>) -> bool {
self.with_miner(py, |miner| miner.supports_presets())
}
/// Whether this miner supports restart commands.
#[getter]
fn supports_restart(&self, py: Python<'_>) -> bool {
self.with_miner(py, |miner| miner.supports_restart())
}
/// Whether this miner supports pause commands.
#[getter]
fn supports_pause(&self, py: Python<'_>) -> bool {
self.with_miner(py, |miner| miner.supports_pause())
}
/// Whether this miner supports resume commands.
#[getter]
fn supports_resume(&self, py: Python<'_>) -> bool {
self.with_miner(py, |miner| miner.supports_resume())
}
/// Whether this miner supports changing its password.
#[getter]
fn supports_change_password(&self, py: Python<'_>) -> bool {
self.with_miner(py, |miner| miner.supports_change_password())
}
/// Whether this miner supports reading logs.
#[getter]
fn supports_read_logs(&self, py: Python<'_>) -> bool {
self.with_miner(py, |miner| miner.supports_read_logs())
}
/// Whether this miner supports factory reset.
#[getter]
fn supports_factory_reset(&self, py: Python<'_>) -> bool {
self.with_miner(py, |miner| miner.supports_factory_reset())
}
/// Whether this miner supports reading and writing pool configuration.
#[getter]
fn supports_pools_config(&self, py: Python<'_>) -> bool {
self.with_miner(py, |miner| miner.supports_pools_config())
}
/// Whether this miner supports firmware upgrades through the API.
#[getter]
fn supports_upgrade_firmware(&self, py: Python<'_>) -> bool {
self.with_miner(py, |miner| miner.supports_upgrade_firmware())
}
/// Whether this miner can validate and resolve firmware without uploading it.
#[getter]
fn supports_prepare_firmware(&self, py: Python<'_>) -> bool {
self.with_miner(py, |miner| miner.supports_prepare_firmware())
}
/// Whether this miner supports checking for an available firmware update.
#[getter]
fn supports_check_firmware_update(&self, py: Python<'_>) -> bool {
self.with_miner(py, |miner| miner.supports_check_firmware_update())
}
/// Whether this miner supports reading and writing timezone configuration.
#[getter]
fn supports_timezone_config(&self, py: Python<'_>) -> bool {
self.with_miner(py, |miner| miner.supports_timezone_config())
}
/// Whether this miner supports scaling configuration.
#[getter]
fn supports_scaling_config(&self, py: Python<'_>) -> bool {
self.with_miner(py, |miner| miner.supports_scaling_config())
}
/// Whether this miner reports configured thermal limits.
#[getter]
fn supports_temperature_config(&self, py: Python<'_>) -> bool {
self.with_miner(py, |miner| miner.supports_temperature_config())
}
/// Whether this miner supports tuning configuration.
#[getter]
fn supports_tuning_config(&self, py: Python<'_>) -> bool {
self.with_miner(py, |miner| miner.supports_tuning_config())
}
/// Whether this miner supports fan configuration.
#[getter]
fn supports_fan_config(&self, py: Python<'_>) -> bool {
self.with_miner(py, |miner| miner.supports_fan_config())
}
/// Set username/password credentials used by subsequent operations on this
/// miner.
///
/// Call this before starting concurrent operations. It raises `RuntimeError`
/// if the miner handle is already shared by an active async operation.
pub fn set_auth(&mut self, username: String, password: String) -> PyResult<()> {
self.apply_auth(MinerAuth::new(username, password))
}
/// Set a pre-issued bearer token for firmwares that accept one (e.g. VNish);
/// backends that support it use the token instead of logging in with a
/// password.
///
/// Call this before starting concurrent operations. It raises `RuntimeError`
/// if the miner handle is already shared by an active async operation.
pub fn set_token(&mut self, token: String) -> PyResult<()> {
self.apply_auth(MinerAuth::from_token(token))
}
// Data functions
/// Await a full telemetry snapshot.
///
/// Pass `exclude=[DataField.SomeField]` to skip expensive or unnecessary
/// fields during collection.
#[pyo3(signature = (exclude: "list[DataField] | None" = None))]
pub fn get_data<'a>(
&self,
py: Python<'a>,
exclude: Option<Vec<DataField>>,
) -> PyResult<PyAwaitable<MinerData>> {
let inner = Arc::clone(&self.inner);
future_into_py(py, async move {
let inner = inner.read().await;
match exclude {
None => Ok(inner.get_data().await),
Some(excl) => Ok(inner.get_data_filtered(excl).await),
}
})
}
/// Check for an available firmware update (on-demand; queries the vendor's
/// release server). Returns `None` if unsupported or the check fails.
pub fn check_firmware_update<'a>(
&self,
py: Python<'a>,
) -> PyResult<PyAwaitable<Option<FirmwareStats>>> {
let inner = Arc::clone(&self.inner);
future_into_py(py, async move {
let inner = inner.read().await;
Ok(inner.check_firmware_update().await.ok())
})
}
/// Await the miner MAC address, if exposed by the firmware.
pub fn get_mac<'a>(&self, py: Python<'a>) -> PyResult<PyAwaitable<Option<String>>> {
let inner = Arc::clone(&self.inner);
future_into_py(py, async move {
let inner = inner.read().await;
let data = inner.get_mac().await;
Ok(data.map(|m| m.to_string()))
})
}
/// Await the miner serial number, if exposed by the firmware.
pub fn get_serial_number<'a>(&self, py: Python<'a>) -> PyResult<PyAwaitable<Option<String>>> {
let inner = Arc::clone(&self.inner);
future_into_py(py, async move {
let inner = inner.read().await;
let data = inner.get_serial_number().await;
Ok(data)
})
}
/// Await the network hostname, if exposed by the firmware.
pub fn get_hostname<'a>(&self, py: Python<'a>) -> PyResult<PyAwaitable<Option<String>>> {
let inner = Arc::clone(&self.inner);
future_into_py(py, async move {
let inner = inner.read().await;
let data = inner.get_hostname().await;
Ok(data)
})
}
/// Await the miner API version, if exposed by the firmware.
pub fn get_api_version<'a>(&self, py: Python<'a>) -> PyResult<PyAwaitable<Option<String>>> {
let inner = Arc::clone(&self.inner);
future_into_py(py, async move {
let inner = inner.read().await;
let data = inner.get_api_version().await;
Ok(data)
})
}
/// Await the firmware version string, if exposed by the firmware.
pub fn get_firmware_version<'a>(
&self,
py: Python<'a>,
) -> PyResult<PyAwaitable<Option<String>>> {
let inner = Arc::clone(&self.inner);
future_into_py(py, async move {
let inner = inner.read().await;
let data = inner.get_firmware_version().await;
Ok(data)
})
}
/// Await the control board version or name, if exposed by the firmware.
pub fn get_control_board_version<'a>(
&self,
py: Python<'a>,
) -> PyResult<PyAwaitable<Option<String>>> {
let inner = Arc::clone(&self.inner);
future_into_py(py, async move {
let inner = inner.read().await;
let data = inner
.get_control_board_version()
.await
.map(|cb| cb.to_string());
Ok(data)
})
}
/// Await per-hashboard data including chip details where available.
pub fn get_hashboards<'a>(&self, py: Python<'a>) -> PyResult<PyAwaitable<Vec<BoardData>>> {
let inner = Arc::clone(&self.inner);
future_into_py(py, async move {
let inner = inner.read().await;
Ok(inner.get_hashboards().await)
})
}
/// Await per-hashboard data without collecting per-chip details.
pub fn get_hashboards_no_chips<'a>(
&self,
py: Python<'a>,
) -> PyResult<PyAwaitable<Vec<BoardData>>> {
let inner = Arc::clone(&self.inner);
future_into_py(py, async move {
let inner = inner.read().await;
Ok(inner.get_hashboards_no_chips().await)
})
}
/// Await the current hashrate, if exposed by the firmware.
pub fn get_hashrate<'a>(&self, py: Python<'a>) -> PyResult<PyAwaitable<Option<HashRate>>> {
let inner = Arc::clone(&self.inner);
future_into_py(py, async move {
let inner = inner.read().await;
let data = inner.get_hashrate().await;
Ok(data)
})
}
/// Await the expected or nominal hashrate, if known.
pub fn get_expected_hashrate<'a>(
&self,
py: Python<'a>,
) -> PyResult<PyAwaitable<Option<HashRate>>> {
let inner = Arc::clone(&self.inner);
future_into_py(py, async move {
let inner = inner.read().await;
let data = inner.get_expected_hashrate().await;
Ok(data)
})
}
/// Await current fan readings.
pub fn get_fans<'a>(&self, py: Python<'a>) -> PyResult<PyAwaitable<Vec<FanData>>> {
let inner = Arc::clone(&self.inner);
future_into_py(py, async move {
let inner = inner.read().await;
Ok(inner.get_fans().await)
})
}
/// Await power-supply fan readings, if exposed separately.
pub fn get_psu_fans<'a>(&self, py: Python<'a>) -> PyResult<PyAwaitable<Vec<FanData>>> {
let inner = Arc::clone(&self.inner);
future_into_py(py, async move {
let inner = inner.read().await;
Ok(inner.get_psu_fans().await)
})
}
/// Await fluid or ambient temperature in Celsius, if available.
pub fn get_fluid_temperature<'a>(&self, py: Python<'a>) -> PyResult<PyAwaitable<Option<f64>>> {
let inner = Arc::clone(&self.inner);
future_into_py(py, async move {
let inner = inner.read().await;
let data = inner.get_fluid_temperature().await;
Ok(data.map(|t| t.as_celsius()))
})
}
/// Await coolant exhaust (outlet fluid) temperature in Celsius, if available.
pub fn get_outlet_fluid_temperature<'a>(
&self,
py: Python<'a>,
) -> PyResult<PyAwaitable<Option<f64>>> {
let inner = Arc::clone(&self.inner);
future_into_py(py, async move {
let inner = inner.read().await;
let data = inner.get_outlet_fluid_temperature().await;
Ok(data.map(|t| t.as_celsius()))
})
}
/// Await current power draw in watts, if available.
pub fn get_wattage<'a>(&self, py: Python<'a>) -> PyResult<PyAwaitable<Option<f64>>> {
let inner = Arc::clone(&self.inner);
future_into_py(py, async move {
let inner = inner.read().await;
let data = inner.get_wattage().await;
Ok(data.map(|w| w.as_watts()))
})
}
/// Await all-time best share difficulty, if the firmware reports it.
pub fn get_best_share<'a>(&self, py: Python<'a>) -> PyResult<PyAwaitable<Option<f64>>> {
let inner = Arc::clone(&self.inner);
future_into_py(py, async move {
let inner = inner.read().await;
Ok(inner.get_best_share().await)
})
}
/// Await session best share difficulty (since boot), if the firmware reports it.
pub fn get_session_best_share<'a>(&self, py: Python<'a>) -> PyResult<PyAwaitable<Option<f64>>> {
let inner = Arc::clone(&self.inner);
future_into_py(py, async move {
let inner = inner.read().await;
Ok(inner.get_session_best_share().await)
})
}
/// Await the current manual throttle percent (100 = unthrottled), if exposed.
pub fn get_tuning_percent<'a>(&self, py: Python<'a>) -> PyResult<PyAwaitable<Option<u8>>> {
let inner = Arc::clone(&self.inner);
future_into_py(py, async move {
let inner = inner.read().await;
Ok(inner.get_tuning_percent().await)
})
}
/// Await the active tuning target, if exposed by the firmware.
pub fn get_tuning_target<'a>(
&self,
py: Python<'a>,
) -> PyResult<PyAwaitable<Option<TuningTarget>>> {
let inner = Arc::clone(&self.inner);
future_into_py(py, async move {
let inner = inner.read().await;
Ok(inner.get_tuning_target().await)
})
}
/// Await the current fault light state, if available.
pub fn get_light_flashing<'a>(&self, py: Python<'a>) -> PyResult<PyAwaitable<Option<bool>>> {
let inner = Arc::clone(&self.inner);
future_into_py(py, async move {
let inner = inner.read().await;
let data = inner.get_light_flashing().await;
Ok(data)
})
}
/// Await current miner messages and errors.
pub fn get_messages<'a>(&self, py: Python<'a>) -> PyResult<PyAwaitable<Vec<MinerMessage>>> {
let inner = Arc::clone(&self.inner);
future_into_py(py, async move {
let inner = inner.read().await;
Ok(inner.get_messages().await)
})
}
/// Await system uptime as `datetime.timedelta`, if available.
pub fn get_uptime<'a>(&self, py: Python<'a>) -> PyResult<PyAwaitable<Option<Duration>>> {
let inner = Arc::clone(&self.inner);
future_into_py(py, async move {
let inner = inner.read().await;
let data = inner.get_uptime().await;
Ok(data)
})
}
/// Await whether the miner is currently mining.
pub fn get_is_mining<'a>(&self, py: Python<'a>) -> PyResult<PyAwaitable<bool>> {
let inner = Arc::clone(&self.inner);
future_into_py(py, async move {
let inner = inner.read().await;
let data = inner.get_is_mining().await;
Ok(data)
})
}
/// Await the detailed operating state explicitly reported by firmware.
pub fn get_operating_state<'a>(
&self,
py: Python<'a>,
) -> PyResult<PyAwaitable<Option<OperatingState>>> {
let inner = Arc::clone(&self.inner);
future_into_py(py, async move {
let inner = inner.read().await;
Ok(inner.get_operating_state().await)
})
}
/// Await the current mining pool status.
pub fn get_pools<'a>(&self, py: Python<'a>) -> PyResult<PyAwaitable<Vec<PoolGroupData>>> {
let inner = Arc::clone(&self.inner);
future_into_py(py, async move {
let inner = inner.read().await;
Ok(inner.get_pools().await)
})
}
/// Await configured pool groups, or `None` when unsupported/unavailable.
pub fn get_pools_config<'a>(
&self,
py: Python<'a>,
) -> PyResult<PyAwaitable<Option<Vec<PoolGroup>>>> {
let inner = Arc::clone(&self.inner);
future_into_py(py, async move {
let inner = inner.read().await;
Ok(inner.get_pools_config().await.ok())
})
}
/// Await scaling configuration, or `None` when unsupported/unavailable.
pub fn get_scaling_config<'a>(
&self,
py: Python<'a>,
) -> PyResult<PyAwaitable<Option<ScalingConfig>>> {
let inner = Arc::clone(&self.inner);
future_into_py(py, async move {
let inner = inner.read().await;
Ok(inner.get_scaling_config().await.ok())
})
}
/// Await the configured thermal limits, or `None` when unsupported/unavailable.
pub fn get_temperature_config<'a>(
&self,
py: Python<'a>,
) -> PyResult<PyAwaitable<Option<TemperatureConfig>>> {
let inner = Arc::clone(&self.inner);
future_into_py(py, async move {
let inner = inner.read().await;
Ok(inner.get_temperature_config().await.ok())
})
}
/// Await tuning configuration, or `None` when unsupported/unavailable.
pub fn get_tuning_config<'a>(
&self,
py: Python<'a>,
) -> PyResult<PyAwaitable<Option<TuningConfig>>> {
let inner = Arc::clone(&self.inner);
future_into_py(py, async move {
let inner = inner.read().await;
Ok(inner.get_tuning_config().await.ok())
})
}
/// Await fan configuration, or `None` when unsupported/unavailable.
pub fn get_fan_config<'a>(&self, py: Python<'a>) -> PyResult<PyAwaitable<Option<FanConfig>>> {
let inner = Arc::clone(&self.inner);
future_into_py(py, async move {
let inner = inner.read().await;
Ok(inner.get_fan_config().await.ok())
})
}
// Control functions
/// Set the fault light state.
///
pub fn set_fault_light<'a>(&self, py: Python<'a>, fault: bool) -> PyResult<PyAwaitable<bool>> {
let inner = Arc::clone(&self.inner);
future_into_py(py, async move {
let inner = inner.read().await;
inner
.set_fault_light(fault)
.await
.map_err(|e| PyRuntimeError::new_err(e.to_string()))
})
}
/// Restart the miner.
///
pub fn restart<'a>(&self, py: Python<'a>) -> PyResult<PyAwaitable<bool>> {
let inner = Arc::clone(&self.inner);
future_into_py(py, async move {
let inner = inner.read().await;
inner
.restart()
.await
.map_err(|e| PyRuntimeError::new_err(e.to_string()))
})
}
/// Pause mining immediately or after a delay.
///
/// `at_time` may be `datetime.timedelta`, non-negative seconds, or `None`.
#[pyo3(signature = (at_time: "timedelta | float | int | None" = None))]
pub fn pause<'a>(
&self,
py: Python<'a>,
at_time: Option<&Bound<'_, PyAny>>,
) -> PyResult<PyAwaitable<bool>> {
let inner = Arc::clone(&self.inner);
let at_time = parse_optional_duration(at_time)?;
future_into_py(py, async move {
let inner = inner.read().await;
inner
.pause(at_time)
.await
.map_err(|e| PyRuntimeError::new_err(e.to_string()))
})
}
/// Resume mining immediately or after a delay.
///
/// `at_time` may be `datetime.timedelta`, non-negative seconds, or `None`.
#[pyo3(signature = (at_time: "timedelta | float | int | None" = None))]
pub fn resume<'a>(
&self,
py: Python<'a>,
at_time: Option<&Bound<'_, PyAny>>,
) -> PyResult<PyAwaitable<bool>> {
let inner = Arc::clone(&self.inner);
let at_time = parse_optional_duration(at_time)?;
future_into_py(py, async move {
let inner = inner.read().await;
inner
.resume(at_time)
.await
.map_err(|e| PyRuntimeError::new_err(e.to_string()))
})
}
/// Re-run this miner backend's discovery checks against the same IP.
///
/// Returns `False` when the device is offline, no longer responds as the
/// same firmware/model, or would no longer be valid for this backend.
pub fn revalidate<'a>(&self, py: Python<'a>) -> PyResult<PyAwaitable<Option<bool>>> {
let inner = Arc::clone(&self.inner);
future_into_py(py, async move {
let inner = inner.read().await;
let data = inner.revalidate().await;
Ok(data.ok())
})
}
/// Factory reset the miner.
///
pub fn factory_reset<'a>(&self, py: Python<'a>) -> PyResult<PyAwaitable<bool>> {
let inner = Arc::clone(&self.inner);
future_into_py(py, async move {
let inner = inner.read().await;
inner
.factory_reset()
.await
.map_err(|e| PyRuntimeError::new_err(e.to_string()))
})
}
/// Read miner logs, if supported.
pub fn read_logs<'a>(&self, py: Python<'a>) -> PyResult<PyAwaitable<Option<String>>> {
let inner = Arc::clone(&self.inner);
future_into_py(py, async move {
let inner = inner.read().await;
let data = inner.read_logs().await;
Ok(data.ok())
})
}
/// Change the miner password.
///
/// This may require existing credentials to have been set with `set_auth`.
pub fn change_password<'a>(
&self,
py: Python<'a>,
password: &str,
) -> PyResult<PyAwaitable<bool>> {
let password = password.to_string();
let inner = Arc::clone(&self.inner);
future_into_py(py, async move {
let mut inner = inner.write().await;
inner
.change_password(&password)
.await
.map_err(|e| PyRuntimeError::new_err(e.to_string()))
})
}
/// Set the power limit in watts.
pub fn set_power_limit<'a>(&self, py: Python<'a>, watts: f64) -> PyResult<PyAwaitable<bool>> {
let inner = Arc::clone(&self.inner);
future_into_py(py, async move {
let inner = inner.read().await;
inner
.set_power_limit(Power::from_watts(watts))
.await
.map_err(|e| PyRuntimeError::new_err(e.to_string()))
})
}
/// Set a manual tuning percent of full power (100 = unthrottled).
pub fn set_tuning_percent<'a>(
&self,
py: Python<'a>,
percent: u8,
) -> PyResult<PyAwaitable<bool>> {
let inner = Arc::clone(&self.inner);
future_into_py(py, async move {
let inner = inner.read().await;
inner
.set_tuning_percent(percent)
.await
.map_err(|e| PyRuntimeError::new_err(e.to_string()))
})
}
/// Await the firmware's available autotune/overclock presets.
///
/// Select one with `set_tuning_config(TuningConfig.preset(name))`; the active
/// preset is reported by `get_tuning_target()` as a `TuningTarget.preset`.
pub fn get_presets<'a>(&self, py: Python<'a>) -> PyResult<PyAwaitable<Vec<PresetInfo>>> {
let inner = Arc::clone(&self.inner);
future_into_py(py, async move {
let inner = inner.read().await;
Ok(inner.get_presets().await)
})
}
/// Await timezone configuration, or `None` when unsupported/unavailable.
pub fn get_timezone_config<'a>(
&self,
py: Python<'a>,
) -> PyResult<PyAwaitable<Option<TimezoneConfig>>> {
let inner = Arc::clone(&self.inner);
future_into_py(py, async move {
let inner = inner.read().await;
Ok(inner.get_timezone_config().await.ok())
})
}
/// Set timezone configuration.
///
/// `config.timezone` is an IANA zone (a `zoneinfo.ZoneInfo`, or its name
/// when constructing the config: `"Europe/Vienna"`, `"Etc/GMT-2"`) on every
/// firmware; the backend converts to its own dialect. Raises when the
/// firmware cannot represent the zone (VNish only takes fixed-offset
/// `Etc/GMT*` zones; the error names the equivalent).
#[pyo3(signature = (config: "TimezoneConfig"))]
pub fn set_timezone_config<'a>(
&self,
py: Python<'a>,
config: TimezoneConfig,
) -> PyResult<PyAwaitable<bool>> {
let inner = Arc::clone(&self.inner);
future_into_py(py, async move {
let inner = inner.read().await;
inner
.set_timezone_config(config)
.await
.map_err(|e| PyRuntimeError::new_err(e.to_string()))
})
}
/// Replace the configured mining pool groups.
#[pyo3(signature = (groups: "list[PoolGroup]"))]
pub fn set_pools_config<'a>(
&self,
py: Python<'a>,
groups: Vec<PoolGroup>,
) -> PyResult<PyAwaitable<bool>> {
let inner = Arc::clone(&self.inner);
future_into_py(py, async move {
let inner = inner.read().await;
inner
.set_pools_config(groups)
.await
.map_err(|e| PyRuntimeError::new_err(e.to_string()))
})
}
/// Set scaling configuration.
#[pyo3(signature = (config: "ScalingConfig"))]
pub fn set_scaling_config<'a>(
&self,
py: Python<'a>,
config: ScalingConfig,
) -> PyResult<PyAwaitable<bool>> {
let inner = Arc::clone(&self.inner);
future_into_py(py, async move {
let inner = inner.read().await;
inner
.set_scaling_config(config)
.await
.map_err(|e| PyRuntimeError::new_err(e.to_string()))
})
}
/// Set tuning configuration, optionally with companion scaling settings.
#[pyo3(signature = (config: "TuningConfig", scaling_config: "ScalingConfig | None" = None))]
pub fn set_tuning_config<'a>(
&self,
py: Python<'a>,
config: TuningConfig,
scaling_config: Option<ScalingConfig>,
) -> PyResult<PyAwaitable<bool>> {
let inner = Arc::clone(&self.inner);
future_into_py(py, async move {
let inner = inner.read().await;
inner
.set_tuning_config(config, scaling_config)
.await
.map_err(|e| PyRuntimeError::new_err(e.to_string()))
})
}
/// Set fan configuration.
#[pyo3(signature = (config: "FanConfig"))]
pub fn set_fan_config<'a>(
&self,
py: Python<'a>,
config: FanConfig,
) -> PyResult<PyAwaitable<bool>> {
let inner = Arc::clone(&self.inner);
future_into_py(py, async move {
let inner = inner.read().await;
inner
.set_fan_config(config)
.await
.map_err(|e| PyRuntimeError::new_err(e.to_string()))
})
}
/// Validate and resolve a local firmware image without uploading it.
pub fn prepare_firmware<'a>(
&self,
py: Python<'a>,
path: FirmwarePath,
) -> PyResult<PyAwaitable<FirmwareImage>> {
let inner = Arc::clone(&self.inner);
future_into_py(py, async move {
let image = FirmwareImage::from_file_async(&path.0)
.await
.map_err(|e| PyValueError::new_err(e.to_string()))?;
let inner = inner.read().await;
inner
.prepare_firmware(image)
.await
.map_err(|e| PyRuntimeError::new_err(e.to_string()))
})
}
/// Upload and apply a firmware image from a local path.
pub fn upgrade_firmware<'a>(
&self,
py: Python<'a>,
path: FirmwarePath,
) -> PyResult<PyAwaitable<bool>> {
let inner = Arc::clone(&self.inner);
future_into_py(py, async move {
let image = FirmwareImage::from_file_async(&path.0)
.await
.map_err(|e| PyValueError::new_err(e.to_string()))?;
let inner = inner.read().await;
inner
.upgrade_firmware(image)
.await
.map_err(|e| PyRuntimeError::new_err(e.to_string()))
})
}
}
+58
View File
@@ -0,0 +1,58 @@
use pyo3::prelude::*;
mod factory;
mod listener;
mod miner;
mod typing;
#[pymodule(module = "pyasic_rs.asic_rs")]
mod asic_rs {
use pyo3::prelude::*;
#[pymodule_init]
fn init(_m: &Bound<'_, PyModule>) -> PyResult<()> {
pyo3_log::init();
Ok(())
}
#[pymodule_export]
use asic_rs_core::data::collector::DataField;
#[pymodule_export]
use asic_rs_core::data::device::HashAlgorithm;
#[pymodule_export]
use asic_rs_core::data::hashrate::{HashRate, HashRateUnit};
#[pymodule_export]
use asic_rs_core::data::miner::MiningMode;
#[pymodule_export]
use super::factory::MinerFactory;
#[pymodule_export]
use super::listener::MinerListener;
#[pymodule_export]
use super::miner::Miner;
#[pymodule_export]
use asic_rs_core::config::{
fan::{FanConfig, FanMode},
pools::{PoolConfig as Pool, PoolGroupConfig as PoolGroup},
preset::PresetInfo,
scaling::ScalingConfig,
temperature::TemperatureConfig,
timezone::TimezoneConfig,
tuning::TuningConfig,
};
#[pymodule_export]
use asic_rs_core::data::{
board::{BoardData, ChipData, MinerControlBoard},
capabilities::{
HashRateTuningCapabilities, PowerTuningCapabilities, PresetTuningCapabilities,
TuningCapabilities,
},
device::{DeviceInfo, MinerHardware},
fan::FanData,
firmware::{FirmwareImage, FirmwareStats, PyFirmwareUpdate as FirmwareUpdate},
message::{MessageSeverity, MinerComponent, MinerMessage},
miner::{MinerData, PyTuningTarget as TuningTarget},
operating_state::OperatingState,
pool::{PoolData, PoolGroupData, PoolScheme, PoolURL},
};
}
+189
View File
@@ -0,0 +1,189 @@
use std::{any::Any, future::Future, marker::PhantomData, panic::AssertUnwindSafe};
use futures::{
FutureExt,
future::{AbortHandle, Abortable},
};
use pyo3::{
IntoPyObject, PyAny, PyErr, PyResult, Python, exceptions::PyRuntimeError, prelude::*,
type_hint_identifier, type_hint_subscript,
};
use pyo3_async_runtimes::tokio::future_into_py as raw_future_into_py;
pub(crate) type CancelAction = Box<dyn FnOnce() + Send + Sync + 'static>;
pub(crate) struct PyAwaitable<T> {
inner: Py<PyAny>,
_ty: PhantomData<T>,
}
impl<T> PyAwaitable<T> {
pub(crate) fn new(inner: Bound<'_, PyAny>) -> Self {
Self {
inner: inner.unbind(),
_ty: PhantomData,
}
}
}
impl<'py, T> IntoPyObject<'py> for PyAwaitable<T>
where
T: IntoPyObject<'py>,
{
type Target = PyAny;
type Output = Bound<'py, PyAny>;
type Error = PyErr;
const OUTPUT_TYPE: pyo3::inspect::PyStaticExpr = type_hint_subscript!(
type_hint_identifier!("collections.abc", "Awaitable"),
T::OUTPUT_TYPE
);
fn into_pyobject(self, py: Python<'py>) -> Result<Self::Output, Self::Error> {
Ok(self.inner.into_bound(py))
}
}
pub(crate) struct PyAsyncIterator<T> {
inner: Py<PyAny>,
_ty: PhantomData<T>,
}
impl<T> PyAsyncIterator<T> {
pub(crate) fn new(inner: Bound<'_, PyAny>) -> Self {
Self {
inner: inner.unbind(),
_ty: PhantomData,
}
}
}
impl<'py, T> IntoPyObject<'py> for PyAsyncIterator<T>
where
T: IntoPyObject<'py>,
{
type Target = PyAny;
type Output = Bound<'py, PyAny>;
type Error = PyErr;
const OUTPUT_TYPE: pyo3::inspect::PyStaticExpr = type_hint_subscript!(
type_hint_identifier!("collections.abc", "AsyncIterator"),
T::OUTPUT_TYPE
);
fn into_pyobject(self, py: Python<'py>) -> Result<Self::Output, Self::Error> {
Ok(self.inner.into_bound(py))
}
}
pub(crate) fn future_into_py<'py, T, F>(py: Python<'py>, future: F) -> PyResult<PyAwaitable<T>>
where
T: for<'a> IntoPyObject<'a> + Send + 'static,
F: Future<Output = PyResult<T>> + Send + 'static,
{
abortable_future_into_py(py, future).map(PyAwaitable::new)
}
pub(crate) fn abortable_future_into_py<'py, T, F>(
py: Python<'py>,
future: F,
) -> PyResult<Bound<'py, PyAny>>
where
T: for<'a> IntoPyObject<'a> + Send + 'static,
F: Future<Output = PyResult<T>> + Send + 'static,
{
abortable_future_into_py_with_cancel(py, future, None)
}
pub(crate) fn abortable_future_into_py_with_cancel<'py, T, F>(
py: Python<'py>,
future: F,
cancel_action: Option<CancelAction>,
) -> PyResult<Bound<'py, PyAny>>
where
T: for<'a> IntoPyObject<'a> + Send + 'static,
F: Future<Output = PyResult<T>> + Send + 'static,
{
let (abort_handle, abort_registration) = AbortHandle::new_pair();
let abortable = Abortable::new(
async move {
match AssertUnwindSafe(future).catch_unwind().await {
Ok(result) => result,
Err(panic) => Err(PyRuntimeError::new_err(format!(
"rust future panicked: {}",
panic_message(&*panic),
))),
}
},
abort_registration,
);
let awaitable = raw_future_into_py(py, async move {
abortable.await.map_err(|_| {
PyRuntimeError::new_err("rust future cancelled before returning a result")
})?
})?;
awaitable.call_method1(
pyo3::intern!(py, "add_done_callback"),
(Py::new(
py,
RustFutureCancellationGuard {
abort_handle: Some(abort_handle),
cancel_action,
},
)?,),
)?;
Ok(awaitable)
}
fn panic_message(panic: &(dyn Any + Send)) -> &str {
if let Some(message) = panic.downcast_ref::<&str>() {
message
} else if let Some(message) = panic.downcast_ref::<String>() {
message.as_str()
} else {
"unknown error"
}
}
#[pyclass]
struct RustFutureCancellationGuard {
abort_handle: Option<AbortHandle>,
cancel_action: Option<CancelAction>,
}
impl RustFutureCancellationGuard {
fn cancel(&mut self) {
if let Some(abort_handle) = self.abort_handle.take() {
abort_handle.abort();
}
if let Some(cancel_action) = self.cancel_action.take() {
cancel_action();
}
}
}
impl Drop for RustFutureCancellationGuard {
fn drop(&mut self) {
// If callback registration or Python future ownership fails, do not let
// the wrapped Rust future continue without an owner.
self.cancel();
}
}
#[pymethods]
impl RustFutureCancellationGuard {
fn __call__(&mut self, fut: &Bound<PyAny>) -> PyResult<()> {
let cancelled = fut
.call_method0(pyo3::intern!(fut.py(), "cancelled"))?
.extract()?;
if cancelled {
self.cancel();
} else {
self.abort_handle.take();
self.cancel_action.take();
}
Ok(())
}
}