|
- /*!
- * \file drv/ATmodem.h
- * \brief
- * ATmodem 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_ATmodem_H_
- #define TBX_DRV_ATmodem_H_
-
- #define __cplusplus 201703L
-
- #include <core/core.h>
- #include <core/crtp.h>
- #include <cont/equeue.h>
- #include <cont/range.h>
- #include <com/sequencer.h>
-
- #include <cstring>
- #include <cstdlib>
- #include <algorithm>
-
- #include <utility>
- #include <atomic>
-
- namespace tbx {
-
- /*!
- * \class BG95_base
- * \brief
- *
- * \example implementation example
- * \code
-
- * \endcode
- *
- * \tparam Impl_t
- * \tparam Cont_t
- * \tparam N
- * \tparam Delimiter
- */
- template<typename Impl_t, size_t N, char Delimiter ='\n'>
- class ATmodem
- : public sequencer<ATmodem<Impl_t, N, Delimiter>, char, N>{
- _CRTP_IMPL(Impl_t);
-
- // local type dispatch
- using base_type = sequencer<ATmodem, 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;
-
- //! Required types for inetd async handler operation
- //! @{
- struct inetd_handler_t {
- string_view token;
- match_ft match;
- handler_ft handler;
- };
- template <size_t Nm>
- using inetd_handlers = std::array<inetd_handler_t, Nm>;
- //! @}
- //! @}
-
- //! \name Constructor / Destructor
- //!@{
- protected:
- //!< \brief A default constructor from derived only
- ATmodem() noexcept = default;
- ~ATmodem () = default; //!< \brief Allow destructor from derived only
- ATmodem(const ATmodem&) = delete; //!< No copies
- ATmodem& operator= (const ATmodem&) = 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);
- }
- size_t contents (char* data) {
- return impl().contents(data);
- }
- clock_t clock () {
- return impl().clock();
- }
- //! @}
-
- //! \name Private functionality
- //! @{
- private:
-
- template <typename... Ts>
- struct typelist {
- using type = typelist; //!< act as identity
- };
-
- template <typename L>
- struct front_impl {
- using type = void;
- };
-
- template <typename Head, typename... Tail>
- struct front_impl<typelist<Head, Tail...>> {
- using type = Head;
- };
-
- //! Return the first element in \c meta::typelist \c List.
- //!
- //! Complexity \f$ O(1) \f$.
- template <typename List>
- using front = typename front_impl<List>::type;
-
- 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);
- }
- }
- void extract (const char* str, void* value) {
- (void)*str; (void)value;
- }
-
- 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 to token the next part of buffer, from begin up to expected[1] where
- // the expected[1] character is and return the size of that part.
- auto next = std::find(buffer.begin(), buffer.end(), expected[1]);
- if (next == buffer.end())
- break;
- 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);
- }
-
- //! @}
-
- //! \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
- * Send a command to modem and check if the response matches to
- * \c expected. If so read any token inside response marked with
- * \c Marker, convert the value into type \c T and write it to \c t
- *
- * \param cmd The comand to send (null terminated)
- * \param expected The expected response
- * \param t The value to return
- * \param timeout The timeout in CPU time (leave it for 0 - no timeout)
- *
- * \tparam T The type of the value to read from response marked with \c Marker
- * \tparam Marker The marker character
- * \return True on success
- *
- * example
- * \code
- * BG95<256> modem;
- * std::thread th1 ([&](){
- * modem.inetd(false);
- * });
- * int status;
- * bool done = modem.command("AT+CREG?\r\n", "\r\n+CREG: 0,%\r\n\r\nOK\r\n", status);
- * if (done && status == 1)
- * std::cout << "Connected to home network\n"
- * \endcode
- * element_type (&arr)[N]
- */
- template<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);
- front<typelist<Ts...>>* vargs[Nr] = {values...};
-
- if constexpr (Nr == 0) { (void)vargs; }
-
- char buffer[N], token[N];
- size_t v =0;
-
- transmit(cmd.data()); // send command
-
- for (auto ex = expected.begin() ; ex != expected.end() ; ) {
- clock_t mark = clock(); // load the answer with timeout
- size_t sz =0;
- bool redo = false; do {
- do {
- sz = receive(buffer);
- if ((timeout != 0 )&& ((clock() - mark) >= timeout))
- return false;
- } while (!sz);
-
- redo = false; // have faith to parse successfully
- for (size_t i=0 ; i<sz ; ) { // parse buffer based on expected
- auto [step, marker] = parse<Marker> (ex++, {&buffer[i], sz-i}, token);
- if (!step) {
- redo = true; // fail to parse, reload and retry
- break;
- }
- if constexpr (Nr > 0) {
- if (marker && v< Nr)
- extract(token, vargs[v++]);
- }
- i += step;
- }
- } while (redo);
- }
- return true;
- }
-
- /*!
- * \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 tbx;
-
- #endif /* #ifndef TBX_DRV_ATmodem_H_ */
|