A C++ toolbox repo until the pair uTL/dTL arives
25'ten fazla konu seçemezsiniz Konular bir harf veya rakamla başlamalı, kısa çizgiler ('-') içerebilir ve en fazla 35 karakter uzunluğunda olabilir.
 
 
 

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