1use crate::types::Protocol;
14use async_trait::async_trait;
15use std::collections::HashMap;
16use std::fmt;
17use std::sync::Arc;
18
19#[derive(Debug, Clone)]
21pub struct Command {
22 pub device_id: String,
24 pub name: String,
26 pub payload: Vec<u8>,
28 pub request_id: Option<String>,
31}
32
33impl Command {
34 pub fn new(device_id: impl Into<String>, name: impl Into<String>, payload: Vec<u8>) -> Self {
36 Self {
37 device_id: device_id.into(),
38 name: name.into(),
39 payload,
40 request_id: None,
41 }
42 }
43
44 pub fn text(device_id: impl Into<String>, name: impl Into<String>, text: &str) -> Self {
46 Self::new(device_id, name, text.as_bytes().to_vec())
47 }
48}
49
50#[derive(Debug, Clone, PartialEq, Eq)]
52pub enum CommandError {
53 NoRoute(String),
55 Unreachable(String),
57 Transport(String),
59}
60
61impl fmt::Display for CommandError {
62 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
63 match self {
64 CommandError::NoRoute(d) => write!(f, "设备 {d} 无下行路由"),
65 CommandError::Unreachable(d) => write!(f, "设备 {d} 不可达(离线或未订阅指令主题)"),
66 CommandError::Transport(e) => write!(f, "下行传输错误: {e}"),
67 }
68 }
69}
70
71impl std::error::Error for CommandError {}
72
73#[async_trait]
75pub trait Downlink: Send + Sync {
76 fn protocol(&self) -> Protocol;
78 async fn dispatch(&self, cmd: &Command) -> Result<u32, CommandError>;
80}
81
82#[derive(Default)]
87pub struct CommandRouter {
88 downlinks: HashMap<Protocol, Arc<dyn Downlink>>,
89 routes: HashMap<String, Protocol>,
90}
91
92impl CommandRouter {
93 pub fn new() -> Self {
95 Self::default()
96 }
97
98 pub fn register_downlink(&mut self, downlink: Arc<dyn Downlink>) {
100 self.downlinks.insert(downlink.protocol(), downlink);
101 }
102
103 pub fn bind_route(&mut self, device_id: impl Into<String>, protocol: Protocol) {
105 self.routes.insert(device_id.into(), protocol);
106 }
107
108 pub fn route_count(&self) -> usize {
110 self.routes.len()
111 }
112
113 pub async fn dispatch(&self, cmd: &Command) -> Result<u32, CommandError> {
115 let protocol = self
116 .routes
117 .get(&cmd.device_id)
118 .copied()
119 .ok_or_else(|| CommandError::NoRoute(cmd.device_id.clone()))?;
120 let downlink = self
121 .downlinks
122 .get(&protocol)
123 .ok_or_else(|| CommandError::NoRoute(cmd.device_id.clone()))?;
124 downlink.dispatch(cmd).await
125 }
126}
127
128#[cfg(test)]
129mod tests {
130 use super::*;
131 use parking_lot::Mutex;
132
133 struct MockDownlink {
135 protocol: Protocol,
136 seen: Arc<Mutex<Vec<Command>>>,
137 deliver: u32,
138 }
139
140 #[async_trait]
141 impl Downlink for MockDownlink {
142 fn protocol(&self) -> Protocol {
143 self.protocol
144 }
145 async fn dispatch(&self, cmd: &Command) -> Result<u32, CommandError> {
146 self.seen.lock().push(cmd.clone());
147 if self.deliver == 0 {
148 Err(CommandError::Unreachable(cmd.device_id.clone()))
149 } else {
150 Ok(self.deliver)
151 }
152 }
153 }
154
155 #[tokio::test]
156 async fn routes_to_bound_protocol() {
157 let seen = Arc::new(Mutex::new(Vec::new()));
158 let mut router = CommandRouter::new();
159 router.register_downlink(Arc::new(MockDownlink {
160 protocol: Protocol::Mqtt,
161 seen: seen.clone(),
162 deliver: 1,
163 }));
164 router.bind_route("dev-1", Protocol::Mqtt);
165
166 let n = router
167 .dispatch(&Command::text("dev-1", "set", "on"))
168 .await
169 .unwrap();
170 assert_eq!(n, 1);
171 assert_eq!(seen.lock().len(), 1);
172 assert_eq!(seen.lock()[0].name, "set");
173 }
174
175 #[tokio::test]
176 async fn unrouted_device_errors() {
177 let router = CommandRouter::new();
178 let err = router
179 .dispatch(&Command::text("ghost", "x", "y"))
180 .await
181 .unwrap_err();
182 assert_eq!(err, CommandError::NoRoute("ghost".to_string()));
183 }
184
185 #[tokio::test]
186 async fn no_receiver_is_unreachable() {
187 let seen = Arc::new(Mutex::new(Vec::new()));
188 let mut router = CommandRouter::new();
189 router.register_downlink(Arc::new(MockDownlink {
190 protocol: Protocol::Mqtt,
191 seen,
192 deliver: 0,
193 }));
194 router.bind_route("dev-1", Protocol::Mqtt);
195 let err = router
196 .dispatch(&Command::text("dev-1", "set", "on"))
197 .await
198 .unwrap_err();
199 assert_eq!(err, CommandError::Unreachable("dev-1".to_string()));
200 }
201}