brlapi 0.4.1

Safe Rust bindings for the BrlAPI library
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
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
// SPDX-License-Identifier: LGPL-2.1

//! BrlAPI Parameter Management System
//!
//! This module provides access to BrlAPI's parameter management system, which allows
//! querying and modifying various aspects of the braille display, driver, and
//! connection state.
//!
//! Parameters are organized into several categories:
//! - Connection parameters (server version, client priority)
//! - Device parameters (driver info, display size, device properties)
//! - Input parameters (key handling preferences)
//! - Braille rendering parameters (cursor, literary braille settings)
//! - Navigation parameters (line skipping, audible alerts)
//! - Clipboard parameters (clipboard content)
//! - TTY mode parameters (bound commands, keycode information)
//! - Braille translation parameters (tables, character mappings)
//!
//! ## Parameter Watching Version Requirements
//!
//! Parameter watching functionality was added in BRLTTY 6.2 (BrlAPI 0.8.2) released
//! December 23, 2020. This includes the functions:
//! - `brlapi__watchParameter()`
//! - `brlapi__unwatchParameter()`
//! - Parameter update notifications via `BRLAPI_PACKET_PARAM_UPDATE`
//!
//! ## Parameter Watching Reality Check
//!
//! **IMPORTANT**: Based on research of real-world BrlAPI usage, parameter watching has
//! significant limitations and is **NOT widely used** even by major screen readers like
//! NVDA and Orca. Most applications use alternative approaches.
//!
//! ### Evidence-Based Limitations:
//!
//! 1. **Driver Compatibility**: Most braille display drivers do NOT support parameter watching:
//!    - **HIMS**: Parameter operations often fail with "Invalid parameter value"
//!    - **Baum**: Limited parameter support, watching unreliable
//!    - **HandyTech**: Variable support across device models
//!    - **Freedom Scientific**: Native drivers preferred over BrlAPI
//!    - **NoBraille**: Minimal parameter support (testing only)
//!
//! 2. **Threading Limitations**: Parameter callbacks only trigger when "BrlAPI gets direct
//!    control of execution" - requires explicit polling or `brlapi_pause()` calls.
//!
//! 3. **Real-World Usage**: Major screen readers use **native device drivers** instead:
//!    - NVDA removed BRLTTY dependency due to reliability issues
//!    - Orca uses direct device communication for responsiveness
//!    - Parameter watching is primarily useful for development/debugging
//!
//! ## Recommended Alternatives
//!
//! Instead of parameter watching, consider:
//! - **Direct device APIs** for real-time monitoring
//! - **Polling-based status checks** for non-critical updates
//! - **Event-driven architectures** using device-specific protocols
//! - **Cooperative display sharing** without parameter dependencies
//!
//! ## Troubleshooting Parameter Access
//!
//! If you still need parameter operations and they fail:
//!
//! 1. **Version Check**: Ensure BRLTTY 6.2+ is installed:
//!    ```bash
//!    brltty --version  # Should show 6.2 or later
//!    ```
//!
//! 2. **Try Basic Parameters First**: Test with simple parameters before watching:
//!    ```rust,no_run
//!    use brlapi::Connection;
//!
//!    // Test basic parameter access before attempting watching
//!    let connection = Connection::open()?;
//!    let driver = connection.display_driver()?;  // This should work
//!    let size = connection.display_size()?;      // This should work
//!    # Ok::<(), brlapi::BrlApiError>(())
//!    ```
//!
//! 3. **Check Driver Logs**: Look for parameter-related errors:
//!    ```bash
//!    journalctl -u brltty -f  # Watch logs in real-time
//!    ```
//!
//! 4. **Use Fallback Approaches**: Design your application to work without parameter watching
//!
//! ## Known Working Configurations
//!
//! Parameter operations have been tested to work with:
//! - **Simulated drivers** (for development)
//! - **Some USB-connected devices** (when drivers support parameter access)
//! - **Basic parameter reading** (more reliable than watching)
//!
//! # Example
//! ```no_run
//! use brlapi::{Connection, parameters::{Parameter, ParameterFlags}};
//!
//! fn main() -> Result<(), brlapi::BrlApiError> {
//!     let connection = Connection::open()?;
//!
//!     // Get server version
//!     let version: u32 = connection.get_parameter(Parameter::ServerVersion, 0, ParameterFlags::LOCAL)?;
//!     println!("BrlAPI server version: {}", version);
//!
//!     // Get display size
//!     let size: (u32, u32) = connection.get_parameter(Parameter::DisplaySize, 0, ParameterFlags::LOCAL)?;
//!     println!("Display: {}x{} cells", size.0, size.1);
//!
//!     // Get driver name
//!     let driver: String = connection.get_parameter(Parameter::DriverName, 0, ParameterFlags::LOCAL)?;
//!     println!("Driver: {}", driver);
//!
//!     Ok(())
//! }
//! ```

use crate::{Result, brlapi_call};

/// BrlAPI parameter identifiers
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[repr(u32)]
pub enum Parameter {
    // Connection Parameters
    ServerVersion = 0,
    ClientPriority = 1,

    // Device Parameters
    DriverName = 2,
    DriverCode = 3,
    DriverVersion = 4,
    DeviceModel = 5,
    DeviceCellSize = 31,
    DisplaySize = 6,
    DeviceIdentifier = 7,
    DeviceSpeed = 8,
    DeviceOnline = 9,

    // Input Parameters
    RetainDots = 10,

    // Braille Rendering Parameters
    ComputerBrailleCellSize = 11,
    LiteraryBraille = 12,
    CursorDots = 13,
    CursorBlinkPeriod = 14,
    CursorBlinkPercentage = 15,
    RenderedCells = 16,

    // Navigation Parameters
    SkipIdenticalLines = 17,
    AudibleAlerts = 18,

    // Clipboard Parameters
    ClipboardContent = 19,

    // TTY Mode Parameters
    BoundCommandKeycodes = 20,
    CommandKeycodeName = 21,
    CommandKeycodeSummary = 22,
    DefinedDriverKeycodes = 23,
    DriverKeycodeName = 24,
    DriverKeycodeSummary = 25,

    // Braille Translation Parameters
    ComputerBrailleRowsMask = 26,
    ComputerBrailleRowCells = 27,
    ComputerBrailleTable = 28,
    LiteraryBrailleTable = 29,
    MessageLocale = 30,

    // Driver-specific Parameters
    DriverPropertyValue = 32,
}

impl From<Parameter> for u32 {
    fn from(param: Parameter) -> Self {
        param as u32
    }
}

/// Flags for parameter operations
///
/// These flags control the scope of parameter access in BrlAPI:
///
/// ## Parameter Scope Guidelines
///
/// **Use GLOBAL for:**
/// - System-wide user preferences (contraction tables, braille modes)
/// - BRLTTY daemon configuration settings
/// - Settings that affect all clients equally
///
/// **Use LOCAL for:**
/// - Connection-specific temporary settings
/// - Client-specific priority adjustments
/// - Per-application customizations
///
/// **Best Practice:** Use fallback pattern for maximum compatibility:
/// ```rust
/// use brlapi::{Connection, parameters::{Parameter, ParameterFlags}};
///
/// # fn example() -> Result<(), brlapi::BrlApiError> {
/// let connection = Connection::open()?;
/// let param = Parameter::LiteraryBrailleTable;
///
/// // Try the most appropriate scope first, fallback to the other
/// let result = connection.get_parameter::<String>(param, 0, ParameterFlags::GLOBAL)
///     .or_else(|_| connection.get_parameter::<String>(param, 0, ParameterFlags::LOCAL));
/// # Ok(())
/// # }
/// ```
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct ParameterFlags(u32);

impl ParameterFlags {
    /// Refer to the value local to the connection instead of the global value
    ///
    /// Use for connection-specific settings that don't affect other clients.
    pub const LOCAL: Self = Self(0x00);

    /// Refer to the global value instead of the value local to the connection
    ///
    /// Use for system-wide preferences like contraction tables, braille modes,
    /// and daemon configuration that affects all clients.
    pub const GLOBAL: Self = Self(0x01);

    /// Specify whether to receive notifications of value self-changes
    pub const SELF: Self = Self(0x02);

    /// Create new parameter flags from raw value
    pub const fn from_raw(flags: u32) -> Self {
        Self(flags)
    }

    /// Get the raw flag value
    pub const fn raw(self) -> u32 {
        self.0
    }

    /// Combine with another flag
    pub const fn with(self, other: Self) -> Self {
        Self(self.0 | other.0)
    }
}

impl From<ParameterFlags> for brlapi_sys::brlapi_param_flags_t {
    fn from(flags: ParameterFlags) -> Self {
        flags.0
    }
}

/// Trait for types that can be used as parameter values
pub trait ParameterValue: Sized {
    /// Convert from raw parameter data
    fn from_parameter_data(data: &[u8]) -> Result<Self>;

    /// Convert to raw parameter data
    fn to_parameter_data(&self) -> Result<Vec<u8>>;
}

/// Boolean parameter value
pub type ParameterBool = bool;

impl ParameterValue for bool {
    fn from_parameter_data(data: &[u8]) -> Result<Self> {
        if data.is_empty() {
            return Ok(false);
        }
        Ok(data[0] != 0)
    }

    fn to_parameter_data(&self) -> Result<Vec<u8>> {
        Ok(vec![if *self { 1 } else { 0 }])
    }
}

impl ParameterValue for u8 {
    fn from_parameter_data(data: &[u8]) -> Result<Self> {
        if data.is_empty() {
            return Err(crate::BrlApiError::invalid_parameter_data(
                "u8 requires 1 byte",
            ));
        }
        Ok(data[0])
    }

    fn to_parameter_data(&self) -> Result<Vec<u8>> {
        Ok(vec![*self])
    }
}

impl ParameterValue for u32 {
    fn from_parameter_data(data: &[u8]) -> Result<Self> {
        if data.len() < 4 {
            return Err(crate::BrlApiError::invalid_parameter_data(
                "u32 requires 4 bytes",
            ));
        }
        Ok(u32::from_le_bytes([data[0], data[1], data[2], data[3]]))
    }

    fn to_parameter_data(&self) -> Result<Vec<u8>> {
        Ok(self.to_le_bytes().to_vec())
    }
}

impl ParameterValue for u64 {
    fn from_parameter_data(data: &[u8]) -> Result<Self> {
        if data.len() < 8 {
            return Err(crate::BrlApiError::invalid_parameter_data(
                "u64 requires 8 bytes",
            ));
        }
        let mut bytes = [0u8; 8];
        bytes.copy_from_slice(&data[0..8]);
        Ok(u64::from_le_bytes(bytes))
    }

    fn to_parameter_data(&self) -> Result<Vec<u8>> {
        Ok(self.to_le_bytes().to_vec())
    }
}

impl ParameterValue for String {
    fn from_parameter_data(data: &[u8]) -> Result<Self> {
        // BrlAPI strings are null-terminated UTF-8
        let len = data.iter().position(|&b| b == 0).unwrap_or(data.len());
        std::str::from_utf8(&data[0..len])
            .map(|s| s.to_owned())
            .map_err(|_| crate::BrlApiError::invalid_parameter_data("Invalid UTF-8 string"))
    }

    fn to_parameter_data(&self) -> Result<Vec<u8>> {
        let mut data = self.as_bytes().to_vec();
        data.push(0); // Null terminator
        Ok(data)
    }
}

impl ParameterValue for (u32, u32) {
    fn from_parameter_data(data: &[u8]) -> Result<Self> {
        if data.len() < 8 {
            return Err(crate::BrlApiError::invalid_parameter_data(
                "Display size requires 8 bytes",
            ));
        }
        let width = u32::from_le_bytes([data[0], data[1], data[2], data[3]]);
        let height = u32::from_le_bytes([data[4], data[5], data[6], data[7]]);
        Ok((width, height))
    }

    fn to_parameter_data(&self) -> Result<Vec<u8>> {
        let mut data = Vec::with_capacity(8);
        data.extend_from_slice(&self.0.to_le_bytes());
        data.extend_from_slice(&self.1.to_le_bytes());
        Ok(data)
    }
}

impl ParameterValue for Vec<u8> {
    fn from_parameter_data(data: &[u8]) -> Result<Self> {
        Ok(data.to_vec())
    }

    fn to_parameter_data(&self) -> Result<Vec<u8>> {
        Ok(self.clone())
    }
}

impl ParameterValue for Vec<u64> {
    fn from_parameter_data(data: &[u8]) -> Result<Self> {
        if data.len() % 8 != 0 {
            return Err(crate::BrlApiError::invalid_parameter_data(
                "Vec<u64> requires multiple of 8 bytes",
            ));
        }

        let mut result = Vec::with_capacity(data.len() / 8);
        for chunk in data.chunks_exact(8) {
            let mut bytes = [0u8; 8];
            bytes.copy_from_slice(chunk);
            result.push(u64::from_le_bytes(bytes));
        }
        Ok(result)
    }

    fn to_parameter_data(&self) -> Result<Vec<u8>> {
        let mut data = Vec::with_capacity(self.len() * 8);
        for &value in self {
            data.extend_from_slice(&value.to_le_bytes());
        }
        Ok(data)
    }
}

/// Constants for parameter values
pub mod constants {
    /// Default client priority
    pub const CLIENT_PRIORITY_DEFAULT: u32 = 50;

    /// Client priority that disables input/output
    pub const CLIENT_PRIORITY_DISABLE: u32 = 0;
}

/// Parameter management implementation
impl crate::Connection {
    /// Get the value of a parameter
    ///
    /// # Arguments
    /// * `parameter` - The parameter to get
    /// * `subparam` - Subparameter instance (0 for most parameters)
    /// * `flags` - Parameter flags specifying local/global scope
    ///
    /// # Returns
    /// The parameter value converted to the requested type
    ///
    /// # Example
    /// ```no_run
    /// use brlapi::{Connection, parameters::{Parameter, ParameterFlags}};
    ///
    /// let connection = Connection::open()?;
    /// let version: u32 = connection.get_parameter(Parameter::ServerVersion, 0, ParameterFlags::LOCAL)?;
    /// # Ok::<(), brlapi::BrlApiError>(())
    /// ```
    pub fn get_parameter<T: ParameterValue>(
        &self,
        parameter: Parameter,
        subparam: u64,
        flags: ParameterFlags,
    ) -> Result<T> {
        // First try to get the parameter size
        let size = brlapi_call!(unsafe {
            brlapi_sys::brlapi__getParameter(
                self.handle_ptr(),
                parameter.into(),
                subparam,
                flags.into(),
                std::ptr::null_mut(),
                0,
            )
        })?;

        if size < 0 {
            return Err(crate::BrlApiError::from_brlapi_error());
        }

        let size = size as usize;
        let mut buffer = vec![0u8; size];

        // Get the actual parameter data
        let actual_size = brlapi_call!(unsafe {
            brlapi_sys::brlapi__getParameter(
                self.handle_ptr(),
                parameter.into(),
                subparam,
                flags.into(),
                buffer.as_mut_ptr() as *mut std::ffi::c_void,
                size,
            )
        })?;

        if actual_size < 0 {
            return Err(crate::BrlApiError::from_brlapi_error());
        }

        // Truncate buffer to actual size
        buffer.truncate(actual_size as usize);

        T::from_parameter_data(&buffer)
    }

    /// Set the value of a parameter
    ///
    /// # Arguments
    /// * `parameter` - The parameter to set
    /// * `subparam` - Subparameter instance (0 for most parameters)
    /// * `flags` - Parameter flags specifying local/global scope
    /// * `value` - The value to set
    ///
    /// # Example
    /// ```no_run
    /// use brlapi::{Connection, parameters::{Parameter, ParameterFlags, constants}};
    ///
    /// let connection = Connection::open()?;
    /// connection.set_parameter(
    ///     Parameter::ClientPriority,
    ///     0,
    ///     ParameterFlags::LOCAL,
    ///     &constants::CLIENT_PRIORITY_DEFAULT
    /// )?;
    /// # Ok::<(), brlapi::BrlApiError>(())
    /// ```
    pub fn set_parameter<T: ParameterValue>(
        &self,
        parameter: Parameter,
        subparam: u64,
        flags: ParameterFlags,
        value: &T,
    ) -> Result<()> {
        let data = value.to_parameter_data()?;

        brlapi_call!(unsafe {
            brlapi_sys::brlapi__setParameter(
                self.handle_ptr(),
                parameter.into(),
                subparam,
                flags.into(),
                data.as_ptr() as *const std::ffi::c_void,
                data.len(),
            )
        })?;

        Ok(())
    }

    /// Get a parameter value using automatic allocation
    ///
    /// This is more efficient for variable-length parameters like strings.
    ///
    /// # Arguments
    /// * `parameter` - The parameter to get
    /// * `subparam` - Subparameter instance (0 for most parameters)
    /// * `flags` - Parameter flags specifying local/global scope
    pub fn get_parameter_alloc<T: ParameterValue>(
        &self,
        parameter: Parameter,
        subparam: u64,
        flags: ParameterFlags,
    ) -> Result<T> {
        let mut len: usize = 0;

        let ptr = unsafe {
            brlapi_sys::brlapi__getParameterAlloc(
                self.handle_ptr(),
                parameter.into(),
                subparam,
                flags.into(),
                &mut len,
            )
        };

        if ptr.is_null() {
            return Err(crate::BrlApiError::from_brlapi_error());
        }

        // Convert to slice and then to our type
        // SAFETY: ptr is non-null (checked above) and points to valid memory of size len
        // returned from brlapi__getParameterAlloc. len is the actual size returned by BrlAPI.
        let data = unsafe { std::slice::from_raw_parts(ptr as *const u8, len) };
        let result = T::from_parameter_data(data);

        // Free the allocated memory
        unsafe {
            libc::free(ptr);
        }

        result
    }
}

/// Error extension for parameter-specific errors
impl crate::BrlApiError {
    /// Create an error for invalid parameter data
    pub fn invalid_parameter_data(msg: &str) -> Self {
        crate::BrlApiError::Custom {
            message: format!("Invalid parameter data: {}", msg),
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_parameter_value_bool() {
        assert!(
            bool::from_parameter_data(&[1])
                .expect("Bool parameter with value 1 should parse as true")
        );
        assert!(
            !bool::from_parameter_data(&[0])
                .expect("Bool parameter with value 0 should parse as false")
        );
        assert!(
            !bool::from_parameter_data(&[]).expect("Empty bool parameter should parse as false")
        );

        assert_eq!(
            true.to_parameter_data()
                .expect("True should convert to parameter data [1]"),
            vec![1]
        );
        assert_eq!(
            false
                .to_parameter_data()
                .expect("False should convert to parameter data [0]"),
            vec![0]
        );
    }

    #[test]
    fn test_parameter_value_u32() {
        let value = 0x12345678u32;
        let data = value
            .to_parameter_data()
            .expect("u32 value should convert to parameter data");
        assert_eq!(
            u32::from_parameter_data(&data)
                .expect("Parameter data should convert back to original u32 value"),
            value
        );
    }

    #[test]
    fn test_parameter_value_string() {
        let s = "Hello, BrlAPI!";
        let data = s
            .to_string()
            .to_parameter_data()
            .expect("String should convert to parameter data");
        assert_eq!(
            String::from_parameter_data(&data)
                .expect("Parameter data should convert back to original string"),
            s
        );

        // Should have null terminator
        assert_eq!(data.last(), Some(&0));
    }

    #[test]
    fn test_parameter_value_display_size() {
        let size = (80u32, 25u32);
        let data = size
            .to_parameter_data()
            .expect("Display size tuple should convert to parameter data");
        assert_eq!(
            <(u32, u32)>::from_parameter_data(&data)
                .expect("Parameter data should convert back to original display size"),
            size
        );
    }

    #[test]
    fn test_parameter_flags() {
        let flags = ParameterFlags::LOCAL.with(ParameterFlags::SELF);
        assert_eq!(flags.raw(), 0x02);

        let global = ParameterFlags::GLOBAL;
        assert_eq!(global.raw(), 0x01);
    }
}

/// Basic parameter polling (evidence-based alternative to unreliable watching)
pub mod polling {
    use super::*;
    use crate::Connection;
    use std::time::{Duration, Instant};

    /// Simple parameter monitoring using reliable polling instead of callbacks
    ///
    /// This provides a practical alternative to parameter watching, which fails
    /// on most braille display drivers. Instead of complex callbacks, this uses
    /// simple polling that works consistently across all driver types.
    pub struct ParameterMonitor<T> {
        connection: Connection,
        parameter: Parameter,
        subparam: u64,
        flags: ParameterFlags,
        last_value: Option<T>,
        last_check: Instant,
        check_interval: Duration,
    }

    impl<T> ParameterMonitor<T>
    where
        T: ParameterValue + Clone + PartialEq,
    {
        /// Create a new parameter monitor
        pub fn new(
            connection: Connection,
            parameter: Parameter,
            subparam: u64,
            flags: ParameterFlags,
            check_interval: Duration,
        ) -> Self {
            Self {
                connection,
                parameter,
                subparam,
                flags,
                last_value: None,
                last_check: Instant::now(),
                check_interval,
            }
        }

        /// Check if the parameter has changed since last check
        ///
        /// Returns `Some(new_value)` if changed, `None` if unchanged or error
        pub fn check_for_change(&mut self) -> Option<T> {
            if self.last_check.elapsed() < self.check_interval {
                return None;
            }

            self.last_check = Instant::now();

            match self
                .connection
                .get_parameter(self.parameter, self.subparam, self.flags)
            {
                Ok(new_value) => {
                    if let Some(ref last) = self.last_value {
                        if *last == new_value {
                            return None; // No change
                        }
                    }

                    self.last_value = Some(new_value.clone());
                    Some(new_value)
                }
                Err(_) => None, // Parameter access failed - common with many drivers
            }
        }

        /// Get the current value without checking for changes
        pub fn current_value(&self) -> Option<&T> {
            self.last_value.as_ref()
        }

        /// Force a check regardless of interval
        pub fn force_check(&mut self) -> Option<T> {
            self.last_check = Instant::now() - self.check_interval;
            self.check_for_change()
        }
    }

    /// Simple screen reader activity hint based on basic parameter checks
    #[derive(Debug, Clone, PartialEq)]
    pub enum ScreenReaderHint {
        /// Likely no screen reader active
        Inactive,
        /// Possible screen reader activity
        Possible,
        /// Unable to determine (parameter access failed)
        Unknown,
    }

    /// Check for potential screen reader activity using basic parameter polling
    ///
    /// This provides a simple heuristic without relying on parameter watching.
    /// Returns a hint about screen reader activity based on what can be detected.
    pub fn detect_screen_reader_activity(connection: &Connection) -> ScreenReaderHint {
        // Try to detect activity by checking if we can get basic display info
        // If parameter access fails completely, assume a screen reader might be present
        match connection.display_driver() {
            Ok(_) => {
                // Basic parameter access works - screen reader likely not interfering
                ScreenReaderHint::Inactive
            }
            Err(_) => {
                // Parameter access issues might indicate screen reader activity
                // or just driver limitations - we can't tell the difference
                ScreenReaderHint::Unknown
            }
        }
    }

    /// Create a simple parameter monitor for basic polling
    ///
    /// This is a convenience function for the most common use case.
    pub fn monitor_display_size(connection: Connection) -> ParameterMonitor<(u32, u32)> {
        ParameterMonitor::new(
            connection,
            Parameter::DisplaySize,
            0,
            ParameterFlags::LOCAL,
            Duration::from_secs(1), // Check every second
        )
    }
}