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
/* timer.rs
 *
 * Developed by Tim Walls <tim.walls@snowgoons.com>
 * Copyright (c) All Rights Reserved, Tim Walls
 */
//! Generic trait for controlling timer devices

// Imports ===================================================================
use core::any::Any;
use ufmt::derive::uDebug;
use avr_oxide::concurrency::Isolated;
use oxide_macros::Persist;
use avr_oxide::hal::generic::callback::IsrCallback;

// Declarations ==============================================================
#[derive(Clone,Copy)]
pub enum TimerMode {
  Periodic
}


/**
 * Identifies a particular source of timer events, i.e. a particular hardware
 * clock source, at runtime.
 */
#[derive(Clone,Copy,PartialEq,Eq,uDebug,Persist)]
pub enum TimerIdentity {
  /// Timer-Counter Type B, 0
  Tcb0,
  /// Timer-Counter Type B, 1
  Tcb1,
  /// Timer-Counter Type B, 2
  Tcb2,
  /// Timer-Counter Type B, 3
  Tcb3,
  /// Real-Time Counter
  Rtc
}

/**
 * Callback called by a timer when it generates an interrupt.  The callback
 * is given the number of ticks counted since the last such event.  The
 * callback should return a boolean:
 * * true:  Continue timer running
 * * false: Stop timer running
 *
 * Note: The callback runs *within the interrupt context* - be careful about
 * using mutual exclusion where necessary, and *DO NOT DO HEAVY PROCESSING
 * IN THE CALLBACK*.
 */
pub type TimerIsrFunction = fn(Isolated, TimerIdentity, u16, Option<*const dyn Any>) ->bool;

pub type TimerIsrCallback = IsrCallback<TimerIsrFunction,bool>;

pub trait TimerControl {
  /// Set the period (number of underlying timer interrupts) that
  /// trigger an interrupt callback (i.e. if 10, every 10 timer events
  /// the callback passed to start() will be called.)
  fn set_interrupt_period(&mut self, period: u16);

  /// Set the clock's mode
  fn set_mode(&mut self, mode: TimerMode);

  /// Set the clock's counter trigger
  fn set_count_max(&mut self, max: u16);

  /// Start this timer.  The given callback will be called periodically
  /// when timer interrupts occur (see the interrupting(period) method.)
  ///
  /// If the timer is in a constant-run mode (e.g. TimerMode::Periodic), it
  /// will run constantly until either stopped (with the stop() method!)
  /// or until the callback function returns false.
  fn start(&self, handler: TimerIsrCallback);

  /// Stop this timer
  fn stop(&self);

  /// Get the timer's current count value
  fn get_count(&self) -> u16;

  /// Reset the timer's current count value
  fn reset_count(&mut self);
}

#[derive(Copy,Clone)]
pub enum RtcSource {
  /// Internal 32.768 KHz clock source
  Int32k,
  /// Internal 1.024 KHz clock source
  Int1k,
  /// External 32.768 KHz clock source
  TOsc32k,
  /// External clock source on EXTCLK pin
  External
}

#[derive(Copy,Clone)]
pub enum RtcCalibration {
  /// Positive correction causing prescaler to count slower (i.e. the clock
  /// source is fast.)
  Fast(u8),
  /// Negative correction causing prescaler to count faster (i.e. the clock
  /// source is slow.)
  Slow(u8)
}

#[derive(Copy,Clone)]
pub enum RtcPrescaler {
  Div1,
  Div2,
  Div4,
  Div8,
  Div16,
  Div32,
  Div64,
  Div128,
  Div256,
  Div512,
  Div1024,
  Div2048,
  Div4096,
  Div8192,
  Div16384,
  Div32768
}

pub trait RtcTimerCalibration {
  /// Set the clock source and calibration configuration for an RTC device
  fn set_clock_calibration(&mut self, source: RtcSource, calibration: RtcCalibration, prescaler: RtcPrescaler);
}

// Code ======================================================================
#[cfg(target_arch="avr")]
pub mod base {
  use core::cell::{Cell};
  use avr_oxide::hal::generic::timer::{TimerIsrCallback, TimerMode, TimerControl, TimerIdentity, RtcTimerCalibration, RtcSource, RtcCalibration, RtcPrescaler};
  use avr_oxide::{isr_cb_invoke};
  use avr_oxide::concurrency::{interrupt, Isolated};
  use avr_oxide::hal::generic::MutDeviceRef;
  use avr_oxide::util::datatypes::{BitFieldAccess, BitIndex, Volatile, VolatileBitField};

  #[repr(C)]
  pub struct AvrTypeBTimerControl {
    pub(crate) ctrla: Volatile<u8>,
    pub(crate) ctrlb: VolatileBitField,
    pub(crate) reserved: [u8; 2],
    pub(crate) evctrl: Volatile<u8>,
    pub(crate) intctrl: VolatileBitField,
    pub(crate) intflags: VolatileBitField,
    pub(crate) status: Volatile<u8>,
    pub(crate) dbgctrl: Volatile<u8>,
    pub(crate) temp: Volatile<u8>,
    pub(crate) cnt: Volatile<u16>,
    pub(crate) ccmp: Volatile<u16>
  }

  pub trait AtmelTCB {
    fn enable(&mut self, isotoken: interrupt::token::Isolated);
    fn disable(&mut self, isotoken: interrupt::token::Isolated);
    fn enable_interrupt(&mut self, isotoken: interrupt::token::Isolated);
    fn clear_interrupt(&mut self, isotoken: interrupt::token::Isolated);
    fn mask_interrupt(&mut self, isotoken: interrupt::token::Isolated);
    fn set_top(&mut self, isotoken: interrupt::token::Isolated, top: u16);
    fn set_periodic_mode(&mut self, isotoken: interrupt::token::Isolated);
  }

  impl AtmelTCB for AvrTypeBTimerControl {
    fn enable(&mut self, _isotoken: interrupt::token::Isolated) {
      // Flags == Run in standby, divide clock by 2, enable
      self.ctrla.write(0b01000011);
    }

    fn disable(&mut self, _isotoken: interrupt::token::Isolated) {
      self.ctrla.write(0b00000000);
    }

    fn enable_interrupt(&mut self, isotoken: interrupt::token::Isolated) {
      self.intctrl.set_isolated(isotoken, BitIndex::bit_c(0));
    }

    fn clear_interrupt(&mut self, isotoken: interrupt::token::Isolated) {
      self.intflags.set_isolated(isotoken, BitIndex::bit_c(0));
    }

    fn mask_interrupt(&mut self, isotoken: interrupt::token::Isolated) {
      self.intctrl.clr_isolated(isotoken, BitIndex::bit_c(0));
    }

    fn set_top(&mut self, isotoken: interrupt::token::Isolated, top: u16) {
      self.cnt.write_isolated(isotoken,0x0000);
      self.ccmp.write_isolated(isotoken,top);
    }

    fn set_periodic_mode(&mut self, isotoken: interrupt::token::Isolated) {
      self.ctrlb.set_isolated(isotoken, BitIndex::bit_c(4));
    }
  }



  pub struct AtmelTimer<T>
    where
      T: 'static + AtmelTCB
  {
    pub(crate) interrupt_handler: Cell<TimerIsrCallback>,
    pub(crate) interrupt_period: Volatile<u16>,
    pub(crate) tcb: MutDeviceRef<T>,
    pub(crate) count_max: Volatile<u16>,
    pub(crate) mode: TimerMode
  }

  impl<T> TimerControl for AtmelTimer<T>
    where
      T: AtmelTCB
  {
    fn set_interrupt_period(&mut self, period: u16) {
      self.interrupt_period.write(period);
    }

    fn set_mode(&mut self, mode: TimerMode) {
      self.mode = mode;
    }

    fn set_count_max(&mut self, max: u16) {
      self.count_max.write(max);
    }

    fn start(&self, handler: TimerIsrCallback) {
      avr_oxide::concurrency::interrupt::isolated(|isotoken|{
        let tcb = self.tcb.borrow_mut(isotoken);

        tcb.disable(isotoken);
        match self.mode {
          TimerMode::Periodic => {
            tcb.set_periodic_mode(isotoken);
            tcb.set_top(isotoken, self.count_max.read());
          }
        };

        tcb.clear_interrupt(isotoken);


        self.interrupt_handler.replace(handler);

        if handler.is_nop() {
          tcb.mask_interrupt(isotoken);
        } else {
          tcb.enable_interrupt(isotoken);
        }

        tcb.enable(isotoken);
      });
    }

    fn stop(&self) {
      avr_oxide::concurrency::interrupt::isolated(|isotoken|{
        let tcb = self.tcb.borrow_mut(isotoken);

        tcb.disable(isotoken);
      });
    }

    fn get_count(&self) -> u16 {
      todo!()
    }

    fn reset_count(&mut self) {
      todo!()
    }
  }

  impl<T> AtmelTimer<T>
    where
      T: AtmelTCB
  {
    pub(crate) fn call_interrupt(&mut self, isotoken: Isolated, source: TimerIdentity, ticks: u16) {
      let continue_running = isr_cb_invoke!(isotoken, self.interrupt_handler.get(), source, ticks);

      if !continue_running {
        self.tcb.borrow_mut(isotoken).disable(isotoken);
      }
    }

    pub(crate) fn interrupt_period(&self, _isotoken: Isolated) -> u16 {
      self.interrupt_period.read()
    }

    pub(crate) fn clear_interrupt(&self, isotoken: Isolated) {
      self.tcb.borrow_mut(isotoken).clear_interrupt(isotoken);
    }
  }

  #[doc(hidden)]
  #[macro_export]
  macro_rules! atmel_tcb {
    ($tcbref:expr, $timersrc:expr, $isr:expr) => {
      use avr_oxide::hal::generic::timer::{ TimerMode, TimerIsrCallback };
      use avr_oxide::hal::generic::timer::base::{ AtmelTimer, AtmelTCB, AvrTypeBTimerControl };
      use avr_oxide::util::datatypes::Volatile;
      use avr_oxide::mut_singleton_explicit_init;
      use avr_oxide::hal::generic::MutDeviceRef;
      use core::cell::Cell;


      pub type TimerImpl = AtmelTimer<AvrTypeBTimerControl>;

      mut_singleton_explicit_init!(
        AtmelTimer<AvrTypeBTimerControl>,
        __INSTANCE,
        initialise, instance, instance_isolated,
        AtmelTimer {
          interrupt_handler: Cell::new(TimerIsrCallback::Nop(false)),
          interrupt_period: Volatile::<u16>::zero(),
          tcb: MutDeviceRef::new($tcbref),
          count_max: Volatile::<u16>::zero(),
          mode: TimerMode::Periodic
        });


      #[oxide_macros::interrupt(isr=$isr)]
      fn usart_timer_interrupt(isotoken: avr_oxide::concurrency::Isolated) {
        static mut COUNT_INTS : Volatile<u16> = Volatile::<u16>::zero();

        let counter = COUNT_INTS.read();

        let atmeltimer = instance_isolated(isotoken);
        if counter > atmeltimer.interrupt_period(isotoken) {
          atmeltimer.call_interrupt(isotoken, $timersrc, atmeltimer.interrupt_period(isotoken));
          COUNT_INTS.write_isolated(isotoken, 0u16);
        } else {
          COUNT_INTS.write_isolated(isotoken, counter+1);
        }

        atmeltimer.clear_interrupt(isotoken);
      }
    }
  }

  #[repr(C)]
  pub struct AvrRealTimeCounterControl {
    pub(crate) ctrla: Volatile<u8>,
    pub(crate) status: VolatileBitField,
    pub(crate) intctrl: VolatileBitField,
    pub(crate) intflags: VolatileBitField,
    pub(crate) temp: Volatile<u8>,
    pub(crate) dbgctrl: Volatile<u8>,
    pub(crate) calib: Volatile<u8>,
    pub(crate) clksel: Volatile<u8>,
    pub(crate) cnt: Volatile<u16>,
    pub(crate) per: Volatile<u16>,
    pub(crate) cmp: Volatile<u16>,
    res_1: u8,
    res_2: u8,
    pub(crate) pitctrla: Volatile<u8>,
    pub(crate) pitstatus: VolatileBitField,
    pub(crate) pitintctrl: VolatileBitField,
    pub(crate) pitintflags: VolatileBitField,
    pub(crate) pitdbgctrl: Volatile<u8>
  }

  pub enum RtcPitPeriod {
    Cyc4,
    Cyc8,
    Cyc16,
    Cyc32,
    Cyc64,
    Cyc128,
    Cyc256,
    Cyc512,
    Cyc1024,
    Cyc2048,
    Cyc4096,
    Cyc8192,
    Cyc16384,
    Cyc32768
  }

  pub struct AvrRealTimeCounter {
    pub(crate) interrupt_handler: Cell<TimerIsrCallback>,
    pub(crate) interrupt_period: RtcPitPeriod,
    pub(crate) rtc: MutDeviceRef<AvrRealTimeCounterControl>,
    pub(crate) mode: TimerMode
  }

  impl From<u16> for RtcPitPeriod {
    fn from(val: u16) -> Self {
      match val {
        4 => RtcPitPeriod::Cyc4,
        8 => RtcPitPeriod::Cyc8,
        16 => RtcPitPeriod::Cyc16,
        32 => RtcPitPeriod::Cyc32,
        64 => RtcPitPeriod::Cyc64,
        128 => RtcPitPeriod::Cyc128,
        256 => RtcPitPeriod::Cyc256,
        512 => RtcPitPeriod::Cyc512,
        1024 => RtcPitPeriod::Cyc1024,
        2048 => RtcPitPeriod::Cyc2048,
        4096 => RtcPitPeriod::Cyc4096,
        8192 => RtcPitPeriod::Cyc8192,
        16384 => RtcPitPeriod::Cyc16384,
        32768 => RtcPitPeriod::Cyc32768,
        _ => avr_oxide::oserror::halt(avr_oxide::oserror::OsError::BadParams)
      }
    }
  }

  impl RtcTimerCalibration for AvrRealTimeCounter {
    /// Set the clock source and calibration for this RTC device.  Note that
    /// this function will also disable the clock until the next time you
    /// set it running (with, for example, the start() method :-).)
    fn set_clock_calibration(&mut self, source: RtcSource, calibration: RtcCalibration, prescaler: RtcPrescaler) {
      interrupt::isolated(|isotoken|{
        let rtc = self.rtc.borrow_mut(isotoken);

        // Wait for clock control register to not be busy
        while rtc.status.is_set(BitIndex::bit_c(0)) {}

        rtc.ctrla.write(match prescaler {
          RtcPrescaler::Div1 => 0x00,
          RtcPrescaler::Div2 => 0x01,
          RtcPrescaler::Div4 => 0x02,
          RtcPrescaler::Div8 => 0x03,
          RtcPrescaler::Div16 => 0x04,
          RtcPrescaler::Div32 => 0x05,
          RtcPrescaler::Div64 => 0x06,
          RtcPrescaler::Div128 => 0x07,
          RtcPrescaler::Div256 => 0x08,
          RtcPrescaler::Div512 => 0x09,
          RtcPrescaler::Div1024 => 0x0a,
          RtcPrescaler::Div2048 => 0x0b,
          RtcPrescaler::Div4096 => 0x0c,
          RtcPrescaler::Div8192 => 0x0d,
          RtcPrescaler::Div16384 => 0x0e,
          RtcPrescaler::Div32768 => 0x0f,
        } << 3);
        rtc.clksel.write(match source {
          RtcSource::Int32k   => 0x00,
          RtcSource::Int1k    => 0x01,
          RtcSource::TOsc32k  => 0x02,
          RtcSource::External => 0x03
        });
        rtc.calib.write(match calibration {
          RtcCalibration::Fast(val) => {
            val & 0b01111111
          },
          RtcCalibration::Slow(val) => {
            0b10000000 | (val & 0b01111111)
          }
        });
      });
    }
  }
  impl TimerControl for AvrRealTimeCounter {
    /**
     * The RTC implementation of TimerControl handles periodic interrupts
     * in a special way - it uses hardware support to count RTC events
     * before generating interrupts instead of a software counter.  This
     * makes it more CPU and energy efficient than using one of the general
     * purpose timers, but has the side effect that only certain values for
     * period are acceptable, specifically:
     *    4,8,16,32,64,128,256,512,1024,2048,4096,8192,16384,32768
     */
    fn set_interrupt_period(&mut self, period: u16) {
      interrupt::isolated(|_isotoken|{
        self.interrupt_period = period.into();
      });
    }

    fn set_mode(&mut self, mode: TimerMode) {
      interrupt::isolated(|_isotoken|{
        self.mode = mode;
      });
    }

    fn set_count_max(&mut self, _max: u16) {
      todo!()
    }

    fn start(&self, handler: TimerIsrCallback) {
      interrupt::isolated(|isotoken|{
        let rtc = self.rtc.borrow_mut(isotoken);

        // Wait for clock control register to not be busy
        while rtc.status.is_set(BitIndex::bit_c(0)) {}

        // Set interrupt handler and enable if necessary
        self.interrupt_handler.replace(handler);

        if handler.is_nop() {
          rtc.pitintctrl.clr_all();
        } else {
          // Wait for the periodic interrupt control register to not be busy
          while rtc.pitstatus.is_set(BitIndex::bit_c(0)) {}

          rtc.pitctrla.write(match self.interrupt_period {
              RtcPitPeriod::Cyc4 => 0x01,
              RtcPitPeriod::Cyc8 => 0x02,
              RtcPitPeriod::Cyc16 => 0x03,
              RtcPitPeriod::Cyc32 => 0x04,
              RtcPitPeriod::Cyc64 => 0x05,
              RtcPitPeriod::Cyc128 => 0x06,
              RtcPitPeriod::Cyc256 => 0x07,
              RtcPitPeriod::Cyc512 => 0x08,
              RtcPitPeriod::Cyc1024 => 0x09,
              RtcPitPeriod::Cyc2048 => 0x0a,
              RtcPitPeriod::Cyc4096 => 0x0b,
              RtcPitPeriod::Cyc8192 => 0x0c,
              RtcPitPeriod::Cyc16384 => 0x0d,
              RtcPitPeriod::Cyc32768 => 0x0e,

            } << 3 | 0x01);
          rtc.pitintctrl.exc_set(BitIndex::bit_c(0));
        }

        // Flags: Run In Standby, Enable Correction, Enable RTC
        rtc.ctrla |= 0b10000101;

      });
    }

    fn stop(&self) {
      interrupt::isolated(|isotoken|{
        let rtc = self.rtc.borrow_mut(isotoken);

        rtc.ctrla &= 0b01111000;
      });
    }

    fn get_count(&self) -> u16 {
      todo!()
    }

    fn reset_count(&mut self) {
      todo!()
    }
  }

  impl AvrRealTimeCounter {
    pub(crate) fn call_interrupt(&self, isotoken: Isolated, source: TimerIdentity, ticks: u16) {
      let continue_running = isr_cb_invoke!(isotoken, self.interrupt_handler.get(), source, ticks);

      if !continue_running {
        self.stop();
      }
    }
    pub(crate) unsafe fn clear_interrupt(&self, isotoken: Isolated) {
      let rtc = self.rtc.borrow_mut(isotoken);

      rtc.pitintflags.exc_set(BitIndex::bit_c(0));
    }
  }

  #[doc(hidden)]
  #[macro_export]
  macro_rules! atmel_rtc {
    ($rtcref:expr, $timersrc:expr, $isr:expr) => {
      use avr_oxide::hal::generic::timer::{ TimerMode, TimerIsrCallback };
      use avr_oxide::hal::generic::timer::base::{ AvrRealTimeCounterControl, AvrRealTimeCounter, RtcPitPeriod };
      use avr_oxide::hal::generic::MutDeviceRef;
      use avr_oxide::mut_singleton_explicit_init;
      use core::cell::Cell;


      pub type TimerImpl = AvrRealTimeCounter;

      mut_singleton_explicit_init!(
        AvrRealTimeCounter,
        __INSTANCE,
        initialise, instance, instance_isolated,
        AvrRealTimeCounter {
          interrupt_handler: Cell::new(TimerIsrCallback::Nop(false)),
          interrupt_period: RtcPitPeriod::Cyc4,
          rtc: MutDeviceRef::new($rtcref),
          mode: TimerMode::Periodic
        });

      #[oxide_macros::interrupt(isr=$isr)]
      fn usart_timer_interrupt(isotoken: avr_oxide::concurrency::Isolated) {
        let avrrtc = instance_isolated(isotoken);

        avrrtc.call_interrupt(isotoken, $timersrc, 1);
        avrrtc.clear_interrupt(isotoken);
      }
    }
  }
}

#[cfg(not(target_arch="avr"))]
pub mod base {
  use crate::concurrency::Isolated;
  use avr_oxide::hal::generic::timer::{TimerIsrCallback, TimerMode, TimerControl, TimerIdentity, RtcTimerCalibration, RtcSource, RtcCalibration, RtcPrescaler};
  use avr_oxide::isr_cb_invoke;

  #[repr(C)]
  pub struct DummyTypeBTimerControl {
  }

  pub trait DummyTCB {
    fn enable(&mut self);
    fn disable(&mut self);
    fn enable_interrupt(&mut self);
    fn clear_interrupt(&mut self);
    fn mask_interrupt(&mut self);
    fn set_top(&mut self, top: u16);
    fn set_periodic_mode(&mut self);
  }

  impl DummyTCB for DummyTypeBTimerControl {
    fn enable(&mut self) {
      println!("*** TCB: Enabled");
    }

    fn disable(&mut self) {
      println!("*** TCB: Disabled");
    }

    fn enable_interrupt(&mut self) {
      println!("*** TCB: Interrupts enabled");
    }

    fn clear_interrupt(&mut self) {
      println!("*** TCB: Interrupts cleared");
    }

    fn mask_interrupt(&mut self) {
      println!("*** TCB: Interrupts masked");
    }

    fn set_top(&mut self, top: u16) {
      println!("*** TCB: Counter top set to {}", top);
    }

    #[inline(always)]
    fn set_periodic_mode(&mut self) {
      println!("*** TCB: Set to periodic mode");
    }
  }


  #[allow(dead_code)]
  pub struct DummyTimer<T>
    where
      T: 'static + DummyTCB
  {
    pub(crate) interrupt_handler: TimerIsrCallback,
    pub(crate) interrupt_period: u16,
    pub(crate) tcb: T,
    pub(crate) count_max: u16,
    pub(crate) mode: TimerMode
  }

  impl<T> TimerControl for DummyTimer<T>
    where
      T: DummyTCB
  {
    fn set_interrupt_period(&mut self, period: u16) {
      println!("*** TCB: Set to interrupt every {} cycles", period);
    }

    fn set_mode(&mut self, _mode: TimerMode) {
      println!("*** TCB: Set timer mode");
    }

    fn set_count_max(&mut self, max: u16) {
      println!("*** TCB: Set count_max to {}", max);
    }

    fn start(&self, handler: TimerIsrCallback) {
      println!("*** TCB: Set handler to {:?}", handler);
    }

    fn stop(&self) {
      println!("*** TCB: Stop interrupts");
    }

    fn get_count(&self) -> u16 {
      todo!()
    }

    fn reset_count(&mut self) {
      todo!()
    }
  }

  impl<T> DummyTimer<T>
    where
      T: DummyTCB
  {
    #[allow(dead_code)]
    pub(crate) fn call_interrupt(&mut self, isotoken: Isolated, source: TimerIdentity, ticks: u16) {
      let continue_running = isr_cb_invoke!(isotoken, self.interrupt_handler, source, ticks);

      if !continue_running {
        self.tcb.disable();
      }
    }

    #[allow(dead_code)]
    pub(crate) fn interrupt_period(&self) -> u16 {
      self.interrupt_period
    }
  }

  #[doc(hidden)]
  #[macro_export]
  macro_rules! atmel_tcb {
    ($tcbref:expr, $timersrc:expr, $isr:expr) => {
      use avr_oxide::hal::generic::timer::{ TimerMode, TimerIsrCallback };
      use avr_oxide::hal::generic::timer::base::{ DummyTimer, DummyTypeBTimerControl };

      pub type TimerImpl = DummyTimer<DummyTypeBTimerControl>;

      static mut INSTANCE: DummyTimer<DummyTypeBTimerControl> = DummyTimer {
        interrupt_handler: TimerIsrCallback::Nop(false),
        interrupt_period: 0,
        tcb: DummyTypeBTimerControl {},
        count_max: 0,
        mode: TimerMode::Periodic
      };

      pub fn initialise(){
      }

      pub fn instance() -> &'static mut TimerImpl {
        unsafe {
          &mut INSTANCE
        }
      }
      pub fn instance_isolated(_isotoken: avr_oxide::concurrency::Isolated) -> &'static mut TimerImpl {
        unsafe {
          &mut INSTANCE
        }
      }
    }
  }

  pub enum RtcPitPeriod {
    Cyc4,
    Cyc8,
    Cyc16,
    Cyc32,
    Cyc64,
    Cyc128,
    Cyc256,
    Cyc512,
    Cyc1024,
    Cyc2048,
    Cyc4096,
    Cyc8192,
    Cyc16384,
    Cyc32768
  }


  pub struct DummyRealTimeCounter {
    pub(crate) interrupt_handler: TimerIsrCallback,
    pub(crate) interrupt_period: RtcPitPeriod,
    pub(crate) mode: TimerMode
  }

  impl From<u16> for RtcPitPeriod {
    fn from(val: u16) -> Self {
      match val {
        4 => RtcPitPeriod::Cyc4,
        8 => RtcPitPeriod::Cyc8,
        16 => RtcPitPeriod::Cyc16,
        32 => RtcPitPeriod::Cyc32,
        64 => RtcPitPeriod::Cyc64,
        128 => RtcPitPeriod::Cyc128,
        256 => RtcPitPeriod::Cyc256,
        512 => RtcPitPeriod::Cyc512,
        1024 => RtcPitPeriod::Cyc1024,
        2048 => RtcPitPeriod::Cyc2048,
        4096 => RtcPitPeriod::Cyc4096,
        8192 => RtcPitPeriod::Cyc8192,
        16384 => RtcPitPeriod::Cyc16384,
        32768 => RtcPitPeriod::Cyc32768,
        _ => avr_oxide::oserror::halt(avr_oxide::oserror::OsError::BadParams)
      }
    }
  }

  impl RtcTimerCalibration for DummyRealTimeCounter {
    /// Set the clock source and calibration for this RTC device.  Note that
    /// this function will also disable the clock until the next time you
    /// set it running (with, for example, the start() method :-).)
    fn set_clock_calibration(&mut self, source: RtcSource, calibration: RtcCalibration, prescaler: RtcPrescaler) {
      println!("RTC calibration set");
    }
  }
  impl TimerControl for DummyRealTimeCounter {
    /**
     * The RTC implementation of TimerControl handles periodic interrupts
     * in a special way - it uses hardware support to count RTC events
     * before generating interrupts instead of a software counter.  This
     * makes it more CPU and energy efficient than using one of the general
     * purpose timers, but has the side effect that only certain values for
     * period are acceptable, specifically:
     *    4,8,16,32,64,128,256,512,1024,2048,4096,8192,16384,32768
     */
    fn set_interrupt_period(&mut self, period: u16) {
      let rtcperiod : RtcPitPeriod = period.into();

      println!("*** RTC: Set to interrupt every {} cycles", period);
    }

    fn set_mode(&mut self, mode: TimerMode) {
      println!("*** TCB: Set time mode");
    }

    fn set_count_max(&mut self, _max: u16) {
      todo!()
    }

    fn start(&self, handler: TimerIsrCallback) {
      println!("*** RTC: Set handler to {:?}", handler);
    }

    fn stop(&self) {
      println!("*** RTC: stop()");
    }

    fn get_count(&self) -> u16 {
      todo!()
    }

    fn reset_count(&mut self) {
      todo!()
    }
  }

  #[doc(hidden)]
  #[macro_export]
  macro_rules! atmel_rtc {
    ($rtcref:expr, $timersrc:expr, $isr:expr) => {
      use avr_oxide::hal::generic::timer::{ TimerMode, TimerIsrCallback };
      use avr_oxide::hal::generic::timer::base::{ DummyRealTimeCounter, RtcPitPeriod };

      use avr_oxide::mut_singleton_explicit_init;

      pub type TimerImpl = DummyRealTimeCounter;

      mut_singleton_explicit_init!(
        DummyRealTimeCounter,
        __INSTANCE,
        initialise, instance, instance_isolated,
        DummyRealTimeCounter {
          interrupt_handler: TimerIsrCallback::Nop(false),
          interrupt_period: RtcPitPeriod::Cyc4,
          mode: TimerMode::Periodic
        });
    }
  }
}