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.
 
 
 

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