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.
 
 
 

496 lines
20 KiB

  1. /*!
  2. * \file drv/cli_device.h
  3. * \brief
  4. * command line device 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_CLI_DEVICE_H_
  31. #define TBX_DRV_CLI_DEVICE_H_
  32. #include <core/core.h>
  33. #include <core/crtp.h>
  34. #include <cont/equeue.h>
  35. #include <com/sequencer.h>
  36. #include <cstring>
  37. #include <cstdlib>
  38. #include <algorithm>
  39. #include <utility>
  40. #include <atomic>
  41. namespace tbx {
  42. /*!
  43. * \class cli_device
  44. * \brief
  45. * Its a base class for command-line based devices
  46. *
  47. * Inherits the sequencer functionality and provides a command interface for sending
  48. * commands and parse the response.
  49. *
  50. * \example implementation example
  51. * \code
  52. * class BG95 : public cli_device<BG95, 256> {
  53. * using base_type = cli_device<BG95, 256>;
  54. * using Queue = equeue<typename base_type::value_type, 256, true>;
  55. * Queue RxQ{};
  56. * std::atomic<size_t> lines{};
  57. * public:
  58. * // cli_device driver requirements
  59. * BG95() noexcept :
  60. * RxQ(Queue::data_match::MATCH_PUSH, base_type::delimiter, [&](){
  61. * lines.fetch_add(1, std::memory_order_acq_rel);
  62. * }), lines(0) { }
  63. * void feed(char x) { RxQ << x; } // To be used inside ISR
  64. * size_t get(char* data, bool wait =false) {
  65. * do {
  66. * if (lines.load(std::memory_order_acquire)) {
  67. * size_t n =0;
  68. * do{
  69. * *data << RxQ;
  70. * ++n;
  71. * } while (*data++ != base_type::delimiter);
  72. * lines.fetch_sub(1, std::memory_order_acq_rel);
  73. * return n;
  74. * }
  75. * } while (wait);
  76. * return 0;
  77. * }
  78. * size_t contents(char* data) {
  79. * char* nullpos = std::copy(RxQ.begin(), RxQ.end(), data);
  80. * *nullpos =0;
  81. * return nullpos - data;
  82. * }
  83. * size_t put (const char* data, size_t n) {
  84. * // send data to BG95
  85. * return n;
  86. * }
  87. * clock_t clock() noexcept { //return CPU time }
  88. * };
  89. * \endcode
  90. *
  91. * \tparam Impl_t The type of derived class
  92. * \tparam N The size of the queue buffer for the receive/command interface
  93. * \tparam Delimiter The incoming data delimiter [default line buffered -- Delimiter = '\n']
  94. */
  95. template<typename Impl_t, size_t N, char Delimiter ='\n'>
  96. class cli_device
  97. : public sequencer<cli_device<Impl_t, N, Delimiter>, char, N>{
  98. _CRTP_IMPL(Impl_t);
  99. // local type dispatch
  100. using base_type = sequencer<cli_device, char, N>;
  101. //! \name Public types
  102. //! @{
  103. public:
  104. using value_type = char;
  105. using pointer_type = char*;
  106. using size_type = size_t;
  107. using string_view = typename base_type::string_view;
  108. using action_t = typename base_type::action_t;
  109. using control_t = typename base_type::control_t;
  110. using match_ft = typename base_type::match_ft;
  111. using handler_ft = typename base_type::handler_ft;
  112. template<size_t Nm>
  113. using script_t = typename base_type::template script_t<Nm>;
  114. //! Publish delimiter
  115. constexpr static char delimiter = Delimiter;
  116. enum Flush_t { Keep =0, Flush };
  117. enum Receive_t { Get =0, Detect };
  118. //! Required types for inetd async handler operation
  119. //! @{
  120. /*!
  121. * inetd handler structure for asynchronous incoming data dispatching
  122. */
  123. struct inetd_handler_t {
  124. string_view token; //!< The token we match against
  125. match_ft match; //!< The predicate we use to match
  126. handler_ft handler; //!< The handler to call on match
  127. };
  128. //! Alias template for the async handler array
  129. template <size_t Nm>
  130. using inetd_handlers = std::array<inetd_handler_t, Nm>;
  131. //! @}
  132. //! @}
  133. //! \name object lifetime
  134. //!@{
  135. protected:
  136. //!< \brief A default constructor from derived only
  137. cli_device() noexcept = default;
  138. ~cli_device () = default; //!< \brief Allow destructor from derived only
  139. cli_device(const cli_device&) = delete; //!< No copies
  140. cli_device& operator= (const cli_device&) = delete; //!< No copy assignments
  141. //!@}
  142. //! \name Sequencer interface requirements
  143. //! Forwarded to implementer the calls and cascade the the incoming channel
  144. //! @{
  145. friend base_type;
  146. private:
  147. size_t get_ (char* data) {
  148. return impl().get (data);
  149. }
  150. size_t get (char* data) {
  151. return receive (data);
  152. }
  153. size_t contents (char* data) {
  154. return impl().contents(data);
  155. }
  156. size_t put (const char* data, size_t n) {
  157. return impl().put (data, n);
  158. }
  159. clock_t clock () noexcept {
  160. return impl().clock();
  161. }
  162. //! @}
  163. //! \name Private functionality
  164. //! @{
  165. private:
  166. //! typelist "container". A container of template parameter type arguments
  167. template <typename... Ts>
  168. struct typelist {
  169. using type = typelist; //!< act as identity
  170. };
  171. //! front functionality: get the first type of the typelist "container"
  172. template <typename L>
  173. struct front_impl {
  174. using type = void;
  175. };
  176. template <typename Head, typename... Tail>
  177. struct front_impl<typelist<Head, Tail...>> {
  178. using type = Head;
  179. };
  180. //! Return the first element in \c typelist \c List.
  181. //!
  182. //! Complexity \f$ O(1) \f$.
  183. template <typename List>
  184. using front = typename front_impl<List>::type;
  185. /*!
  186. * Convert the text pointed by \c str to a value and store it to
  187. * \c value. The type of conversion is deduced by the compiler
  188. * \tparam T The type of the value
  189. * \param str pointer to string with the value
  190. * \param value pointer to converted value
  191. */
  192. template<typename T>
  193. void extract_ (const char* str, T* value) {
  194. static_assert (
  195. std::is_same_v<std::remove_cv_t<T>, int>
  196. || std::is_same_v<std::remove_cv_t<T>, double>
  197. || std::is_same_v<std::remove_cv_t<T>, char>,
  198. "Not supported conversion type.");
  199. if constexpr (std::is_same_v<std::remove_cv_t<T>, int>) {
  200. *value = std::atoi(str);
  201. } else if (std::is_same_v<std::remove_cv_t<T>, double>) {
  202. *value = std::atof(str);
  203. } else if (std::is_same_v<std::remove_cv_t<T>, char>) {
  204. std::strcpy(value, str);
  205. }
  206. }
  207. //! Specialization (as overload function) to handle void* types
  208. void extract_ (const char* str, void* value) noexcept {
  209. (void)*str; (void)value;
  210. }
  211. /*!
  212. * Parse a chunk of the buffer based on \c expected character
  213. *
  214. * Tries to match the \c *expected character in buffer and if so it copies the
  215. * character to token.
  216. * If the \c *expected is the \c Marker character, copy the entire chunk of the buffer
  217. * up to the character that matches the next expected character (expected[1]).
  218. * If there is no next expected character or if its not found in the buffer,
  219. * copy the entire buffer.
  220. *
  221. * \tparam Marker The special character to indicate chunk extraction
  222. *
  223. * \param expected The character to parse/remove from the buffer
  224. * \param buffer The buffer we parse
  225. * \param token Pointer to store the parsed tokens
  226. * \return A (number of characters parsed, marker found) pair
  227. */
  228. template <char Marker>
  229. std::pair<size_t, bool> parse_ (const char* expected, const string_view buffer, char* token) {
  230. do {
  231. if (*expected == Marker) {
  232. // We have Marker. Copy the entire chunk of the buffer
  233. // up to the character that matches the next expected character (expected[1]).
  234. // If there is none next expected character or if its not found in the buffer,
  235. // copy the entire buffer.
  236. auto next = std::find(buffer.begin(), buffer.end(), expected[1]);
  237. char* nullpos = std::copy(buffer.begin(), next, token);
  238. *nullpos =0;
  239. return std::make_pair(next - buffer.begin(), true);
  240. }
  241. else if (*expected == buffer.front()) {
  242. // We have character match, copy the character to token and return 1 (the char size)
  243. *token++ = buffer.front();
  244. *token =0;
  245. return std::make_pair(1, false);
  246. }
  247. } while (0);
  248. // Fail to parse
  249. *token =0;
  250. return std::make_pair(0, false);
  251. }
  252. //! @}
  253. //! \name public functionality
  254. //! @{
  255. public:
  256. //! Clears the incoming data buffer
  257. void clear () noexcept {
  258. rx_q.clear();
  259. streams_.store(size_t(0), std::memory_order_release);
  260. }
  261. //! \return Returns the size of the incoming data buffer
  262. size_t size() noexcept {
  263. return rx_q.size();
  264. }
  265. /*!
  266. * \brief
  267. * Transmit data to modem
  268. * \param data Pointer to data to send
  269. * \param n The size of data buffer
  270. * \return The number of transmitted chars
  271. */
  272. size_t transmit (const char* data, size_t n) {
  273. if (data == nullptr)
  274. return 0;
  275. return put (data, n);
  276. }
  277. /*!
  278. * \brief
  279. * Transmit data to modem
  280. * \param data Pointer to data to send
  281. * \return The number of transmitted chars
  282. */
  283. size_t transmit (const char* data) {
  284. if (data == nullptr)
  285. return 0;
  286. return put (data, std::strlen(data));
  287. }
  288. /*!
  289. * \brief
  290. * Try to receive data from modem. If there are data copy them to \c data pointer and return
  291. * the size. Otherwise return zero. In the case \c wait is true block until there are data to get.
  292. *
  293. * \param data Pointer to data buffer to write
  294. * \param wait Flag to select blocking / non-blocking functionality
  295. * \return The number of copied data.
  296. */
  297. size_t receive (char* data, bool wait =false) {
  298. do {
  299. if (streams_.load(std::memory_order_acquire)) {
  300. size_t n =0;
  301. do {
  302. *data << rx_q;
  303. ++n;
  304. } while (*data++ != delimiter);
  305. *data =0;
  306. streams_.fetch_sub(1, std::memory_order_acq_rel);
  307. return n;
  308. }
  309. } while (wait); // on wait flag we block until available stream
  310. return 0;
  311. }
  312. /*!
  313. * Analyze the response of a command based on \c expected.
  314. *
  315. * Tries to receive data via get() path with timeout and match them against expected string_view.
  316. * For each Marker inside the expected string the value gets extracted, converted and
  317. * copied to \c vargs pointer array.
  318. *
  319. * \param expected The expected string view
  320. * \param timeout the timeout in CPU time
  321. * \param vargs Pointer to variable arguments array
  322. * \param nargs Size of variable arguments array
  323. * \return
  324. */
  325. template<Receive_t Recv, char Marker, typename T>
  326. bool response (const string_view expected, clock_t timeout, T* vargs, size_t nargs) {
  327. char buffer[N], token[N], *pbuffer = buffer;
  328. size_t v =0, sz =0;
  329. for (auto ex = expected.begin() ; ex != expected.end() ; ) {
  330. clock_t mark = clock(); // mark the time
  331. while (sz <= 0) { // if buffer is empty get buffer with timeout
  332. if constexpr (Recv == Get)
  333. sz = receive(buffer);
  334. else
  335. sz = contents(buffer);
  336. pbuffer = buffer;
  337. if ((timeout != 0 )&& ((clock() - mark) >= timeout))
  338. return false;
  339. }
  340. // try to parse
  341. auto [step, marker] = parse_<Marker> (ex, {pbuffer, sz}, token);
  342. if (!step)
  343. return false; // discard buffer and fail
  344. if (marker && v < nargs)
  345. extract_(token, vargs[v++]);
  346. pbuffer += step;
  347. sz -= (step <= sz) ? step: sz;
  348. ++ex;
  349. }
  350. return true;
  351. }
  352. /*!
  353. * \brief
  354. * Send a command to modem and check if the response matches to \c expected.
  355. *
  356. * This function executes 3 steps.
  357. * - Clears the incoming buffer if requested by template parameter
  358. * - Sends the command to device
  359. * - Waits to get the response and parse it accordingly to \c expected \see response()
  360. *
  361. * The user can mark spots inside the expected string using the \c Marker ['%'] character.
  362. * These spots will be extracted to tokens upon parsing. If the user passes \c values parameters,
  363. * then the extracted tokens will be converted to the type of the \c values (\c Ts) and copied to them
  364. * one by one. If the values are less than spots, the rest of the tokens get discarded.
  365. *
  366. * \param cmd The command to send (null terminated)
  367. * \param expected The expected response
  368. * \param timeout The timeout in CPU time (leave it for 0 - no timeout)
  369. * \param values The value pointer arguments to get the converted tokens
  370. *
  371. * \tparam Flush Flag to indicate if we Flush the buffer before command or not
  372. * \tparam Marker The marker character
  373. * \tparam Ts The type of the values to read from response marked with \c Marker
  374. * \warning The types MUST be the same
  375. *
  376. * \return True on success
  377. *
  378. * \example examples
  379. * \code
  380. * Derived cli;
  381. * int status;
  382. * char str[32];
  383. *
  384. * // discard 3 lines and expect OK\r\n at the end with 1000[CPU time] timeout
  385. * cli.command("AT+CREG?\r\n", "%%%OK\r\n", 1000);
  386. *
  387. * // extract a number from response without timeout (blocking)
  388. * cli.command<Flush>("AT+CREG?\r\n", "\r\n+CREG: 0,%\r\n\r\nOK\r\n", 0, &status);
  389. *
  390. * // extract a number and discard the last 2 lines
  391. * cli.command<Flush>("AT+CREG?\r\n", "\r\n+CREG: 0,%\r\n%%", 1000, &status);
  392. *
  393. * // discard first line, read the 2nd to str, discard the 3rd line.
  394. * // expect the last to be "OK\r\n"
  395. * cli.command<Flush>("AT+CREG?\r\n", "", 100000);
  396. * cli.command<Keep>("", "%", 1000);
  397. * cli.command<Keep>("", "%%", 1000, str);
  398. * cli.command<Keep>("", "OK\r\n", 1000);
  399. * \endcode
  400. */
  401. template<Receive_t Recv =Get, Flush_t Flsh =Flush, char Marker = '%', typename ...Ts>
  402. bool command (const string_view cmd, const string_view expected, clock_t timeout, Ts* ...values) {
  403. constexpr size_t Nr = sizeof...(Ts);
  404. front<typelist<Ts...>>* vargs[Nr] = {values...}; // read all args to local buffer
  405. if constexpr (Flsh == Flush) {
  406. clear ();
  407. }
  408. if (transmit(cmd.data(), cmd.size()) != cmd.size()) // send command
  409. return false;
  410. // parse the response and return the status
  411. return response<Recv, Marker>(expected, timeout, vargs, Nr);
  412. }
  413. /*!
  414. * \brief
  415. * inetd daemon functionality provided as member function of the driver. This should be running
  416. * in the background either as consecutive calls from an periodic ISR with \c loop = false, or
  417. * as a thread in an RTOS environment with \c loop = true.
  418. *
  419. * \tparam Nm The number of handler array entries
  420. *
  421. * \param async_handles Reference to asynchronous handler array
  422. * \param loop Flag to indicate blocking mode. If true blocking.
  423. */
  424. template <size_t Nm =0>
  425. void inetd (bool loop =true, const inetd_handlers<Nm>* inetd_handlers =nullptr) {
  426. std::array<char, N> buffer;
  427. size_t resp_size;
  428. do {
  429. if ((resp_size = get_(buffer.data())) != 0) {
  430. // on data check for async handlers
  431. bool match = false;
  432. if (inetd_handlers != nullptr) {
  433. for (auto& h : *inetd_handlers)
  434. match |= base_type::check_handle({buffer.data(), resp_size}, h.token, h.match, h.handler);
  435. }
  436. // if no match forward data to receive channel.
  437. if (!match) {
  438. char* it = buffer.data();
  439. do {
  440. rx_q << *it;
  441. } while (*it++ != delimiter);
  442. streams_.fetch_add(1, std::memory_order_acq_rel);
  443. }
  444. }
  445. } while (loop);
  446. }
  447. //! @}
  448. private:
  449. equeue<char, N, true> rx_q{};
  450. std::atomic<size_t> streams_{};
  451. };
  452. } // namespace tbx;
  453. #endif /* #ifndef TBX_DRV_CLI_DEVICE_H_ */