1use serde::{Deserialize, Serialize};
7use std::collections::HashMap;
8
9#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
11#[serde(rename_all = "lowercase")]
12#[derive(Default)]
13pub enum BusType {
14 System,
16 #[default]
18 Session,
19}
20
21impl std::fmt::Display for BusType {
22 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
23 match self {
24 BusType::System => write!(f, "system"),
25 BusType::Session => write!(f, "session"),
26 }
27 }
28}
29
30#[derive(Debug, Clone, Serialize, Deserialize)]
34#[serde(untagged)]
35pub enum DbusValue {
36 String(String),
38 Bool(bool),
40 Int32(i32),
42 Uint32(u32),
44 Int64(i64),
46 Uint64(u64),
48 Double(f64),
50 Array(Vec<DbusValue>),
52 Dict(HashMap<String, DbusValue>),
54 Bytes(Vec<u8>),
56 ObjectPath(String),
58 Variant(Box<DbusValue>),
60}
61
62impl DbusValue {
63 pub fn string(s: impl Into<String>) -> Self {
65 DbusValue::String(s.into())
66 }
67
68 pub fn object_path(path: impl Into<String>) -> Self {
70 DbusValue::ObjectPath(path.into())
71 }
72
73 pub fn variant(inner: DbusValue) -> Self {
75 DbusValue::Variant(Box::new(inner))
76 }
77
78 pub fn as_str(&self) -> Option<&str> {
80 match self {
81 DbusValue::String(s) | DbusValue::ObjectPath(s) => Some(s),
82 _ => None,
83 }
84 }
85
86 pub fn as_i64(&self) -> Option<i64> {
88 match self {
89 DbusValue::Int32(n) => Some(*n as i64),
90 DbusValue::Int64(n) => Some(*n),
91 DbusValue::Uint32(n) => Some(*n as i64),
92 _ => None,
93 }
94 }
95
96 pub fn as_bool(&self) -> Option<bool> {
98 match self {
99 DbusValue::Bool(b) => Some(*b),
100 _ => None,
101 }
102 }
103}
104
105#[derive(Debug, Clone, Serialize, Deserialize)]
107pub struct DbusCallRequest {
108 #[serde(default)]
110 pub bus: BusType,
111
112 pub destination: String,
114
115 pub path: String,
117
118 pub interface: String,
120
121 pub method: String,
123
124 #[serde(default)]
126 pub args: Vec<DbusValue>,
127
128 #[serde(default)]
130 pub timeout_ms: u32,
131}
132
133impl DbusCallRequest {
134 pub fn new(
136 destination: impl Into<String>,
137 path: impl Into<String>,
138 interface: impl Into<String>,
139 method: impl Into<String>,
140 ) -> Self {
141 Self {
142 bus: BusType::Session,
143 destination: destination.into(),
144 path: path.into(),
145 interface: interface.into(),
146 method: method.into(),
147 args: Vec::new(),
148 timeout_ms: 0,
149 }
150 }
151
152 pub fn bus(mut self, bus: BusType) -> Self {
154 self.bus = bus;
155 self
156 }
157
158 pub fn arg(mut self, value: DbusValue) -> Self {
160 self.args.push(value);
161 self
162 }
163
164 pub fn timeout(mut self, ms: u32) -> Self {
166 self.timeout_ms = ms;
167 self
168 }
169}
170
171#[derive(Debug, Clone, Serialize, Deserialize)]
173pub struct DbusGetPropertyRequest {
174 #[serde(default)]
176 pub bus: BusType,
177
178 pub destination: String,
180
181 pub path: String,
183
184 pub interface: String,
186
187 pub property: String,
189}
190
191#[derive(Debug, Clone, Serialize, Deserialize)]
193pub struct DbusSetPropertyRequest {
194 #[serde(default)]
196 pub bus: BusType,
197
198 pub destination: String,
200
201 pub path: String,
203
204 pub interface: String,
206
207 pub property: String,
209
210 pub value: DbusValue,
212}
213
214#[derive(Debug, Clone, Serialize, Deserialize)]
216pub struct DbusSubscribeRequest {
217 #[serde(default)]
219 pub bus: BusType,
220
221 #[serde(default)]
223 pub sender: Option<String>,
224
225 #[serde(default)]
227 pub path: Option<String>,
228
229 pub interface: String,
231
232 pub signal: String,
234}
235
236#[derive(Debug, Clone, Serialize, Deserialize)]
238pub struct DbusCallResponse {
239 pub values: Vec<DbusValue>,
241}
242
243impl DbusCallResponse {
244 pub fn new(values: Vec<DbusValue>) -> Self {
246 Self { values }
247 }
248
249 pub fn empty() -> Self {
251 Self { values: Vec::new() }
252 }
253
254 pub fn first(&self) -> Option<&DbusValue> {
256 self.values.first()
257 }
258}
259
260#[derive(Debug, Clone, Serialize, Deserialize)]
262pub struct DbusError {
263 pub name: String,
265
266 pub message: String,
268}
269
270impl DbusError {
271 pub fn new(name: impl Into<String>, message: impl Into<String>) -> Self {
273 Self {
274 name: name.into(),
275 message: message.into(),
276 }
277 }
278
279 pub fn access_denied(resource: &str) -> Self {
281 Self::new(
282 "org.freedesktop.DBus.Error.AccessDenied",
283 format!("Access denied to {resource}"),
284 )
285 }
286
287 pub fn service_unknown(service: &str) -> Self {
289 Self::new(
290 "org.freedesktop.DBus.Error.ServiceUnknown",
291 format!("Service {service} is not available"),
292 )
293 }
294
295 pub fn method_not_found(interface: &str, method: &str) -> Self {
297 Self::new(
298 "org.freedesktop.DBus.Error.UnknownMethod",
299 format!("Method {interface}.{method} not found"),
300 )
301 }
302}
303
304impl std::fmt::Display for DbusError {
305 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
306 write!(f, "{}: {}", self.name, self.message)
307 }
308}
309
310impl std::error::Error for DbusError {}
311
312#[derive(Debug, Clone, Serialize, Deserialize)]
314pub struct DbusSignal {
315 pub sender: String,
317
318 pub path: String,
320
321 pub interface: String,
323
324 pub signal: String,
326
327 pub args: Vec<DbusValue>,
329}
330
331#[derive(Debug, Clone, Serialize, Deserialize)]
333#[serde(tag = "type", rename_all = "snake_case")]
334pub enum DbusRequest {
335 Call(DbusCallRequest),
337
338 GetProperty(DbusGetPropertyRequest),
340
341 SetProperty(DbusSetPropertyRequest),
343
344 Subscribe(DbusSubscribeRequest),
346
347 Unsubscribe {
349 subscription_id: String,
351 },
352}
353
354#[derive(Debug, Clone, Serialize, Deserialize)]
356#[serde(tag = "type", rename_all = "snake_case")]
357pub enum DbusResponse {
358 Return(DbusCallResponse),
360
361 Property { value: DbusValue },
363
364 Subscribed {
366 subscription_id: String,
368 },
369
370 Unsubscribed,
372
373 Error(DbusError),
375}
376
377impl DbusResponse {
378 pub fn return_values(values: Vec<DbusValue>) -> Self {
380 DbusResponse::Return(DbusCallResponse::new(values))
381 }
382
383 pub fn error(name: impl Into<String>, message: impl Into<String>) -> Self {
385 DbusResponse::Error(DbusError::new(name, message))
386 }
387
388 pub fn access_denied(resource: &str) -> Self {
390 DbusResponse::Error(DbusError::access_denied(resource))
391 }
392}
393
394#[cfg(test)]
395mod tests {
396 use super::*;
397
398 #[test]
399 fn test_dbus_value_serialization() -> serde_json::Result<()> {
400 let value = DbusValue::Dict(HashMap::from([
401 ("app_name".to_owned(), DbusValue::String("test".to_owned())),
402 ("urgency".to_owned(), DbusValue::Uint32(1)),
403 ]));
404
405 let json = serde_json::to_string(&value)?;
406 let parsed: DbusValue = serde_json::from_str(&json)?;
407
408 match parsed {
409 DbusValue::Dict(map) => {
410 assert!(map.contains_key("app_name"));
411 assert!(map.contains_key("urgency"));
412 }
413 _ => panic!("Expected Dict"),
414 }
415 Ok(())
416 }
417
418 #[test]
419 fn test_call_request_builder() {
420 let request = DbusCallRequest::new(
421 "org.freedesktop.Notifications",
422 "/org/freedesktop/Notifications",
423 "org.freedesktop.Notifications",
424 "Notify",
425 )
426 .bus(BusType::Session)
427 .arg(DbusValue::String("app".to_owned()))
428 .arg(DbusValue::Uint32(0))
429 .timeout(5000);
430
431 assert_eq!(request.method, "Notify");
432 assert_eq!(request.args.len(), 2);
433 assert_eq!(request.timeout_ms, 5000);
434 }
435
436 #[test]
437 fn test_request_serialization() -> serde_json::Result<()> {
438 let request = DbusRequest::Call(DbusCallRequest::new(
439 "org.example.Service",
440 "/org/example/Object",
441 "org.example.Interface",
442 "Method",
443 ));
444
445 let json = serde_json::to_string(&request)?;
446 assert!(json.contains("\"type\":\"call\""));
447
448 let parsed: DbusRequest = serde_json::from_str(&json)?;
449 match parsed {
450 DbusRequest::Call(call) => {
451 assert_eq!(call.destination, "org.example.Service");
452 }
453 _ => panic!("Expected Call"),
454 }
455 Ok(())
456 }
457
458 #[test]
459 fn test_response_serialization() -> serde_json::Result<()> {
460 let response = DbusResponse::return_values(vec![DbusValue::Uint32(42)]);
461
462 let json = serde_json::to_string(&response)?;
463 assert!(json.contains("\"type\":\"return\""));
464 Ok(())
465 }
466
467 #[test]
468 fn test_error_creation() {
469 let err = DbusError::access_denied("dbus:session:org.example:Method");
470 assert!(err.name.contains("AccessDenied"));
471 assert!(err.message.contains("org.example"));
472 }
473}