|
| 1 | +/* |
| 2 | + * Copyright (C) 2022 Nikolas Koesling <nikolas@koesling.info>. |
| 3 | + * This program is free software. You can redistribute it and/or modify it under the terms of the MIT License. |
| 4 | + */ |
| 5 | + |
| 6 | +#include "Modbus_TCP_connection.hpp" |
| 7 | + |
| 8 | +#include <cstring> |
| 9 | +#include <sys/poll.h> |
| 10 | + |
| 11 | +namespace Modbus { |
| 12 | +namespace TCP { |
| 13 | + |
| 14 | +bool Connection::handle_request() { |
| 15 | + struct pollfd fd; |
| 16 | + memset(&fd, 0, sizeof(fd)); |
| 17 | + fd.fd = socket; |
| 18 | + fd.events = POLL_IN; |
| 19 | + do { |
| 20 | + int tmp = poll(&fd, 1, -1); |
| 21 | + if (tmp <= 0) { |
| 22 | + if (errno == EINTR) continue; |
| 23 | + throw std::system_error(errno, std::generic_category(), "Failed to poll client socket"); |
| 24 | + } else |
| 25 | + break; |
| 26 | + } while (true); |
| 27 | + |
| 28 | + |
| 29 | + std::lock_guard<std::mutex> guard(modbus_lock); |
| 30 | + |
| 31 | + // set client socket |
| 32 | + int restore_socket = modbus_get_socket(modbus); |
| 33 | + modbus_set_socket(modbus, socket); |
| 34 | + |
| 35 | + // receive modbus request |
| 36 | + uint8_t query[MODBUS_TCP_MAX_ADU_LENGTH]; |
| 37 | + int rc = modbus_receive(modbus, query); |
| 38 | + |
| 39 | + if (rc > 0) { |
| 40 | + const auto CLIENT_ID = query[6]; |
| 41 | + |
| 42 | + // get mapping |
| 43 | + auto mapping = mappings[CLIENT_ID]; |
| 44 | + |
| 45 | + // handle request |
| 46 | + int ret = modbus_reply(modbus, query, rc, mapping); |
| 47 | + if (ret == -1) { |
| 48 | + modbus_set_socket(modbus, restore_socket); |
| 49 | + const std::string error_msg = modbus_strerror(errno); |
| 50 | + throw std::runtime_error("modbus_reply failed: " + error_msg + ' ' + std::to_string(errno)); |
| 51 | + } |
| 52 | + } else if (rc == -1) { |
| 53 | + if (errno == ECONNRESET) { |
| 54 | + modbus_set_socket(modbus, restore_socket); |
| 55 | + return true; |
| 56 | + } |
| 57 | + |
| 58 | + modbus_set_socket(modbus, restore_socket); |
| 59 | + const std::string error_msg = modbus_strerror(errno); |
| 60 | + throw std::runtime_error("modbus_receive failed: " + error_msg + ' ' + std::to_string(errno)); |
| 61 | + } |
| 62 | + |
| 63 | + modbus_set_socket(modbus, restore_socket); |
| 64 | + return false; |
| 65 | +} |
| 66 | + |
| 67 | +} // namespace TCP |
| 68 | +} // namespace Modbus |
0 commit comments