oc2_hlapi_v2 0.2.0

A client for the new version of OpenComputers II's HLAPI
Documentation
//! The fluid handler device and its associated types
//!
//! [OC2 Docs](https://fnuecke.github.io/oc2/manual/en_us/device/fluid_handler.html)

use std::convert::Infallible;

use thiserror::Error;
use uuid::Uuid;

use crate::{
    client::{DeviceBase, HlapiClient, HlapiClientError},
    devices::TankContentInfo,
};

#[derive(Debug, Clone)]
/// A fluid handler device
pub struct FluidHandler {
    client: HlapiClient,
    uuid: Uuid,
    tank_count: u32,
}

/// The possible errors for device functions
#[non_exhaustive]
#[derive(Error, Debug)]
pub enum FluidHandlerError {
    #[error("HLAPI client error: {0}")]
    /// HLAPI client error
    HlapiClientError(#[from] HlapiClientError),
    #[error("Tank index out of range")]
    /// Tank index out of range
    TankIndexOutOfRange,
}

impl FluidHandler {
    /// Gets the contents of the specified tank. An empty tank returns [`None`]. Tanks are
    /// 0-indexed.
    pub fn get_fluid_in_tank(
        &self,
        tank: u32,
    ) -> Result<Option<TankContentInfo>, FluidHandlerError> {
        if tank >= self.tank_count {
            return Err(FluidHandlerError::TankIndexOutOfRange);
        }
        Ok(self.call("getFluidInTank", &[&tank as _], &[])?.0)
    }

    /// Gets the capacity of the specified tank, in millibuckets. Tanks are 0-indexed.
    pub fn get_fluid_tank_capacity(&self, tank: u32) -> Result<u32, FluidHandlerError> {
        if tank >= self.tank_count {
            return Err(FluidHandlerError::TankIndexOutOfRange);
        }
        Ok(self.call("getFluidTankCapacity", &[&tank as _], &[])?.0)
    }

    /// Gets how many tanks the container has
    #[must_use]
    pub fn get_fluid_tank_count(&self) -> u32 {
        self.tank_count
    }
}

impl DeviceBase for FluidHandler {
    const TYPE: &'static str = "fluid_handler";

    type Event = Infallible;

    fn new(client: HlapiClient, uuid: Uuid) -> Result<Self, HlapiClientError> {
        let mut slf = Self {
            client,
            uuid,
            tank_count: 0,
        };
        slf.tank_count = slf.call("getFluidTankCount", &[], &[])?.0;
        Ok(slf)
    }

    fn uuid_base(&self) -> Uuid {
        self.uuid
    }

    fn client(&self) -> &HlapiClient {
        &self.client
    }
}