-
Notifications
You must be signed in to change notification settings - Fork 0
/
JVisa.java
628 lines (574 loc) · 21.5 KB
/
JVisa.java
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
/**
* @license
Copyright 2014 Günter Fuchs
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.
*
* @version 0.3
*/
package com.gpib;
import com.sun.jna.Memory;
import com.sun.jna.NativeLong;
import com.sun.jna.Pointer;
import com.sun.jna.ptr.ByteByReference;
import com.sun.jna.ptr.IntByReference;
import com.sun.jna.ptr.LongByReference;
import com.sun.jna.ptr.NativeLongByReference;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.nio.ByteBuffer;
import java.util.logging.FileHandler;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.logging.SimpleFormatter;
import java.nio.file.Paths;
import java.nio.file.Path;
import java.nio.file.Files;
import visa.VisaLibrary;
import visatype.VisatypeLibrary;
/**
* This class provides Java wrapper functions around the native Windows VISA API.
* @author Günter Fuchs (gfuchs@acousticmicroscopy.com)
* todo Test instantiating more than one instrument.
*/
public class JVisa {
/** version of this library */
public static final String JVISA_VERSION = "JVisa Version 0.3";
/** What is called viSession in Visa DLL becomes Handle in JVisa
so that viSession is not mistaken for a Java object.
The handle gets initialized only once when this class is loaded (first
time only initialization).
*/
protected static long visaResourceManagerHandle = 0;
/**
* number of bytes read
*/
long readCount;
/**
* This method gets the resource manager handle.
* @return handle
*/
public long getResourceManagerHandle() {
return visaResourceManagerHandle;
}
/**
* handle for one instrument
* This class handles only one instrument. To control more instruments
* instantiate one class per instrument. The resource manager is common (static)
* to all instances.
*/
protected NativeLong visaInstrumentHandle;
/**
* This method returns the handle for the instrument.
* @return instrument handle
*/
public long getInstrumentHandle() {
return visaInstrumentHandle.longValue();
}
/** default size for input buffer */
protected int bufferSizeDefault = 1024;
/** encoding of response when it is a string */
protected String responseEncoding = "UTF8";
/** the name of this class used by its logger */
protected static final String className = JVisa.class.getName();
/** logger of this class */
public static final Logger LOGGER = Logger.getLogger(className);
/** logger file handler */
public static FileHandler logFileHandler;
/** logger formatter */
public static SimpleFormatter logFormatter;
/** Log folder is added to the current path. */
public final String LOG_FOLDER = "log/";
/** constant when VISA return status is not success */
public long VISA_JAVA_ERROR = 0x7FFFFFFF;
/** JNA VISA functions return this status object */
public JVisaStatus statusObject;
/**
* constructor
*/
public JVisa() {
try {
statusObject = new JVisaStatus(bufferSizeDefault, responseEncoding);
// LOGGER.setLevel(Level.INFO);
LOGGER.setLevel(Level.SEVERE);
LOGGER.info(String.format("user.dir is %s", System.getProperty("user.dir")));
// todo Create log folder if it does not exist.
Path logPath = Paths.get(LOG_FOLDER);
if (Files.notExists(logPath)) {
Files.createDirectory(logPath);
}
logFileHandler = new FileHandler(String.format("%s%sLog.txt", LOG_FOLDER, JVisa.class.getSimpleName()));
logFormatter = new SimpleFormatter();
logFileHandler.setFormatter(logFormatter);
LOGGER.addHandler(logFileHandler);
}
catch(SecurityException | IOException e) {
LOGGER.log(Level.SEVERE, e.getMessage(), e);
}
}
/**
* This method returns the version of this library.
* @return version string
*/
// public static String getVersion() {
// return JVISA_VERSION;
// }
/**
* This method sets the path and file name for a log file.
* @param logPath path and full name of log file
*/
public void setLogFile(String logPath) {
try {
// Is closing necessary, or does removal close the file?
logFileHandler.close();
LOGGER.removeHandler(logFileHandler);
logFileHandler = new FileHandler(logPath);
LOGGER.addHandler(logFileHandler);
}
catch(SecurityException | IOException e) {
LOGGER.log(Level.SEVERE, e.getMessage(), e);
}
}
/**
* This method gets the resource manager handle.
* @return the visaResourceManagerHandle
*/
public long getVisaResourceManagerHandle() {
return visaResourceManagerHandle;
}
/**
* This method creates a session for a default resource manager.
* @return status of the operation
* todo VisaLibrary.ViStatus is the interface for a callback function. Implement it.
*/
public long openDefaultResourceManager() {
try {
LOGGER.info("Open resource manager.");
NativeLongByReference pViSession = new NativeLongByReference();
VisaLibrary.ViStatus visaStatus = VisaLibrary.INSTANCE.viOpenDefaultRM(pViSession);
statusObject.setStatus(visaStatus);
if (statusObject.visaStatusLong != VisatypeLibrary.VI_SUCCESS) {
return statusObject.visaStatusLong;
}
LOGGER.info(String.format("visaStatus = 0x%08X", statusObject.visaStatusLong));
visaResourceManagerHandle = pViSession.getValue().longValue();
if (visaResourceManagerHandle != 0) {
statusObject.printStatusDescription(visaResourceManagerHandle);
statusObject.resourceManagerHandle = visaResourceManagerHandle;
}
// Install event handler.
// JVisaEvent eventObject = new JVisaEvent(userHandle);
// JVisaCallback callback = new JVisaCallback(eventObject);
// Pointer pUserHandle = new LongByReference(userHandle).getPointer();
// visaStatus = TkVISA64Library.INSTANCE.viInstallHandler(
// new NativeLong(visaResourceManagerHandle),
// new NativeLong(TkVISA64Library.VI_EVENT_EXCEPTION),
// eventObject.getHandlerType(),
// pUserHandle);
// statusObject.setStatus(visaStatus);
// if (statusObject.visaStatusLong != VisatypeLibrary.VI_SUCCESS) {
// return statusObject.visaStatusLong;
// }
}
catch (Error | Exception e) {
LOGGER.log(Level.SEVERE, e.getMessage(), e);
statusObject.resourceManagerHandle = 0;
return VISA_JAVA_ERROR;
}
return statusObject.visaStatusLong;
}
/**
* This method closes the resource manager.
* @return status of the operation
*/
public long closeResourceManager() {
try {
LOGGER.info("Close resource manager.");
VisaLibrary.ViStatus visaStatus = VisaLibrary.INSTANCE.viClose(new NativeLong(visaResourceManagerHandle));
statusObject.setStatus(visaStatus);
statusObject.resourceManagerHandle = visaResourceManagerHandle = 0;
}
catch (Exception e) {
LOGGER.log(Level.SEVERE, e.getMessage(), e);
return VISA_JAVA_ERROR;
}
return statusObject.visaStatusLong;
}
/**
* This method gets an attribute of type byte (native ViUInt8).
* @param attribute which attribute to get
* @param value contains an attribute of type short
* @param sessionHandle handle of resource manager or instrument
* @return status of the operation
*/
public long getAttribute(int attribute, JVisaReturnNumber value, long sessionHandle) {
try {
VisaLibrary.ViStatus visaStatus;
String formatString = "Attribute value = 0x";
LOGGER.info(String.format("Get attribute %08X.", attribute));
if (value.returnNumber instanceof Short) {
ByteByReference pByte = new ByteByReference();
visaStatus = VisaLibrary.INSTANCE.viGetAttribute(
new NativeLong(visaResourceManagerHandle),
new NativeLong(attribute), pByte.getPointer());
value.returnNumber = pByte.getValue();
formatString += "%02X";
}
else if (value.returnNumber instanceof Integer) {
IntByReference pInt = new IntByReference();
visaStatus = VisaLibrary.INSTANCE.viGetAttribute(
new NativeLong(visaResourceManagerHandle),
new NativeLong(attribute), pInt.getPointer());
value.returnNumber = pInt.getValue();
formatString += "%04X";
}
else if (value.returnNumber instanceof Long) {
LongByReference pLong = new LongByReference();
visaStatus = VisaLibrary.INSTANCE.viGetAttribute(
new NativeLong(visaResourceManagerHandle),
new NativeLong(attribute), pLong.getPointer());
value.returnNumber = pLong.getValue();
formatString += "%08X";
}
else {
return VISA_JAVA_ERROR;
}
statusObject.setStatus(visaStatus);
LOGGER.info(String.format(formatString, value.returnNumber));
}
catch (Exception e) {
LOGGER.log(Level.SEVERE, e.getMessage(), e);
return VISA_JAVA_ERROR;
}
return statusObject.visaStatusLong;
}
/**
* This method gets an attribute of type String (native ViPChar).
* @param attribute which attribute to get
* @param value contains an attribute of type String
* @param sessionHandle handle of resource manager or instrument
* @return status of the operation
*/
public long getAttribute(int attribute, JVisaReturnString value, long sessionHandle) {
try {
LOGGER.info(String.format("Get attribute %08X.", attribute));
Memory responseBuffer = new Memory(bufferSizeDefault);
VisaLibrary.ViStatus visaStatus = VisaLibrary.INSTANCE.viGetAttribute(
new NativeLong(visaResourceManagerHandle),
new NativeLong(attribute),
(Pointer) responseBuffer);
statusObject.setStatus(visaStatus);
value.returnString = responseBuffer.getString(0, responseEncoding).trim();
LOGGER.info(String.format("Attribute value = %s", value.returnString));
}
catch (Exception e) {
LOGGER.log(Level.SEVERE, e.getMessage(), e);
return VISA_JAVA_ERROR;
}
return statusObject.visaStatusLong;
}
/**
* This method sets an attribute.
* @param attribute which attribute to get
* @param value contains an attribute
* @param sessionHandle handle of resource manager or instrument
* @return status of the operation
* todo Investigate whether the Java signed int variable value gets converted
* correctly to unsigned int in NativeLong(value). Sometimes, msb is
* set in an attribute, e.g. VI_ATTR_RECV_TCPIP_ADDR is 0xBFFF4198UL.
*/
public long setAttribute(int attribute, int value, long sessionHandle) {
try {
LOGGER.info(String.format("Set attribute %08X to %08X.", attribute, value));
VisaLibrary.ViStatus visaStatus = VisaLibrary.INSTANCE.viSetAttribute(
new NativeLong(sessionHandle),
new NativeLong(attribute),
new NativeLong(value));
statusObject.setStatus(visaStatus);
}
catch (Exception e) {
LOGGER.log(Level.SEVERE, e.getMessage(), e);
return VISA_JAVA_ERROR;
}
return statusObject.visaStatusLong;
}
/**
* This method sets an attribute for a resource manager.
* @param attribute which attribute to get
* @param value contains an attribute
* @return status of the operation
*/
public long setAttribute(int attribute, int value) {
return setAttribute(attribute, value, visaResourceManagerHandle);
}
/**
* This method sets the communication timeout.
* @param timeout in ms
* @return status of the operation
*/
public long setTimeout(int timeout) {
try {
LOGGER.info("Set timeout.");
long visaStatus = setAttribute(VisaLibrary.VI_ATTR_TMO_VALUE, timeout, getInstrumentHandle());
if (visaStatus != VisatypeLibrary.VI_SUCCESS) {
return visaStatus;
}
return visaStatus;
}
catch (Exception e) {
LOGGER.log(Level.SEVERE, e.getMessage(), e);
return VISA_JAVA_ERROR;
}
}
/**
* This method gets the version of the resource (TekVisa.dll).
* @param version resource version number
* @return status of the operation
*/
public long getResourceVersion(JVisaReturnNumber version) {
try {
LOGGER.info("Get resource version.");
long visaStatus = getAttribute(VisaLibrary.VI_ATTR_RSRC_SPEC_VERSION, version, visaResourceManagerHandle);
if (visaStatus != VisatypeLibrary.VI_SUCCESS) {
return visaStatus;
}
LOGGER.info(String.format("Resource version = 0x%08X", version.returnNumber));
return visaStatus;
}
catch (Exception e) {
LOGGER.log(Level.SEVERE, e.getMessage(), e);
return VISA_JAVA_ERROR;
}
}
/**
* This method converts a Java String to a ByteBuffer / C-type string.
* @param source string to convert
* @return Java string converted to C-type string (0 terminated)
*/
public ByteBuffer stringToByteBuffer(String source) {
try {
ByteBuffer dest = ByteBuffer.allocate(source.length() + 1);
dest.put(source.getBytes(responseEncoding));
dest.position(0);
return dest;
}
catch (UnsupportedEncodingException e) {
LOGGER.log(Level.SEVERE, e.getMessage(), e);
return null;
}
}
/**
* Opens an instrument session.
* @param instrument string that contains the instrument address and bus interface
* @return status of the operation
*/
public long openInstrument(String instrument) {
VisaLibrary.ViStatus visaStatus;
NativeLongByReference pViInstrument = new NativeLongByReference();
try {
LOGGER.info(String.format("Open instrument %s.", instrument));
ByteBuffer pViString = stringToByteBuffer(instrument);
if (pViString == null) {
return VISA_JAVA_ERROR;
}
visaStatus = VisaLibrary.INSTANCE.viOpen(
new NativeLong(visaResourceManagerHandle),
pViString, // byte buffer for instrument string
new NativeLong(0), // access mode (locking or not). 0:Use Visa default
new NativeLong(0), // timeout, only when access mode equals locking,
pViInstrument // pointer to instrument object
);
statusObject.setStatus(visaStatus);
if (statusObject.visaStatusLong != VisatypeLibrary.VI_SUCCESS) {
LOGGER.log(Level.SEVERE, String.format("Could not open session for %s.", instrument), (Throwable) null);
return statusObject.visaStatusLong;
}
else {
if (statusObject.visaStatusLong == VisatypeLibrary.VI_SUCCESS) {
visaInstrumentHandle = pViInstrument.getValue();
LOGGER.info(String.format("viInstrument = 0x%08X.", visaInstrumentHandle.longValue()));
}
else {
visaInstrumentHandle = new NativeLong(0);
}
}
}
catch (Exception e) {
LOGGER.log(Level.SEVERE, e.getMessage(), e);
return VISA_JAVA_ERROR;
}
return VisatypeLibrary.VI_SUCCESS;
}
/**
* This method closes an instrument session.
* @return status of the operation
*/
public long closeInstrument() {
VisaLibrary.ViStatus visaStatus;
try {
LOGGER.info("Close instrument.");
visaStatus = VisaLibrary.INSTANCE.viClose(visaInstrumentHandle);
statusObject.setStatus(visaStatus);
if (statusObject.visaStatusLong != VisatypeLibrary.VI_SUCCESS) {
LOGGER.severe("Could not close session.");
return VISA_JAVA_ERROR;
}
return VisatypeLibrary.VI_SUCCESS;
}
catch (Exception e) {
LOGGER.log(Level.SEVERE, e.getMessage(), e);
return VISA_JAVA_ERROR;
}
}
/**
* @return the visaInstrumentHandle as long
*/
public long getVisaInstrumentHandle() {
return visaInstrumentHandle.longValue();
}
/**
* This method sends buffer content (usually a command) to the instrument.
* @param command command or other ASCII data
* @return status of the operation
*/
public long write(String command) {
VisaLibrary.ViStatus visaStatus;
try {
LOGGER.info(String.format("Write command \"%s\".", command));
ByteBuffer pBuffer = stringToByteBuffer(command);
if (pBuffer == null) {
return VISA_JAVA_ERROR;
}
long commandLength = command.length();
NativeLongByReference returnCount = new NativeLongByReference();
visaStatus = VisaLibrary.INSTANCE.viWrite(
visaInstrumentHandle, pBuffer, new NativeLong(commandLength), returnCount);
statusObject.setStatus(visaStatus);
if (statusObject.visaStatusLong != VisatypeLibrary.VI_SUCCESS) {
LOGGER.severe(String.format("Could not write %s.", command));
}
else {
long count = returnCount.getValue().longValue();
if (count != commandLength) {
LOGGER.severe(String.format("Could only write %d instead of %d bytes.", count, commandLength));
return VISA_JAVA_ERROR;
}
}
return VisatypeLibrary.VI_SUCCESS;
}
catch (Exception e) {
LOGGER.log(Level.SEVERE, e.getMessage(), e);
return VISA_JAVA_ERROR;
}
}
/**
* This method reads data from the instrument, e.g. a command response or data.
* @param response response buffer
* @param bufferSize size of response buffer in bytes
* @return status of the operation
*/
protected long read(ByteBuffer response, int bufferSize) {
VisaLibrary.ViStatus visaStatus;
try {
LOGGER.info("Read response.");
NativeLongByReference returnCount = new NativeLongByReference();
visaStatus = VisaLibrary.INSTANCE.viRead(
visaInstrumentHandle, response, new NativeLong(bufferSize), returnCount);
statusObject.setStatus(visaStatus);
readCount = returnCount.getValue().longValue();
if (statusObject.visaStatusLong != VisatypeLibrary.VI_SUCCESS) {
if (readCount == 0) {
LOGGER.severe("Reading count is 0.");
return VISA_JAVA_ERROR;
}
}
return VisatypeLibrary.VI_SUCCESS;
}
catch (Exception e) {
LOGGER.log(Level.SEVERE, e.getMessage(), e);
return VISA_JAVA_ERROR;
}
}
/**
* This method reads a string from the instrument, e.g. a command response.
* @param response response string
* @param bufferSize size of response buffer in bytes
* @return status of the operation
*/
public long read(JVisaReturnString response, int bufferSize) {
long visaStatus;
try {
ByteBuffer buffer = ByteBuffer.allocate(bufferSize);
visaStatus = read(buffer, bufferSize);
if (visaStatus == VISA_JAVA_ERROR) {
return visaStatus;
}
response.returnString = new String(buffer.array(), 0, (int) readCount, responseEncoding).trim();
LOGGER.info(response.returnString);
return VisatypeLibrary.VI_SUCCESS;
}
catch (UnsupportedEncodingException e) {
LOGGER.log(Level.SEVERE, e.getMessage(), e);
return VISA_JAVA_ERROR;
}
}
/**
* This method reads a string from the instrument, usually a command response.
* @param response response string
* @return status of the operation
*/
public long read(JVisaReturnString response) {
return read(response, bufferSizeDefault);
}
/**
* This method reads a byte array from the instrument, usually a command response.
* @param response response byte array
* @param bufferSize size of response buffer in bytes
* @return status of the operation
*/
public long read(JVisaReturnBytes response, int bufferSize) {
long visaStatus;
try {
readCount = 0;
ByteBuffer buffer = ByteBuffer.allocate(bufferSize);
visaStatus = read(buffer, bufferSize);
if (visaStatus == VISA_JAVA_ERROR) {
return visaStatus;
}
response.returnBytes = new byte[(int) readCount];
System.arraycopy(buffer.array(), 0, response.returnBytes, 0, (int) readCount);
return VisatypeLibrary.VI_SUCCESS;
}
catch (Exception e) {
LOGGER.log(Level.SEVERE, e.getMessage(), e);
return VISA_JAVA_ERROR;
}
}
/**
* This method clears the instrument.
* @return status of the operation
*/
public long clear() {
VisaLibrary.ViStatus visaStatus;
try {
LOGGER.info("Send viClear.");
visaStatus = VisaLibrary.INSTANCE.viClear(visaInstrumentHandle);
statusObject.setStatus(visaStatus);
if (statusObject.visaStatusLong != VisatypeLibrary.VI_SUCCESS) {
LOGGER.severe("Could not send viClear.");
}
return VisatypeLibrary.VI_SUCCESS;
}
catch (Exception e) {
LOGGER.log(Level.SEVERE, e.getMessage(), e);
return VISA_JAVA_ERROR;
}
}
}