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
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
//! Provides userspace applications with the ability to sample
//! analog signals.

use core::cell::Cell;
use core::cmp;
use kernel::{AppId, AppSlice, Callback, Driver, ReturnCode, Shared};
use kernel::common::take_cell::{MapCell, TakeCell};
use kernel::hil;

/// Syscall driver number.
pub const DRIVER_NUM: usize = 0x00000005;

/// ADC application driver, used by applications to interact with ADC.
/// Not currently virtualized, only one application can use it at a time.
pub struct Adc<'a, A: hil::adc::Adc + hil::adc::AdcHighSpeed + 'a> {
    // ADC driver
    adc: &'a A,
    channels: &'a [&'a <A as hil::adc::Adc>::Channel],

    // ADC state
    active: Cell<bool>,
    mode: Cell<AdcMode>,

    // App state
    app: MapCell<App>,
    channel: Cell<usize>,
    callback: Cell<Option<Callback>>,
    app_buf_offset: Cell<usize>,
    samples_remaining: Cell<usize>,
    samples_outstanding: Cell<usize>,
    next_samples_outstanding: Cell<usize>,
    using_app_buf1: Cell<bool>,

    // ADC buffers
    adc_buf1: TakeCell<'static, [u16]>,
    adc_buf2: TakeCell<'static, [u16]>,
    adc_buf3: TakeCell<'static, [u16]>,
}

/// ADC modes, used to track internal state and to signify to applications which
/// state a callback came from
#[derive(Copy, Clone, Debug, PartialEq)]
enum AdcMode {
    NoMode = -1,
    SingleSample = 0,
    ContinuousSample = 1,
    SingleBuffer = 2,
    ContinuousBuffer = 3,
}

/// Holds buffers that the application has passed us
pub struct App {
    app_buf1: Option<AppSlice<Shared, u8>>,
    app_buf2: Option<AppSlice<Shared, u8>>,
}

impl Default for App {
    fn default() -> App {
        App {
            app_buf1: None,
            app_buf2: None,
        }
    }
}

/// Buffers to use for DMA transfers
/// The size is chosen somewhat arbitrarily, but has been tested. At 175000 Hz,
/// buffers need to be swapped every 70 us and copied over before the next
/// swap. In testing, it seems to keep up fine.
pub static mut ADC_BUFFER1: [u16; 128] = [0; 128];
pub static mut ADC_BUFFER2: [u16; 128] = [0; 128];
pub static mut ADC_BUFFER3: [u16; 128] = [0; 128];

/// Functions to create, initialize, and interact with the ADC
impl<'a, A: hil::adc::Adc + hil::adc::AdcHighSpeed + 'a> Adc<'a, A> {
    /// Create a new Adc application interface
    ///
    /// adc - ADC driver to provide application access to
    /// channels - list of ADC channels usable by applications
    /// adc_buf1 - buffer used to hold ADC samples
    /// adc_buf2 - second buffer used when continuously sampling ADC
    pub fn new(
        adc: &'a A,
        channels: &'a [&'a <A as hil::adc::Adc>::Channel],
        adc_buf1: &'static mut [u16; 128],
        adc_buf2: &'static mut [u16; 128],
        adc_buf3: &'static mut [u16; 128],
    ) -> Adc<'a, A> {
        Adc {
            // ADC driver
            adc: adc,
            channels: channels,

            // ADC state
            active: Cell::new(false),
            mode: Cell::new(AdcMode::NoMode),

            // App state
            app: MapCell::new(App::default()),
            channel: Cell::new(0),
            callback: Cell::new(None),
            app_buf_offset: Cell::new(0),
            samples_remaining: Cell::new(0),
            samples_outstanding: Cell::new(0),
            next_samples_outstanding: Cell::new(0),
            using_app_buf1: Cell::new(true),

            // ADC buffers
            adc_buf1: TakeCell::new(adc_buf1),
            adc_buf2: TakeCell::new(adc_buf2),
            adc_buf3: TakeCell::new(adc_buf3),
        }
    }

    /// Initialize the ADC
    /// This can be called harmlessly if the ADC has already been initialized
    fn initialize(&self) -> ReturnCode {
        self.adc.initialize()
    }

    /// Store a buffer we've regained ownership of and return a handle to it
    /// The handle can have `map` called on it in order to process the data in
    /// the buffer
    ///
    /// buf - buffer to be stored
    fn replace_buffer(&self, buf: &'static mut [u16]) -> &TakeCell<'static, [u16]> {
        if self.adc_buf1.is_none() {
            self.adc_buf1.replace(buf);
            &self.adc_buf1
        } else if self.adc_buf2.is_none() {
            self.adc_buf2.replace(buf);
            &self.adc_buf2
        } else {
            self.adc_buf3.replace(buf);
            &self.adc_buf3
        }
    }

    /// Find a buffer to give to the ADC to store samples in
    ///
    /// closure - function to run on the found buffer
    fn take_and_map_buffer<F: FnOnce(&'static mut [u16])>(&self, closure: F) {
        if self.adc_buf1.is_some() {
            self.adc_buf1.take().map(|val| {
                closure(val);
            });
        } else if self.adc_buf2.is_some() {
            self.adc_buf2.take().map(|val| {
                closure(val);
            });
        } else if self.adc_buf3.is_some() {
            self.adc_buf3.take().map(|val| {
                closure(val);
            });
        }
    }

    /// Collect a single analog sample on a channel
    ///
    /// channel - index into `channels` array, which channel to sample
    fn sample(&self, channel: usize) -> ReturnCode {
        // only one sample at a time
        if self.active.get() {
            return ReturnCode::EBUSY;
        }

        // always initialize. Initialization will be skipped if already complete
        let res = self.initialize();
        if res != ReturnCode::SUCCESS {
            return res;
        }

        // convert channel index
        if channel >= self.channels.len() {
            return ReturnCode::EINVAL;
        }
        let chan = self.channels[channel];

        // save state for callback
        self.active.set(true);
        self.mode.set(AdcMode::SingleSample);
        self.channel.set(channel);

        // start a single sample
        let res = self.adc.sample(chan);
        if res != ReturnCode::SUCCESS {
            // failure, clear state
            self.active.set(false);
            self.mode.set(AdcMode::NoMode);

            return res;
        }

        ReturnCode::SUCCESS
    }

    /// Collected repeated single analog samples on a channel
    ///
    /// channel - index into `channels` array, which channel to sample
    /// frequency - number of samples per second to collect
    fn sample_continuous(&self, channel: usize, frequency: u32) -> ReturnCode {
        // only one sample at a time
        if self.active.get() {
            return ReturnCode::EBUSY;
        }

        // always initialize. Initialization will be skipped if already complete
        let res = self.initialize();
        if res != ReturnCode::SUCCESS {
            return res;
        }

        // convert channel index
        if channel >= self.channels.len() {
            return ReturnCode::EINVAL;
        }
        let chan = self.channels[channel];

        // save state for callback
        self.active.set(true);
        self.mode.set(AdcMode::ContinuousSample);
        self.channel.set(channel);

        // start a single sample
        let res = self.adc.sample_continuous(chan, frequency);
        if res != ReturnCode::SUCCESS {
            // failure, clear state
            self.active.set(false);
            self.mode.set(AdcMode::NoMode);

            return res;
        }

        ReturnCode::SUCCESS
    }

    /// Collect a buffer-full of analog samples
    /// Samples are collected into the first app buffer provided. The number of
    /// samples collected is equal to the size of the buffer "allowed"
    ///
    /// channel - index into `channels` array, which channel to sample
    /// frequency - number of samples per second to collect
    fn sample_buffer(&self, channel: usize, frequency: u32) -> ReturnCode {
        // only one sample at a time
        if self.active.get() {
            return ReturnCode::EBUSY;
        }

        // always initialize. Initialization will be skipped if already complete
        let res = self.initialize();
        if res != ReturnCode::SUCCESS {
            return res;
        }

        // convert channel index
        if channel >= self.channels.len() {
            return ReturnCode::EINVAL;
        }
        let chan = self.channels[channel];

        // cannot sample a buffer without a buffer to sample into
        let mut app_buf_length = 0;
        let exists = self.app.map_or(false, |state| {
            app_buf_length = state.app_buf1.as_mut().map_or(0, |buf| buf.len());
            state.app_buf1.is_some()
        });
        if !exists {
            return ReturnCode::ENOMEM;
        }

        // save state for callback
        self.active.set(true);
        self.mode.set(AdcMode::SingleBuffer);
        self.app_buf_offset.set(0);
        self.channel.set(channel);

        // start a continuous sample
        let res = self.adc_buf1.take().map_or(ReturnCode::EBUSY, |buf1| {
            self.adc_buf2.take().map_or(ReturnCode::EBUSY, move |buf2| {
                // determine request length
                let request_len = app_buf_length / 2;
                let len1;
                let len2;
                if request_len <= buf1.len() {
                    len1 = app_buf_length / 2;
                    len2 = 0;
                } else if request_len <= (buf1.len() + buf2.len()) {
                    len1 = buf1.len();
                    len2 = request_len - buf1.len();
                } else {
                    len1 = buf1.len();
                    len2 = buf2.len();
                }

                // begin sampling
                self.using_app_buf1.set(true);
                self.samples_remaining.set(request_len - len1 - len2);
                self.samples_outstanding.set(len1 + len2);
                let (rc, retbuf1, retbuf2) =
                    self.adc
                        .sample_highspeed(chan, frequency, buf1, len1, buf2, len2);
                if rc != ReturnCode::SUCCESS {
                    // store buffers again
                    retbuf1.map(|buf| {
                        self.replace_buffer(buf);
                    });
                    retbuf2.map(|buf| {
                        self.replace_buffer(buf);
                    });
                }
                rc
            })
        });
        if res != ReturnCode::SUCCESS {
            // failure, clear state
            self.active.set(false);
            self.mode.set(AdcMode::NoMode);
            self.samples_remaining.set(0);
            self.samples_outstanding.set(0);

            return res;
        }

        ReturnCode::SUCCESS
    }

    /// Collect analog samples continuously
    /// Fills one "allowed" application buffer at a time and then swaps to
    /// filling the second buffer. Callbacks occur when the in use "allowed"
    /// buffer fills
    ///
    /// channel - index into `channels` array, which channel to sample
    /// frequency - number of samples per second to collect
    fn sample_buffer_continuous(&self, channel: usize, frequency: u32) -> ReturnCode {
        // only one sample at a time
        if self.active.get() {
            return ReturnCode::EBUSY;
        }

        // always initialize. Initialization will be skipped if already complete
        let res = self.initialize();
        if res != ReturnCode::SUCCESS {
            return res;
        }

        // convert channel index
        if channel >= self.channels.len() {
            return ReturnCode::EINVAL;
        }
        let chan = self.channels[channel];

        // cannot continuously sample without two buffers
        let mut app_buf_length = 0;
        let mut next_app_buf_length = 0;
        let exists = self.app.map_or(false, |state| {
            app_buf_length = state.app_buf1.as_mut().map_or(0, |buf| buf.len());
            next_app_buf_length = state.app_buf2.as_mut().map_or(0, |buf| buf.len());
            state.app_buf1.is_some() && state.app_buf2.is_some()
        });
        if !exists {
            return ReturnCode::ENOMEM;
        }

        // save state for callback
        self.active.set(true);
        self.mode.set(AdcMode::ContinuousBuffer);
        self.app_buf_offset.set(0);
        self.channel.set(channel);

        // start a continuous sample
        let res = self.adc_buf1.take().map_or(ReturnCode::EBUSY, |buf1| {
            self.adc_buf2.take().map_or(ReturnCode::EBUSY, move |buf2| {
                // determine request lengths
                let samples_needed = app_buf_length / 2;
                let next_samples_needed = next_app_buf_length / 2;

                // determine request lengths
                let len1;
                let len2;
                if samples_needed <= buf1.len() {
                    // we can fit the entire app_buffer request in the first
                    // buffer. The second buffer will be used for the next
                    // app_buffer
                    len1 = samples_needed;
                    len2 = cmp::min(next_samples_needed, buf2.len());
                    self.samples_remaining.set(0);
                    self.samples_outstanding.set(len1);
                } else if samples_needed <= (buf1.len() + buf2.len()) {
                    // we can fit the entire app_buffer request between the two
                    // buffers
                    len1 = buf1.len();
                    len2 = samples_needed - buf1.len();
                    self.samples_remaining.set(0);
                    self.samples_outstanding.set(len1 + len2);
                } else {
                    // the app_buffer is larger than both buffers, so just
                    // request max lengths
                    len1 = buf1.len();
                    len2 = buf2.len();
                    self.samples_remaining.set(samples_needed - len1 - len2);
                    self.samples_outstanding.set(len1 + len2);
                }

                // begin sampling
                self.using_app_buf1.set(true);
                let (rc, retbuf1, retbuf2) =
                    self.adc
                        .sample_highspeed(chan, frequency, buf1, len1, buf2, len2);
                if rc != ReturnCode::SUCCESS {
                    // store buffers again
                    retbuf1.map(|buf| {
                        self.replace_buffer(buf);
                    });
                    retbuf2.map(|buf| {
                        self.replace_buffer(buf);
                    });
                }
                rc
            })
        });
        if res != ReturnCode::SUCCESS {
            // failure, clear state
            self.active.set(false);
            self.mode.set(AdcMode::NoMode);
            self.samples_remaining.set(0);
            self.samples_outstanding.set(0);

            return res;
        }

        ReturnCode::SUCCESS
    }

    /// Stops sampling the ADC
    /// Any active operation by the ADC is canceled. No additional callbacks
    /// will occur. Also retrieves buffers from the ADC (if any)
    fn stop_sampling(&self) -> ReturnCode {
        if !self.active.get() || self.mode.get() == AdcMode::NoMode {
            // already inactive!
            return ReturnCode::SUCCESS;
        }

        // clean up state
        self.active.set(false);
        self.mode.set(AdcMode::NoMode);
        self.app_buf_offset.set(0);

        // actually cancel the operation
        let rc = self.adc.stop_sampling();
        if rc != ReturnCode::SUCCESS {
            return rc;
        }

        // reclaim buffers
        let (rc, buf1, buf2) = self.adc.retrieve_buffers();

        // store buffers again
        buf1.map(|buf| {
            self.replace_buffer(buf);
        });
        buf2.map(|buf| {
            self.replace_buffer(buf);
        });

        // return result
        rc
    }
}

/// Callbacks from the ADC driver
impl<'a, A: hil::adc::Adc + hil::adc::AdcHighSpeed + 'a> hil::adc::Client for Adc<'a, A> {
    /// Single sample operation complete
    /// Collects the sample and provides a callback to the application
    ///
    /// sample - analog sample value
    fn sample_ready(&self, sample: u16) {
        if self.active.get() && self.mode.get() == AdcMode::SingleSample {
            // single sample complete, clean up state
            self.active.set(false);
            self.mode.set(AdcMode::NoMode);

            // perform callback
            self.callback.get().map(|mut callback| {
                callback.schedule(
                    AdcMode::SingleSample as usize,
                    self.channel.get(),
                    sample as usize,
                );
            });
        } else if self.active.get() && self.mode.get() == AdcMode::ContinuousSample {
            // sample ready in continuous sampling operation, keep state

            // perform callback
            self.callback.get().map(|mut callback| {
                callback.schedule(
                    AdcMode::ContinuousSample as usize,
                    self.channel.get(),
                    sample as usize,
                );
            });
        } else {
            // operation probably canceled. Make sure state is consistent. No
            // callback
            self.active.set(false);
            self.mode.set(AdcMode::NoMode);
        }
    }
}

/// Callbacks from the High Speed ADC driver
impl<'a, A: hil::adc::Adc + hil::adc::AdcHighSpeed + 'a> hil::adc::HighSpeedClient for Adc<'a, A> {
    /// Internal buffer has filled from a buffered sampling operation.
    /// Copies data over to application buffer, determines if more data is
    /// needed, and performs a callback to the application if ready. If
    /// continuously sampling, also swaps application buffers and continues
    /// sampling when neccessary. If only filling a single buffer, stops
    /// sampling operation when the application buffer is full.
    ///
    /// buf - internal buffer filled with analog samples
    /// length - number of valid samples in the buffer, guaranteed to be less
    ///          than or equal to buffer length
    fn samples_ready(&self, buf: &'static mut [u16], length: usize) {
        // do we expect a buffer?
        if self.active.get()
            && (self.mode.get() == AdcMode::SingleBuffer
                || self.mode.get() == AdcMode::ContinuousBuffer)
        {
            // we did expect a buffer. Determine the current application state
            self.app.map(|state| {
                // determine which app buffer to copy data into and which is
                // next up if we're in continuous mode
                let app_buf;
                let next_app_buf;
                if self.using_app_buf1.get() {
                    app_buf = state.app_buf1.as_mut();
                    next_app_buf = state.app_buf2.as_ref();
                } else {
                    app_buf = state.app_buf2.as_mut();
                    next_app_buf = state.app_buf1.as_ref();
                }

                // update count of outstanding sample requests
                self.samples_outstanding
                    .set(self.samples_outstanding.get() - length);

                // provide a new buffer and length request to the ADC if
                // necessary. If we haven't received enough samples for the
                // current app_buffer, we may need to place more requests. If we
                // have received enough, but are in continuous mode, we should
                // place a request for the next app_buffer. This is all
                // unfortunately made more complicated by the fact that there is
                // always one outstanding request to the ADC.
                let perform_callback;
                if self.samples_remaining.get() == 0 {
                    // we have already placed outstanding requests for all the
                    // samples needed to fill the current app_buffer

                    if self.samples_outstanding.get() == 0 {
                        // and the samples we just received are the last ones
                        // we need
                        perform_callback = true;

                        if self.mode.get() == AdcMode::ContinuousBuffer {
                            // it's time to switch to the next app_buffer, but
                            // there's already an outstanding request to the ADC
                            // for the next app_buffer that was placed last
                            // time, so we need to account for that
                            let samples_needed = next_app_buf.map_or(0, |buf| buf.len() / 2);
                            self.samples_remaining
                                .set(samples_needed - self.next_samples_outstanding.get());
                            self.samples_outstanding
                                .set(self.next_samples_outstanding.get());
                            self.using_app_buf1.set(!self.using_app_buf1.get());

                            // we also need to place our next request, however
                            // the outstanding request already placed for the
                            // next app_buffer might have completed it! So we
                            // have to account for that case
                            if self.samples_remaining.get() == 0 {
                                // oh boy. We actually need to place a request
                                // for the next next app_buffer (which is
                                // actually the current app_buf, but try not to
                                // think about that...). In practice, this
                                // should be a pretty uncommon case to hit, only
                                // occurring if the length of the app buffers
                                // are smaller than the length of the adc
                                // buffers, which is unsustainable at high
                                // sampling frequencies
                                let next_next_app_buf = &app_buf;

                                // provide a new buffer. However, we cannot
                                // currently update state since the next
                                // app_buffer still has a request outstanding.
                                // We'll just make a request and handle the
                                // state updating on next callback
                                self.take_and_map_buffer(|adc_buf| {
                                    let samples_needed =
                                        next_next_app_buf.as_ref().map_or(0, |buf| buf.len() / 2);
                                    let request_len = cmp::min(samples_needed, adc_buf.len());
                                    self.next_samples_outstanding.set(request_len);
                                    let (res, retbuf) =
                                        self.adc.provide_buffer(adc_buf, request_len);
                                    if res != ReturnCode::SUCCESS {
                                        retbuf.map(|buf| {
                                            self.replace_buffer(buf);
                                        });
                                    }
                                });
                            } else {
                                // okay, we still need more samples for the next
                                // app_buffer

                                // provide a new buffer and update state
                                self.take_and_map_buffer(|adc_buf| {
                                    let request_len =
                                        cmp::min(self.samples_remaining.get(), adc_buf.len());
                                    self.samples_remaining
                                        .set(self.samples_remaining.get() - request_len);
                                    self.samples_outstanding
                                        .set(self.samples_outstanding.get() + request_len);
                                    let (res, retbuf) =
                                        self.adc.provide_buffer(adc_buf, request_len);
                                    if res != ReturnCode::SUCCESS {
                                        retbuf.map(|buf| {
                                            self.replace_buffer(buf);
                                        });
                                    }
                                });
                            }
                        }
                    } else {
                        // but there are still outstanding samples for the
                        // current app_buffer (actually exactly one request, the
                        // one the ADC is currently acting on)
                        perform_callback = false;

                        if self.mode.get() == AdcMode::ContinuousBuffer {
                            // we're in continuous mode, so we need to start the
                            // first request for the next app_buffer

                            // provide a new buffer. However, we cannot
                            // currently update state since the current
                            // app_buffer still has a request outstanding. We'll
                            // just make a request and handle the state updating
                            // on next callback
                            self.take_and_map_buffer(|adc_buf| {
                                let samples_needed = next_app_buf.map_or(0, |buf| buf.len() / 2);
                                let request_len = cmp::min(samples_needed, adc_buf.len());
                                self.next_samples_outstanding.set(request_len);
                                let (res, retbuf) = self.adc.provide_buffer(adc_buf, request_len);
                                if res != ReturnCode::SUCCESS {
                                    retbuf.map(|buf| {
                                        self.replace_buffer(buf);
                                    });
                                }
                            });
                        }
                    }
                } else {
                    // we need to get more samples from the current app_buffer
                    perform_callback = false;

                    // provide a new buffer and update state
                    self.take_and_map_buffer(|adc_buf| {
                        let request_len = cmp::min(self.samples_remaining.get(), adc_buf.len());
                        self.samples_remaining
                            .set(self.samples_remaining.get() - request_len);
                        self.samples_outstanding
                            .set(self.samples_outstanding.get() + request_len);
                        let (res, retbuf) = self.adc.provide_buffer(adc_buf, request_len);
                        if res != ReturnCode::SUCCESS {
                            retbuf.map(|buf| {
                                self.replace_buffer(buf);
                            });
                        }
                    });
                }

                // next we should copy bytes to the app buffer
                app_buf.map(move |app_buf| {
                    // copy bytes to app buffer
                    // first, regain ownership of the buffer and then iterate
                    // over the data
                    self.replace_buffer(buf).map(|adc_buf| {
                        // The `for` commands:
                        //  * `chunks_mut`: get sets of two bytes from the app
                        //                  buffer
                        //  * `skip`: skips the already written bytes from the
                        //            app buffer
                        //  * `zip`: ties that iterator to an iterator on the
                        //           adc buffer, limiting iteration length to
                        //           the minimum of each of their lengths
                        //  * `take`: limits us to the minimum of buffer lengths
                        //            or sample length
                        // We then split each sample into its two bytes and copy
                        // them to the app buffer
                        for (chunk, &sample) in app_buf
                            .chunks_mut(2)
                            .skip(self.app_buf_offset.get() / 2)
                            .zip(adc_buf.iter())
                            .take(length)
                        {
                            let mut val = sample;
                            for byte in chunk.iter_mut() {
                                *byte = (val & 0xFF) as u8;
                                val = val >> 8;
                            }
                        }

                        // update our byte offset based on how many samples we
                        // copied
                        self.app_buf_offset
                            .set(self.app_buf_offset.get() + length * 2);
                    });

                    // if the app_buffer is filled, perform callback
                    if perform_callback {
                        // actually schedule the callback
                        self.callback.get().map(|mut callback| {
                            let len_chan = ((app_buf.len() / 2) << 8) | (self.channel.get() & 0xFF);
                            callback.schedule(
                                self.mode.get() as usize,
                                len_chan,
                                app_buf.ptr() as usize,
                            );
                        });

                        // if the mode is SingleBuffer, the operation is
                        // complete. Clean up state
                        if self.mode.get() == AdcMode::SingleBuffer {
                            self.active.set(false);
                            self.mode.set(AdcMode::NoMode);
                            self.app_buf_offset.set(0);

                            // need to actually stop sampling
                            self.adc.stop_sampling();

                            // reclaim buffers and store them
                            let (_, buf1, buf2) = self.adc.retrieve_buffers();
                            buf1.map(|buf| {
                                self.replace_buffer(buf);
                            });
                            buf2.map(|buf| {
                                self.replace_buffer(buf);
                            });
                        } else {
                            // if the mode is ContinuousBuffer, we've just
                            // switched app buffers. Reset our offset to zero
                            self.app_buf_offset.set(0);
                        }
                    }
                });
            });
        } else {
            // operation was likely canceled. Make sure state is consistent. No
            // callback
            self.active.set(false);
            self.mode.set(AdcMode::NoMode);
            self.app_buf_offset.set(0);

            // still need to replace the buffer
            self.replace_buffer(buf);
        }
    }
}

/// Implementations of application syscalls
impl<'a, A: hil::adc::Adc + hil::adc::AdcHighSpeed + 'a> Driver for Adc<'a, A> {
    /// Provides access to a buffer from the application to store data in or
    /// read data from
    ///
    /// _appid - application identifier, unused
    /// allow_num - which allow call this is
    /// slice - representation of application memory to copy data into
    fn allow(&self, _appid: AppId, allow_num: usize, slice: AppSlice<Shared, u8>) -> ReturnCode {
        match allow_num {
            // Pass buffer for samples to go into
            0 => {
                // set first buffer
                self.app.map(|state| {
                    state.app_buf1 = Some(slice);
                });

                ReturnCode::SUCCESS
            }

            // Pass a second buffer to be used for double-buffered continuous sampling
            1 => {
                // set second buffer
                self.app.map(|state| {
                    state.app_buf2 = Some(slice);
                });

                ReturnCode::SUCCESS
            }

            // default
            _ => ReturnCode::ENOSUPPORT,
        }
    }

    /// Provides a callback which can be used to signal the application
    ///
    /// subscribe_num - which subscribe call this is
    /// callback - callback object which can be scheduled to signal the
    ///            application
    fn subscribe(&self, subscribe_num: usize, callback: Callback) -> ReturnCode {
        match subscribe_num {
            // subscribe to ADC sample done (from all types of sampling)
            0 => {
                // set callback
                self.callback.set(Some(callback));
                ReturnCode::SUCCESS
            }

            // default
            _ => ReturnCode::ENOSUPPORT,
        }
    }

    /// Method for the application to command or query this driver
    ///
    /// command_num - which command call this is
    /// data - value sent by the application, varying uses
    /// _appid - application identifier, unused
    fn command(
        &self,
        command_num: usize,
        channel: usize,
        frequency: usize,
        _appid: AppId,
    ) -> ReturnCode {
        match command_num {
            // check if present
            0 => ReturnCode::SuccessWithValue {
                value: self.channels.len() as usize,
            },

            // Single sample on channel
            1 => self.sample(channel),

            // Repeated single samples on a channel
            2 => self.sample_continuous(channel, frequency as u32),

            // Multiple sample on a channel
            3 => self.sample_buffer(channel, frequency as u32),

            // Continuous buffered sampling on a channel
            4 => self.sample_buffer_continuous(channel, frequency as u32),

            // Stop sampling
            5 => self.stop_sampling(),

            // default
            _ => ReturnCode::ENOSUPPORT,
        }
    }
}