Skip to main content

nanonis_rs/client/
tip_recovery.rs

1use super::NanonisClient;
2use crate::error::NanonisError;
3use crate::types::NanonisValue;
4use std::time::Duration;
5
6/// Configuration parameters for tip shaper
7#[derive(Debug, Clone)]
8pub struct TipShaperConfig {
9    pub switch_off_delay: Duration,
10    pub change_bias: bool,
11    pub bias_v: f32,
12    pub tip_lift_m: f32,
13    pub lift_time_1: Duration,
14    pub bias_lift_v: f32,
15    pub bias_settling_time: Duration,
16    pub lift_height_m: f32,
17    pub lift_time_2: Duration,
18    pub end_wait_time: Duration,
19    pub restore_feedback: bool,
20}
21
22/// Return type for tip shaper properties
23pub type TipShaperProps = (f32, u32, f32, f32, f32, f32, f32, f32, f32, f32, u32);
24
25impl NanonisClient {
26    /// Set the buffer size of the Tip Move Recorder.
27    ///
28    /// Sets the number of data elements that can be stored in the Tip Move Recorder
29    /// buffer. This recorder tracks signal values while the tip is moving in Follow Me mode.
30    /// **Note**: This function clears the existing graph data.
31    ///
32    /// # Arguments
33    /// * `buffer_size` - Number of data elements to store in the recorder buffer
34    ///
35    /// # Errors
36    /// Returns `NanonisError` if communication fails or invalid buffer size.
37    ///
38    /// # Examples
39    /// ```no_run
40    /// use nanonis_rs::NanonisClient;
41    ///
42    /// let mut client = NanonisClient::new("127.0.0.1", 6501)?;
43    ///
44    /// // Set buffer for 10,000 data points
45    /// client.tip_rec_buffer_size_set(10000)?;
46    ///
47    /// // Set smaller buffer for quick tests
48    /// client.tip_rec_buffer_size_set(1000)?;
49    /// # Ok::<(), Box<dyn std::error::Error>>(())
50    /// ```
51    pub fn tip_rec_buffer_size_set(&mut self, buffer_size: i32) -> Result<(), NanonisError> {
52        self.quick_send(
53            "TipRec.BufferSizeSet",
54            vec![NanonisValue::I32(buffer_size)],
55            vec!["i"],
56            vec![],
57        )?;
58        Ok(())
59    }
60
61    /// Get the current buffer size of the Tip Move Recorder.
62    ///
63    /// Returns the number of data elements that can be stored in the recorder buffer.
64    ///
65    /// # Returns
66    /// Current buffer size (number of data elements).
67    ///
68    /// # Errors
69    /// Returns `NanonisError` if communication fails.
70    ///
71    /// # Examples
72    /// ```no_run
73    /// use nanonis_rs::NanonisClient;
74    ///
75    /// let mut client = NanonisClient::new("127.0.0.1", 6501)?;
76    ///
77    /// let buffer_size = client.tip_rec_buffer_size_get()?;
78    /// println!("Tip recorder buffer size: {} points", buffer_size);
79    /// # Ok::<(), Box<dyn std::error::Error>>(())
80    /// ```
81    pub fn tip_rec_buffer_size_get(&mut self) -> Result<i32, NanonisError> {
82        let result = self.quick_send("TipRec.BufferSizeGet", vec![], vec![], vec!["i"])?;
83
84        match result.first() {
85            Some(value) => Ok(value.as_i32()?),
86            None => Err(NanonisError::Protocol(
87                "No buffer size returned".to_string(),
88            )),
89        }
90    }
91
92    /// Clear the buffer of the Tip Move Recorder.
93    ///
94    /// Removes all recorded data from the Tip Move Recorder buffer, resetting
95    /// it to an empty state. This is useful before starting a new recording session.
96    ///
97    /// # Errors
98    /// Returns `NanonisError` if communication fails.
99    ///
100    /// # Examples
101    /// ```no_run
102    /// use nanonis_rs::NanonisClient;
103    ///
104    /// let mut client = NanonisClient::new("127.0.0.1", 6501)?;
105    ///
106    /// // Clear buffer before starting new measurement
107    /// client.tip_rec_buffer_clear()?;
108    /// println!("Tip recorder buffer cleared");
109    /// # Ok::<(), Box<dyn std::error::Error>>(())
110    /// ```
111    pub fn tip_rec_buffer_clear(&mut self) -> Result<(), NanonisError> {
112        self.quick_send("TipRec.BufferClear", vec![], vec![], vec![])?;
113        Ok(())
114    }
115
116    /// Get the recorded data from the Tip Move Recorder.
117    ///
118    /// Returns all data recorded while the tip was moving in Follow Me mode.
119    /// This includes channel indexes, names, and the complete 2D data array
120    /// with measurements taken during tip movement.
121    ///
122    /// # Returns
123    /// A tuple containing:
124    /// - `Vec<i32>` - Channel indexes (0-23 for Signals Manager slots)
125    /// - `Vec<Vec<f32>>` - 2D data array \[rows\]\[columns\] with recorded measurements
126    ///
127    /// # Errors
128    /// Returns `NanonisError` if communication fails or no data available.
129    ///
130    /// # Examples
131    /// ```no_run
132    /// use nanonis_rs::NanonisClient;
133    ///
134    /// let mut client = NanonisClient::new("127.0.0.1", 6501)?;
135    ///
136    /// // Get recorded tip movement data
137    /// let (channel_indexes, data) = client.tip_rec_data_get()?;
138    ///
139    /// println!("Recorded {} channels with {} data points",
140    ///          channel_indexes.len(), data.len());
141    ///
142    /// // Analyze data for each channel
143    /// for (i, &channel_idx) in channel_indexes.iter().enumerate() {
144    ///     if i < data[0].len() {
145    ///         println!("Channel {}: {} values", channel_idx, data.len());
146    ///     }
147    /// }
148    /// # Ok::<(), Box<dyn std::error::Error>>(())
149    /// ```
150    pub fn tip_rec_data_get(&mut self) -> Result<(Vec<i32>, Vec<Vec<f32>>), NanonisError> {
151        let result = self.quick_send(
152            "TipRec.DataGet",
153            vec![],
154            vec![],
155            vec!["i", "*i", "i", "i", "2f"],
156        )?;
157
158        if result.len() >= 5 {
159            let channel_indexes = result[1].as_i32_array()?.to_vec();
160
161            // The protocol layer already parses "2f" into a 2D array
162            let data_2d = result[4].as_f32_2d_array()?.clone();
163
164            Ok((channel_indexes, data_2d))
165        } else {
166            Err(NanonisError::Protocol(
167                "Invalid tip recorder data response".to_string(),
168            ))
169        }
170    }
171
172    /// Save the tip movement data to a file.
173    ///
174    /// Saves all data recorded in Follow Me mode to a file with the specified basename.
175    /// Optionally clears the buffer after saving to prepare for new recordings.
176    ///
177    /// # Arguments
178    /// * `clear_buffer` - If `true`, clears buffer after saving
179    /// * `basename` - Base filename for saved data (empty to use last basename)
180    ///
181    /// # Errors
182    /// Returns `NanonisError` if communication fails or file save error occurs.
183    ///
184    /// # Examples
185    /// ```no_run
186    /// use nanonis_rs::NanonisClient;
187    ///
188    /// let mut client = NanonisClient::new("127.0.0.1", 6501)?;
189    ///
190    /// // Save data and clear buffer for next measurement
191    /// client.tip_rec_data_save(true, "tip_approach_001")?;
192    ///
193    /// // Save without clearing buffer (keep data for analysis)
194    /// client.tip_rec_data_save(false, "tip_movement_log")?;
195    /// # Ok::<(), Box<dyn std::error::Error>>(())
196    /// ```
197    pub fn tip_rec_data_save(
198        &mut self,
199        clear_buffer: bool,
200        basename: &str,
201    ) -> Result<(), NanonisError> {
202        let clear_flag = if clear_buffer { 1u32 } else { 0u32 };
203
204        self.quick_send(
205            "TipRec.DataSave",
206            vec![
207                NanonisValue::U32(clear_flag),
208                NanonisValue::String(basename.to_string()),
209            ],
210            vec!["I", "+*c"],
211            vec![],
212        )?;
213        Ok(())
214    }
215
216    /// Start the tip shaper procedure for tip conditioning.
217    ///
218    /// Initiates the tip shaper procedure which performs controlled tip conditioning
219    /// by applying specific voltage sequences and mechanical movements. This is used
220    /// to improve tip sharpness and stability after crashes or contamination.
221    ///
222    /// # Arguments
223    /// * `wait_until_finished` - If `true`, waits for procedure completion
224    /// * `timeout_ms` - Timeout in milliseconds (-1 for infinite wait)
225    ///
226    /// # Errors
227    /// Returns `NanonisError` if communication fails or procedure cannot start.
228    ///
229    /// # Examples
230    /// ```no_run
231    /// use nanonis_rs::NanonisClient;
232    /// use std::time::Duration;
233    ///
234    /// let mut client = NanonisClient::new("127.0.0.1", 6501)?;
235    ///
236    /// // Start tip shaping and wait for completion (30 second timeout)
237    /// client.tip_shaper_start(true, Duration::from_secs(30))?;
238    /// println!("Tip shaping completed");
239    ///
240    /// // Start tip shaping without waiting
241    /// client.tip_shaper_start(false, Duration::ZERO)?;
242    /// # Ok::<(), Box<dyn std::error::Error>>(())
243    /// ```
244    pub fn tip_shaper_start(
245        &mut self,
246        wait_until_finished: bool,
247        timeout: Duration,
248    ) -> Result<(), NanonisError> {
249        let wait_flag = if wait_until_finished { 1u32 } else { 0u32 };
250        let timeout = timeout.as_millis().min(u32::MAX as u128) as i32;
251
252        self.quick_send(
253            "TipShaper.Start",
254            vec![NanonisValue::U32(wait_flag), NanonisValue::I32(timeout)],
255            vec!["I", "i"],
256            vec![],
257        )?;
258        Ok(())
259    }
260
261    /// Set the tip shaper procedure configuration.
262    ///
263    /// Configures all parameters for the tip conditioning procedure including
264    /// timing, voltages, and mechanical movements. This is a complex procedure
265    /// with multiple stages of tip treatment.
266    ///
267    /// # Arguments
268    /// * `config` - Tip shaper configuration parameters
269    ///
270    /// # Errors
271    /// Returns `NanonisError` if communication fails or invalid parameters.
272    ///
273    /// # Examples
274    /// ```no_run
275    /// use nanonis_rs::NanonisClient;
276    /// use nanonis_rs::tip_recovery::TipShaperConfig;
277    /// use std::time::Duration;
278    ///
279    /// let mut client = NanonisClient::new("127.0.0.1", 6501)?;
280    ///
281    /// // Conservative tip conditioning parameters
282    /// let config = TipShaperConfig {
283    ///     switch_off_delay: Duration::from_millis(100),
284    ///     change_bias: true,
285    ///     bias_v: -2.0,
286    ///     tip_lift_m: 50e-9,   // 50 nm
287    ///     lift_time_1: Duration::from_secs(1),
288    ///     bias_lift_v: 5.0,
289    ///     bias_settling_time: Duration::from_millis(500),
290    ///     lift_height_m: 100e-9, // 100 nm
291    ///     lift_time_2: Duration::from_millis(500),
292    ///     end_wait_time: Duration::from_millis(200),
293    ///     restore_feedback: true,
294    /// };
295    /// client.tip_shaper_props_set(config)?;
296    /// # Ok::<(), Box<dyn std::error::Error>>(())
297    /// ```
298    pub fn tip_shaper_props_set(&mut self, config: TipShaperConfig) -> Result<(), NanonisError> {
299        self.quick_send(
300            "TipShaper.PropsSet",
301            vec![
302                NanonisValue::F32(config.switch_off_delay.as_secs_f32()),
303                NanonisValue::U32(config.change_bias.into()),
304                NanonisValue::F32(config.bias_v),
305                NanonisValue::F32(config.tip_lift_m),
306                NanonisValue::F32(config.lift_time_1.as_secs_f32()),
307                NanonisValue::F32(config.bias_lift_v),
308                NanonisValue::F32(config.bias_settling_time.as_secs_f32()),
309                NanonisValue::F32(config.lift_height_m),
310                NanonisValue::F32(config.lift_time_2.as_secs_f32()),
311                NanonisValue::F32(config.end_wait_time.as_secs_f32()),
312                NanonisValue::U32(config.restore_feedback.into()),
313            ],
314            vec!["f", "I", "f", "f", "f", "f", "f", "f", "f", "f", "I"],
315            vec![],
316        )?;
317        Ok(())
318    }
319
320    /// Get the current tip shaper procedure configuration.
321    ///
322    /// Returns all parameters currently configured for the tip conditioning procedure.
323    /// Use this to verify settings before starting the procedure.
324    ///
325    /// # Returns
326    /// A tuple containing all tip shaper parameters:
327    /// - `f32` - Switch off delay (s)
328    /// - `u32` - Change bias flag (0=no change, 1=true, 2=false)
329    /// - `f32` - Bias voltage (V)
330    /// - `f32` - Tip lift distance (m)
331    /// - `f32` - First lift time (s)
332    /// - `f32` - Bias lift voltage (V)
333    /// - `f32` - Bias settling time (s)
334    /// - `f32` - Second lift height (m)
335    /// - `f32` - Second lift time (s)
336    /// - `f32` - End wait time (s)
337    /// - `u32` - Restore feedback flag (0=no change, 1=true, 2=false)
338    ///
339    /// # Errors
340    /// Returns `NanonisError` if communication fails.
341    ///
342    /// # Examples
343    /// ```no_run
344    /// use nanonis_rs::NanonisClient;
345    ///
346    /// let mut client = NanonisClient::new("127.0.0.1", 6501)?;
347    ///
348    /// let (switch_delay, change_bias, bias_v, tip_lift, lift_time1,
349    ///      bias_lift, settling, lift_height, lift_time2, end_wait, restore) =
350    ///      client.tip_shaper_props_get()?;
351    ///
352    /// println!("Tip lift: {:.1} nm, Bias: {:.1} V", tip_lift * 1e9, bias_v);
353    /// println!("Total procedure time: ~{:.1} s",
354    ///          switch_delay + lift_time1 + settling + lift_time2 + end_wait);
355    /// # Ok::<(), Box<dyn std::error::Error>>(())
356    /// ```
357    pub fn tip_shaper_props_get(&mut self) -> Result<TipShaperProps, NanonisError> {
358        let result = self.quick_send(
359            "TipShaper.PropsGet",
360            vec![],
361            vec![],
362            vec!["f", "I", "f", "f", "f", "f", "f", "f", "f", "f", "I"],
363        )?;
364
365        if result.len() >= 11 {
366            Ok((
367                result[0].as_f32()?,  // switch_off_delay
368                result[1].as_u32()?,  // change_bias
369                result[2].as_f32()?,  // bias_v
370                result[3].as_f32()?,  // tip_lift_m
371                result[4].as_f32()?,  // lift_time_1_s
372                result[5].as_f32()?,  // bias_lift_v
373                result[6].as_f32()?,  // bias_settling_time_s
374                result[7].as_f32()?,  // lift_height_m
375                result[8].as_f32()?,  // lift_time_2_s
376                result[9].as_f32()?,  // end_wait_time_s
377                result[10].as_u32()?, // restore_feedback
378            ))
379        } else {
380            Err(NanonisError::Protocol(
381                "Invalid tip shaper properties response".to_string(),
382            ))
383        }
384    }
385
386    /// Get the Tip Shaper properties as a type-safe TipShaperConfig struct
387    ///
388    /// This method returns the same information as `tip_shaper_props_get()` but
389    /// with Duration types for time fields instead of raw f32 seconds.
390    ///
391    /// # Returns
392    /// Returns a `TipShaperConfig` struct with type-safe Duration fields for all time parameters.
393    ///
394    /// # Errors
395    /// Returns `NanonisError` if communication fails or if the response format is invalid.
396    ///
397    /// # Examples
398    /// ```no_run
399    /// use nanonis_rs::NanonisClient;
400    /// use std::time::Duration;
401    ///
402    /// let mut client = NanonisClient::new("127.0.0.1", 6501)?;
403    /// let config = client.tip_shaper_config_get()?;
404    ///
405    /// println!("Tip lift: {:.1} nm, Bias: {:.1} V",
406    ///          config.tip_lift_m * 1e9, config.bias_v);
407    /// println!("Total procedure time: {:.1} s",
408    ///          (config.switch_off_delay + config.lift_time_1 +
409    ///           config.bias_settling_time + config.lift_time_2 +
410    ///           config.end_wait_time).as_secs_f32());
411    /// # Ok::<(), Box<dyn std::error::Error>>(())
412    /// ```
413    pub fn tip_shaper_config_get(&mut self) -> Result<TipShaperConfig, NanonisError> {
414        let result = self.quick_send(
415            "TipShaper.PropsGet",
416            vec![],
417            vec![],
418            vec!["f", "I", "f", "f", "f", "f", "f", "f", "f", "f", "I"],
419        )?;
420
421        if result.len() >= 11 {
422            let restore_feedback = match result[10].as_u32()? {
423                0 => true,
424                1 => false,
425                v => return Err(NanonisError::Protocol(format!(
426                    "Invalid restore_feedback value: {v}, expected 0 or 1"
427                ))),
428            };
429
430            let change_bias = match result[1].as_u32()? {
431                0 => true,
432                1 => false,
433                v => return Err(NanonisError::Protocol(format!(
434                    "Invalid change_bias value: {v}, expected 0 or 1"
435                ))),
436            };
437
438            Ok(TipShaperConfig {
439                switch_off_delay: Duration::from_secs_f32(result[0].as_f32()?),
440                change_bias,
441                bias_v: result[2].as_f32()?,
442                tip_lift_m: result[3].as_f32()?,
443                lift_time_1: Duration::from_secs_f32(result[4].as_f32()?),
444                bias_lift_v: result[5].as_f32()?,
445                bias_settling_time: Duration::from_secs_f32(result[6].as_f32()?),
446                lift_height_m: result[7].as_f32()?,
447                lift_time_2: Duration::from_secs_f32(result[8].as_f32()?),
448                end_wait_time: Duration::from_secs_f32(result[9].as_f32()?),
449                restore_feedback,
450            })
451        } else {
452            Err(NanonisError::Protocol(
453                "Invalid tip shaper properties response".to_string(),
454            ))
455        }
456    }
457}