3

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?

sehe
  • 374,641
  • 47
  • 450
  • 633
colossus47
  • 99
  • 9
  • 2
    What do you mean by "hex values"? Are you sure the line `uint8_t hexValue = ...;` is correct? – MikeCAT Apr 14 '16 at 15:18
  • @MikeCAT I was looking to pass hex values like {0,1,...E,F} as binary data. So yeah it looks like my conversion was incorrect. However the person below who provided the a working conversion and way to write it to the serial port. – colossus47 Apr 14 '16 at 16:27
  • A byte (8 bits) is made of two hex digits, not one. Are you sure? – MikeCAT Apr 15 '16 at 00:14

2 Answers2

2

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.

Community
  • 1
  • 1
sehe
  • 374,641
  • 47
  • 450
  • 633
0

you seem to forgot the io_service for instanciate the serial_port. The serial_port default constructor has 2 parameters io_service and the port name

Loki
  • 43
  • 1
  • 6