Files
adcs_api
cbor_protocol
channel_protocol
clyde_3g_eps_api
clyde_3g_eps_service
comms_service
db_test
eps_api
example_rust_c_service
example_rust_service
extern_lib
file_protocol
file_service
iobc_supervisor_service
isis_ants
isis_ants_api
isis_ants_service
isis_imtq_api
isis_iobc_supervisor
kubos_app
kubos_app_service
kubos_build_helper
kubos_file_client
kubos_service
kubos_shell_client
kubos_system
kubos_telemetry_db
large_download
large_upload
local_comms_service
mai400
mai400_api
mai400_service
monitor_service
novatel_oem6_api
novatel_oem6_service
nsl_duplex_d2
nsl_duplex_d2_comms_service
obc_hs
radio_api
rust_i2c
rust_mission_app
rust_uart
scheduler_service
serial_comms_service
shell_protocol
shell_service
telemetry_service
uart_comms_client
udp_client
utils
  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
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
/*
 * Copyright (C) 2018 Kubos Corporation
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

use crate::ffi::*;
use adcs_api::*;

/// Structure for interacting with the ISIS iMTQ
pub struct Imtq<T: ImtqFFI> {
    handle: T,
}

impl Imtq<ImtqRaw> {
    /// Constructor - Returns an `AdcsResult<Imtq>`
    ///
    /// Opens a connection to the underlying Imtq device.
    ///
    /// # Arguments
    ///
    /// * `bus` - I2C bus device of iMTQ
    /// * `addr` - I2C address of iMTQ
    /// * `timeout` - Timeout for watchdog kicking (in seconds)
    ///
    /// # Example
    /// ```
    /// extern crate adcs_api;
    /// extern crate isis_imtq_api;
    /// use adcs_api::*;
    /// use isis_imtq_api::*;
    ///
    /// # fn main() { func(); }
    ///
    /// # fn func() -> AdcsResult<()> {
    /// let imtq = Imtq::imtq("/dev/i2c-0", 0x40, 60)?;
    /// # Ok(())
    /// # }
    /// ```
    pub fn imtq(bus: &str, addr: u16, timeout: i32) -> AdcsResult<Self> {
        let handle = ImtqRaw {};
        Imtq::new(&handle, bus, addr, timeout)
    }
}

impl<T: ImtqFFI> Imtq<T> {
    /// Private Constructor - returns `AdcsResult<Imtq>`
    /// Used by Imtq::imtq and tests to inject
    /// appropriate ImtqFFI object.
    ///
    /// The one argument *must* implement the `ImtqFFI` trait.
    fn new(handle: &T, bus: &str, addr: u16, timeout: i32) -> AdcsResult<Self> {
        adcs_status_to_err(&handle.k_adcs_init(bus.as_ptr(), addr, timeout))?;
        adcs_status_to_err(&handle.k_imtq_watchdog_start())?;
        Ok(Imtq {
            handle: handle.clone(),
        })
    }

    /// Passes a command directly to the Imtq device and returns back the response
    /// Useful for executing commands which have not been implemented in the API
    ///
    /// # Arguments
    ///
    /// * `command` - A string slice containing the command to be sent
    /// * `rx_len` - Expected length of command response
    /// * `delay_secs` - Delay between sending command and requesting response (seconds)
    /// * `delay_nsecs` - Delay between sending command and requesting response (nano seconds)
    ///
    /// # Example
    /// ```
    /// extern crate adcs_api;
    /// extern crate isis_imtq_api;
    /// use adcs_api::*;
    /// use isis_imtq_api::*;
    ///
    /// # fn main() { func(); }
    ///
    /// # fn func() -> AdcsResult<()> {
    /// let imtq = Imtq::imtq("/dev/i2c-0", 0x40, 60)?;
    /// let cmd = vec![10, 10, 10, 10];
    /// let result = imtq.passthrough(&cmd, 10, 0, 0)?;
    /// # Ok(())
    /// # }
    /// ```
    pub fn passthrough(
        &self,
        command: &[u8],
        rx_len: i32,
        delay_secs: i32,
        delay_nsecs: i64,
    ) -> AdcsResult<Vec<u8>> {
        let mut rx_buffer = vec![0; rx_len as usize];
        let tspec = timespec {
            tv_sec: delay_secs,
            tv_nsec: delay_nsecs,
        };

        adcs_status_to_err(&self.handle.k_adcs_passthrough(
            command.as_ptr(),
            command.len() as i32,
            rx_buffer.as_mut_ptr(),
            rx_len,
            &tspec,
        ))?;

        Ok(rx_buffer)
    }

    /// Reboots the iMTQ.
    /// Performing a reset will revert all configuration options
    /// to their default values.
    ///
    /// # Example
    /// ```
    /// extern crate adcs_api;
    /// extern crate isis_imtq_api;
    /// use adcs_api::*;
    /// use isis_imtq_api::*;
    ///
    /// # fn main() { func(); }
    ///
    /// # fn func() -> AdcsResult<()> {
    /// let imtq = Imtq::imtq("/dev/i2c-0", 0x40, 60)?;
    /// imtq.reset()?;
    /// # Ok(())
    /// # }
    /// ```
    pub fn reset(&self) -> AdcsResult<()> {
        adcs_status_to_err(&self.handle.k_imtq_reset())?;
        Ok(())
    }

    fn watchdog_stop(&self) -> AdcsResult<()> {
        adcs_status_to_err(&self.handle.k_imtq_watchdog_stop())?;
        Ok(())
    }
}

impl<T: ImtqFFI> Drop for Imtq<T> {
    fn drop(&mut self) {
        let _res = self.watchdog_stop();
        self.handle.k_adcs_terminate();
    }
}

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

    mock_trait!(
        MockImtq,
        k_adcs_init(*const u8, u16, i32) -> KADCSStatus,
        k_adcs_terminate() -> (),
        k_adcs_passthrough(*const u8, i32, *mut u8, i32, *const timespec) -> KADCSStatus,
        k_imtq_reset() -> KADCSStatus,
        k_imtq_watchdog_start() -> KADCSStatus,
        k_imtq_watchdog_stop() -> KADCSStatus
    );

    impl ImtqFFI for MockImtq {
        mock_method!(k_adcs_init(&self, bus: *const u8, addr: u16, timeout: i32) -> KADCSStatus);
        mock_method!(k_adcs_terminate(&self));
        mock_method!(k_adcs_passthrough(&self, tx: *const u8,
        tx_len: i32,
        rx: *mut u8,
        rx_len: i32,
        delay: *const timespec) -> KADCSStatus);
        mock_method!(k_imtq_reset(&self) -> KADCSStatus);
        mock_method!(k_imtq_watchdog_start(&self) -> KADCSStatus);
        mock_method!(k_imtq_watchdog_stop(&self) -> KADCSStatus);
    }

    #[test]
    fn test_new_good() {
        let mock = MockImtq::default();
        mock.k_adcs_init.return_value(KADCSStatus::Ok);

        let imtq = Imtq::new(&mock, "/dev/i2c-0", 0x40, 60);
        assert!(imtq.is_ok());
        assert_eq!(1, mock.k_adcs_init.num_calls());
        assert_eq!(1, mock.k_imtq_watchdog_start.num_calls());
    }

    #[test]
    fn test_new_err() {
        let mock = MockImtq::default();
        mock.k_adcs_init.return_value(KADCSStatus::Error);

        let imtq = Imtq::new(&mock, "/dev/i2c-0", 0x40, 60);
        assert!(imtq.is_err());
    }

    #[test]
    fn test_on_drop() {
        let mock = MockImtq::default();

        let imtq = Imtq::new(&mock, "/dev/i2c-0", 0x40, 60);
        drop(imtq);
        assert_eq!(1, mock.k_adcs_terminate.num_calls());
        assert_eq!(1, mock.k_imtq_watchdog_stop.num_calls());
    }

    #[test]
    fn test_passthrough() {
        let mock = MockImtq::default();
        let mock_result = vec![1, 1, 2, 3];
        mock.k_adcs_passthrough.use_closure(Box::new(
            |(_tx, tx_len, rx, _rx_len, _delay): (
                *const u8,
                i32,
                *mut u8,
                i32,
                *const timespec,
            )| {
                assert_eq!(4, tx_len);
                unsafe {
                    *rx = 1;
                    *rx.offset(1) = 1;
                    *rx.offset(2) = 2;
                    *rx.offset(3) = 3;
                }
                KADCSStatus::Ok
            },
        ));
        let imtq = Imtq::new(&mock, "/dev/i2c-0", 0x40, 60).unwrap();

        let cmd = vec![0, 1, 1, 1];
        let result = imtq.passthrough(&cmd, 4, 0, 100);
        assert!(result.is_ok());
        assert_eq!(mock_result, result.unwrap());
    }

    #[test]
    fn test_reset() {
        let mock = MockImtq::default();
        let imtq = Imtq::new(&mock, "/dev/i2c-0", 0x40, 60).unwrap();
        assert_eq!(Ok(()), imtq.reset());
    }

    #[test]
    fn test_watchdog_stop() {
        let mock = MockImtq::default();
        let imtq = Imtq::new(&mock, "/dev/i2c-0", 0x40, 60).unwrap();
        assert_eq!(Ok(()), imtq.watchdog_stop());
    }
}