|
| 1 | +// This file is part of the CircuitPython project: https://circuitpython.org |
| 2 | +// |
| 3 | +// SPDX-FileCopyrightText: Copyright (c) 2026 Vladimir Smitka |
| 4 | +// |
| 5 | +// SPDX-License-Identifier: MIT |
| 6 | + |
| 7 | +// An SPI loopback device for native_sim: MOSI is wired to MISO, so every byte sent is read back. |
| 8 | +// With nothing to send the line idles low. Tests use it through busio.SPI and async_spi.SPI. |
| 9 | + |
| 10 | +#define DT_DRV_COMPAT circuitpython_spi_loopback |
| 11 | + |
| 12 | +#include <zephyr/device.h> |
| 13 | +#include <zephyr/drivers/emul.h> |
| 14 | +#include <zephyr/drivers/spi.h> |
| 15 | +#include <zephyr/drivers/spi_emul.h> |
| 16 | + |
| 17 | +static int loopback_io(const struct emul *target, const struct spi_config *config, |
| 18 | + const struct spi_buf_set *tx_bufs, const struct spi_buf_set *rx_bufs) { |
| 19 | + ARG_UNUSED(target); |
| 20 | + ARG_UNUSED(config); |
| 21 | + if (rx_bufs == NULL) { |
| 22 | + return 0; |
| 23 | + } |
| 24 | + // A buffer with no data stands for that many idle or dropped bytes, as in Zephyr's drivers. |
| 25 | + size_t tx_i = 0; |
| 26 | + size_t tx_pos = 0; |
| 27 | + for (size_t i = 0; i < rx_bufs->count; i++) { |
| 28 | + uint8_t *rx = rx_bufs->buffers[i].buf; |
| 29 | + for (size_t j = 0; j < rx_bufs->buffers[i].len; j++) { |
| 30 | + uint8_t value = 0; |
| 31 | + while (tx_bufs != NULL && tx_i < tx_bufs->count && tx_pos >= tx_bufs->buffers[tx_i].len) { |
| 32 | + tx_i++; |
| 33 | + tx_pos = 0; |
| 34 | + } |
| 35 | + if (tx_bufs != NULL && tx_i < tx_bufs->count) { |
| 36 | + const uint8_t *tx = tx_bufs->buffers[tx_i].buf; |
| 37 | + if (tx != NULL) { |
| 38 | + value = tx[tx_pos]; |
| 39 | + } |
| 40 | + tx_pos++; |
| 41 | + } |
| 42 | + if (rx != NULL) { |
| 43 | + rx[j] = value; |
| 44 | + } |
| 45 | + } |
| 46 | + } |
| 47 | + return 0; |
| 48 | +} |
| 49 | + |
| 50 | +static int loopback_init(const struct emul *target, const struct device *parent) { |
| 51 | + ARG_UNUSED(target); |
| 52 | + ARG_UNUSED(parent); |
| 53 | + return 0; |
| 54 | +} |
| 55 | + |
| 56 | +static const struct spi_emul_api loopback_api = { |
| 57 | + .io = loopback_io, |
| 58 | +}; |
| 59 | + |
| 60 | +#define LOOPBACK_DEFINE(n) \ |
| 61 | + DEVICE_DT_INST_DEFINE(n, NULL, NULL, NULL, NULL, POST_KERNEL, CONFIG_SPI_INIT_PRIORITY, NULL); \ |
| 62 | + EMUL_DT_INST_DEFINE(n, loopback_init, NULL, NULL, &loopback_api, NULL); |
| 63 | + |
| 64 | +DT_INST_FOREACH_STATUS_OKAY(LOOPBACK_DEFINE) |
0 commit comments