23 #include <boost/algorithm/string.hpp> 24 #include <boost/crc.hpp> 25 #include <netinet/in.h> 27 #include "goby/util/base_convert.h" 28 #include "goby/util/binary.h" 29 #include "rudics_packet.h" 31 void goby::acomms::serialize_rudics_packet(std::string bytes, std::string* rudics_pkt,
32 const std::string& reserved,
bool include_crc)
37 boost::crc_32_type crc;
38 crc.process_bytes(bytes.data(), bytes.length());
39 bytes += uint32_to_byte_string(crc.checksum());
43 const int reduced_base = 256 - reserved.size();
45 goby::util::base_convert(bytes, rudics_pkt, 256, reduced_base);
48 for (
int i = 0, n = reserved.size(); i < n; ++i)
50 std::replace(rudics_pkt->begin(), rudics_pkt->end(), reserved[i],
51 static_cast<char>(reduced_base + i));
58 void goby::acomms::parse_rudics_packet(std::string* bytes, std::string rudics_pkt,
59 const std::string& reserved,
bool include_crc)
61 const unsigned CR_SIZE = 1;
62 if (rudics_pkt.size() < CR_SIZE)
63 throw(RudicsPacketException(
"Packet too short for <CR>"));
66 rudics_pkt = rudics_pkt.substr(0, rudics_pkt.size() - 1);
68 const int reduced_base = 256 - reserved.size();
72 std::remove_if(rudics_pkt.begin(), rudics_pkt.end(), boost::is_any_of(reserved)),
76 for (
int i = 0, n = reserved.size(); i < n; ++i)
78 std::replace(rudics_pkt.begin(), rudics_pkt.end(),
static_cast<char>(reduced_base + i),
83 goby::util::base_convert(rudics_pkt, bytes, reduced_base, 256);
88 const unsigned CRC_BYTE_SIZE = 4;
89 if (bytes->size() < CRC_BYTE_SIZE)
90 throw(RudicsPacketException(
"Packet too short for CRC32"));
92 std::string crc_str = bytes->substr(bytes->size() - 4, 4);
93 uint32_t given_crc = byte_string_to_uint32(crc_str);
94 *bytes = bytes->substr(0, bytes->size() - 4);
96 boost::crc_32_type crc;
97 crc.process_bytes(bytes->data(), bytes->length());
98 uint32_t computed_crc = crc.checksum();
100 if (given_crc != computed_crc)
101 throw(RudicsPacketException(
"Bad CRC32"));
105 std::string goby::acomms::uint32_to_byte_string(uint32_t i)
112 return std::string(u.c, 4);
115 uint32_t goby::acomms::byte_string_to_uint32(std::string s)
121 memcpy(u.c, s.c_str(), 4);