message class

// Structure of the messages to be ket track.
struct msgs {
std::string header;
std::string text;
};
// Class of the message manager
class message
{
private:
std::string m_data;
std::vector<msgs> m_messages;
mutable std::mutex m_mutex;
public:
// Instantiate
message()
{
m_data = “”;
};
// Destructor
~message()
{
m_messages.clear();
};
/** Resolve last message */
void solve_last(std::string l_data)
{
m_data += l_data;
int soh, stx, etx, eot;
soh = m_data.rfind(‘\x01’);
stx = m_data.rfind(‘\x02’);
etx = m_data.rfind(‘\x03’);
eot = m_data.rfind(‘\x04’);

if (soh > -1 && stx > -1 && etx > -1 && eot > -1)
{
if (eot > etx && etx > stx && stx > soh) { // stx = soh + 2 && eot = etx + 1
msgs l_msg;
l_msg.header = m_data.substr(soh + 1, (stx – soh) – 1); // Get Header
l_msg.text = m_data.substr(stx + 1, (etx – stx) – 1); // Get Text

std::lock_guard<std::mutex> l_guard(m_mutex);
m_messages.push_back(l_msg);
}
if (m_data.size() > (size_t)(eot + 1))
m_data = m_data.substr(eot + 1);
else
m_data = “”;
}
}

/** Resolve all messages in the incoming string */
void solve_all(std::string l_data)
{
m_data += l_data;
int soh, stx, etx, eot;
soh = m_data.find(‘\x01’);
stx = m_data.find(‘\x02’);
etx = m_data.find(‘\x03’);
eot = m_data.find(‘\x04’);

while (soh > -1 && stx > -1 && etx > -1 && eot > -1)
{
if (eot > etx && etx > stx && stx > soh) { // stx = soh + 2 && eot = etx + 1
msgs l_msg;
l_msg.header = m_data.substr(soh + 1, (stx – soh) – 1); // Get Header
l_msg.text = m_data.substr(stx + 1, (etx – stx) – 1); // Get Text

std::lock_guard<std::mutex> l_guard(m_mutex);
m_messages.push_back(l_msg);
}

if (m_data.size() > (size_t)(eot + 1))
m_data = m_data.substr(eot + 1);
else
m_data = “”;

soh = m_data.find(‘\x01’);
stx = m_data.find(‘\x02’);
etx = m_data.find(‘\x03’);
eot = m_data.find(‘\x04’);
}
};
// print to consol the values in the m_messages
friend std::ostream& operator<<(std::ostream& os, const message& l_msg)
{
std::lock_guard<std::mutex> l_guard(l_msg.m_mutex);
for (auto x : l_msg.m_messages)
os << x.header << “\t” << x.text << std::endl;
return os;
};
// retuen the list of messages
std::vector<msgs> get_messages(void)
{
std::lock_guard<std::mutex> l_guard(m_mutex);
std::vector<msgs> l_messages = m_messages;
m_messages.clear();
return l_messages;
};
};