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
//! The Vexide Simulator Protocol enables communication between VEX robot simulators and user-facing frontends using a JSON-based protocol.
//!
//! The code executor and frontend communicate over a stream in [newline-delimited JSON format](https://jsonlines.org/).
//!
//! The backend sends [`Event`]s which represent a change in simulator state.
//! These are used by the frontend to correctly display the state of the simulated program.
//!
//! The frontend sends [`Command`]s to the code executor to control the robot code environment, simulating changes in robot hardware (like controller input and LCD touch events) or competition phase.
//!
//! The full protocol is documented at <https://internals.vexide.dev/simulators/protocol>.

use base64::{prelude::*, DecodeError};
use serde::{Deserialize, Serialize};
use std::{num::NonZeroU16, path::PathBuf};

/// A message sent from the simulator to the frontend.
#[derive(Debug, Clone, PartialEq, PartialOrd, Serialize, Deserialize)]
pub enum Event {
    Handshake {
        version: i32,
        extensions: Vec<String>,
    },
    ScreenDraw {
        command: DrawCommand,
        color: Color,
        background: Color,
    },
    ScreenClear {
        color: Color,
    },
    ScreenDoubleBufferMode {
        enable: bool,
    },
    ScreenRender,
    VCodeSig(VCodeSig),
    Ready,
    Exited,
    Serial {
        channel: i32,
        data: Vec<u8>,
    },
    DeviceUpdate {
        status: DeviceStatus,
        port: Port,
    },
    Battery(Battery),
    RobotPose {
        x: f64,
        y: f64,
    },
    RobotState(RobotState),
    Log {
        level: LogLevel,
        message: String,
    },
    VEXLinkConnect {
        port: SmartPort,
        id: String,
        mode: LinkMode,
        r#override: bool,
    },
    VEXLinkDisconnect {
        port: SmartPort,
    },
}

/// A message sent from the frontend to the simulator.
#[derive(Debug, Clone, PartialEq, PartialOrd, Serialize, Deserialize)]
pub enum Command {
    Handshake {
        version: i32,
        extensions: Vec<String>,
    },
    Touch {
        pos: Point,
        event: TouchEvent,
    },
    ControllerUpdate(ControllerUpdate),
    USD {
        root: Option<PathBuf>,
    },
    VEXLinkOpened {
        port: SmartPort,
        mode: LinkMode,
    },
    VEXLinkClosed {
        port: SmartPort,
    },
    CompetitionMode {
        connected: bool,
        mode: CompMode,
        is_competition: bool,
    },
    ConfigureDevice {
        port: Port,
        device: Device,
    },
    AdiInput {
        port: AdiPort,
        voltage: f64,
    },
    StartExecution,
    SetBatteryCapacity {
        capacity: f64,
    },
}

/// Base64-encoded program metadata.
#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
pub struct VCodeSig(pub String);

impl VCodeSig {
    pub fn new(bytes: &[u8]) -> Self {
        Self(BASE64_STANDARD.encode(bytes))
    }

    pub fn to_bytes(&self) -> Result<Vec<u8>, DecodeError> {
        BASE64_STANDARD.decode(&self.0)
    }
}

/// The configuration of a V5 peripheral.
#[derive(Debug, Clone, Copy, PartialEq, PartialOrd, Serialize, Deserialize)]
#[non_exhaustive]
pub enum Device {
    Motor {
        physical_gearset: MotorGearset,
        moment_of_inertia: f64,
    },
}

/// The current state of the robot as a whole.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
#[non_exhaustive]
pub struct RobotState;

/// An instruction for drawing to the robot LCD screen.
#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
pub enum DrawCommand {
    Fill {
        shape: Shape,
    },
    Stroke {
        shape: Shape,
    },
    CopyBuffer {
        top_left: Point,
        bottom_right: Point,
        stride: NonZeroU16,
        /// Base64 string
        buffer: String,
    },
}

/// A shape that can be drawn to the robot LCD screen.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
pub enum Shape {
    Rectangle {
        top_left: Point,
        bottom_right: Point,
    },
    Circle {
        center: Point,
        radius: u16,
    },
    Pixel {
        pos: Point,
    },
}

/// A pixel with X and Y coordinates.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
pub struct Point {
    pub x: i16,
    pub y: i16,
}

/// The current state of a V5 peripheral.
#[derive(Debug, Clone, Copy, PartialEq, PartialOrd, Serialize, Deserialize)]
#[non_exhaustive]
pub enum DeviceStatus {
    Motor {
        velocity: f64,
        reversed: bool,
        power_draw: f64,
        torque_output: f64,
        flags: i32,
        position: f64,
        target_position: f64,
        voltage: f64,
        gearset: MotorGearset,
        brake_mode: MotorBrakeMode,
    },
}

/// The gearset of a VEX V5 motor.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
pub enum MotorGearset {
    Red,
    Green,
    Blue,
}

/// The brake mode of a VEX V5 motor.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
pub enum MotorBrakeMode {
    Coast,
    Brake,
    Hold,
}

/// The mode of a [VEXlink](https://drive.google.com/file/d/13mTA6BT7CPskJzh4YgsfAfoH9OgK75Hn/view)-configured radio.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
pub enum LinkMode {
    Manager,
    Worker,
}

/// The gearset of a VEX V5 motor.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
pub enum TouchEvent {
    Released,
    Pressed,
    Held,
}

/// An arbitrary port on the VEX V5.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
pub enum Port {
    Smart(SmartPort),
    Adi(AdiPort),
}

/// An RJ9 4p4c "Smart" port on the VEX V5.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
pub struct SmartPort(pub u8);

/// A 3-wire "ADI" port for analog devices.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
pub struct AdiPort(pub u8);

/// The current stage of a competition.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
pub enum CompMode {
    Auto,
    Driver,
}

/// An RGB color.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
pub struct Color {
    pub r: u8,
    pub g: u8,
    pub b: u8,
}

/// The importance level of a log message.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
pub enum LogLevel {
    Trace,
    Info,
    Warn,
    Error,
}

/// Battery status and statistics.
#[derive(Debug, Clone, Copy, PartialEq, PartialOrd, Serialize, Deserialize)]
pub struct Battery {
    pub voltage: f64,
    pub current: f64,
    pub capacity: f64,
}

/// A method of retrieving a controller's current state.
#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
pub enum ControllerUpdate {
    /// Implementors can send raw controller state to the simulator,
    /// allowing for keyboard-and-mouse-based control.
    Raw(ControllerState),
    /// Implementors can can send the UUID of a physical controller (more efficient and allows for SDL2 mappings).
    UUID(String),
}

/// The raw state of a VEX V5 controller.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
pub struct ControllerState {
    pub axis1: i32,
    pub axis2: i32,
    pub axis3: i32,
    pub axis4: i32,
    pub button_l1: bool,
    pub button_l2: bool,
    pub button_r1: bool,
    pub button_r2: bool,
    pub button_up: bool,
    pub button_down: bool,
    pub button_left: bool,
    pub button_right: bool,
    pub button_x: bool,
    pub button_b: bool,
    pub button_y: bool,
    pub button_a: bool,
    pub button_sel: bool,
    pub battery_level: i32,
    pub button_all: bool,
    pub flags: i32,
    pub battery_capacity: i32,
}