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
#![no_std]

#[cfg(any(feature = "defmt", feature = "defmt-raw"))]
pub mod defmt;
#[cfg(feature = "log")]
pub mod logger;
#[cfg(feature = "rtt")]
mod rtt;

#[cfg(not(feature = "no-op"))]
#[macro_export]
macro_rules! println {
    ($($arg:tt)*) => {{
        {
            use core::fmt::Write;
            writeln!($crate::Printer, $($arg)*).ok();
        }
    }};
}

#[cfg(not(feature = "no-op"))]
#[macro_export]
macro_rules! print {
    ($($arg:tt)*) => {{
        {
            use core::fmt::Write;
            write!($crate::Printer, $($arg)*).ok();
        }
    }};
}

#[cfg(feature = "no-op")]
#[macro_export]
macro_rules! println {
    ($($arg:tt)*) => {{}};
}

#[cfg(feature = "no-op")]
#[macro_export]
macro_rules! print {
    ($($arg:tt)*) => {{}};
}

// implementation adapted from `std::dbg`
#[macro_export]
macro_rules! dbg {
    // NOTE: We cannot use `concat!` to make a static string as a format argument
    // of `eprintln!` because `file!` could contain a `{` or
    // `$val` expression could be a block (`{ .. }`), in which case the `println!`
    // will be malformed.
    () => {
        $crate::println!("[{}:{}]", ::core::file!(), ::core::line!())
    };
    ($val:expr $(,)?) => {
        // Use of `match` here is intentional because it affects the lifetimes
        // of temporaries - https://stackoverflow.com/a/48732525/1063961
        match $val {
            tmp => {
                $crate::println!("[{}:{}] {} = {:#?}",
                    ::core::file!(), ::core::line!(), ::core::stringify!($val), &tmp);
                tmp
            }
        }
    };
    ($($val:expr),+ $(,)?) => {
        ($($crate::dbg!($val)),+,)
    };
}

pub struct Printer;

impl core::fmt::Write for Printer {
    fn write_str(&mut self, s: &str) -> core::fmt::Result {
        Printer.write_bytes(s.as_bytes());
        Ok(())
    }
}

#[cfg(feature = "rtt")]
mod rtt_printer {
    impl super::Printer {
        pub fn write_bytes(&mut self, bytes: &[u8]) {
            super::with(|| {
                let count = crate::rtt::write_bytes_internal(bytes);
                if count < bytes.len() {
                    crate::rtt::write_bytes_internal(&bytes[count..]);
                }
            })
        }
    }
}

#[cfg(feature = "jtag_serial")]
mod serial_jtag_printer {
    #[cfg(feature = "esp32c3")]
    const SERIAL_JTAG_FIFO_REG: usize = 0x6004_3000;
    #[cfg(feature = "esp32c3")]
    const SERIAL_JTAG_CONF_REG: usize = 0x6004_3004;

    #[cfg(any(feature = "esp32c6", feature = "esp32h2"))]
    const SERIAL_JTAG_FIFO_REG: usize = 0x6000_F000;
    #[cfg(any(feature = "esp32c6", feature = "esp32h2"))]
    const SERIAL_JTAG_CONF_REG: usize = 0x6000_F004;

    #[cfg(feature = "esp32s3")]
    const SERIAL_JTAG_FIFO_REG: usize = 0x6003_8000;
    #[cfg(feature = "esp32s3")]
    const SERIAL_JTAG_CONF_REG: usize = 0x6003_8004;

    #[cfg(any(
        feature = "esp32c3",
        feature = "esp32c6",
        feature = "esp32h2",
        feature = "esp32s3"
    ))]
    impl super::Printer {
        pub fn write_bytes(&mut self, bytes: &[u8]) {
            super::with(|| {
                const TIMEOUT_ITERATIONS: usize = 5_000;

                let fifo = SERIAL_JTAG_FIFO_REG as *mut u32;
                let conf = SERIAL_JTAG_CONF_REG as *mut u32;

                if unsafe { conf.read_volatile() } & 0b011 == 0b000 {
                    // still wasn't able to drain the FIFO - early return
                    return;
                }

                // todo 64 byte chunks max
                for chunk in bytes.chunks(32) {
                    unsafe {
                        for &b in chunk {
                            fifo.write_volatile(b as u32);
                        }
                        conf.write_volatile(0b001);

                        let mut timeout = TIMEOUT_ITERATIONS;
                        while conf.read_volatile() & 0b011 == 0b000 {
                            // wait
                            timeout -= 1;
                            if timeout == 0 {
                                return;
                            }
                        }
                    }
                }
            })
        }
    }
}

#[cfg(feature = "uart")]
mod uart_printer {
    #[cfg(feature = "esp32")]
    const UART_TX_ONE_CHAR: usize = 0x4000_9200;
    #[cfg(any(feature = "esp32c2", feature = "esp32c6", feature = "esp32h2"))]
    const UART_TX_ONE_CHAR: usize = 0x4000_0058;
    #[cfg(feature = "esp32c3")]
    const UART_TX_ONE_CHAR: usize = 0x4000_0068;
    #[cfg(feature = "esp32s3")]
    const UART_TX_ONE_CHAR: usize = 0x4000_0648;
    #[cfg(feature = "esp8266")]
    const UART_TX_ONE_CHAR: usize = 0x4000_3b30;

    impl super::Printer {
        #[cfg(not(feature = "esp32s2"))]
        pub fn write_bytes(&mut self, bytes: &[u8]) {
            super::with(|| {
                for &b in bytes {
                    unsafe {
                        let uart_tx_one_char: unsafe extern "C" fn(u8) -> i32 =
                            core::mem::transmute(UART_TX_ONE_CHAR);
                        uart_tx_one_char(b)
                    };
                }
            })
        }

        #[cfg(feature = "esp32s2")]
        pub fn write_bytes(&mut self, bytes: &[u8]) {
            super::with(|| {
                // On ESP32-S2 the UART_TX_ONE_CHAR ROM-function seems to have some issues.
                for chunk in bytes.chunks(64) {
                    for &b in chunk {
                        unsafe {
                            // write FIFO
                            (0x3f400000 as *mut u32).write_volatile(b as u32);
                        };
                    }

                    // wait for TX_DONE
                    while unsafe { (0x3f400004 as *const u32).read_volatile() } & (1 << 14) == 0 {}
                    unsafe {
                        // reset TX_DONE
                        (0x3f400010 as *mut u32).write_volatile(1 << 14);
                    }
                }
            })
        }
    }
}

#[inline]
fn with<R>(f: impl FnOnce() -> R) -> R {
    #[cfg(feature = "critical-section")]
    return critical_section::with(|_| f());

    #[cfg(not(feature = "critical-section"))]
    f()
}