Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Boost ASIO Serial Write Hex values

I am communicating with a device via a serial port using ubuntu. All the messages need to be hex values. I have tested the communication setup using termite in a Windows environment and I get the responses I am expecting. I cannot get any responses when using Boost:asio though.

Here is how I am setting up my serial port:

boost::asio::serial_port serialPort;
    serialPort.open(portNumber);
    serialPort.set_option(boost::asio::serial_port_base::baud_rate(baudRate));
    serialPort.set_option(boost::asio::serial_port_base::character_size(8));
    serialPort.set_option(boost::asio::serial_port_base::stop_bits(boost::asio::serial_port_base::stop_bits::one));
    serialPort.set_option(boost::asio::serial_port_base::parity(boost::asio::serial_port_base::parity::none));
    serialPort.set_option(boost::asio::serial_port_base::flow_control(boost::asio::serial_port_base::flow_control::none));

  uint8_t hexValue = message.at(i) >= 'A' ? (message.at(i) - 'A' + 10) : message.at(i) - '0';
  serialPort.write_some(boost::asio::buffer(&hexValue, sizeof(uint8_t)));

So is there something I need to setup in ASIO to make it send correctly?

like image 965
colossus47 Avatar asked Dec 21 '25 23:12

colossus47


1 Answers

It looks like really you want to send the binary data that corresponds to the hex-encoded text you have in message.

There are many ways to skin that cat. I'd personally start with decoding the whole message. This will always reduce the message from the hex-encoded size. So you can do this inplace, if you want.

A simple take from an older answer:

std::string hex2bin(std::string const& s) {
    assert(s.length() % 2 == 0);

    std::string sOut;
    sOut.reserve(s.length()/2);

    std::string extract;
    for (std::string::const_iterator pos = s.begin(); pos<s.end(); pos += 2)
    {
        extract.assign(pos, pos+2);
        sOut.push_back(std::stoi(extract, nullptr, 16));
    }
    return sOut;
}

Now you simply send the returned string to the serial port:

std::string binary_msg = hex2bin(message);
serialPort.write_some(boost::asio::buffer(binary_msg));

Also look at the global http://www.boost.org/doc/libs/1_60_0/doc/html/boost_asio/reference/write.html to write the whole message in one composed operation.

like image 134
sehe Avatar answered Dec 23 '25 14:12

sehe