-
Notifications
You must be signed in to change notification settings - Fork 118
/
rtu.rs
193 lines (161 loc) · 5.01 KB
/
rtu.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
// SPDX-FileCopyrightText: Copyright (c) 2017-2024 slowtec GmbH <post@slowtec.de>
// SPDX-License-Identifier: MIT OR Apache-2.0
use std::{fmt, io};
use futures_util::{SinkExt as _, StreamExt as _};
use tokio::io::{AsyncRead, AsyncWrite};
use tokio_util::codec::Framed;
use crate::{
codec,
frame::{rtu::*, *},
slave::*,
ProtocolError, Result,
};
use super::verify_response_header;
/// Modbus RTU client
#[derive(Debug)]
pub(crate) struct Client<T> {
framed: Framed<T, codec::rtu::ClientCodec>,
slave_id: SlaveId,
}
impl<T> Client<T>
where
T: AsyncRead + AsyncWrite + Unpin,
{
pub(crate) fn new(transport: T, slave: Slave) -> Self {
let framed = Framed::new(transport, codec::rtu::ClientCodec::default());
let slave_id = slave.into();
Self { framed, slave_id }
}
fn next_request_adu<'a, R>(&self, req: R, disconnect: bool) -> RequestAdu<'a>
where
R: Into<RequestPdu<'a>>,
{
let slave_id = self.slave_id;
let hdr = Header { slave_id };
let pdu = req.into();
RequestAdu {
hdr,
pdu,
disconnect,
}
}
async fn call(&mut self, req: Request<'_>) -> Result<Response> {
let disconnect = req == Request::Disconnect;
let req_function_code = req.function_code();
let req_adu = self.next_request_adu(req, disconnect);
let req_hdr = req_adu.hdr;
self.framed.read_buffer_mut().clear();
self.framed.send(req_adu).await?;
let res_adu = self
.framed
.next()
.await
.unwrap_or_else(|| Err(io::Error::from(io::ErrorKind::BrokenPipe)))?;
let ResponsePdu(result) = res_adu.pdu;
// Match headers of request and response.
if let Err(message) = verify_response_header(&req_hdr, &res_adu.hdr) {
return Err(ProtocolError::HeaderMismatch { message, result }.into());
}
// Match function codes of request and response.
let rsp_function_code = match &result {
Ok(response) => response.function_code(),
Err(ExceptionResponse { function, .. }) => *function,
};
if req_function_code != rsp_function_code {
return Err(ProtocolError::FunctionCodeMismatch {
request: req_function_code,
result,
}
.into());
}
Ok(result.map_err(
|ExceptionResponse {
function: _,
exception,
}| exception,
))
}
}
impl<T> SlaveContext for Client<T> {
fn set_slave(&mut self, slave: Slave) {
self.slave_id = slave.into();
}
}
#[async_trait::async_trait]
impl<T> crate::client::Client for Client<T>
where
T: fmt::Debug + AsyncRead + AsyncWrite + Send + Unpin,
{
async fn call(&mut self, req: Request<'_>) -> Result<Response> {
self.call(req).await
}
}
#[cfg(test)]
mod tests {
use core::{
pin::Pin,
task::{Context, Poll},
};
use tokio::io::{AsyncRead, AsyncWrite, ReadBuf, Result};
use crate::{
service::{rtu::Header, verify_response_header},
Error,
};
#[test]
fn validate_same_headers() {
// Given
let req_hdr = Header { slave_id: 0 };
let rsp_hdr = Header { slave_id: 0 };
// When
let result = verify_response_header(&req_hdr, &rsp_hdr);
// Then
assert!(result.is_ok());
}
#[test]
fn invalid_validate_not_same_slave_id() {
// Given
let req_hdr = Header { slave_id: 0 };
let rsp_hdr = Header { slave_id: 5 };
// When
let result = verify_response_header(&req_hdr, &rsp_hdr);
// Then
assert!(result.is_err());
}
#[derive(Debug)]
struct MockTransport;
impl Unpin for MockTransport {}
impl AsyncRead for MockTransport {
fn poll_read(
self: Pin<&mut Self>,
_: &mut Context<'_>,
_: &mut ReadBuf<'_>,
) -> Poll<Result<()>> {
Poll::Ready(Ok(()))
}
}
impl AsyncWrite for MockTransport {
fn poll_write(self: Pin<&mut Self>, _: &mut Context<'_>, _: &[u8]) -> Poll<Result<usize>> {
Poll::Ready(Ok(2))
}
fn poll_flush(self: Pin<&mut Self>, _: &mut Context<'_>) -> Poll<Result<()>> {
Poll::Ready(Ok(()))
}
fn poll_shutdown(self: Pin<&mut Self>, _: &mut Context<'_>) -> Poll<Result<()>> {
unimplemented!()
}
}
#[tokio::test]
async fn handle_broken_pipe() {
let transport = MockTransport;
let mut client =
crate::service::rtu::Client::new(transport, crate::service::rtu::Slave::broadcast());
let res = client
.call(crate::service::rtu::Request::ReadCoils(0x00, 5))
.await;
assert!(res.is_err());
let err = res.err().unwrap();
assert!(
matches!(err, Error::Transport(err) if err.kind() == std::io::ErrorKind::BrokenPipe)
);
}
}