Commit 4cbc5252c598acf903d940d1fa100603fe68de6f

Authored by Stéphane Raimbault
1 parent 7fed3ff9

Exception response on report slave ID wasn't detected (closes #27)

Showing 1 changed file with 25 additions and 15 deletions
src/modbus.c
... ... @@ -483,6 +483,7 @@ static int check_confirmation(modbus_t *ctx, uint8_t *req,
483 483 int rc;
484 484 int rsp_length_computed;
485 485 const int offset = ctx->backend->header_length;
  486 + const int function = rsp[offset];
486 487  
487 488 if (ctx->backend->pre_check_confirmation) {
488 489 rc = ctx->backend->pre_check_confirmation(ctx, req, rsp, rsp_length);
... ... @@ -496,12 +497,33 @@ static int check_confirmation(modbus_t *ctx, uint8_t *req,
496 497  
497 498 rsp_length_computed = compute_response_length_from_request(ctx, req);
498 499  
  500 + /* Exception code */
  501 + if (function >= 0x80) {
  502 + if (rsp_length == (offset + 2 + ctx->backend->checksum_length) &&
  503 + req[offset] == (rsp[offset] - 0x80)) {
  504 + /* Valid exception code received */
  505 +
  506 + int exception_code = rsp[offset + 1];
  507 + if (exception_code < MODBUS_EXCEPTION_MAX) {
  508 + errno = MODBUS_ENOBASE + exception_code;
  509 + } else {
  510 + errno = EMBBADEXC;
  511 + }
  512 + _error_print(ctx, NULL);
  513 + return -1;
  514 + } else {
  515 + errno = EMBBADEXC;
  516 + _error_print(ctx, NULL);
  517 + return -1;
  518 + }
  519 + }
  520 +
499 521 /* Check length */
500   - if (rsp_length == rsp_length_computed ||
501   - rsp_length_computed == MSG_LENGTH_UNDEFINED) {
  522 + if ((rsp_length == rsp_length_computed ||
  523 + rsp_length_computed == MSG_LENGTH_UNDEFINED) &&
  524 + function < 0x80) {
502 525 int req_nb_value;
503 526 int rsp_nb_value;
504   - const int function = rsp[offset];
505 527  
506 528 /* Check function code */
507 529 if (function != req[offset]) {
... ... @@ -566,18 +588,6 @@ static int check_confirmation(modbus_t *ctx, uint8_t *req,
566 588 errno = EMBBADDATA;
567 589 rc = -1;
568 590 }
569   - } else if (rsp_length == (offset + 2 + ctx->backend->checksum_length) &&
570   - req[offset] == (rsp[offset] - 0x80)) {
571   - /* EXCEPTION CODE RECEIVED */
572   -
573   - int exception_code = rsp[offset + 1];
574   - if (exception_code < MODBUS_EXCEPTION_MAX) {
575   - errno = MODBUS_ENOBASE + exception_code;
576   - } else {
577   - errno = EMBBADEXC;
578   - }
579   - _error_print(ctx, NULL);
580   - rc = -1;
581 591 } else {
582 592 if (ctx->debug) {
583 593 fprintf(stderr,
... ...