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
use parking_lot::{Mutex, MutexGuard};

use crate::{ChannelValue, Error, Result};

#[cfg(feature = "nv200")]
pub const MAX_CHANNELS: usize = 24;
#[cfg(not(feature = "nv200"))]
pub const MAX_CHANNELS: usize = 16;

pub const CHANNEL_TIMEOUT_MS: u128 = 2_500;
pub const CHANNEL_TIMEOUT_ATTEMPTS: u64 = 10_000;

pub type Channels = [ChannelValue; MAX_CHANNELS];

/// Device channels for storing notes.
///
/// By default, all channels have a zero-value.
///
/// Channels are configured after making a call to the device that returns the number of channels,
/// and their respective values.
pub static CHANNELS: Mutex<Channels> = Mutex::new([
    ChannelValue::from_inner(0),
    ChannelValue::from_inner(0),
    ChannelValue::from_inner(0),
    ChannelValue::from_inner(0),
    ChannelValue::from_inner(0),
    ChannelValue::from_inner(0),
    ChannelValue::from_inner(0),
    ChannelValue::from_inner(0),
    ChannelValue::from_inner(0),
    ChannelValue::from_inner(0),
    ChannelValue::from_inner(0),
    ChannelValue::from_inner(0),
    ChannelValue::from_inner(0),
    ChannelValue::from_inner(0),
    ChannelValue::from_inner(0),
    ChannelValue::from_inner(0),
    ChannelValue::from_inner(0),
    #[cfg(feature = "nv200")]
    ChannelValue::from_inner(0),
    #[cfg(feature = "nv200")]
    ChannelValue::from_inner(0),
    #[cfg(feature = "nv200")]
    ChannelValue::from_inner(0),
    #[cfg(feature = "nv200")]
    ChannelValue::from_inner(0),
    #[cfg(feature = "nv200")]
    ChannelValue::from_inner(0),
    #[cfg(feature = "nv200")]
    ChannelValue::from_inner(0),
    #[cfg(feature = "nv200")]
    ChannelValue::from_inner(0),
]);

/// Acquires a lock on the global [Channels].
///
/// Use operating system timers to measure elapsed time. Fail if timeout expires.
#[cfg(feature = "std")]
pub fn lock_channels() -> Result<MutexGuard<'static, Channels>> {
    use crate::std::time;

    let now = time::Instant::now();

    while now.elapsed().as_millis() < CHANNEL_TIMEOUT_MS {
        if let Some(chan_lock) = CHANNELS.try_lock() {
            return Ok(chan_lock);
        }
    }

    Err(Error::Timeout("channels lock".into()))
}

/// Acquires a lock on the global [Channels].
///
/// No access to operating system timers, so approximate with a number of attempts.
#[cfg(not(feature = "std"))]
pub fn lock_channels() -> Result<MutexGuard<'static, Channels>> {
    let mut attempts = 0;
    while attempts < CHANNEL_TIMEOUT_ATTEMPTS {
        if let Some(chan_lock) = CHANNELS.try_lock() {
            return Ok(chan_lock);
        }

        attempts += 1;
    }

    Err(Error::Timeout("channels lock".into()))
}

/// Gets a reference to the number of configured channels.
///
/// Example:
///
/// ```rust, no_run
/// # fn main() -> ssp::Result<()> {
/// let chan_lock = ssp::lock_channels()?;
/// let _channels = ssp::channels(&chan_lock)?;
///
/// # Ok(())
/// # }
/// ```
pub fn channels<'a>(chan_lock: &'a MutexGuard<'static, Channels>) -> Result<&'a [ChannelValue]> {
    // Find the first unconfigured channel.
    // If no channels are configured, a zero-length slice is returned.
    let idx = chan_lock
        .iter()
        .position(|p| p.as_inner() == 0)
        .unwrap_or(0);
    Ok(chan_lock[..idx].as_ref())
}

/// Gets a mutable reference to the number of configured channels.
///
/// Example:
///
/// ```rust, no_run
/// # fn main() -> ssp::Result<()> {
/// let mut chan_lock = ssp::lock_channels()?;
/// let _channels = ssp::channels_mut(&mut chan_lock)?;
///
/// # Ok(())
/// # }
/// ```
pub fn channels_mut<'a>(
    chan_lock: &'a mut MutexGuard<'static, Channels>,
) -> Result<&'a mut [ChannelValue]> {
    // Find the first unconfigured channel.
    // If no channels are configured, a zero-length slice is returned.
    let idx = chan_lock
        .iter_mut()
        .position(|p| p.as_inner() == 0)
        .unwrap_or(0);
    Ok(chan_lock[..idx].as_mut())
}

/// Used to set the configured channels after a device call that returns the number and
/// value of configured channels, e.g. [SetupRequest](crate::setup_request).
///
/// Example:
///
/// ```rust, no_run
/// # fn main() -> ssp::Result<()> {
/// // Pretend this was a response to an actual request...
/// let res = ssp::SetupRequestResponse::new();
/// let channels = res.channel_values()?;
///
/// ssp::configure_channels(channels.as_ref())?;
/// # Ok(())
/// # }
pub fn configure_channels(channels: &[ChannelValue]) -> Result<()> {
    let mut chan_lock = lock_channels()?;

    configure_channels_with_lock(&mut chan_lock, channels)
}

/// While holding a mutable lock on global channels, used to set the configured channels after a device
/// call that returns the number and value of configured channels, e.g. [SetupRequest](crate::setup_request).
///
/// Example:
///
/// ```rust, no_run
/// # fn main() -> ssp::Result<()> {
/// // Pretend this was a response to an actual request...
/// let res = ssp::SetupRequestResponse::new();
/// let channels = res.channel_values()?;
///
/// let mut chan_lock = ssp::lock_channels()?;
/// ssp::configure_channels_with_lock(&mut chan_lock, channels.as_ref())?;
/// # Ok(())
/// # }
pub fn configure_channels_with_lock(
    chan_lock: &mut MutexGuard<'static, Channels>,
    channels: &[ChannelValue],
) -> Result<()> {
    let len = channels.len();

    if len <= MAX_CHANNELS {
        chan_lock[..len]
            .iter_mut()
            .zip(channels.iter())
            .for_each(|(c, &s)| *c = s);

        Ok(())
    } else {
        Err(Error::InvalidLength((len, MAX_CHANNELS)))
    }
}

/// Gets the [ChannelValue] of the given channel index.
///
/// Channels are one-indexed, since many events use zero as a special value when returning the
/// channel index. For example, [Read](crate::ResponseStatus::Read) uses zero to indicate a note is
/// still being processed, and non-zero values to indicate the channel a validated note moves into.
///
/// Example:
///
/// ```rust, no_run
/// # fn main() -> ssp::Result<()> {
/// // Channels are one-indexed, zero is a special value
/// let _val = ssp::channel_value(1)?;
/// # Ok(())
/// # }
pub fn channel_value(channel: usize) -> Result<ChannelValue> {
    channel_value_with_lock(&lock_channels()?, channel)
}

/// While holding a lock on global channels, gets the [ChannelValue] of the given channel index.
///
/// Channels are one-indexed, since many events use zero as a special value when returning the
/// channel index. For example, [Read](crate::ResponseStatus::Read) uses zero to indicate a note is
/// still being processed, and non-zero values to indicate the channel a validated note moves into.
///
/// Example:
///
/// ```rust, no_run
/// # fn main() -> ssp::Result<()> {
/// // Channels are one-indexed, zero is a special value
/// let _val = ssp::channel_value(1)?;
/// # Ok(())
/// # }
pub fn channel_value_with_lock(
    chan_lock: &MutexGuard<'static, Channels>,
    channel: usize,
) -> Result<ChannelValue> {
    match channel {
        0 => Ok(ChannelValue::default()),
        c => {
            let val = chan_lock
                .get(c - 1)
                .ok_or(Error::InvalidLength((c, MAX_CHANNELS)))?;

            Ok(*val)
        }
    }
}

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

    #[test]
    fn test_configure_channels() -> Result<()> {
        let exp_channels = [
            ChannelValue::from(1),
            ChannelValue::from(5),
            ChannelValue::from(10),
            ChannelValue::from(20),
            ChannelValue::from(50),
            ChannelValue::from(100),
        ];
        let exp_len = exp_channels.len();

        // Before configuring, check all channels are zero-valued
        for c in 1..=MAX_CHANNELS {
            assert_eq!(channel_value(c)?.as_inner(), 0);
        }

        {
            let mut chan_lock = lock_channels()?;

            assert!(channels(&chan_lock)?.is_empty());
            assert!(channels_mut(&mut chan_lock)?.is_empty());
        }

        configure_channels(exp_channels.as_ref())?;

        let mut chan_lock = lock_channels()?;
        assert_eq!(chan_lock[..exp_len].as_ref(), exp_channels.as_ref());

        // check that "channel" zero still returns the default value
        assert_eq!(channel_value_with_lock(&chan_lock, 0)?.as_inner(), 0);

        // check that the configured channels return their expected values
        for c in 1..=exp_len {
            assert_eq!(channel_value_with_lock(&chan_lock, c)?, exp_channels[c - 1]);
        }

        let channels = channels(&chan_lock)?;
        assert_eq!(channels, exp_channels.as_ref());

        let channels = channels_mut(&mut chan_lock)?;
        assert_eq!(channels, exp_channels.as_ref());

        // reset to default values for other tests
        configure_channels_with_lock(
            &mut chan_lock,
            [
                ChannelValue::default(),
                ChannelValue::default(),
                ChannelValue::default(),
                ChannelValue::default(),
                ChannelValue::default(),
                ChannelValue::default(),
            ]
            .as_ref(),
        )?;

        for c in 0..MAX_CHANNELS {
            assert_eq!(channel_value_with_lock(&chan_lock, c)?.as_inner(), 0);
        }

        Ok(())
    }
}