A C++ toolbox repo until the pair uTL/dTL arives
Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.
 
 
 

369 строки
13 KiB

  1. /*!
  2. * \file drv/ATmodem.h
  3. * \brief
  4. * ATmodem driver functionality as CRTP base class
  5. *
  6. * \copyright Copyright (C) 2021 Christos Choutouridis <christos@choutouridis.net>
  7. *
  8. * <dl class=\"section copyright\"><dt>License</dt><dd>
  9. * The MIT License (MIT)
  10. *
  11. * Permission is hereby granted, free of charge, to any person obtaining a copy
  12. * of this software and associated documentation files (the "Software"), to deal
  13. * in the Software without restriction, including without limitation the rights
  14. * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  15. * copies of the Software, and to permit persons to whom the Software is
  16. * furnished to do so, subject to the following conditions:
  17. *
  18. * The above copyright notice and this permission notice shall be included in all
  19. * copies or substantial portions of the Software.
  20. *
  21. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  22. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  23. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  24. * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  25. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  26. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  27. * SOFTWARE.
  28. * </dd></dl>
  29. */
  30. #ifndef TBX_DRV_ATmodem_H_
  31. #define TBX_DRV_ATmodem_H_
  32. #define __cplusplus 201703L
  33. #include <core/core.h>
  34. #include <core/crtp.h>
  35. #include <cont/equeue.h>
  36. #include <cont/range.h>
  37. #include <com/sequencer.h>
  38. #include <cstring>
  39. #include <cstdlib>
  40. #include <algorithm>
  41. #include <utility>
  42. #include <atomic>
  43. namespace tbx {
  44. /*!
  45. * \class BG95_base
  46. * \brief
  47. *
  48. * \example implementation example
  49. * \code
  50. * \endcode
  51. *
  52. * \tparam Impl_t
  53. * \tparam Cont_t
  54. * \tparam N
  55. * \tparam Delimiter
  56. */
  57. template<typename Impl_t, size_t N, char Delimiter ='\n'>
  58. class ATmodem
  59. : public sequencer<ATmodem<Impl_t, N, Delimiter>, char, N>{
  60. _CRTP_IMPL(Impl_t);
  61. // local type dispatch
  62. using base_type = sequencer<ATmodem, char, N>;
  63. //! \name Public types
  64. //! @{
  65. public:
  66. using value_type = char;
  67. using pointer_type = char*;
  68. using size_type = size_t;
  69. using string_view = typename base_type::string_view;
  70. using action_t = typename base_type::action_t;
  71. using control_t = typename base_type::control_t;
  72. using match_ft = typename base_type::match_ft;
  73. using handler_ft = typename base_type::handler_ft;
  74. template<size_t Nm>
  75. using script_t = typename base_type::template script_t<Nm>;
  76. //! Publish delimiter
  77. constexpr static char delimiter = Delimiter;
  78. //! Required types for inetd async handler operation
  79. //! @{
  80. struct inetd_handler_t {
  81. string_view token;
  82. match_ft match;
  83. handler_ft handler;
  84. };
  85. template <size_t Nm>
  86. using inetd_handlers = std::array<inetd_handler_t, Nm>;
  87. //! @}
  88. //! @}
  89. //! \name Constructor / Destructor
  90. //!@{
  91. protected:
  92. //!< \brief A default constructor from derived only
  93. ATmodem() noexcept = default;
  94. ~ATmodem () = default; //!< \brief Allow destructor from derived only
  95. ATmodem(const ATmodem&) = delete; //!< No copies
  96. ATmodem& operator= (const ATmodem&) = delete; //!< No copy assignments
  97. //!@}
  98. //! \name Sequencer interface requirements
  99. //! Forwarded to implementer the calls and cascade the the incoming channel
  100. //! sequencer::get --resolved--> this->receive() --calls--> impl().get()
  101. //! @{
  102. friend base_type;
  103. private:
  104. size_t get_ (char* data) {
  105. return impl().get (data);
  106. }
  107. size_t get (char* data) {
  108. return receive (data);
  109. }
  110. size_t put (const char* data, size_t n) {
  111. return impl().put (data, n);
  112. }
  113. size_t contents (char* data) {
  114. return impl().contents(data);
  115. }
  116. clock_t clock () {
  117. return impl().clock();
  118. }
  119. //! @}
  120. //! \name Private functionality
  121. //! @{
  122. private:
  123. template <typename... Ts>
  124. struct typelist {
  125. using type = typelist; //!< act as identity
  126. };
  127. template <typename L>
  128. struct front_impl {
  129. using type = void;
  130. };
  131. template <typename Head, typename... Tail>
  132. struct front_impl<typelist<Head, Tail...>> {
  133. using type = Head;
  134. };
  135. //! Return the first element in \c meta::typelist \c List.
  136. //!
  137. //! Complexity \f$ O(1) \f$.
  138. template <typename List>
  139. using front = typename front_impl<List>::type;
  140. template<typename T>
  141. void extract (const char* str, T* value) {
  142. static_assert (
  143. std::is_same_v<std::remove_cv_t<T>, int>
  144. || std::is_same_v<std::remove_cv_t<T>, double>
  145. || std::is_same_v<std::remove_cv_t<T>, char>,
  146. "Not supported conversion type.");
  147. if constexpr (std::is_same_v<std::remove_cv_t<T>, int>) {
  148. *value = std::atoi(str);
  149. } else if (std::is_same_v<std::remove_cv_t<T>, double>) {
  150. *value = std::atof(str);
  151. } else if (std::is_same_v<std::remove_cv_t<T>, char>) {
  152. std::strcpy(value, str);
  153. }
  154. }
  155. void extract (const char* str, void* value) {
  156. (void)*str; (void)value;
  157. }
  158. template <char Marker = '%'>
  159. std::pair<size_t, bool> parse (const char* expected, const string_view buffer, char* token) {
  160. do {
  161. if (*expected == Marker) {
  162. // We have Marker. Copy to token the next part of buffer, from begin up to expected[1] where
  163. // the expected[1] character is and return the size of that part.
  164. auto next = std::find(buffer.begin(), buffer.end(), expected[1]);
  165. if (next == buffer.end())
  166. break;
  167. char* nullpos = std::copy(buffer.begin(), next, token);
  168. *nullpos =0;
  169. return std::make_pair(next - buffer.begin(), true);
  170. }
  171. else if (*expected == buffer.front()) {
  172. // We have character match, copy the character to token and return 1 (the char size)
  173. *token++ = buffer.front();
  174. *token =0;
  175. return std::make_pair(1, false);
  176. }
  177. } while (0);
  178. // Fail to parse
  179. *token =0;
  180. return std::make_pair(0, false);
  181. }
  182. //! @}
  183. //! \name public functionality
  184. //! @{
  185. public:
  186. /*!
  187. * \brief
  188. * Transmit data to modem
  189. * \param data Pointer to data to send
  190. * \param n The size of data buffer
  191. * \return The number of transmitted chars
  192. */
  193. size_t transmit (const char* data, size_t n) {
  194. return put (data, n);
  195. }
  196. size_t transmit (const char* data) {
  197. return put (data, strlen(data));
  198. }
  199. /*!
  200. * \brief
  201. * Try to receive data from modem. If there are data copy them to \c data pointer and retur
  202. * the size. Otherwise return zero. In the case \c wait is true block until there are data to get.
  203. *
  204. * \param data Pointer to data buffer to write
  205. * \param wait Flag to select blocking / non-blocking functionality
  206. * \return The number of copied data.
  207. */
  208. size_t receive (char* data, bool wait =false) {
  209. do {
  210. if (streams_.load(std::memory_order_acquire)) {
  211. size_t n =0;
  212. do {
  213. *data << rx_q;
  214. ++n;
  215. } while (*data++ != delimiter);
  216. *data =0;
  217. streams_.fetch_sub(1, std::memory_order_acq_rel);
  218. return n;
  219. }
  220. } while (wait); // on wait flag we block until available stream
  221. return 0;
  222. }
  223. /*!
  224. * \brief
  225. * Send a command to modem and check if the response matches to
  226. * \c expected. If so read any token inside response marked with
  227. * \c Marker, convert the value into type \c T and write it to \c t
  228. *
  229. * \param cmd The comand to send (null terminated)
  230. * \param expected The expected response
  231. * \param t The value to return
  232. * \param timeout The timeout in CPU time (leave it for 0 - no timeout)
  233. *
  234. * \tparam T The type of the value to read from response marked with \c Marker
  235. * \tparam Marker The marker character
  236. * \return True on success
  237. *
  238. * example
  239. * \code
  240. * BG95<256> modem;
  241. * std::thread th1 ([&](){
  242. * modem.inetd(false);
  243. * });
  244. * int status;
  245. * bool done = modem.command("AT+CREG?\r\n", "\r\n+CREG: 0,%\r\n\r\nOK\r\n", status);
  246. * if (done && status == 1)
  247. * std::cout << "Connected to home network\n"
  248. * \endcode
  249. * element_type (&arr)[N]
  250. */
  251. template<char Marker = '%', typename ...Ts>
  252. bool command (const string_view cmd, const string_view expected, clock_t timeout, Ts* ...values) {
  253. constexpr size_t Nr = sizeof...(Ts);
  254. front<typelist<Ts...>>* vargs[Nr] = {values...};
  255. if constexpr (Nr == 0) { (void)vargs; }
  256. char buffer[N], token[N];
  257. size_t v =0;
  258. transmit(cmd.data()); // send command
  259. for (auto ex = expected.begin() ; ex != expected.end() ; ) {
  260. clock_t mark = clock(); // load the answer with timeout
  261. size_t sz =0;
  262. bool redo = false; do {
  263. do {
  264. sz = receive(buffer);
  265. if ((timeout != 0 )&& ((clock() - mark) >= timeout))
  266. return false;
  267. } while (!sz);
  268. redo = false; // have faith to parse successfully
  269. for (size_t i=0 ; i<sz ; ) { // parse buffer based on expected
  270. auto [step, marker] = parse<Marker> (ex++, {&buffer[i], sz-i}, token);
  271. if (!step) {
  272. redo = true; // fail to parse, reload and retry
  273. break;
  274. }
  275. if constexpr (Nr > 0) {
  276. if (marker && v< Nr)
  277. extract(token, vargs[v++]);
  278. }
  279. i += step;
  280. }
  281. } while (redo);
  282. }
  283. return true;
  284. }
  285. /*!
  286. * \brief
  287. * inetd daemon functionality provided as member function of the driver. This should be running
  288. * in the background either as consecutive calls from an periodic ISR with \c loop = false, or
  289. * as a thread in an RTOS environment with \c loop = true.
  290. *
  291. * \tparam Nm The number of handler array entries
  292. *
  293. * \param async_handles Reference to asynchronous handler array
  294. * \param loop Flag to indicate blocking mode. If true blocking.
  295. */
  296. template <size_t Nm =0>
  297. void inetd (bool loop =true, const inetd_handlers<Nm>* inetd_handlers =nullptr) {
  298. std::array<char, N> buffer;
  299. size_t resp_size;
  300. do {
  301. if ((resp_size = get_(buffer.data())) != 0) {
  302. // on data check for async handlers
  303. bool match = false;
  304. if (inetd_handlers != nullptr) {
  305. for (auto& h : *inetd_handlers)
  306. match |= base_type::check_handle({buffer.data(), resp_size}, h.token, h.match, h.handler);
  307. }
  308. // if no match forward data to receive channel.
  309. if (!match) {
  310. char* it = buffer.data();
  311. do {
  312. rx_q << *it;
  313. } while (*it++ != delimiter);
  314. streams_.fetch_add(1, std::memory_order_acq_rel);
  315. }
  316. }
  317. } while (loop);
  318. }
  319. //! @}
  320. private:
  321. equeue<char, N, true> rx_q{};
  322. std::atomic<size_t> streams_{};
  323. };
  324. } // namespace tbx;
  325. #endif /* #ifndef TBX_DRV_ATmodem_H_ */