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.
 
 
 

495 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. }
  260. //! \return Returns the size of the incoming data buffer
  261. size_t size() noexcept {
  262. return rx_q.size();
  263. }
  264. /*!
  265. * \brief
  266. * Transmit data to modem
  267. * \param data Pointer to data to send
  268. * \param n The size of data buffer
  269. * \return The number of transmitted chars
  270. */
  271. size_t transmit (const char* data, size_t n) {
  272. if (data == nullptr)
  273. return 0;
  274. return put (data, n);
  275. }
  276. /*!
  277. * \brief
  278. * Transmit data to modem
  279. * \param data Pointer to data to send
  280. * \return The number of transmitted chars
  281. */
  282. size_t transmit (const char* data) {
  283. if (data == nullptr)
  284. return 0;
  285. return put (data, std::strlen(data));
  286. }
  287. /*!
  288. * \brief
  289. * Try to receive data from modem. If there are data copy them to \c data pointer and return
  290. * the size. Otherwise return zero. In the case \c wait is true block until there are data to get.
  291. *
  292. * \param data Pointer to data buffer to write
  293. * \param wait Flag to select blocking / non-blocking functionality
  294. * \return The number of copied data.
  295. */
  296. size_t receive (char* data, bool wait =false) {
  297. do {
  298. if (streams_.load(std::memory_order_acquire)) {
  299. size_t n =0;
  300. do {
  301. *data << rx_q;
  302. ++n;
  303. } while (*data++ != delimiter);
  304. *data =0;
  305. streams_.fetch_sub(1, std::memory_order_acq_rel);
  306. return n;
  307. }
  308. } while (wait); // on wait flag we block until available stream
  309. return 0;
  310. }
  311. /*!
  312. * Analyze the response of a command based on \c expected.
  313. *
  314. * Tries to receive data via get() path with timeout and match them against expected string_view.
  315. * For each Marker inside the expected string the value gets extracted, converted and
  316. * copied to \c vargs pointer array.
  317. *
  318. * \param expected The expected string view
  319. * \param timeout the timeout in CPU time
  320. * \param vargs Pointer to variable arguments array
  321. * \param nargs Size of variable arguments array
  322. * \return
  323. */
  324. template<Receive_t Recv, char Marker, typename T>
  325. bool response (const string_view expected, clock_t timeout, T* vargs, size_t nargs) {
  326. char buffer[N], token[N], *pbuffer = buffer;
  327. size_t v =0, sz =0;
  328. for (auto ex = expected.begin() ; ex != expected.end() ; ) {
  329. clock_t mark = clock(); // mark the time
  330. while (sz <= 0) { // if buffer is empty get buffer with timeout
  331. if constexpr (Recv == Get)
  332. sz = receive(buffer);
  333. else
  334. sz = contents(buffer);
  335. pbuffer = buffer;
  336. if ((timeout != 0 )&& ((clock() - mark) >= timeout))
  337. return false;
  338. }
  339. // try to parse
  340. auto [step, marker] = parse_<Marker> (ex, {pbuffer, sz}, token);
  341. if (!step)
  342. return false; // discard buffer and fail
  343. if (marker && v < nargs)
  344. extract_(token, vargs[v++]);
  345. pbuffer += step;
  346. sz -= (step <= sz) ? step: sz;
  347. ++ex;
  348. }
  349. return true;
  350. }
  351. /*!
  352. * \brief
  353. * Send a command to modem and check if the response matches to \c expected.
  354. *
  355. * This function executes 3 steps.
  356. * - Clears the incoming buffer if requested by template parameter
  357. * - Sends the command to device
  358. * - Waits to get the response and parse it accordingly to \c expected \see response()
  359. *
  360. * The user can mark spots inside the expected string using the \c Marker ['%'] character.
  361. * These spots will be extracted to tokens upon parsing. If the user passes \c values parameters,
  362. * then the extracted tokens will be converted to the type of the \c values (\c Ts) and copied to them
  363. * one by one. If the values are less than spots, the rest of the tokens get discarded.
  364. *
  365. * \param cmd The command to send (null terminated)
  366. * \param expected The expected response
  367. * \param timeout The timeout in CPU time (leave it for 0 - no timeout)
  368. * \param values The value pointer arguments to get the converted tokens
  369. *
  370. * \tparam Flush Flag to indicate if we Flush the buffer before command or not
  371. * \tparam Marker The marker character
  372. * \tparam Ts The type of the values to read from response marked with \c Marker
  373. * \warning The types MUST be the same
  374. *
  375. * \return True on success
  376. *
  377. * \example examples
  378. * \code
  379. * Derived cli;
  380. * int status;
  381. * char str[32];
  382. *
  383. * // discard 3 lines and expect OK\r\n at the end with 1000[CPU time] timeout
  384. * cli.command("AT+CREG?\r\n", "%%%OK\r\n", 1000);
  385. *
  386. * // extract a number from response without timeout (blocking)
  387. * cli.command<Flush>("AT+CREG?\r\n", "\r\n+CREG: 0,%\r\n\r\nOK\r\n", 0, &status);
  388. *
  389. * // extract a number and discard the last 2 lines
  390. * cli.command<Flush>("AT+CREG?\r\n", "\r\n+CREG: 0,%\r\n%%", 1000, &status);
  391. *
  392. * // discard first line, read the 2nd to str, discard the 3rd line.
  393. * // expect the last to be "OK\r\n"
  394. * cli.command<Flush>("AT+CREG?\r\n", "", 100000);
  395. * cli.command<Keep>("", "%", 1000);
  396. * cli.command<Keep>("", "%%", 1000, str);
  397. * cli.command<Keep>("", "OK\r\n", 1000);
  398. * \endcode
  399. */
  400. template<Receive_t Recv =Get, Flush_t Flsh =Flush, char Marker = '%', typename ...Ts>
  401. bool command (const string_view cmd, const string_view expected, clock_t timeout, Ts* ...values) {
  402. constexpr size_t Nr = sizeof...(Ts);
  403. front<typelist<Ts...>>* vargs[Nr] = {values...}; // read all args to local buffer
  404. if constexpr (Flsh == Flush) {
  405. clear ();
  406. }
  407. if (transmit(cmd.data(), cmd.size()) != cmd.size()) // send command
  408. return false;
  409. // parse the response and return the status
  410. return response<Recv, Marker>(expected, timeout, vargs, Nr);
  411. }
  412. /*!
  413. * \brief
  414. * inetd daemon functionality provided as member function of the driver. This should be running
  415. * in the background either as consecutive calls from an periodic ISR with \c loop = false, or
  416. * as a thread in an RTOS environment with \c loop = true.
  417. *
  418. * \tparam Nm The number of handler array entries
  419. *
  420. * \param async_handles Reference to asynchronous handler array
  421. * \param loop Flag to indicate blocking mode. If true blocking.
  422. */
  423. template <size_t Nm =0>
  424. void inetd (bool loop =true, const inetd_handlers<Nm>* inetd_handlers =nullptr) {
  425. std::array<char, N> buffer;
  426. size_t resp_size;
  427. do {
  428. if ((resp_size = get_(buffer.data())) != 0) {
  429. // on data check for async handlers
  430. bool match = false;
  431. if (inetd_handlers != nullptr) {
  432. for (auto& h : *inetd_handlers)
  433. match |= base_type::check_handle({buffer.data(), resp_size}, h.token, h.match, h.handler);
  434. }
  435. // if no match forward data to receive channel.
  436. if (!match) {
  437. char* it = buffer.data();
  438. do {
  439. rx_q << *it;
  440. } while (*it++ != delimiter);
  441. streams_.fetch_add(1, std::memory_order_acq_rel);
  442. }
  443. }
  444. } while (loop);
  445. }
  446. //! @}
  447. private:
  448. equeue<char, N, true> rx_q{};
  449. std::atomic<size_t> streams_{};
  450. };
  451. } // namespace tbx;
  452. #endif /* #ifndef TBX_DRV_CLI_DEVICE_H_ */