device-envoy-esp 0.1.0

Build ESP32 applications with composable device abstractions
Documentation
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
//! A device abstraction for hobby servos on ESP LEDC PWM.
//!
//! This module provides both direct servo control ([`servo!`](macro@crate::servo::servo)) and
//! servo animationl ([`servo_player!`](macro@crate::servo::servo_player)).
//!
//! Use [`servo!`] for a keyword-driven typed constructor.
//!
//! **After reading the examples below, see also:**
//!
//! - [`servo!`](macro@crate::servo::servo) — Direct servo control without animation support.
//! - [`servo_player!`](macro@crate::servo::servo_player) — Macro to generate a servo player struct
//!   type (includes syntax details). See [`ServoPlayerGenerated`](servo_player_generated::ServoPlayerGenerated)
//!   for a sample of a generated type.
//! - [`combine!`](macro@crate::servo::combine) & [`linear`] — Macro and function for creating
//!   complex motion sequences.
//! - [`Servo`] — Trait defining core methods and constants for direct servo control.
//! - [`ServoPlayer`] — Trait defining core methods and constants for animatable servos.
//!
#![doc = include_str!("../docs/how_servos_work.md")]
//!
//! This device abstraction, `servo_player`, adds a background software task around the hardware
//! control signal.
//!
//! # Controlling Multiple Servos
//!
//! Supports multiple servos, where each servo consumes one [LEDC](crate#glossary) timer resource and
//! one [LEDC](crate#glossary) channel resource. The macro-generated link-time ownership claims enforce
//! this exclusivity so duplicate timer/channel selections fail at link time.
//!
//! # Example: Basic Servo Control
//!
//! This example demonstrates basic servo control: moving to a position, relaxing,
//! and using animation. Here, the generated struct type is named `Servo11`.
//!
//! ```rust,no_run
//! # #![no_std]
//! # #![no_main]
//! # use esp_backtrace as _;
//! # use core::convert::Infallible;
//! use device_envoy_esp::{Result, init_and_start, servo::{Servo as _, servo}};
//! use embassy_time::{Duration, Timer};
//!
//! servo! {
//!     Servo11 {
//!         pin: GPIO11,
//!         timer: Timer0,
//!         channel: Channel0,
//!     }
//! }
//!
//! # #[esp_rtos::main]
//! # async fn main(_spawner: embassy_executor::Spawner) -> ! {
//! #     let err = inner_main().await.unwrap_err();
//! #     panic!("{err:?}");
//! # }
//! async fn inner_main() -> Result<Infallible> {
//!     init_and_start!(p, ledc: ledc);
//!     let servo11 = Servo11::new(&ledc, p.GPIO11)?;
//!     servo11.set_degrees(45);
//!     Timer::after(Duration::from_secs(1)).await;
//!     servo11.relax();
//!     core::future::pending().await
//! }
//! ```
//!
//! # Example: Multi-Step Animation
//!
//! This example combines 40 animation steps using `linear` and `combine!` to
//! sweep up, hold, sweep down, hold pattern. Here, the generated struct type is named
//! `ServoSweep`.
//!
//! ```rust,no_run
//! # #![no_std]
//! # #![no_main]
//! # use esp_backtrace as _;
//! # use core::convert::Infallible;
//! use device_envoy_esp::{Result, init_and_start, servo::{AtEnd, Servo as _, ServoPlayer as _, combine, linear, servo_player}};
//! use embassy_time::Duration;
//!
//! servo_player! {
//!     ServoSweep {
//!         pin: GPIO12,
//!         timer: Timer1,
//!         channel: Channel1,
//!         max_steps: 40,
//!     }
//! }
//!
//! # #[esp_rtos::main]
//! # async fn main(spawner: embassy_executor::Spawner) -> ! {
//! #     let err = inner_main(spawner).await.unwrap_err();
//! #     panic!("{err:?}");
//! # }
//! async fn inner_main(spawner: embassy_executor::Spawner) -> Result<Infallible> {
//!     init_and_start!(p, ledc: ledc);
//!     let servo_sweep = ServoSweep::new(&ledc, p.GPIO12, spawner)?;
//!     const STEPS: [(u16, Duration); 40] = combine!(
//!         linear::<19>(0, 180, Duration::from_secs(2)),
//!         [(180, Duration::from_millis(400))],
//!         linear::<19>(180, 0, Duration::from_secs(2)),
//!         [(0, Duration::from_millis(400))]
//!     );
//!     servo_sweep.animate(STEPS, AtEnd::Loop);
//!     core::future::pending().await
//! }
//! ```

use crate::Result;
use core::cell::RefCell;
pub use device_envoy_core::servo::{Direction, Servo};
use esp_hal::gpio::{DriveMode, interconnect::PeripheralOutput};
use esp_hal::ledc::{LowSpeed, channel, timer};
use esp_hal::ledc::{channel::ChannelHW, channel::ChannelIFace, timer::TimerIFace};
use esp_hal::time::Rate;
use static_cell::StaticCell;

#[doc(inline)]
pub use crate::combine;
#[doc(inline)]
pub use crate::servo_player::servo_player;
#[doc(hidden)]
pub use device_envoy_core::servo::{
    __servo_player_animate, __servo_player_hold, __servo_player_relax, __servo_player_set_degrees,
    device_loop,
};
pub use device_envoy_core::servo::{
    AtEnd, ServoPlayer, ServoPlayerHandle, ServoPlayerStatic, combine, linear,
};

/// Sample generated servo-player type documentation.
pub mod servo_player_generated {
    #[cfg(doc)]
    pub use crate::servo_player::servo_player_generated::*;
}

const SERVO_PERIOD_US: u32 = 20_000;
const SERVO_TIMER_DUTY_BITS: u32 = 14;

/// Default minimum pulse width for hobby servos (microseconds).
pub const SERVO_MIN_US_DEFAULT: u32 = 500;

/// Default maximum pulse width for hobby servos (microseconds).
pub const SERVO_MAX_US_DEFAULT: u32 = 2_500;

/// LEDC-backed servo static resources and motion configuration.
pub struct ServoStatic {
    timer: StaticCell<timer::Timer<'static, LowSpeed>>,
    channel: StaticCell<channel::Channel<'static, LowSpeed>>,
    timer_number: timer::Number,
    channel_number: channel::Number,
    min_us: u32,
    max_us: u32,
    max_degrees: u16,
    direction: Direction,
}

impl ServoStatic {
    /// Create static resources for one servo output.
    #[must_use]
    pub const fn new_static(
        timer_number: timer::Number,
        channel_number: channel::Number,
        min_us: u32,
        max_us: u32,
        max_degrees: u16,
        direction: Direction,
    ) -> Self {
        assert!(min_us < max_us, "min_us must be less than max_us");
        assert!(max_degrees > 0, "max_degrees must be positive");
        Self {
            timer: StaticCell::new(),
            channel: StaticCell::new(),
            timer_number,
            channel_number,
            min_us,
            max_us,
            max_degrees,
            direction,
        }
    }
}

/// A direct servo output using one LEDC timer and one LEDC channel.
///
/// This type is public only because `servo!` and `servo_player!` macro
/// expansions in downstream crates reference it.
#[doc(hidden)]
pub struct ServoEsp {
    channel: RefCell<&'static mut channel::Channel<'static, LowSpeed>>,
    min_us: u32,
    max_us: u32,
    max_degrees: u16,
    direction: Direction,
}

impl ServoEsp {
    /// Default maximum rotation range in degrees.
    pub const DEFAULT_MAX_DEGREES: u16 = <Self as Servo>::DEFAULT_MAX_DEGREES;

    /// Create a servo from static resources and a GPIO output pin.
    pub fn new(
        servo_static: &'static ServoStatic,
        ledc: &esp_hal::ledc::Ledc<'static>,
        pin: impl PeripheralOutput<'static>,
    ) -> Result<Self> {
        let timer = servo_static
            .timer
            .init(ledc.timer::<LowSpeed>(servo_static.timer_number));
        timer.configure(timer::config::Config {
            duty: timer::config::Duty::Duty14Bit,
            clock_source: timer::LSClockSource::APBClk,
            frequency: Rate::from_hz(50),
        })?;

        let channel = servo_static
            .channel
            .init(ledc.channel(servo_static.channel_number, pin));
        channel.configure(channel::config::Config {
            timer,
            duty_pct: 0,
            drive_mode: DriveMode::PushPull,
        })?;

        Ok(Self {
            channel: RefCell::new(channel),
            min_us: servo_static.min_us,
            max_us: servo_static.max_us,
            max_degrees: servo_static.max_degrees,
            direction: servo_static.direction,
        })
    }

    fn pulse_for_degrees(&self, degrees: u16) -> u32 {
        let pulse_span = self.max_us - self.min_us;
        self.min_us
            + (u32::from(degrees) * pulse_span + u32::from(self.max_degrees / 2))
                / u32::from(self.max_degrees)
    }

    fn degrees_to_duty(&self, degrees: u16) -> u32 {
        let pulse_us = self.pulse_for_degrees(degrees);
        let duty_range = 1u32 << SERVO_TIMER_DUTY_BITS;
        ((pulse_us * duty_range) + (SERVO_PERIOD_US / 2)) / SERVO_PERIOD_US
    }
}

impl Servo for ServoEsp {
    const DEFAULT_MAX_DEGREES: u16 = 180;

    /// Set position in degrees `0..=max_degrees`.
    fn set_degrees(&self, degrees: u16) {
        assert!(degrees <= self.max_degrees);
        let physical_degrees = match self.direction {
            Direction::Forward => degrees,
            Direction::Reverse => self.max_degrees - degrees,
        };
        let duty = self.degrees_to_duty(physical_degrees);
        self.channel.borrow_mut().set_duty_hw(duty);
    }

    /// Keep driving pulses at the last commanded angle.
    fn hold(&self) {}

    /// Stop driving pulses.
    fn relax(&self) {
        self.channel
            .borrow_mut()
            .set_duty(0)
            .expect("LEDC set_duty failed in Servo::relax");
    }
}

#[doc(hidden)]
pub use paste;

/// Macro to generate a direct-servo struct type (includes syntax details).
///
/// **See the [servo module documentation](mod@crate::servo) for usage examples.**
///
/// **Syntax:**
///
/// ```text
/// servo! {
///     <Name> {
///         pin: <pin_ident>,
///         timer: <timer_ident>,
///         channel: <channel_ident>,
///         min_us: <u32_expr>,         // optional
///         max_us: <u32_expr>,         // optional
///         max_degrees: <u16_expr>,    // optional
///         direction: <Direction_expr>, // optional
///     }
/// }
/// ```
///
/// **Required fields:**
///
/// - `pin` - GPIO pin for servo output
/// - `timer` - [LEDC](crate#glossary) timer resource
/// - `channel` - [LEDC](crate#glossary) channel resource
///
/// **Optional fields:**
///
/// - `min_us` - Minimum pulse width in microseconds for 0° (default: `500`)
/// - `max_us` - Maximum pulse width in microseconds for `max_degrees` (default: `2500`)
/// - `max_degrees` - Maximum servo angle in degrees (default: `180`)
/// - `direction` - Logical angle direction (`Direction::Forward` by default)
///
/// See the [servo module documentation](mod@crate::servo) for details and examples.
#[macro_export]
#[doc(hidden)]
macro_rules! servo {
    ($($tt:tt)*) => { $crate::__servo_impl! { $($tt)* } };
}
#[doc(inline)]
pub use servo;

/// Public for macro expansion in downstream crates.
#[doc(hidden)]
#[macro_export]
macro_rules! __servo_impl {
    (
        $name:ident {
            $($fields:tt)*
        }
    ) => {
        $crate::__servo_impl! {
            @__parse
            name: $name,
            pin: [],
            timer: [],
            channel: [],
            min_us: [],
            max_us: [],
            max_degrees: [],
            direction: [],
            fields: [ $($fields)* ]
        }
    };

    (@__parse
        name: $name:ident,
        pin: [],
        timer: [$($timer:ident)?],
        channel: [$($channel:ident)?],
        min_us: [$($min_us:expr)?],
        max_us: [$($max_us:expr)?],
        max_degrees: [$($max_degrees:expr)?],
        direction: [$($direction:expr)?],
        fields: [ pin: $pin:ident $(, $($rest:tt)*)? ]
    ) => {
        $crate::__servo_impl! {
            @__parse
            name: $name,
            pin: [$pin],
            timer: [$($timer)?],
            channel: [$($channel)?],
            min_us: [$($min_us)?],
            max_us: [$($max_us)?],
            max_degrees: [$($max_degrees)?],
            direction: [$($direction)?],
            fields: [ $($($rest)*)? ]
        }
    };
    (@__parse
        name: $name:ident,
        pin: [$_pin_seen:ident],
        timer: [$($timer:ident)?],
        channel: [$($channel:ident)?],
        min_us: [$($min_us:expr)?],
        max_us: [$($max_us:expr)?],
        max_degrees: [$($max_degrees:expr)?],
        direction: [$($direction:expr)?],
        fields: [ pin: $pin:ident $(, $($rest:tt)*)? ]
    ) => {
        compile_error!("servo! duplicate `pin` field");
    };

    (@__parse
        name: $name:ident,
        pin: [$($pin:ident)?],
        timer: [],
        channel: [$($channel:ident)?],
        min_us: [$($min_us:expr)?],
        max_us: [$($max_us:expr)?],
        max_degrees: [$($max_degrees:expr)?],
        direction: [$($direction:expr)?],
        fields: [ timer: $timer:ident $(, $($rest:tt)*)? ]
    ) => {
        $crate::__servo_impl! {
            @__parse
            name: $name,
            pin: [$($pin)?],
            timer: [$timer],
            channel: [$($channel)?],
            min_us: [$($min_us)?],
            max_us: [$($max_us)?],
            max_degrees: [$($max_degrees)?],
            direction: [$($direction)?],
            fields: [ $($($rest)*)? ]
        }
    };
    (@__parse
        name: $name:ident,
        pin: [$($pin:ident)?],
        timer: [$_timer_seen:ident],
        channel: [$($channel:ident)?],
        min_us: [$($min_us:expr)?],
        max_us: [$($max_us:expr)?],
        max_degrees: [$($max_degrees:expr)?],
        direction: [$($direction:expr)?],
        fields: [ timer: $timer:ident $(, $($rest:tt)*)? ]
    ) => {
        compile_error!("servo! duplicate `timer` field");
    };

    (@__parse
        name: $name:ident,
        pin: [$($pin:ident)?],
        timer: [$($timer:ident)?],
        channel: [],
        min_us: [$($min_us:expr)?],
        max_us: [$($max_us:expr)?],
        max_degrees: [$($max_degrees:expr)?],
        direction: [$($direction:expr)?],
        fields: [ channel: $channel:ident $(, $($rest:tt)*)? ]
    ) => {
        $crate::__servo_impl! {
            @__parse
            name: $name,
            pin: [$($pin)?],
            timer: [$($timer)?],
            channel: [$channel],
            min_us: [$($min_us)?],
            max_us: [$($max_us)?],
            max_degrees: [$($max_degrees)?],
            direction: [$($direction)?],
            fields: [ $($($rest)*)? ]
        }
    };
    (@__parse
        name: $name:ident,
        pin: [$($pin:ident)?],
        timer: [$($timer:ident)?],
        channel: [$_channel_seen:ident],
        min_us: [$($min_us:expr)?],
        max_us: [$($max_us:expr)?],
        max_degrees: [$($max_degrees:expr)?],
        direction: [$($direction:expr)?],
        fields: [ channel: $channel:ident $(, $($rest:tt)*)? ]
    ) => {
        compile_error!("servo! duplicate `channel` field");
    };

    (@__parse
        name: $name:ident,
        pin: [$($pin:ident)?],
        timer: [$($timer:ident)?],
        channel: [$($channel:ident)?],
        min_us: [],
        max_us: [$($max_us:expr)?],
        max_degrees: [$($max_degrees:expr)?],
        direction: [$($direction:expr)?],
        fields: [ min_us: $min_us:expr $(, $($rest:tt)*)? ]
    ) => {
        $crate::__servo_impl! {
            @__parse
            name: $name,
            pin: [$($pin)?],
            timer: [$($timer)?],
            channel: [$($channel)?],
            min_us: [$min_us],
            max_us: [$($max_us)?],
            max_degrees: [$($max_degrees)?],
            direction: [$($direction)?],
            fields: [ $($($rest)*)? ]
        }
    };
    (@__parse
        name: $name:ident,
        pin: [$($pin:ident)?],
        timer: [$($timer:ident)?],
        channel: [$($channel:ident)?],
        min_us: [$_min_us_seen:expr],
        max_us: [$($max_us:expr)?],
        max_degrees: [$($max_degrees:expr)?],
        direction: [$($direction:expr)?],
        fields: [ min_us: $min_us:expr $(, $($rest:tt)*)? ]
    ) => {
        compile_error!("servo! duplicate `min_us` field");
    };

    (@__parse
        name: $name:ident,
        pin: [$($pin:ident)?],
        timer: [$($timer:ident)?],
        channel: [$($channel:ident)?],
        min_us: [$($min_us:expr)?],
        max_us: [],
        max_degrees: [$($max_degrees:expr)?],
        direction: [$($direction:expr)?],
        fields: [ max_us: $max_us:expr $(, $($rest:tt)*)? ]
    ) => {
        $crate::__servo_impl! {
            @__parse
            name: $name,
            pin: [$($pin)?],
            timer: [$($timer)?],
            channel: [$($channel)?],
            min_us: [$($min_us)?],
            max_us: [$max_us],
            max_degrees: [$($max_degrees)?],
            direction: [$($direction)?],
            fields: [ $($($rest)*)? ]
        }
    };
    (@__parse
        name: $name:ident,
        pin: [$($pin:ident)?],
        timer: [$($timer:ident)?],
        channel: [$($channel:ident)?],
        min_us: [$($min_us:expr)?],
        max_us: [$_max_us_seen:expr],
        max_degrees: [$($max_degrees:expr)?],
        direction: [$($direction:expr)?],
        fields: [ max_us: $max_us:expr $(, $($rest:tt)*)? ]
    ) => {
        compile_error!("servo! duplicate `max_us` field");
    };

    (@__parse
        name: $name:ident,
        pin: [$($pin:ident)?],
        timer: [$($timer:ident)?],
        channel: [$($channel:ident)?],
        min_us: [$($min_us:expr)?],
        max_us: [$($max_us:expr)?],
        max_degrees: [],
        direction: [$($direction:expr)?],
        fields: [ max_degrees: $max_degrees:expr $(, $($rest:tt)*)? ]
    ) => {
        $crate::__servo_impl! {
            @__parse
            name: $name,
            pin: [$($pin)?],
            timer: [$($timer)?],
            channel: [$($channel)?],
            min_us: [$($min_us)?],
            max_us: [$($max_us)?],
            max_degrees: [$max_degrees],
            direction: [$($direction)?],
            fields: [ $($($rest)*)? ]
        }
    };
    (@__parse
        name: $name:ident,
        pin: [$($pin:ident)?],
        timer: [$($timer:ident)?],
        channel: [$($channel:ident)?],
        min_us: [$($min_us:expr)?],
        max_us: [$($max_us:expr)?],
        max_degrees: [$_max_degrees_seen:expr],
        direction: [$($direction:expr)?],
        fields: [ max_degrees: $max_degrees:expr $(, $($rest:tt)*)? ]
    ) => {
        compile_error!("servo! duplicate `max_degrees` field");
    };

    (@__parse
        name: $name:ident,
        pin: [$($pin:ident)?],
        timer: [$($timer:ident)?],
        channel: [$($channel:ident)?],
        min_us: [$($min_us:expr)?],
        max_us: [$($max_us:expr)?],
        max_degrees: [$($max_degrees:expr)?],
        direction: [$($direction:expr)?],
        fields: [ direction: $new_direction:expr $(, $($rest:tt)*)? ]
    ) => {
        $crate::__servo_impl! {
            @__parse
            name: $name,
            pin: [$($pin)?],
            timer: [$($timer)?],
            channel: [$($channel)?],
            min_us: [$($min_us)?],
            max_us: [$($max_us)?],
            max_degrees: [$($max_degrees)?],
            direction: [$new_direction],
            fields: [ $($($rest)*)? ]
        }
    };
    (@__parse
        name: $name:ident,
        pin: [$($pin:ident)?],
        timer: [$($timer:ident)?],
        channel: [$($channel:ident)?],
        min_us: [$($min_us:expr)?],
        max_us: [$($max_us:expr)?],
        max_degrees: [$($max_degrees:expr)?],
        direction: [$_direction_seen:expr],
        fields: [ direction: $direction:expr $(, $($rest:tt)*)? ]
    ) => {
        compile_error!("servo! duplicate `direction` field");
    };

    (@__parse
        name: $name:ident,
        pin: [$($pin:ident)?],
        timer: [$($timer:ident)?],
        channel: [$($channel:ident)?],
        min_us: [$($min_us:expr)?],
        max_us: [$($max_us:expr)?],
        max_degrees: [$($max_degrees:expr)?],
        direction: [$($direction:expr)?],
        fields: [ ]
    ) => {
        $crate::__servo_impl! {
            @__finish
            name: $name,
            pin: [$($pin)?],
            timer: [$($timer)?],
            channel: [$($channel)?],
            min_us: [$($min_us)?],
            max_us: [$($max_us)?],
            max_degrees: [$($max_degrees)?],
            direction: [$($direction)?]
        }
    };

    (@__parse
        name: $name:ident,
        pin: [$($pin:ident)?],
        timer: [$($timer:ident)?],
        channel: [$($channel:ident)?],
        min_us: [$($min_us:expr)?],
        max_us: [$($max_us:expr)?],
        max_degrees: [$($max_degrees:expr)?],
        direction: [$($direction:expr)?],
        fields: [ $field:ident : $($value:tt)+ ]
    ) => {
        compile_error!(
            "servo! unknown field; expected `pin`, `timer`, `channel`, `min_us`, `max_us`, `max_degrees`, or `direction`"
        );
    };

    (@__finish
        name: $name:ident,
        pin: [],
        timer: [$($timer:ident)?],
        channel: [$($channel:ident)?],
        min_us: [$($min_us:expr)?],
        max_us: [$($max_us:expr)?],
        max_degrees: [$($max_degrees:expr)?],
        direction: [$($direction:expr)?]
    ) => {
        compile_error!("servo! missing required `pin` field");
    };
    (@__finish
        name: $name:ident,
        pin: [$pin:ident],
        timer: [],
        channel: [$($channel:ident)?],
        min_us: [$($min_us:expr)?],
        max_us: [$($max_us:expr)?],
        max_degrees: [$($max_degrees:expr)?],
        direction: [$($direction:expr)?]
    ) => {
        compile_error!("servo! missing required `timer` field");
    };
    (@__finish
        name: $name:ident,
        pin: [$pin:ident],
        timer: [$timer:ident],
        channel: [],
        min_us: [$($min_us:expr)?],
        max_us: [$($max_us:expr)?],
        max_degrees: [$($max_degrees:expr)?],
        direction: [$($direction:expr)?]
    ) => {
        compile_error!("servo! missing required `channel` field");
    };
    (@__finish
        name: $name:ident,
        pin: [$pin:ident],
        timer: [$timer:ident],
        channel: [$channel:ident],
        min_us: [$($min_us:expr)?],
        max_us: [$($max_us:expr)?],
        max_degrees: [$($max_degrees:expr)?],
        direction: [$($direction:expr)?]
    ) => {
        $crate::servo::paste::paste! {
            pub struct $name;

            // Link-time ownership claims: duplicate timer or channel selection across the
            // final binary should fail the link with duplicate symbol errors.
            #[used]
            #[unsafe(no_mangle)]
            static [<__device_envoy_esp_ledc_timer_claim_ $timer:lower>]: u8 = 0;

            #[used]
            #[unsafe(no_mangle)]
            static [<__device_envoy_esp_ledc_channel_claim_ $channel:lower>]: u8 = 0;

            static [<$name:upper _SERVO_STATIC>]: [<$name Static>] = $name::new_static();

            pub struct [<$name Static>] {
                servo_static: $crate::servo::ServoStatic,
            }

            impl $name {
                #[must_use]
                pub const fn new_static() -> [<$name Static>] {
                    [<$name Static>] {
                        servo_static: $crate::servo::ServoStatic::new_static(
                            ::esp_hal::ledc::timer::Number::$timer,
                            ::esp_hal::ledc::channel::Number::$channel,
                            $crate::__servo_impl!(@min_us $($min_us)?),
                            $crate::__servo_impl!(@max_us $($max_us)?),
                            $crate::__servo_impl!(@max_degrees $($max_degrees)?),
                            $crate::__servo_impl!(@direction $($direction)?),
                        ),
                    }
                }

                pub fn new(
                    ledc: &::esp_hal::ledc::Ledc<'static>,
                    pin: ::esp_hal::peripherals::$pin<'static>,
                ) -> $crate::Result<$crate::servo::ServoEsp> {
                    $crate::servo::ServoEsp::new(&[<$name:upper _SERVO_STATIC>].servo_static, ledc, pin)
                }
            }
        }
    };

    (@min_us $min_us:expr) => { $min_us };
    (@min_us) => { $crate::servo::SERVO_MIN_US_DEFAULT };
    (@max_us $max_us:expr) => { $max_us };
    (@max_us) => { $crate::servo::SERVO_MAX_US_DEFAULT };
    (@max_degrees $max_degrees:expr) => { $max_degrees };
    (@max_degrees) => { $crate::servo::ServoEsp::DEFAULT_MAX_DEGREES };
    (@direction $direction:expr) => { $direction };
    (@direction) => { $crate::servo::Direction::Forward };
}