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
//! # G29 Driver
//!
//! This library provides a Rust interface for Logitech G29 wheel/pedal and force feedback control. 
//! It utilizes the `hidapi` crate to interact with the G29 hardware.
//!
//! ## Usage
//!
//! ```rust
//! use g29::{G29, G29Driver};
//!
//! fn main() {
//!     // Create a new G29 instance
//!     let mut g29 = G29::new();
//!     // set force feedback for G29 controller - make sure to set the Logitech to PS3 Mode
//!     g29.g29.lock().unwrap().force_feedback_constant(0.6);
//!     // Start the reading thread to continuously read input from the G29 device
//!     g29.start_pumping();
//!     loop {
//!           println!("steering = {:?}", g29.g29.lock().unwrap().get_state());
//!      }
//! }
//! ```
//! 
//! 
//
// 
//! ## Example
//!
//! Interacting with the driver without starting a thread to set force feedback.
//!
//! ```rust
//! use g29::G29Driver;
//!
//! fn main() {
//!     // Create a new G29 driver instance
//!     let mut g29 = G29Driver::new();
//!
//!     // Reset the G29 device, including steering wheel calibration
//!     g29.reset();
//!
//!     // Example: Set autocenter with a strength of 0.5 and a rate of 0.05
//!     g29.set_autocenter(0.5, 0.05);
//!
//!     // Other operations and configurations can be performed here
//! }
//! ```
//!
 
use core::panic;
use hidapi::{HidApi, HidDevice};
use std::{
    collections::HashMap,
    sync::{Arc, Mutex},
    thread::{self, JoinHandle},
    time::Duration,
};

///! The `G29Driver` struct is the underlying driver for the G29 device, managing communication and state.
#[derive(Debug)]
pub struct G29Driver {
    device: HidDevice,
    cache: Vec<u8>,
    state: HashMap<&'static str, u8>,
}

impl G29Driver {
    /// Initializes a new G29 driver, opens the device, and sets initial state.
    pub fn new() -> Self {
        let api = HidApi::new().unwrap();
        let device = api.open(0x046d, 0xc24f).unwrap();
        let mut state = HashMap::new();
        state.insert("steering", 255);
        state.insert("throttle", 255);
        state.insert("clutch", 255);
        state.insert("brake", 255);
        Self {
            device,
            cache: vec![0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], //Vec::new(),
            state,
        }
    }

    // Write to the G29Driver Driver
    /// Resets the G29 device, including steering wheel calibration.
    /// calibration the steering wheel of the G2
    ///
    pub fn reset(&self) {
        self.device
            .write(&[0xf8, 0x0a, 0x00, 0x00, 0x00, 0x00, 0x00])
            .unwrap();
        self.device
            .write(&[0xf8, 0x09, 0x05, 0x01, 0x01, 0x00, 0x00])
            .unwrap();
        // wait for setting the calibration
        thread::sleep(Duration::from_secs(10));
    }
    /// Connects to the G29 device by pumping data and resetting.
    pub fn connect(&mut self) {
        self.pump(10);
        self.reset();
    }
    /// Sets constant force feedback on the G29 device.
    pub fn force_feedback_constant(&self, val: f32) {
        if val < 0.0 || val > 1.0 {
            panic!("Value must be in range of 0 to 1");
        }
        let val_scale = (val * 255.0).round() as u8;
        let msg = [0x14, 0x00, val_scale, 0x00, 0x00, 0x00, 0x00];
        self.device.write(&msg).unwrap();
        thread::sleep(Duration::from_secs(1));
    }

    /// Configures autocentering strength and rate.
    /// default value to be used strength = 0.5 and rate = 0.05                                                                                   
    pub fn set_autocenter(&self, strength: f32, rate: f32) {
        if (strength < 0.0) || (strength > 1.0) {
            panic!("Strength must be in range of 0.0 to 1.0");
        }
        if (rate < 0.0) || (rate > 1.0) {
            panic!("Rate must be in range of 0.0 to 1.0 ");
        }

        // autocenter Up
        let up_msg = [0x14, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00];
        self.device.write(&up_msg).unwrap();

        //scale Rate 0 -> 255 and Strength to 0 ->15
        let strength_scale = (strength * 15.0).round() as u8;
        let rate_scale = (rate * 255.0).round() as u8;

        self.device
            .write(&[
                0xfe,
                0x0d,
                strength_scale,
                strength_scale,
                rate_scale,
                0x00,
                0x00,
                0x00,
            ])
            .unwrap();
        thread::sleep(Duration::from_secs(10));
    }

    /// Turns off force feedback on the G29 device.
    pub fn force_off(&self) {
        self.device
            .write(&[0xf3, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00])
            .unwrap();
    }

    /// Reads data from the G29 device buffer.
    pub fn pump(&mut self, timeout: i32) -> usize {
        let mut buf = [0u8; 16]; //16
        let data = self.device.read_timeout(&mut buf, timeout).unwrap();
        let byte_array = buf[..data].to_vec();

        if byte_array.len() >= 12 {
            self.update_state(&byte_array);
            self.cache = byte_array;
        }
        return data;
    }
    /// Continuously pumps data in a loop.
    pub fn read_loop(&mut self) {
        loop {
            self.pump(10);
        }
    }

    /// Updates the internal state based on the latest data.
    pub fn update_state(&mut self, byte_array: &Vec<u8>) {
        if self.cache.is_empty() {
            panic!("cache is Empty");
        }

        //Update state
        // steering
        if byte_array[4] != self.cache[4] || byte_array[5] != self.cache[5] {
            let steering_val = self.calculate_steering(&byte_array[5], &byte_array[4]);
            //println!("steering_scaled = {}", steering_val);
            self.state.insert("steering", steering_val);
        }
        //throttle
        if byte_array[6] != self.cache[6] {
            self.state.insert("throttle", byte_array[6]);
        }
        //brake
        if byte_array[7] != self.cache[7] {
            self.state.insert("brake", byte_array[7]);
        }

        //clutch
        if byte_array[8] != self.cache[8] {
            self.state.insert("clutch", byte_array[8]);
        }

        println!("update_state = {:?}", self.state);
    }

    /// Retrieves the current state of the G29 device.
    pub fn get_state(&self) -> &HashMap<&str, u8> {
        &self.state
    }
    /// Calculates the scaled steering value based on raw input.
    pub fn calculate_steering(&self, start: &u8, end: &u8) -> u8 {
        // start from 0 to 255
        // end from 0 to 255
        // scale between 0 -> 100
        let start_scale = (*start as f32 / 256.0) * (100.0 - (100.0 / 256.0));
        // scale between 0 -> 3
        let end_scale = (*end as f32 / 255.0) * (100.0 / 256.0);
        return (start_scale + end_scale).round() as u8;
    }
}


// ## G29 Struct
/// The `G29` struct represents the G29 device and provides methods for controlling and interacting with it.

#[derive(Debug)]
pub struct G29 {
    pub g29: Arc<Mutex<G29Driver>>,
    reading_thread: Option<JoinHandle<()>>,
}

impl G29 {
    /// Creates a new G29 instance.
    pub fn new() -> Self {
        Self {
            g29: Arc::new(Mutex::new(G29Driver::new())),
            reading_thread: None,
        }
    }
    /// Starts a thread to continuously read input from the G29 device.
    pub fn start_pumping(&mut self) {
        let local_g29 = self.g29.clone();
        self.reading_thread = Some(thread::spawn(move || {
            local_g29.lock().unwrap().read_loop();
        }));
    }
    
    /// Stops the reading thread.
    pub fn stop_pumping(&mut self) {
        if let Some(handle) = self.reading_thread.take() {
            handle.join().unwrap();
        } else {
            println!("No Thread spawned");
        }
    }
}