A C++ toolbox repo until the pair uTL/dTL arives
25개 이상의 토픽을 선택하실 수 없습니다. Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 

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