Skip to content

Support for Windows compilation #14

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

Merged
merged 1 commit into from
Nov 10, 2024
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
8 changes: 5 additions & 3 deletions .github/workflows/cmake-multi-platform.yml
Original file line number Diff line number Diff line change
Expand Up @@ -30,9 +30,10 @@ jobs:
- os: ubuntu-latest
c_compiler: clang
cpp_compiler: clang++
exclude:
- os: windows-latest
c_compiler: cl
cpp_compiler: cl
exclude:
- os: windows-latest
c_compiler: gcc
- os: windows-latest
Expand Down Expand Up @@ -67,11 +68,12 @@ jobs:
-DCMAKE_BUILD_TYPE=${{ matrix.build_type }}
-DMODBUS_EXAMPLE=ON
-DMODBUS_TESTS=ON
-DMODBUS_COMMUNICATION=${{ matrix.os == 'windows-latest' && 'OFF' || matrix.os == 'ubuntu-latest' && 'ON' }}
-DMODBUS_TCP_COMMUNICATION=${{ matrix.os == 'windows-latest' && 'OFF' || matrix.os == 'ubuntu-latest' && 'ON' }}
-DMODBUS_SERIAL_COMMUNICATION=${{ matrix.os == 'windows-latest' && 'OFF' || matrix.os == 'ubuntu-latest' && 'ON' }}
-S ${{ github.workspace }}

- name: Build
run: cmake --build ${{ steps.strings.outputs.build-output-dir }} --config ${{ matrix.build_type }}

- name: Test
run: ${{ steps.strings.outputs.build-output-dir }}/tests/Google_Tests_run
run: ${{ steps.strings.outputs.build-output-dir }}/${{ matrix.os == 'windows-latest' && 'tests\Release\Google_Tests_run.exe' || matrix.os == 'ubuntu-latest' && '/tests/Google_Tests_run' }}
5 changes: 4 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -30,9 +30,12 @@
*.exe
*.out
*.app

build

# Windows specific
out
.vs

# Gtags
GTAGS
GRTAGS
Expand Down
17 changes: 13 additions & 4 deletions CMakeLists.txt
Original file line number Diff line number Diff line change
@@ -1,17 +1,26 @@
cmake_minimum_required(VERSION 3.13)
project(protocolConverter)
project(modbus)

set(CMAKE_CXX_STANDARD 17)

if (MSVC)
add_compile_options(/W3)
add_compile_options(/W3 /MT)
# Otherwise, MSVC complains about strncopy
add_definitions(-D_CRT_SECURE_NO_WARNINGS)
else()
add_compile_options(-Wall -Wextra -Werror -pedantic)
endif()

option(MODBUS_EXAMPLE "Build example program" OFF)
option(MODBUS_TESTS "Build tests" OFF)
option(MODBUS_COMMUNICATION "Use Modbus communication library" ON)
option(MODBUS_TCP_COMMUNICATION "Use Modbus TCP communication library" ON)

if(NOT win32)
# Serial not supported on Windows
option(MODBUS_SERIAL_COMMUNICATION "Use Modbus serial communication library" OFF) # not supported by windows platform
else()
message(STATUS "Modbus Serial not supported on Windows.")
endif()

add_subdirectory(src)

Expand All @@ -21,5 +30,5 @@ endif()

if(MODBUS_EXAMPLE)
add_executable(ex example/main.cpp)
target_link_libraries(ex Modbus)
target_link_libraries(ex PUBLIC Modbus_Core)
endif()
18 changes: 12 additions & 6 deletions include/MB/crc.hpp
Original file line number Diff line number Diff line change
@@ -1,13 +1,19 @@
#include <cstdint>
#include <optional>
#include <vector>

//! This namespace contains functions used for CRC calculation
namespace MB::CRC {
//! Calculates CRC based on the input buffer - C style
uint16_t calculateCRC(const uint8_t *buff, std::size_t len);
//! Calculates CRC based on the input buffer - C style
uint16_t calculateCRC(const uint8_t *buff, std::size_t len);

//! Calculate CRC based on the input vector of bytes
inline uint16_t calculateCRC(const std::vector<uint8_t> &buffer) {
return calculateCRC(buffer.begin().base(), buffer.size());
//! Calculate CRC based on the input vector of bytes
inline uint16_t calculateCRC(const std::vector<uint8_t> &buffer, std::optional<std::size_t> len = std::nullopt) {
std::size_t bufferLength = buffer.size();
if (len.has_value() && bufferLength >= *len) {
bufferLength = *len;
}
};

return calculateCRC(static_cast<const uint8_t *>(&(*buffer.begin())), bufferLength);
}
}; // namespace MB::CRC
2 changes: 1 addition & 1 deletion include/MB/modbusCell.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
#pragma once

#include <cstdint>
#include <stdexcept>
#include <string>
#include <variant>

/**
Expand Down
13 changes: 8 additions & 5 deletions include/MB/modbusException.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,10 @@

#pragma once

#include <algorithm>
#include <cstddef>
#include <cstdint>
#include <cstring>
#include <stdexcept>
#include <vector>

#include "modbusUtils.hpp"
Expand Down Expand Up @@ -81,12 +82,14 @@ class ModbusException : public std::exception {

/**
* This function is less optimal, it is just to be compatible with
* std::excepetion You should preferably use toString()
* `std::exception`, you should preferably use toString()
*/
[[nodiscard]] const char *what() const noexcept override {
auto og = toString();
char *str = new char[og.size()];
stpcpy(str, og.c_str());
const std::size_t MAX_STRING_SIZE = 1024;
static char str[MAX_STRING_SIZE];
auto originalStr = toString();
std::strncpy(str, originalStr.c_str(),
std::min(originalStr.size(), MAX_STRING_SIZE));
return str;
}

Expand Down
12 changes: 6 additions & 6 deletions include/MB/modbusRequest.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -81,14 +81,14 @@ class ModbusRequest {
std::vector<ModbusCell> values = {}) noexcept;

/**
* Copy constructor for the response.
*/
ModbusRequest(const ModbusRequest&);
* Copy constructor for the response.
*/
ModbusRequest(const ModbusRequest &);

/**
* Equal operator for the response.
*/
ModbusRequest& operator=(const ModbusRequest &);
* Equal operator for the response.
*/
ModbusRequest &operator=(const ModbusRequest &);

//! Returns string representation of object
[[nodiscard]] std::string toString() const noexcept;
Expand Down
8 changes: 4 additions & 4 deletions include/MB/modbusResponse.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -83,12 +83,12 @@ class ModbusResponse {
/**
* Copy constructor for the response.
*/
ModbusResponse(const ModbusResponse&);
ModbusResponse(const ModbusResponse &);

/**
* Equal operator for the response.
*/
ModbusResponse& operator=(const ModbusResponse &);
* Equal operator for the response.
*/
ModbusResponse &operator=(const ModbusResponse &);

//! Converts object to it's string representation
[[nodiscard]] std::string toString() const;
Expand Down
6 changes: 2 additions & 4 deletions include/MB/modbusUtils.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -204,8 +204,7 @@ inline std::string mbFunctionToStr(MBFunctionCode code) noexcept {

//! Create uint16_t from buffer of two bytes, ex. { 0x01, 0x02 } => 0x0102
inline uint16_t bigEndianConv(const uint8_t *buf) {
return static_cast<uint16_t>(buf[1]) +
(static_cast<uint16_t>(buf[0]) << 8u);
return static_cast<uint16_t>(buf[1]) + (static_cast<uint16_t>(buf[0]) << 8u);
}

//! @deprecated Calculates CRC - please use functions from `MB::CRC`
Expand Down Expand Up @@ -234,7 +233,6 @@ inline void pushUint16(std::vector<uint8_t> &buffer, const uint16_t val) {
}

//! Ignore some value explicitly
template<typename T>
inline void ignore_result(T&& v) { (void)v; }
template <typename T> inline void ignore_result(T &&v) { (void)v; }

} // namespace MB::utils
14 changes: 9 additions & 5 deletions src/CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -17,16 +17,20 @@ set(CORE_SOURCE_FILES
)

add_library(Modbus_Core)
target_sources(Modbus_Core PRIVATE ${CORE_SOURCE_FILES} PUBLIC ${CORE_HEADER_FILES})
target_sources(Modbus_Core PRIVATE ${CORE_SOURCE_FILES} INTERFACE ${CORE_HEADER_FILES})
target_include_directories(Modbus_Core PUBLIC ${PROJECT_SOURCE_DIR}/include PRIVATE ${MODBUS_HEADER_FILES_DIR})

add_library(Modbus)
target_link_libraries(Modbus Modbus_Core)

if(MODBUS_SERIAL_COMMUNICATION)
message(STATUS "Enabling Modbus Serial")
add_subdirectory(Serial)
target_link_libraries(Modbus Modbus_Serial)
endif()

if(MODBUS_COMMUNICATION)
message("Modbus communication is experimental")
if(MODBUS_TCP_COMMUNICATION)
message(STATUS "Enabling Modbus Serial")
add_subdirectory(TCP)
add_subdirectory(Serial)
target_link_libraries(Modbus Modbus_TCP Modbus_Serial)
target_link_libraries(Modbus Modbus_TCP)
endif()
4 changes: 2 additions & 2 deletions src/Serial/connection.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -55,8 +55,8 @@ std::vector<uint8_t> Connection::awaitRawMessage() {
std::vector<uint8_t> data(1024);

pollfd waitingFD;
waitingFD.fd = this->_fd;
waitingFD.events = POLLIN;
waitingFD.fd = this->_fd;
waitingFD.events = POLLIN;
waitingFD.revents = POLLIN;

if (::poll(&waitingFD, 1, _timeout) <= 0) {
Expand Down
34 changes: 20 additions & 14 deletions src/TCP/connection.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -26,15 +26,17 @@ std::vector<uint8_t> Connection::sendRequest(const MB::ModbusRequest &req) {
std::vector<uint8_t> rawReq;
rawReq.reserve(6);

rawReq.push_back(static_cast<const uint8_t&&>(reinterpret_cast<const uint8_t *>(&_messageID)[1]));
rawReq.push_back(
static_cast<const uint8_t &&>(reinterpret_cast<const uint8_t *>(&_messageID)[1]));
rawReq.push_back(static_cast<uint8_t>(_messageID));
rawReq.push_back(0x00);
rawReq.push_back(0x00);

std::vector<uint8_t> dat = req.toRaw();

uint32_t size = dat.size();
rawReq.push_back(static_cast<const uint16_t&&>(reinterpret_cast<const uint16_t *>(&size)[1]));
rawReq.push_back(
static_cast<const uint16_t &&>(reinterpret_cast<const uint16_t *>(&size)[1]));
rawReq.push_back(static_cast<uint16_t>(size));

rawReq.insert(rawReq.end(), dat.begin(), dat.end());
Expand All @@ -48,15 +50,17 @@ std::vector<uint8_t> Connection::sendResponse(const MB::ModbusResponse &res) {
std::vector<uint8_t> rawReq;
rawReq.reserve(6);

rawReq.push_back(static_cast<const uint8_t&&>(reinterpret_cast<const uint8_t *>(&_messageID)[1]));
rawReq.push_back(
static_cast<const uint8_t &&>(reinterpret_cast<const uint8_t *>(&_messageID)[1]));
rawReq.push_back(static_cast<uint8_t>(_messageID));
rawReq.push_back(0x00);
rawReq.push_back(0x00);

std::vector<uint8_t> dat = res.toRaw();

uint32_t size = dat.size();
rawReq.push_back(static_cast<const uint16_t&&>(reinterpret_cast<const uint16_t *>(&size)[1]));
rawReq.push_back(
static_cast<const uint16_t &&>(reinterpret_cast<const uint16_t *>(&size)[1]));
rawReq.push_back(static_cast<uint16_t>(size));

rawReq.insert(rawReq.end(), dat.begin(), dat.end());
Expand All @@ -70,15 +74,17 @@ std::vector<uint8_t> Connection::sendException(const MB::ModbusException &ex) {
std::vector<uint8_t> rawReq;
rawReq.reserve(6);

rawReq.push_back(static_cast<const uint8_t&&>(reinterpret_cast<const uint8_t *>(&_messageID)[1]));
rawReq.push_back(
static_cast<const uint8_t &&>(reinterpret_cast<const uint8_t *>(&_messageID)[1]));
rawReq.push_back(static_cast<uint8_t>(_messageID));
rawReq.push_back(0x00);
rawReq.push_back(0x00);

std::vector<uint8_t> dat = ex.toRaw();

uint32_t size = dat.size();
rawReq.push_back(static_cast<const uint16_t&&>(reinterpret_cast<const uint16_t *>(&size)[1]));
rawReq.push_back(
static_cast<const uint16_t &&>(reinterpret_cast<const uint16_t *>(&size)[1]));
rawReq.push_back(static_cast<uint16_t>(size));

rawReq.insert(rawReq.end(), dat.begin(), dat.end());
Expand All @@ -90,8 +96,8 @@ std::vector<uint8_t> Connection::sendException(const MB::ModbusException &ex) {

std::vector<uint8_t> Connection::awaitRawMessage() {
pollfd pfd;
pfd.fd = this->_sockfd;
pfd.events = POLLIN;
pfd.fd = this->_sockfd;
pfd.events = POLLIN;
pfd.revents = POLLIN;
if (::poll(&pfd, 1, 60 * 1000 /* 1 minute means the connection has died */) <= 0) {
throw MB::ModbusException(MB::utils::ConnectionClosed);
Expand All @@ -115,8 +121,8 @@ std::vector<uint8_t> Connection::awaitRawMessage() {

MB::ModbusRequest Connection::awaitRequest() {
pollfd pfd;
pfd.fd = this->_sockfd;
pfd.events = POLLIN;
pfd.fd = this->_sockfd;
pfd.events = POLLIN;
pfd.revents = POLLIN;
if (::poll(&pfd, 1, 60 * 1000 /* 1 minute means the connection has died */) <= 0) {
throw MB::ModbusException(MB::utils::Timeout);
Expand Down Expand Up @@ -146,8 +152,8 @@ MB::ModbusRequest Connection::awaitRequest() {

MB::ModbusResponse Connection::awaitResponse() {
pollfd pfd;
pfd.fd = this->_sockfd;
pfd.events = POLLIN;
pfd.fd = this->_sockfd;
pfd.events = POLLIN;
pfd.revents = POLLIN;

if (::poll(&pfd, 1, this->_timeout) <= 0) {
Expand Down Expand Up @@ -195,8 +201,8 @@ Connection Connection::with(std::string addr, int port) {

sockaddr_in server;
server.sin_family = AF_INET;
server.sin_port = ::htons(port);
server.sin_addr = { inet_addr(addr.c_str()) };
server.sin_port = ::htons(port);
server.sin_addr = {inet_addr(addr.c_str())};

if (::connect(sock, reinterpret_cast<struct sockaddr *>(&server), sizeof(server)) < 0)
throw std::runtime_error("Cannot connect, errno = " + std::to_string(errno));
Expand Down
21 changes: 15 additions & 6 deletions src/modbusException.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -3,13 +3,22 @@
// Licensed under: MIT License <http://opensource.org/licenses/MIT>

#include "modbusException.hpp"
#include "modbusUtils.hpp"

#include <cstddef>
#include <cstdint>
#include <vector>

using namespace MB;

// Construct Modbus exception from raw data
ModbusException::ModbusException(const std::vector<uint8_t> &inputData,
bool CRC) noexcept {
if (inputData.size() != ((CRC) ? 5 : 3)) {
bool checkCRC) noexcept {
const std::size_t PACKET_SIZE_WITHOUT_CRC = 3;
const std::size_t PACKET_SIZE_WITH_CRC = 5;

if (inputData.size() !=
((checkCRC) ? PACKET_SIZE_WITH_CRC : PACKET_SIZE_WITHOUT_CRC)) {
_slaveId = 0xFF;
_functionCode = utils::Undefined;
_validSlave = false;
Expand All @@ -22,11 +31,11 @@ ModbusException::ModbusException(const std::vector<uint8_t> &inputData,
_validSlave = true;
_errorCode = static_cast<utils::MBErrorCode>(inputData[2]);

if (CRC) {
auto CRC = *reinterpret_cast<const uint16_t *>(&inputData[3]);
auto calculatedCRC = utils::calculateCRC(inputData.begin().base(), 3);
if (checkCRC) {
const auto actualCrc = *reinterpret_cast<const uint16_t *>(&inputData[3]);
const uint16_t calculatedCRC = MB::CRC::calculateCRC(inputData, PACKET_SIZE_WITHOUT_CRC);

if (CRC != calculatedCRC) {
if (actualCrc != calculatedCRC) {
_errorCode = utils::ErrorCodeCRCError;
}
}
Expand Down
Loading