Modbus cpp 0.1
Loading...
Searching...
No Matches
connection.hpp
1// Modbus for c++ <https://github.com/Mazurel/Modbus>
2// Copyright (c) 2020 Mateusz Mazur aka Mazurel
3// Licensed under: MIT License <http://opensource.org/licenses/MIT>
4
5#pragma once
6
7#include <memory>
8#include <type_traits>
9
10#include <cerrno>
11#include <libnet.h>
12#include <netinet/in.h>
13#include <poll.h>
14#include <sys/socket.h>
15
16#include "MB/modbusException.hpp"
17#include "MB/modbusRequest.hpp"
18#include "MB/modbusResponse.hpp"
19
20namespace MB::TCP {
22 public:
23 static const unsigned int DefaultTCPTimeout = 500;
24
25 private:
26 int _sockfd = -1;
27 uint16_t _messageID = 0;
28 int _timeout = Connection::DefaultTCPTimeout;
29
30 public:
31 explicit Connection() noexcept : _sockfd(-1), _messageID(0) {};
32 explicit Connection(int sockfd) noexcept;
33 Connection(const Connection &copy) = delete;
34 Connection(Connection &&moved) noexcept;
35 Connection &operator=(Connection &&other) noexcept {
36 if (this == &other)
37 return *this;
38
39 if (_sockfd != -1 && _sockfd != other._sockfd)
40 ::close(_sockfd);
41
42 _sockfd = other._sockfd;
43 _messageID = other._messageID;
44 other._sockfd = -1;
45
46 return *this;
47 }
48
49 [[nodiscard]] int getSockfd() const { return _sockfd; }
50
51 static Connection with(std::string addr, int port);
52
54
55 std::vector<uint8_t> sendRequest(const MB::ModbusRequest &req);
56 std::vector<uint8_t> sendResponse(const MB::ModbusResponse &res);
57 std::vector<uint8_t> sendException(const MB::ModbusException &ex);
58
59 [[nodiscard]] MB::ModbusRequest awaitRequest();
60 [[nodiscard]] MB::ModbusResponse awaitResponse();
61
62 [[nodiscard]] std::vector<uint8_t> awaitRawMessage();
63
64 [[nodiscard]] uint16_t getMessageId() const { return _messageID; }
65
66 void setMessageId(uint16_t messageId) { _messageID = messageId; }
67};
68} // namespace MB::TCP
Definition modbusException.hpp:23
Definition modbusRequest.hpp:23
Definition modbusResponse.hpp:25
Definition connection.hpp:21