Skip to main content

uf_dshot/
command.rs

1use core::num::NonZeroU8;
2use core::time::Duration;
3
4const FRAME_BITS: usize = 16;
5const CRC_MASK_4BIT: u16 = 0x0F;
6// DShot reserves 0..=47 for commands; throttle starts at 48.
7const THROTTLE_VALUE_OFFSET: u16 = 48;
8const THROTTLE_MAX_RAW: u16 = 1999;
9
10#[derive(Copy, Clone, Debug, PartialEq, Eq)]
11#[cfg_attr(feature = "defmt", derive(defmt::Format))]
12pub enum Command {
13    MotorStop = 0,
14    /// Wait at least 260ms before next command.
15    Beep1,
16    /// Wait at least 260ms before next command.
17    Beep2,
18    /// Wait at least 260ms before next command.
19    Beep3,
20    /// Wait at least 260ms before next command.
21    Beep4,
22    /// Wait at least 260ms before next command.
23    Beep5,
24    /// Wait at least 12ms before next command.
25    EscInfo,
26    /// Needs 6 transmissions.
27    SpinDirection1,
28    /// Needs 6 transmissions.
29    SpinDirection2,
30    /// Needs 6 transmissions.
31    ThreeDModeOn,
32    /// Needs 6 transmissions.
33    ThreeDModeOff,
34    SettingsRequest,
35    /// Needs 6 transmissions. Wait at least 35ms before next command.
36    SettingsSave,
37    /// Needs 6 transmissions.
38    ExtendedTelemetryEnable,
39    /// Needs 6 transmissions.
40    ExtendedTelemetryDisable,
41
42    // 15-19 are unassigned.
43    /// Needs 6 transmissions.
44    SpinDirectionNormal = 20,
45    /// Needs 6 transmissions.
46    SpinDirectionReversed,
47    Led0On,
48    Led1On,
49    Led2On,
50    Led3On,
51    Led0Off,
52    Led1Off,
53    Led2Off,
54    Led3Off,
55    AudioStreamModeToggle,
56    SilentModeToggle,
57    /// Needs 6 transmissions. Enables individual signal line commands.
58    SignalLineTelemetryEnable,
59    /// Needs 6 transmissions. Disables individual signal line commands.
60    SignalLineTelemetryDisable,
61    /// Needs 6 transmissions. Enables individual signal line commands.
62    SignalLineContinuousERPMTelemetry,
63    /// Needs 6 transmissions. Enables individual signal line commands.
64    SignalLineContinuousERPMPeriodTelemetry,
65
66    // 36-41 are unassigned.
67    /// 1ÂșC per LSB.
68    SignalLineTemperatureTelemetry = 42,
69    /// 10mV per LSB, 40.95V max.
70    SignalLineVoltageTelemetry,
71    /// 100mA per LSB, 409.5A max.
72    SignalLineCurrentTelemetry,
73    /// 10mAh per LSB, 40.95Ah max.
74    SignalLineConsumptionTelemetry,
75    /// 100erpm per LSB, 409500erpm max.
76    SignalLineERPMTelemetry,
77    /// 16us per LSB, 65520us max.
78    SignalLineERPMPeriodTelemetry,
79}
80
81#[derive(Debug, Copy, Clone, PartialEq, Eq)]
82#[cfg_attr(feature = "defmt", derive(defmt::Format))]
83pub struct CommandTiming {
84    min_gap: Duration,
85    repeat_count: NonZeroU8,
86}
87
88impl CommandTiming {
89    pub const fn min_gap(self) -> Duration {
90        self.min_gap
91    }
92
93    pub const fn repeat_count(self) -> NonZeroU8 {
94        self.repeat_count
95    }
96}
97
98impl Command {
99    pub const fn min_repetitions(self) -> u8 {
100        match self {
101            Command::SpinDirection1
102            | Command::SpinDirection2
103            | Command::ThreeDModeOn
104            | Command::ThreeDModeOff
105            | Command::SettingsSave
106            | Command::ExtendedTelemetryEnable
107            | Command::ExtendedTelemetryDisable
108            | Command::SpinDirectionNormal
109            | Command::SpinDirectionReversed
110            | Command::SignalLineTelemetryEnable
111            | Command::SignalLineTelemetryDisable
112            | Command::SignalLineContinuousERPMTelemetry
113            | Command::SignalLineContinuousERPMPeriodTelemetry => {
114                // Protocol docs often mention 6 repeats for these commands.
115                // We intentionally use 10 as a conservative policy, similar to Betaflight.
116                10
117            }
118            _ => 1,
119        }
120    }
121
122    pub const fn min_delay_us(self) -> u32 {
123        match self {
124            Command::Beep1 | Command::Beep2 | Command::Beep3 | Command::Beep4 | Command::Beep5 => {
125                260_000
126            }
127            Command::EscInfo => 12_000,
128            Command::SettingsSave => 35_000,
129            _ => 0,
130        }
131    }
132
133    pub const fn exec_policy(self) -> CommandTiming {
134        let repeat_count = match NonZeroU8::new(self.min_repetitions()) {
135            Some(v) => v,
136            None => unreachable!(),
137        };
138
139        CommandTiming {
140            min_gap: Duration::from_micros(self.min_delay_us() as u64),
141            repeat_count,
142        }
143    }
144}
145
146#[derive(Copy, Clone, Debug, PartialEq, Eq)]
147#[cfg_attr(feature = "defmt", derive(defmt::Format))]
148pub enum ThrottleError {
149    OutOfRange { raw: u16 },
150}
151
152#[derive(Copy, Clone, Debug, PartialEq, Eq)]
153#[cfg_attr(feature = "defmt", derive(defmt::Format))]
154pub enum DshotMode {
155    Standard,
156    Bidirectional,
157}
158
159#[derive(Copy, Clone, Debug, PartialEq, Eq)]
160#[cfg_attr(feature = "defmt", derive(defmt::Format))]
161pub struct DshotTx {
162    mode: DshotMode,
163    request_separate_wire_telemetry: bool,
164}
165
166impl DshotTx {
167    pub const fn standard() -> Self {
168        Self {
169            mode: DshotMode::Standard,
170            request_separate_wire_telemetry: false,
171        }
172    }
173
174    pub const fn bidirectional() -> Self {
175        Self {
176            mode: DshotMode::Bidirectional,
177            request_separate_wire_telemetry: false,
178        }
179    }
180
181    pub const fn mode(mode: DshotMode) -> Self {
182        match mode {
183            DshotMode::Standard => Self::standard(),
184            DshotMode::Bidirectional => Self::bidirectional(),
185        }
186    }
187
188    pub const fn dshot_mode(self) -> DshotMode {
189        self.mode
190    }
191
192    pub const fn with_telemetry_request(mut self, enabled: bool) -> Self {
193        if matches!(self.mode, DshotMode::Standard) {
194            self.request_separate_wire_telemetry = enabled;
195        }
196        self
197    }
198
199    pub const fn telemetry_request(self) -> bool {
200        match self.mode {
201            DshotMode::Standard => self.request_separate_wire_telemetry,
202            DshotMode::Bidirectional => true,
203        }
204    }
205
206    pub fn throttle(self, raw: u16) -> Result<EncodedFrame, ThrottleError> {
207        if raw > THROTTLE_MAX_RAW {
208            return Err(ThrottleError::OutOfRange { raw });
209        }
210        Ok(self.encode_raw_value(raw + THROTTLE_VALUE_OFFSET, None))
211    }
212
213    pub fn throttle_clamped(self, raw: u16) -> EncodedFrame {
214        self.encode_raw_value(raw.min(THROTTLE_MAX_RAW) + THROTTLE_VALUE_OFFSET, None)
215    }
216
217    pub fn throttle_with_telemetry_request(
218        self,
219        raw: u16,
220        enabled: bool,
221    ) -> Result<EncodedFrame, ThrottleError> {
222        if raw > THROTTLE_MAX_RAW {
223            return Err(ThrottleError::OutOfRange { raw });
224        }
225        Ok(self.encode_raw_value(raw + THROTTLE_VALUE_OFFSET, Some(enabled)))
226    }
227
228    pub fn command(self, command: Command) -> EncodedFrame {
229        self.encode_raw_value(command as u16, None)
230    }
231
232    fn encode_raw_value(self, raw_value: u16, telemetry_override: Option<bool>) -> EncodedFrame {
233        let telemetry_bit = match self.mode {
234            DshotMode::Standard => {
235                telemetry_override.unwrap_or(self.request_separate_wire_telemetry)
236            }
237            DshotMode::Bidirectional => true,
238        };
239
240        let data_12 = encode_data_12(raw_value, telemetry_bit);
241        let base = base_crc(data_12);
242        let crc_4 = match self.mode {
243            DshotMode::Standard => base,
244            DshotMode::Bidirectional => (!base) & 0x0F,
245        };
246
247        EncodedFrame {
248            payload: (data_12 << 4) | u16::from(crc_4),
249        }
250    }
251}
252
253#[derive(Copy, Clone, Debug, PartialEq, Eq)]
254#[cfg_attr(feature = "defmt", derive(defmt::Format))]
255pub struct EncodedFrame {
256    pub payload: u16,
257}
258
259#[derive(Copy, Clone, Debug, PartialEq, Eq)]
260#[cfg_attr(feature = "defmt", derive(defmt::Format))]
261pub struct WaveformTiming {
262    pub period_ticks: u16,
263    pub bit0_high_ticks: u16,
264    pub bit1_high_ticks: u16,
265}
266
267#[derive(Copy, Clone, Debug, PartialEq, Eq)]
268#[cfg_attr(feature = "defmt", derive(defmt::Format))]
269pub struct WaveformTicks {
270    pub bit_high_ticks: [u16; 16],
271    /// Optional trailing slot value for backends that append one explicit low reset period.
272    pub reset_low_ticks: Option<u16>,
273}
274
275#[derive(Copy, Clone, Debug, PartialEq, Eq)]
276#[cfg_attr(feature = "defmt", derive(defmt::Format))]
277pub enum DshotSpeed {
278    Dshot150,
279    Dshot300,
280    Dshot600,
281}
282
283#[derive(Copy, Clone, Debug, PartialEq, Eq)]
284#[cfg_attr(feature = "defmt", derive(defmt::Format))]
285pub struct FrameTimingHints {
286    pub nominal_bitrate_hz: u32,
287    pub min_frame_period_us: u16,
288}
289
290impl DshotSpeed {
291    pub const fn timing_hints(self) -> FrameTimingHints {
292        match self {
293            DshotSpeed::Dshot150 => FrameTimingHints {
294                nominal_bitrate_hz: 150_000,
295                min_frame_period_us: 107,
296            },
297            DshotSpeed::Dshot300 => FrameTimingHints {
298                nominal_bitrate_hz: 300_000,
299                min_frame_period_us: 54,
300            },
301            DshotSpeed::Dshot600 => FrameTimingHints {
302                nominal_bitrate_hz: 600_000,
303                min_frame_period_us: 27,
304            },
305        }
306    }
307}
308
309impl EncodedFrame {
310    pub const fn data_12(&self) -> u16 {
311        self.payload >> 4
312    }
313
314    pub const fn crc_4(&self) -> u8 {
315        (self.payload & CRC_MASK_4BIT) as u8
316    }
317
318    pub fn bits_msb_first(&self) -> [bool; 16] {
319        let mut bits = [false; FRAME_BITS];
320        for (i, bit) in bits.iter_mut().enumerate() {
321            *bit = ((self.payload >> (FRAME_BITS - 1 - i)) & 1) != 0;
322        }
323        bits
324    }
325
326    pub fn to_waveform_ticks(
327        &self,
328        timing: WaveformTiming,
329        with_reset_slot: bool,
330    ) -> WaveformTicks {
331        let bits = self.bits_msb_first();
332        let mut bit_high_ticks = [0u16; FRAME_BITS];
333        for (tick, bit) in bit_high_ticks.iter_mut().zip(bits.iter()) {
334            *tick = if *bit {
335                timing.bit1_high_ticks
336            } else {
337                timing.bit0_high_ticks
338            };
339        }
340
341        WaveformTicks {
342            bit_high_ticks,
343            reset_low_ticks: if with_reset_slot { Some(0) } else { None },
344        }
345    }
346}
347
348fn encode_data_12(raw_value: u16, telemetry_request: bool) -> u16 {
349    (raw_value << 1) | u16::from(telemetry_request)
350}
351
352fn base_crc(data_12: u16) -> u8 {
353    ((data_12 ^ (data_12 >> 4) ^ (data_12 >> 8)) & CRC_MASK_4BIT) as u8
354}
355
356#[cfg(test)]
357mod tests {
358    use super::*;
359
360    #[test]
361    fn throttle_checked_and_clamped() {
362        assert_eq!(
363            DshotTx::bidirectional().throttle(2000),
364            Err(ThrottleError::OutOfRange { raw: 2000 })
365        );
366        assert_eq!(
367            DshotTx::bidirectional().throttle_clamped(5000).data_12(),
368            0xFFF
369        );
370    }
371
372    #[test]
373    fn command_metadata() {
374        assert_eq!(Command::Beep1.min_delay_us(), 260_000);
375        assert_eq!(Command::Beep1.min_repetitions(), 1);
376        assert_eq!(Command::SettingsSave.min_delay_us(), 35_000);
377        assert_eq!(Command::SettingsSave.min_repetitions(), 10);
378    }
379
380    #[test]
381    fn dshot_crc_vector() {
382        let frame = DshotTx::standard().throttle(1000).unwrap();
383        assert_eq!(frame.payload, 0x830B);
384        assert_eq!(frame.data_12(), 0x830);
385        assert_eq!(frame.crc_4(), 0xB);
386    }
387
388    #[test]
389    fn dshot_crc_with_telemetry_request_vector() {
390        let frame = DshotTx::standard()
391            .with_telemetry_request(true)
392            .throttle(1000)
393            .unwrap();
394        assert_eq!(frame.payload, 0x831A);
395        assert_eq!(frame.data_12(), 0x831);
396        assert_eq!(frame.crc_4(), 0xA);
397    }
398
399    #[test]
400    fn bidir_inverted_crc_vector() {
401        let frame = DshotTx::bidirectional().throttle(1000).unwrap();
402        assert_eq!(frame.payload, 0x8315);
403        assert_eq!(frame.data_12(), 0x831);
404        assert_eq!(frame.crc_4(), 0x5);
405    }
406
407    #[test]
408    fn throttle_zero_does_not_overlap_max_command() {
409        let throttle_zero = DshotTx::standard().throttle(0).unwrap().data_12();
410        let max_command = DshotTx::standard()
411            .command(Command::SignalLineERPMPeriodTelemetry)
412            .data_12();
413        assert_ne!(throttle_zero, max_command);
414    }
415
416    #[test]
417    fn bits_msb_first_order_matches_payload() {
418        let frame = DshotTx::standard()
419            .with_telemetry_request(true)
420            .command(Command::Beep1);
421        assert_eq!(frame.payload, 0x0033);
422        assert_eq!(
423            frame.bits_msb_first(),
424            [
425                false, false, false, false, false, false, false, false, false, false, true, true,
426                false, false, true, true,
427            ]
428        );
429    }
430
431    #[test]
432    fn waveform_ticks_mapping_and_reset_slot() {
433        let frame = DshotTx::standard()
434            .with_telemetry_request(true)
435            .command(Command::Beep1);
436        let timing = WaveformTiming {
437            period_ticks: 100,
438            bit0_high_ticks: 37,
439            bit1_high_ticks: 75,
440        };
441
442        let with_reset = frame.to_waveform_ticks(timing, true);
443        let no_reset = frame.to_waveform_ticks(timing, false);
444
445        assert_eq!(with_reset.reset_low_ticks, Some(0));
446        assert_eq!(no_reset.reset_low_ticks, None);
447        assert_eq!(with_reset.bit_high_ticks[10], 75);
448        assert_eq!(with_reset.bit_high_ticks[0], 37);
449    }
450
451    #[test]
452    fn speed_hints_are_consistent() {
453        let s150 = DshotSpeed::Dshot150.timing_hints();
454        let s300 = DshotSpeed::Dshot300.timing_hints();
455        let s600 = DshotSpeed::Dshot600.timing_hints();
456
457        assert!(s150.min_frame_period_us > s300.min_frame_period_us);
458        assert!(s300.min_frame_period_us > s600.min_frame_period_us);
459        assert!(s150.nominal_bitrate_hz < s300.nominal_bitrate_hz);
460        assert!(s300.nominal_bitrate_hz < s600.nominal_bitrate_hz);
461    }
462
463    #[test]
464    fn exec_policy_remains_derived_from_metadata() {
465        let policy = Command::EscInfo.exec_policy();
466        assert_eq!(policy.min_gap(), Duration::from_micros(12_000));
467        assert_eq!(policy.repeat_count().get(), 1);
468    }
469
470    #[test]
471    fn per_frame_standard_telemetry_override_works() {
472        let tx = DshotTx::standard().with_telemetry_request(false);
473        let no_telem = tx.throttle(1000).unwrap();
474        let with_telem = tx.throttle_with_telemetry_request(1000, true).unwrap();
475        assert_eq!(no_telem.data_12(), 0x830);
476        assert_eq!(with_telem.data_12(), 0x831);
477    }
478
479    #[test]
480    fn bidir_forces_telemetry_even_when_override_is_false() {
481        let tx = DshotTx::bidirectional();
482        let frame = tx.throttle_with_telemetry_request(1000, false).unwrap();
483        assert_eq!(frame.data_12(), 0x831);
484    }
485}