visa_rs/instrument.rs
1use super::*;
2/// Session to a specified resource
3#[derive(Debug, PartialEq, Eq, Hash)]
4pub struct Instrument(pub(crate) OwnedSs);
5
6// One VISA operation can represent at most a 32-bit byte count.
7pub(crate) fn async_transfer_count(len: usize) -> vs::ViUInt32 {
8 len.min(vs::ViUInt32::MAX as usize) as vs::ViUInt32
9}
10
11impl std::io::Write for Instrument {
12 fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
13 <&Instrument>::write(&mut &*self, buf)
14 }
15
16 fn flush(&mut self) -> std::io::Result<()> {
17 <&Instrument>::flush(&mut &*self)
18 }
19}
20
21impl std::io::Read for Instrument {
22 fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> {
23 <&Instrument>::read(&mut &*self, buf)
24 }
25}
26
27impl std::io::Write for &Instrument {
28 fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
29 let mut ret_cnt: vs::ViUInt32 = 0;
30 wrap_raw_error_in_unsafe!(vs::viWrite(
31 self.as_raw_ss(),
32 buf.as_ptr(),
33 buf.len() as _,
34 &mut ret_cnt as _
35 ))
36 .map_err(vs_to_io_err)?;
37
38 Ok(ret_cnt as _)
39 }
40
41 fn flush(&mut self) -> std::io::Result<()> {
42 self.visa_flush(flags::FlushMode::IO_OUT_BUF)
43 .map_err(vs_to_io_err)
44 // Flush the low-level I/O buffer used by viWrite
45 }
46}
47
48impl std::io::Read for &Instrument {
49 fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> {
50 let mut ret_cnt: vs::ViUInt32 = 0;
51 wrap_raw_error_in_unsafe!(vs::viRead(
52 self.as_raw_ss(),
53 buf.as_mut_ptr(),
54 buf.len() as _,
55 &mut ret_cnt as _
56 ))
57 .map_err(vs_to_io_err)?;
58 Ok(ret_cnt as _)
59 }
60}
61
62impl Instrument {
63 ///Manually flushes the specified buffers associated with formatted I/O operations and/or serial communication.
64 pub fn visa_flush(&self, mode: flags::FlushMode) -> Result<()> {
65 wrap_raw_error_in_unsafe!(vs::viFlush(self.as_raw_ss(), mode.bits()))?;
66 Ok(())
67 }
68 /// Returns a user-readable description of the status code passed to the operation.
69 pub fn status_desc(&self, error: Error) -> Result<VisaString> {
70 let mut desc: VisaBuf = new_visa_buf();
71 wrap_raw_error_in_unsafe!(vs::viStatusDesc(
72 self.as_raw_ss(),
73 error.into(),
74 desc.as_mut_ptr() as _
75 ))?;
76 Ok(desc.try_into().unwrap())
77 }
78 /// Establishes an access mode to the specified resources.
79 ///
80 /// This operation is used to obtain a lock on the specified resource. The caller can specify the type of lock requested—exclusive or shared lock—and the length of time the operation will suspend while waiting to acquire the lock before timing out. This operation can also be used for sharing and nesting locks.
81 ///
82 /// The session that gained a shared lock can pass the accessKey to other sessions for the purpose of sharing the lock. The session wanting to join the group of sessions sharing the lock can use the key as an input value to the requestedKey parameter. VISA will add the session to the list of sessions sharing the lock, as long as the requestedKey value matches the accessKey value for the particular resource. The session obtaining a shared lock in this manner will then have the same access privileges as the original session that obtained the lock.
83 ///
84 ///It is also possible to obtain nested locks through this operation. To acquire nested locks, invoke the viLock() operation with the same lock type as the previous invocation of this operation. For each session, viLock() and viUnlock() share a lock count, which is initialized to 0. Each invocation of viLock() for the same session (and for the same lockType) increases the lock count. In the case of a shared lock, it returns with the same accessKey every time. When a session locks the resource a multiple number of times, it is necessary to invoke the viUnlock() operation an equal number of times in order to unlock the resource. That is, the lock count increments for each invocation of viLock(), and decrements for each invocation of viUnlock(). A resource is actually unlocked only when the lock count is 0.
85 ///
86 ///The VISA locking mechanism enforces arbitration of accesses to resources on an individual basis. If a session locks a resource, operations invoked by other sessions to the same resource are serviced or returned with a locking error, depending on the operation and the type of lock used. If a session has an exclusive lock, other sessions cannot modify global attributes or invoke operations, but can still get attributes and set local attributes. If the session has a shared lock, other sessions that have shared locks can also modify global attributes and invoke operations. Regardless of which type of lock a session has, if the session is closed without first being unlocked, VISA automatically performs a viUnlock() on that session.
87 ///
88 ///The locking mechanism works for all processes and resources existing on the same computer. When using remote resources, however, the networking protocol may not provide the ability to pass lock requests to the remote device or resource. In this case, locks will behave as expected from multiple sessions on the same computer, but not necessarily on the remote device. For example, when using the VXI-11 protocol, exclusive lock requests can be sent to a device, but shared locks can only be handled locally.
89 ///
90 /// see also [`Self::lock_exclusive`], [`Self::lock_shared`] and [`Self::lock_shared_with_key`]
91 ///
92 pub fn lock(
93 &self,
94 mode: flags::AccessMode,
95 timeout: Duration,
96 key: Option<AccessKey>,
97 ) -> Result<Option<AccessKey>> {
98 if (mode & flags::AccessMode::SHARED_LOCK).is_empty() {
99 wrap_raw_error_in_unsafe!(vs::viLock(
100 self.as_raw_ss(),
101 mode.bits(),
102 timeout.as_millis() as _,
103 vs::VI_NULL as _,
104 vs::VI_NULL as _
105 ))?;
106 Ok(None)
107 } else {
108 let mut ak = new_visa_buf();
109 wrap_raw_error_in_unsafe!(vs::viLock(
110 self.as_raw_ss(),
111 mode.bits(),
112 timeout.as_millis() as _,
113 key.map(|x| x.as_vi_const_string())
114 .unwrap_or(vs::VI_NULL as _),
115 ak.as_mut_ptr() as _
116 ))?;
117 Ok(Some(ak.try_into().unwrap()))
118 }
119 }
120
121 pub fn lock_exclusive(&self, timeout: Duration) -> Result<()> {
122 wrap_raw_error_in_unsafe!(vs::viLock(
123 self.as_raw_ss(),
124 flags::AccessMode::EXCLUSIVE_LOCK.bits(),
125 timeout.as_millis() as _,
126 vs::VI_NULL as _,
127 vs::VI_NULL as _
128 ))?;
129 Ok(())
130 }
131
132 pub fn lock_shared(&self, timeout: Duration) -> Result<AccessKey> {
133 let mut ak = new_visa_buf();
134 wrap_raw_error_in_unsafe!(vs::viLock(
135 self.as_raw_ss(),
136 flags::AccessMode::SHARED_LOCK.bits(),
137 timeout.as_millis() as _,
138 vs::VI_NULL as _,
139 ak.as_mut_ptr() as _
140 ))?;
141 Ok(ak.try_into().unwrap())
142 }
143
144 pub fn lock_shared_with_key(&self, timeout: Duration, key: AccessKey) -> Result<AccessKey> {
145 let mut ak = new_visa_buf();
146 wrap_raw_error_in_unsafe!(vs::viLock(
147 self.as_raw_ss(),
148 flags::AccessMode::SHARED_LOCK.bits(),
149 timeout.as_millis() as _,
150 key.as_vi_const_string() as _,
151 ak.as_mut_ptr() as _
152 ))?;
153 Ok(ak.try_into().unwrap())
154 }
155
156 ///Relinquishes a lock for the specified resource.
157 pub fn unlock(&self) -> Result<()> {
158 wrap_raw_error_in_unsafe!(vs::viUnlock(self.as_raw_ss()))?;
159 Ok(())
160 }
161
162 ///Enables notification of a specified event.
163 ///
164 ///The specified session can be enabled to queue events by specifying VI_QUEUE. Applications can enable the session to invoke a callback function to execute the handler by specifying VI_HNDLR. The applications are required to install at least one handler to be enabled for this mode. Specifying VI_SUSPEND_HNDLR enables the session to receive callbacks, but the invocation of the handler is deferred to a later time. Successive calls to this operation replace the old callback mechanism with the new callback mechanism.
165 ///
166 ///Specifying VI_ALL_ENABLED_EVENTS for the eventType parameter refers to all events which have previously been enabled on this session, making it easier to switch between the two callback mechanisms for multiple events.
167 ///
168 /// NI-VISA does not support enabling both the queue and the handler for the same event type on the same session. If you need to use both mechanisms for the same event type, you should open multiple sessions to the resource.
169 pub fn enable_event(
170 &self,
171 event_kind: event::EventKind,
172 mechanism: event::Mechanism,
173 ) -> Result<()> {
174 wrap_raw_error_in_unsafe!(vs::viEnableEvent(
175 self.as_raw_ss(),
176 event_kind as _,
177 mechanism as _,
178 event::EventFilter::Null as _
179 ))?;
180 Ok(())
181 }
182
183 /// Disables notification of the specified event type(s) via the specified mechanism(s).
184 ///
185 /// The viDisableEvent() operation disables servicing of an event identified by the eventType parameter for the mechanisms specified in the mechanism parameter. This operation prevents new event occurrences from being added to the queue(s). However, event occurrences already existing in the queue(s) are not flushed. Use viDiscardEvents() if you want to discard events remaining in the queue(s).
186 ///
187 /// Specifying VI_ALL_ENABLED_EVENTS for the eventType parameter allows a session to stop receiving all events. The session can stop receiving queued events by specifying VI_QUEUE. Applications can stop receiving callback events by specifying either VI_HNDLR or VI_SUSPEND_HNDLR. Specifying VI_ALL_MECH disables both the queuing and callback mechanisms.
188 ///
189 pub fn disable_event(
190 &self,
191 event_kind: event::EventKind,
192 mechanism: event::Mechanism,
193 ) -> Result<()> {
194 wrap_raw_error_in_unsafe!(vs::viDisableEvent(
195 self.as_raw_ss(),
196 event_kind as _,
197 mechanism as _,
198 ))?;
199 Ok(())
200 }
201 /// Discards event occurrences for specified event types and mechanisms in a session.
202 ///
203 /// The viDiscardEvents() operation discards all pending occurrences of the specified event types and mechanisms from the specified session. Specifying VI_ALL_ENABLED_EVENTS for the eventType parameter discards events of every type that is enabled for the given session.
204 ///
205 /// The information about all the event occurrences which have not yet been handled is discarded. This operation is useful to remove event occurrences that an application no longer needs. The discarded event occurrences are not available to a session at a later time.
206 ///
207 /// This operation does not apply to event contexts that have already been delivered to the application.
208 pub fn discard_events(
209 &self,
210 event: event::EventKind,
211 mechanism: event::Mechanism,
212 ) -> Result<()> {
213 wrap_raw_error_in_unsafe!(vs::viDiscardEvents(
214 self.as_raw_ss(),
215 event as _,
216 mechanism as _,
217 ))?;
218 Ok(())
219 }
220 /// Waits for an occurrence of the specified event for a given session.
221 ///
222 /// The viWaitOnEvent() operation suspends the execution of a thread of an application and waits for an event of the type specified by inEventType for a time period specified by timeout. You can wait only for events that have been enabled with the viEnableEvent() operation. Refer to individual event descriptions for context definitions. If the specified inEventType is VI_ALL_ENABLED_EVENTS, the operation waits for any event that is enabled for the given session. If the specified timeout value is VI_TMO_INFINITE, the operation is suspended indefinitely. If the specified timeout value is VI_TMO_IMMEDIATE, the operation is not suspended; therefore, this value can be used to dequeue events from an event queue.
223 ///
224 /// When the outContext handle returned from a successful invocation of viWaitOnEvent() is no longer needed, it should be passed to viClose().
225 ///
226 /// If a session's event queue becomes full and a new event arrives, the new event is discarded. The default event queue size (per session) is 50, which is sufficiently large for most applications. If an application expects more than 50 events to arrive without having been handled, it can modify the value of the attribute VI_ATTR_MAX_QUEUE_LENGTH to the required size.
227 pub fn wait_on_event(
228 &self,
229 event_kind: event::EventKind,
230 timeout: Duration,
231 ) -> Result<event::Event> {
232 let mut handler: vs::ViEvent = 0;
233 let mut out_kind: vs::ViEventType = 0;
234 wrap_raw_error_in_unsafe!(vs::viWaitOnEvent(
235 self.as_raw_ss(),
236 event_kind as _,
237 timeout.as_millis() as _,
238 &mut out_kind as _,
239 &mut handler as _
240 ))?;
241 let kind = event::EventKind::try_from(out_kind).expect("should be valid event type");
242 Ok(event::Event { handler, kind })
243 }
244
245 /// Installs handlers for event callbacks.
246 ///
247 /// The viInstallHandler() operation allows applications to install handlers on sessions. The handler specified in the handler parameter is installed along with any previously installed handlers for the specified event.
248 ///
249 /// VISA allows applications to install multiple handlers for an eventType on the same session. You can install multiple handlers through multiple invocations of the viInstallHandler() operation, where each invocation adds to the previous list of handlers. If more than one handler is installed for an eventType, each of the handlers is invoked on every occurrence of the specified event(s). VISA specifies that the handlers are invoked in Last In First Out (LIFO) order.
250 ///
251 /// *Note*: for some reason pass a closure with type `|instr, event|{...}` may get compile error.
252 /// Instead, use `|instr: & Instrument, event: & Event|{...}`.
253 pub fn install_handler<F: handler::Callback>(
254 &self,
255 event_kind: event::EventKind,
256 callback: F,
257 ) -> Result<handler::Handler<'_, F>> {
258 handler::Handler::new(self.as_ss(), event_kind, callback)
259 }
260
261 /// Reads a status byte of the service request.
262 ///
263 /// The IEEE 488.2 standard defines several bit assignments in the status byte. For example, if bit 6 of the status is set, the device is requesting service. In addition to setting bit 6 when requesting service, 488.2 devices also use two other bits to specify their status. Bit 4, the Message Available bit (MAV), is set when the device is ready to send previously queried data. Bit 5, the Event Status bit (ESB), is set if one or more of the enabled 488.2 events occurs. These events include power-on, user request, command error, execution error, device dependent error, query error, request control, and operation complete. The device can assert SRQ when ESB or MAV are set, or when a manufacturer-defined condition occurs. Manufacturers of 488.2 devices use the remaining lower-order bits to communicate the reason for the service request or to summarize the device state.
264 ///
265 pub fn read_stb(&self) -> Result<u16> {
266 let mut stb = 0;
267 wrap_raw_error_in_unsafe!(vs::viReadSTB(self.as_raw_ss(), &mut stb as *mut _))?;
268 Ok(stb)
269 }
270
271 /// The viClear() operation clears the device input and output buffers.
272 pub fn clear(&self) -> Result<()> {
273 wrap_raw_error_in_unsafe!(vs::viClear(self.as_raw_ss()))?;
274 Ok(())
275 }
276
277 /// Asserts the specified interrupt or signal.
278 ///
279 /// This operation can be used to assert a device interrupt condition. In VXI, for example, this can be done with either a VXI signal or a VXI interrupt. On certain bus types, the statusID parameter may be ignored.
280 /// statusID: This is the status value to be presented during an interrupt acknowledge cycle.
281 ///
282 /// # Warning:
283 /// I'm not sure if should use [CompletionCode](crate::enums::status::CompletionCode) as status_id as I'm not familiar with this function, let me know if you can help
284 pub fn assert_intr_signal(
285 &self,
286 how: enums::assert::AssertIntrHow,
287 status_id: vs::ViUInt32,
288 ) -> Result<()> {
289 wrap_raw_error_in_unsafe!(vs::viAssertIntrSignal(
290 self.as_raw_ss(),
291 how as _,
292 status_id as _
293 ))?;
294 Ok(())
295 }
296 /// Asserts software or hardware trigger.
297 ///
298 /// The viAssertTrigger() operation sources a software or hardware trigger dependent on the interface type.
299 ///
300 /// # Software Triggers for 488.2 Instruments (GPIB, VXI, TCPIP, and USB)
301 /// This operation sends an IEEE-488.2 software trigger to the addressed device. For software triggers, VI_TRIG_PROT_DEFAULT is the only valid protocol. The bus-specific details are:
302 ///
303 /// + For a GPIB device, VISA addresses the device to listen and then sends the GPIB GET command.
304 /// + For a VXI device, VISA sends the Word Serial Trigger command.
305 /// + For a USB device, VISA sends the TRIGGER message ID on the Bulk-OUT pipe.
306 ///
307 /// # Software Triggers for Non-488.2 Instruments (Serial INSTR, TCPIP SOCKET, and USB RAW)
308 /// If VI_ATTR_IO_PROT is VI_PROT_4882_STRS, this operations sends "*TRG\n" to the device; otherwise, this operation is not valid. For software triggers, VI_TRIG_PROT_DEFAULT is the only valid protocol.
309 ///
310 /// # Hardware Triggering for VXI
311 /// For hardware triggers to VXI instruments, VI_ATTR_TRIG_ID must first be set to the desired trigger line to use; this operation performs the specified trigger operation on the previously selected trigger line. For VXI hardware triggers, VI_TRIG_PROT_DEFAULT is equivalent to VI_TRIG_PROT_SYNC.
312 ///
313 /// # Trigger Reservation for PXI
314 /// For PXI instruments, this operation reserves or releases (unreserves) a trigger line for use in external triggering. For PXI triggers, VI_TRIG_PROT_RESERVE and VI_TRIG_PROT_UNRESERVE are the only valid protocols.
315 pub fn assert_trigger(&self, protocol: enums::assert::AssertTrigPro) -> Result<()> {
316 wrap_raw_error_in_unsafe!(vs::viAssertTrigger(self.as_raw_ss(), protocol as _))?;
317 Ok(())
318 }
319
320 /// Asserts or deasserts the specified utility bus signal.
321 ///
322 /// This operation can be used to assert either the SYSFAIL or SYSRESET utility bus interrupts on the VXIbus backplane. This operation is valid only on BACKPLANE (mainframe) and VXI SERVANT (servant) sessions.
323 ///
324 /// Asserting SYSRESET (also known as HARD RESET in the VXI specification) should be used only when it is necessary to promptly terminate operation of all devices in a VXIbus system. This is a serious action that always affects the entire VXIbus system.
325 pub fn assert_util_signal(&self, line: enums::assert::AssertBusSignal) -> Result<()> {
326 wrap_raw_error_in_unsafe!(vs::viAssertUtilSignal(self.as_raw_ss(), line as _))?;
327 Ok(())
328 }
329
330 /// Reads data from device or interface through the use of a formatted I/O read buffer.
331 ///
332 /// The viBufRead() operation is similar to viRead() and does not perform any kind of data formatting. It differs from viRead() in that the data is read from the formatted I/O read buffer—the same buffer used by viScanf() and related operations—rather than directly from the device. You can intermix this operation with viScanf(), but you should not mix it with viRead().
333 ///
334 /// * Note: If `buf` is empty, the `retCount` in [viBufRead](vs::viBufRead) is set to [VI_NULL](vs::VI_NULL), the number of bytes transferred is not returned. You may find this useful if you need to know only whether the operation succeeded or failed.
335 pub fn buf_read(&self, buf: &mut [u8]) -> Result<usize> {
336 let mut ret_cnt: vs::ViUInt32 = 0;
337 wrap_raw_error_in_unsafe!(vs::viBufRead(
338 self.as_raw_ss(),
339 if !buf.is_empty() {
340 buf.as_mut_ptr()
341 } else {
342 vs::VI_NULL as _
343 },
344 buf.len() as _,
345 &mut ret_cnt as _
346 ))?;
347 Ok(ret_cnt as _)
348 }
349
350 /// Writes data to a formatted I/O write buffer synchronously.
351 ///
352 /// The viBufWrite() operation is similar to viWrite() and does not perform any kind of data formatting. It differs from viWrite() in that the data is written to the formatted I/O write buffer—the same buffer used by viPrintf() and related operations—rather than directly to the device. You can intermix this operation with viPrintf(), but you should not mix it with viWrite().
353 ///
354 /// If this operation returns VI_ERROR_TMO, the write buffer for the specified session is cleared.
355 ///
356 /// * Note: If `buf` is empty, the `retCount` in [viBufWrite](vs::viBufWrite) is set to [VI_NULL](vs::VI_NULL), the number of bytes transferred is not returned. You may find this useful if you need to know only whether the operation succeeded or failed.
357 pub fn buf_write(&self, buf: &[u8]) -> Result<usize> {
358 let mut ret_cnt: vs::ViUInt32 = 0;
359 wrap_raw_error_in_unsafe!(vs::viBufWrite(
360 self.as_raw_ss(),
361 if !buf.is_empty() {
362 buf.as_ptr()
363 } else {
364 vs::VI_NULL as _
365 },
366 buf.len() as _,
367 &mut ret_cnt as _
368 ))?;
369 Ok(ret_cnt as _)
370 }
371
372 /// Sets the size for the formatted I/O and/or low-level I/O communication buffer(s).
373 pub fn set_buf(&self, mask: flags::BufMask, size: usize) -> Result<()> {
374 wrap_raw_error_in_unsafe!(vs::viSetBuf(self.as_raw_ss(), mask.bits(), size as _))?;
375 Ok(())
376 }
377}
378
379impl Instrument {
380 /// Reads data from device or interface asynchronously.
381 ///
382 /// The viReadAsync() operation asynchronously transfers data. The data read is to be stored in the buffer represented by buf. This operation normally returns before the transfer terminates.
383 ///
384 /// Before calling this operation, you should enable the session for receiving I/O completion events. After the transfer has completed, an I/O completion event is posted.
385 ///
386 /// The operation returns jobId, which you can use with either viTerminate() to abort the operation, or with an I/O completion event to identify which asynchronous read operation completed. VISA will never return VI_NULL for a valid jobID.
387 ///
388 /// If you have enabled VI_EVENT_IO_COMPLETION for queueing (VI_QUEUE), for each successful call to viReadAsync(), you must call viWaitOnEvent() to retrieve the I/O completion event. This is true even if the I/O is done synchronously (that is, if the operation returns VI_SUCCESS_SYNC).
389 ///
390 /// Returns the job id together with the completion code, which is
391 /// [`SuccessSync`](enums::status::CompletionCode::SuccessSync) when the transfer
392 /// already finished. In that case visa may have run the io completion handler before
393 /// this call even returned the job id, so anything tracking jobs by id must tolerate
394 /// a completion that arrives before the job is registered.
395 ///
396 /// Transfers at most `u32::MAX` bytes in one operation.
397 ///
398 /// # Safety
399 /// This function is unsafe because the `buf` passed in may be dropped before the transfer terminates
400 pub unsafe fn visa_read_async(
401 &self,
402 buf: &mut [u8],
403 ) -> Result<(JobID, enums::status::CompletionCode)> {
404 let mut id: vs::ViJobId = 0;
405 #[allow(unused_unsafe)]
406 let completion = wrap_raw_error_in_unsafe!(vs::viReadAsync(
407 self.as_raw_ss(),
408 buf.as_mut_ptr(),
409 async_transfer_count(buf.len()),
410 &mut id as _
411 ))?;
412 Ok((JobID(id), completion))
413 }
414
415 /// The viWriteAsync() operation asynchronously transfers data. The data to be written is in the buffer represented by buf. This operation normally returns before the transfer terminates.
416 ///
417 /// Before calling this operation, you should enable the session for receiving I/O completion events. After the transfer has completed, an I/O completion event is posted.
418 ///
419 /// The operation returns a job identifier that you can use with either viTerminate() to abort the operation or with an I/O completion event to identify which asynchronous write operation completed. VISA will never return VI_NULL for a valid jobId.
420 ///
421 /// If you have enabled VI_EVENT_IO_COMPLETION for queueing (VI_QUEUE), for each successful call to viWriteAsync(), you must call viWaitOnEvent() to retrieve the I/O completion event. This is true even if the I/O is done synchronously (that is, if the operation returns VI_SUCCESS_SYNC).
422 ///
423 ///
424 /// Returns the job id together with the completion code; see
425 /// [`visa_read_async`](Self::visa_read_async) for what
426 /// [`SuccessSync`](enums::status::CompletionCode::SuccessSync) implies.
427 ///
428 /// Transfers at most `u32::MAX` bytes in one operation.
429 ///
430 /// # Safety
431 /// This function is unsafe because the `buf` passed in may be dropped before the transfer terminates
432 pub unsafe fn visa_write_async(
433 &self,
434 buf: &[u8],
435 ) -> Result<(JobID, enums::status::CompletionCode)> {
436 let mut id: vs::ViJobId = 0;
437 #[allow(unused_unsafe)]
438 let completion = wrap_raw_error_in_unsafe!(vs::viWriteAsync(
439 self.as_raw_ss(),
440 buf.as_ptr(),
441 async_transfer_count(buf.len()),
442 &mut id as _
443 ))?;
444 Ok((JobID(id), completion))
445 }
446
447 /// Requests session to terminate normal execution of an operation.
448 ///
449 /// This operation is used to request a session to terminate normal execution of an operation, as specified by the jobId parameter. The jobId parameter is a unique value generated from each call to an asynchronous operation.
450 ///
451 /// If a user passes VI_NULL as the jobId value to viTerminate(), VISA will abort any calls in the current process executing on the specified vi. Any call that is terminated this way should return VI_ERROR_ABORT. Due to the nature of multi-threaded systems, for example where operations in other threads may complete normally before the operation viTerminate() has any effect, the specified return value is not guaranteed.
452 ///
453 pub fn terminate(&self, job_id: JobID) -> Result<()> {
454 wrap_raw_error_in_unsafe!(vs::viTerminate(
455 self.as_raw_ss(),
456 vs::VI_NULL as _,
457 job_id.0
458 ))?;
459 Ok(())
460 }
461 /// Wraps the instrument with async I/O support.
462 pub fn into_async(self) -> Result<async_io::AsyncInstrument> {
463 async_io::AsyncInstrument::new(self)
464 }
465
466 /// Tokio async IO adapter
467 #[cfg(feature = "tokio")]
468 pub fn into_tokio_async(self) -> Result<async_tokio::InstrumentTokioAdapter> {
469 self.try_into()
470 }
471}
472
473// GPIB operations
474impl Instrument {
475 /// Write GPIB command bytes on the bus.
476 ///
477 /// This operation attempts to write count number of bytes of GPIB commands to the interface bus specified by vi. This operation is valid only on GPIB INTFC (interface) sessions. This operation returns only when the transfer terminates.
478 ///
479 /// * Note: If `buf` is empty, the `retCount` in [viGpibCommand](vs::viGpibCommand) is set to [VI_NULL](vs::VI_NULL), the number of bytes transferred is not returned. You may find this useful if you need to know only whether the operation succeeded or failed.
480 pub fn gpib_command(&self, buf: &[u8]) -> Result<usize> {
481 let mut ret_cnt: vs::ViUInt32 = 0;
482 wrap_raw_error_in_unsafe!(vs::viGpibCommand(
483 self.as_raw_ss(),
484 if !buf.is_empty() {
485 buf.as_ptr()
486 } else {
487 vs::VI_NULL as _
488 },
489 buf.len() as _,
490 &mut ret_cnt as _
491 ))?;
492 Ok(ret_cnt as _)
493 }
494
495 /// Specifies the state of the ATN line and the local active controller state.
496 ///
497 /// This operation asserts or deasserts the GPIB ATN interface line according to the specified mode. The mode can also specify whether the local interface should acquire or release Controller Active status. This operation is valid only on GPIB INTFC (interface) sessions.
498 ///
499 /// It is generally not necessary to use the viGpibControlATN() operation in most applications. Other operations such as viGpibCommand() and viGpibPassControl() modify the ATN and/or CIC state automatically.
500 pub fn gpib_control_atn(&self, mode: enums::gpib::AtnMode) -> Result<()> {
501 wrap_raw_error_in_unsafe!(vs::viGpibControlATN(self.as_raw_ss(), mode as _))?;
502 Ok(())
503 }
504
505 /// Controls the state of the GPIB Remote Enable (REN) interface line, and optionally the remote/local state of the device.
506 ///
507 /// The viGpibControlREN() operation asserts or unasserts the GPIB REN interface line according to the specified mode. The mode can also specify whether the device associated with this session should be placed in local state (before deasserting REN) or remote state (after asserting REN). This operation is valid only if the GPIB interface associated with the session specified by vi is currently the system controller.
508 pub fn gpib_control_ren(&self, mode: enums::gpib::RenMode) -> Result<()> {
509 wrap_raw_error_in_unsafe!(vs::viGpibControlREN(self.as_raw_ss(), mode as _))?;
510 Ok(())
511 }
512
513 /// Tell the GPIB device at the specified address to become controller in charge (CIC).
514 ///
515 /// This operation passes controller in charge status to the device indicated by primAddr and secAddr, and then deasserts the ATN line. This operation assumes that the targeted device has controller capability. This operation is valid only on GPIB INTFC (interface) sessions.
516 ///
517 /// + `prim_addr`: Primary address of the GPIB device to which you want to pass control.
518 ///
519 /// + `sec_addr`: Secondary address of the targeted GPIB device. If the targeted device does not have a secondary address, this parameter should set as None or the value [VI_NO_SEC_ADDR](vs::VI_NO_SEC_ADDR).
520 ///
521 pub fn gpib_pass_control(
522 &self,
523 prim_addr: vs::ViUInt16,
524 sec_addr: impl Into<Option<vs::ViUInt16>>,
525 ) -> Result<()> {
526 wrap_raw_error_in_unsafe!(vs::viGpibPassControl(
527 self.as_raw_ss(),
528 prim_addr as _,
529 sec_addr.into().unwrap_or(vs::VI_NO_SEC_ADDR as _) as _
530 ))?;
531 Ok(())
532 }
533 /// Pulse the interface clear line (IFC) for at least 100 microseconds.
534 ///
535 /// This operation asserts the IFC line and becomes controller in charge (CIC). The local board must be the system controller. This operation is valid only on GPIB INTFC (interface) sessions.
536 ///
537 pub fn gpib_send_ifc(&self) -> Result<()> {
538 wrap_raw_error_in_unsafe!(vs::viGpibSendIFC(self.as_raw_ss(),))?;
539 Ok(())
540 }
541}