From 46e204dd6ce7d839f05e0ae974183ac90465925b Mon Sep 17 00:00:00 2001 From: Thomas Watson Date: Sat, 1 Jun 2024 23:23:25 -0500 Subject: [PATCH] AP_Scripting: clear serial device sim buffers appropriately Ensures the script won't process data created before it started, and that the protocol won't process data created after the script stopped. --- libraries/AP_Scripting/AP_Scripting.cpp | 10 ++++++++++ .../AP_Scripting/AP_Scripting_SerialDevice.cpp | 18 ++++++++++++++++++ .../AP_Scripting/AP_Scripting_SerialDevice.h | 2 ++ 3 files changed, 30 insertions(+) diff --git a/libraries/AP_Scripting/AP_Scripting.cpp b/libraries/AP_Scripting/AP_Scripting.cpp index f1cf7b5b48..b4056d7139 100644 --- a/libraries/AP_Scripting/AP_Scripting.cpp +++ b/libraries/AP_Scripting/AP_Scripting.cpp @@ -311,6 +311,11 @@ void AP_Scripting::thread(void) { GCS_SEND_TEXT(MAV_SEVERITY_CRITICAL, "Scripting: %s", "Unable to allocate memory"); _init_failed = true; } else { +#if AP_SCRIPTING_SERIALDEVICE_ENABLED + // clear data in serial buffers that the script wasn't ready to + // receive + _serialdevice.clear(); +#endif // run won't return while scripting is still active lua->run(); @@ -345,6 +350,11 @@ void AP_Scripting::thread(void) { } } #endif // AP_NETWORKING_ENABLED + +#if AP_SCRIPTING_SERIALDEVICE_ENABLED + // clear data in serial buffers that hasn't been transmitted + _serialdevice.clear(); +#endif // Clear blocked commands { diff --git a/libraries/AP_Scripting/AP_Scripting_SerialDevice.cpp b/libraries/AP_Scripting/AP_Scripting_SerialDevice.cpp index ba09c9c0a0..39412246d5 100644 --- a/libraries/AP_Scripting/AP_Scripting_SerialDevice.cpp +++ b/libraries/AP_Scripting/AP_Scripting_SerialDevice.cpp @@ -35,6 +35,13 @@ void AP_Scripting_SerialDevice::init(void) } } +void AP_Scripting_SerialDevice::clear(void) +{ + for (auto &p : ports) { + p.clear(); + } +} + /* initialise port */ @@ -43,6 +50,17 @@ void AP_Scripting_SerialDevice::Port::init(void) begin(1000000, 0, 0); // assume 1MBaud rate even though it's a bit meaningless } +void AP_Scripting_SerialDevice::Port::clear(void) +{ + WITH_SEMAPHORE(sem); + if (readbuffer) { + readbuffer->clear(); + } + if (writebuffer) { + writebuffer->clear(); + } +} + size_t AP_Scripting_SerialDevice::Port::device_write(const uint8_t *buffer, size_t size) { WITH_SEMAPHORE(sem); diff --git a/libraries/AP_Scripting/AP_Scripting_SerialDevice.h b/libraries/AP_Scripting/AP_Scripting_SerialDevice.h index d69b2e45b0..979405a8b3 100644 --- a/libraries/AP_Scripting/AP_Scripting_SerialDevice.h +++ b/libraries/AP_Scripting/AP_Scripting_SerialDevice.h @@ -19,12 +19,14 @@ public: AP_Int8 enable; void init(void); + void clear(void); public: class Port : public AP_SerialManager::RegisteredPort { public: friend class AP_Scripting_SerialDevice; void init(void); + void clear(void); size_t device_write(const uint8_t *buffer, size_t size); ssize_t device_read(uint8_t *buffer, uint16_t count);