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.
 
 
 

488 lines
22 KiB

  1. /*!
  2. * \file utils/sequencer.h
  3. * \brief
  4. * A terminal-like device communication automation tool
  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_UTILS_SEQUENCER_H_
  31. #define TBX_UTILS_SEQUENCER_H_
  32. #include <core/core.h>
  33. #include <core/crtp.h>
  34. #include <cont/range.h>
  35. #include <ctime>
  36. #include <array>
  37. #include <string_view>
  38. #include <type_traits>
  39. #include <utility>
  40. #include <tuple>
  41. namespace tbx {
  42. /*!
  43. * \class sequencer
  44. * \brief
  45. * A CRTP base class to provide the sequencer functionality.
  46. *
  47. * Sequencer is a script engine with receive/transmit functionalities based on predicates. It has:
  48. * - A program counter like variable named \c step.
  49. * - \c step actions like NEXT, GOTO exit with status etc...
  50. * - Input data match predicates to trigger those actions.
  51. * - Input data handlers to trigger external functionality on predicate match
  52. * - Output data handlers to "edit" data before transmiting them
  53. * - A small predicate set provided to the user. (starts_with, ends_with, contains).
  54. *
  55. * Sequencer can automate communication with a terminal-like device such as AT-command modems, can
  56. * be used to implement communication protocols, or even small http servers.
  57. *
  58. * It can operate based on a script array and handle the outgoing commands and incoming responses.
  59. * The user can create matching rules on received data and hook handlers and actions on them.
  60. *
  61. * The derived class (implementation) has to provide:
  62. * 1) size_t get(Data_t* data);
  63. * This function return 0 or a number of Data_t items. The data points to buffer for the input data.
  64. *
  65. * 3) size_t contents_ (Data_t* data);
  66. * This function return 0 or a number of Data_t items without removing them from the implementer's container
  67. * The data points to buffer for the input data.
  68. *
  69. * 2) size_t put(const Data_t* data, size_t n);
  70. * This function sends to implementation the data pointed by \c data witch have size \c n.
  71. *
  72. * 4) clock_t clock();
  73. * This function return a number to be used as time. The units of this function may be arbitrary but they
  74. * match the units in \c record_t::timeout field.
  75. *
  76. * \tparam Impl_t The type of derived class
  77. * \tparam Data_t The char-like stream item type. Usually \c char
  78. * \tparam N The size of the sequence buffer to temporary store each line from get().
  79. *
  80. * \note
  81. * We need access to derived class container to sneaky get a range of the data beside
  82. * the normal data flow, in order to implement the \see control_t::DETECT operation.
  83. */
  84. template <typename Impl_t, typename Data_t, size_t N>
  85. class sequencer {
  86. _CRTP_IMPL(Impl_t);
  87. //! \name Public types
  88. //! @{
  89. public:
  90. using value_type = Data_t;
  91. using pointer_type = Data_t*;
  92. using size_type = size_t;
  93. using string_view = std::basic_string_view<Data_t>;
  94. /*!
  95. * The sequencer engine status. A variable of this type is returned by
  96. * \see action_().
  97. */
  98. enum class seq_status_t {
  99. CONTINUE, //!< Means we keep looping
  100. EXIT //!< Means, we exit with status the one indicated by \c action_t of the \c record_t
  101. };
  102. //! \enum control_t
  103. //! \brief The control type of the script entry.
  104. enum class control_t {
  105. NOP, //!< No command, dont send or expect anything, used for delays
  106. SEND, //!< Send data to implementation through put()
  107. EXPECT, //!< Expects data from implementation via get()
  108. OR_EXPECT, //!< Expects data from implementation via get() in conjunction with previous EXPECT
  109. DETECT, //!< Detects data into rx buffer without receiving them via contents()
  110. OR_DETECT //!< Detects data into rx buffer without receiving them via contents() in conjunction with
  111. //!< previous DETECT
  112. //! \note
  113. //! The \c DETECT extra incoming channel serve the purpose of sneak into receive
  114. //! buffer and check for data without getting them. This is useful when the receive driver
  115. //! is buffered with a delimiter and we seek for data that don't follow the delimiter pattern.
  116. //!
  117. //! For example:
  118. //! A modem sends responses with '\n' termination but for some "special" command it opens a cursor
  119. //! lets say ">$ " without '\n' at the end.
  120. };
  121. //! \enum action_t
  122. //! \brief
  123. //! Possible response actions for the sequencer. This is the
  124. //! equivalent of changing the program counter of the sequencer
  125. //! and is composed by a type and a value.
  126. //!
  127. struct action_t {
  128. enum {
  129. NO =0, //!< Do not change sequencer's step
  130. NEXT, //!< Go to next sequencer step. In case of EXPECT/DETECT block of records
  131. //!< skip the entire block of EXPECT[, OR_EXPECT[, OR_EXPECT ...]] and go
  132. //!< to the next (non OR_*) control record.
  133. GOTO, //!< Manually sets the step counter to the number of the \c step member.
  134. EXIT, //!< Instruct for an exit returning the action.value as status
  135. } type;
  136. size_t value; //!< Used by \c GOTO to indicate the next sequencer's step.
  137. };
  138. static constexpr action_t no_action = {action_t::NO, 0};
  139. static constexpr action_t next = {action_t::NEXT, 0};
  140. template <size_t GOTO>
  141. static constexpr action_t go_to = {action_t::GOTO, static_cast<size_t>(GOTO)};
  142. static constexpr action_t exit_ok = {action_t::EXIT, 0};
  143. static constexpr action_t exit_error = {action_t::EXIT, static_cast<size_t>(-1)};
  144. template <size_t Status>
  145. static constexpr action_t exit = {action_t::EXIT, static_cast<size_t>(Status)};
  146. /*!
  147. * Match binary predicate function pointer type.
  148. * Expects two string views and return a boolean.
  149. * It is used by EXPECT/DETECT blocks to trigger their {handler, action} pair.
  150. */
  151. using match_ft = bool (*) (const string_view haystack, const string_view needle);
  152. /*!
  153. * Send/Receive handler function pointer type.
  154. * Expects a pointer to buffer and a size and returns status.
  155. * It is used on predicate match on EXPECT/DETECT blocks, or as data wrapper on SEND blocks.
  156. */
  157. using handler_ft = void (*) (const Data_t*, size_t);
  158. /*!
  159. * \struct record_t
  160. * \brief
  161. * Describes the sequencer's script record entry (line).
  162. */
  163. struct record_t {
  164. control_t control; //!< The control type of the entry
  165. string_view token; //!< String view to token data. [MUST BE null terminated].
  166. //!< This is passed as 2nd argument to match predicate on EXPECT/DETECT, or as
  167. //! {data, size} pair to SEND handler and put_().
  168. //!< If unused set it to ""
  169. match_ft match; //!< Match predicate to used in EXPECT/DETECT blocks
  170. //!< If unused set it to nullptr
  171. handler_ft handler; //!< The handler to called if the match is successful, or before put_()
  172. //!< If unused set it to nullptr
  173. action_t action; //!< Indicates the step manipulation if the match is successful or after NOP and put_()
  174. clock_t timeout; //!< Timeout in CPU time
  175. };
  176. /*!
  177. * \struct script_t
  178. * \brief
  179. * Describes the sequencer's script.
  180. *
  181. * The user can create arrays as the example bellow to act as a script.
  182. * \code
  183. * Seq s;
  184. * const Seq::script_t<4> script = {{
  185. * {Seq::control_t::NOP, "", Seq::nil, Seq::nil, {Seq::action_t::GOTO, 1}, 1000},
  186. *
  187. * {Seq::control_t::SEND, "ATE0\r\n", Seq::nil, Seq::nil, {Seq::action_t::NEXT, 0}, 0},
  188. * {Seq::control_t::EXPECT, "OK\r\n", Seq::ends_with, Seq::nil, {Seq::action_t::EXIT_OK, 0}, 1000},
  189. * {Seq::control_t::OR_EXPECT, "ERROR", Seq::contains, Seq::nil, {Seq::action_t::EXIT_ERROR, 0}, 0}
  190. * }};
  191. * s.run(script);
  192. * \endcode
  193. */
  194. template <size_t Nrecords>
  195. using script_t = std::array<record_t, Nrecords>;
  196. /*!
  197. * \brief
  198. * Check if the \c stream1 is equal to \c stream2
  199. * \param stream1 The stream in witch we search [The input buffer]
  200. * \param stream2 What we search [The record's token]
  201. * \return True on success, false otherwise
  202. */
  203. static constexpr auto equals = [](const string_view stream1, const string_view stream2) -> bool {
  204. return (stream1 == stream2);
  205. };
  206. /*!
  207. * \brief
  208. * Check if the \c stream starts with the \c prefix
  209. * \param stream The stream in witch we search [The input buffer]
  210. * \param prefix What we search [The record's token]
  211. * \return True on success, false otherwise
  212. */
  213. static constexpr auto starts_with = [](const string_view stream, const string_view prefix) -> bool {
  214. return (stream.rfind(prefix, 0) != string_view::npos);
  215. };
  216. /*!
  217. * \brief
  218. * Check if the \c stream ends with the \c postfix
  219. * \param stream The stream in witch we search [The input buffer]
  220. * \param postfix What we search [The record's token]
  221. * \return True on success, false otherwise
  222. */
  223. static constexpr auto ends_with = [](const string_view stream, const string_view postfix) -> bool {
  224. if (stream.size() < postfix.size())
  225. return false;
  226. return (
  227. stream.compare(
  228. stream.size() - postfix.size(),
  229. postfix.size(),
  230. postfix) == 0
  231. );
  232. };
  233. /*!
  234. * \brief
  235. * Check if the \c haystack contains the \c needle
  236. * \param haystack The stream in witch we search [The input buffer]
  237. * \param needle What we search [The record's token]
  238. * \return True on success, false otherwise
  239. */
  240. static constexpr auto contains = [](const string_view haystack, const string_view needle) -> bool {
  241. return (haystack.find(needle) != string_view::npos);
  242. };
  243. //! Always false predicate
  244. static constexpr auto always_true = [](const string_view s1, const string_view s2) -> bool {
  245. (void)s1; (void)s2;
  246. return true;
  247. };
  248. //! Always false predicate
  249. static constexpr auto always_false = [](const string_view s1, const string_view s2) -> bool {
  250. (void)s1; (void)s2;
  251. return false;
  252. };
  253. //! Empty predicate or handler
  254. static constexpr auto nil = nullptr;
  255. //! @}
  256. //! \name Object lifetime
  257. //!@{
  258. protected:
  259. ~sequencer () = default; //!< \brief Allow destructor from derived only
  260. constexpr sequencer () noexcept = default; //!< \brief A default constructor from derived only
  261. sequencer(const sequencer&) = delete; //!< No copies
  262. sequencer& operator= (const sequencer&) = delete; //!< No copy assignments
  263. //!@}
  264. //! \name Sequencer interface requirements for implementer
  265. //! @{
  266. private:
  267. size_t get_ (Data_t* data) { return impl().get (data); }
  268. size_t contents_ (Data_t* data) { return impl().contents(data); }
  269. size_t put_ (const Data_t* data, size_t n) { return impl().put (data, n); }
  270. clock_t clock_ () { return impl().clock(); }
  271. //! @}
  272. //! \name Private functionality
  273. //! @{
  274. private:
  275. /*!
  276. * Check if there is a handler and call it
  277. * \param handler The handler to check
  278. * \param buffer String view to buffer to pass to handler
  279. * \return True if handler is called
  280. */
  281. constexpr bool handle_ (handler_ft handler, const string_view buffer = string_view{}) {
  282. if (handler != nullptr) {
  283. handler (buffer.begin(), buffer.size());
  284. return true;
  285. }
  286. return false;
  287. }
  288. /*!
  289. * \brief
  290. * Return the new sequencer's step value and the sequencer's loop status as pair.
  291. *
  292. * \param script Reference to entire script.
  293. * \param step The current step
  294. * \return new step - status pair
  295. */
  296. template <size_t Steps>
  297. constexpr std::pair<size_t, seq_status_t> action_ (const script_t<Steps>& script, size_t step) {
  298. control_t skip_while{};
  299. size_t s;
  300. switch (script[step].action.type) {
  301. default:
  302. case action_t::NO: return std::make_pair(step, seq_status_t::CONTINUE);
  303. case action_t::NEXT:
  304. switch (script[step].control) {
  305. case control_t::NOP: return std::make_pair(++step, seq_status_t::CONTINUE);
  306. case control_t::SEND: return std::make_pair(++step, seq_status_t::CONTINUE);
  307. case control_t::EXPECT:
  308. case control_t::OR_EXPECT: skip_while = control_t::OR_EXPECT; break;
  309. case control_t::DETECT:
  310. case control_t::OR_DETECT: skip_while = control_t::OR_DETECT; break;
  311. }
  312. s = step;
  313. while (script[++s].control == skip_while)
  314. ;
  315. return std::make_pair(s, seq_status_t::CONTINUE);
  316. case action_t::GOTO: return std::make_pair(script[step].action.value, seq_status_t::CONTINUE);
  317. case action_t::EXIT: return std::make_pair(script[step].action.value, seq_status_t::EXIT);
  318. }
  319. }
  320. //! @}
  321. public:
  322. //! \return The buffer size of the sequencer
  323. constexpr size_t size() const { return N; }
  324. /*!
  325. * \brief
  326. * A static functionality to provide access to sequencer's inner matching mechanism.
  327. * Checks the \c buffer against \c handle and calls its action if needed.
  328. *
  329. * \param buffer The buffer to check (1st parameter to match)
  330. * \param token String view to check against buffer (2nd parameter to match)
  331. * \param handler Function pointer to match predicate to use
  332. * \param handle Reference to handle to call on match
  333. *
  334. * \return True on match, false otherwise
  335. */
  336. constexpr bool check_handle (const string_view buffer, const string_view token, match_ft match, handler_ft handle) {
  337. if (match != nullptr && match(buffer, token))
  338. return handle_ (handle, buffer);
  339. return false;
  340. }
  341. /*!
  342. * \brief
  343. * Run the script array
  344. *
  345. * The main sequencer functionality. It starts with the first entry of the array.
  346. *
  347. * - If the record is \c NOP it executes the action after the timeout.
  348. * \c NOP uses {\c action_t, \c timeout}.
  349. * - If the record is \c SEND passes the token to handler (if any), then to put_() and executes the action after that.
  350. * \c SEND uses {\c token, \c handler, \c action_t}
  351. * - If the record is \c EXCEPT it continuously try to receive data using \see get_()
  352. * * If no data until timeout, exit with failure
  353. * * On data reception for this record AND for each OR_EXPECT that follows, calls the match predicate
  354. * by passing the received data and token.
  355. * On predicate match
  356. * - Calls the handler if there is one
  357. * - Executes the action. No farther EXPECT, OR_EXPECT, ... checks are made.
  358. * - If the record is \c DETECT it continuously try to receive data using \see contents_()
  359. * * If no data until timeout, exit with failure
  360. * * On data reception for this record AND for each OR_DETECT that follows, calls the match predicate
  361. * by passing the received data and token.
  362. * On predicate match
  363. * - Calls the handler if there is one
  364. * - Executes the action. No farther DETECT, OR_DETECT, ... checks are made.
  365. *
  366. * \tparam Steps The number of records of the script
  367. *
  368. * \param script Reference to script to run
  369. * \return The status of entire operation as described above
  370. * \arg 0 Success
  371. * \arg (size_t)-1 Failure
  372. * \arg other Arbitrary return status
  373. */
  374. template <size_t Steps>
  375. size_t run (const script_t<Steps>& script) {
  376. Data_t buffer[N];
  377. size_t resp_size;
  378. size_t step =0, p_step =0;
  379. clock_t mark = clock_();
  380. seq_status_t status{seq_status_t::CONTINUE}; do {
  381. const record_t& record = script[step]; // get reference ot current line
  382. if (step != p_step) { // renew time marker in each step
  383. p_step = step;
  384. mark = clock_();
  385. }
  386. switch (record.control) {
  387. default:
  388. case control_t::NOP:
  389. if ((clock_() - mark) >= record.timeout)
  390. std::tie(step, status) = action_ (script, step);
  391. break;
  392. case control_t::SEND:
  393. if (record.handler != nullptr)
  394. record.handler(record.token.data(), record.token.size());
  395. if (put_(record.token.data(), record.token.size()) != record.token.size())
  396. return exit_error.value;
  397. std::tie(step, status) = action_ (script, step);
  398. break;
  399. case control_t::EXPECT:
  400. case control_t::OR_EXPECT:
  401. resp_size = get_(buffer);
  402. if (resp_size) {
  403. size_t s = step ; do{
  404. if (script[s].match != nullptr && script[s].match({buffer, resp_size}, script[s].token)) {
  405. handle_ (script[s].handler, {buffer, resp_size});
  406. std::tie(step, status) = action_ (script, s);
  407. break;
  408. }
  409. } while (script[++s].control == control_t::OR_EXPECT);
  410. }
  411. if (record.timeout && (clock_() - mark) >= record.timeout)
  412. return exit_error.value;
  413. break;
  414. case control_t::DETECT:
  415. case control_t::OR_DETECT:
  416. resp_size = contents_(buffer);
  417. if (resp_size) {
  418. size_t s = step ; do {
  419. if (script[s].match != nullptr && script[s].match({buffer, resp_size}, script[s].token)) {
  420. handle_ (script[s].handler, {buffer, resp_size});
  421. std::tie(step, status) = action_ (script, s);
  422. break;
  423. }
  424. } while (script[++s].control == control_t::OR_DETECT);
  425. }
  426. if (record.timeout && (clock_() - mark) >= record.timeout)
  427. return exit_error.value;
  428. break;
  429. } // switch (record.control)
  430. } while ( status == seq_status_t::CONTINUE);
  431. return step; // step here is set by action_ as the return status
  432. }
  433. };
  434. }
  435. #endif /* TBX_UTILS_SEQUENCER_H_ */