Skip to content

Commit

Permalink
codefmt
Browse files Browse the repository at this point in the history
  • Loading branch information
divi255 committed Feb 25, 2024
1 parent d5b5133 commit d09ce90
Show file tree
Hide file tree
Showing 8 changed files with 76 additions and 81 deletions.
15 changes: 8 additions & 7 deletions examples/app.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,8 @@ use std::error::Error;
use std::fs::File;
use std::io::{Read, Write};

use rmodbus::server::context::ModbusContextFull;
use rmodbus::server::context::ModbusContext;
use rmodbus::server::storage::ModbusStorageFull;

#[path = "servers/tcp.rs"]
mod srv;
Expand Down Expand Up @@ -40,25 +41,25 @@ fn looping() {
// WRITE RESULTS
let mut ctx = srv::CONTEXT.write().unwrap();
ctx.set_coil(0, true).unwrap();
ctx.set_holdings_bulk(10, &(vec![10, 20])).unwrap();
ctx.set_holdings_bulk(10, &[10, 20]).unwrap();
ctx.set_inputs_from_f32(20, 935.77).unwrap();
}
}

fn save(fname: &str, ctx: &ModbusContextFull) -> Result<(), Box<dyn Error>> {
fn save(fname: &str, ctx: &ModbusStorageFull) -> Result<(), Box<dyn Error>> {
let config = bincode::config::standard();
let mut file = File::create(fname)?;
file.write(&bincode::encode_to_vec(ctx, config)?)?;
file.write_all(&bincode::encode_to_vec(ctx, config)?)?;
file.sync_all()?;
Ok(())
}

fn load(fname: &str, ctx: &mut ModbusContextFull) -> Result<(), Box<dyn Error>> {
fn load(fname: &str, ctx: &mut ModbusStorageFull) -> Result<(), Box<dyn Error>> {
let config = bincode::config::standard();
let mut file = File::open(fname)?;
let mut data: Vec<u8> = Vec::new();
file.read_to_end(&mut data)?;
let (bctx, _): (Box<ModbusContextFull>, usize) = bincode::decode_from_slice(&data, config)?;
let (bctx, _): (Box<ModbusStorageFull>, usize) = bincode::decode_from_slice(&data, config)?;
*ctx = *bctx;
Ok(())
}
Expand All @@ -68,7 +69,7 @@ fn main() {
let unit_id = 1;
{
let mut ctx = srv::CONTEXT.write().unwrap();
let _ = load(&"/tmp/plc1.dat", &mut ctx).map_err(|_| {
let _ = load("/tmp/plc1.dat", &mut ctx).map_err(|_| {
eprintln!("warning: no saved context");
});
}
Expand Down
7 changes: 3 additions & 4 deletions examples/servers/ascii.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ use std::sync::RwLock;

use rmodbus::{
generate_ascii_frame, guess_request_frame_len, parse_ascii_frame,
server::{context::ModbusContext, storage::ModbusStorageFull, ModbusFrame},
server::{storage::ModbusStorageFull, ModbusFrame},
ModbusFrameBuf, ModbusProto,
};

Expand Down Expand Up @@ -42,9 +42,8 @@ pub fn asciiserver(unit: u8, port: &str) {
if result.is_err() {
println!("unable to decode");
continue;
} else {
println!("parsed {} bytes", result.unwrap());
}
println!("parsed {} bytes", result.unwrap());
let mut response = Vec::new();
let mut frame = ModbusFrame::new(unit, &buf, ModbusProto::Ascii, &mut response);
if frame.parse().is_err() {
Expand All @@ -67,7 +66,7 @@ pub fn asciiserver(unit: u8, port: &str) {
let mut response_ascii = Vec::new();
generate_ascii_frame(&response, &mut response_ascii).unwrap();
println!("{:x?}", response_ascii);
port.write(response_ascii.as_slice()).unwrap();
port.write_all(response_ascii.as_slice()).unwrap();
}
}
}
Expand Down
4 changes: 2 additions & 2 deletions examples/servers/rtu.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ use lazy_static::lazy_static;
use std::sync::RwLock;

use rmodbus::{
server::{context::ModbusContext, storage::ModbusStorageFull, ModbusFrame},
server::{storage::ModbusStorageFull, ModbusFrame},
ModbusFrameBuf, ModbusProto,
};

Expand Down Expand Up @@ -50,7 +50,7 @@ pub fn rtuserver(unit: u8, port: &str) {
if frame.response_required {
frame.finalize_response().unwrap();
println!("{:x?}", response);
port.write(response.as_slice()).unwrap();
port.write_all(response.as_slice()).unwrap();
}
}
}
Expand Down
2 changes: 1 addition & 1 deletion examples/servers/tcp.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ use lazy_static::lazy_static;
use std::sync::RwLock;

use rmodbus::{
server::{context::ModbusContext, storage::ModbusStorageFull, ModbusFrame},
server::{storage::ModbusStorageFull, ModbusFrame},
ModbusFrameBuf, ModbusProto,
};

Expand Down
4 changes: 2 additions & 2 deletions examples/servers/udp.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ use lazy_static::lazy_static;
use std::sync::RwLock;

use rmodbus::{
server::{context::ModbusContext, storage::ModbusStorageFull, ModbusFrame},
server::{storage::ModbusStorageFull, ModbusFrame},
ModbusFrameBuf, ModbusProto,
};

Expand Down Expand Up @@ -38,7 +38,7 @@ pub fn udpserver(unit: u8, listen: &str) {
if frame.response_required {
frame.finalize_response().unwrap();
println!("{:x?}", response.as_slice());
socket.send_to(response.as_slice(), &src).unwrap();
socket.send_to(response.as_slice(), src).unwrap();
}
}
}
28 changes: 15 additions & 13 deletions src/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -41,24 +41,26 @@ impl ErrorKind {
}

pub fn is_modbus_error(&self) -> bool {
#[allow(clippy::enum_glob_use)]
use ErrorKind::*;

match self {
matches!(
self,
IllegalFunction
| IllegalDataAddress
| IllegalDataValue
| SlaveDeviceFailure
| Acknowledge
| SlaveDeviceBusy
| NegativeAcknowledge
| MemoryParityError
| GatewayPathUnavailable
| GatewayTargetFailed => true,
_ => false,
}
| IllegalDataAddress
| IllegalDataValue
| SlaveDeviceFailure
| Acknowledge
| SlaveDeviceBusy
| NegativeAcknowledge
| MemoryParityError
| GatewayPathUnavailable
| GatewayTargetFailed
)
}

pub fn to_modbus_error(&self) -> Result<u8, ErrorKind> {
#[allow(clippy::enum_glob_use)]
use ErrorKind::*;

match self {
Expand All @@ -72,7 +74,7 @@ impl ErrorKind {
MemoryParityError => Ok(8),
GatewayPathUnavailable => Ok(9),
GatewayTargetFailed => Ok(10),
_ => Err(self.clone()),
_ => Err(*self),
}
}
}
Expand Down
1 change: 1 addition & 0 deletions src/server/context.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
use crate::{ErrorKind, VectorTrait};

#[allow(clippy::module_name_repetitions)]
pub trait ModbusContext {
/// Get inputs as Vec of u8
///
Expand Down
96 changes: 44 additions & 52 deletions src/server/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ pub mod storage;
#[cfg(feature = "std")]
use std::slice;

#[allow(clippy::wildcard_imports)]
use crate::consts::*;
use crate::{calc_crc16, calc_lrc, ErrorKind, ModbusProto, VectorTrait};

Expand Down Expand Up @@ -215,7 +216,7 @@ impl<'a, V: VectorTrait<u8>> ModbusFrame<'a, V> {
}
}
MODBUS_GET_HOLDINGS | MODBUS_GET_INPUTS | MODBUS_GET_COILS | MODBUS_GET_DISCRETES => {
return Err(ErrorKind::ReadCallOnWriteFrame);
Err(ErrorKind::ReadCallOnWriteFrame)
}
_ => Ok(()),
}
Expand Down Expand Up @@ -248,12 +249,12 @@ impl<'a, V: VectorTrait<u8>> ModbusFrame<'a, V> {
data: slice::from_ref(&0u8),
}),
_ => {
self.set_modbus_error_if_unset(&ErrorKind::IllegalDataValue);
self.set_modbus_error_if_unset(&ErrorKind::IllegalDataValue)?;
return Err(ErrorKind::IllegalDataValue);
}
};

return Ok(val);
Ok(val)
}
MODBUS_SET_HOLDING => {
// func 6
Expand All @@ -265,7 +266,7 @@ impl<'a, V: VectorTrait<u8>> ModbusFrame<'a, V> {
data: &self.buf[self.frame_start + 4..self.frame_start + 6],
});

return Ok(write);
Ok(write)
}
MODBUS_SET_COILS_BULK => {
// funcs 15 & 16
Expand All @@ -279,7 +280,7 @@ impl<'a, V: VectorTrait<u8>> ModbusFrame<'a, V> {
data: &self.buf[data_start..data_start + bytes as usize],
});

return Ok(write);
Ok(write)
}
MODBUS_SET_HOLDINGS_BULK => {
// funcs 15 & 16
Expand All @@ -293,14 +294,14 @@ impl<'a, V: VectorTrait<u8>> ModbusFrame<'a, V> {
data: &self.buf[data_start..data_start + bytes as usize],
});

return Ok(write);
Ok(write)
}
MODBUS_GET_HOLDINGS | MODBUS_GET_INPUTS | MODBUS_GET_COILS | MODBUS_GET_DISCRETES => {
return Err(ErrorKind::ReadCallOnWriteFrame);
Err(ErrorKind::ReadCallOnWriteFrame)
}
_ => {
self.set_modbus_error_if_unset(&ErrorKind::IllegalFunction);
return Err(ErrorKind::IllegalFunction);
self.set_modbus_error_if_unset(&ErrorKind::IllegalFunction)?;
Err(ErrorKind::IllegalFunction)
}
}
}
Expand All @@ -310,7 +311,7 @@ impl<'a, V: VectorTrait<u8>> ModbusFrame<'a, V> {
write_result: Result<(), ErrorKind>,
) -> Result<(), ErrorKind> {
match write_result {
Ok(_) => {
Ok(()) => {
match self.func {
MODBUS_SET_COIL
| MODBUS_SET_HOLDING
Expand All @@ -327,18 +328,16 @@ impl<'a, V: VectorTrait<u8>> ModbusFrame<'a, V> {
.extend(&self.buf[self.frame_start..self.frame_start + 6])
}
MODBUS_GET_HOLDINGS | MODBUS_GET_INPUTS | MODBUS_GET_COILS
| MODBUS_GET_DISCRETES => {
return Err(ErrorKind::ReadCallOnWriteFrame);
}
| MODBUS_GET_DISCRETES => Err(ErrorKind::ReadCallOnWriteFrame),
_ => {
self.set_modbus_error_if_unset(&ErrorKind::IllegalFunction);
return Err(ErrorKind::IllegalFunction);
self.set_modbus_error_if_unset(&ErrorKind::IllegalFunction)?;
Err(ErrorKind::IllegalFunction)
}
}
}
Err(e) if e.is_modbus_error() => {
self.set_modbus_error_if_unset(&e);
return Ok(());
self.set_modbus_error_if_unset(&e)?;
Ok(())
}
Err(e) => Err(e),
}
Expand Down Expand Up @@ -414,9 +413,7 @@ impl<'a, V: VectorTrait<u8>> ModbusFrame<'a, V> {
MODBUS_SET_COIL
| MODBUS_SET_HOLDING
| MODBUS_SET_COILS_BULK
| MODBUS_SET_HOLDINGS_BULK => {
return Err(ErrorKind::WriteCallOnReadFrame);
}
| MODBUS_SET_HOLDINGS_BULK => Err(ErrorKind::WriteCallOnReadFrame),
_ => Ok(()),
}
}
Expand Down Expand Up @@ -451,7 +448,7 @@ impl<'a, V: VectorTrait<u8>> ModbusFrame<'a, V> {
// extend with data_len so we can get the extra space as &mut slice for Read struct
let current_length = self.response.len();
let new_length = current_length + data_len as usize;
self.response.resize(new_length, 0u8);
self.response.resize(new_length, 0u8)?;

return Ok(Read::Bits(ReadBits {
address: self.reg,
Expand All @@ -477,7 +474,7 @@ impl<'a, V: VectorTrait<u8>> ModbusFrame<'a, V> {
// extend with data_len so we can get the extra space as &mut slice for Read struct
let current_length = self.response.len();
let new_length = current_length + data_len as usize;
self.response.resize(new_length, 0u8);
self.response.resize(new_length, 0u8)?;

return Ok(Read::Words(ReadWords {
address: self.reg,
Expand All @@ -488,12 +485,10 @@ impl<'a, V: VectorTrait<u8>> ModbusFrame<'a, V> {
MODBUS_SET_COIL
| MODBUS_SET_HOLDING
| MODBUS_SET_COILS_BULK
| MODBUS_SET_HOLDINGS_BULK => {
return Err(ErrorKind::WriteCallOnReadFrame);
}
| MODBUS_SET_HOLDINGS_BULK => Err(ErrorKind::WriteCallOnReadFrame),
_ => {
self.set_modbus_error_if_unset(&ErrorKind::IllegalFunction);
return Err(ErrorKind::IllegalFunction);
self.set_modbus_error_if_unset(&ErrorKind::IllegalFunction)?;
Err(ErrorKind::IllegalFunction)
}
}
}
Expand All @@ -504,31 +499,23 @@ impl<'a, V: VectorTrait<u8>> ModbusFrame<'a, V> {
read_result: Result<(), ErrorKind>,
) -> Result<(), ErrorKind> {
match read_result {
Ok(_) => {
match self.func {
MODBUS_GET_COILS | MODBUS_GET_DISCRETES | MODBUS_GET_HOLDINGS
| MODBUS_GET_INPUTS => {
return Ok(());
}
MODBUS_SET_COIL
| MODBUS_SET_HOLDING
| MODBUS_SET_COILS_BULK
| MODBUS_SET_HOLDINGS_BULK => {
return Err(ErrorKind::WriteCallOnReadFrame);
}
_ => {
self.set_modbus_error_if_unset(&ErrorKind::IllegalFunction);
return Ok(());
}
};
}
Ok(()) => match self.func {
MODBUS_GET_COILS | MODBUS_GET_DISCRETES | MODBUS_GET_HOLDINGS
| MODBUS_GET_INPUTS => Ok(()),
MODBUS_SET_COIL
| MODBUS_SET_HOLDING
| MODBUS_SET_COILS_BULK
| MODBUS_SET_HOLDINGS_BULK => Err(ErrorKind::WriteCallOnReadFrame),
_ => {
self.set_modbus_error_if_unset(&ErrorKind::IllegalFunction)?;
Ok(())
}
},
Err(e) if e.is_modbus_error() => {
self.set_modbus_error_if_unset(&e);
return Ok(());
}
Err(e) => {
return Err(e);
self.set_modbus_error_if_unset(&e)?;
Ok(())
}
Err(e) => Err(e),
}
}

Expand Down Expand Up @@ -704,7 +691,11 @@ impl<'a, V: VectorTrait<u8>> ModbusFrame<'a, V> {

/// If the error field on the [`ModbusFrame`] isn't already set this function will set it and
/// resize the response buffer to what's expected by [`ModbusFrame::finalize_response`]
pub fn set_modbus_error_if_unset(&mut self, err: &ErrorKind) {
///
/// # Panics
///
/// Should not panic
pub fn set_modbus_error_if_unset(&mut self, err: &ErrorKind) -> Result<(), ErrorKind> {
if self.error == 0 && err.is_modbus_error() {
// leave 0 bytes for RTU/ASCII, leave 4 bytes for TCP/UDP (Transaction ID and Protocol ID)
let len_leave_before_finalize = if self.proto == ModbusProto::TcpUdp {
Expand All @@ -713,11 +704,12 @@ impl<'a, V: VectorTrait<u8>> ModbusFrame<'a, V> {
0
};

self.response.resize(len_leave_before_finalize, 0);
self.response.resize(len_leave_before_finalize, 0)?;
self.error = err
.to_modbus_error()
.expect("the outer if statement checks for this");
}
Ok(())
}
}

Expand Down

0 comments on commit d09ce90

Please sign in to comment.