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
use adapters::adapter::Adapter;
use adapters::adapter::DiscoveryAdapter;
use adapters::errors::Error;
use adapters::PlatformDependentAdapter;

#[derive(Clone, Copy, Debug)]
pub enum ServiceProtocol {
    IPv4 = 0,
    IPv6 = 1,
    Unspecified = -1,
}

#[derive(Debug)]
pub struct ServiceInfo {
    pub address: Option<String>,
    pub domain: Option<String>,
    pub host_name: Option<String>,
    pub interface: i32,
    pub name: Option<String>,
    pub port: u16,
    pub protocol: ServiceProtocol,
    pub type_name: Option<String>,
    pub txt: Option<String>,
}

pub struct DiscoveryListeners<'a> {
    pub on_service_discovered: Option<&'a dyn Fn(ServiceInfo)>,
    pub on_all_discovered: Option<&'a dyn Fn()>,
}

pub struct ResolveListeners<'a> {
    pub on_service_resolved: Option<&'a dyn Fn(ServiceInfo)>,
}

pub struct DiscoveryManager {
    adapter: Box<dyn DiscoveryAdapter>,
}

impl DiscoveryManager {
    pub fn new() -> Self {
        Default::default()
    }

    pub fn discover_services(
        &self,
        service_type: &str,
        listeners: DiscoveryListeners,
    ) -> Result<(), Error> {
        self.adapter.start_discovery(service_type, listeners)
    }

    pub fn resolve_service(&self, service: ServiceInfo, listeners: ResolveListeners) {
        self.adapter.resolve(service, listeners);
    }

    pub fn stop_service_discovery(&self) {
        self.adapter.stop_discovery();
    }
}

impl Default for DiscoveryManager {
    fn default() -> Self {
        let adapter: Box<dyn DiscoveryAdapter> = Box::new(PlatformDependentAdapter::new());

        DiscoveryManager { adapter }
    }
}