A C++ toolbox repo until the pair uTL/dTL arives
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 

328 lines
12 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. * \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 BG95_base
  59. : public sequencer<BG95_base<Impl_t, N, Delimiter>, char, N>{
  60. _CRTP_IMPL(Impl_t);
  61. // local type dispatch
  62. using base_type = sequencer<BG95_base, 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. BG95_base() = default;
  94. ~BG95_base () = default; //!< \brief Allow destructor from derived only
  95. BG95_base(const BG95_base&) = delete; //!< No copies
  96. BG95_base& operator= (const BG95_base&) = 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 T>
  124. void extract (const char* str, T* value) {
  125. static_assert (
  126. std::is_same_v<std::remove_cv_t<T>, int>
  127. || std::is_same_v<std::remove_cv_t<T>, double>
  128. || std::is_same_v<std::remove_cv_t<T>, char>,
  129. "Not supported conversion type.");
  130. if constexpr (std::is_same_v<std::remove_cv_t<T>, int>) {
  131. *value = std::atoi(str);
  132. } else if (std::is_same_v<std::remove_cv_t<T>, double>) {
  133. *value = std::atof(str);
  134. } else if (std::is_same_v<std::remove_cv_t<T>, char>) {
  135. std::strcpy(value, str);
  136. }
  137. }
  138. template <char Marker = '%'>
  139. std::pair<size_t, bool> parse (const char* expected, const string_view buffer, char* token) {
  140. do {
  141. if (*expected == Marker) {
  142. // We have Marker. Copy to token the next part of buffer, from begin up to expected[1] where
  143. // the expected[1] character is and return the size of that part.
  144. auto next = std::find(buffer.begin(), buffer.end(), expected[1]);
  145. if (next == buffer.end())
  146. break;
  147. char* nullpos = std::copy(buffer.begin(), next, token);
  148. *nullpos =0;
  149. return std::make_pair(next - buffer.begin(), true);
  150. }
  151. else if (*expected == buffer.front()) {
  152. // We have character match, copy the character to token and return 1 (the char size)
  153. *token++ = buffer.front();
  154. *token =0;
  155. return std::make_pair(1, false);
  156. }
  157. } while (0);
  158. // Fail to parse
  159. *token =0;
  160. return std::make_pair(0, false);
  161. }
  162. //! @}
  163. //! \name public functionality
  164. //! @{
  165. public:
  166. /*!
  167. * \brief
  168. * Transmit data to modem
  169. * \param data Pointer to data to send
  170. * \param n The size of data buffer
  171. * \return The number of transmitted chars
  172. */
  173. size_t transmit (const char* data, size_t n) {
  174. return put (data, n);
  175. }
  176. size_t transmit (const char* data) {
  177. return put (data, strlen(data));
  178. }
  179. /*!
  180. * \brief
  181. * Try to receive data from modem. If there are data copy them to \c data pointer and retur
  182. * the size. Otherwise return zero. In the case \c wait is true block until there are data to get.
  183. *
  184. * \param data Pointer to data buffer to write
  185. * \param wait Flag to select blocking / non-blocking functionality
  186. * \return The number of copied data.
  187. */
  188. size_t receive (char* data, bool wait =false) {
  189. do {
  190. if (streams_.load(std::memory_order_acquire)) {
  191. size_t n =0;
  192. do {
  193. *data << rx_q;
  194. ++n;
  195. } while (*data++ != delimiter);
  196. *data =0;
  197. streams_.fetch_sub(1, std::memory_order_acq_rel);
  198. return n;
  199. }
  200. } while (wait); // on wait flag we block until available stream
  201. return 0;
  202. }
  203. /*!
  204. * \brief
  205. * Send a command to modem and check if the response matches to
  206. * \c expected. If so read any token inside response marked with
  207. * \c Marker, convert the value into type \c T and write it to \c t
  208. *
  209. * \param cmd The comand to send (null terminated)
  210. * \param expected The expected response
  211. * \param t The value to return
  212. * \param timeout The timeout in CPU time (leave it for 0 - no timeout)
  213. *
  214. * \tparam T The type of the value to read from response marked with \c Marker
  215. * \tparam Marker The marker character
  216. * \return True on success
  217. *
  218. * example
  219. * \code
  220. * BG95<256> modem;
  221. * std::thread th1 ([&](){
  222. * modem.inetd(false);
  223. * });
  224. * int status;
  225. * bool done = modem.command("AT+CREG?\r\n", "\r\n+CREG: 0,%\r\n\r\nOK\r\n", status);
  226. * if (done && status == 1)
  227. * std::cout << "Connected to home network\n"
  228. * \endcode
  229. */
  230. template <typename T, char Marker = '%'>
  231. bool command (const string_view cmd, const string_view expected, T* value, clock_t timeout =0) {
  232. char buffer[N];
  233. char token[N];
  234. transmit(cmd.data()); // send command
  235. for (auto ex = expected.begin() ; ex != expected.end() ; ) {
  236. clock_t mark = clock(); // load the answer with timeout
  237. size_t sz =0;
  238. do {
  239. sz = receive(buffer);
  240. if ((timeout != 0 )&& ((clock() - mark) >= timeout))
  241. return false;
  242. } while (!sz);
  243. for (size_t i=0 ; i<sz ; ) { // parse buffer based on expected
  244. auto [step, marker] = parse<Marker> (ex++, {&buffer[i], sz-i}, token);
  245. if (!step) return false;
  246. if (marker) extract(token, value);
  247. i += step;
  248. }
  249. }
  250. return true;
  251. }
  252. /*!
  253. * \brief
  254. * inetd daemon functionality provided as member function of the driver. This should be running
  255. * in the background either as consecutive calls from an periodic ISR with \c loop = false, or
  256. * as a thread in an RTOS environment with \c loop = true.
  257. *
  258. * \tparam Nm The number of handler array entries
  259. *
  260. * \param async_handles Reference to asynchronous handler array
  261. * \param loop Flag to indicate blocking mode. If true blocking.
  262. */
  263. template <size_t Nm =0>
  264. void inetd (bool loop =true, const inetd_handlers<Nm>* inetd_handlers =nullptr) {
  265. std::array<char, N> buffer;
  266. size_t resp_size;
  267. do {
  268. if ((resp_size = get_(buffer.data())) != 0) {
  269. // on data check for async handlers
  270. bool match = false;
  271. if (inetd_handlers != nullptr) {
  272. for (auto& h : *inetd_handlers)
  273. match |= base_type::check_handle({buffer.data(), resp_size}, h.token, h.match, h.handler);
  274. }
  275. // if no match forward data to receive channel.
  276. if (!match) {
  277. char* it = buffer.data();
  278. do {
  279. rx_q << *it;
  280. } while (*it++ != delimiter);
  281. streams_.fetch_add(1, std::memory_order_acq_rel);
  282. }
  283. }
  284. } while (loop);
  285. }
  286. //! @}
  287. private:
  288. equeue<char, N, true> rx_q{};
  289. std::atomic<size_t> streams_{};
  290. };
  291. } // namespace tbx;
  292. #endif /* TBX_DRV_BG95_base_H_ */