Skip to content

Commit 6ddfe66

Browse files
rtu layer: fix parsing of settings string
Throw exceptions on error instead of silently changing values. Check settings string for given stop bit value. Up until now, the stop bits value was hard coded to be 2 if the parity mode was set to none or 1 if the parity mode was set to even or odd. So a setting of "115200E1" would result in a stop bit value of 1. But "115200E2" would result also in a stop bit value of 1. And "115200N1" would result in a stop bit value of 2. This is not a restriction of libmodbus. The library supports all these modes just fine. In fact they are using 115200N1 in the documentation for modbus_new_rtu(). Rather this is a bug in the string parsing that libmodbuspp introduces in its constructor. libmodbus has no string parsing in modbus_new_rtu() and takes in the arguments as parameters directly. Fixes: b0f3dc4
1 parent c76baa9 commit 6ddfe66

File tree

1 file changed

+15
-9
lines changed

1 file changed

+15
-9
lines changed

src/rtulayer.cpp

Lines changed: 15 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -234,14 +234,12 @@ namespace Modbus {
234234
// ---------------------------------------------------------------------------
235235
// static
236236
int RtuLayer::baud (const std::string & settings) {
237-
int b;
238237
try {
239-
b = std::stoi (settings);
238+
return std::stoi (settings);
240239
}
241240
catch (...) {
242-
b = 19200;
241+
throw std::invalid_argument ("RtuLayer settings\"" + settings + "\" has an invalid baud rate setting.");
243242
}
244-
return b;
245243
}
246244

247245
// ---------------------------------------------------------------------------
@@ -256,18 +254,26 @@ namespace Modbus {
256254
return c;
257255
}
258256
}
259-
return p;
257+
258+
throw std::invalid_argument ("RtuLayer settings\"" + settings + "\" has an invalid parity setting.");
260259
}
261260

262261
// ---------------------------------------------------------------------------
263262
// static
264263
int RtuLayer::stop (const std::string & settings) {
264+
size_t s = settings.length();
265265

266-
if (parity (settings) == 'N') {
267-
268-
return 2;
266+
if (s >= 3) {
267+
char c = settings[s - 1];
268+
switch (c) {
269+
case '1':
270+
return 1;
271+
case '2':
272+
return 2;
273+
}
269274
}
270-
return 1;
275+
276+
throw std::invalid_argument ("RtuLayer settings\"" + settings + "\" has an invalid stop bit setting.");
271277
}
272278

273279
// ---------------------------------------------------------------------------

0 commit comments

Comments
 (0)