oc2_hlapi_v2 0.2.0

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

use std::{convert::Infallible, num::NonZeroU32};

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

use crate::{
    client::{DeviceBase, HlapiClient, HlapiClientError},
    devices::robot::RobotSide,
};
#[derive(Debug, Clone)]
/// The device for the block operations module
pub struct BlockOperations {
    client: HlapiClient,
    uuid: Uuid,
}

/// The possible errors for device functions
#[non_exhaustive]
#[derive(Error, Debug)]
pub enum BlockOperationsError {
    #[error("HLAPI client error: {0}")]
    /// HLAPI client error
    HlapiClientError(#[from] HlapiClientError),
    #[error("Operation failed")]
    /// Operation failed
    OperationFailed,
}

impl BlockOperations {
    /// Gets the remaining durability of the tool, if one is present. Also returns [`None`]
    /// if the tool cannot take damage.
    pub fn durability(&self) -> Result<Option<NonZeroU32>, BlockOperationsError> {
        let raw = self.call("durability", &[], &[])?.0;
        Ok(NonZeroU32::new(raw))
    }

    /// Tries to break a block on the specified side, defaulting to [`RobotSide::Front`].
    pub fn excavate(&self, side: Option<RobotSide>) -> Result<(), BlockOperationsError> {
        if self.call("excavate", &[&side as _], &[])?.0 {
            Ok(())
        } else {
            Err(BlockOperationsError::OperationFailed)
        }
    }

    /// Tries to place a block on the specified side, defaulting to [`RobotSide::Front`].
    pub fn place(&self, side: Option<RobotSide>) -> Result<(), BlockOperationsError> {
        if self.call("place", &[&side as _], &[])?.0 {
            Ok(())
        } else {
            Err(BlockOperationsError::OperationFailed)
        }
    }
}

impl DeviceBase for BlockOperations {
    const TYPE: &'static str = "block_operations";

    type Event = Infallible;

    fn new(client: HlapiClient, uuid: Uuid) -> Result<Self, HlapiClientError> {
        Ok(Self { client, uuid })
    }

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

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