ccapi 0.3.0

A simple library to interact with the ControlConsole API for the PlayStation 3
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
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
#![forbid(unsafe_code)]

use anyhow::{anyhow, bail, Result};
use std::collections::HashMap;
use std::net::{IpAddr, Ipv4Addr, SocketAddr};
use std::str::FromStr;

const CCAPI_OK: i32 = 0;
const DEFAULT_CCAPI_PORT: u16 = 6333;
const DEFAULT_RADIX: u32 = 16;

pub struct CCAPI {
    console_socket: SocketAddr,
}

#[derive(Debug)]
pub enum BuzzerType {
    Continuous,
    Single,
    Double,
    Triple,
}

impl BuzzerType {
    pub fn get_value(&self) -> i32 {
        match *self {
            BuzzerType::Continuous => 0,
            BuzzerType::Single => 1,
            BuzzerType::Double => 2,
            BuzzerType::Triple => 3,
        }
    }
}

impl FromStr for BuzzerType {
    type Err = anyhow::Error;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        match s {
            "single" => Ok(BuzzerType::Single),
            "double" => Ok(BuzzerType::Double),
            "triple" => Ok(BuzzerType::Triple),
            "continuous" => Ok(BuzzerType::Continuous),
            _ => bail!("Invalid buzzer type '{s}' provided"),
        }
    }
}

#[derive(Debug)]
pub enum ShutdownMode {
    Shutdown,
    SoftReboot,
    HardReboot,
}

impl ShutdownMode {
    pub fn get_value(&self) -> i32 {
        match *self {
            ShutdownMode::Shutdown => 1,
            ShutdownMode::SoftReboot => 2,
            ShutdownMode::HardReboot => 3,
        }
    }
}

#[derive(Debug)]
pub enum NotifyIcon {
    Info,
    Caution,
    Friend,
    Slider,
    WrongWay,
    Dialog,
    DialogShadow,
    Text,
    Pointer,
    Grab,
    Hand,
    Pen,
    Finger,
    Arrow,
    ArrowRight,
    Progress,
    Trophy1,
    Trophy2,
    Trophy3,
    Trophy4,
}

impl NotifyIcon {
    fn get_value(&self) -> i32 {
        match *self {
            NotifyIcon::Info => 0,
            NotifyIcon::Caution => 1,
            NotifyIcon::Friend => 2,
            NotifyIcon::Slider => 3,
            NotifyIcon::WrongWay => 4,
            NotifyIcon::Dialog => 5,
            NotifyIcon::DialogShadow => 6,
            NotifyIcon::Text => 7,
            NotifyIcon::Pointer => 8,
            NotifyIcon::Grab => 9,
            NotifyIcon::Hand => 10,
            NotifyIcon::Pen => 11,
            NotifyIcon::Finger => 12,
            NotifyIcon::Arrow => 13,
            NotifyIcon::ArrowRight => 14,
            NotifyIcon::Progress => 15,
            NotifyIcon::Trophy1 => 16,
            NotifyIcon::Trophy2 => 17,
            NotifyIcon::Trophy3 => 18,
            NotifyIcon::Trophy4 => 19,
        }
    }
}

impl FromStr for NotifyIcon {
    type Err = anyhow::Error;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        match s {
            "info" => Ok(NotifyIcon::Info),
            "caution" => Ok(NotifyIcon::Caution),
            "friend" => Ok(NotifyIcon::Friend),
            "slider" => Ok(NotifyIcon::Slider),
            "wrongway" => Ok(NotifyIcon::WrongWay),
            "dialog" => Ok(NotifyIcon::Dialog),
            "dialogshadow" => Ok(NotifyIcon::DialogShadow),
            "text" => Ok(NotifyIcon::Text),
            "pointer" => Ok(NotifyIcon::Pointer),
            "grab" => Ok(NotifyIcon::Grab),
            "hand" => Ok(NotifyIcon::Hand),
            "pen" => Ok(NotifyIcon::Pen),
            "finger" => Ok(NotifyIcon::Finger),
            "arrow" => Ok(NotifyIcon::Arrow),
            "arrowright" => Ok(NotifyIcon::ArrowRight),
            "progress" => Ok(NotifyIcon::Progress),
            "trophy1" => Ok(NotifyIcon::Trophy1),
            "trophy2" => Ok(NotifyIcon::Trophy2),
            "trophy3" => Ok(NotifyIcon::Trophy3),
            "trophy4" => Ok(NotifyIcon::Trophy4),
            _ => bail!("Invalid notify icon '{s}' provided"),
        }
    }
}

#[derive(Debug)]
pub enum ConsoleLed {
    Red,
    Green,
}

impl FromStr for ConsoleLed {
    type Err = anyhow::Error;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        match s {
            "red" => Ok(ConsoleLed::Red),
            "green" => Ok(ConsoleLed::Green),
            _ => bail!("Invalid LED color '{s}' provided"),
        }
    }
}

impl ConsoleLed {
    pub fn get_value(&self) -> i32 {
        match *self {
            ConsoleLed::Green => 1,
            ConsoleLed::Red => 2,
        }
    }
}

#[derive(Debug)]
pub enum LedStatus {
    Off,
    On,
    Blink,
}

impl FromStr for LedStatus {
    type Err = anyhow::Error;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        match s {
            "on" => Ok(LedStatus::On),
            "off" => Ok(LedStatus::Off),
            "blink" => Ok(LedStatus::Blink),
            _ => bail!("Invalid LED status '{s}' provided")
        }
    }
}

impl LedStatus {
    pub fn get_value(&self) -> i32 {
        match *self {
            LedStatus::Off => 0,
            LedStatus::On => 1,
            LedStatus::Blink => 2,
        }
    }
}

#[derive(Debug)]
pub enum ConsoleType {
    Unknown,
    CEX,
    DEX,
    TOOL,
}

impl ConsoleType {
    pub fn get_value(&self) -> i32 {
        match *self {
            ConsoleType::Unknown => 0,
            ConsoleType::CEX => 1,
            ConsoleType::DEX => 2,
            ConsoleType::TOOL => 3,
        }
    }
}

impl From<i32> for ConsoleType {
    fn from(value: i32) -> Self {
        match value {
            1 => ConsoleType::CEX,
            2 => ConsoleType::DEX,
            3 => ConsoleType::TOOL,
            _ => ConsoleType::Unknown,
        }
    }
}

#[derive(Debug)]
pub struct FirmwareInfo {
    pub firmware_version: u32,
    pub ccapi_version: u32,
    pub console_type: ConsoleType,
}

#[derive(Debug)]
pub struct TemperatureInfo {
    pub cell: i32,
    pub rsx: i32,
}

struct ConsoleRequest<'a> {
    socket: &'a SocketAddr,
    command: String,
    parameters: HashMap<String, String>,
    strict: bool,
}

struct ConsoleResponse {
    lines: Vec<String>,
}

impl<'a> ConsoleRequest<'a> {
    fn new(socket: &'a SocketAddr, command: &str) -> Self {
        ConsoleRequest {
            socket,
            command: command.to_string(),
            parameters: HashMap::new(),
            strict: true,
        }
    }

    fn param(mut self, name: &str, value: &str) -> Self {
        self.parameters.insert(name.to_string(), value.to_string());
        self
    }

    fn send(&self) -> Result<ConsoleResponse> {
        let url = format!("http://{}/ccapi/{}", self.socket, self.command);
        let mut request = ureq::get(&url);

        for param in &self.parameters {
            request = request.query(&param.0, &param.1);
        }

        let response = request.call()?;

        let body = response.into_string()?;
        let lines: Vec<String> = body.split('\n').map(String::from).collect();

        if self.strict {
            let raw_status_code = lines.get(0).ok_or(anyhow!("Could not read status code"))?;
            let status_code: i32 = raw_status_code.parse()?;

            if status_code != CCAPI_OK {
                bail!(
                    "Invalid status code '{}' received for command '{}'\nParameters: {:?}",
                    status_code,
                    self.command,
                    self.parameters
                )
            }
        }

        Ok(ConsoleResponse { lines })
    }
}

impl CCAPI {
    /// Returns a new instance of CCAPI
    ///
    /// ### Arguments
    ///
    /// * `console_ip` - The IPv4 address of the console to communicate with
    ///
    /// ### Examples
    ///
    /// ```
    /// use ccapi::CCAPI;
    /// use std::net::Ipv4Addr;
    ///
    /// // Typically, the IP will be in a private range (e.g. 192.168.x.x)
    /// let ip: Ipv4Addr = "127.0.0.1".parse().unwrap();
    /// let ccapi = CCAPI::new(ip);
    /// ```
    pub fn new(console_ip: Ipv4Addr) -> Self {
        let console_socket = SocketAddr::new(IpAddr::V4(console_ip), DEFAULT_CCAPI_PORT);

        CCAPI { console_socket }
    }

    /// Sets the IPv4 address of the console to communicate with
    pub fn set_console_ip(&mut self, console_ip: Ipv4Addr) {
        self.console_socket.set_ip(IpAddr::V4(console_ip));
    }

    /// Sets the port to communicate with
    pub fn set_console_port(&mut self, port: u16) {
        self.console_socket.set_port(port);
    }

    /// Rings the console buzzer with the specified [BuzzerType](crate::BuzzerType)
    ///
    /// ### Arguments
    ///
    /// * `buzzer_type` - The buzzer type to use
    pub fn ring_buzzer(&self, buzzer_type: BuzzerType) -> Result<()> {
        let buzzer_code = buzzer_type.get_value();

        ConsoleRequest::new(&self.console_socket, "ringbuzzer")
            .param("type", &buzzer_code.to_string())
            .send()?;

        Ok(())
    }

    /// **WARNING:** This function will return an error even if successful
    /// 
    /// Shutdown/restart the console, depending on the [ShutdownMode](crate::ShutdownMode) given
    ///
    /// ### Arguments
    ///
    /// * `shutdown_mode` - The shutdown mode to use
    pub fn shutdown(&self, shutdown_mode: ShutdownMode) -> Result<()> {
        let shutdown_code = shutdown_mode.get_value();

        // FIXME: Explicitly ignore transport error for shutdown call
        let _ = ConsoleRequest::new(&self.console_socket, "shutdown")
            .param("mode", &shutdown_code.to_string())
            .send()?;

        Ok(())
    }

    /// Displays a notification message with an icon
    ///
    /// ### Arguments
    ///
    /// * `notify_icon` - Icon to display
    /// * `message` - Message to display
    pub fn notify(&self, notify_icon: NotifyIcon, message: &str) -> Result<()> {
        let notify_code = notify_icon.get_value();

        ConsoleRequest::new(&self.console_socket, "notify")
            .param("id", &notify_code.to_string())
            .param("msg", message)
            .send()?;

        Ok(())
    }

    /// Sets console LED color and status
    pub fn set_console_led(&self, color: ConsoleLed, status: LedStatus) -> Result<()> {
        let led_color_code = color.get_value();
        let led_status_code = status.get_value();

        ConsoleRequest::new(&self.console_socket, "setconsoleled")
            .param("color", &led_color_code.to_string())
            .param("status", &led_status_code.to_string())
            .send()?;

        Ok(())
    }

    /// Returns console firmware information
    pub fn get_firmware_info(&self) -> Result<FirmwareInfo> {
        let response = ConsoleRequest::new(&self.console_socket, "getfirmwareinfo").send()?;

        let raw_firmware_version = response.lines.get(1);
        let raw_ccapi_version = response.lines.get(2);
        let raw_console_type = response.lines.get(3);

        match (raw_firmware_version, raw_ccapi_version, raw_console_type) {
            (Some(fv), Some(cv), Some(ct)) => {
                let firmware_version: u32 = fv.parse()?;
                let ccapi_version = u32::from_str_radix(cv, DEFAULT_RADIX)?;
                let console_type_parsed: i32 = ct.parse()?;

                let firmware_info = FirmwareInfo {
                    firmware_version,
                    ccapi_version,
                    console_type: ConsoleType::from(console_type_parsed),
                };

                Ok(firmware_info)
            }
            _ => bail!("Could not retrieve firmware information"),
        }
    }

    /// Returns temperature information in celsius
    pub fn get_temperature_info(&self) -> Result<TemperatureInfo> {
        let response = ConsoleRequest::new(&self.console_socket, "gettemperature").send()?;

        let raw_cell_temp = response.lines.get(1);
        let raw_rsx_temp = response.lines.get(2);

        match (raw_cell_temp, raw_rsx_temp) {
            (Some(ct), Some(rt)) => {
                let cell_temp = i32::from_str_radix(ct, DEFAULT_RADIX)?;
                let rsx_temp = i32::from_str_radix(rt, DEFAULT_RADIX)?;

                let temp_info = TemperatureInfo {
                    cell: cell_temp,
                    rsx: rsx_temp,
                };

                Ok(temp_info)
            }
            _ => bail!("Could not retrieve temperature information"),
        }
    }

    /// Returns a list of process identifiers (pid)
    pub fn get_process_list(&self) -> Result<Vec<u32>> {
        let response = ConsoleRequest::new(&self.console_socket, "getprocesslist").send()?;

        let mut process_ids = Vec::new();

        // Skip first line which contains the "status" code
        for raw_pid in &response.lines[1..] {
            if let Ok(pid) = u32::from_str(raw_pid) {
                process_ids.push(pid);
            }
        }

        Ok(process_ids)
    }

    /// Returns a process name from its identifier (pid)
    pub fn get_process_name(&self, pid: &u32) -> Result<String> {
        let response = ConsoleRequest::new(&self.console_socket, "getprocessname")
            .param("pid", &pid.to_string())
            .send()?;

        let raw_process_name = response.lines.get(1);

        match raw_process_name {
            Some(process_name) => Ok(process_name.to_string()),
            _ => bail!("Could not retrieve process name for pid '{pid}'"),
        }
    }

    /// Returns a map of process ids and their names
    pub fn get_process_map(&self) -> Result<HashMap<u32, String>> {
        let pids = self.get_process_list()?;
        let mut process_map = HashMap::new();

        for pid in pids {
            let process_name = self.get_process_name(&pid)?;
            process_map.insert(pid, process_name);
        }

        Ok(process_map)
    }

    /// **!! NOT IMPLEMENTED !!**
    ///
    /// Read process memory from the given address
    pub fn read_process_memory(&self, _pid: &u32, _address: &u64, _size: &u32) -> Result<Vec<u8>> {
        // let request_url = self.build_command_url("getmemory");
        // let address_hex = format!("{address:x}");

        // let _response = ureq::get(&request_url)
        //     .query("pid", &pid.to_string())
        //     .query("addr", &address_hex)
        //     .query("size", &size.to_string())
        //     .call()?;
        unimplemented!("read_process_memory is not implemented")
    }
}