A C++ toolbox repo until the pair uTL/dTL arives
您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符
 
 
 

370 行
14 KiB

  1. /*!
  2. * \file cont/BG95_base.h
  3. * \brief
  4. * BG95 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_BG95_base_H_
  31. #define TBX_DRV_BG95_base_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 <utils/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. * using Queue = equeue<char, 512, true>;
  51. *
  52. * class BG95 :
  53. * public BG95_base<BG95, Queue, 256> {
  54. * using base_type = BG95_base<BG95, Queue, 256>;
  55. * using range_t = typename Queue::range_t;
  56. * private: // data
  57. * Queue rx_q{};
  58. * std::atomic<size_t> lines{};
  59. * public:
  60. * BG95() :
  61. * rx_q(equeue<char, 512, true>::data_match::MATCH_PUSH, base_type::delimiter, [&](){
  62. * lines.fetch_add(1, std::memory_order_acq_rel);
  63. * }), lines(0) {
  64. * // init code here ...
  65. * }
  66. * // ISR handler
  67. * void usart_isr_ (void) {
  68. * rx_q << // char from ISR
  69. * }
  70. * // CRTP requirements
  71. * size_t get(char* data, bool wait =false) {
  72. * do {
  73. * if (lines.load(std::memory_order_acquire)) {
  74. * size_t n =0;
  75. * do{
  76. * *data << rx_q;
  77. * ++n;
  78. * } while (*data++ != base_type::delimiter);
  79. * lines.fetch_sub(1, std::memory_order_acq_rel);
  80. * return n;
  81. * }
  82. * } while (wait);
  83. * return 0;
  84. * }
  85. * size_t put (const char* data, size_t n) {
  86. * // send data to UART
  87. * return n;
  88. * }
  89. * const range_t contents() const { return range_t {rx_q.begin(), rx_q.end()}; }
  90. * clock_t clock() { } // return systems CPU time
  91. * };
  92. * \endcode
  93. *
  94. * \tparam Impl_t
  95. * \tparam Cont_t
  96. * \tparam N
  97. * \tparam Delimiter
  98. */
  99. template<typename Impl_t, typename Cont_t, size_t N, char Delimiter ='\n'>
  100. class BG95_base
  101. : public sequencer<BG95_base<Impl_t, Cont_t, N, Delimiter>, Cont_t, char, N>{
  102. _CRTP_IMPL(Impl_t);
  103. static_assert(
  104. std::is_same_v<typename Cont_t::value_type, char>,
  105. "Cont_t must be a container of type char"
  106. );
  107. // local type dispatch
  108. using base_type = sequencer<BG95_base, Cont_t, char, N>;
  109. using str_view_t = typename base_type::str_view_t;
  110. using range_t = typename Cont_t::range_t;
  111. //! \name Public types
  112. //! @{
  113. public:
  114. using action_t = typename base_type::action_t;
  115. using control_t = typename base_type::control_t;
  116. using match_t = typename base_type::match_t;
  117. using handler_ft = typename base_type::handler_ft;
  118. template<size_t Nm>
  119. using script_t = typename base_type::template script_t<Nm>;
  120. //! Publish delimiter
  121. constexpr static char delimiter = Delimiter;
  122. //! Required types for inetd async handler operation
  123. //! @{
  124. struct inetd_handler_t {
  125. str_view_t token;
  126. match_t match;
  127. handler_ft handler;
  128. };
  129. template <size_t Nm>
  130. using inetd_handlers = std::array<inetd_handler_t, Nm>;
  131. //! @}
  132. //! @}
  133. //! \name Constructor / Destructor
  134. //!@{
  135. protected:
  136. //!< \brief A default constructor from derived only
  137. BG95_base() = default;
  138. ~BG95_base () = default; //!< \brief Allow destructor from derived only
  139. BG95_base(const BG95_base&) = delete; //!< No copies
  140. BG95_base& operator= (const BG95_base&) = delete; //!< No copy assignments
  141. //!@}
  142. //! \name Sequencer interface requirements
  143. //! Forwarded to implementer the calls and cascade the the incoming channel
  144. //! sequencer::get --resolved--> this->receive() --calls--> impl().get()
  145. //! @{
  146. friend base_type;
  147. private:
  148. size_t get_ (char* data) {
  149. return impl().get (data);
  150. }
  151. size_t get (char* data) {
  152. return receive (data);
  153. }
  154. size_t put (const char* data, size_t n) {
  155. return impl().put (data, n);
  156. }
  157. const range_t contents () const {
  158. return impl().contents();
  159. }
  160. clock_t clock () {
  161. return impl().clock();
  162. }
  163. //! @}
  164. //! \name Private functionality
  165. //! @{
  166. private:
  167. template<typename T>
  168. void extract (const char* str, T* value) {
  169. static_assert (
  170. std::is_same_v<std::remove_cv_t<T>, int>
  171. || std::is_same_v<std::remove_cv_t<T>, double>
  172. || std::is_same_v<std::remove_cv_t<T>, char>,
  173. "Not supported conversion type.");
  174. if constexpr (std::is_same_v<std::remove_cv_t<T>, int>) {
  175. *value = std::atoi(str);
  176. } else if (std::is_same_v<std::remove_cv_t<T>, double>) {
  177. *value = std::atof(str);
  178. } else if (std::is_same_v<std::remove_cv_t<T>, char>) {
  179. std::strcpy(value, str);
  180. }
  181. }
  182. template <char Marker = '%'>
  183. std::pair<size_t, bool> parse (const char* expected, const str_view_t buffer, char* token) {
  184. if (*expected == Marker) {
  185. // We have Marker. Copy to token the next part of buffer, from begin up to expected[1] where
  186. // the expected[1] character is and return the size of that part.
  187. auto next = std::find(buffer.begin(), buffer.end(), expected[1]);
  188. if (next == buffer.end()) {
  189. *token =0;
  190. return std::make_pair(0, false);
  191. }
  192. char* nullpos = std::copy(buffer.begin(), next, token);
  193. *nullpos =0;
  194. return std::make_pair(next - buffer.begin(), true);
  195. }
  196. else if (*expected == buffer.front()) {
  197. // We have character match, copy the character to token and return 1 (the char size)
  198. *token++ = buffer.front();
  199. *token =0;
  200. return std::make_pair(1, false);
  201. }
  202. else {
  203. // Discrepancy. Return 0 (none parsed)
  204. *token =0;
  205. return std::make_pair(0, false);
  206. }
  207. }
  208. //! @}
  209. //! \name public functionality
  210. //! @{
  211. public:
  212. /*!
  213. * \brief
  214. * Transmit data to modem
  215. * \param data Pointer to data to send
  216. * \param n The size of data buffer
  217. * \return The number of transmitted chars
  218. */
  219. size_t transmit (const char* data, size_t n) {
  220. return put (data, n);
  221. }
  222. size_t transmit (const char* data) {
  223. return put (data, strlen(data));
  224. }
  225. /*!
  226. * \brief
  227. * Try to receive data from modem. If there are data copy them to \c data pointer and retur
  228. * the size. Otherwise return zero. In the case \c wait is true block until there are data to get.
  229. *
  230. * \param data Pointer to data buffer to write
  231. * \param wait Flag to select blocking / non-blocking functionality
  232. * \return The number of copied data.
  233. */
  234. size_t receive (char* data, bool wait =false) {
  235. do {
  236. if (streams_.load(std::memory_order_acquire)) {
  237. size_t n =0;
  238. do {
  239. *data << rx_q;
  240. ++n;
  241. } while (*data++ != delimiter);
  242. *data =0;
  243. streams_.fetch_sub(1, std::memory_order_acq_rel);
  244. return n;
  245. }
  246. } while (wait); // on wait flag we block until available stream
  247. return 0;
  248. }
  249. /*!
  250. * \brief
  251. * Send a command to modem and check if the response matches to
  252. * \c expected. If so read any token inside response marked with
  253. * \c Marker, convert the value into type \c T and write it to \c t
  254. *
  255. * \param cmd The comand to send (null terminated)
  256. * \param expected The expected response
  257. * \param t The value to return
  258. * \param timeout The timeout in CPU time (leave it for 0 - no timeout)
  259. *
  260. * \tparam T The type of the value to read from response marked with \c Marker
  261. * \tparam Marker The marker character
  262. * \return True on success
  263. *
  264. * example
  265. * \code
  266. * BG95<256> modem;
  267. * std::thread th1 ([&](){
  268. * modem.inetd(false);
  269. * });
  270. * int status;
  271. * bool done = modem.command("AT+CREG?\r\n", "\r\n+CREG: 0,%\r\n\r\nOK\r\n", status);
  272. * if (done && status == 1)
  273. * std::cout << "Connected to home network\n"
  274. * \endcode
  275. */
  276. template <typename T, char Marker = '%'>
  277. bool command (const str_view_t cmd, const str_view_t expected, T* value, clock_t timeout =0) {
  278. char buffer[N];
  279. char token[N];
  280. transmit(cmd.data()); // send command
  281. for (auto ex = expected.begin() ; ex != expected.end() ; ) {
  282. clock_t mark = clock(); // load the answer with timeout
  283. size_t sz =0;
  284. do {
  285. sz = receive(buffer);
  286. if ((timeout != 0 )&& ((clock() - mark) >= timeout))
  287. return false;
  288. } while (!sz);
  289. for (size_t i=0 ; i<sz ; ) { // parse buffer based on expected
  290. auto [step, marker] = parse<Marker> (ex++, {&buffer[i], sz-i}, token);
  291. if (!step) return false;
  292. if (marker) extract(token, value);
  293. i += step;
  294. }
  295. }
  296. return true;
  297. }
  298. /*!
  299. * \brief
  300. * inetd daemon functionality provided as member function of the driver. This should be running
  301. * in the background either as consecutive calls from an periodic ISR with \c loop = false, or
  302. * as a thread in an RTOS environment with \c loop = true.
  303. *
  304. * \tparam Nm The number of handler array entries
  305. *
  306. * \param async_handles Reference to asynchronous handler array
  307. * \param loop Flag to indicate blocking mode. If true blocking.
  308. */
  309. template <size_t Nm =0>
  310. void inetd (bool loop =true, const inetd_handlers<Nm>* inetd_handlers =nullptr) {
  311. std::array<char, N> buffer;
  312. size_t resp_size;
  313. do {
  314. if ((resp_size = get_(buffer.data())) != 0) {
  315. // on data check for async handlers
  316. bool match = false;
  317. if (inetd_handlers != nullptr) {
  318. for (auto& h : *inetd_handlers)
  319. match |= base_type::check_handle(h.token, h.match, h.handler, {buffer.data(), resp_size});
  320. }
  321. // if no match forward data to receive channel.
  322. if (!match) {
  323. char* it = buffer.data();
  324. do {
  325. rx_q << *it;
  326. } while (*it++ != delimiter);
  327. streams_.fetch_add(1, std::memory_order_acq_rel);
  328. }
  329. }
  330. } while (loop);
  331. }
  332. //! @}
  333. private:
  334. equeue<char, N, true> rx_q{};
  335. std::atomic<size_t> streams_{};
  336. };
  337. } // namespace tbx;
  338. #endif /* TBX_DRV_BG95_base_H_ */