DynExp
Highly flexible laboratory automation for dynamically changing experiments.
HardwareAdapterEthernet.cpp
Go to the documentation of this file.
1 // This file is part of DynExp.
2 
3 #include "stdafx.h"
4 #include "moc_HardwareAdapterEthernet.cpp"
6 
7 namespace DynExp
8 {
10  : ServerName("localhost"), Port(1000), Socket(this)
11  {
12  Socket.setSocketOption(QAbstractSocket::KeepAliveOption, 1);
14 
15  QObject::connect(&Socket, &QTcpSocket::connected, this, &HardwareAdapterTcpSocketWorker::OnConnected);
16  QObject::connect(&Socket, &QTcpSocket::disconnected, this, &HardwareAdapterTcpSocketWorker::OnDisconnected);
17  QObject::connect(&Socket, &QTcpSocket::errorOccurred, this, &HardwareAdapterTcpSocketWorker::OnErrorOccurred);
18  QObject::connect(&Socket, &QTcpSocket::readyRead, this, &HardwareAdapterTcpSocketWorker::OnDataAvailable);
19  }
20 
21  void HardwareAdapterTcpSocketWorker::Init(QString ServerName, quint16 Port)
22  {
23  this->ServerName = ServerName;
24  this->Port = Port;
25  }
26 
28  {
30  }
31 
33  {
35  }
36 
37  void HardwareAdapterTcpSocketWorker::OnErrorOccurred(QAbstractSocket::SocketError SocketError)
38  {
39  SetException(NetworkException(Util::ToStr(Socket.errorString()), SocketError));
40  }
41 
43  {
44  Read();
45  }
46 
48  {
49  return Socket.state() == QAbstractSocket::SocketState::ConnectedState ||
50  Socket.state() == QAbstractSocket::SocketState::BoundState;
51  }
52 
54  {
55  return Socket.state() == QAbstractSocket::SocketState::HostLookupState ||
56  Socket.state() == QAbstractSocket::SocketState::ConnectingState;
57  }
58 
60  {
61  if (!IsOpen() && !IsOpening())
62  Socket.connectToHost(ServerName, Port);
63  }
64 
66  {
67  if (IsOpen())
68  Socket.disconnectFromHost();
69  }
70 
72  {
73  if (IsOpen())
74  Socket.abort();
75  }
76 
78  {
79  // No action needed.
80  }
81 
83  {
84  if (IsOpen())
85  Socket.flush();
86  }
87 
89  {
90  QByteArray BytesRead(Socket.readAll());
91 
92  if (BytesRead.size())
93  DataRead(BytesRead.constData());
94  }
95 
96  void HardwareAdapterTcpSocketWorker::WriteChild(const QString& String)
97  {
98  auto StdString(String.toStdString());
99 
100  Socket.write(StdString.c_str(), StdString.size()); // crop terminating '\0'
101  }
102 
104  {
105  auto Owner = std::dynamic_pointer_cast<const HardwareAdapterTcpSocket>(GetOwner());
106  if (!Owner)
107  return;
108 
109  const auto LineEnding = Owner->GetLineEnding();
110 
111  Socket.write(Owner->LineEndingToChar(LineEnding).data(), Owner->GetLineEndingLength(LineEnding));
112  }
113 
114  HardwareAdapterTcpSocket::HardwareAdapterTcpSocket(const std::thread::id OwnerThreadID, ParamsBasePtrType&& Params)
115  : QSerialCommunicationHardwareAdapter(OwnerThreadID, std::move(Params))
116  {
117  }
118 
120  {
121  auto Worker = std::make_unique<HardwareAdapterTcpSocketWorker>();
122 
124 
125  return Worker;
126  }
127 
129  {
130  auto DerivedParams = dynamic_Params_cast<HardwareAdapterTcpSocket>(GetParams());
131 
132  if (DerivedParams->NetworkParams.Port < 1 || DerivedParams->NetworkParams.Port > std::numeric_limits<uint16_t>::max())
133  ThrowExceptionUnsafe(std::make_exception_ptr(Util::OutOfRangeException(
134  "Port must be in range 1 to " + Util::ToStr(std::numeric_limits<uint16_t>::max()))));
135 
136  emit InitSig(QString::fromStdString(DerivedParams->NetworkParams.ServerName), static_cast<uint16_t>(DerivedParams->NetworkParams.Port));
137  }
138 
140  {
141  emit ResetSig();
142  Init();
143 
145  }
146 }
Implementation of a hardware adapter to communicate text-based commands over TCP sockets.
void ThrowExceptionUnsafe(std::exception_ptr Exception) const
Stores Exception in LastException, wraps it in a Util::ForwardedException and throws the wrapped exce...
virtual void ResetChild() override
Resets the worker and the communication connection.
bool IsOpen() const noexcept
Checks whether Socket is connected.
virtual void Write_endl_Child() override
Writes end of the line character(s) to the communication connection's hardware interface.
virtual void ClearChild() override
Clears the communication connection's buffers and state.
void OnDisconnected()
Qt slot called when Socket has been disconnected. Calls QSerialCommunicationHardwareAdapterWorker::Se...
void Init(QString ServerName, quint16 Port)
Initializes HardwareAdapterTcpSocketWorker::Socket for TCP communication with the given settings.
QString ServerName
IP address to connect to.
virtual void WriteChild(const QString &String) override
Writes String to the communication connection's hardware interface.
void OnConnected()
Qt slot called when Socket has been connected. Calls QSerialCommunicationHardwareAdapterWorker::SetCo...
virtual void OpenChild() override
Opens the communication connection.
void OnDataAvailable()
Qt slot called when Socket has received data which can be read. Calls QSerialCommunicationHardwareAda...
virtual void CloseChild() override
Closes the communication connection.
void OnErrorOccurred(QAbstractSocket::SocketError SocketError)
Qt slot called when Socket transitioned into an error state. Calls QSerialCommunicationHardwareAdapte...
QTcpSocket Socket
COM port for serial communication.
quint16 Port
Network port to connect to.
virtual void FlushChild() override
Flushes the communication connection's buffers.
virtual void ReadChild() override
Reads from the communication connection's hardware interface.
bool IsOpening() const noexcept
Checks whether Socket is connecting right now.
QWorkerPtrType MakeWorker() override
Abstract factory function for a worker instance derived from QSerialCommunicationHardwareAdapterWorke...
void Init()
Initializes the instance at construction or in case Object::Reset() is called.
void ResetImpl(dispatch_tag< QSerialCommunicationHardwareAdapter >) override final
Refer to DynExp::Object::Reset(). Using tag dispatch mechanism to ensure that ResetImpl() of every de...
void InitSig(QString ServerName, quint16 Port)
Initializes HardwareAdapterTcpSocketWorker::Socket for TCP communication with the given settings.
HardwareAdapterTcpSocket(const std::thread::id OwnerThreadID, ParamsBasePtrType &&Params)
Constructs a hardware adapter instance.
Defines an exception caused by a hardware operation on an ethernet interface (e.g....
ParamsConstTypeSyncPtrType GetParams(const std::chrono::milliseconds Timeout=GetParamsTimeoutDefault) const
Locks the mutex of the parameter class instance Params assigned to this Object instance and returns a...
Definition: Object.cpp:436
Refer to ParamsBase::dispatch_tag.
Definition: Object.h:2018
void SetException(const ExceptionType &Exception) const
Calls QSerialCommunicationHardwareAdapter::SetException on QWorker::Owner. Does nothing if QWorker::O...
void DataRead(const std::string &String) const
Calls QSerialCommunicationHardwareAdapter::DataRead on QWorker::Owner. Does nothing if QWorker::Owner...
void Read()
Reads from the communication connection's hardware interface.
void SetCommunicationChannelClosed() const noexcept
Calls QSerialCommunicationHardwareAdapter::SetCommunicationChannelClosed on QWorker::Owner....
void SetCommunicationChannelOpened() const noexcept
Calls QSerialCommunicationHardwareAdapter::SetCommunicationChannelOpened on QWorker::Owner....
SerialCommunicationHardwareAdapter is based on a Qt communication object (wrapped by QSerialCommunica...
void ResetSig()
Resets the worker and the communication connection.
QSerialCommunicationHardwareAdapterWorker * Worker
Worker instance running in its own thread to handle the actual communication there.
std::unique_ptr< QSerialCommunicationHardwareAdapterWorker > QWorkerPtrType
Pointer-type owning the related QSerialCommunicationHardwareAdapterWorker instance.
constexpr static auto GetMaxBufferSize() noexcept
Defines the maximal size of the hardware adapter's (read) buffer.
Thrown when an argument passed to a function exceeds the valid range.
Definition: Exception.h:211
auto GetOwner() const noexcept
Returns this worker instance's owner.
Definition: QtUtil.h:349
OwnerPtrType Owner
Pointer to the hardware adapter owning this instance.
Definition: QtUtil.h:371
DynExp's main namespace contains the implementation of DynExp including classes to manage resources (...
std::unique_ptr< ParamsBase > ParamsBasePtrType
Alias for a pointer to the parameter system base class ParamsBase.
Definition: Object.h:1807
std::string ToStr(const T &Value, int Precision=-1)
Converts a (numeric) value of type T to a std::string using operator<< of std::stringstream.
Definition: Util.h:625
Accumulates include statements to provide a precompiled header.