ask433 0.2.1

A no_std, embedded-hal ASK/OOK modem driver for 433 MHz RF modules (e.g., FS1000A). Supports RX/TX, 4b6b encoding, and software PLL demodulation.
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
#[cfg(not(feature = "std"))]
use crate::consts::ASK_MAX_MESSAGE_LEN_USIZE;
use crate::driver::AskDriver;
use core::cell::RefCell;
use critical_section::Mutex;
use embedded_hal::digital::{InputPin, OutputPin};
#[cfg(not(feature = "std"))]
use heapless::Vec;

/// Used to initialize the global static `AskDriver` for use with
/// `critical_section`.
///
/// # Returns
/// * An empty mutable ref-cell
///
/// # Example
/// ```rust
/// use ask433::driver::AskDriver;
/// use core::cell::RefCell;
/// use critical_section::Mutex;
/// use embedded_hal::digital::{InputPin, OutputPin};
/// # use embedded_hal_mock::eh1::digital::{Mock as Pin, State as PinState, Transaction as PinTransaction};
/// use ask433::timer::global_ask_driver_init;
///
/// static ASK_DRIVER: Mutex<RefCell<Option<AskDriver<Pin, Pin, Pin>>>> =
///     global_ask_driver_init::<Pin, Pin, Pin>();
/// ```
pub const fn global_ask_driver_init<TX: OutputPin, RX: InputPin, PTT: OutputPin>()
-> Mutex<RefCell<Option<AskDriver<TX, RX, PTT>>>> {
    Mutex::new(RefCell::new(None))
}

/// Sets up the `critical_section::with` callback.
///
/// # Arguments
/// * The global static `AskDriver`
/// * The tx pin
/// * The rx pin
/// * The number of ticks per bit such that:
///     `interrupt frequency / ticks per bit = 2000 bits per second`
///     e.g. For the Atmega328P with an interrupt frequency of `~62.5µs`:
///         ```rust
///         // 8 ticks / bit = 1 second / 2000 bits * 1 tick / 6.25e-5 seconds
///         const TICKS_PER_BIT: u8 = (1/2000)*(1/625e-7_f32) as u8
///         ```
///# Example
/// ```rust
/// use ask433::driver::AskDriver;
/// use core::cell::RefCell;
/// use critical_section::Mutex;
/// use embedded_hal::digital::{InputPin, OutputPin};
/// # use embedded_hal_mock::eh1::digital::{Mock as Pin, State as PinState, Transaction as PinTransaction};
/// use ask433::timer::{global_ask_driver_init, global_ask_driver_setup};
///
/// static ASK_DRIVER: Mutex<RefCell<Option<AskDriver<Pin, Pin, Pin>>>> =
///     global_ask_driver_init::<Pin, Pin, Pin>();
///
/// fn main() {
///     # let tx = Pin::new(&[PinTransaction::set(PinState::Low)]);
///     # let rx = Pin::new(&[]);
///     global_ask_driver_setup::<Pin, Pin, Pin>(&ASK_DRIVER, tx, rx, None, 8, None, None);
///     # critical_section::with(|cs| {
///     #    if let Some(driver) = ASK_DRIVER.borrow(cs).borrow_mut().as_mut() {
///     #       driver.tx.done();
///     #       driver.rx.done();
///     #   }
///     # });
/// }
/// ```
pub fn global_ask_driver_setup<TX: OutputPin, RX: InputPin, PTT: OutputPin>(
    global_driver: &'static Mutex<RefCell<Option<AskDriver<TX, RX, PTT>>>>,
    tx: TX,
    rx: RX,
    ptt: Option<PTT>,
    ticks_per_bit: u8,
    ptt_inverted: Option<bool>,
    rx_inverted: Option<bool>,
) {
    critical_section::with(|cs| {
        let _ = global_driver.borrow(cs).replace(Some(AskDriver::new(
            tx,
            rx,
            ptt,
            ticks_per_bit,
            ptt_inverted,
            rx_inverted,
        )));
    });
}

/// Runs the tick at each interrupt
///
/// # Arguments
/// * The global static `AskDriver`
///# Example
/// ```rust,ignore
/// # use embedded_hal_mock::eh1::digital::Mock as Pin;
/// use ask433::driver::AskDriver;
/// use ask433::timer::isr::{global_ask_driver_init, global_ask_driver_tick};
///
/// static ASK_DRIVER: Mutex<RefCell<Option<AskDriver<Pin, Pin, Pin>>>> =
///     global_ask_driver_init::<Pin, Pin, Pin>();
/// #[interrupt]
/// fn TIM2() {
///     global_ask_driver_tick(ASK_DRIVER);
/// }
/// ```
pub fn global_ask_timer_tick<TX: OutputPin, RX: InputPin, PTT: OutputPin>(
    global_driver: &'static Mutex<RefCell<Option<AskDriver<TX, RX, PTT>>>>,
) {
    critical_section::with(|cs| {
        if let Some(driver) = global_driver.borrow(cs).borrow_mut().as_mut() {
            driver.tick();
        }
    });
}

/// Attempts to receive a message from a global `AskDriver` instance wrapped in a `Mutex`.
///
/// This function checks whether a valid and complete message is available using the
/// driver's `availabile()` method. If a message is present, it returns a heapless `Vec`
/// containing the decoded payload. If the buffer is invalid or incomplete, `None` is returned.
///
/// # Type Parameters
/// - `TX`: Type of the TX pin (must implement `OutputPin`)
/// - `RX`: Type of the RX pin (must implement `InputPin`)
/// - `PTT`: Type of the Push-To-Talk (PTT) control pin (must implement `OutputPin`)
///
/// # Arguments
/// - `global_driver`: A reference to a global `Mutex<RefCell<Option<AskDriver>>>`
///   that wraps the ASK driver state, typically created using `critical_section`.
///
/// # Returns
/// - `Some(Vec<u8>)`: A heapless vector containing the decoded message payload
/// - `None`: If no valid message is currently available
///
/// # Safety
/// - This function must be called from a context where `critical_section` access is safe,
///   such as inside `main()` or an interrupt-free routine.
///
/// # Example
/// ```rust
/// # use embedded_hal_mock::eh1::digital::Mock as Pin;
/// use critical_section::Mutex;
/// use core::cell::RefCell;
/// use ask433::driver::AskDriver;
/// use ask433::timer::{global_ask_driver_init, receive_from_global_ask};
///
/// static ASK_DRIVER: Mutex<RefCell<Option<AskDriver<Pin, Pin, Pin>>>> =
///     global_ask_driver_init::<Pin, Pin, Pin>();
/// // ...
/// if let Some(msg) = receive_from_global_ask(&ASK_DRIVER) {
///     // Use the received message
/// }
/// ```
///
/// # See also
/// - [`AskDriver::availabile()`]
/// - [`AskDriver::receive()`]
#[cfg(not(feature = "std"))]
pub fn receive_from_global_ask<TX: OutputPin, RX: InputPin, PTT: OutputPin>(
    global_driver: &'static Mutex<RefCell<Option<AskDriver<TX, RX, PTT>>>>,
) -> Option<Vec<u8, ASK_MAX_MESSAGE_LEN_USIZE>> {
    critical_section::with(|cs| {
        let mut guard = global_driver.borrow(cs).borrow_mut();
        let driver = guard.as_mut()?;
        if driver.availabile() {
            driver.receive()
        } else {
            None
        }
    })
}

/// Attempts to receive a message from a global `AskDriver` instance wrapped in a `Mutex`.
///
/// This function checks whether a valid and complete message is available using the
/// driver's `availabile()` method. If a message is present, it returns a heapless `Vec`
/// containing the decoded payload. If the buffer is invalid or incomplete, `None` is returned.
///
/// # Type Parameters
/// - `TX`: Type of the TX pin (must implement `OutputPin`)
/// - `RX`: Type of the RX pin (must implement `InputPin`)
/// - `PTT`: Type of the Push-To-Talk (PTT) control pin (must implement `OutputPin`)
///
/// # Arguments
/// - `global_driver`: A reference to a global `Mutex<RefCell<Option<AskDriver>>>`
///   that wraps the ASK driver state, typically created using `critical_section`.
///
/// # Returns
/// - `Some(Vec<u8>)`: A vector containing the decoded message payload
/// - `None`: If no valid message is currently available
///
/// # Safety
/// - This function must be called from a context where `critical_section` access is safe,
///   such as inside `main()` or an interrupt-free routine.
///
/// # Example
/// ```rust
/// # use embedded_hal_mock::eh1::digital::Mock as Pin;
/// use critical_section::Mutex;
/// use core::cell::RefCell;
/// use ask433::driver::AskDriver;
/// use ask433::timer::{global_ask_driver_init, receive_from_global_ask};
///
/// static ASK_DRIVER: Mutex<RefCell<Option<AskDriver<Pin, Pin, Pin>>>> =
///     global_ask_driver_init::<Pin, Pin, Pin>();
/// // ...
/// if let Some(msg) = receive_from_global_ask(&ASK_DRIVER) {
///     // Use the received message
/// }
/// ```
///
/// # See also
/// - [`AskDriver::availabile()`]
/// - [`AskDriver::receive()`]
#[cfg(feature = "std")]
pub fn receive_from_global_ask<TX: OutputPin, RX: InputPin, PTT: OutputPin>(
    global_driver: &'static Mutex<RefCell<Option<AskDriver<TX, RX, PTT>>>>,
) -> Option<Vec<u8>> {
    critical_section::with(|cs| {
        let mut guard = global_driver.borrow(cs).borrow_mut();
        let driver = guard.as_mut()?;
        if driver.availabile() {
            driver.receive()
        } else {
            None
        }
    })
}

/// Sends a message using a global `AskDriver` instance wrapped in a `Mutex`.
///
/// This function attempts to send the provided message buffer using the global
/// ASK driver. If the driver is currently idle and the message length is valid,
/// it transitions to transmit mode and begins sending the encoded message
/// (including headers, preamble, and CRC).
///
/// # Type Parameters
/// - `TX`: The TX pin type (must implement `OutputPin`)
/// - `RX`: The RX pin type (must implement `InputPin`)
/// - `PTT`: The Push-To-Talk (PTT) control pin type (must implement `OutputPin`)
///
/// # Arguments
/// - `global_driver`: A reference to a global `Mutex<RefCell<Option<AskDriver>>>`,
///   typically declared using [`init_ask_driver!`](crate::init_ask_driver) and initialized via [`setup_ask_driver!`](crate::setup_ask_driver).
/// - `vec`: A `heapless::Vec<u8>` containing the payload to send. Must not exceed [`ASK_MAX_MESSAGE_LEN`](crate::consts::ASK_MAX_MESSAGE_LEN).
///
/// # Returns
/// - `true` if the message was successfully queued for transmission
/// - `false` if the driver was uninitialized or busy
///
/// # Example
///
/// ```rust
/// # use embedded_hal_mock::eh1::digital::Mock as Pin;
/// use critical_section::Mutex;
/// use heapless::Vec;
/// use core::cell::RefCell;
/// use ask433::driver::AskDriver;
/// use ask433::timer::{global_ask_driver_init, send_from_global_ask};
/// use ask433::consts::ASK_MAX_MESSAGE_LEN_USIZE;
///
/// static ASK_DRIVER: Mutex<RefCell<Option<AskDriver<Pin, Pin, Pin>>>> =
///     global_ask_driver_init::<Pin, Pin, Pin>();
///
/// let mut vec: Vec<u8, ASK_MAX_MESSAGE_LEN_USIZE> = Vec::new();
/// vec.extend_from_slice(b"Hello").unwrap();
/// let sent = send_from_global_ask(&ASK_DRIVER, vec);
/// if sent {
///     // Message is being transmitted
/// }
/// ```
///
/// # Notes
/// - This function does not block. Transmission occurs incrementally via repeated `tick()` calls.
/// - Returns `false` if the driver is uninitialized or already transmitting a message.
/// - The PTT pin is asserted automatically during transmission.
///
/// # See also
/// - [`AskDriver::send()`]
#[cfg(not(feature = "std"))]
pub fn send_from_global_ask<TX: OutputPin, RX: InputPin, PTT: OutputPin>(
    global_driver: &'static Mutex<RefCell<Option<AskDriver<TX, RX, PTT>>>>,
    msg: Vec<u8, ASK_MAX_MESSAGE_LEN_USIZE>,
) -> bool {
    critical_section::with(|cs| {
        if let Some(driver) = global_driver.borrow(cs).borrow_mut().as_mut() {
            driver.send(msg)
        } else {
            false
        }
    })
}

/// Sends a message using a global `AskDriver` instance wrapped in a `Mutex`.
///
/// This function attempts to send the provided message buffer using the global
/// ASK driver. If the driver is currently idle and the message length is valid,
/// it transitions to transmit mode and begins sending the encoded message
/// (including headers, preamble, and CRC).
///
/// # Type Parameters
/// - `TX`: The TX pin type (must implement `OutputPin`)
/// - `RX`: The RX pin type (must implement `InputPin`)
/// - `PTT`: The Push-To-Talk (PTT) control pin type (must implement `OutputPin`)
///
/// # Arguments
/// - `global_driver`: A reference to a global `Mutex<RefCell<Option<AskDriver>>>`,
///   typically declared using [`init_global_ask_driver!`] and initialized via [`setup_global_ask_driver!`].
/// - `vec`: A `Vec<u8>` containing the payload to send.
///
/// # Returns
/// - `true` if the message was successfully queued for transmission
/// - `false` if the driver was uninitialized or busy
///
/// # Example
/// ```rust
/// # use embedded_hal_mock::eh1::digital::Mock as Pin;
/// use critical_section::Mutex;
/// use core::cell::RefCell;
/// use ask433::driver::AskDriver;
/// use ask433::timer::{global_ask_driver_init, send_from_global_ask};
///
/// static ASK_DRIVER: Mutex<RefCell<Option<AskDriver<Pin, Pin, Pin>>>> =
///     global_ask_driver_init::<Pin, Pin, Pin>();
/// let mut vec: Vec<u8> = Vec::new();
/// vec.extend(b"Hello");
/// let sent = send_from_global_ask(&ASK_DRIVER, vec);
/// if sent {
///     // Message is being transmitted
/// }
/// ```
///
/// # Notes
/// - This function does not block. Transmission occurs incrementally via repeated `tick()` calls.
/// - Returns `false` if the driver is uninitialized or already transmitting a message.
/// - The PTT pin is asserted automatically during transmission.
///
/// # See also
/// - [`AskDriver::send()`]
#[cfg(feature = "std")]
pub fn send_from_global_ask<TX: OutputPin, RX: InputPin, PTT: OutputPin>(
    global_driver: &'static Mutex<RefCell<Option<AskDriver<TX, RX, PTT>>>>,
    msg: Vec<u8>,
) -> bool {
    critical_section::with(|cs| {
        if let Some(driver) = global_driver.borrow(cs).borrow_mut().as_mut() {
            driver.send(msg)
        } else {
            false
        }
    })
}

#[cfg(test)]
mod tests {
    use super::*;
    use core::cell::RefCell;
    use embedded_hal_mock::eh1::digital::{
        Mock as PinMock, State as PinState, Transaction as PinTransaction,
    };

    #[test]
    fn test_global_driver_init_and_setup() {
        static GLOBAL_DRIVER: Mutex<RefCell<Option<AskDriver<PinMock, PinMock, PinMock>>>> =
            global_ask_driver_init::<PinMock, PinMock, PinMock>();
        static TICKS: u8 = 8;

        let tx = PinMock::new(&[PinTransaction::set(PinState::Low)]);
        let rx = PinMock::new(&[]);
        let ptt = Some(PinMock::new(&[]));

        global_ask_driver_setup(&GLOBAL_DRIVER, tx, rx, ptt, TICKS, Some(false), Some(false));

        critical_section::with(|cs| {
            assert!(GLOBAL_DRIVER.borrow(cs).borrow().is_some());
        });

        critical_section::with(|cs| {
            if let Some(driver) = GLOBAL_DRIVER.borrow(cs).borrow_mut().as_mut() {
                driver.tx.done();
                driver.rx.done();
                let _ = driver.ptt.as_mut().map(|ptt| ptt.done());
            }
        });
    }

    #[test]
    fn test_global_tick_function_calls_tick() {
        static GLOBAL_DRIVER: Mutex<RefCell<Option<AskDriver<PinMock, PinMock, PinMock>>>> =
            global_ask_driver_init::<PinMock, PinMock, PinMock>();
        static TICKS: u8 = 8;

        let tx = PinMock::new(&[PinTransaction::set(PinState::Low)]);
        let rx = PinMock::new(&[]);
        let ptt = Some(PinMock::new(&[]));

        global_ask_driver_setup(&GLOBAL_DRIVER, tx, rx, ptt, TICKS, Some(false), Some(false));

        global_ask_timer_tick(&GLOBAL_DRIVER);

        critical_section::with(|cs| {
            if let Some(driver) = GLOBAL_DRIVER.borrow(cs).borrow_mut().as_mut() {
                driver.tx.done();
                driver.rx.done();
                let _ = driver.ptt.as_mut().map(|ptt| ptt.done());
            }
        });
    }

    #[test]
    fn test_global_send_and_receive() {
        static GLOBAL_DRIVER: Mutex<RefCell<Option<AskDriver<PinMock, PinMock, PinMock>>>> =
            global_ask_driver_init::<PinMock, PinMock, PinMock>();
        static TICKS: u8 = 8;

        let tx = PinMock::new(&[
            PinTransaction::set(PinState::Low),
            PinTransaction::set(PinState::Low),
        ]);
        let rx = PinMock::new(&[]);
        let ptt = Some(PinMock::new(&[PinTransaction::set(PinState::High)]));

        global_ask_driver_setup(&GLOBAL_DRIVER, tx, rx, ptt, TICKS, Some(false), Some(false));

        for _ in 0..5 {
            global_ask_timer_tick(&GLOBAL_DRIVER);
        }

        let mut msg = Vec::new();
        #[cfg(not(feature = "std"))]
        let _ = msg.extend_from_slice(b"Hello");
        #[cfg(feature = "std")]
        msg.extend_from_slice(b"Hello");

        assert!(send_from_global_ask(&GLOBAL_DRIVER, msg));

        for _ in 0..5 {
            global_ask_timer_tick(&GLOBAL_DRIVER);
        }

        let received = receive_from_global_ask(&GLOBAL_DRIVER);
        assert!(received.is_none()); // No message has been received yet

        for _ in 0..5 {
            global_ask_timer_tick(&GLOBAL_DRIVER);
        }

        critical_section::with(|cs| {
            if let Some(driver) = GLOBAL_DRIVER.borrow(cs).borrow_mut().as_mut() {
                driver.tx.done();
                driver.rx.done();
                let _ = driver.ptt.as_mut().map(|ptt| ptt.done());
            }
        });
    }
}