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
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
mod types;
pub use types::*;
use std::time::Duration;
use super::NanonisClient;
use crate::error::NanonisError;
use crate::types::NanonisValue;
impl NanonisClient {
/// Switch the Z-Controller on or off.
///
/// Controls the Z-Controller state. This is fundamental for enabling/disabling
/// tip-sample distance regulation during scanning and positioning operations.
///
/// # Arguments
/// * `controller_on` - `true` to turn controller on, `false` to turn off
///
/// # Errors
/// Returns `NanonisError` if communication fails or protocol error occurs.
///
/// # Examples
/// ```no_run
/// use nanonis_rs::NanonisClient;
///
/// let mut client = NanonisClient::new("127.0.0.1", 6501)?;
///
/// // Turn Z-controller on for feedback control
/// client.z_ctrl_on_off_set(true)?;
///
/// // Turn Z-controller off for manual positioning
/// client.z_ctrl_on_off_set(false)?;
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// ```
pub fn z_ctrl_on_off_set(&mut self, controller_on: bool) -> Result<(), NanonisError> {
let status_flag = if controller_on { 1u32 } else { 0u32 };
self.quick_send(
"ZCtrl.OnOffSet",
vec![NanonisValue::U32(status_flag)],
vec!["I"],
vec![],
)?;
Ok(())
}
/// Get the current status of the Z-Controller.
///
/// Returns the real-time status from the controller (not from the Z-Controller module).
/// This is useful to ensure the controller is truly off before starting experiments,
/// as there can be communication delays and switch-off delays.
///
/// # Returns
/// `true` if controller is on, `false` if controller is off.
///
/// # Errors
/// Returns `NanonisError` if communication fails or protocol error occurs.
///
/// # Examples
/// ```no_run
/// use nanonis_rs::NanonisClient;
///
/// let mut client = NanonisClient::new("127.0.0.1", 6501)?;
///
/// // Check controller status before experiment
/// if client.z_ctrl_on_off_get()? {
/// println!("Z-controller is active");
/// } else {
/// println!("Z-controller is off - safe to move tip manually");
/// }
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// ```
pub fn z_ctrl_on_off_get(&mut self) -> Result<bool, NanonisError> {
let result = self.quick_send("ZCtrl.OnOffGet", vec![], vec![], vec!["I"])?;
match result.first() {
Some(value) => Ok(value.as_u32()? == 1),
None => Err(NanonisError::Protocol(
"No Z-controller status returned".to_string(),
)),
}
}
/// Set the Z position of the tip.
///
/// **Important**: The Z-controller must be switched OFF to change the tip position.
/// This function directly sets the tip's Z coordinate for manual positioning.
///
/// # Arguments
/// * `z_position_m` - Z position in meters
///
/// # Errors
/// Returns `NanonisError` if:
/// - Z-controller is still active (must be turned off first)
/// - Position is outside safe limits
/// - Communication fails or protocol error occurs
///
/// # Examples
/// ```no_run
/// use nanonis_rs::NanonisClient;
///
/// let mut client = NanonisClient::new("127.0.0.1", 6501)?;
///
/// // Ensure Z-controller is off
/// client.z_ctrl_on_off_set(false)?;
///
/// // Move tip to specific Z position (10 nm above surface)
/// client.z_ctrl_z_pos_set(10e-9)?;
///
/// // Move tip closer to surface (2 nm)
/// client.z_ctrl_z_pos_set(2e-9)?;
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// ```
pub fn z_ctrl_z_pos_set(&mut self, z_position_m: f32) -> Result<(), NanonisError> {
self.quick_send(
"ZCtrl.ZPosSet",
vec![NanonisValue::F32(z_position_m)],
vec!["f"],
vec![],
)?;
Ok(())
}
/// Get the current Z position of the tip.
///
/// Returns the current tip Z coordinate in meters. This works whether
/// the Z-controller is on or off.
///
/// # Returns
/// Current Z position in meters.
///
/// # Errors
/// Returns `NanonisError` if communication fails or protocol error occurs.
///
/// # Examples
/// ```no_run
/// use nanonis_rs::NanonisClient;
///
/// let mut client = NanonisClient::new("127.0.0.1", 6501)?;
///
/// let z_pos = client.z_ctrl_z_pos_get()?;
/// println!("Current tip height: {:.2} nm", z_pos * 1e9);
///
/// // Check if tip is at safe distance
/// if z_pos > 5e-9 {
/// println!("Tip is safely withdrawn");
/// }
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// ```
pub fn z_ctrl_z_pos_get(&mut self) -> Result<f32, NanonisError> {
let result = self.quick_send("ZCtrl.ZPosGet", vec![], vec![], vec!["f"])?;
match result.first() {
Some(value) => Ok(value.as_f32()?),
None => Err(NanonisError::Protocol("No Z position returned".to_string())),
}
}
/// Set the setpoint of the Z-Controller.
///
/// The setpoint is the target value for the feedback signal that the Z-controller
/// tries to maintain by adjusting the tip-sample distance.
///
/// # Arguments
/// * `setpoint` - Z-controller setpoint value (units depend on feedback signal)
///
/// # Errors
/// Returns `NanonisError` if communication fails or protocol error occurs.
///
/// # Examples
/// ```no_run
/// use nanonis_rs::NanonisClient;
///
/// let mut client = NanonisClient::new("127.0.0.1", 6501)?;
///
/// // Set tunneling current setpoint to 100 pA
/// client.z_ctrl_setpoint_set(100e-12)?;
///
/// // Set force setpoint for AFM mode
/// client.z_ctrl_setpoint_set(1e-9)?; // 1 nN
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// ```
pub fn z_ctrl_setpoint_set(&mut self, setpoint: f32) -> Result<(), NanonisError> {
self.quick_send(
"ZCtrl.SetpntSet",
vec![NanonisValue::F32(setpoint)],
vec!["f"],
vec![],
)?;
Ok(())
}
/// Get the current setpoint of the Z-Controller.
///
/// Returns the target value that the Z-controller is trying to maintain.
///
/// # Returns
/// Current Z-controller setpoint value.
///
/// # Errors
/// Returns `NanonisError` if communication fails or protocol error occurs.
///
/// # Examples
/// ```no_run
/// use nanonis_rs::NanonisClient;
///
/// let mut client = NanonisClient::new("127.0.0.1", 6501)?;
///
/// let setpoint = client.z_ctrl_setpoint_get()?;
/// println!("Current setpoint: {:.3e}", setpoint);
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// ```
pub fn z_ctrl_setpoint_get(&mut self) -> Result<f32, NanonisError> {
let result = self.quick_send("ZCtrl.SetpntGet", vec![], vec![], vec!["f"])?;
match result.first() {
Some(value) => Ok(value.as_f32()?),
None => Err(NanonisError::Protocol("No setpoint returned".to_string())),
}
}
/// Set the Z-Controller gains and time settings.
///
/// Configures the PID controller parameters for Z-axis feedback control.
/// The integral gain is calculated as I = P/T where P is proportional gain
/// and T is the time constant.
///
/// # Arguments
/// * `p_gain` - Proportional gain of the regulation loop
/// * `time_constant_s` - Time constant T in seconds
/// * `i_gain` - Integral gain of the regulation loop (calculated as P/T)
///
/// # Errors
/// Returns `NanonisError` if communication fails or invalid gains provided.
///
/// # Examples
/// ```no_run
/// use nanonis_rs::NanonisClient;
///
/// let mut client = NanonisClient::new("127.0.0.1", 6501)?;
///
/// // Set moderate feedback gains for stable operation
/// client.z_ctrl_gain_set(1.0, 0.1, 10.0)?;
///
/// // Set aggressive gains for fast response
/// client.z_ctrl_gain_set(5.0, 0.05, 100.0)?;
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// ```
pub fn z_ctrl_gain_set(
&mut self,
p_gain: f32,
time_constant_s: f32,
i_gain: f32,
) -> Result<(), NanonisError> {
self.quick_send(
"ZCtrl.GainSet",
vec![
NanonisValue::F32(p_gain),
NanonisValue::F32(time_constant_s),
NanonisValue::F32(i_gain),
],
vec!["f", "f", "f"],
vec![],
)?;
Ok(())
}
/// Get the current Z-Controller gains and time settings.
///
/// Returns the PID controller parameters currently in use.
///
/// # Returns
/// A tuple containing:
/// - `f32` - Proportional gain
/// - `f32` - Time constant in seconds
/// - `f32` - Integral gain (P/T)
///
/// # Errors
/// Returns `NanonisError` if communication fails or protocol error occurs.
///
/// # Examples
/// ```no_run
/// use nanonis_rs::NanonisClient;
///
/// let mut client = NanonisClient::new("127.0.0.1", 6501)?;
///
/// let (p_gain, time_const, i_gain) = client.z_ctrl_gain_get()?;
/// println!("P: {:.3}, T: {:.3}s, I: {:.3}", p_gain, time_const, i_gain);
///
/// // Check if gains are in reasonable range
/// if p_gain > 10.0 {
/// println!("Warning: High proportional gain may cause instability");
/// }
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// ```
pub fn z_ctrl_gain_get(&mut self) -> Result<(f32, f32, f32), NanonisError> {
let result = self.quick_send("ZCtrl.GainGet", vec![], vec![], vec!["f", "f", "f"])?;
if result.len() >= 3 {
Ok((
result[0].as_f32()?,
result[1].as_f32()?,
result[2].as_f32()?,
))
} else {
Err(NanonisError::Protocol("Invalid gain response".to_string()))
}
}
/// Move the tip to its home position.
///
/// Moves the tip to the predefined home position, which can be either absolute
/// (fixed position) or relative to the current position, depending on the
/// controller configuration.
///
/// # Errors
/// Returns `NanonisError` if communication fails or protocol error occurs.
///
/// # Examples
/// ```no_run
/// use nanonis_rs::NanonisClient;
///
/// let mut client = NanonisClient::new("127.0.0.1", 6501)?;
///
/// // Move tip to home position after experiment
/// client.z_ctrl_home()?;
///
/// // Wait a moment for positioning to complete
/// std::thread::sleep(std::time::Duration::from_secs(1));
///
/// // Check final position
/// let final_pos = client.z_ctrl_z_pos_get()?;
/// println!("Tip homed to: {:.2} nm", final_pos * 1e9);
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// ```
pub fn z_ctrl_home(&mut self) -> Result<(), NanonisError> {
self.quick_send("ZCtrl.Home", vec![], vec![], vec![])?;
Ok(())
}
/// Withdraw the tip.
///
/// Switches off the Z-Controller and fully withdraws the tip to the upper limit.
/// This is a safety function to prevent tip crashes during approach or when
/// moving to new scan areas.
///
/// # Arguments
/// * `wait_until_finished` - If `true`, waits for withdrawal to complete
/// * `timeout_ms` - Timeout in milliseconds for the withdrawal operation
///
/// # Errors
/// Returns `NanonisError` if communication fails or withdrawal times out.
///
/// # Examples
/// ```no_run
/// use nanonis_rs::NanonisClient;
/// use std::time::Duration;
///
/// let mut client = NanonisClient::new("127.0.0.1", 6501)?;
///
/// // Emergency withdrawal - don't wait
/// client.z_ctrl_withdraw(false, Duration::from_secs(5))?;
///
/// // Controlled withdrawal with waiting
/// client.z_ctrl_withdraw(true, Duration::from_secs(10))?;
/// println!("Tip safely withdrawn");
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// ```
pub fn z_ctrl_withdraw(
&mut self,
wait_until_finished: bool,
timeout_ms: Duration,
) -> Result<(), NanonisError> {
let wait_flag = if wait_until_finished { 1u32 } else { 0u32 };
self.quick_send(
"ZCtrl.Withdraw",
vec![
NanonisValue::U32(wait_flag),
NanonisValue::I32(timeout_ms.as_millis().min(i32::MAX as u128) as i32),
],
vec!["I", "i"],
vec![],
)?;
Ok(())
}
/// Set the Z-Controller switch-off delay.
///
/// Before turning off the controller, the Z position is averaged over this delay.
/// This leads to reproducible Z positions when switching off the controller.
///
/// # Arguments
/// * `delay_s` - Switch-off delay in seconds
///
/// # Errors
/// Returns `NanonisError` if communication fails.
pub fn z_ctrl_switch_off_delay_set(&mut self, delay_s: f32) -> Result<(), NanonisError> {
self.quick_send(
"ZCtrl.SwitchOffDelaySet",
vec![NanonisValue::F32(delay_s)],
vec!["f"],
vec![],
)?;
Ok(())
}
/// Get the Z-Controller switch-off delay.
///
/// # Returns
/// Switch-off delay in seconds.
///
/// # Errors
/// Returns `NanonisError` if communication fails.
pub fn z_ctrl_switch_off_delay_get(&mut self) -> Result<f32, NanonisError> {
let result = self.quick_send("ZCtrl.SwitchOffDelayGet", vec![], vec![], vec!["f"])?;
if result.is_empty() {
return Err(NanonisError::Protocol(
"Empty response from ZCtrl.SwitchOffDelayGet".to_string(),
));
}
result[0].as_f32()
}
// NOTE: z_ctrl_tip_lift_set/get are implemented in safe_tip.rs
/// Set the home position properties.
///
/// # Arguments
/// * `home_mode` - Home position mode (no change / absolute / relative)
/// * `home_position_m` - Home position in meters
///
/// # Errors
/// Returns `NanonisError` if communication fails.
pub fn z_ctrl_home_props_set(
&mut self,
home_mode: ZHomeMode,
home_position_m: f32,
) -> Result<(), NanonisError> {
self.quick_send(
"ZCtrl.HomePropsSet",
vec![
NanonisValue::U16(home_mode.into()),
NanonisValue::F32(home_position_m),
],
vec!["H", "f"],
vec![],
)?;
Ok(())
}
/// Get the home position properties.
///
/// # Returns
/// Tuple of (is_relative, home_position_m).
///
/// # Errors
/// Returns `NanonisError` if communication fails.
pub fn z_ctrl_home_props_get(&mut self) -> Result<(bool, f32), NanonisError> {
let result = self.quick_send("ZCtrl.HomePropsGet", vec![], vec![], vec!["H", "f"])?;
if result.len() < 2 {
return Err(NanonisError::Protocol(
"Truncated response from ZCtrl.HomePropsGet".to_string(),
));
}
Ok((result[0].as_u16()? != 0, result[1].as_f32()?))
}
/// Set the active Z-Controller.
///
/// # Arguments
/// * `controller_index` - Controller index from the list
///
/// # Errors
/// Returns `NanonisError` if communication fails.
pub fn z_ctrl_active_ctrl_set(&mut self, controller_index: i32) -> Result<(), NanonisError> {
self.quick_send(
"ZCtrl.ActiveCtrlSet",
vec![NanonisValue::I32(controller_index)],
vec!["i"],
vec![],
)?;
Ok(())
}
/// Get the list of Z-Controllers and active controller index.
///
/// # Returns
/// Tuple of (list of controller names, active controller index).
///
/// # Errors
/// Returns `NanonisError` if communication fails.
pub fn z_ctrl_ctrl_list_get(&mut self) -> Result<(Vec<String>, i32), NanonisError> {
let result = self.quick_send(
"ZCtrl.CtrlListGet",
vec![],
vec![],
vec!["i", "i", "*+c", "i"],
)?;
if result.len() < 4 {
return Err(NanonisError::Protocol(
"Truncated response from ZCtrl.CtrlListGet".to_string(),
));
}
Ok((result[2].as_string_array()?.to_vec(), result[3].as_i32()?))
}
/// Set the withdraw slew rate.
///
/// # Arguments
/// * `rate_m_s` - Withdraw rate in m/s
///
/// # Errors
/// Returns `NanonisError` if communication fails.
pub fn z_ctrl_withdraw_rate_set(&mut self, rate_m_s: f32) -> Result<(), NanonisError> {
self.quick_send(
"ZCtrl.WithdrawRateSet",
vec![NanonisValue::F32(rate_m_s)],
vec!["f"],
vec![],
)?;
Ok(())
}
/// Get the withdraw slew rate.
///
/// # Returns
/// Withdraw rate in m/s.
///
/// # Errors
/// Returns `NanonisError` if communication fails.
pub fn z_ctrl_withdraw_rate_get(&mut self) -> Result<f32, NanonisError> {
let result = self.quick_send("ZCtrl.WithdrawRateGet", vec![], vec![], vec!["f"])?;
if result.is_empty() {
return Err(NanonisError::Protocol(
"Empty response from ZCtrl.WithdrawRateGet".to_string(),
));
}
result[0].as_f32()
}
/// Enable or disable Z position limits.
///
/// # Arguments
/// * `enabled` - True to enable limits
///
/// # Errors
/// Returns `NanonisError` if communication fails.
pub fn z_ctrl_limits_enabled_set(&mut self, enabled: bool) -> Result<(), NanonisError> {
self.quick_send(
"ZCtrl.LimitsEnabledSet",
vec![NanonisValue::U32(if enabled { 1 } else { 0 })],
vec!["I"],
vec![],
)?;
Ok(())
}
/// Get the Z position limits enabled status.
///
/// # Returns
/// True if limits are enabled.
///
/// # Errors
/// Returns `NanonisError` if communication fails.
pub fn z_ctrl_limits_enabled_get(&mut self) -> Result<bool, NanonisError> {
let result = self.quick_send("ZCtrl.LimitsEnabledGet", vec![], vec![], vec!["I"])?;
if result.is_empty() {
return Err(NanonisError::Protocol(
"Empty response from ZCtrl.LimitsEnabledGet".to_string(),
));
}
Ok(result[0].as_u32()? != 0)
}
/// Set the Z position limits.
///
/// # Arguments
/// * `high_limit_m` - High Z limit in meters
/// * `low_limit_m` - Low Z limit in meters
///
/// # Errors
/// Returns `NanonisError` if communication fails.
pub fn z_ctrl_limits_set(
&mut self,
high_limit_m: f32,
low_limit_m: f32,
) -> Result<(), NanonisError> {
self.quick_send(
"ZCtrl.LimitsSet",
vec![
NanonisValue::F32(high_limit_m),
NanonisValue::F32(low_limit_m),
],
vec!["f", "f"],
vec![],
)?;
Ok(())
}
/// Get the Z position limits.
///
/// # Returns
/// Tuple of (high_limit_m, low_limit_m).
///
/// # Errors
/// Returns `NanonisError` if communication fails.
pub fn z_ctrl_limits_get(&mut self) -> Result<(f32, f32), NanonisError> {
let result = self.quick_send("ZCtrl.LimitsGet", vec![], vec![], vec!["f", "f"])?;
if result.len() < 2 {
return Err(NanonisError::Protocol(
"Truncated response from ZCtrl.LimitsGet".to_string(),
));
}
Ok((result[0].as_f32()?, result[1].as_f32()?))
}
/// Get the current Z-Controller status.
///
/// # Returns
/// Controller status (1=Off, 2=On, 3=Hold, 4=Switching Off, 5=Safe Tip, 6=Withdrawing).
///
/// # Errors
/// Returns `NanonisError` if communication fails.
pub fn z_ctrl_status_get(&mut self) -> Result<ZControllerStatus, NanonisError> {
let result = self.quick_send("ZCtrl.StatusGet", vec![], vec![], vec!["H"])?;
if result.is_empty() {
return Err(NanonisError::Protocol(
"Empty response from ZCtrl.StatusGet".to_string(),
));
}
ZControllerStatus::try_from(result[0].as_u16()?)
}
}