tbx/include/drv/BG95_base.h

322 lines
11 KiB
C++

/*!
* \file cont/BG95_base.h
* \brief
* BG95 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 TBX_DRV_BG95_base_H_
#define TBX_DRV_BG95_base_H_
#include <core/core.h>
#include <core/crtp.h>
#include <cont/equeue.h>
#include <cont/range.h>
#include <utils/sequencer.h>
#include <cstring>
#include <cstdio>
#include <algorithm>
//#include <iostream>
#include <atomic>
namespace tbx {
/*!
* \class BG95_base
* \brief
*
* \example implementation example
* \code
* using Queue = equeue<char, 512, true>;
*
* class BG95 :
* public BG95_base<BG95, Queue, 256> {
* using base_type = BG95_base<BG95, Queue, 256>;
* using range_t = typename Queue::range_t;
* private: // data
* Queue rx_q{};
* std::atomic<size_t> lines{};
* public:
* BG95() :
* rx_q(equeue<char, 512, true>::data_match::MATCH_PUSH, base_type::delimiter, [&](){
* lines.fetch_add(1, std::memory_order_acq_rel);
* }), lines(0) {
* // init code here ...
* }
* // ISR handler
* void usart_isr_ (void) {
* rx_q << // char from ISR
* }
* // CRTP requirements
* size_t get(char* data, bool wait =false) {
* do {
* if (lines.load(std::memory_order_acquire)) {
* size_t n =0;
* do{
* *data << rx_q;
* ++n;
* } while (*data++ != base_type::delimiter);
* lines.fetch_sub(1, std::memory_order_acq_rel);
* return n;
* }
* } while (wait);
* return 0;
* }
* size_t put (const char* data, size_t n) {
* // send data to UART
* return n;
* }
* const range_t contents() const { return range_t {rx_q.begin(), rx_q.end()}; }
* clock_t clock() { } // return systems CPU time
* };
* \endcode
*
* \tparam Impl_t
* \tparam Cont_t
* \tparam N
* \tparam Delimiter
*/
template<typename Impl_t, typename Cont_t, size_t N, char Delimiter ='\n'>
class BG95_base
: public sequencer<BG95_base<Impl_t, Cont_t, N, Delimiter>, Cont_t, char, N>{
_CRTP_IMPL(Impl_t);
static_assert(
std::is_same_v<typename Cont_t::value_type, char>,
"Cont_t must be a container of type char"
);
// local type dispatch
using base_type = sequencer<BG95_base, Cont_t, char, N>;
using str_view_t = typename base_type::str_view_t;
using range_t = typename Cont_t::range_t;
using status_t = typename base_type::status_t;
//! \name Public types
//! @{
public:
using action_t = typename base_type::action_t;
using control_t = typename base_type::control_t;
using match_t = typename base_type::match_t;
using handler_t = typename base_type::handler_ft;
template<size_t Nr, size_t Nh =2>
using script_t = typename base_type::template script_t<Nr, Nh>;
//! Publish delimiter
constexpr static char delimiter = Delimiter;
//! Required typenames for async operation
//! @{
template <size_t Nm>
using async_handlers = std::array<typename base_type::handle_t, Nm>;
//! @}
//! @}
//! \name Constructor / Destructor
//!@{
protected:
//!< \brief A default constructor from derived only
BG95_base() = default;
~BG95_base () = default; //!< \brief Allow destructor from derived only
BG95_base(const BG95_base&) = delete; //!< No copies
BG95_base& operator= (const BG95_base&) = delete; //!< No copy assignments
//!@}
//! \name Sequencer interface requirements
//! Forwarded to implementer the calls and cascade the the incoming channel
//! sequencer::get --resolved--> this->receive() --calls--> impl().get()
//! @{
friend base_type;
private:
size_t get_ (char* data) {
return impl().get (data);
}
size_t get (char* data) {
return receive (data);
}
size_t put (const char* data, size_t n) {
return impl().put (data, n);
}
const range_t contents () const {
return impl().contents();
}
clock_t clock () {
return impl().clock();
}
//! @}
//! \name Private functionality
//! @{
private:
//! @}
//! \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) {
return put (data, n);
}
size_t transmit (const char* data) {
return put (data, strlen(data));
}
/*!
* \brief
* Try to receive data from modem. If there are data copy them to \c data pointer and retur
* 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;
}
/*!
* \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 async_handlers<Nm>* async_handles =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 (async_handles != nullptr) {
for (auto& h : *async_handles)
match |= base_type::check_handle (h, buffer.data());
}
// 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);
}
template <size_t Steps, size_t Nhandles>
bool configure (const script_t<Steps, Nhandles>& script) {
return base_type::run (script);
}
// // General API
// static constexpr typename base_type::handle_t error_handle_ = {
// "ERROR", match_t::CONTAINS, nullptr, action_t::EXIT_ERROR, 0
// };
template<typename T>
void parse (char* str, size_t n, char next, T value) {
auto next_ptr = std::find(str, &str[n], next);
char save = *next_ptr;
*next_ptr =0;
if constexpr (std::is_same_v<std::remove_cv<T>, int>) {
sscanf(str, "%d", &value);
} else if (std::is_same_v<std::remove_cv<T>, float>) {
sscanf(str, "%f", &value);
} else if (std::is_same_v<std::remove_cv<T>, double>) {
sscanf(str, "%lf", &value);
} else if (std::is_same_v<std::remove_cv<T>, char>) {
sscanf(str, "%c", &value);
} else if (std::is_same_v<std::remove_cv<T>, char*>) {
strcpy(value, str);
}
*next_ptr = save;
}
// cmd: "AT+CREG?"
// expected: "\r\n+CREG: 0,%\r\nOK\r\n"
template <typename T, char Marker = '%'>
bool command (const str_view_t cmd, const str_view_t expected, T& t) {
char buffer[N];
transmit(cmd);
for (size_t pos =0 ; pos < expected.size(); ) {
str_view_t ex = expected.substr(pos); // get starting point of expected
size_t sz = receive(buffer, 1); // load the answer
for (size_t i ; i<sz ; ) {
if (ex[i] == Marker)
parse(buffer[i], sz, ex[i+1], t); // parse and convert
else if (ex[i] == buffer[i])
++i; // consume current character
else
return false; // Fail to parse
}
}
return true;
}
//! @}
private:
equeue<char, N> rx_q{};
std::atomic<size_t> streams_{};
};
} // namespace tbx;
#endif /* TBX_DRV_BG95_base_H_ */