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.
 
 
 

525 lines
24 KiB

  1. /*!
  2. * \file com/sequencer.h
  3. * \brief
  4. * A script based automation tool for send/receive communications
  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_COM_SEQUENCER_H_
  31. #define TBX_COM_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. OTHERWISE //!< An "else" path if the EXPECT[, OR_EXPECT[, OR_EXPECT ... ]] block timesout.
  113. //! \note
  114. //! The \c DETECT extra incoming channel serve the purpose of sneak into receive
  115. //! buffer and check for data without getting them. This is useful when the receive driver
  116. //! is buffered with a delimiter and we seek for data that don't follow the delimiter pattern.
  117. //!
  118. //! For example:
  119. //! A modem sends responses with '\n' termination but for some "special" command it opens a cursor
  120. //! lets say ">$ " without '\n' at the end.
  121. };
  122. //! \enum action_t
  123. //! \brief
  124. //! Possible response actions for the sequencer. This is the
  125. //! equivalent of changing the program counter of the sequencer
  126. //! and is composed by a type and a value.
  127. //!
  128. struct action_t {
  129. enum {
  130. NO =0, //!< Do not change sequencer's step
  131. NEXT, //!< Go to next sequencer step. In case of EXPECT/DETECT block of records
  132. //!< skip the entire block of EXPECT[, OR_EXPECT[, OR_EXPECT ...]] and go
  133. //!< to the next (non OR_*) control record.
  134. GOTO, //!< Manually sets the step counter to the number of the \c step member.
  135. EXIT, //!< Instruct for an exit returning the action.value as status
  136. } type;
  137. size_t value; //!< Used by \c GOTO to indicate the next sequencer's step.
  138. };
  139. //! A no_action action_t
  140. static constexpr action_t no_action = {action_t::NO, 0};
  141. //! A next action_t
  142. static constexpr action_t next = {action_t::NEXT, 0};
  143. //! A goto action_t template
  144. template <size_t GOTO>
  145. static constexpr action_t go_to = {action_t::GOTO, static_cast<size_t>(GOTO)};
  146. //! An exit ok action_t
  147. static constexpr action_t exit_ok = {action_t::EXIT, 0};
  148. //! An exit error action_t
  149. static constexpr action_t exit_error = {action_t::EXIT, static_cast<size_t>(-1)};
  150. //! A generic exit action_t template
  151. template <size_t Status>
  152. static constexpr action_t exit = {action_t::EXIT, static_cast<size_t>(Status)};
  153. /*!
  154. * Match binary predicate function pointer type.
  155. * Expects two string views and return a boolean.
  156. * It is used by EXPECT/DETECT blocks to trigger their {handler, action} pair.
  157. */
  158. using match_ft = bool (*) (const string_view haystack, const string_view needle);
  159. /*!
  160. * Send/Receive handler function pointer type.
  161. * Expects a pointer to buffer and a size and returns status.
  162. * It is used on predicate match on EXPECT/DETECT blocks, or as data wrapper on SEND blocks.
  163. */
  164. using handler_ft = void (*) (const Data_t*, size_t);
  165. /*!
  166. * \struct record_t
  167. * \brief
  168. * Describes the sequencer's script record entry (line).
  169. */
  170. struct record_t {
  171. control_t control; //!< The control type of the entry
  172. string_view token; //!< String view to token data. [MUST BE null terminated].
  173. //!< This is passed as 2nd argument to match predicate on EXPECT/DETECT, or as
  174. //! {data, size} pair to SEND handler and put_().
  175. //!< If unused set it to ""
  176. match_ft match; //!< Match predicate to used in EXPECT/DETECT blocks
  177. //!< If unused set it to nullptr
  178. handler_ft handler; //!< The handler to called if the match is successful, or before put_()
  179. //!< If unused set it to nullptr
  180. action_t action; //!< Indicates the step manipulation if the match is successful or after NOP and put_()
  181. clock_t timeout; //!< Timeout in CPU time
  182. };
  183. /*!
  184. * \struct script_t
  185. * \brief
  186. * Describes the sequencer's script.
  187. *
  188. * The user can create arrays as the example bellow to act as a script.
  189. * \code
  190. * Seq s;
  191. * const Seq::script_t<4> script = {{
  192. * {Seq::control_t::NOP, "", Seq::nil, Seq::nil, {Seq::action_t::GOTO, 1}, 1000},
  193. *
  194. * {Seq::control_t::SEND, "ATE0\r\n", Seq::nil, Seq::nil, {Seq::action_t::NEXT, 0}, 0},
  195. * {Seq::control_t::EXPECT, "OK\r\n", Seq::ends_with, Seq::nil, {Seq::action_t::EXIT_OK, 0}, 1000},
  196. * {Seq::control_t::OR_EXPECT, "ERROR", Seq::contains, Seq::nil, {Seq::action_t::EXIT_ERROR, 0}, 0}
  197. * }};
  198. * s.run(script);
  199. * \endcode
  200. */
  201. template <size_t Nrecords>
  202. using script_t = std::array<record_t, Nrecords>;
  203. /*!
  204. * \brief
  205. * Check if the \c stream1 is equal to \c stream2
  206. * \param stream1 The stream in witch we search [The input buffer]
  207. * \param stream2 What we search [The record's token]
  208. * \return True on success, false otherwise
  209. */
  210. static constexpr auto equals = [](const string_view stream1, const string_view stream2) noexcept -> bool {
  211. return (stream1 == stream2);
  212. };
  213. /*!
  214. * \brief
  215. * Check if the \c stream starts with the \c prefix
  216. * \param stream The stream in witch we search [The input buffer]
  217. * \param prefix What we search [The record's token]
  218. * \return True on success, false otherwise
  219. */
  220. static constexpr auto starts_with = [](const string_view stream, const string_view prefix) noexcept -> bool {
  221. return (stream.rfind(prefix, 0) != string_view::npos);
  222. };
  223. /*!
  224. * \brief
  225. * Check if the \c stream ends with the \c postfix
  226. * \param stream The stream in witch we search [The input buffer]
  227. * \param postfix What we search [The record's token]
  228. * \return True on success, false otherwise
  229. */
  230. static constexpr auto ends_with = [](const string_view stream, const string_view postfix) -> bool {
  231. if (stream.size() < postfix.size())
  232. return false;
  233. return (
  234. stream.compare(
  235. stream.size() - postfix.size(),
  236. postfix.size(),
  237. postfix) == 0
  238. );
  239. };
  240. /*!
  241. * \brief
  242. * Check if the \c haystack contains the \c needle
  243. * \param haystack The stream in witch we search [The input buffer]
  244. * \param needle What we search [The record's token]
  245. * \return True on success, false otherwise
  246. */
  247. static constexpr auto contains = [](const string_view haystack, const string_view needle) noexcept -> bool {
  248. return (haystack.find(needle) != string_view::npos);
  249. };
  250. //! Always false predicate
  251. static constexpr auto always_true = [](const string_view s1, const string_view s2) noexcept -> bool {
  252. (void)s1; (void)s2;
  253. return true;
  254. };
  255. //! Always false predicate
  256. static constexpr auto always_false = [](const string_view s1, const string_view s2) noexcept -> bool {
  257. (void)s1; (void)s2;
  258. return false;
  259. };
  260. //! Empty predicate or handler
  261. static constexpr auto nil = nullptr;
  262. //! @}
  263. //! \name Object lifetime
  264. //!@{
  265. protected:
  266. ~sequencer () = default; //!< \brief Allow destructor from derived only
  267. constexpr sequencer () noexcept = default; //!< \brief A default constructor from derived only
  268. sequencer(const sequencer&) = delete; //!< No copies
  269. sequencer& operator= (const sequencer&) = delete; //!< No copy assignments
  270. //!@}
  271. //! \name Sequencer interface requirements for implementer
  272. //! @{
  273. private:
  274. size_t get_ (Data_t* data) { return impl().get (data); }
  275. size_t contents_ (Data_t* data) { return impl().contents(data); }
  276. size_t put_ (const Data_t* data, size_t n) { return impl().put (data, n); }
  277. clock_t clock_ () noexcept { return impl().clock(); }
  278. //! @}
  279. //! \name Private functionality
  280. //! @{
  281. private:
  282. /*!
  283. * Check if there is a handler and call it
  284. * \param handler The handler to check
  285. * \param buffer String view to buffer to pass to handler
  286. * \return True if handler is called
  287. */
  288. constexpr bool handle_ (handler_ft handler, const string_view buffer = string_view{}) {
  289. if (handler != nullptr) {
  290. handler (buffer.begin(), buffer.size());
  291. return true;
  292. }
  293. return false;
  294. }
  295. /*!
  296. * \brief
  297. * Return the new sequencer's step value and the sequencer's loop status as pair.
  298. *
  299. * \param script Reference to entire script.
  300. * \param step The current step
  301. * \return new step - status pair
  302. */
  303. template <size_t Steps>
  304. constexpr std::pair<size_t, seq_status_t> action_ (const script_t<Steps>& script, size_t step) {
  305. control_t skip_while{};
  306. size_t s;
  307. switch (script[step].action.type) {
  308. default:
  309. case action_t::NO: return std::make_pair(step, seq_status_t::CONTINUE);
  310. case action_t::NEXT:
  311. switch (script[step].control) {
  312. case control_t::NOP: return std::make_pair(++step, seq_status_t::CONTINUE);
  313. case control_t::SEND: return std::make_pair(++step, seq_status_t::CONTINUE);
  314. case control_t::EXPECT:
  315. case control_t::OR_EXPECT: skip_while = control_t::OR_EXPECT; break;
  316. case control_t::DETECT:
  317. case control_t::OR_DETECT: skip_while = control_t::OR_DETECT; break;
  318. case control_t::OTHERWISE: skip_while = control_t::OTHERWISE; break;
  319. }
  320. s = step;
  321. while (script[++s].control == skip_while)
  322. ;
  323. return std::make_pair(s, seq_status_t::CONTINUE);
  324. case action_t::GOTO: return std::make_pair(script[step].action.value, seq_status_t::CONTINUE);
  325. case action_t::EXIT: return std::make_pair(script[step].action.value, seq_status_t::EXIT);
  326. }
  327. }
  328. template <size_t Steps>
  329. size_t expect_end (const script_t<Steps>& script, size_t step) {
  330. while ((++step < Steps) && (script[step].control == control_t::OR_EXPECT)) ;
  331. return step;
  332. }
  333. template <size_t Steps>
  334. size_t detect_end (const script_t<Steps>& script, size_t step) {
  335. while ((++step < Steps) && (script[step].control == control_t::OR_DETECT)) ;
  336. return step;
  337. }
  338. //! @}
  339. public:
  340. //! \return The buffer size of the sequencer
  341. constexpr size_t size() const noexcept { return N; }
  342. /*!
  343. * \brief
  344. * A static functionality to provide access to sequencer's inner matching mechanism.
  345. * Checks the \c buffer against \c handle and calls its action if needed.
  346. *
  347. * \param buffer The buffer to check (1st parameter to match)
  348. * \param token String view to check against buffer (2nd parameter to match)
  349. * \param handler Function pointer to match predicate to use
  350. * \param handle Reference to handle to call on match
  351. *
  352. * \return True on match, false otherwise
  353. */
  354. constexpr bool check_handle (const string_view buffer, const string_view token, match_ft match, handler_ft handle) {
  355. if (match != nullptr && match(buffer, token))
  356. return handle_ (handle, buffer);
  357. return false;
  358. }
  359. /*!
  360. * \brief
  361. * Run the script array
  362. *
  363. * The main sequencer functionality. It starts with the first entry of the array.
  364. *
  365. * - If the record is \c NOP it executes the action after the timeout.
  366. * \c NOP uses {\c action_t, \c timeout}.
  367. * - If the record is \c SEND passes the token to handler (if any), then to put_() and executes the action after that.
  368. * \c SEND uses {\c token, \c handler, \c action_t}
  369. * - If the record is \c EXCEPT it continuously try to receive data using \see get_()
  370. * * If no data until timeout, exit with failure
  371. * * On data reception for this record AND for each OR_EXPECT that follows, calls the match predicate
  372. * by passing the received data and token.
  373. * On predicate match
  374. * - Calls the handler if there is one
  375. * - Executes the action. No farther EXPECT, OR_EXPECT, ... checks are made.
  376. * - If the record is \c DETECT it continuously try to receive data using \see contents_()
  377. * * If no data until timeout, exit with failure
  378. * * On data reception for this record AND for each OR_DETECT that follows, calls the match predicate
  379. * by passing the received data and token.
  380. * On predicate match
  381. * - Calls the handler if there is one
  382. * - Executes the action. No farther DETECT, OR_DETECT, ... checks are made.
  383. *
  384. * \tparam Steps The number of records of the script
  385. *
  386. * \param script Reference to script to run
  387. * \return The status of entire operation as described above
  388. * \arg 0 Success
  389. * \arg (size_t)-1 Failure
  390. * \arg other Arbitrary return status
  391. */
  392. template <size_t Steps>
  393. size_t run (const script_t<Steps>& script) {
  394. Data_t buffer[N];
  395. size_t resp_size;
  396. size_t step =0, p_step =0;
  397. clock_t mark = clock_();
  398. seq_status_t status{seq_status_t::CONTINUE}; do {
  399. if (step >= Steps)
  400. return exit_error.value;
  401. const record_t& record = script[step]; // get reference ot current line
  402. if (step != p_step) { // renew time marker in each step
  403. p_step = step;
  404. mark = clock_();
  405. }
  406. switch (record.control) {
  407. default:
  408. case control_t::NOP:
  409. if ((clock_() - mark) >= record.timeout)
  410. std::tie(step, status) = action_ (script, step);
  411. break;
  412. case control_t::SEND:
  413. if (record.handler != nullptr)
  414. record.handler(record.token.data(), record.token.size());
  415. if (put_(record.token.data(), record.token.size()) != record.token.size())
  416. return exit_error.value;
  417. std::tie(step, status) = action_ (script, step);
  418. break;
  419. case control_t::EXPECT:
  420. case control_t::OR_EXPECT:
  421. resp_size = get_(buffer);
  422. if (resp_size) {
  423. for (size_t s = step ; s < expect_end(script, step) ; ++s) {
  424. if (script[s].match != nullptr && script[s].match({buffer, resp_size}, script[s].token)) {
  425. handle_ (script[s].handler, {buffer, resp_size});
  426. std::tie(step, status) = action_ (script, s);
  427. break;
  428. }
  429. }
  430. }
  431. if (record.timeout && (clock_() - mark) >= record.timeout) {
  432. size_t s = expect_end(script, step);
  433. if ((s < Steps) && (script[s].control == control_t::OTHERWISE)) {
  434. handle_ (script[s].handler, {buffer, resp_size});
  435. std::tie(step, status) = action_ (script, s);
  436. } else {
  437. return exit_error.value;
  438. }
  439. }
  440. break;
  441. case control_t::DETECT:
  442. case control_t::OR_DETECT:
  443. resp_size = contents_(buffer);
  444. if (resp_size) {
  445. for (size_t s = step ; s < detect_end(script, step) ; ++s) {
  446. if (script[s].match != nullptr && script[s].match({buffer, resp_size}, script[s].token)) {
  447. handle_ (script[s].handler, {buffer, resp_size});
  448. std::tie(step, status) = action_ (script, s);
  449. break;
  450. }
  451. }
  452. }
  453. if (record.timeout && (clock_() - mark) >= record.timeout) {
  454. size_t s = detect_end(script, step);
  455. if ((s < Steps) && (script[s].control == control_t::OTHERWISE)) {
  456. handle_ (script[s].handler, {buffer, resp_size});
  457. std::tie(step, status) = action_ (script, s);
  458. } else {
  459. return exit_error.value;
  460. }
  461. }
  462. break;
  463. case control_t::OTHERWISE:
  464. handle_ (script[step].handler, {buffer, resp_size});
  465. std::tie(step, status) = action_ (script, step);
  466. break;
  467. } // switch (record.control)
  468. } while ( status == seq_status_t::CONTINUE);
  469. return step; // step here is set by action_ as the return status
  470. }
  471. };
  472. }
  473. #endif /* TBX_COM_SEQUENCER_H_ */