Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

BroadcastTime string to rate quarters fix #716

Merged
merged 2 commits into from
Jul 8, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 9 additions & 1 deletion src/openlcb/BroadcastTimeDefs.cxx
Original file line number Diff line number Diff line change
Expand Up @@ -139,7 +139,15 @@ bool BroadcastTimeDefs::string_to_time(
//
int16_t BroadcastTimeDefs::string_to_rate_quarters(const std::string &srate)
{
float rate = std::stof(srate);
const char *rate_c_str = srate.c_str();
char *end;
float rate = strtof(rate_c_str, &end);

if (end == rate_c_str)
{
// None of the string processed.
return 0;
}
if (rate < -512)
{
// set to minimum valid rate
Expand Down
46 changes: 46 additions & 0 deletions src/openlcb/BroadcastTimeDefs.cxxtest
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
#include "utils/async_if_test_helper.hxx"

#include "openlcb/BroadcastTimeDefs.hxx"

#if 0
#define PRINT_ALL_PACKETS() print_all_packets()
#else
#define PRINT_ALL_PACKETS()
#endif

namespace openlcb
{

TEST(BroadcastTimeDefs, string_to_rate_quarters)
{
int16_t rate;

rate = BroadcastTimeDefs::string_to_rate_quarters("Freddy");
EXPECT_EQ(0, rate);

rate = BroadcastTimeDefs::string_to_rate_quarters("2000");
EXPECT_EQ(2047, rate);

rate = BroadcastTimeDefs::string_to_rate_quarters("-2000");
EXPECT_EQ(-2048, rate);

rate = BroadcastTimeDefs::string_to_rate_quarters("");
EXPECT_EQ(0, rate);

rate = BroadcastTimeDefs::string_to_rate_quarters("-");
EXPECT_EQ(0, rate);

rate = BroadcastTimeDefs::string_to_rate_quarters(" ");
EXPECT_EQ(0, rate);

rate = BroadcastTimeDefs::string_to_rate_quarters("511,75");
EXPECT_EQ(2044, rate);

rate = BroadcastTimeDefs::string_to_rate_quarters("1.75");
EXPECT_EQ(7, rate);

rate = BroadcastTimeDefs::string_to_rate_quarters("-1.75");
EXPECT_EQ(-7, rate);
}

} // namespace openlcb
4 changes: 3 additions & 1 deletion src/openlcb/BroadcastTimeDefs.hxx
Original file line number Diff line number Diff line change
Expand Up @@ -362,7 +362,9 @@ struct BroadcastTimeDefs

/// Convert a string (float) to rate quarters.
/// @param srate rate in the form of a string float
/// @return rate in the form of an int16_t in rate quarters
/// @return Rate in the form of an int16_t in rate quarters. If a
/// conversion error occurs, then the returned value will be 0,
/// which is at least a valid rate.
static int16_t string_to_rate_quarters(const std::string &srate);
};

Expand Down