py32f030_hal 0.1.0

Peripheral Hal Crate for Puya's PY32F030 microcontroller
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
#[cfg(feature = "embassy")]
mod future;
mod hal;
mod pins;
mod types;

use crate::clock;
use crate::clock::peripheral::{
    PeripheralClockIndex, PeripheralIdToClockIndex, PeripheralInterrupt,
};
use crate::dma::{self, DmaChannel};
use crate::gpio::{self, AnyPin};
use crate::macro_def::pin_af_for_instance_def;
use crate::mcu::peripherals::DMA;
#[cfg(feature = "embassy")]
use crate::mode::Async;
use crate::mode::{Blocking, Mode};
use crate::syscfg::DmaChannelMap;
#[cfg(feature = "embassy")]
use core::future::poll_fn;
use core::marker::PhantomData;
#[cfg(feature = "embassy")]
use core::task::Poll;
use drop_move::DropGuard;
use embassy_hal_internal::{into_ref, Peripheral, PeripheralRef};
use enumset::{EnumSet, EnumSetType};
#[cfg(feature = "embassy")]
use future::EventFuture;
use hal::sealed;
use types::*;

pub trait Instance: Peripheral<P = Self> + sealed::Instance + 'static + Send {}

// 定义 串口的特殊引脚 trait
pin_af_for_instance_def!(TxPin, Instance);
pin_af_for_instance_def!(RxPin, Instance);
pin_af_for_instance_def!(RtsPin, Instance);
pin_af_for_instance_def!(CtsPin, Instance);

/// 串口的综合配置结构体
#[derive(Default)]
pub struct Config {
    pub baud_rate: BaudRate,
    pub stop_bit: StopBits,
    pub word_len: WordLen,
    pub parity: Parity,
    // pub hw_flow_ctrl: HwFlowCtrl,
    pub data_bits: DataBits,
    pub over_sampling: OverSampling,
    // pub mode: T,
}

/// 串口号定义
#[derive(Clone, Copy, PartialEq)]
pub enum Id {
    USART1,
    USART2,
}

// 为 usart1/2 实现 Instance 和 sealed::Instance trait
impl_sealed_peripheral_id!(USART1, USART1);
impl_sealed_peripheral_id!(USART2, USART2);

impl PeripheralIdToClockIndex for Id {
    fn clock(&self) -> PeripheralClockIndex {
        match *self {
            Self::USART1 => PeripheralClockIndex::USART1,
            Self::USART2 => PeripheralClockIndex::UART2,
        }
    }
}

impl PeripheralInterrupt for Id {
    fn interrupt(&self) -> PY32f030xx_pac::interrupt {
        match *self {
            Self::USART1 => PY32f030xx_pac::interrupt::USART1,
            Self::USART2 => PY32f030xx_pac::interrupt::USART2,
        }
    }
}

impl Id {
    // 返回串口 rx 和 tx 的 dma 映射值
    fn dma_channel_map(&self) -> (DmaChannelMap, DmaChannelMap) {
        match *self {
            Self::USART1 => (DmaChannelMap::USART1_RX, DmaChannelMap::USART1_TX),
            Self::USART2 => (DmaChannelMap::USART2_RX, DmaChannelMap::USART2_TX),
        }
    }
}

#[derive(EnumSetType)]
pub enum Event {
    /// 自动波特率错误标志
    ABRE,
    /// 自动波特率检测标志
    ABRF,
    /// CTS 标志
    CTS,
    /// 传输寄存器空标志
    TXE,
    /// 传送完成标志
    TC,
    /// 读数据寄存器不空标志
    RXNE,
    /// 空闲标志
    IDLE,
    /// Over 正常运行错误标志
    ORE,
    /// 噪声错误标志
    NE,
    /// 噪声错误标志
    FE,
    /// 校验值错误
    PE,
}

/// 串口接收处理的对象
pub struct UsartRx<'d, T: Instance, M: Mode> {
    // _p: PeripheralRef<'d, T>,
    _p: PhantomData<(T, M)>,
    _rxd: Option<PeripheralRef<'d, AnyPin>>,
    _rts: Option<PeripheralRef<'d, AnyPin>>,

    rx_dma: Option<DmaChannel<'d, DMA, M>>,
}

/// 串口发送对象
pub struct UsartTx<'d, T: Instance, M: Mode> {
    _p: PhantomData<(T, M)>,
    _txd: Option<PeripheralRef<'d, AnyPin>>,
    _cts: Option<PeripheralRef<'d, AnyPin>>,

    tx_dma: Option<DmaChannel<'d, DMA, M>>,
}

/// 串口对象
pub struct AnyUsart<'d, T: Instance, M: Mode> {
    pub rx: UsartRx<'d, T, M>,
    pub tx: UsartTx<'d, T, M>,
}

impl<'d, T: Instance, M: Mode> AnyUsart<'d, T, M> {
    pub fn split(self) -> (UsartRx<'d, T, M>, UsartTx<'d, T, M>) {
        (self.rx, self.tx)
    }

    pub fn new(
        usart: impl Peripheral<P = T> + 'd,
        rxd: Option<impl Peripheral<P = impl RxPin<T>> + 'd>,
        txd: Option<impl Peripheral<P = impl TxPin<T>> + 'd>,

        rx_dma: Option<DmaChannel<'d, DMA, M>>,
        tx_dma: Option<DmaChannel<'d, DMA, M>>,

        config: Config,
    ) -> Self {
        // 初始化 rxd 引脚
        let rxd = rxd.map_or_else(
            || None,
            |rxd| {
                into_ref!(rxd);
                rxd.set_instance_af(gpio::PinSpeed::VeryHigh, gpio::PinIoType::OpenDrain);
                Some(rxd.map_into())
            },
        );
        // 初始化 txd 引脚
        let txd = txd.map_or_else(
            || None,
            |txd| {
                into_ref!(txd);
                txd.set_instance_af(gpio::PinSpeed::VeryHigh, gpio::PinIoType::OpenDrain);
                Some(txd.map_into())
            },
        );

        into_ref!(usart);

        Self::new_inner(usart, rxd, txd, None, None, rx_dma, tx_dma, config)
    }

    #[allow(clippy::too_many_arguments)]
    fn new_inner(
        _usart: PeripheralRef<'d, T>,
        rxd: Option<PeripheralRef<'d, AnyPin>>,
        txd: Option<PeripheralRef<'d, AnyPin>>,
        cts: Option<PeripheralRef<'d, AnyPin>>,
        rts: Option<PeripheralRef<'d, AnyPin>>,
        rx_dma: Option<DmaChannel<'d, DMA, M>>,
        tx_dma: Option<DmaChannel<'d, DMA, M>>,
        config: Config,
    ) -> Self {
        T::enable();
        T::config(config);

        if M::is_async() {
            T::id().enable_interrupt();
        }

        Self {
            rx: UsartRx::<T, M>::new(rxd, rts, rx_dma),
            tx: UsartTx::<T, M>::new(txd, cts, tx_dma),
        }
    }
}

impl<'d, T: Instance> UsartRx<'d, T, Blocking> {
    pub fn read_blocking(&self, buf: &mut [u8]) -> usize {
        T::read_bytes_blocking(buf)
    }

    pub fn read_dma_idle_blocking(&mut self, buf: &mut [u8]) -> Result<usize, Error> {
        let len = buf.len();

        if let Some(dma) = &mut self.rx_dma {
            // 删除上次的标志
            let clear_events = Event::IDLE | Event::RXNE | Event::NE | Event::FE | Event::PE;
            clear_events.iter().for_each(|e| T::event_clear(e));

            // 返回dma 通道的映射值
            let (rx_dma_map, _tx_dma_map) = T::id().dma_channel_map();

            dma.clear_flag(EnumSet::all());
            // 不管成功与否都关闭dma触发
            let _tx_dmp_close = DropGuard::new(|| T::tx_dma_enable(false));

            // 配置dma channel
            dma.config(dma::Config::new_periph2mem(
                T::block().dr.as_ptr() as u32, // 数据寄存器
                false,
                dma::Burst::Single,
                buf.as_ptr() as u32,
                true,
                dma::Burst::Single,
                dma::Priorities::Medium,
                dma::RepeatMode::OneTime(buf.len() as u16),
            ));

            // 将 tx 信号绑定到 通道
            dma.bind(rx_dma_map);
            // 使能 dma channel
            dma.start();

            // 串口开启dma
            T::rx_dma_enable(true);

            let remain = loop {
                if T::event_flag(Event::FE) {
                    return Err(Error::Frame);
                }
                if T::event_flag(Event::PE) {
                    return Err(Error::Parity);
                }
                if T::event_flag(Event::NE) {
                    return Err(Error::Noise);
                }

                if dma.is_error() {
                    return Err(Error::DMA);
                }

                if dma.is_finish() {
                    break 0;
                }

                if T::event_flag(Event::IDLE) {
                    break dma.remain() as usize;
                }
            };
            Ok(len - remain)
        } else {
            Err(Error::DMA)
        }
    }

    pub fn read_idle_blocking(&self, buf: &mut [u8]) -> usize {
        T::read_bytes_idle_blocking(buf)
    }

    pub fn nb_read(&self) -> Result<u8, nb::Error<Error>> {
        if T::rx_ready() {
            Ok(T::read_byte_blocking())
        } else {
            Err(nb::Error::WouldBlock)
        }
    }
}

#[cfg(feature = "embassy")]
impl<'d, T: Instance> UsartRx<'d, T, Async> {
    pub async fn read(&mut self, buf: &mut [u8]) -> Result<usize, Error> {
        let mut cnt = 0;
        for v in buf {
            let events = Event::RXNE | Event::PE | Event::NE | Event::FE | Event::ORE; //

            let event_future = poll_fn(move |cx| {
                events.iter().for_each(|e| {
                    future::EVENT_WAKERS[T::id() as usize][e as usize].register(cx.waker());
                    T::event_config(e, true);
                });

                // 查看事件
                let mut events_happen = EnumSet::empty();
                events.iter().for_each(|e| {
                    if T::event_flag(e) {
                        T::event_clear(e);
                        events_happen |= e;
                    }
                });

                // some event happen, so reset the event future
                if !events_happen.is_empty() {
                    events.iter().for_each(|e| {
                        T::event_config(e, false);
                    });
                    return Poll::Ready(events_happen);
                }

                Poll::Pending
            });

            let events_happen = event_future.await;

            // grab rx data or clear some flag
            *v = T::read();
            cnt += 1;

            if events_happen != Event::RXNE {
                return Err(Error::Others);
            }
        }

        Ok(cnt)
    }

    pub async fn read_with_idle(&mut self, buf: &mut [u8]) -> Result<usize, Error> {
        let mut cnt = 0;
        let events = Event::RXNE | Event::PE | Event::NE | Event::FE | Event::ORE | Event::IDLE;
        for v in buf {
            let event = EventFuture::<T>::new(events).await;
            if event == Event::RXNE {
                *v = T::read();
                cnt += 1;
            } else if event.contains(Event::IDLE) {
                return Ok(cnt);
            } else {
                return Err(Error::Others);
            }
        }
        Ok(cnt)
    }
}

impl<'d, T: Instance, M: Mode> UsartRx<'d, T, M> {
    pub(crate) fn new(
        rxd: Option<PeripheralRef<'d, AnyPin>>,
        rts: Option<PeripheralRef<'d, AnyPin>>,
        rx_dma: Option<DmaChannel<'d, DMA, M>>,
    ) -> Self {
        T::rx_enable(rxd.is_some());
        T::rts_enable(rts.is_none());

        Self {
            _p: PhantomData,
            _rxd: rxd,
            _rts: rts,
            rx_dma,
        }
    }
}

impl<'d, T: Instance> UsartTx<'d, T, Blocking> {
    fn write_bytes_dma_blocking(&mut self, buf: &[u8]) -> Result<(), Error> {
        if let Some(dma) = &mut self.tx_dma {
            // 返回dma 通道的映射值
            let (_rx_dma_map, tx_dma_map) = T::id().dma_channel_map();

            // 不管成功与否都关闭dma触发
            let _tx_dmp_close = DropGuard::new(|| T::tx_dma_enable(false));

            dma.clear_flag(EnumSet::all());

            // 配置dma channel
            dma.config(dma::Config::new_mem2periph(
                buf.as_ptr() as u32,
                true,
                dma::Burst::Single,
                T::block().dr.as_ptr() as u32,
                false,
                dma::Burst::Single,
                dma::Priorities::Medium,
                dma::RepeatMode::OneTime(buf.len() as u16),
            ));

            // 将 tx 信号绑定到 通道
            dma.bind(tx_dma_map);
            // 使能 dma channel
            dma.start();

            // 串口开启dma
            T::tx_dma_enable(true);
            // 等待dma传输完成
            dma.wait_complet().map_err(|_| Error::DMA)?;
            Ok(())
        } else {
            Err(Error::DMA)
        }
    }

    fn write_bytes_blocking(&mut self, buf: &[u8]) -> Result<(), Error> {
        T::write_bytes_blocking(buf)
    }

    pub fn write(&mut self, buf: &[u8]) -> Result<(), Error> {
        if self.tx_dma.is_none() {
            self.write_bytes_blocking(buf)
        } else {
            self.write_bytes_dma_blocking(buf)
        }
    }

    fn flush(&self) -> nb::Result<(), Error> {
        T::tx_flush();
        Ok(())
    }
}

#[cfg(feature = "embassy")]
impl<'d, T: Instance> UsartTx<'d, T, Async> {
    pub async fn write(&mut self, buf: &[u8]) -> Result<(), Error> {
        if self.tx_dma.is_some() {
            self.write_bytes_dma(buf).await
        } else {
            self.write_bytes(buf).await
        }
    }

    // 异步发送数据
    async fn write_bytes(&mut self, buf: &[u8]) -> Result<(), Error> {
        let events = Event::TXE | Event::CTS;
        for v in buf {
            T::write(*v);
            let rst = EventFuture::<T>::new(events).await;
            if rst != Event::TXE {
                return Err(Error::Others);
            }
        }
        Ok(())
    }

    /// 通过dma异步发送数据
    async fn write_bytes_dma(&mut self, buf: &[u8]) -> Result<(), Error> {
        if let Some(dma) = &mut self.tx_dma {
            // 返回dma 通道的映射值
            let (_rx_dma_map, tx_dma_map) = T::id().dma_channel_map();

            // 不管成功与否都关闭dma触发
            let _tx_dmp_close = DropGuard::new(|| T::tx_dma_enable(false));

            // 配置dma channel
            dma.config(dma::Config::new_mem2periph(
                buf.as_ptr() as u32,
                true,
                dma::Burst::Single,
                T::block().dr.as_ptr() as u32,
                false,
                dma::Burst::Single,
                dma::Priorities::Medium,
                dma::RepeatMode::OneTime(buf.len() as u16),
            ));

            // 将 tx 信号绑定到 通道
            dma.bind(tx_dma_map);
            // 使能 dma channel
            dma.start();

            // 串口开启dma
            T::tx_dma_enable(true);

            // 等待dma传输完成
            dma.wait_complet().await.map_err(|_| Error::DMA)?;

            Ok(())
        } else {
            Err(Error::DMA)
        }
    }

    pub async fn flush(&mut self) -> Result<(), Error> {
        EventFuture::<T>::new(EnumSet::empty() | Event::TC).await;
        Ok(())
    }
}

impl<'d, T: Instance, M: Mode> UsartTx<'d, T, M> {
    pub(crate) fn new(
        txd: Option<PeripheralRef<'d, AnyPin>>,
        cts: Option<PeripheralRef<'d, AnyPin>>,
        tx_dma: Option<DmaChannel<'d, DMA, M>>,
    ) -> Self {
        T::tx_enable(txd.is_some());
        T::cts_enable(cts.is_some());

        Self {
            _p: PhantomData,
            _txd: txd,
            _cts: cts,
            tx_dma,
        }
    }
}

/// embedded_hal::serial for AnyUsart<'d, T, Blocking>
impl<'d, T: Instance> embedded_hal::serial::Read<u8> for AnyUsart<'d, T, Blocking> {
    type Error = Error;
    fn read(&mut self) -> nb::Result<u8, Self::Error> {
        self.rx.nb_read()
    }
}

impl<'d, T: Instance> embedded_hal::serial::Write<u8> for AnyUsart<'d, T, Blocking> {
    type Error = Error;
    fn flush(&mut self) -> nb::Result<(), Self::Error> {
        self.tx.flush()
    }
    fn write(&mut self, word: u8) -> nb::Result<(), Self::Error> {
        self.tx.write(&[word])?;
        Ok(())
    }
}

/// embedded_hal::serial for UsartRx<'d, T, Blocking>
impl<'d, T: Instance> embedded_hal::serial::Read<u8> for UsartRx<'d, T, Blocking> {
    type Error = Error;
    fn read(&mut self) -> nb::Result<u8, Self::Error> {
        self.nb_read()
    }
}

/// embedded_hal::serial for UsartTx<'d, T, Blocking>
impl<'d, T: Instance> embedded_hal::serial::Write<u8> for UsartTx<'d, T, Blocking> {
    type Error = Error;
    fn flush(&mut self) -> nb::Result<(), Self::Error> {
        T::tx_flush();
        Ok(())
    }

    fn write(&mut self, word: u8) -> nb::Result<(), Self::Error> {
        self.write(&[word])?;
        // T::write_byte_blocking(word)?;
        Ok(())
    }
}

impl embedded_io::Error for Error {
    fn kind(&self) -> embedded_io::ErrorKind {
        embedded_io::ErrorKind::Other
    }
}

impl<'d, T: Instance> embedded_io::ErrorType for AnyUsart<'d, T, Blocking> {
    type Error = Error;
}

impl<'d, T: Instance> embedded_io::ErrorType for UsartRx<'d, T, Blocking> {
    type Error = Error;
}

impl<'d, T: Instance> embedded_io::Read for AnyUsart<'d, T, Blocking> {
    fn read(&mut self, buf: &mut [u8]) -> Result<usize, Self::Error> {
        self.rx.read(buf)
    }
}

impl<'d, T: Instance> embedded_io::Read for UsartRx<'d, T, Blocking> {
    fn read(&mut self, buf: &mut [u8]) -> Result<usize, Self::Error> {
        Ok(T::read_bytes_blocking(buf))
    }
}

impl<'d, T: Instance> embedded_io::ErrorType for UsartTx<'d, T, Blocking> {
    type Error = Error;
}

impl<'d, T: Instance> embedded_io::Write for AnyUsart<'d, T, Blocking> {
    fn write(&mut self, buf: &[u8]) -> Result<usize, Self::Error> {
        self.tx.write(buf)?;
        Ok(buf.len())
    }

    fn flush(&mut self) -> Result<(), Self::Error> {
        T::tx_flush();
        Ok(())
    }
}

impl<'d, T: Instance> embedded_io::Write for UsartTx<'d, T, Blocking> {
    fn write(&mut self, buf: &[u8]) -> Result<usize, Self::Error> {
        self.write(buf)?;
        Ok(buf.len())
    }

    fn flush(&mut self) -> Result<(), Self::Error> {
        T::tx_flush();
        Ok(())
    }
}

#[cfg(feature = "embassy")]
impl<'d, T: Instance> embedded_io_async::ErrorType for AnyUsart<'d, T, Async> {
    type Error = Error;
}

#[cfg(feature = "embassy")]
impl<'d, T: Instance> embedded_io_async::ErrorType for UsartRx<'d, T, Async> {
    type Error = Error;
}

#[cfg(feature = "embassy")]
impl<'d, T: Instance> embedded_io_async::Read for AnyUsart<'d, T, Async> {
    async fn read(&mut self, buf: &mut [u8]) -> Result<usize, Self::Error> {
        self.rx.read(buf).await
    }
}

#[cfg(feature = "embassy")]
impl<'d, T: Instance> embedded_io_async::Read for UsartRx<'d, T, Async> {
    async fn read(&mut self, buf: &mut [u8]) -> Result<usize, Self::Error> {
        self.read_with_idle(buf).await
    }
}

#[cfg(feature = "embassy")]
impl<'d, T: Instance> embedded_io_async::ErrorType for UsartTx<'d, T, Async> {
    type Error = Error;
}

#[cfg(feature = "embassy")]
impl<'d, T: Instance> embedded_io_async::Write for UsartTx<'d, T, Async> {
    async fn flush(&mut self) -> Result<(), Self::Error> {
        EventFuture::<T>::new(EnumSet::empty() | Event::TC).await;
        Ok(())
    }

    async fn write(&mut self, buf: &[u8]) -> Result<usize, Self::Error> {
        self.write(buf).await?;
        Ok(buf.len())
    }
}