utl/include/utl/dev/cli_device.h

474 lines
19 KiB
C++

/*!
* \file dev/cli_device.h
* \brief
* command line device driver functionality as CRTP base class
*
* \copyright Copyright (C) 2021 Christos Choutouridis <christos@choutouridis.net>
*
* <dl class=\"section copyright\"><dt>License</dt><dd>
* The MIT License (MIT)
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
* </dd></dl>
*/
#ifndef utl_dev_cli_device_h__
#define utl_dev_cli_device_h__
#include <utl/core/impl.h>
#include <utl/core/crtp.h>
#include <utl/container/equeue.h>
#include <utl/dev/sequencer.h>
#include <utl/meta/meta.h>
#include <cstring>
#include <cstdlib>
#include <algorithm>
#include <utility>
#include <atomic>
namespace utl {
/*!
* \class cli_device
* \brief
* Its a base class for command-line based devices
*
* Inherits the sequencer functionality and provides a command interface for sending
* commands and parse the response.
*
* \example implementation example
* \code
* class BG95 : public cli_device<BG95, 256> {
* using base_type = cli_device<BG95, 256>;
* using Queue = equeue<typename base_type::value_type, 256, true>;
* Queue RxQ{};
* std::atomic<size_t> lines{};
* public:
* // cli_device driver requirements
* BG95() noexcept :
* RxQ(Queue::data_match::MATCH_PUSH, base_type::delimiter, [&](){
* lines.fetch_add(1, std::memory_order_acq_rel);
* }), lines(0) { }
* void feed(char x) { RxQ << x; } // To be used inside ISR
* size_t get(char* data, bool wait =false) {
* do {
* if (lines.load(std::memory_order_acquire)) {
* size_t n =0;
* do{
* *data << RxQ;
* ++n;
* } while (*data++ != base_type::delimiter);
* lines.fetch_sub(1, std::memory_order_acq_rel);
* return n;
* }
* } while (wait);
* return 0;
* }
* size_t contents(char* data) {
* char* nullpos = std::copy(RxQ.begin(), RxQ.end(), data);
* *nullpos =0;
* return nullpos - data;
* }
* size_t put (const char* data, size_t n) {
* // send data to BG95
* return n;
* }
* clock_t clock() noexcept { //return CPU time }
* };
* \endcode
*
* \tparam Impl_t The type of derived class
* \tparam N The size of the queue buffer for the receive/command interface
* \tparam Delimiter The incoming data delimiter [default line buffered -- Delimiter = '\n']
*/
template<typename Impl_t, size_t N, char Delimiter ='\n'>
class cli_device
: public sequencer<cli_device<Impl_t, N, Delimiter>, char, N>{
_CRTP_IMPL(Impl_t);
// local type dispatch
using base_type = sequencer<cli_device, char, N>;
//! \name Public types
//! @{
public:
using value_type = char;
using pointer_type = char*;
using size_type = size_t;
using string_view = typename base_type::string_view;
using action_t = typename base_type::action_t;
using control_t = typename base_type::control_t;
using match_ft = typename base_type::match_ft;
using handler_ft = typename base_type::handler_ft;
template<size_t Nm>
using script_t = typename base_type::template script_t<Nm>;
//! Publish delimiter
constexpr static char delimiter = Delimiter;
enum flush_type { keep =0, flush };
//! Required types for inetd async handler operation
//! @{
/*!
* inetd handler structure for asynchronous incoming data dispatching
*/
struct inetd_handler_t {
string_view token; //!< The token we match against
match_ft match; //!< The predicate we use to match
handler_ft handler; //!< The handler to call on match
};
//! Alias template for the async handler array
template <size_t Nm>
using inetd_handlers = std::array<inetd_handler_t, Nm>;
//! @}
//! @}
//! \name object lifetime
//!@{
protected:
//!< \brief A default constructor from derived only
cli_device() noexcept = default;
~cli_device () = default; //!< \brief Allow destructor from derived only
cli_device(const cli_device&) = delete; //!< No copies
cli_device& operator= (const cli_device&) = delete; //!< No copy assignments
//!@}
//! \name Sequencer interface requirements
//! Forwarded to implementer the calls and cascade the the incoming channel
//! @{
friend base_type;
private:
size_t get_ (char* data) {
return impl().get (data);
}
size_t get (char* data) {
return receive (data);
}
size_t contents (char* data) {
return impl().contents(data);
}
size_t put (const char* data, size_t n) {
return impl().put (data, n);
}
clock_t clock () noexcept {
return impl().clock();
}
//! @}
//! \name Private functionality
//! @{
private:
/*!
* Convert the text pointed by \c str to a value and store it to
* \c value. The type of conversion is deduced by the compiler
* \tparam T The type of the value
* \param str pointer to string with the value
* \param value pointer to converted value
*/
template<typename T>
void extract_ (const char* str, T* value) {
static_assert (
std::is_same_v<std::remove_cv_t<T>, int>
|| std::is_same_v<std::remove_cv_t<T>, double>
|| std::is_same_v<std::remove_cv_t<T>, char>,
"Not supported conversion type.");
if constexpr (std::is_same_v<std::remove_cv_t<T>, int>) {
*value = std::atoi(str);
} else if (std::is_same_v<std::remove_cv_t<T>, double>) {
*value = std::atof(str);
} else if (std::is_same_v<std::remove_cv_t<T>, char>) {
std::strcpy(value, str);
}
}
//! Specialization (as overload function) to handle void* types
void extract_ (const char* str, void* value) noexcept {
(void)*str; (void)value;
}
/*!
* Parse a chunk of the buffer based on \c expected character
*
* Tries to match the \c *expected character in buffer and if so it copies the
* character to token.
* If the \c *expected is the \c Marker character, copy the entire chunk of the buffer
* up to the character that matches the next expected character (expected[1]).
* If there is no next expected character or if its not found in the buffer,
* copy the entire buffer.
*
* \tparam Marker The special character to indicate chunk extraction
*
* \param expected The character to parse/remove from the buffer
* \param buffer The buffer we parse
* \param token Pointer to store the parsed tokens
* \return A (number of characters parsed, marker found) pair
*/
template <char Marker = '%'>
std::pair<size_t, bool> parse_ (const char* expected, const string_view buffer, char* token) {
do {
if (*expected == Marker) {
// We have Marker. Copy the entire chunk of the buffer
// up to the character that matches the next expected character (expected[1]).
// If there is none next expected character or if its not found in the buffer,
// copy the entire buffer.
auto next = std::find(buffer.begin(), buffer.end(), expected[1]);
char* nullpos = std::copy(buffer.begin(), next, token);
*nullpos =0;
return std::make_pair(next - buffer.begin(), true);
}
else if (*expected == buffer.front()) {
// We have character match, copy the character to token and return 1 (the char size)
*token++ = buffer.front();
*token =0;
return std::make_pair(1, false);
}
} while (0);
// Fail to parse
*token =0;
return std::make_pair(0, false);
}
/*!
* Analyze the response of a command based on \c expected.
*
* Tries to receive data with timeout and match them against expected string_view.
* For each Marker inside the expected string the value gets extracted, converted and
* copied to \c vargs pointer array.
*
* \param expected The expected string view
* \param timeout the timeout in CPU time
* \param vargs Pointer to variable arguments array
* \param nargs Size of variable arguments array
* \return
*/
template<char Marker = '%', typename T>
bool response_ (const string_view expected, clock_t timeout, T* vargs, size_t nargs) {
char buffer[N], token[N], *pbuffer = buffer;
size_t v =0, sz =0;
for (auto ex = expected.begin() ; ex != expected.end() ; ) {
clock_t mark = clock(); // mark the time
while (sz <= 0) { // if buffer is empty get buffer with timeout
sz = receive(buffer);
pbuffer = buffer;
if ((timeout != 0 )&& ((clock() - mark) >= timeout))
return false;
}
// try to parse
auto [step, marker] = parse_<Marker> (ex, {pbuffer, sz}, token);
if (!step)
return false; // discard buffer and fail
if (marker && v < nargs)
extract_(token, vargs[v++]);
pbuffer += step;
sz -= (step <= sz) ? step: sz;
++ex;
}
return true;
}
//! @}
//! \name public functionality
//! @{
public:
/*!
* \brief
* Transmit data to modem
* \param data Pointer to data to send
* \param n The size of data buffer
* \return The number of transmitted chars
*/
size_t transmit (const char* data, size_t n) {
if (data == nullptr)
return 0;
return put (data, n);
}
/*!
* \brief
* Transmit data to modem
* \param data Pointer to data to send
* \return The number of transmitted chars
*/
size_t transmit (const char* data) {
if (data == nullptr)
return 0;
return put (data, std::strlen(data));
}
/*!
* \brief
* Try to receive data from modem. If there are data copy them to \c data pointer and return
* the size. Otherwise return zero. In the case \c wait is true block until there are data to get.
*
* \param data Pointer to data buffer to write
* \param wait Flag to select blocking / non-blocking functionality
* \return The number of copied data.
*/
size_t receive (char* data, bool wait =false) {
do {
if (streams_.load(std::memory_order_acquire)) {
size_t n =0;
do {
*data << rx_q;
++n;
} while (*data++ != delimiter);
*data =0;
streams_.fetch_sub(1, std::memory_order_acq_rel);
return n;
}
} while (wait); // on wait flag we block until available stream
return 0;
}
//! Clears the incoming data buffer
void clear () noexcept {
rx_q.clear();
}
//! \return Returns the size of the incoming data buffer
size_t size() noexcept {
return rx_q.size();
}
/*!
* \brief
* Send a command to modem and check if the response matches to \c expected.
*
* This function executes 3 steps.
* - Clears the incoming buffer if requested by template parameter
* - Sends the command to device
* - Waits to get the response and parse it accordingly to \c expected \see response_()
*
* The user can mark spots inside the expected string using the \c Marker ['%'] character.
* These spots will be extracted to tokens upon parsing. If the user passes \c values parameters,
* then the extracted tokens will be converted to the type of the \c values (\c Ts) and copied to them
* one by one. If the values are less than spots, the rest of the tokens get discarded.
*
* \param cmd The command to send (null terminated)
* \param expected The expected response
* \param timeout The timeout in CPU time (leave it for 0 - no timeout)
* \param values The value pointer arguments to get the converted tokens
*
* \tparam Flush Flag to indicate if we flush the buffer before command or not
* \tparam Marker The marker character
* \tparam Ts The type of the values to read from response marked with \c Marker
* \warning The types MUST be the same
*
* \return True on success
*
* \example examples
* \code
* Derived cli;
* int status;
* char str[32];
*
* // discard 3 lines and expect OK\r\n at the end with 1000[CPU time] timeout
* cli.command("AT+CREG?\r\n", "%%%OK\r\n", 1000);
*
* // extract a number from response without timeout (blocking)
* cli.command<flush>("AT+CREG?\r\n", "\r\n+CREG: 0,%\r\n\r\nOK\r\n", 0, &status);
*
* // extract a number and discard the last 2 lines
* cli.command<flush>("AT+CREG?\r\n", "\r\n+CREG: 0,%\r\n%%", 1000, &status);
*
* // discard first line, read the 2nd to str, discard the 3rd line.
* // expect the last to be "OK\r\n"
* cli.command<flush>("AT+CREG?\r\n", "", 100000);
* cli.command<keep>("", "%", 1000);
* cli.command<keep>("", "%%", 1000, str);
* cli.command<keep>("", "OK\r\n", 1000);
* \endcode
*/
template<flush_type Flush =flush, char Marker = '%', typename ...Ts>
bool command (const string_view cmd, const string_view expected, clock_t timeout, Ts* ...values) {
constexpr size_t Nr = sizeof...(Ts);
meta::if_c<
(sizeof...(Ts) != 0),
meta::front<meta::typelist<Ts...>>*,
void*
> vargs[Nr] = {values...}; // read all args to local buffer
if constexpr (Flush == flush) {
clear ();
}
if (transmit(cmd.data(), cmd.size()) != cmd.size()) // send command
return false;
// parse the response and return the status
return response_<Marker>(expected, timeout, vargs, Nr);
}
/*!
* \brief
* inetd daemon functionality provided as member function of the driver. This should be running
* in the background either as consecutive calls from an periodic ISR with \c loop = false, or
* as a thread in an RTOS environment with \c loop = true.
*
* \tparam Nm The number of handler array entries
*
* \param async_handles Reference to asynchronous handler array
* \param loop Flag to indicate blocking mode. If true blocking.
*/
template <size_t Nm =0>
void inetd (bool loop =true, const inetd_handlers<Nm>* inetd_handlers =nullptr) {
std::array<char, N> buffer;
size_t resp_size;
do {
if ((resp_size = get_(buffer.data())) != 0) {
// on data check for async handlers
bool match = false;
if (inetd_handlers != nullptr) {
for (auto& h : *inetd_handlers)
match |= base_type::check_handle({buffer.data(), resp_size}, h.token, h.match, h.handler);
}
// if no match forward data to receive channel.
if (!match) {
char* it = buffer.data();
do {
rx_q << *it;
} while (*it++ != delimiter);
streams_.fetch_add(1, std::memory_order_acq_rel);
}
}
} while (loop);
}
//! @}
private:
equeue<char, N, true> rx_q{};
std::atomic<size_t> streams_{};
};
} // namespace utl;
#endif /* #ifndef utl_dev_cli_device_h__ */