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
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
#![cfg(target_os = "windows")]

use std::convert::TryInto;
use std::default::Default;
use std::error::Error;
use std::ffi::CStr;
use std::fmt::Display;
use std::fmt;
use std::os::windows::raw::HANDLE;
use std::ptr::null;
use std::slice::from_raw_parts;
use std::time::Duration;

use libc::c_char;
use libc::c_void;
use winapi::um::errhandlingapi::GetLastError;
use winapi::um::handleapi::CloseHandle;
use winapi::um::minwinbase::LPSECURITY_ATTRIBUTES;
use winapi::um::synchapi::{CreateEventW,WaitForSingleObject,ResetEvent};

use serde::{Serialize, Deserialize};

const DATA_EVENT_NAME: &'static str = "Local\\IRSDKDataValidEvent";

#[derive(Copy, Clone, Debug)]
#[repr(C)]
pub struct Header {
    pub version: i32,              // Telemetry version
    pub status: i32,               // Status
    pub tick_rate: i32,            // Tick rate (Hz)
    pub session_info_version: i32, // Increments each time session info is updated
    pub session_info_length: i32,  // Length of session info data
    pub session_info_offset: i32,  // Offset of session info data

    pub n_vars: i32,        // Number of values
    pub header_offset: i32, // Offset to start of variables

    pub n_buffers: i32,     // # of buffers (<= 3 for now)
    pub buffer_length: i32, // Length per line
    pub padding: [u32; 2],  // Padding

    buffers: [ValueBuffer; 4], // Data buffers
}

/// Blocking telemetry interface
/// 
/// Calling `sample()` on a Blocking interface will block until a new telemetry sample is made available.
/// 
pub struct Blocking {
    origin: *const c_void,
    values: Vec<ValueHeader>,
    header: Header,
    event_handle: HANDLE
}

#[derive(Copy, Clone, Debug)]
#[repr(C)]
struct ValueBuffer {
    pub ticks: i32,        // Tick count
    pub offset: i32,       // Offset
    pub padding: [u32; 2], // (16-byte align) Padding
}

#[derive(Clone)]
#[repr(C)]
struct ValueHeader {
    pub value_type: i32,     // Value type
    pub offset: i32,         // Value offset
    pub count: i32,          // Number of values for an array
    pub count_as_time: bool, // Values in array represent timeseries data

    _pad: [u8; 3],                                                   // Padding
    _name: [c_char; ValueHeader::MAX_VAR_NAME_LENGTH],               // Value name
    _description: [c_char; ValueHeader::MAX_VAR_DESCRIPTION_LENGTH], // Value description
    _unit: [c_char; ValueHeader::MAX_VAR_NAME_LENGTH],               // Value units
}

#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct ValueDescription {
    pub value: Value,
    pub count: usize,
    pub count_as_time: bool,
    
    pub name: String,
    pub description: String,
    pub unit: String
}

///
/// Sample represents a single sample of telemetry data from iRacing
/// either from live telemetry, or from a telemetry file.
#[derive(Debug, Default)]
pub struct Sample {
    tick: i32,
    buffer: Vec<u8>,
    values: Vec<ValueHeader>
}

/// Telemetry Value
/// 
/// Represents a single value in the telemetry. 
/// Telemetry data is always quantitive but may be of varying numeric types, plus boolean.
/// 
/// The iRacing Telemetry documentation describes the data-type expected for a given telemetry measurement.
/// `Into` can be used when the expected data type is known, else `match` can be used to dynamically handle the
/// returned data type.
/// 
/// # Examples
/// 
/// ## Known, Expected Data Type
/// ```
/// use iracing::telemetry::Sample;
/// 
/// let s: Sample = some_sample_getter();
/// 
/// let gear: i32 = s.get("Gear").unwrap().into();
/// ```
/// 
/// ## Unknown data type
/// 
/// ```
/// use iracing::telemtry::{Sample, Value};
/// 
/// let v: &'static str = some_input_for_var_name();
/// let s: Sample = some_sample_getter();
/// 
/// match s.get(v) {
///     None => println!("Didn't find that value");
///     Some(value) => match {
///         Value::CHAR(c) => println!("Value: {:x}", c),
///         Value::BOOL(b) => println!("Yes") if b,
///         Value::INT(i) => println!("Value: {}", i),
///         Value::BITS(u) => println!("Value: 0x{:32b}", u),
///         Value::FLOAT(f) | Value::DOUBLE(f) => println!("Value: {:.2}", f),
///         _  => println!("Unknown Value")
///     }
/// };  
/// ```
#[derive(Debug,Clone,Serialize,Deserialize)]
pub enum Value {
    CHAR(u8),
    BOOL(bool),
    INT(i32),
    BITS(u32),
    FLOAT(f32),
    DOUBLE(f64),
    UNKNOWN(()),
    IntVec(Vec<i32>),
    FloatVec(Vec<f32>),
    BoolVec(Vec<bool>)
}

impl From<i32> for Value {
    fn from(v: i32) -> Value {
        match v {
            0 => Value::CHAR(0x0),
            1 => Value::BOOL(false),
            2 => Value::INT(0),
            3 => Value::BITS(0x00),
            4 => Value::FLOAT(0.0),
            5 => Value::DOUBLE(0.0),
            _ => Value::UNKNOWN(())
        }
    }
}

impl Value {
    pub fn size(&self) -> usize {
        match self {
            Self::CHAR(_) | Self::BOOL(_) | Self::BoolVec(_) => 1,
            Self::INT(_) | Self::BITS(_) | Self::FLOAT(_) | Self::IntVec(_) | Self::FloatVec(_) => 4,
            Self::DOUBLE(_) => 8,
            Self::UNKNOWN(_) => 1
        }
    }
}

impl TryInto<i32> for Value {
    type Error = &'static str;

    fn try_into(self) -> Result<i32, Self::Error> {
        match self {
            Self::INT(n) => Ok(n),
            _ => Err("Value is not a signed 4-byte integer")
        }
    }
}

impl TryInto<u32> for Value {
    type Error = &'static str;
    
    fn try_into(self) -> Result<u32, Self::Error> {
        match self {
            Self::INT(n) => Ok(n as u32),
            Self::BITS(n) => Ok(n),
            _ => Err("Value is not a 4-byte integer")
        }
    }
}

impl TryInto<f32> for Value {
    type Error = &'static str;

    fn try_into(self) -> Result<f32, Self::Error> {
        match self {
            Self::FLOAT(n) => Ok(n),
            _ => Err("Value is not a float")
        }
    }
}

impl TryInto<f64> for Value {
    type Error = &'static str;

    fn try_into(self) -> Result<f64, Self::Error> {
        match self {
            Self::DOUBLE(n) => Ok(n),
            Self::FLOAT(f) => Ok(f as f64),
            _ => Err("Value is not a float or double")
        }
    }
}

impl Into<bool> for Value {
    fn into(self) -> bool {
        match self {
            Self::BOOL(b) => b,
            _ => false
        }
    }
}

impl Into<Vec<bool>> for Value {
    fn into(self) -> Vec<bool> {
        match self {
            Self::BoolVec(b) => b,
            _ => vec![false]
        }
    }
}

impl ValueHeader {
    ///
    /// Maximum length of a variable name/unit
    const MAX_VAR_NAME_LENGTH: usize = 32;

    ///
    /// Maximum length for a variable description
    const MAX_VAR_DESCRIPTION_LENGTH: usize = 64;

    /// Convert the name from a c_char[32] to a rust String
    /// Expect that we won't have any encoding issues as the values should always be ASCII
    pub fn name(&self) -> String {
        let name = unsafe { CStr::from_ptr(self._name.as_ptr()) };
        name.to_string_lossy().to_string()
    }

    pub fn description(&self) -> String {
        let description = unsafe { CStr::from_ptr(self._description.as_ptr()) };
        description.to_string_lossy().to_string()
    }

    pub fn unit(&self) -> String {
        let unit = unsafe { CStr::from_ptr(self._unit.as_ptr()) };
        unit.to_string_lossy().to_string()
    }

}


// Workaround to handle cloning var descriptions which are [u8; 64] thus cannot be derived
struct VarDescription([c_char; ValueHeader::MAX_VAR_DESCRIPTION_LENGTH]);

impl Clone for VarDescription {
    fn clone(&self) -> Self {
        let mut new = VarDescription([0; ValueHeader::MAX_VAR_DESCRIPTION_LENGTH]);

        for i in 1 .. ValueHeader::MAX_VAR_DESCRIPTION_LENGTH {
            new.0[i] = self.0[i];
        }

        new
    }
}

impl Default for ValueHeader {
    ///
    /// Create a new, empty ValueHeader
    fn default() -> Self {
        ValueHeader {
            value_type: 0,
            offset: 0,
            count: 0,
            count_as_time: false,
            _pad: [0; 3],
            _name: [0; ValueHeader::MAX_VAR_NAME_LENGTH],
            _unit: [0; ValueHeader::MAX_VAR_NAME_LENGTH],
            _description: [0; ValueHeader::MAX_VAR_DESCRIPTION_LENGTH],
        }
    }
}

impl fmt::Debug for ValueHeader {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> std::fmt::Result {
        write!(
            f,
            "ValueHeader(name=\"{}\", type={}, count={}, offset={})",
            self.name(),
            self.value_type,
            self.count,
            self.offset
        )
    }
}

impl Header {
    fn latest_buffer(&self) -> (i32, ValueBuffer) {
        let mut latest_tick: i32 = 0;
        let mut buffer = self.buffers[0];

        for b in self.buffers.iter() {

            if b.ticks > latest_tick {
                buffer = *b;
                latest_tick = b.ticks;
            }
        }

        return (latest_tick, buffer);
    }

    fn var_buffer(&self, lb: ValueBuffer, from_loc: *const c_void) -> &[u8] {
        let sz = self.buffer_length as usize;

        let buffer_loc = from_loc as usize + lb.offset as usize;
        unsafe { from_raw_parts(buffer_loc as *const u8, sz) }
    }

    fn get_var_header(&self, from_loc: *const c_void) -> &[ValueHeader] {
        let n_vars = self.n_vars as usize;
        let header_loc = from_loc as usize + self.header_offset as usize;

        let content = unsafe { from_raw_parts(header_loc as *const ValueHeader, n_vars) };

        content.clone()
    }

    pub fn telemetry(
        &self,
        from_loc: *const c_void,
    ) -> Result<Sample, Box<dyn std::error::Error>> {
        let (tick, vbh) = self.latest_buffer();
        let value_buffer = self.var_buffer(vbh, from_loc);
        let value_header = self.get_var_header(from_loc);

        Ok(Sample::new(tick, value_header.to_vec(), value_buffer.to_vec()))
    }
}

impl Sample {
    fn new(tick: i32, header: Vec<ValueHeader>, buffer: Vec<u8>) -> Self {
        Sample {
            tick: tick,
            values: header,
            buffer: buffer,
        }
    }

    fn header_for(&self, name: &'static str) -> Option<ValueHeader> {
        for v in self.values.iter() {
            if v.name() == name {
                return Some(v.clone());
            }
        }
        None
    }

    ///
    /// Check if a given variable is available in the telemetry sample
    pub fn has(&self, name: &'static str) -> bool {
        match self.header_for(name) {
            Some(_) => true,
            None => false
        }
    }

    /// Gets all values in the same along with names and descriptions.
    ///
    /// Returns a vec of all values in the telemetry sample, along with
    /// additional metadata such as the name, description, unit and value count.
    ///
    /// Note: This method is expensive and will return a large number of values.
    ///       It should be used primarily for debugging, and for most use cases
    ///       Selecting only the values required with `get()` is suggested.
    pub fn all(&self) -> Vec<ValueDescription> {

        let r = self.values.iter().map( |v| {
            let val = self.value(v);

            ValueDescription{
                name: v.name().to_owned(),
                description: v.description().to_owned(),
                unit: v.unit().to_owned(),
                count: v.count as usize,
                count_as_time: v.count_as_time,
                value: val
            }
        });

        r.collect::<Vec<ValueDescription>>()
    }

    ///
    /// Get a Value from the sample.
    /// 
    /// Read a single varialbe from the telemetry sample.
    /// 
    /// Returns `Ok(Value)` if the telemetry value is available.
    /// Returns `Err(String)` if the value cannot be found.
    /// 
    /// # Parameters
    /// 
    /// `name`  Name of the telemetry variable to get
    ///   - see the iRacing Telemtry documentation for a complete list of possible values
    pub fn get(&self, name: &'static str) -> Result<Value, String> {
        match self.header_for(name) {
            None => Err(format!("No value '{}' found", name)),
            Some(vh) => Ok(self.value(&vh))
        }
    }

    fn value(&self, vh: &ValueHeader) -> Value {
        let vs = vh.offset as usize; // Value start
        let vt = Value::from(vh.value_type);
        let vz = vt.size();
        let ve = vs + vz;
        let vc = vh.count as usize;
        
        let raw_val = &self.buffer[vs..ve];

        let v: Value;
        v = match vt {
            Value::INT(_) => {
                if vc == 1 {
                    Value::INT( i32::from_le_bytes( raw_val.try_into().unwrap() ))
                } else {
                    let mut values: Vec<i32> = Vec::with_capacity(vc);
                    for i in 0..vc-1 {
                        values.push(i32::from_le_bytes( self.buffer[vs+vz*i .. vs+vz*(i+1) ].try_into().unwrap() ));
                    }
                    
                    Value::IntVec(values)
                }
            },
            Value::FLOAT(_) => {
                if vc == 1 {
                    Value::FLOAT( f32::from_le_bytes( raw_val.try_into().unwrap() ))
                } else {
                    let mut values: Vec<f32> = Vec::with_capacity(vc);
                    
                    for i in 0 .. vc-1 {
                        values.push(f32::from_le_bytes( self.buffer[vs+vz*i .. vs+vz*(i+1) ].try_into().unwrap() ));
                    }
                    
                    Value::FloatVec(values)
                }
            }, 
            Value::DOUBLE(_) => Value::DOUBLE( f64::from_le_bytes( raw_val.try_into().unwrap() )),
            Value::BITS(_) => Value::BITS( u32::from_le_bytes( raw_val.try_into().unwrap() )),
            Value::CHAR(_) => Value::CHAR(raw_val[0] as u8),
            Value::BOOL(_) => {
                if vc == 1 {
                    Value::BOOL(raw_val[0] > 0)
                } else {
                    let mut values: Vec<bool> = Vec::with_capacity(vc);

                    for i in 0..vc-1 {
                        values.push(self.buffer[vs + i] > 0);
                    }

                    Value::BoolVec(values)
                }
            }
            _ => unimplemented!()
        };

        v
    }
}

///
/// Telemetry Error
/// 
/// An error which occurs when telemetry samples cannot be read from the memory buffer.
#[derive(Debug)]
pub enum TelemetryError {
    ABANDONED,
    TIMEOUT(usize),
    UNKNOWN(u32)
}

impl Display for TelemetryError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::ABANDONED => write!(f, "{}", "Abandoned"),
            Self::TIMEOUT(ms) => write!(f, "Timeout after {}ms", ms),
            Self::UNKNOWN(v) => write!(f, "Unknown error code = {:x?}", v)
        }
    }
}

impl Error for TelemetryError {
}

impl Blocking {
    pub fn new(location: *const c_void, head: Header) -> std::io::Result<Self> {
        let values = head.get_var_header(location).to_vec();
    
        let mut event_name: Vec<u16> = DATA_EVENT_NAME.encode_utf16().collect();
        event_name.push(0);

        let sc: LPSECURITY_ATTRIBUTES = unsafe { std::mem::zeroed() };

        let handle: HANDLE = unsafe { CreateEventW(sc, 0, 0, event_name.as_ptr()) };

        if null() == handle {
            let errno: i32 = unsafe { GetLastError() as i32 };

            return Err(std::io::Error::from_raw_os_error(errno));
        }


        Ok(Blocking{
           origin: location,
           header: head,
           values: values,
           event_handle: handle
        }) 
    }

    pub fn close(&self) -> std::io::Result<()> {
        if self.event_handle.is_null() {
            return Ok(());
        }

        let succ = unsafe { CloseHandle(self.event_handle) };

        if succ == 0 {
            let err: i32 = unsafe { GetLastError() as i32 };

            return Err(std::io::Error::from_raw_os_error(err));
        }

        if self.origin.is_null() {
            return Ok(());
        }

        let succ = unsafe { CloseHandle(self.origin as HANDLE) };

        if succ == 0 {
            let err: i32 = unsafe { GetLastError() as i32 };

            Err(std::io::Error::from_raw_os_error(err))
        } else {
            Ok(())
        }
    }

    ///
    /// Sample Telemetry Data
    /// 
    /// Waits for new telemetry data up to `timeout` and returns a safe copy of the telemetry data.
    /// Returns an error on timeout or underlying system error.
    /// 
    /// # Examples
    /// 
    /// ```
    /// use iracing::Connection;
    /// use std::time::Duration;
    /// 
    /// let sampler = Connection::new()?.blocking()?;
    /// let sample = sampler.get(Duration::from_millis(50))?;
    /// ```
    pub fn sample(&self, timeout: Duration) -> Result<Sample, Box<dyn Error>> {
        
        let wait_time: u32 = match timeout.as_millis().try_into() {
            Ok(v) => v,
            Err(e) => return Err(Box::new(e))
        };

        let signal = unsafe { WaitForSingleObject(self.event_handle, wait_time)  };

        match signal {
            0x80 => Err(Box::new(TelemetryError::ABANDONED)), // Abandoned
            0x102 => Err(Box::new(TelemetryError::TIMEOUT(wait_time as usize))), // Timeout
            0xFFFFFFFF => { // Error
                let errno = unsafe { GetLastError() as i32 };
                Err(Box::new(std::io::Error::from_raw_os_error(errno)))
            }, 
            0x00 => { // OK
                unsafe { ResetEvent(self.event_handle) };
                self.header.telemetry(self.origin)
            }
            _ => Err(Box::new(TelemetryError::UNKNOWN(signal as u32)))
        }
    }
}