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
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
use std::net::SocketAddr;
use futures::Future;
use futures::future::{ok, Either, err};
use futures::sync::mpsc::{Sender, Receiver, channel as mpsc_channel};
use futures::sync::oneshot::channel;
use tokio::prelude::*;
use tokio_core::reactor::Core;

use nt_packet::ClientMessage;
use crate::proto::*;
use crate::proto::types::*;
use crate::proto::types::rpc::{RPCResponseBody, RPCExecutionBody};

use std::sync::{Arc, Mutex};
use std::thread;
use std::collections::HashMap;

use failure::{Error, err_msg};

pub(crate) mod state;
mod conn;
mod handler;
/// Module containing definitions for working with NetworkTables entries
mod entry;
mod callback;

use self::handler::*;
use self::state::*;
use self::conn::Connection;

pub use self::entry::*;
pub use self::callback::CallbackType;

/// Core struct representing a connection to a NetworkTables server
pub struct NetworkTables {
    /// Contains the initial connection future with a reference to the framed NT codec
    state: Arc<Mutex<State>>,
    end_tx: Sender<()>,
}

/// Handle to the reactor backing a given `NetworkTables`
pub struct Handle {
    end_tx: Sender<()>
}

impl Handle {
    /// Instructs the backing reactor to disconnect from the remote
    pub fn disconnect(&mut self) {
        self.end_tx.clone().send(()).wait().unwrap();
    }
}

impl NetworkTables {
    /// Performs the initial connection process to the given `target`.
    /// Assumes that target is a valid, running NetworkTables server.
    /// Returns a new [`NetworkTables`] once a connection has been established.
    /// If any errors are returned when trying to perform the connection, returns an [`Err`]
    pub fn connect(client_name: &'static str, target: SocketAddr) -> crate::Result<NetworkTables> {
        let state = Arc::new(Mutex::new(State::new()));
        state.lock().unwrap().set_connection_state(ConnectionState::Connecting);
        let (tx, rx) = channel();

        let (end_tx, end_rx) = mpsc_channel(1);

        let thread_state = state.clone();
        let _ = thread::spawn(move || {
            let mut core = Core::new().unwrap();
            let handle = core.handle();
            let state = thread_state;
            {
                state.lock().unwrap().set_handle(handle.clone().remote().clone());
            }

            core.run(Connection::new(&handle, &target, client_name, state, tx, end_rx)).unwrap();
        });

        rx.wait()?;

        {
            while state.lock().unwrap().connection_state().connecting() {}
        }

        Ok(NetworkTables {
            state,
            end_tx,
        })
    }

    /// Returns a handle to this client
    /// Allows indirect termination of the remote connection without moving `self` into closures
    pub fn handle(&self) -> Handle {
        Handle {
            end_tx: self.end_tx.clone()
        }
    }

    /// Initiates an RPC request for the given id.
    /// `cb` will be called with the response body when the server has processed the request and returned
    pub fn call_rpc<F>(&mut self, id: u16, args: RPCExecutionBody, cb: F) -> Result<(), ::failure::Error>
        where F: FnOnce(RPCResponseBody) + Send + 'static
    {
        let entry = self.get_entry(id);
        ensure!(entry.value().entry_type() == EntryType::RPCDef, "The given entry must be of type RPCDef");
        let mut state = self.state.lock().unwrap();
        state.call_rpc(entry, args, cb);

        Ok(())
    }

    /// Registers the given closure `cb` as a callback to be called for [`CallbackType`] `action`
    /// When `action` occurs due to either network or user events, all callbacks registered for that type will be called
    pub fn add_callback<F>(&mut self, action: CallbackType, cb: F)
        where F: FnMut(&EntryData) + Send + 'static
    {
        let mut state = self.state.lock().unwrap();
        state.callbacks_mut().insert(action, Box::new(cb));
    }

    /// Returns a clone of all the entries this client currently knows of.
    pub fn entries(&self) -> HashMap<u16, EntryData> {
        self.state.lock().unwrap().entries()
    }

    /// Returns an [`Entry`] for the given `id`
    /// The underlying value of the entry cannot be mutated.
    pub fn get_entry(&self, id: u16) -> Entry {
        Entry::new(self, id)
    }

    /// Returns an [`EntryMut`] for the given `id`
    /// The underlying value of the entry can be mutated through the given [`EntryMut`]
    pub fn get_entry_mut(&mut self, id: u16) -> EntryMut {
        EntryMut::new(self, id)
    }

    /// Creates a new entry with data contained in `data`.
    /// Returns the id of the new entry, once the server has assigned it
    pub fn create_entry(&mut self, data: EntryData) -> u16 {
        let rx = self.state.lock().unwrap().create_entry(data);
        let id = rx.wait().next().unwrap().unwrap();
        id
    }

    /// Attempts to find an entry with the name `name`
    ///
    /// Returns Some with the id if an entry exists with that name. Returns None if there isn't an entry with that name
    pub fn find_id_by_name(&self, name: &str) -> Option<u16> {
        self.entries().iter()
            .filter(|&(_, data)| data.name == name.to_owned())
            .map(|(id, _)| *id)
            .nth(0)
    }

    /// Find all the entries of type `ty`
    /// Returns a Vec of entry ids
    pub fn find_entries_by_type(&self, ty: EntryType) -> Vec<u16> {
        self.entries()
            .iter()
            .filter(|&(_, data)| data.entry_type() == ty)
            .map(|(id, _)| *id)
            .collect()
    }

    /// Deletes the entry with id `id` from the server the client is currently connected to
    /// Must be used with care. Cannot be undone
    pub(crate) fn delete_entry(&mut self, id: u16) {
        self.state.lock().unwrap().delete_entry(id);
    }

    /// Deletes all entries from the server this client is currently connected to
    /// Must be used with care. Cannot be undone
    pub fn delete_all_entries(&mut self) {
        self.state.lock().unwrap().delete_all_entries();
    }

    /// Updates the value of the entry with id `id`.
    /// The updated value of the entry will match `new_value`
    pub(crate) fn update_entry(&mut self, id: u16, new_value: EntryValue) {
        self.state.lock().unwrap().update_entry(id, new_value);
    }

    /// Updates the flags of the entry with id `id`.
    pub(crate) fn update_entry_flags(&mut self, id: u16, flags: u8) {
        self.state.lock().unwrap().update_entry_flags(id, flags);
    }

    /// Checks if the client is actively connected to an NT server
    /// true if the 3-way handshake has been completed, and the client is fully synchronized
    pub fn connected(&self) -> bool {
        self.state.lock().unwrap().connection_state().connected()
    }
}

impl Drop for NetworkTables {
    #[allow(unused_must_use)]
    fn drop(&mut self) {
        let _ = self.end_tx.clone().send(()).wait();
    }
}

#[doc(hidden)]
pub(crate) fn send_packets(tx: impl Sink<SinkItem=Box<ClientMessage>, SinkError=Error>, rx: Receiver<Box<ClientMessage>>) -> impl Future<Item=(), Error=()> {
    debug!("Spawned packet send loop");
    rx
        .fold(tx, |tx, packet| tx.send(packet).map_err(|e| error!("Packet sender encountered an error: {}", e)))
        .map(drop)
}

#[doc(hidden)]
pub fn poll_socket(state: Arc<Mutex<State>>, rx: impl Stream<Item=Packet, Error=Error>, tx: Sender<Box<ClientMessage>>, end_rx: Receiver<()>) -> impl Future<Item=(), Error=Error> {
    debug!("Spawned socket poll");

    // This function will be called as new packets arrive. Has to be `fold` to maintain ownership over the write half of our codec
    rx.map(Either::A).select(end_rx.map(Either::B).map_err(|_| err_msg("Error from termination channel")))
        .fold(tx, move |tx, packet| {
            match packet {
                Either::A(packet) => match handle_packet(packet, &state, tx.clone()) {
                    Ok(Some(packet)) => Either::A(tx.send(packet).map_err(|e| err_msg(format!("{}", e)))),
                    Ok(None) => Either::B(ok(tx)),
                    Err(e) => Either::B(err(e.into())),
                }
                Either::B(_) => Either::B(err(err_msg("NetworkTables dropped or disconnected.")))
            }
        })
        .map_err(|e| {
            if &format!("{}", e) == "NetworkTables dropped or disconnected." {
                info!("Remote socket closed.");
                return e;
            }
            error!("handle_packet encountered an error: {}", e);
            e
        })
        .map(drop)
}