plc_comm_hostlink/
error.rs1use thiserror::Error;
2
3const ERROR_CODE_MESSAGES: &[(&str, &str)] = &[
4 ("E0", "Abnormal device No."),
5 ("E1", "Abnormal command"),
6 ("E2", "Program not registered"),
7 ("E4", "Write disabled"),
8 ("E5", "Unit error"),
9 ("E6", "No comments"),
10];
11
12pub fn decode_error_code(code: &str) -> &'static str {
13 ERROR_CODE_MESSAGES
14 .iter()
15 .find_map(|(key, value)| (*key == code).then_some(*value))
16 .unwrap_or("Unknown error")
17}
18
19#[derive(Debug, Error)]
20pub enum HostLinkError {
21 #[error("{0}")]
22 Protocol(String),
23 #[error("{0}")]
24 Connection(String),
25 #[error("{code}: {message} (response={response:?})")]
26 Plc {
27 code: String,
28 response: String,
29 message: &'static str,
30 },
31}
32
33impl HostLinkError {
34 pub fn protocol(message: impl Into<String>) -> Self {
35 Self::Protocol(message.into())
36 }
37
38 pub fn connection(message: impl Into<String>) -> Self {
39 Self::Connection(message.into())
40 }
41
42 pub fn plc(code: impl Into<String>, response: impl Into<String>) -> Self {
43 let code = code.into();
44 Self::Plc {
45 message: decode_error_code(&code),
46 response: response.into(),
47 code,
48 }
49 }
50}
51
52impl From<std::io::Error> for HostLinkError {
53 fn from(value: std::io::Error) -> Self {
54 Self::connection(value.to_string())
55 }
56}