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
//! Kernkomponente dieser Anwendung
//!
use api;
use bincode;
use prelude::*;
use std::fs::File;
use std::io::Write;
use std::path::PathBuf;


/// Struktur der Server Komponente
#[derive(Clone, Debug)]
pub struct Server {
    /// Wartungsintervall in Tagen
    pub service_interval: u32,
    /// Liste der Sensoren die dieser Server verwaltet
    pub sensors: SensorList,
    pub configuration_path: Option<PathBuf>,
    pub runtime_info_path: Option<PathBuf>,
}

impl Default for Server {
    /// Default Konfiguration des Servers
    ///
    /// Die `default()` Konfiguration des Servers mit den sinnvollsten Werten.
    ///
    fn default() -> Self {
        let sensors: SensorList = vec![
            Arc::new(RwLock::new(Box::new(RaGasCONO2Mod::new()))),
            Arc::new(RwLock::new(Box::new(MetzConnectCI4::new()))),
            Arc::new(RwLock::new(Box::new(TestSensor::new()))),
        ];
        Server {
            service_interval: 365,
            sensors: sensors,
            // zones: vec![],
            configuration_path: None,
            runtime_info_path: None,
        }
    }
}

impl Server {
    /// Erstellt eine neue Server Instanz
    ///
    /// Die `new()` Funktion erstellt eine "leere" neue Server Instanz. Das heist alle Member sind
    /// Null oder leer, entsprechenden ihres Datentypes.
    /// Die `default()` Implementation hingegen liefert einen "kompletten" Server. Das bedeutet
    /// alle Member des Servers sind mit sinnvollen default Werten gefüllt. So sind zum
    /// Beispiel alle unterstützten Sensoren, Messzellen jeweils einmal verfügbar.
    ///
    /// # Example
    ///
    /// ```rust
    /// use xmz_server::prelude::*;
    ///
    /// let server = Server::default();
    /// assert_eq!(server.get_sensors().len(), 3);
    /// ```
    ///
    pub fn new() -> Self {
        Server {
            service_interval: 0,
            sensors: vec![],
            ..Default::default()
        }
    }

    /// Liefert eine Referenz auf die Liste der Sensoren
    ///
    /// # Example
    ///
    /// ```rust
    /// use xmz_server::prelude::*;
    ///
    /// let server = Server::default();
    /// assert_eq!(server.get_sensors().len(), 3);
    /// ```
    pub fn get_sensors(&self) -> Vec<Arc<RwLock<BoxedSensor>>> {
        self.sensors.clone()
    }

    ///
    /// # Example
    ///
    /// ```rust
    /// use xmz_server::prelude::*;
    ///
    /// let server = Server::default();
    /// assert_eq!(server.get_sensors().len(), 3);
    /// ```
    pub fn get_sensor(&self, num: usize) -> Option<&Arc<RwLock<BoxedSensor>>> {
        let sensor = self.sensors.get(num);
        sensor
    }

    ///
    /// # Example
    ///
    /// ```rust
    /// use xmz_server::prelude::*;
    ///
    /// let server = Server::default();
    /// assert_eq!(server.get_sensors().len(), 3);
    /// ```
    pub fn add_sensor(&mut self, sensor: BoxedSensor) {
        self.sensors.push(Arc::new(RwLock::new(sensor)));
    }

    /// Serialize Server Instanz in das Bincode format
    ///
    /// # Example
    ///
    /// ```rust
    /// use xmz_server::prelude::*;
    ///
    /// let server = Server::default();
    /// assert_eq!(server.get_sensors().len(), 3);
    /// ```
    ///
    pub fn serialize_to_bincode(&self) -> Result<Vec<u8>, ServerError> {
        let server: runtime_info::Server = self.into();
        debug!("{:?}", &server);

        match bincode::serialize(&server) {
            Ok(data) => {
                debug!("{:?}", &data);
                Ok(data)
            },
            Err(err) => Err(ServerError::Bincode(err)),
        }
    }

    fn store_runtime_information(&self) -> Result<(), ServerError> {
        match &self.runtime_info_path {
            Some(path) => {
                info!("Create runtime info at: {:?}", path);
                let mut buffer = File::create(path)?;

                info!("Speichere Server Instanz im bincode Format");
                let data = &self.serialize_to_bincode()?;
                buffer.write(data)?;

                Ok(())
            }
            None => Err(ServerError::RuntimePathNotSet),
        }
    }

    /// Aktualisiert der Reihe nach jeden Sensor
    ///
    /// # Example
    ///
    /// ```rust
    /// use xmz_server::prelude::*;
    ///
    /// let server = Server::default();
    /// assert_eq!(server.get_sensors().len(), 3);
    /// ```
    ///
    pub fn update_sensors(&self) -> thread::JoinHandle<()> {
        let sensors = self.sensors.clone();
        thread::spawn(move || loop {
            for sensor in sensors.clone() {
                if let Ok(sensor) = sensor.read() {
                    sensor.update();
                }
            }
            thread::sleep(Duration::from_millis(100));
        })
    }

    /// Startet die Api (Json, Web)
    ///
    pub fn launch_api(&self) {
        api::launch(self.clone());
    }


    /// Started alle Komponenten des Servers
    ///
    /// Viele Teile des Servers werden in eigenen Threads gestarted.
    pub fn start(&self) -> Result<(), ServerError> {
        // Laufzeit Informationen speichern
        self.store_runtime_information()?;

        // Sensor Update Thread starten
        self.update_sensors();

        // JSON Api (rocket) starten
        self.launch_api();

        Ok(())
    }
}


#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn new() {
        let server = Server::new();
        assert_eq!(server.service_interval, 0);
        assert_eq!(server.sensors.len(), 0);
    }

    #[test]
    fn default() {
        let server = Server::default();
        assert_eq!(server.service_interval, 365);
        assert_eq!(server.sensors.len(), 3);
    }
}