From 394d70abe078ca8440e4c7eddab4d168e6bd25d4 Mon Sep 17 00:00:00 2001 From: Peter Barker Date: Tue, 21 Feb 2023 20:35:57 +1100 Subject: [PATCH] AP_HAL: add and use a "bool read(c)" method to AP_HAL this is much less likely to not work vs the int16_t equivalent --- libraries/AP_HAL/UARTDriver.h | 2 +- libraries/AP_HAL/Util.cpp | 2 +- libraries/AP_HAL/utility/BetterStream.cpp | 9 +++++++++ libraries/AP_HAL/utility/BetterStream.h | 5 ++--- 4 files changed, 13 insertions(+), 5 deletions(-) diff --git a/libraries/AP_HAL/UARTDriver.h b/libraries/AP_HAL/UARTDriver.h index b69169971d..48d789daee 100644 --- a/libraries/AP_HAL/UARTDriver.h +++ b/libraries/AP_HAL/UARTDriver.h @@ -66,7 +66,7 @@ public: virtual size_t write_locked(const uint8_t *buffer, size_t size, uint32_t key) { return 0; } // read from a locked port. If port is locked and key is not correct then 0 is returned - virtual int16_t read_locked(uint32_t key) { return -1; } + virtual bool read_locked(uint32_t key, uint8_t &b) WARN_IF_UNUSED { return -1; } // control optional features virtual bool set_options(uint16_t options) { _last_options = options; return options==0; } diff --git a/libraries/AP_HAL/Util.cpp b/libraries/AP_HAL/Util.cpp index 3afa823be4..374fc77c48 100644 --- a/libraries/AP_HAL/Util.cpp +++ b/libraries/AP_HAL/Util.cpp @@ -36,7 +36,7 @@ public: const size_t _size; uint32_t available() override { return 0; } - int16_t read() override { return -1; } + bool read(uint8_t &b) override { return false; } uint32_t txspace() override { return 0; } bool discard_input() override { return false; } }; diff --git a/libraries/AP_HAL/utility/BetterStream.cpp b/libraries/AP_HAL/utility/BetterStream.cpp index de9387eb5c..a16062fc47 100644 --- a/libraries/AP_HAL/utility/BetterStream.cpp +++ b/libraries/AP_HAL/utility/BetterStream.cpp @@ -20,6 +20,15 @@ size_t AP_HAL::BetterStream::write(const char *str) return write((const uint8_t *)str, strlen(str)); } +int16_t AP_HAL::BetterStream::read() +{ + uint8_t b; + if (!read(b)) { + return -1; + } + return b; +} + ssize_t AP_HAL::BetterStream::read(uint8_t *buffer, uint16_t count) { uint16_t offset = 0; while (count--) { diff --git a/libraries/AP_HAL/utility/BetterStream.h b/libraries/AP_HAL/utility/BetterStream.h index 0881fdefaa..433869eea4 100644 --- a/libraries/AP_HAL/utility/BetterStream.h +++ b/libraries/AP_HAL/utility/BetterStream.h @@ -40,9 +40,8 @@ public: virtual uint32_t available() = 0; - /* return value for read(): - * -1 if nothing available, uint8_t value otherwise. */ - virtual int16_t read() = 0; + int16_t read(); // old function; prefer calling the boolean method + virtual bool read(uint8_t &b) WARN_IF_UNUSED = 0; // no base-class implementation to force descendants to // do things efficiently. Looping over 2^32-1 bytes would be bad.