oc2_hlapi_v2 0.2.0

A client for the new version of OpenComputers II's HLAPI
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
//! The robot's device and its associated types
//!
//! [OC2 Docs](https://fnuecke.github.io/oc2/manual/en_us/device/robot.html)
use rgb::RGB8;
use serde::{Deserialize, Serialize};
use std::{
    error::Error as StdError,
    time::{Duration, Instant},
};
use thiserror::Error;
use uuid::Uuid;

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

/// Valid sides for robot operations
#[derive(Serialize, Deserialize, Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[serde(rename_all = "snake_case")]
pub enum RobotSide {
    /// The side in front of the robot
    Front,
    /// The side above the robot
    Up,
    /// The side below the robot
    Down,
}

/// The direction a robot is facing
#[derive(Serialize, Deserialize, Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[serde(rename_all = "snake_case")]
#[allow(missing_docs)] // This enum's variants are self-documenting
pub enum Facing {
    North,
    East,
    South,
    West,
}

/// The position of a robot relative to its origin.
///
/// Axes have the same direction and sign as in Minecraft commands - X is east/west, Y is up/down, and Z is north/south.
#[derive(Serialize, Deserialize, Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct Position {
    /// The robot's x-coordinate
    pub x: i32,
    /// The robot's y-coordinate
    pub y: i32,
    /// The robot's z-coordinate
    pub z: i32,
}

/// The result of a call to [`detect`]
///
/// [`detect`]: Robot::detect
#[derive(Serialize, Deserialize, Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[serde(rename_all = "snake_case")]
pub enum DetectResult {
    /// The space blocks movement
    Solid,
    /// The space contains a fluid that does not block movement
    Fluid,
    /// The space is free
    Air,
}

/// The result of a call to [`get_action_result`]
///
/// [`get_action_result`]: Robot::get_action_result
#[derive(Serialize, Deserialize, Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[serde(rename_all = "UPPERCASE")]
pub enum ActionResult {
    /// The action has not completed yet
    Incomplete,
    /// The action succeeded
    Success,
    /// The action failed
    Failure,
}

/// A direction to move the robot in
#[derive(Serialize, Deserialize, Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[serde(rename_all = "snake_case")]
#[allow(missing_docs)] // This enum's variants are self-documenting
pub enum MoveDirection {
    Forward,
    Backward,
    Upward,
    Downward,
}

/// A direction to turn the robot in
#[derive(Serialize, Deserialize, Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[serde(rename_all = "snake_case")]
#[allow(missing_docs)] // This enum's variants are self-documenting
pub enum TurnDirection {
    Left,
    Right,
}

#[derive(Serialize, Deserialize, Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[repr(transparent)]
#[serde(transparent)]
/// A submitted action's ID
pub struct ActionId(u32);

#[derive(Serialize, Deserialize, Debug, Clone, Copy, PartialEq, Eq)]
#[serde(rename_all = "camelCase")]
/// The event fired by the robot when an action completes
pub struct ActionCompleted {
    /// The ID of the action
    pub action_id: ActionId,
    /// The result of the action
    pub result: ActionResult,
}

/// A robot device
///
/// Due to limitations of the API that the mod provides, using the same robot device on two threads
/// simultaneously is not recommended, as if two threads perform a move or turn action simultaneously
/// the wrong action IDs may be read for each action and the logic to wait for the event finishing will
/// thus be messed up. Thus, if a robot is shared between threads, it should have a mutex protecting it.
#[derive(Debug, Clone)]
pub struct Robot {
    client: HlapiClient,
    uuid: Uuid,
}

/// The possible errors for device functions
#[non_exhaustive]
#[derive(Error, Debug)]
pub enum RobotError {
    #[error("HLAPI client error: {0}")]
    /// HLAPI client error
    HlapiClientError(#[from] HlapiClientError),
    #[error("Status bar fill value invalid")]
    /// Status bar fill value invalid
    FillValueInvalid,
    #[error("Timed out enqueuing action")]
    /// Timed out enqueuing action
    EnqueueTimeout,
    #[error("Timed out performing action")]
    /// Timed out performing action
    ActionTimeout,
}

impl Robot {
    /// Sets the robot's origin to the current position
    pub fn calibrate_position(&self) -> Result<(), RobotError> {
        self.call::<()>("calibratePosition", &[], &[])?;
        Ok(())
    }

    /// Reports the contents of the space on the given side of the robot
    pub fn detect(&self, side: RobotSide) -> Result<DetectResult, RobotError> {
        Ok(self.call("detect", &[&side as _], &[])?.0)
    }

    /// Gets the result of the specified action. Returns [`None`] if the action's result is not
    /// available.
    pub fn get_action_result(
        &self,
        action_id: ActionId,
    ) -> Result<Option<ActionResult>, RobotError> {
        Ok(self.call("getActionResult", &[&action_id as _], &[])?.0)
    }

    /// Gets the maximum amount of energy that the robot can store
    pub fn get_energy_capacity(&self) -> Result<u32, RobotError> {
        Ok(self.call("getEnergyCapacity", &[], &[])?.0)
    }

    /// Gets the current amount of energy the robot has stored
    pub fn get_energy_stored(&self) -> Result<u32, RobotError> {
        Ok(self.call("getEnergyStored", &[], &[])?.0)
    }

    /// Gets the direction the robot is facing
    pub fn get_facing(&self) -> Result<Facing, RobotError> {
        Ok(self.call("getFacing", &[], &[])?.0)
    }

    /// Gets the contents of the robot's fluid tank. Returns [`None`] if the tank is empty.
    pub fn get_fluid(&self) -> Result<Option<TankContentInfo>, RobotError> {
        Ok(self.call("getFluid", &[], &[])?.0)
    }

    /// Gets the ID of the last enqueued action
    pub fn get_last_action_id(&self) -> Result<ActionId, RobotError> {
        Ok(self.call("getLastActionId", &[], &[])?.0)
    }

    /// Gets the position of the robot relative to its origin
    ///
    /// The origin starts out at where the robot was placed, until a call to [`calibrate_position`],
    /// and it survives across restarts.
    ///
    /// [`calibrate_position`]: Self::calibrate_position
    pub fn get_position(&self) -> Result<Position, RobotError> {
        Ok(self.call("getPosition", &[], &[])?.0)
    }

    /// Gets the count of actions in the queue
    pub fn get_queued_action_count(&self) -> Result<u32, RobotError> {
        Ok(self.call("getQueuedActionCount", &[], &[])?.0)
    }

    /// Gets the currently selected inventory slot
    pub fn get_selected_slot(&self) -> Result<u32, RobotError> {
        Ok(self.call("getSelectedSlot", &[], &[])?.0)
    }

    /// Gets the stack in the given inventory slot. Returns [`None`] if the slot is empty
    pub fn get_stack_in_slot(&self, slot: u32) -> Result<Option<ItemStack>, RobotError> {
        Ok(self.call("getStackInSlot", &[&slot as _], &[])?.0)
    }

    /// Gets the color of the robot's status light
    pub fn get_status_color(&self) -> Result<RGB8, RobotError> {
        let raw: u32 = self.call("getStatusColor", &[], &[])?.0;
        Ok(RGB8 {
            r: ((raw >> 16) & 0xFF) as u8,
            g: ((raw >> 8) & 0xFF) as u8,
            b: (raw & 0xFF) as u8,
        })
    }

    /// Gets the fill percentage of the robot's status light as a number from 0 to 1
    pub fn get_status_fill(&self) -> Result<f32, RobotError> {
        Ok(self.call("getStatusValue", &[], &[])?.0)
    }

    /// Enqueues a move action in the specified direction, optionally with a timeout. A zero timeout is
    /// a non-blocking enqueue, and [`None`] means wait forever. If enqueues fail forever and a slot
    /// never opens, calling this with a `None`] timeout will never return.
    pub fn enqueue_move(
        &self,
        direction: MoveDirection,
        timeout: Option<Duration>,
    ) -> Result<ActionId, RobotError> {
        let deadline = timeout.map(|t| Instant::now() + t);
        loop {
            let event_stream = self.event_stream();
            if self.call("move", &[&direction as _], &[])?.0 {
                return self.get_last_action_id();
            }
            if deadline.is_some_and(|x| Instant::now() >= x) {
                return Err(RobotError::EnqueueTimeout);
            }
            if event_stream
                .get_event(deadline.map(|d| d.saturating_duration_since(Instant::now())))?
                .is_none()
            {
                return Err(RobotError::EnqueueTimeout);
            }
        }
    }

    /// Moves in the specified direction, optionally with a timeout. Returns whether the move succeeded,
    /// assuming it did not if the result for it was unavailable.
    ///
    /// If the move is enqueued but does not occur in the given timeout (this method returns
    /// `RobotError::ActionTimeout`), it may still occur as canceling actions is impossible.
    pub fn move_blocking(
        &self,
        direction: MoveDirection,
        timeout: Option<Duration>,
    ) -> Result<bool, RobotError> {
        let deadline = timeout.map(|t| Instant::now() + t);
        let id = self.enqueue_move(
            direction,
            deadline.map(|d| d.saturating_duration_since(Instant::now())),
        )?;
        let event_stream = self.event_stream();
        let mut result = self.get_action_result(id)?;
        while result == Some(ActionResult::Incomplete) {
            if deadline.is_some_and(|x| Instant::now() >= x) {
                return Err(RobotError::ActionTimeout);
            }
            loop {
                if let Some(event) = event_stream
                    .get_event(deadline.map(|d| d.saturating_duration_since(Instant::now())))?
                {
                    if event.action_id == id {
                        result = Some(event.result);
                        break;
                    }
                } else {
                    return Err(RobotError::ActionTimeout);
                }
            }
        }
        Ok(result == Some(ActionResult::Success))
    }

    /// Sets the selected inventory slot of the robot. Returns the actual selected slot, which may
    /// differ if the given slot was invalid.
    pub fn set_selected_slot(&self, slot: u32) -> Result<u32, RobotError> {
        Ok(self.call("setSelectedSlot", &[&slot as _], &[])?.0)
    }

    /// Sets the color of the robot's status light
    pub fn set_status_color(&self, color: RGB8) -> Result<(), RobotError> {
        let color = ((color.r as u32) << 16) | ((color.g as u32) << 8) | (color.b as u32);
        self.call::<u32>("setStatusColor", &[&color as _], &[])?;
        Ok(())
    }

    /// Sets the fill percentage of the robot's status light as a number from 0 to 1
    pub fn set_status_fill(&self, fill: f32) -> Result<(), RobotError> {
        if !(0.0..=1.0).contains(&fill) {
            return Err(RobotError::FillValueInvalid);
        }
        self.call::<f32>("setStatusValue", &[&fill as _], &[])?;
        Ok(())
    }

    /// Enqueues a turn action in the specified direction, optionally with a timeout. A zero timeout is
    /// a non-blocking enqueue, and [`None`] means wait forever. If enqueues fail forever and a slot
    /// never opens, calling this with a [`None`] timeout will never return.
    pub fn enqueue_turn(
        &self,
        direction: TurnDirection,
        timeout: Option<Duration>,
    ) -> Result<ActionId, RobotError> {
        let deadline = timeout.map(|t| Instant::now() + t);
        loop {
            let event_stream = self.event_stream();
            if self.call("turn", &[&direction as _], &[])?.0 {
                return self.get_last_action_id();
            }
            if deadline.is_some_and(|x| Instant::now() >= x) {
                return Err(RobotError::EnqueueTimeout);
            }
            if event_stream
                .get_event(deadline.map(|d| d.saturating_duration_since(Instant::now())))?
                .is_none()
            {
                return Err(RobotError::EnqueueTimeout);
            }
        }
    }

    /// Turns in the specified direction, optionally with a timeout. Returns whether the turn succeeded,
    /// assuming it did not if the result for it was unavailable.
    ///
    /// If the turn is enqueued but does not occur in the given timeout (this method returns
    /// `RobotError::ActionTimeout`), it may still occur as canceling actions is impossible.
    pub fn turn_blocking(
        &self,
        direction: TurnDirection,
        timeout: Option<Duration>,
    ) -> Result<bool, RobotError> {
        let deadline = timeout.map(|t| Instant::now() + t);
        let id = self.enqueue_turn(
            direction,
            deadline.map(|d| d.saturating_duration_since(Instant::now())),
        )?;
        let event_stream = self.event_stream();
        let mut result = self.get_action_result(id)?;
        while result == Some(ActionResult::Incomplete) {
            if deadline.is_some_and(|x| Instant::now() >= x) {
                return Err(RobotError::ActionTimeout);
            }
            loop {
                if let Some(event) = event_stream
                    .get_event(deadline.map(|d| d.saturating_duration_since(Instant::now())))?
                {
                    if event.action_id == id {
                        result = Some(event.result);
                        break;
                    }
                } else {
                    return Err(RobotError::ActionTimeout);
                }
            }
        }
        Ok(result == Some(ActionResult::Success))
    }
}

impl DeviceBase for Robot {
    const TYPE: &'static str = "robot";

    type Event = ActionCompleted;

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

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

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

    fn parse_event(
        typ: &str,
        data: &serde_json::Value,
    ) -> Result<Self::Event, Box<dyn StdError + Send + Sync>> {
        if typ != "robotActionCompleted" {
            return Err("invalid event type".into());
        }
        Ok(serde_json::from_value(data.clone())?)
    }
}