A C++ toolbox repo until the pair uTL/dTL arives
Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

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