HDLCd-Tools
LineReader.h
Go to the documentation of this file.
1 
22 #ifndef LINE_READER_H
23 #define LINE_READER_H
24 
25 #include <iostream>
26 #include <vector>
27 #include <boost/asio.hpp>
28 
29 class LineReader {
30 public:
31  // CTOR
32  LineReader(boost::asio::io_service& io_service): m_InputStream(io_service, ::dup(STDIN_FILENO)), m_InputBuffer(4096), m_InputReader(&m_InputBuffer) {
33  // Read single lines of input from STDIN
34  do_read();
35  }
36 
37  void SetOnInputLineCallback(std::function<void(const std::vector<unsigned char>)> a_OnInputLineCallback) {
38  m_OnInputLineCallback = a_OnInputLineCallback;
39  }
40 
41 private:
42  // Helpers
43  void do_read() {
44  boost::asio::async_read_until(m_InputStream, m_InputBuffer, '\n',[this](boost::system::error_code a_ErrorCode, size_t) {
45  if (!a_ErrorCode) {
46  // Obtain one line from the input buffer, parse the provided hex dump, and create a StreamFrame from it
47  char l_InputLineBuffer[1000];
48  m_InputReader.getline(l_InputLineBuffer,1000);
49  std::istringstream l_InputStream(l_InputLineBuffer);
50  l_InputStream >> std::hex;
51  std::vector<unsigned char> l_Buffer;
52  l_Buffer.reserve(65536);
53  l_Buffer.insert(l_Buffer.end(),std::istream_iterator<unsigned int>(l_InputStream), {});
54  if (m_OnInputLineCallback) {
55  m_OnInputLineCallback(std::move(l_Buffer));
56  } // if
57 
58  // Read the next line
59  do_read();
60  } else {
61  // Some error occured
62  m_InputStream.close();
63  } // else
64  });
65  }
66 
67  // Members
68  std::function<void(const std::vector<unsigned char>)> m_OnInputLineCallback;
69  boost::asio::posix::stream_descriptor m_InputStream;
70  boost::asio::streambuf m_InputBuffer;
71  std::istream m_InputReader;
72 };
73 
74 #endif // LINE_READER_H
LineReader(boost::asio::io_service &io_service)
Definition: LineReader.h:32
void SetOnInputLineCallback(std::function< void(const std::vector< unsigned char >)> a_OnInputLineCallback)
Definition: LineReader.h:37