mirror of
https://github.com/PX4/PX4-Autopilot.git
synced 2026-11-25 16:51:16 +08:00
feat(drivers): implemented serial passthrough (#27605)
* feat: implemented serial passthrough * fix: used make format * fix: changed function order to match other drivers * fix: moved passthrough from systemcmds to drivers * fix: renamed BITBANG_TIMER to UART_BITBANG_TIMER * fix: used make format * feat: added PASSTHRU_EN guard to start of dshot&pwm_out * fix: made changing ESC channels more stable * fix: adjusted naming of guards * fix: changed include guard of bitbang * fix: removed unused variable SER_PASS_BAUD * fix: adjusted comments * fix: adjusted print_usage() to match other drivers * fix: remove bitbang_write_byte from public API and some buffer guard * fix: added Serialpassthrough&Bitbang to exclude list of allyesconfig.py * fix: added missing flag to print_usage()
This commit is contained in:
1 parent
add48c25a6
commit
f2eecc33f7
20 files changed
+1752
-6
No files matched your search
@@ -539,8 +539,13 @@ else
|
||||
else
|
||||
commander start
|
||||
|
||||
dshot start
|
||||
pwm_out start
|
||||
if param compare -s PASSTHRU_EN 0
|
||||
then
|
||||
dshot start
|
||||
pwm_out start
|
||||
else
|
||||
param set PASSTHRU_EN 0
|
||||
fi
|
||||
fi
|
||||
|
||||
#
|
||||
|
||||
@@ -54,6 +54,8 @@ exception_list = [
|
||||
'MODULES_MUORB_APPS', # Weird QURT/Posix package doesn't work on x86 px4 sitl
|
||||
'MODULES_SIMULATION_SIMULATOR_SIH', # Causes compile errors
|
||||
'MODULES_SPACECRAFT', # Clashes with Control Allocation (mom's spaghetti code)
|
||||
'DRIVERS_SERIALPASSTHROUGH', # Requires board-specific UART config and NuttX
|
||||
'SERIALPASSTHROUGH_BITBANG', # Requires STM32 timer and GPIO config
|
||||
]
|
||||
|
||||
exception_list_sitl = [
|
||||
@@ -110,6 +112,7 @@ exception_list_sitl = [
|
||||
'SYSTEMCMDS_USB_CONNECTED', # Not supported in SITL
|
||||
'SYSTEMCMDS_MFT_CFG', # Not supported in SITL
|
||||
'MODULES_SPACECRAFT', # Clashes with Control Allocation (mom's spaghetti code)
|
||||
'DRIVERS_SERIALPASSTHROUGH', # Not supported in SITL
|
||||
]
|
||||
|
||||
def main():
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
CONFIG_BOARD_TOOLCHAIN="arm-none-eabi"
|
||||
CONFIG_BOARD_ARCHITECTURE="cortex-m7"
|
||||
CONFIG_ARCH_CHIP_STM32H7=y
|
||||
CONFIG_BOARD_ETHERNET=y
|
||||
CONFIG_BOARD_SERIAL_GPS1="/dev/ttyS6"
|
||||
CONFIG_BOARD_SERIAL_TEL1="/dev/ttyS0"
|
||||
@@ -95,4 +96,6 @@ CONFIG_SYSTEMCMDS_TOPIC_LISTENER=y
|
||||
CONFIG_SYSTEMCMDS_UORB=y
|
||||
CONFIG_SYSTEMCMDS_VER=y
|
||||
CONFIG_SYSTEMCMDS_WORK_QUEUE=y
|
||||
CONFIG_DRIVERS_SERIALPASSTHROUGH=y
|
||||
CONFIG_SERIALPASSTHROUGH_BITBANG=y
|
||||
CONFIG_WQ_TTY_STACKSIZE=2500
|
||||
@@ -244,6 +244,7 @@ CONFIG_STM32H7_TIM3=y
|
||||
CONFIG_STM32H7_TIM4=y
|
||||
CONFIG_STM32H7_TIM5=y
|
||||
CONFIG_STM32H7_TIM8=y
|
||||
CONFIG_STM32H7_TIM13=y
|
||||
CONFIG_STM32H7_UART4=y
|
||||
CONFIG_STM32H7_UART5=y
|
||||
CONFIG_STM32H7_UART7=y
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
CONFIG_BOARD_TOOLCHAIN="arm-none-eabi"
|
||||
CONFIG_BOARD_ARCHITECTURE="cortex-m7"
|
||||
CONFIG_ARCH_CHIP_STM32H7=y
|
||||
CONFIG_BOARD_ETHERNET=y
|
||||
CONFIG_BOARD_SERIAL_GPS1="/dev/ttyS0"
|
||||
CONFIG_BOARD_SERIAL_GPS2="/dev/ttyS7"
|
||||
@@ -99,3 +100,5 @@ CONFIG_SYSTEMCMDS_TUNE_CONTROL=y
|
||||
CONFIG_SYSTEMCMDS_UORB=y
|
||||
CONFIG_SYSTEMCMDS_VER=y
|
||||
CONFIG_SYSTEMCMDS_WORK_QUEUE=y
|
||||
CONFIG_DRIVERS_SERIALPASSTHROUGH=y
|
||||
CONFIG_SERIALPASSTHROUGH_BITBANG=y
|
||||
@@ -257,6 +257,7 @@ CONFIG_STM32H7_TIM12=y
|
||||
CONFIG_STM32H7_TIM1=y
|
||||
CONFIG_STM32H7_TIM4=y
|
||||
CONFIG_STM32H7_TIM5=y
|
||||
CONFIG_STM32H7_TIM13=y
|
||||
CONFIG_STM32H7_UART4=y
|
||||
CONFIG_STM32H7_UART5=y
|
||||
CONFIG_STM32H7_UART7=y
|
||||
|
||||
@@ -0,0 +1,37 @@
|
||||
############################################################################
|
||||
#
|
||||
# Copyright (c) 2026 PX4 Development Team. All rights reserved.
|
||||
#
|
||||
# Redistribution and use in source and binary forms, with or without
|
||||
# modification, are permitted provided that the following conditions
|
||||
# are met:
|
||||
#
|
||||
# 1. Redistributions of source code must retain the above copyright
|
||||
# notice, this list of conditions and the following disclaimer.
|
||||
# 2. Redistributions in binary form must reproduce the above copyright
|
||||
# notice, this list of conditions and the following disclaimer in
|
||||
# the documentation and/or other materials provided with the
|
||||
# distribution.
|
||||
# 3. Neither the name PX4 nor the names of its contributors may be
|
||||
# used to endorse or promote products derived from this software
|
||||
# without specific prior written permission.
|
||||
#
|
||||
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
|
||||
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
|
||||
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
|
||||
# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
|
||||
# COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
|
||||
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
|
||||
# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
|
||||
# OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
|
||||
# AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
|
||||
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
|
||||
# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
|
||||
# POSSIBILITY OF SUCH DAMAGE.
|
||||
#
|
||||
############################################################################
|
||||
|
||||
px4_add_library(arch_bitbang_uart
|
||||
bitbang_uart.cpp
|
||||
)
|
||||
target_compile_options(arch_bitbang_uart PRIVATE ${MAX_CUSTOM_OPT_LEVEL})
|
||||
@@ -0,0 +1,534 @@
|
||||
/****************************************************************************
|
||||
*
|
||||
* Copyright (c) 2026 PX4 Development Team. All rights reserved.
|
||||
*
|
||||
* Redistribution and use in source and binary forms, with or without
|
||||
* modification, are permitted provided that the following conditions
|
||||
* are met:
|
||||
*
|
||||
* 1. Redistributions of source code must retain the above copyright
|
||||
* notice, this list of conditions and the following disclaimer.
|
||||
* 2. Redistributions in binary form must reproduce the above copyright
|
||||
* notice, this list of conditions and the following disclaimer in
|
||||
* the documentation and/or other materials provided with the
|
||||
* distribution.
|
||||
* 3. Neither the name PX4 nor the names of its contributors may be
|
||||
* used to endorse or promote products derived from this software
|
||||
* without specific prior written permission.
|
||||
*
|
||||
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
|
||||
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
|
||||
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
|
||||
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
|
||||
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
|
||||
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
|
||||
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
|
||||
* OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
|
||||
* AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
|
||||
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
|
||||
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
|
||||
* POSSIBILITY OF SUCH DAMAGE.
|
||||
*
|
||||
****************************************************************************/
|
||||
|
||||
/**
|
||||
* @file bitbang_uart.cpp
|
||||
*
|
||||
* Simple bit-bang UART using timer for periodic interrupts and direct GPIO control.
|
||||
* Note: due to interrupt latency and CPU overhead, reliable operation is only
|
||||
* guaranteed up to 19200 baud. Higher baud rates are not supported.
|
||||
*/
|
||||
|
||||
#include <drivers/drv_bitbang_uart.h>
|
||||
|
||||
#include <px4_platform_common/px4_config.h>
|
||||
#include <px4_platform_common/log.h>
|
||||
#include <px4_platform_common/atomic.h>
|
||||
#include <drivers/drv_hrt.h>
|
||||
|
||||
#include <px4_arch/io_timer.h>
|
||||
#include <board_config.h>
|
||||
|
||||
#include <stm32_tim.h>
|
||||
#include <stm32_gpio.h>
|
||||
#include <nuttx/arch.h>
|
||||
#include <nuttx/irq.h>
|
||||
|
||||
#include <string.h>
|
||||
#include <errno.h>
|
||||
|
||||
#if !defined(CONFIG_ARCH_CHIP_STM32F7) && !defined(CONFIG_ARCH_CHIP_STM32H7)
|
||||
# error "Not supported on this MCU, requires STM32 based MCU"
|
||||
#endif
|
||||
|
||||
// Timer interrupt sources
|
||||
#define GTIM_SR_UIF (1 << 0)
|
||||
#define GTIM_DIER_UIE (1 << 0)
|
||||
|
||||
// UART frame format: 8N1 (8 data bits, no parity, 1 stop bit)
|
||||
#define MAX_UART_CHANNELS 8
|
||||
#define UART_TOTAL_BITS 10 // Start + 8 data + Stop
|
||||
#define TX_BUFFER_SIZE 512 // Circular buffer for queued bytes
|
||||
#define RX_BUFFER_SIZE 512 // Circular buffer for received bytes
|
||||
|
||||
typedef struct {
|
||||
// Configuration
|
||||
uint8_t channel;
|
||||
uint32_t gpio_pin;
|
||||
uint32_t bit_time_ticks;
|
||||
bool initialized;
|
||||
bool single_wire; // true = half-duplex (TX and RX share one GPIO); false = full-duplex (not yet implemented)
|
||||
struct stm32_tim_dev_s *timer;
|
||||
|
||||
// TX state
|
||||
px4::atomic_bool tx_busy;
|
||||
uint16_t tx_shift_reg;
|
||||
uint8_t tx_bit_count;
|
||||
|
||||
// TX buffer (circular queue)
|
||||
uint8_t tx_buffer[TX_BUFFER_SIZE];
|
||||
volatile uint16_t tx_head; // Write position
|
||||
volatile uint16_t tx_tail; // Read position
|
||||
|
||||
// RX state
|
||||
volatile bool rx_in_progress;
|
||||
volatile uint16_t rx_shift_reg;
|
||||
volatile uint8_t rx_bit_count;
|
||||
|
||||
// RX buffer (circular queue)
|
||||
uint8_t rx_buffer[RX_BUFFER_SIZE];
|
||||
volatile uint16_t rx_head; // Write position (interrupt)
|
||||
volatile uint16_t rx_tail; // Read position (user)
|
||||
|
||||
} bitbang_uart_t;
|
||||
|
||||
// Single UART instance (only one channel active at a time)
|
||||
static bitbang_uart_t uart = {};
|
||||
|
||||
// Forward declarations
|
||||
static int gpio_rx_interrupt_callback(int irq, void *context, void *arg);
|
||||
|
||||
// Helper function to enable/disable GPIO interrupt for RX
|
||||
static int set_gpio_interrupt(bool enable)
|
||||
{
|
||||
if (enable) {
|
||||
// Stop timer
|
||||
STM32_TIM_SETMODE(uart.timer, STM32_TIM_MODE_DISABLED);
|
||||
|
||||
px4_arch_gpiowrite(uart.gpio_pin, true);
|
||||
// Configure new GPIO as input with pullup for RX
|
||||
px4_arch_configgpio(PX4_MAKE_GPIO_INPUT(uart.gpio_pin));
|
||||
|
||||
// Enable falling edge interrupt for start bit detection
|
||||
return px4_arch_gpiosetevent(PX4_MAKE_GPIO_EXTI(uart.gpio_pin), false, true, true, &gpio_rx_interrupt_callback, &uart);
|
||||
|
||||
} else {
|
||||
// Disable interrupt
|
||||
return px4_arch_gpiosetevent(PX4_MAKE_GPIO_EXTI(uart.gpio_pin), false, false, false, nullptr, nullptr);
|
||||
}
|
||||
}
|
||||
|
||||
// TIM update interrupt handler - fires every bit period
|
||||
static int timer_update_isr(int, void *, void *)
|
||||
{
|
||||
// Clear update interrupt flag
|
||||
STM32_TIM_ACKINT(uart.timer, GTIM_SR_UIF);
|
||||
|
||||
// Handle TX
|
||||
if (uart.tx_busy.load()) {
|
||||
// Get current bit value from shift register
|
||||
bool bit_value = (uart.tx_shift_reg >> uart.tx_bit_count) & 0x01;
|
||||
|
||||
// Set GPIO directly
|
||||
px4_arch_gpiowrite(uart.gpio_pin, bit_value);
|
||||
|
||||
uart.tx_bit_count++;
|
||||
|
||||
// Check if transmission complete
|
||||
if (uart.tx_bit_count >= UART_TOTAL_BITS) {
|
||||
// Check if there's more data in the buffer
|
||||
if (uart.tx_tail != uart.tx_head) {
|
||||
// Start next byte immediately without returning to scheduler
|
||||
uint8_t next_byte = uart.tx_buffer[uart.tx_tail];
|
||||
uart.tx_tail = (uart.tx_tail + 1) % TX_BUFFER_SIZE;
|
||||
|
||||
// Build frame for next byte
|
||||
uart.tx_shift_reg = 0;
|
||||
uart.tx_shift_reg |= (0 << 0); // Start bit
|
||||
uart.tx_shift_reg |= (next_byte << 1); // Data bits
|
||||
uart.tx_shift_reg |= (1 << 9); // Stop bit
|
||||
uart.tx_bit_count = 0;
|
||||
// tx_busy stays true
|
||||
|
||||
} else {
|
||||
// No more data, stop transmitting
|
||||
uart.tx_busy.store(false);
|
||||
|
||||
// Clear RX buffer
|
||||
uart.rx_tail = uart.rx_head;
|
||||
|
||||
// Re-enable RX interrupt after transmission
|
||||
set_gpio_interrupt(true);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Handle RX
|
||||
else if (uart.rx_in_progress) {
|
||||
// Sample current pin state
|
||||
bool bit_value = px4_arch_gpioread(uart.gpio_pin);
|
||||
|
||||
// Accumulate all bits as seen on the wire
|
||||
if (bit_value) {
|
||||
uart.rx_shift_reg |= (1 << uart.rx_bit_count);
|
||||
}
|
||||
|
||||
uart.rx_bit_count++;
|
||||
|
||||
// Check if we've received the complete frame (start + 8 data + stop)
|
||||
if (uart.rx_bit_count >= UART_TOTAL_BITS) {
|
||||
// Extract data bits (bits 1-8) and reverse them (LSB-first on wire -> MSB-first in byte)
|
||||
const uint8_t received_byte = (uart.rx_shift_reg >> 1) & 0xFF; // Skip start bit, get bits 1-8
|
||||
|
||||
uart.rx_in_progress = false;
|
||||
|
||||
// Store byte in RX buffer
|
||||
uint16_t next_head = (uart.rx_head + 1) % RX_BUFFER_SIZE;
|
||||
|
||||
if (next_head != uart.rx_tail) {
|
||||
// Buffer not full, store byte
|
||||
uart.rx_buffer[uart.rx_head] = received_byte;
|
||||
uart.rx_head = next_head;
|
||||
}
|
||||
|
||||
// If buffer full, drop byte (overrun)
|
||||
|
||||
// Re-enable start bit detection
|
||||
set_gpio_interrupt(true);
|
||||
}
|
||||
}
|
||||
|
||||
return OK;
|
||||
}
|
||||
|
||||
// GPIO interrupt handler for RX - detects start bit only
|
||||
static int gpio_rx_interrupt_callback(int irq, void *context, void *arg)
|
||||
{
|
||||
// Start bit detection (high to low transition)
|
||||
if (!uart.rx_in_progress) {
|
||||
// Disable further start bit detection until this byte completes
|
||||
set_gpio_interrupt(false);
|
||||
|
||||
uart.rx_in_progress = true;
|
||||
uart.rx_shift_reg = 0;
|
||||
uart.rx_bit_count = 0;
|
||||
|
||||
// Configure timer to sample in middle of each bit period
|
||||
STM32_TIM_SETCOUNTER(uart.timer, uart.bit_time_ticks / 2);
|
||||
|
||||
// Clear any pending update interrupt
|
||||
STM32_TIM_ACKINT(uart.timer, GTIM_SR_UIF);
|
||||
|
||||
// Start timer for RX sampling
|
||||
STM32_TIM_SETMODE(uart.timer, STM32_TIM_MODE_UP);
|
||||
}
|
||||
|
||||
return OK;
|
||||
}
|
||||
|
||||
static bool tim_initialized = false;
|
||||
// Shared timer initialization (call once)
|
||||
static int bitbang_uart_init_timer(uint32_t baudrate)
|
||||
{
|
||||
if (tim_initialized) {
|
||||
return 0; // Already initialized
|
||||
}
|
||||
|
||||
uart.bit_time_ticks = 1000000 / baudrate; // Assume 1MHz timer
|
||||
|
||||
// Initialize timer using NuttX API
|
||||
uart.timer = stm32_tim_init(CONFIG_UART_BITBANG_TIMER);
|
||||
|
||||
if (uart.timer == nullptr) {
|
||||
PX4_ERR("Failed to initialize timer %d", CONFIG_UART_BITBANG_TIMER);
|
||||
return -1;
|
||||
}
|
||||
|
||||
// Set timer to 1MHz clock
|
||||
STM32_TIM_SETCLOCK(uart.timer, 1000000);
|
||||
|
||||
// Set period for baud rate
|
||||
STM32_TIM_SETPERIOD(uart.timer, uart.bit_time_ticks - 1);
|
||||
|
||||
// Attach interrupt handler for update event
|
||||
STM32_TIM_SETISR(uart.timer, timer_update_isr, nullptr, 0);
|
||||
|
||||
// Enable update interrupt
|
||||
STM32_TIM_ENABLEINT(uart.timer, GTIM_DIER_UIE);
|
||||
|
||||
tim_initialized = true;
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
int bitbang_uart_init(uint32_t baudrate, bool single_wire)
|
||||
{
|
||||
if (!single_wire) {
|
||||
PX4_ERR("bitbang_uart: full-duplex (dual-wire) mode is not yet implemented");
|
||||
return -ENOSYS;
|
||||
}
|
||||
|
||||
// Initialize timer once (shared across all channels)
|
||||
int ret = bitbang_uart_init_timer(baudrate);
|
||||
|
||||
if (ret != 0) {
|
||||
return ret;
|
||||
}
|
||||
|
||||
// Initialize structure (no channel yet)
|
||||
uart.channel = 0xFF; // Mark as no channel selected
|
||||
uart.initialized = true;
|
||||
uart.single_wire = single_wire;
|
||||
|
||||
// Set all ESC signal pins (channels 0-3) to high (idle state)
|
||||
for (uint8_t ch = 0; ch < MAX_UART_CHANNELS; ch++) {
|
||||
uint32_t gpio_pin = io_timer_channel_get_gpio_output(ch);
|
||||
PX4_DEBUG("bitbang_uart_init: channel %u gpio_pin=0x%08lx", ch, (unsigned long)gpio_pin);
|
||||
|
||||
if (gpio_pin == 0) {
|
||||
PX4_WARN("bitbang_uart_init: channel %u has no GPIO pin (not in timer_config?)", ch);
|
||||
continue;
|
||||
}
|
||||
|
||||
px4_arch_configgpio(PX4_MAKE_GPIO_OUTPUT_SET(gpio_pin));
|
||||
}
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
int bitbang_uart_switch_channel(uint8_t channel)
|
||||
{
|
||||
if (channel >= MAX_UART_CHANNELS) {
|
||||
return -EINVAL;
|
||||
}
|
||||
|
||||
if (!uart.initialized) {
|
||||
return -EINVAL;
|
||||
}
|
||||
|
||||
// If already on this channel, nothing to do
|
||||
if (uart.channel == channel) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
// Disable previous channel's RX interrupt if a channel was active
|
||||
if (uart.channel != 0xFF) {
|
||||
set_gpio_interrupt(false);
|
||||
|
||||
// Wait for any ongoing TX to complete
|
||||
while (uart.tx_busy.load()) {
|
||||
px4_usleep(10);
|
||||
}
|
||||
|
||||
// Stop the timer and clear any pending interrupt so a remaining RX
|
||||
// transfer cannot fire and overwrite the buffer state
|
||||
STM32_TIM_SETMODE(uart.timer, STM32_TIM_MODE_DISABLED);
|
||||
STM32_TIM_ACKINT(uart.timer, GTIM_SR_UIF);
|
||||
}
|
||||
|
||||
// Reset TX/RX buffers to avoid stale data from the previous channel
|
||||
uart.tx_head = 0;
|
||||
uart.tx_tail = 0;
|
||||
uart.rx_head = 0;
|
||||
uart.rx_tail = 0;
|
||||
uart.rx_in_progress = false;
|
||||
|
||||
// Update to new channel
|
||||
uart.channel = channel;
|
||||
uart.gpio_pin = io_timer_channel_get_gpio_output(channel);
|
||||
PX4_DEBUG("bitbang_uart_switch_channel: channel %u gpio_pin=0x%08lx", channel, (unsigned long)uart.gpio_pin);
|
||||
|
||||
if (uart.gpio_pin == 0) {
|
||||
PX4_ERR("bitbang_uart_switch_channel: channel %u has no GPIO pin", channel);
|
||||
return -EINVAL;
|
||||
}
|
||||
|
||||
// Set up interrupt on falling edge for start bit detection
|
||||
int ret = set_gpio_interrupt(true);
|
||||
|
||||
if (ret != PX4_OK) {
|
||||
PX4_ERR("Failed to setup GPIO interrupt for channel %d", channel);
|
||||
return ret;
|
||||
}
|
||||
|
||||
PX4_DEBUG("Switched to channel %d", channel);
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
int bitbang_uart_deinit()
|
||||
{
|
||||
if (!uart.initialized) {
|
||||
return -EINVAL;
|
||||
}
|
||||
|
||||
// Disable RX interrupt if a channel is active
|
||||
if (uart.channel != 0xFF) {
|
||||
set_gpio_interrupt(false);
|
||||
}
|
||||
|
||||
// Wait for TX to complete
|
||||
while (uart.tx_busy.load()) {
|
||||
px4_usleep(100);
|
||||
}
|
||||
|
||||
// Disable timer interrupts
|
||||
STM32_TIM_DISABLEINT(uart.timer, GTIM_DIER_UIE);
|
||||
|
||||
// Detach interrupt handler
|
||||
STM32_TIM_SETISR(uart.timer, nullptr, nullptr, 0);
|
||||
|
||||
// Stop timer
|
||||
STM32_TIM_SETMODE(uart.timer, STM32_TIM_MODE_DISABLED);
|
||||
|
||||
// Deinitialize timer
|
||||
stm32_tim_deinit(uart.timer);
|
||||
uart.timer = nullptr;
|
||||
|
||||
uart.initialized = false;
|
||||
tim_initialized = false;
|
||||
uart.channel = 0xFF;
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
static int bitbang_uart_write_byte(uint8_t channel, uint8_t byte)
|
||||
{
|
||||
if (!uart.initialized) {
|
||||
return -EINVAL;
|
||||
}
|
||||
|
||||
// Switch to requested channel if needed
|
||||
int ret = bitbang_uart_switch_channel(channel);
|
||||
|
||||
if (ret != 0) {
|
||||
return ret;
|
||||
}
|
||||
|
||||
// Check if buffer is full
|
||||
uint16_t next_head = (uart.tx_head + 1) % TX_BUFFER_SIZE;
|
||||
|
||||
while (next_head == uart.tx_tail) {
|
||||
// Buffer full, wait
|
||||
px4_usleep(10);
|
||||
}
|
||||
|
||||
// Add byte to buffer
|
||||
uart.tx_buffer[uart.tx_head] = byte;
|
||||
uart.tx_head = next_head;
|
||||
|
||||
// If not currently transmitting, start transmission
|
||||
if (!uart.tx_busy.load()) {
|
||||
// In single-wire mode, disable RX interrupt during TX (shared GPIO)
|
||||
if (uart.single_wire) {
|
||||
set_gpio_interrupt(false);
|
||||
}
|
||||
|
||||
// Reconfigure GPIO as output for transmission
|
||||
px4_arch_configgpio(PX4_MAKE_GPIO_OUTPUT_SET(uart.gpio_pin));
|
||||
|
||||
// Get first byte from buffer
|
||||
uint8_t first_byte = uart.tx_buffer[uart.tx_tail];
|
||||
uart.tx_tail = (uart.tx_tail + 1) % TX_BUFFER_SIZE;
|
||||
|
||||
// Build frame: START(0) + DATA(8 bits) + STOP(1)
|
||||
uart.tx_shift_reg = 0;
|
||||
uart.tx_shift_reg |= (0 << 0); // Start bit
|
||||
uart.tx_shift_reg |= (first_byte << 1); // Data bits
|
||||
uart.tx_shift_reg |= (1 << 9); // Stop bit
|
||||
|
||||
uart.tx_bit_count = 0;
|
||||
uart.tx_busy.store(true);
|
||||
|
||||
// Reset timer counter
|
||||
STM32_TIM_SETCOUNTER(uart.timer, 0);
|
||||
|
||||
// Clear any pending update interrupt
|
||||
STM32_TIM_ACKINT(uart.timer, GTIM_SR_UIF);
|
||||
|
||||
// Start timer
|
||||
STM32_TIM_SETMODE(uart.timer, STM32_TIM_MODE_UP);
|
||||
}
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
int bitbang_uart_write(uint8_t channel, const uint8_t *data, size_t length)
|
||||
{
|
||||
if (!uart.initialized) {
|
||||
return -EINVAL;
|
||||
}
|
||||
|
||||
if (length == 0) {
|
||||
return -EINVAL;
|
||||
}
|
||||
|
||||
// Switch to requested channel if needed
|
||||
int ret = bitbang_uart_switch_channel(channel);
|
||||
|
||||
if (ret != 0) {
|
||||
return ret;
|
||||
}
|
||||
|
||||
for (size_t i = 0; i < length; i++) {
|
||||
ret = bitbang_uart_write_byte(channel, data[i]);
|
||||
|
||||
if (ret < 0) {
|
||||
return ret;
|
||||
}
|
||||
}
|
||||
|
||||
// Wait for last byte to complete
|
||||
while (uart.tx_busy.load()) {
|
||||
px4_usleep(10);
|
||||
}
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
int bitbang_uart_read(uint8_t channel, uint8_t *data, size_t length, uint32_t timeout_us)
|
||||
{
|
||||
if (!uart.initialized || !data || length == 0) {
|
||||
return -EINVAL;
|
||||
}
|
||||
|
||||
// Switch to requested channel if needed
|
||||
int ret = bitbang_uart_switch_channel(channel);
|
||||
|
||||
if (ret != 0) {
|
||||
return ret;
|
||||
}
|
||||
|
||||
hrt_abstime deadline = hrt_absolute_time() + timeout_us;
|
||||
size_t bytes_read = 0;
|
||||
|
||||
while (bytes_read < length) {
|
||||
// Check for timeout
|
||||
if (timeout_us > 0 && hrt_absolute_time() >= deadline) {
|
||||
break; // Return partial read on timeout
|
||||
}
|
||||
|
||||
// Check if data available
|
||||
if (uart.rx_tail != uart.rx_head) {
|
||||
// Read byte from buffer
|
||||
data[bytes_read++] = uart.rx_buffer[uart.rx_tail];
|
||||
uart.rx_tail = (uart.rx_tail + 1) % RX_BUFFER_SIZE;
|
||||
|
||||
} else {
|
||||
// No data available, yield briefly
|
||||
px4_usleep(10);
|
||||
}
|
||||
}
|
||||
|
||||
return bytes_read;
|
||||
}
|
||||
@@ -44,5 +44,9 @@ add_subdirectory(../stm32_common/spi spi)
|
||||
add_subdirectory(../stm32_common/tone_alarm tone_alarm)
|
||||
add_subdirectory(../stm32_common/version version)
|
||||
|
||||
if(CONFIG_SERIALPASSTHROUGH_BITBANG)
|
||||
add_subdirectory(../stm32_common/bitbang_uart bitbang_uart)
|
||||
endif()
|
||||
|
||||
add_subdirectory(px4io_serial)
|
||||
add_subdirectory(watchdog)
|
||||
@@ -45,4 +45,8 @@ add_subdirectory(../stm32_common/spi spi)
|
||||
add_subdirectory(../stm32_common/tone_alarm tone_alarm)
|
||||
add_subdirectory(../stm32_common/version version)
|
||||
|
||||
if(CONFIG_SERIALPASSTHROUGH_BITBANG)
|
||||
add_subdirectory(../stm32_common/bitbang_uart bitbang_uart)
|
||||
endif()
|
||||
|
||||
add_subdirectory(px4io_serial)
|
||||
@@ -0,0 +1,95 @@
|
||||
/****************************************************************************
|
||||
*
|
||||
* Copyright (c) 2026 PX4 Development Team. All rights reserved.
|
||||
*
|
||||
* Redistribution and use in source and binary forms, with or without
|
||||
* modification, are permitted provided that the following conditions
|
||||
* are met:
|
||||
*
|
||||
* 1. Redistributions of source code must retain the above copyright
|
||||
* notice, this list of conditions and the following disclaimer.
|
||||
* 2. Redistributions in binary form must reproduce the above copyright
|
||||
* notice, this list of conditions and the following disclaimer in
|
||||
* the documentation and/or other materials provided with the
|
||||
* distribution.
|
||||
* 3. Neither the name PX4 nor the names of its contributors may be
|
||||
* used to endorse or promote products derived from this software
|
||||
* without specific prior written permission.
|
||||
*
|
||||
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
|
||||
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
|
||||
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
|
||||
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
|
||||
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
|
||||
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
|
||||
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
|
||||
* OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
|
||||
* AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
|
||||
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
|
||||
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
|
||||
* POSSIBILITY OF SUCH DAMAGE.
|
||||
*
|
||||
****************************************************************************/
|
||||
|
||||
/**
|
||||
* @file drv_bitbang_uart.h
|
||||
*
|
||||
* Architecture-agnostic interface for bit-bang UART.
|
||||
*
|
||||
* Currently implemented for STM32F7/H7 in:
|
||||
* platforms/nuttx/src/px4/stm/stm32_common/bitbang_uart/
|
||||
*
|
||||
* NOTE: Currently only single-wire (half-duplex) operation is implemented.
|
||||
* The single_wire flag is provided in the API to make this explicit and to
|
||||
* allow future extension to dual-wire (full-duplex) operation.
|
||||
*/
|
||||
|
||||
#pragma once
|
||||
|
||||
#include <stdint.h>
|
||||
#include <stdbool.h>
|
||||
#include <stddef.h>
|
||||
|
||||
#include <px4_platform_common/defines.h>
|
||||
|
||||
__BEGIN_DECLS
|
||||
|
||||
/**
|
||||
* Initialize bit-bang UART
|
||||
*
|
||||
* @param baudrate Baudrate (typically 19200)
|
||||
* @param single_wire True for single-wire half-duplex (TX and RX share one GPIO).
|
||||
* False for dual-wire full-duplex (separate TX/RX GPIOs) — not yet implemented.
|
||||
* @return 0 on success, negative error code on failure
|
||||
*/
|
||||
int bitbang_uart_init(uint32_t baudrate, bool single_wire);
|
||||
|
||||
/**
|
||||
* Deinitialize bit-bang UART
|
||||
*
|
||||
* @return 0 on success, negative error code on failure
|
||||
*/
|
||||
int bitbang_uart_deinit(void);
|
||||
|
||||
/**
|
||||
* Transmit multiple bytes
|
||||
*
|
||||
* @param channel Timer/GPIO channel
|
||||
* @param data Pointer to data buffer
|
||||
* @param length Number of bytes to transmit
|
||||
* @return Number of bytes transmitted, or negative error code on failure
|
||||
*/
|
||||
int bitbang_uart_write(uint8_t channel, const uint8_t *data, size_t length);
|
||||
|
||||
/**
|
||||
* Read received bytes (blocking with timeout)
|
||||
*
|
||||
* @param channel Timer/GPIO channel
|
||||
* @param data Pointer to buffer for received data
|
||||
* @param length Number of bytes to read
|
||||
* @param timeout_us Timeout in microseconds (0 = block until length bytes received)
|
||||
* @return Number of bytes actually read
|
||||
*/
|
||||
int bitbang_uart_read(uint8_t channel, uint8_t *data, size_t length, uint32_t timeout_us);
|
||||
|
||||
__END_DECLS
|
||||
@@ -0,0 +1,47 @@
|
||||
############################################################################
|
||||
#
|
||||
# Copyright (c) 2025 PX4 Development Team. All rights reserved.
|
||||
#
|
||||
# Redistribution and use in source and binary forms, with or without
|
||||
# modification, are permitted provided that the following conditions
|
||||
# are met:
|
||||
#
|
||||
# 1. Redistributions of source code must retain the above copyright
|
||||
# notice, this list of conditions and the following disclaimer.
|
||||
# 2. Redistributions in binary form must reproduce the above copyright
|
||||
# notice, this list of conditions and the following disclaimer in
|
||||
# the documentation and/or other materials provided with the
|
||||
# distribution.
|
||||
# 3. Neither the name PX4 nor the names of its contributors may be
|
||||
# used to endorse or promote products derived from this software
|
||||
# without specific prior written permission.
|
||||
#
|
||||
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
|
||||
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
|
||||
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
|
||||
# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
|
||||
# COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
|
||||
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
|
||||
# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
|
||||
# OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
|
||||
# AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
|
||||
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
|
||||
# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
|
||||
# POSSIBILITY OF SUCH DAMAGE.
|
||||
#
|
||||
############################################################################
|
||||
|
||||
px4_add_module(
|
||||
MODULE drivers__serialpassthrough
|
||||
MAIN serialpassthrough
|
||||
SRCS
|
||||
serialpassthrough.cpp
|
||||
DEPENDS
|
||||
px4_platform
|
||||
MODULE_CONFIG
|
||||
module.yaml
|
||||
)
|
||||
|
||||
if(CONFIG_SERIALPASSTHROUGH_BITBANG)
|
||||
target_link_libraries(drivers__serialpassthrough PRIVATE arch_bitbang_uart)
|
||||
endif()
|
||||
@@ -0,0 +1,30 @@
|
||||
menuconfig DRIVERS_SERIALPASSTHROUGH
|
||||
bool "serialpassthrough"
|
||||
default n
|
||||
---help---
|
||||
Enable the serialpassthrough module.
|
||||
Forwards data between a UART and a MAVLink via
|
||||
SERIAL_CONTROL messages.
|
||||
|
||||
if DRIVERS_SERIALPASSTHROUGH
|
||||
|
||||
config SERIALPASSTHROUGH_BITBANG
|
||||
bool "Enable bit-bang UART support (ESC channel mode)"
|
||||
default n
|
||||
depends on PLATFORM_NUTTX
|
||||
---help---
|
||||
Enable bit-bang UART.
|
||||
|
||||
if SERIALPASSTHROUGH_BITBANG
|
||||
|
||||
config UART_BITBANG_TIMER
|
||||
int "Timer instance for bit-bang UART"
|
||||
default 13
|
||||
range 1 17
|
||||
---help---
|
||||
Timer instance to use for bit-bang UART timing mode.
|
||||
Default TIM13.
|
||||
|
||||
endif # SERIALPASSTHROUGH_BITBANG
|
||||
|
||||
endif # DRIVERS_SERIALPASSTHROUGH
|
||||
@@ -0,0 +1,15 @@
|
||||
module_name: Serial Passthrough (MAVLink)
|
||||
|
||||
parameters:
|
||||
- group: Serial Passthrough
|
||||
definitions:
|
||||
PASSTHRU_EN:
|
||||
description:
|
||||
short: Serial passthrough enable
|
||||
long: |
|
||||
When enabled, the serial passthrough mode is active and the
|
||||
normal motor output drivers (dshot, pwm_out) are not started
|
||||
at boot.
|
||||
type: boolean
|
||||
default: 0
|
||||
reboot_required: true
|
||||
@@ -0,0 +1,729 @@
|
||||
/****************************************************************************
|
||||
*
|
||||
* Copyright (c) 2026 PX4 Development Team. All rights reserved.
|
||||
*
|
||||
* Redistribution and use in source and binary forms, with or without
|
||||
* modification, are permitted provided that the following conditions
|
||||
* are met:
|
||||
*
|
||||
* 1. Redistributions of source code must retain the above copyright
|
||||
* notice, this list of conditions and the following disclaimer.
|
||||
* 2. Redistributions in binary form must reproduce the above copyright
|
||||
* notice, this list of conditions and the following disclaimer in
|
||||
* the documentation and/or other materials provided with the
|
||||
* distribution.
|
||||
* 3. Neither the name PX4 nor the names of its contributors may be
|
||||
* used to endorse or promote products derived from this software
|
||||
* without specific prior written permission.
|
||||
*
|
||||
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
|
||||
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
|
||||
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
|
||||
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
|
||||
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
|
||||
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
|
||||
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
|
||||
* OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
|
||||
* AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
|
||||
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
|
||||
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
|
||||
* POSSIBILITY OF SUCH DAMAGE.
|
||||
*
|
||||
****************************************************************************/
|
||||
|
||||
/**
|
||||
* @file serialpassthrough.cpp
|
||||
*
|
||||
* Serial passthrough driven by MAVLink SERIAL_CONTROL messages.
|
||||
*
|
||||
* Data flow:
|
||||
* SERIAL_CONTROL -> MavlinkReceiver::handle_message_serial_control()
|
||||
* -> SerialPassthrough::pushFromMavlink()
|
||||
* -> [mutex-protected rx buffer]
|
||||
* -> SerialPassthrough::run() drains to UART
|
||||
*
|
||||
* UART -> SerialPassthrough::run() reads to [mutex-protected tx buffer]
|
||||
* -> Mavlink::handleSerialPassthroughOutput() drains
|
||||
* -> SERIAL_CONTROL (FLAG_REPLY)
|
||||
*/
|
||||
|
||||
#include <px4_platform_common/px4_config.h>
|
||||
|
||||
#include "serialpassthrough.hpp"
|
||||
|
||||
#include <px4_platform_common/cli.h>
|
||||
#include <px4_platform_common/getopt.h>
|
||||
#include <px4_platform_common/posix.h>
|
||||
#include <px4_platform_common/log.h>
|
||||
#include <px4_platform_common/module.h>
|
||||
|
||||
#include <string.h>
|
||||
#include <errno.h>
|
||||
#include <unistd.h>
|
||||
|
||||
using device::SerialConfig::ByteSize;
|
||||
using device::SerialConfig::Parity;
|
||||
using device::SerialConfig::StopBits;
|
||||
using device::SerialConfig::FlowControl;
|
||||
|
||||
static constexpr int TASK_STACK_SIZE = PX4_STACK_ADJUSTED(1224 * 2);
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Static member definitions
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
SerialPassthrough *SerialPassthrough::_instances[SP_MAX_INSTANCES] {};
|
||||
pthread_mutex_t SerialPassthrough::_instances_mutex = PTHREAD_MUTEX_INITIALIZER;
|
||||
|
||||
SerialPassthrough::SerialPassthrough(const char *device_path, unsigned baudrate,
|
||||
bool swap_rxtx, bool single_wire, int esc_channel) :
|
||||
_serial_port(device_path, baudrate,
|
||||
ByteSize::EightBits,
|
||||
Parity::None,
|
||||
StopBits::One,
|
||||
FlowControl::Disabled),
|
||||
_baudrate(baudrate),
|
||||
_swap_rxtx(swap_rxtx),
|
||||
_single_wire(single_wire),
|
||||
_esc_channel(esc_channel)
|
||||
{
|
||||
strncpy(_dev_path, device_path, sizeof(_dev_path) - 1);
|
||||
_dev_path[sizeof(_dev_path) - 1] = '\0';
|
||||
|
||||
pthread_mutex_init(&_rx_mutex, nullptr);
|
||||
pthread_mutex_init(&_tx_mutex, nullptr);
|
||||
pthread_mutex_init(&_meta_mutex, nullptr);
|
||||
}
|
||||
|
||||
SerialPassthrough::~SerialPassthrough()
|
||||
{
|
||||
if (_serial_port.isOpen()) {
|
||||
_serial_port.close();
|
||||
}
|
||||
|
||||
pthread_mutex_destroy(&_rx_mutex);
|
||||
pthread_mutex_destroy(&_tx_mutex);
|
||||
pthread_mutex_destroy(&_meta_mutex);
|
||||
}
|
||||
|
||||
void SerialPassthrough::run()
|
||||
{
|
||||
px4_prctl(PR_SET_NAME, "serialpassthrough", px4_getpid());
|
||||
|
||||
if (_esc_channel >= 0) {
|
||||
#ifdef CONFIG_SERIALPASSTHROUGH_BITBANG
|
||||
|
||||
// --- Bitbang UART mode (motor signal pin) ---
|
||||
if (bitbang_uart_init(_baudrate, true /* single_wire */) < 0) {
|
||||
PX4_ERR("Failed to init bitbang_uart at %u baud", _baudrate);
|
||||
return;
|
||||
}
|
||||
|
||||
PX4_INFO("serialpassthrough running on ESC channel %d via bitbang at %u baud",
|
||||
_esc_channel, _baudrate);
|
||||
|
||||
while (!should_exit()) {
|
||||
// MAVLink -> ESC
|
||||
pthread_mutex_lock(&_rx_mutex);
|
||||
|
||||
if (_rx_len > 0) {
|
||||
uint8_t tmp[SP_BUF_SIZE];
|
||||
size_t to_write = _rx_len;
|
||||
memcpy(tmp, _rx_buf, to_write);
|
||||
_rx_len = 0;
|
||||
pthread_mutex_unlock(&_rx_mutex);
|
||||
|
||||
bitbang_uart_write((uint8_t)_esc_channel, tmp, to_write);
|
||||
|
||||
} else {
|
||||
pthread_mutex_unlock(&_rx_mutex);
|
||||
}
|
||||
|
||||
// ESC -> MAVLink: try to read up to 5ms
|
||||
ssize_t nread = bitbang_uart_read((uint8_t)_esc_channel,
|
||||
_ser_read_buf, sizeof(_ser_read_buf),
|
||||
5000 /* us */);
|
||||
|
||||
if (nread > 0) {
|
||||
pthread_mutex_lock(&_tx_mutex);
|
||||
size_t space = SP_BUF_SIZE - _tx_len;
|
||||
size_t to_copy = ((size_t)nread < space) ? (size_t)nread : space;
|
||||
memcpy(_tx_buf + _tx_len, _ser_read_buf, to_copy);
|
||||
_tx_len += to_copy;
|
||||
pthread_mutex_unlock(&_tx_mutex);
|
||||
}
|
||||
}
|
||||
|
||||
bitbang_uart_deinit();
|
||||
#else
|
||||
PX4_ERR("Bitbang UART not supported on this platform");
|
||||
#endif // CONFIG_SERIALPASSTHROUGH_BITBANG
|
||||
return;
|
||||
}
|
||||
|
||||
if (!_serial_port.isOpen()) {
|
||||
if (!_serial_port.open()) {
|
||||
PX4_ERR("Failed to open serial port %s", _dev_path);
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
if (_swap_rxtx) {
|
||||
_serial_port.setSwapRxTxMode();
|
||||
}
|
||||
|
||||
if (_single_wire) {
|
||||
_serial_port.setSingleWireMode();
|
||||
}
|
||||
|
||||
PX4_INFO("serialpassthrough running on %s at %u baud", _dev_path, _baudrate);
|
||||
|
||||
while (!should_exit()) {
|
||||
|
||||
// --- MAVLink -> UART ---
|
||||
pthread_mutex_lock(&_rx_mutex);
|
||||
|
||||
if (_rx_len > 0) {
|
||||
uint8_t tmp[SP_BUF_SIZE];
|
||||
size_t to_write = _rx_len;
|
||||
memcpy(tmp, _rx_buf, to_write);
|
||||
_rx_len = 0;
|
||||
pthread_mutex_unlock(&_rx_mutex);
|
||||
|
||||
_serial_port.write(tmp, to_write);
|
||||
|
||||
} else {
|
||||
pthread_mutex_unlock(&_rx_mutex);
|
||||
}
|
||||
|
||||
// --- UART -> MAVLink ---
|
||||
// Wait up to 5ms for the first byte, then drain the rest with 1ms inter-byte timeout.
|
||||
// Keep timeout short so data reaches _tx_buf quickly for the MAVLink loop to send.
|
||||
ssize_t nread = _serial_port.readAtLeast(_ser_read_buf, sizeof(_ser_read_buf), 1, 5);
|
||||
|
||||
if (nread > 0) {
|
||||
// Keep draining as long as more bytes arrive within 1ms
|
||||
while (nread < (ssize_t)sizeof(_ser_read_buf)) {
|
||||
ssize_t n = _serial_port.readAtLeast(_ser_read_buf + nread,
|
||||
sizeof(_ser_read_buf) - nread, 1, 1);
|
||||
|
||||
if (n <= 0) { break; }
|
||||
|
||||
nread += n;
|
||||
}
|
||||
|
||||
pthread_mutex_lock(&_tx_mutex);
|
||||
size_t space = SP_BUF_SIZE - _tx_len;
|
||||
size_t to_copy = ((size_t)nread < space) ? (size_t)nread : space;
|
||||
|
||||
if (to_copy < (size_t)nread) {
|
||||
PX4_WARN("serialpassthrough: tx buffer overflow, dropping %zd bytes",
|
||||
nread - (ssize_t)to_copy);
|
||||
}
|
||||
|
||||
memcpy(_tx_buf + _tx_len, _ser_read_buf, to_copy);
|
||||
_tx_len += to_copy;
|
||||
pthread_mutex_unlock(&_tx_mutex);
|
||||
}
|
||||
}
|
||||
|
||||
if (_serial_port.isOpen()) {
|
||||
_serial_port.close();
|
||||
}
|
||||
}
|
||||
|
||||
int SerialPassthrough::run_trampoline(int argc, char *argv[])
|
||||
{
|
||||
// Parse -i <device_id> before instantiate() to get the registry key.
|
||||
// This flag is injected internally by startForDevice() and is not user-facing.
|
||||
uint8_t device_id = 255;
|
||||
{
|
||||
int myoptind = 1;
|
||||
int ch;
|
||||
const char *myoptarg = nullptr;
|
||||
|
||||
while ((ch = px4_getopt(argc, argv, "b:d:e:i:sx", &myoptind, &myoptarg)) != EOF) {
|
||||
if (ch == 'i') { device_id = (uint8_t)strtoul(myoptarg, nullptr, 0); }
|
||||
}
|
||||
}
|
||||
|
||||
SerialPassthrough *instance = instantiate(argc, argv);
|
||||
|
||||
if (!instance) {
|
||||
return -1;
|
||||
}
|
||||
|
||||
if (!instance->register_instance(device_id)) {
|
||||
PX4_ERR("serialpassthrough: max instances (%d) already running", SP_MAX_INSTANCES);
|
||||
delete instance;
|
||||
return -1;
|
||||
}
|
||||
|
||||
instance->run();
|
||||
|
||||
instance->unregister_instance();
|
||||
delete instance;
|
||||
return 0;
|
||||
}
|
||||
|
||||
void SerialPassthrough::pushFromMavlink(const uint8_t *data, size_t len,
|
||||
uint8_t sysid, uint8_t compid, uint8_t device,
|
||||
uint8_t channel)
|
||||
{
|
||||
// Store reply metadata
|
||||
pthread_mutex_lock(&_meta_mutex);
|
||||
_target_sysid = sysid;
|
||||
_target_compid = compid;
|
||||
_device_id = device;
|
||||
_tx_channel = channel;
|
||||
pthread_mutex_unlock(&_meta_mutex);
|
||||
|
||||
if (len == 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
pthread_mutex_lock(&_rx_mutex);
|
||||
size_t space = SP_BUF_SIZE - _rx_len;
|
||||
size_t to_copy = (len < space) ? len : space;
|
||||
|
||||
if (to_copy < len) {
|
||||
PX4_WARN("serialpassthrough: rx buffer overflow, dropping %zu bytes", len - to_copy);
|
||||
}
|
||||
|
||||
memcpy(_rx_buf + _rx_len, data, to_copy);
|
||||
_rx_len += to_copy;
|
||||
pthread_mutex_unlock(&_rx_mutex);
|
||||
}
|
||||
|
||||
size_t SerialPassthrough::popToMavlink(uint8_t *buf, size_t max_len,
|
||||
uint8_t *out_sysid, uint8_t *out_compid, uint8_t *out_device,
|
||||
uint8_t channel)
|
||||
{
|
||||
pthread_mutex_lock(&_meta_mutex);
|
||||
uint8_t tx_channel = _tx_channel;
|
||||
*out_sysid = _target_sysid;
|
||||
*out_compid = _target_compid;
|
||||
*out_device = _device_id;
|
||||
pthread_mutex_unlock(&_meta_mutex);
|
||||
|
||||
// Only the channel that received the request should send the reply
|
||||
if (channel != tx_channel) {
|
||||
PX4_DEBUG("popToMavlink: channel %u != tx_channel %u, skipping", channel, tx_channel);
|
||||
return 0;
|
||||
}
|
||||
|
||||
pthread_mutex_lock(&_tx_mutex);
|
||||
size_t to_copy = (_tx_len < max_len) ? _tx_len : max_len;
|
||||
|
||||
if (to_copy > 0) {
|
||||
|
||||
memcpy(buf, _tx_buf, to_copy);
|
||||
_tx_len -= to_copy;
|
||||
|
||||
if (_tx_len > 0) {
|
||||
memmove(_tx_buf, _tx_buf + to_copy, _tx_len);
|
||||
}
|
||||
}
|
||||
|
||||
pthread_mutex_unlock(&_tx_mutex);
|
||||
return to_copy;
|
||||
}
|
||||
|
||||
int SerialPassthrough::startForDevice(uint8_t device_id, uint32_t baudrate)
|
||||
{
|
||||
// Map device_id to device path and options
|
||||
const char *dev = nullptr;
|
||||
bool single_wire = false;
|
||||
int esc_channel = -1;
|
||||
|
||||
switch (device_id) {
|
||||
#ifdef CONFIG_BOARD_SERIAL_TEL1
|
||||
|
||||
case 0: dev = CONFIG_BOARD_SERIAL_TEL1; break;
|
||||
#endif
|
||||
#ifdef CONFIG_BOARD_SERIAL_TEL2
|
||||
|
||||
case 1: dev = CONFIG_BOARD_SERIAL_TEL2; break;
|
||||
#endif
|
||||
#ifdef CONFIG_BOARD_SERIAL_GPS1
|
||||
|
||||
case 2: dev = CONFIG_BOARD_SERIAL_GPS1; break;
|
||||
#endif
|
||||
#ifdef CONFIG_BOARD_SERIAL_GPS2
|
||||
|
||||
case 3: dev = CONFIG_BOARD_SERIAL_GPS2; break;
|
||||
#endif
|
||||
#ifdef CONFIG_BOARD_SERIAL_TEL3
|
||||
|
||||
case 4: dev = CONFIG_BOARD_SERIAL_TEL3; break;
|
||||
#endif
|
||||
#ifdef CONFIG_BOARD_SERIAL_TEL4
|
||||
|
||||
case 5: dev = CONFIG_BOARD_SERIAL_TEL4; break;
|
||||
#endif
|
||||
#ifdef CONFIG_SERIALPASSTHROUGH_BITBANG
|
||||
|
||||
case 20: esc_channel = 0; break;
|
||||
|
||||
case 21: esc_channel = 1; break;
|
||||
|
||||
case 22: esc_channel = 2; break;
|
||||
|
||||
case 23: esc_channel = 3; break;
|
||||
|
||||
case 24: esc_channel = 4; break;
|
||||
|
||||
case 25: esc_channel = 5; break;
|
||||
|
||||
case 26: esc_channel = 6; break;
|
||||
|
||||
case 27: esc_channel = 7; break;
|
||||
#endif
|
||||
|
||||
default:
|
||||
PX4_WARN("serialpassthrough: device_id %u not supported on this board", device_id);
|
||||
return -1;
|
||||
}
|
||||
|
||||
// Check if already running on the same device_id
|
||||
SerialPassthrough *sp = get_instance_for_device(device_id);
|
||||
|
||||
if (sp) {
|
||||
PX4_DEBUG("serialpassthrough: already running for device_id %u", device_id);
|
||||
return 0;
|
||||
}
|
||||
|
||||
#ifdef CONFIG_SERIALPASSTHROUGH_BITBANG
|
||||
|
||||
if (esc_channel >= 0) {
|
||||
// The bitbang UART uses a single shared hardware timer and a single
|
||||
// global state struct — only one ESC channel can be active at a time.
|
||||
// Stop any existing bitbang instance and wait for it to exit before
|
||||
// spawning the new task, otherwise both tasks race on the shared HW
|
||||
// and corrupt each other's RX buffers via bitbang_uart_switch_channel().
|
||||
pthread_mutex_lock(&_instances_mutex);
|
||||
|
||||
for (int i = 0; i < SP_MAX_INSTANCES; i++) {
|
||||
if (_instances[i] && _instances[i]->_esc_channel >= 0) {
|
||||
_instances[i]->request_stop();
|
||||
}
|
||||
}
|
||||
|
||||
pthread_mutex_unlock(&_instances_mutex);
|
||||
|
||||
// Wait up to 100 ms (20 × 5 ms) for the old task to exit and
|
||||
// unregister itself. The bitbang run-loop polls every 5 ms, so
|
||||
// it should exit almost immediately.
|
||||
for (int i = 0; i < 20; i++) {
|
||||
bool any_bitbang = false;
|
||||
pthread_mutex_lock(&_instances_mutex);
|
||||
|
||||
for (int j = 0; j < SP_MAX_INSTANCES; j++) {
|
||||
if (_instances[j] && _instances[j]->_esc_channel >= 0) {
|
||||
any_bitbang = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
pthread_mutex_unlock(&_instances_mutex);
|
||||
|
||||
if (!any_bitbang) { break; }
|
||||
|
||||
px4_usleep(5000); // 5 ms
|
||||
}
|
||||
}
|
||||
|
||||
#endif // CONFIG_SERIALPASSTHROUGH_BITBANG
|
||||
|
||||
if (esc_channel >= 0) {
|
||||
PX4_INFO("serialpassthrough: starting on ESC bitbang channel %d at %lu baud",
|
||||
esc_channel, (unsigned long)baudrate);
|
||||
|
||||
} else {
|
||||
PX4_INFO("serialpassthrough: starting on %s at %lu baud",
|
||||
dev, (unsigned long)baudrate);
|
||||
}
|
||||
|
||||
// Build argv for task_spawn: ["start", "-d", dev, "-b", baud_str] or ["start", "-e", "0", "-b", baud_str]
|
||||
char baud_str[12];
|
||||
snprintf(baud_str, sizeof(baud_str), "%lu", (unsigned long)baudrate);
|
||||
|
||||
char esc_str[4];
|
||||
snprintf(esc_str, sizeof(esc_str), "%d", esc_channel);
|
||||
|
||||
char device_id_str[4];
|
||||
snprintf(device_id_str, sizeof(device_id_str), "%u", (unsigned)device_id);
|
||||
|
||||
const char *argv_buf[12];
|
||||
int argc = 0;
|
||||
|
||||
argv_buf[argc++] = "start";
|
||||
argv_buf[argc++] = "-i";
|
||||
argv_buf[argc++] = device_id_str;
|
||||
|
||||
if (esc_channel >= 0) {
|
||||
argv_buf[argc++] = "-e";
|
||||
argv_buf[argc++] = esc_str;
|
||||
|
||||
} else {
|
||||
argv_buf[argc++] = "-d";
|
||||
argv_buf[argc++] = dev;
|
||||
|
||||
if (single_wire) { argv_buf[argc++] = "-s"; }
|
||||
}
|
||||
|
||||
argv_buf[argc++] = "-b";
|
||||
argv_buf[argc++] = baud_str;
|
||||
argv_buf[argc] = nullptr;
|
||||
|
||||
return task_spawn(argc, (char **)argv_buf);
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Instance registry
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
bool SerialPassthrough::register_instance(uint8_t device_id)
|
||||
{
|
||||
pthread_mutex_lock(&_instances_mutex);
|
||||
|
||||
for (int i = 0; i < SP_MAX_INSTANCES; i++) {
|
||||
if (_instances[i] == nullptr) {
|
||||
_instances[i] = this;
|
||||
_registered_device_id = device_id;
|
||||
pthread_mutex_unlock(&_instances_mutex);
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
pthread_mutex_unlock(&_instances_mutex);
|
||||
return false;
|
||||
}
|
||||
|
||||
void SerialPassthrough::unregister_instance()
|
||||
{
|
||||
pthread_mutex_lock(&_instances_mutex);
|
||||
|
||||
for (int i = 0; i < SP_MAX_INSTANCES; i++) {
|
||||
if (_instances[i] == this) {
|
||||
_instances[i] = nullptr;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
pthread_mutex_unlock(&_instances_mutex);
|
||||
}
|
||||
|
||||
SerialPassthrough *SerialPassthrough::get_instance_by_index(int index)
|
||||
{
|
||||
if (index < 0 || index >= SP_MAX_INSTANCES) { return nullptr; }
|
||||
|
||||
pthread_mutex_lock(&_instances_mutex);
|
||||
SerialPassthrough *inst = _instances[index];
|
||||
pthread_mutex_unlock(&_instances_mutex);
|
||||
return inst;
|
||||
}
|
||||
|
||||
SerialPassthrough *SerialPassthrough::get_instance_for_device(uint8_t device_id)
|
||||
{
|
||||
pthread_mutex_lock(&_instances_mutex);
|
||||
|
||||
for (int i = 0; i < SP_MAX_INSTANCES; i++) {
|
||||
if (_instances[i] && _instances[i]->_registered_device_id == device_id) {
|
||||
SerialPassthrough *inst = _instances[i];
|
||||
pthread_mutex_unlock(&_instances_mutex);
|
||||
return inst;
|
||||
}
|
||||
}
|
||||
|
||||
pthread_mutex_unlock(&_instances_mutex);
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
void SerialPassthrough::stop_for_device(uint8_t device_id)
|
||||
{
|
||||
pthread_mutex_lock(&_instances_mutex);
|
||||
|
||||
for (int i = 0; i < SP_MAX_INSTANCES; i++) {
|
||||
if (_instances[i] && _instances[i]->_registered_device_id == device_id) {
|
||||
_instances[i]->request_stop();
|
||||
pthread_mutex_unlock(&_instances_mutex);
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
pthread_mutex_unlock(&_instances_mutex);
|
||||
}
|
||||
|
||||
void SerialPassthrough::stop_all()
|
||||
{
|
||||
pthread_mutex_lock(&_instances_mutex);
|
||||
|
||||
for (int i = 0; i < SP_MAX_INSTANCES; i++) {
|
||||
if (_instances[i]) {
|
||||
_instances[i]->request_stop();
|
||||
}
|
||||
}
|
||||
|
||||
pthread_mutex_unlock(&_instances_mutex);
|
||||
}
|
||||
|
||||
int SerialPassthrough::task_spawn(int argc, char *argv[])
|
||||
{
|
||||
int task_id = px4_task_spawn_cmd("serialpassthrough",
|
||||
SCHED_DEFAULT,
|
||||
SCHED_PRIORITY_DEFAULT,
|
||||
TASK_STACK_SIZE,
|
||||
run_trampoline,
|
||||
(char *const *)argv);
|
||||
|
||||
if (task_id < 0) {
|
||||
return -errno;
|
||||
}
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
SerialPassthrough *SerialPassthrough::instantiate(int argc, char *argv[])
|
||||
{
|
||||
const char *device = nullptr;
|
||||
unsigned baudrate = 115200;
|
||||
bool swap_rxtx = false;
|
||||
bool single_wire = false;
|
||||
int esc_channel = -1;
|
||||
int myoptind = 1;
|
||||
int ch;
|
||||
const char *myoptarg = nullptr;
|
||||
|
||||
while ((ch = px4_getopt(argc, argv, "b:d:e:i:sx", &myoptind, &myoptarg)) != EOF) {
|
||||
switch (ch) {
|
||||
case 'b':
|
||||
baudrate = strtoul(myoptarg, nullptr, 0);
|
||||
break;
|
||||
|
||||
case 'd':
|
||||
device = myoptarg;
|
||||
break;
|
||||
|
||||
case 'e':
|
||||
esc_channel = (int)strtol(myoptarg, nullptr, 0);
|
||||
break;
|
||||
|
||||
case 's':
|
||||
single_wire = true;
|
||||
break;
|
||||
|
||||
case 'x':
|
||||
swap_rxtx = true;
|
||||
break;
|
||||
|
||||
case 'i':
|
||||
// internal registry key injected by startForDevice(), ignore here
|
||||
break;
|
||||
|
||||
default:
|
||||
print_usage("unrecognized flag");
|
||||
return nullptr;
|
||||
}
|
||||
}
|
||||
|
||||
if (esc_channel >= 0) {
|
||||
// Bitbang mode: no device path needed
|
||||
return new SerialPassthrough("", baudrate, false, false, esc_channel);
|
||||
}
|
||||
|
||||
if (!device || access(device, R_OK | W_OK) != 0) {
|
||||
PX4_ERR("Invalid device (-d): %s", device ? device : "(not set)");
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
return new SerialPassthrough(device, baudrate, swap_rxtx, single_wire);
|
||||
}
|
||||
|
||||
int SerialPassthrough::print_status_all()
|
||||
{
|
||||
pthread_mutex_lock(&_instances_mutex);
|
||||
int count = 0;
|
||||
|
||||
for (int i = 0; i < SP_MAX_INSTANCES; i++) {
|
||||
if (_instances[i]) {
|
||||
SerialPassthrough *inst = _instances[i];
|
||||
|
||||
pthread_mutex_lock(&inst->_rx_mutex);
|
||||
size_t rx = inst->_rx_len;
|
||||
pthread_mutex_unlock(&inst->_rx_mutex);
|
||||
|
||||
pthread_mutex_lock(&inst->_tx_mutex);
|
||||
size_t tx = inst->_tx_len;
|
||||
pthread_mutex_unlock(&inst->_tx_mutex);
|
||||
|
||||
PX4_INFO("[%d] device_id=%u dev=%s baud=%u esc_ch=%d swap=%d single=%d",
|
||||
i, inst->_registered_device_id, inst->_dev_path, inst->_baudrate,
|
||||
inst->_esc_channel, (int)inst->_swap_rxtx, (int)inst->_single_wire);
|
||||
PX4_INFO(" pending rx(mavlink->uart)=%zu tx(uart->mavlink)=%zu", rx, tx);
|
||||
count++;
|
||||
}
|
||||
}
|
||||
|
||||
pthread_mutex_unlock(&_instances_mutex);
|
||||
|
||||
if (count == 0) {
|
||||
PX4_INFO("serialpassthrough: no instances running");
|
||||
}
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
int SerialPassthrough::print_usage(const char *reason)
|
||||
{
|
||||
if (reason) {
|
||||
PX4_WARN("%s\n", reason);
|
||||
}
|
||||
|
||||
PRINT_MODULE_DESCRIPTION(
|
||||
R"DESCR_STR(
|
||||
### Description
|
||||
|
||||
Serial passthrough driver driven by MAVLink SERIAL_CONTROL messages.
|
||||
Bridges a MAVLink stream to a hardware UART or an ESC signal pin (bitbang).
|
||||
|
||||
Only a single sender is supported at a time. Simultaneous SERIAL_CONTROL
|
||||
messages from multiple senders produce undefined behaviour.
|
||||
|
||||
Up to 8 instances can run simultaneously, one per device.
|
||||
)DESCR_STR");
|
||||
|
||||
PRINT_MODULE_USAGE_NAME("serialpassthrough", "driver");
|
||||
PRINT_MODULE_USAGE_COMMAND("start");
|
||||
PRINT_MODULE_USAGE_PARAM_STRING('d', nullptr, "<dev>", "Serial device path", true);
|
||||
PRINT_MODULE_USAGE_PARAM_INT('b', 115200, 0, 4000000, "Baudrate", true);
|
||||
PRINT_MODULE_USAGE_PARAM_FLAG('x', "Swap RX/TX pins", true);
|
||||
PRINT_MODULE_USAGE_PARAM_FLAG('s', "Single-wire (half-duplex) mode", true);
|
||||
PRINT_MODULE_USAGE_PARAM_INT('e', -1, 0, 7, "ESC bitbang channel (0-7), instead of -d", true);
|
||||
PRINT_MODULE_USAGE_PARAM_INT('i', -1, 0, 255, "Internal: instance registry key (injected by startForDevice())", true);
|
||||
PRINT_MODULE_USAGE_COMMAND("stop");
|
||||
PRINT_MODULE_USAGE_COMMAND("status");
|
||||
return 0;
|
||||
}
|
||||
|
||||
extern "C" __EXPORT int serialpassthrough_main(int argc, char *argv[])
|
||||
{
|
||||
if (argc < 2) {
|
||||
return SerialPassthrough::print_usage(nullptr);
|
||||
}
|
||||
|
||||
if (strcmp(argv[1], "start") == 0) {
|
||||
return SerialPassthrough::task_spawn(argc - 1, argv + 1);
|
||||
}
|
||||
|
||||
if (strcmp(argv[1], "stop") == 0) {
|
||||
SerialPassthrough::stop_all();
|
||||
return 0;
|
||||
}
|
||||
|
||||
if (strcmp(argv[1], "status") == 0) {
|
||||
return SerialPassthrough::print_status_all();
|
||||
}
|
||||
|
||||
return SerialPassthrough::print_usage("unknown command");
|
||||
}
|
||||
@@ -0,0 +1,164 @@
|
||||
/****************************************************************************
|
||||
*
|
||||
* Copyright (c) 2026 PX4 Development Team. All rights reserved.
|
||||
*
|
||||
* Redistribution and use in source and binary forms, with or without
|
||||
* modification, are permitted provided that the following conditions
|
||||
* are met:
|
||||
*
|
||||
* 1. Redistributions of source code must retain the above copyright
|
||||
* notice, this list of conditions and the following disclaimer.
|
||||
* 2. Redistributions in binary form must reproduce the above copyright
|
||||
* notice, this list of conditions and the following disclaimer in
|
||||
* the documentation and/or other materials provided with the
|
||||
* distribution.
|
||||
* 3. Neither the name PX4 nor the names of its contributors may be
|
||||
* used to endorse or promote products derived from this software
|
||||
* without specific prior written permission.
|
||||
*
|
||||
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
|
||||
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
|
||||
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
|
||||
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
|
||||
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
|
||||
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
|
||||
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
|
||||
* OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
|
||||
* AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
|
||||
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
|
||||
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
|
||||
* POSSIBILITY OF SUCH DAMAGE.
|
||||
*
|
||||
****************************************************************************/
|
||||
|
||||
/**
|
||||
* @file serialpassthrough.hpp
|
||||
*
|
||||
* Serial passthrough driven by MAVLink SERIAL_CONTROL messages.
|
||||
*
|
||||
* Exposes a thread-safe push/pop interface so MavlinkReceiver can push
|
||||
* incoming payload bytes to the UART, and the Mavlink main loop can drain
|
||||
* UART-received bytes back as SERIAL_CONTROL replies.
|
||||
*/
|
||||
|
||||
#pragma once
|
||||
|
||||
#include <px4_platform_common/px4_config.h>
|
||||
#include <px4_platform_common/atomic.h>
|
||||
#include <px4_platform_common/Serial.hpp>
|
||||
#ifdef CONFIG_SERIALPASSTHROUGH_BITBANG
|
||||
#include <drivers/drv_bitbang_uart.h>
|
||||
#endif
|
||||
#include <stdint.h>
|
||||
#include <stddef.h>
|
||||
#include <pthread.h>
|
||||
|
||||
static constexpr size_t SP_BUF_SIZE = 1024;
|
||||
static constexpr int SP_MAX_INSTANCES = 8;
|
||||
|
||||
class SerialPassthrough
|
||||
{
|
||||
public:
|
||||
SerialPassthrough(const char *device_path, unsigned baudrate, bool swap_rxtx, bool single_wire, int esc_channel = -1);
|
||||
~SerialPassthrough();
|
||||
|
||||
static int task_spawn(int argc, char *argv[]);
|
||||
static int run_trampoline(int argc, char *argv[]);
|
||||
static SerialPassthrough *instantiate(int argc, char *argv[]);
|
||||
static int print_usage(const char *reason = nullptr);
|
||||
|
||||
void run();
|
||||
|
||||
/**
|
||||
* Print status of all running instances.
|
||||
*/
|
||||
static int print_status_all();
|
||||
|
||||
/**
|
||||
* Get instance by slot index (0..SP_MAX_INSTANCES-1). Returns nullptr if slot empty.
|
||||
* Used by Mavlink main loop to iterate all instances.
|
||||
*/
|
||||
static SerialPassthrough *get_instance_by_index(int index);
|
||||
|
||||
/**
|
||||
* Get the running instance for a specific device_id. Returns nullptr if not running.
|
||||
*/
|
||||
static SerialPassthrough *get_instance_for_device(uint8_t device_id);
|
||||
|
||||
/**
|
||||
* Start an instance for a given device ID (from SERIAL_CONTROL device field).
|
||||
* Maps device IDs to board-specific UART paths using CONFIG_BOARD_SERIAL_*.
|
||||
* If already running on the same device, does nothing.
|
||||
* Device IDs: 0=TEL1, 1=TEL2, 2=GPS1, 3=GPS2, 4=TEL3, 5=TEL4, 20-27=ESC bitbang ch0-7
|
||||
* Returns 0 on success, -1 if device ID is not supported on this board.
|
||||
*/
|
||||
static int startForDevice(uint8_t device_id, uint32_t baudrate);
|
||||
|
||||
/**
|
||||
* Stop the instance for a specific device_id.
|
||||
*/
|
||||
static void stop_for_device(uint8_t device_id);
|
||||
|
||||
/**
|
||||
* Stop all running instances.
|
||||
*/
|
||||
static void stop_all();
|
||||
|
||||
/**
|
||||
* Push data received via MAVLink SERIAL_CONTROL to the UART.
|
||||
* Thread-safe; called from MavlinkReceiver thread.
|
||||
* channel: the MAVLink channel index (0-based) this arrived on.
|
||||
*/
|
||||
void pushFromMavlink(const uint8_t *data, size_t len,
|
||||
uint8_t sysid, uint8_t compid, uint8_t device,
|
||||
uint8_t channel);
|
||||
|
||||
/**
|
||||
* Pop up to max_len bytes of UART-received data for sending back as
|
||||
* SERIAL_CONTROL reply. Thread-safe; called from Mavlink main loop.
|
||||
* Only returns data if channel matches the channel that sent the request.
|
||||
*/
|
||||
size_t popToMavlink(uint8_t *buf, size_t max_len,
|
||||
uint8_t *out_sysid, uint8_t *out_compid, uint8_t *out_device,
|
||||
uint8_t channel);
|
||||
|
||||
bool should_exit() const { return _should_exit.load(); }
|
||||
void request_stop() { _should_exit.store(true); }
|
||||
|
||||
private:
|
||||
// --- Static instance registry ---
|
||||
static SerialPassthrough *_instances[SP_MAX_INSTANCES];
|
||||
static pthread_mutex_t _instances_mutex;
|
||||
|
||||
bool register_instance(uint8_t device_id);
|
||||
void unregister_instance();
|
||||
|
||||
device::Serial _serial_port;
|
||||
char _dev_path[20] {};
|
||||
unsigned _baudrate{115200};
|
||||
bool _swap_rxtx{false};
|
||||
bool _single_wire{false};
|
||||
int _esc_channel{-1}; // if >= 0, use bitbang_uart on this motor channel instead of _serial_port
|
||||
uint8_t _registered_device_id{255};
|
||||
|
||||
px4::atomic_bool _should_exit{false};
|
||||
|
||||
// MAVLink → UART buffer (written by pushFromMavlink, drained by run())
|
||||
uint8_t _rx_buf[SP_BUF_SIZE] {};
|
||||
size_t _rx_len{0};
|
||||
pthread_mutex_t _rx_mutex;
|
||||
|
||||
// UART → MAVLink buffer (written by run(), drained by popToMavlink)
|
||||
uint8_t _tx_buf[SP_BUF_SIZE] {};
|
||||
size_t _tx_len{0};
|
||||
pthread_mutex_t _tx_mutex;
|
||||
|
||||
// Reply metadata (sysid/compid/device/channel of last received message)
|
||||
uint8_t _target_sysid{0};
|
||||
uint8_t _target_compid{0};
|
||||
uint8_t _device_id{0};
|
||||
uint8_t _tx_channel{255}; // MAVLink channel index to reply on (255 = not set)
|
||||
pthread_mutex_t _meta_mutex;
|
||||
|
||||
uint8_t _ser_read_buf[256] {};
|
||||
};
|
||||
@@ -147,6 +147,10 @@ px4_add_module(
|
||||
UNITY_BUILD
|
||||
)
|
||||
|
||||
if(CONFIG_DRIVERS_SERIALPASSTHROUGH)
|
||||
target_link_libraries(modules__mavlink PRIVATE drivers__serialpassthrough)
|
||||
endif()
|
||||
|
||||
px4_add_unit_gtest(SRC MavlinkStatustextHandlerTest.cpp
|
||||
INCLUDES
|
||||
${MAVLINK_LIBRARY_DIR}
|
||||
|
||||
@@ -61,6 +61,10 @@
|
||||
#include "mavlink_receiver.h"
|
||||
#include "mavlink_main.h"
|
||||
|
||||
#ifdef CONFIG_DRIVERS_SERIALPASSTHROUGH
|
||||
#include <drivers/serialpassthrough/serialpassthrough.hpp>
|
||||
#endif
|
||||
|
||||
#ifdef MAVLINK_UDP
|
||||
#include <sys/time.h>
|
||||
#endif
|
||||
@@ -2519,6 +2523,7 @@ Mavlink::task_main(int argc, char *argv[])
|
||||
handleCommands();
|
||||
handleAndGetCurrentCommandAck();
|
||||
handleMavlinkShellOutput();
|
||||
handleSerialPassthroughOutput();
|
||||
|
||||
check_requested_subscriptions();
|
||||
|
||||
@@ -2694,6 +2699,39 @@ void Mavlink::handleStatus()
|
||||
}
|
||||
}
|
||||
|
||||
void Mavlink::handleSerialPassthroughOutput()
|
||||
{
|
||||
#ifdef CONFIG_DRIVERS_SERIALPASSTHROUGH
|
||||
// Drain all pending UART->MAVLink data from every active instance,
|
||||
// one SERIAL_CONTROL message at a time.
|
||||
mavlink_serial_control_t msg{};
|
||||
msg.baudrate = 0;
|
||||
msg.timeout = 0;
|
||||
msg.flags = SERIAL_CONTROL_FLAG_REPLY;
|
||||
|
||||
uint8_t sysid, compid, device;
|
||||
|
||||
for (int i = 0; i < SP_MAX_INSTANCES; i++) {
|
||||
SerialPassthrough *sp = SerialPassthrough::get_instance_by_index(i);
|
||||
|
||||
if (!sp) { continue; }
|
||||
|
||||
while (get_free_tx_buf() >= MAVLINK_MSG_ID_SERIAL_CONTROL_LEN + MAVLINK_NUM_NON_PAYLOAD_BYTES) {
|
||||
size_t n = sp->popToMavlink(msg.data, sizeof(msg.data), &sysid, &compid, &device,
|
||||
(uint8_t)get_channel());
|
||||
|
||||
if (n == 0) { break; }
|
||||
|
||||
PX4_DEBUG("handleSerialPassthroughOutput: sending %zu bytes", n);
|
||||
msg.count = n;
|
||||
msg.device = device;
|
||||
mavlink_msg_serial_control_send_struct(get_channel(), &msg);
|
||||
}
|
||||
}
|
||||
|
||||
#endif
|
||||
}
|
||||
|
||||
void Mavlink::handleMavlinkShellOutput()
|
||||
{
|
||||
if (_mavlink_shell) { // First do a fast check before taking the lock
|
||||
|
||||
@@ -694,6 +694,8 @@ private:
|
||||
|
||||
void handleMavlinkShellOutput();
|
||||
|
||||
void handleSerialPassthroughOutput();
|
||||
|
||||
/**
|
||||
* Reconfigure a SiK radio if requested by MAV_SIK_RADIO_ID
|
||||
*
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
/****************************************************************************
|
||||
*
|
||||
* Copyright (c) 2012-2021 PX4 Development Team. All rights reserved.
|
||||
* Copyright (c) 2012-2026 PX4 Development Team. All rights reserved.
|
||||
*
|
||||
* Redistribution and use in source and binary forms, with or without
|
||||
* modification, are permitted provided that the following conditions
|
||||
@@ -61,6 +61,10 @@
|
||||
#include "mavlink_main.h"
|
||||
#include "mavlink_receiver.h"
|
||||
|
||||
#ifdef CONFIG_DRIVERS_SERIALPASSTHROUGH
|
||||
#include <drivers/serialpassthrough/serialpassthrough.hpp>
|
||||
#endif
|
||||
|
||||
#include <lib/drivers/device/Device.hpp> // For DeviceId union
|
||||
#include <containers/LockGuard.hpp>
|
||||
|
||||
@@ -1996,13 +2000,36 @@ MavlinkReceiver::handle_message_serial_control(mavlink_message_t *msg)
|
||||
if ((serial_control_mavlink.target_system != 0 &&
|
||||
mavlink_system.sysid != serial_control_mavlink.target_system) ||
|
||||
(serial_control_mavlink.target_component != 0 &&
|
||||
mavlink_system.compid != serial_control_mavlink.target_component)) {
|
||||
mavlink_system.compid != serial_control_mavlink.target_component) ||
|
||||
(serial_control_mavlink.flags & SERIAL_CONTROL_FLAG_REPLY)) {
|
||||
return;
|
||||
}
|
||||
|
||||
// (0=TEL1, 1=TEL2, 2=GPS1, 3=GPS2, 4=TEL3, 5=TEL4)
|
||||
// (20-27: ESC0 - ESC7)
|
||||
#ifdef CONFIG_DRIVERS_SERIALPASSTHROUGH
|
||||
|
||||
if (serial_control_mavlink.device <= 5 ||
|
||||
(serial_control_mavlink.device >= 20 && serial_control_mavlink.device <= 27)) {
|
||||
|
||||
SerialPassthrough::startForDevice(serial_control_mavlink.device, serial_control_mavlink.baudrate);
|
||||
SerialPassthrough *sp = SerialPassthrough::get_instance_for_device(serial_control_mavlink.device);
|
||||
|
||||
if (sp && serial_control_mavlink.count > 0) {
|
||||
sp->pushFromMavlink(serial_control_mavlink.data,
|
||||
serial_control_mavlink.count,
|
||||
msg->sysid, msg->compid,
|
||||
serial_control_mavlink.device,
|
||||
(uint8_t)_mavlink.get_channel());
|
||||
}
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
#endif // CONFIG_DRIVERS_SERIALPASSTHROUGH
|
||||
|
||||
// we only support shell commands
|
||||
if (serial_control_mavlink.device != SERIAL_CONTROL_DEV_SHELL
|
||||
|| (serial_control_mavlink.flags & SERIAL_CONTROL_FLAG_REPLY)) {
|
||||
if (serial_control_mavlink.device != SERIAL_CONTROL_DEV_SHELL) {
|
||||
return;
|
||||
}
|
||||
|
||||
|
||||
Reference in new issue
Block a user