B. Listati dei programmi
B.1 Il package device
Il package device contiene la sola
classe ControllableDevice superclasse dei
dispositivi controllabili.
La classe ControllableDevice
/*
* @(#)
ControllableDevice.java v.0.9 - Gennaio 1997 - by Donato Cappetta
*/
package
device;
/**
* Classe
astratta ControllableDevice che e' una superclasse
* per
i dispositivi elettronici controllabili.
*
* @see
java.lang.Object
* @version
0.9beta Gennaio 1997
* @author
Donato Cappetta <cappetta@diiie.unisa.it>
*/
public
abstract class
ControllableDevice {
/**
* Metodo
che informa se il dispositivo e gia'in uso.
*
* @return
boolean Dispositivo in uso o meno.
*/
public
abstract boolean
inUse();
/**
* Metodo
astratto che informa se il dispositivo puo' essere condiviso
* fra
piu utenti.
*
* @return
'true' se condivisibile o 'false' altrimenti.
*/
public
abstract boolean
isShareble();
/**
* Metodo
astratto che inizializza e istanzia le risorse per
* un nuovo
utente.
*/
public
abstract synchronized
void open();
/**
* Metodo
astratto che chiude e rilascia le risorse.
*/
public
abstract synchronized
void close();
/**
* Metodo
astratto che rappresenta i comandi che possono essere
* impartiti
al dispositivo.
*
* @param
obj Oggetto che informa il dispositivo le operazioni da compiere.
* @return
Risultato dell'operazione.
*/
public
abstract synchronized
Object execute(Object obj);
/**
* Metodo
che restituisce il nome della classe corrente.
*
* @return
Nome della classe corrente.
*/
public
String toString() {
return
this.getClass().getName();
}
} //end
class ControllableObject
B.2 Il package device.server
Questo package contiene le classi: ServerDevice
e ConnectionDevice come previsto in fase
di progetto, inoltre contiene l’interfaccia ID_Messsage
che consente di stabilire un protocollo al livello delle applicazioni e
la classe IllegalSubclassException che
genera un’eccezione quando si prova a caricare dinamicamente una classe
e questa non è sottoclasse di una specifica superclasse.
La classe ServerDevice
/*
* @(#)ServerDevice.java
v.0.9 Gennaio 1997 - by Donato Cappetta
*/
package
device.server;
import
java.io.*;
import
java.net.*;
import
java.util.Vector;
import
java.awt.*;
import
device.server.*;
import
device.ControllableDevice;
/**
* Applicazione
server per comunicazione client-server.
* In fase
di avvio ServerDevice carica in un vettore i dispositivi
* controllabili
che gli vengono forniti come parametri.<br>
* ServerDevice
sta in ascolto su una porta specificata in attesa
* di una
connessione. Accettata la connessione ServerDevice affida
* la comunicazione
con il client all'oggetto ConnectionDevice in
* esecuzione
in un Thread, e ServerDevice si pone di nuovo in attesa
* di una'altra
connessione.<br>
* Al thread
viene passato come parametro il vettore dei dispositivi
* e il
socket che ha accettato la connesione
* @see
java.lang.Thread
* @version
0.9 Gennaio 1997
* @author
Donato Cappetta <cappetta@diiie.unisa.it>
*/
public
class ServerDevice extends
Thread {
/**
* Variabile
per acquisire il valore della porta di ascolto
* dalla
linea di comandi.
* Valore
di default 4444.
*/
private
int port = 4444;
/**
* serverSocket
per l'ascolto della connessione.
*/
private
ServerSocket serverSocket = null;
/**
* Nome
e indirizzo della macchina su cui ServerDevice va in esecuzione.
*/
private
InetAddress inetAddress = null;
/**
* Oggetto
di tipo ControllableDevice per caricare
* dinamicamente
le classi.
*/
private
ControllableDevice cd = null;
/**
* Vettore
che contiene le istanze dei dispositivi controllabili
* caricati
dinamicamente.
*/
private
Vector vectorDevice = new Vector();
/**
* Variabile
booleana
*/
private
boolean bool = true;
/**
* Frame
e area di testo inseriti a scopo di debug.
*/
private
Frame frame = null;
/**
* L'area
di testo e dichiarata static in modo che anche altri thread
* possano
stampare messaggi.
*/
public
static TextArea ta = null;
/**
* Metodo
richiamato in caso di fallimento,
* stampa
l'eccezione ed esce.
*
* @param
str Messaggio di errore impostato dal programmatore
* @param
e Eccezione
*/
private
void fail (String str, Exception e) {
ta.appendText(str
+ ": " + e.getMessage() + '\n');
ta.appendText("ServerDevice
v.0.9 - Gennaio 1997 by Donato Cappetta." +'\n');
frame.dispose();
System.exit(0);
} //end
fail()
/**
* Costruttore.
*
* @param
args[] Lista delle classi di tipo ControllableDevice
* da caricare
dinamicamente.
* @param
port Porta di ascolto per il serverSocket, se port = 0
* si considera
la porta di default.
*/
public
ServerDevice(int port, String[] args) {
super("ServerDevice");
frame = new
Frame("Stato ServerDevice");
ta = new
TextArea();
ta.setEditable(false);
frame.add("Center",
ta);
frame.resize(300,400);
frame.show();
if ((port > 0x0) && (port <= 0xFFFF)) {
this.port = port;
}
try
{
ta.setText("ServerDevice
v.0.9 - Gennaio 1997 by Donato Cappetta" + '\n');
ta.appendText("Avvio
di ServerDevice sulla porta: " + this.port
+'');
inetAddress = InetAddress.getLocalHost();
ta.appendText("Identificazione
di questa macchina: " + inetAddress +'\n');
serverSocket = new
ServerSocket(this.port);
} catch
(UnknownHostException uhe) {
fail("ServerDevice->
Eccezione nell'individuare il nome di questa macchina. ", uhe);
} catch
(IOException ioe) {
fail("ServerDevice->
Eccezione nel creare un ServerSocket. ", ioe);
} //end
try catch()
for
(int i = 0; i
< args.length; i++) {
try
{
ta.appendText("\n"
+ i + ") Caricamento del dispositivo " + args[i]
+ " in corso ... ");
cd = (ControllableDevice)loadSubclassforName(args[i],
"device.ControllableDevice");
vectorDevice.addElement(cd);
ta.appendText("
Fatto " + '\n');
} catch(IllegalSubclassException
isce) {
ta.appendText('' + "Impossibile
caricare " + args[i] + ". Non sottoclasse
di ControllableDevice--> " + isce.getMessage());
} catch(ClassNotFoundException
cnfe){
ta.appendText('' + "Impossibile
caricare " + args[i] + ". Classe non trovata
--> " + cnfe.getMessage());
} catch(InstantiationException
ie) {
ta.appendText('' + "Impossibile
caricare " + args[i] + ". Eccezione nel creare
l'istanza della classe --> " + ie.getMessage());
} catch(
IllegalAccessException iae) {
ta.appendText('' + "Impossibile
caricare " + args[i] + ". Eccezione durane
l'accesso alla classe --> " + iae.getMessage());
} catch(UnsatisfiedLinkError
ule) {
ta.appendText('' + "DLL
non trovata --> " + ule.getMessage());
}// try-catch()
} //end
for.
ta.appendText('' + "----------------------------------------------------------------"
+ '');
ta.appendText("Controllo
dei dispositivi correttamente caricati: " +'\n');
for
(int i = 0; i
< vectorDevice.size(); i++) {
ControllableDevice cd = (ControllableDevice)vectorDevice.elementAt(i);
ta.appendText(i + ")
" + cd.toString() +'\n');
} //end
for
ta.appendText("----------------------------------------------------------------"
+ '');
this.start();
} //end
costruttore ServerDevice.
/**
* Un ciclo
infinito che ascolta e servire le connessioni.
* Per
ogni connesione accettata viene creato un nuovo thread che
* gestisce
la connessione.
* I parametri
che vengono passati a ConnectionDevice, in esecuzione nel
* thread,
sono il socket restituito dalla connesione accettata e il
* vettore
contenente le istanze dei dispositivi disponibili al
* controllo.
*/
public
void run() {
ta.appendText("\nServerDevice
in attesa di connessioni sulla porta " + port + "
... ");
while (bool) {
Socket clientSocket = null;
try {
clientSocket = serverSocket.accept();
} catch (IOException ioe) {
ta.appendText("ServerDevice --> Accept fallito: "
+ port +
", " + ioe.getMessage() +'');
ta.appendText("ServerDevice in attesa di connessioni
sulla porta " + port + " ... " + '\n');
continue;
} //end try-catch()
ConnectionDevice connectionDevice = new ConnectionDevice(clientSocket,
vectorDevice);
} //end
while()
} //end
run()
/**
* Metodo
che restituisce un'instanza di una classe, a partire
* da una
stringa che rappresenta il nome della classe.
*
* @param
classString Stringa che rappresenta il nome della classe.
* @param
superClassstring Stringa che rappresenta il nome della superclasse
* di classString.
* @return
Object Istanza della classe rappresentata da classString
* @exception
IllegalSubclassException La classe rappresentata da classString
* non
ha come superclasse superClassString.
* @exception
ClassNotFoundException
* @exception
InstantiationException
* @exception
IllegalAccessException
*
*/
private
Object loadSubclassforName(String classString, String superclassString)
throws IllegalSubclassException,
ClassNotFoundException,
InstantiationException, IllegalAccessException
{
Class classObject = null;
Class classTemp = null;
String className = null;
try
{
classObject = Class.forName(classString);
} catch
(ClassNotFoundException cnfe) {
throw
cnfe;
} //end
try-catch
for
(classTemp = classObject, className = classTemp.getName();
!(className.equals("java.lang.Object")
||
className.equals(superclassString));
) {
classTemp = classTemp.getSuperclass();
className = classTemp.getName();
} //end
for
if
((className == null) || className.equals("java.lang.Object"))
{
throw
new IllegalSubclassException(classString);
} else
if(className.equals(superclassString)) {
try
{
return
classObject.newInstance();
} catch
(InstantiationException ie) {
throw
ie;
} catch
(IllegalAccessException iae) {
throw
iae;
} //end
try-catch
} else
{
//throw
new Exception();
return
null;
} //end
if - else
} //end
loadSubclassforName()
} // end
class ServerDevice
La classe ConnectionDevice
/*
* @(#)
ConnectionDevice.java 0.9 Gennaio 1997 - by Donato Cappetta
*/
package
device.server;
import
device.ControllableDevice;
import
java.io.*;
import
java.net.*;
import
java.util.Vector;
/**
* Questa
classe e il thread che gestisce la comunicazione
* con
il client.
* ServerDevice
acceta la connesione e genera questa thread.
*
* @version
0.9beta Gennaio 1997
* @author
Donato Cappetta <cappetta@diiie.unisa.it>
*/
public
class ConnectionDevice extends
Thread implements device.server.ID_Message
{
/**
* Variabile
di classe che indica il numero delle connessioni.
*/
static
int connectionNumber = 1;
/**
* Socket
per la comunicazione con il client.
*/
private
Socket clientSocket = null;
/**
* Stream
di input associato al socket.
*/
private
ObjectInputStream is = null;
/**
* Stream
di output associato al socket.
*/
private
ObjectOutputStream os = null;
private
boolean bool = true;
private
boolean isOpenDevice = false;
/**
* Dispositivo
da controllare.
*/
private
ControllableDevice controllableDevice = null;
/**
* Vettore
di tutti i dispositivi disponibili per il controllo
*/
private
Vector vectorDevice = null;
/**
* Metodo
richiamato in caso di fallimento,
* stampa
l'eccezione ed esce.
* @param
str Messaggio di errore impostato dal programmatore
* @param
e Eccezione
*/
private
void fail (String str, Exception e) {
ServerDevice.ta.appendText(str
+ ": " + e.getMessage() + '');
ServerDevice.ta.appendText("ConnectionDevice
v.0.9 - Gennaio 1997 by Donato Cappetta." + '\n');
System.exit(1);
} //end
fail()
/**
* Costruttore.
Inizializza gli stream e avvia il thread.
* @param
clientSocket socket client per la connessione.
* @param
vectorDevice vettore dei dispositivi disponibili.
*/
public
ConnectionDevice(Socket clientSocket, Vector vectorDevice) {
super("Connessione:"
+ connectionNumber++);
this.vectorDevice
= vectorDevice;
this.clientSocket
= clientSocket;
ServerDevice.ta.appendText(''
+ this.toString() + '');
try
{
os = new
ObjectOutputStream(new BufferedOutputStream(clientSocket.getOutputStream()));
try
{
is = new
ObjectInputStream(new BufferedInputStream(clientSocket.getInputStream()));
} catch
(StreamCorruptedException sce){
fail("Eccezione
: ", sce);
} catch(IOException
ioe){
throw
ioe;
}
} catch
(IOException ioe) {
try
{
this.clientSocket.close();
} catch
(IOException ioex){}
fail ("Eccezione
nel caricamento del socket streams. " , ioe);
} //end
try catch()
this.start();
} //end
costruttore ConnectionDevice()
/**
* Fornisce
un servizio.
*/
public
void run() {
String stringClass = null;
Object objInput = null;
Object objOutput = null;
byte
ID_Input, ID_Output;
boolean
isInVector = false;
try
{
try
{
//invia
un messagggio di acknowledgment al client
os.writeByte(ID_ACK);
os.flush();
} catch(IOException
ioe) {
//se ci
sono problemi di comunicazione rilancia l'eccezione.
throw
ioe;
} //end
try-catch()
//attende
il nome della classe
stringClass = is.readUTF();
if(stringClass
== null) { return;}
//System.out.println("ConnectionDevice-->
Dispositivo da controllare: " + stringClass);
ServerDevice.ta.appendText("Dispositivo
richiesto: " + stringClass +'\n');
//verifica
se il dispositivo e in elenco.
for
(int i = 0; i
< vectorDevice.size(); i++) {
ControllableDevice cd = (ControllableDevice)vectorDevice.elementAt(i);
if
(stringClass.equals(cd.toString())) {
controllableDevice = cd;
isInVector = true;
ServerDevice.ta.appendText("Dispositivo
esistente." + '\n');
break;
} //end
if
} //end
for
//se il
dispositivo non c'e' termina
if
(!isInVector) {
try
{
ServerDevice.ta.appendText("Dispositivo
inesistente. " + '\n');
os.writeByte(ID_STOP);
os.writeUTF("Dispositivo
richiesto inesistente.");
os.flush();
}catch
(IOException ioe){
throw
ioe;
}
throw
new Exception(" -->Dispositivo
inesistente.");
}
//se il
dispositivi non e in uso
if
(!controllableDevice.inUse()) {
//Se non
ci sono eccezioni invia un messaggio di ok
try
{
controllableDevice.open();
isOpenDevice = true;
os.writeByte(ID_OKDEVICE);
os.writeUTF("Dispositivo
pronto ... ");
os.flush();
ServerDevice.ta.appendText("Dispositivo
pronto ..." + '\n');
} catch
(IOException ioe) {
throw
ioe;
}
//se il
dispositivo e in uso ma condivisibile
} else
if (controllableDevice.inUse() &&
controllableDevice.isShareble()) {
try
{
os.writeByte(ID_OKDEVICE);
os.writeUTF("Dispositivo
pronto ...");
os.flush();
ServerDevice.ta.appendText("Dispositivo
pronto ..." + '\n');
}catch(IOException
ioe) {
throw
ioe;
}
//altrimenti
... STOP
}else{
try
{
os.writeByte(ID_STOP);
os.writeUTF("Dispositivo
in uso. ");
os.flush();
ServerDevice.ta.appendText("Dispositivo
in uso." + '\n');
}catch(IOException
ioe) {
throw
ioe;
}//end
try-catch()
//lancia
l'eccezione al gestore piu esterno
//che
chiude la connesione
throw
new Exception (" -->
Dispositivo in uso");
} //end
if else-if else
//corpo
del programma che si occupa della connessione
while
(bool) {
objInput = is.readObject();
objOutput = controllableDevice.execute(objInput);
try
{
//invia
il risulta a client
os.writeObject(objOutput);
os.flush();
} catch(IOException
ioe) {
throw
ioe;
}
} //end
while()
} catch(IOException
ioe) {
return;
} catch(Exception
e){
return;
} finally
{
ServerDevice.ta.appendText(this.toString()
+ " --> chiusa " + '');
try
{
if
(isOpenDevice) controllableDevice.close();
is.close();
os.close();
clientSocket.close();
this.stop();
} catch
(IOException ioe){
} catch
(Exception e) {}
} //end
finally
} //end
run()
/**
* Metodo
che restituisce una stringa che rappresenta la connesione.
* La stringa
apparira' nella lista.
* @return
Stringa che rappresenta la connesione.
*/
public
String toString() {
return
this.getName() + " connessione
da: "
+ clientSocket.getInetAddress().getHostName()
+ " :
" + clientSocket.getPort();
} //toString()
} //end
class ConnectionDevice.
L’interfaccia ID_Message
/*
* @(#)
ID_Message.java 0.9beta Gennaio 1997 - by Donato Cappetta
*/
package
device.server;
/**
* Interfacce
che definisce delle costanti per un protocollo
* (di
alto livello) di comunicazione client-server.
* @see
java.lang.Object
* @version
0.9beta Gennaio 1997
* @author
Donato Cappetta <cappetta@diiie.unisa.it>
*/
public
interface ID_Message {
public
static final
byte ID_ERROR = -2;
public
static final
byte ID_EXCEPTION = -1;
public
static final
byte ID_NULL = 0;
public
static final
byte ID_TEST = 1;
public
static final
byte ID_COMMAND = 2;
public
static final
byte ID_OKDEVICE = 3;
public
static final
byte ID_MSG = 4;
public
static final
byte ID_CLASS = 5;
public
static final
byte ID_WAIT = 6;
public
static final
byte ID_ACK = 7;
public
static final
byte ID_STOP = 8;
public
static final
byte ID_OPEN = 9;
public
static final
byte ID_CLOSE = 10;
public
static final
byte ID_RESULT = 11;
} //end
interface ID_Message
La classe IllegalSubclassException
/*
* @(#)
IllegalSubclassException.java 0.9beta Gennaio 1997 - by Donato Cappetta
*/
package
device.server;
/**
* Eccezione
che viene lanciata se la classe da caricare dinamicamente
* non
e sottoclasse di una specificata superclasse.
* @see
java.lang.Object
* @version
0.9beta Gennaio 1997
* @author
Donato Cappetta <cappetta@diiie.unisa.it>
*/
public
class IllegalSubclassException extends
Exception {
private
String stringSubclass;
public
IllegalSubclassException() {
this.stringSubclass
= "";
}
public
IllegalSubclassException(String stringSubclass) {
this.stringSubclass
= stringSubclass;
}
public
String toString() {
return
"IllegalSubclassException: " + stringSubclass;
}
} //end
class IllegalSubclassExcpetion.
B.3 Il package device.client
Questo package contiene: la classe DeviceGUI
che rappresenta l’interfaccia utente per il controllo del dispositivo e
la classe AppletGUI che consente di caricare
come applet la classe DeviceGUI o una sua
sottoclasse.
La classe AppletGUI
/*
* @(#)
AppletGUI.java 0.9beta Gennaio 1997 - by Donato Cappetta
*/
package
device.client;
import
device.client.DeviceGUI;
import
device.server.IllegalSubclassException;
import
java.awt.*;
import
java.net.URL;
/**
* Applet
che riceve come parametro il nome di una classe sottoclasse
* di DeviceGUI
e crea un'istanza di questa classe.
*
* @see
java.lang.Object
* @see
java.applet.Applet
* @version
0.9beta Gennaio 1997
* @author
Donato Cappetta <cappetta@diiie.unisa.it>
*/
public
class AppletGUI extends
java.applet.Applet {
private
URL urlBase = null;
private
String classGUI;
private
String buttonText;
private
String titleGUI;
private
String portId;
private
Button button;
private
Label label;
private
int port;
public
void init() {
setBackground(Color.white);
classGUI = getParameter("classGUI");
if
(classGUI == null) {
classGUI = "DeviceGUI";
}
buttonText = getParameter("buttonText");
if
(buttonText == null) {
buttonText = "Apri
pannello " + classGUI;
}
titleGUI = getParameter("titleGUI");
if
(titleGUI == null) {
titleGUI = "Interfaccia
GUI";
}
portId = getParameter("portId");
if
(portId != null) {
try
{
port = Integer.parseInt(portId);
} catch(NumberFormatException
nfe){
port = 4444;
} //end
try-catch()
} else
{
port = 4444;
} //end
if-else
setLayout(new
GridLayout(2,0));
add(button = new
Button(buttonText));
button.setFont(new
Font("Helvetica", Font.PLAIN, 12));
add(label = new
Label("", Label.CENTER));
urlBase = getCodeBase();
label.setText("connect
to: " + urlBase.getHost() + ": " +
port);
} //end
init()
public
boolean action(Event event, Object obj) {
if
(event.target instanceof Button) {
button.disable();
label.setText("Caricamento
della classe in corso...");
try
{
DeviceGUI frameDevice = (DeviceGUI)loadSubclassforName(classGUI,
"device.client.DeviceGUI");
if
(frameDevice != null) {
label.setText("Caricamento
Ok!");
frameDevice.setTitle(titleGUI);
frameDevice.init(urlBase.getHost(),
port);
frameDevice.resize(500,
300);
frameDevice.show();
label.setText("");
} else
{
label.setText("Valore
non valido " + classGUI + " -> null");
}
}catch
(IllegalSubclassException isce) {
label.setText("Eccezione:
" + isce.getMessage());
}catch(ClassNotFoundException
cnfe){
label.setText("Eccezione:
" + cnfe.getMessage());
} catch
(InstantiationException ie) {
label.setText("Eccezione:
"+ ie.getMessage());
} catch
( IllegalAccessException iae) {
label.setText("Eccezione:
"+ iae.getMessage());
} // try-catch()
}
return
true;
} //end
action()
/**
* Metodo
che restituisce un'instanza di una classe, a partire
* da una
stringa che rappresenta il nome della classe.
* @param
classString Stringa che rappresenta il nome della classe
* @param
superClassstring Stringa che rappresenta il nome della superclasse
* @return
Object Istanza della classe rappresentata da classString
* @exception
IllegalSubclassException La classe rappresentata da classString
* non
ha come superclasse superClassString.
* @exception
*/
private
Object loadSubclassforName(String classString, String superclassString)
throws IllegalSubclassException,
ClassNotFoundException,
InstantiationException, IllegalAccessException
{
Class classObject = null;
Class classTemp = null;
String className = null;
try
{
classObject = Class.forName(classString);
} catch
(ClassNotFoundException cnfe) {
throw
cnfe;
} //end
try-catch
for
(classTemp = classObject, className = classTemp.getName();
!(className.equals("java.lang.Object")
||
className.equals(superclassString));
) {
classTemp = classTemp.getSuperclass();
className = classTemp.getName();
} //end
for
if
((className == null) || className.equals("java.lang.Object"))
{
throw
new IllegalSubclassException(classString);
} else
if(className.equals(superclassString)) {
try
{
return
classObject.newInstance();
} catch
(InstantiationException ie) {
throw
ie;
} catch
(IllegalAccessException iae) {
throw
iae;
} //end
try-catch
} else
{
//throw
new Exception();
return
null;
} //end
if - else
} //end
loadSubclassforName()
public
String getAppletInfo(){
return
"AppletGUI v.0.9 - Gennaio 1997 <cappetta@diiie.unisa.it>";
}
} //end
class AppletGUI.
La classe DeviceGUI
/*
* @(#)
DeviceGUI.java 0.9beta Gennaio 1997 - by Donato Cappetta
*/
package
device.client;
import
java.net.*;
import
java.io.*;
import
java.awt.*;
/**
* Superclasse
interfaccia grafica utente per il controllo di
* un dispositivo
elettronico.<br>
* La classe
implementa i metodi necessari per una
* connessione
client-server.
* @see
java.lang.Object
* @version
0.9beta Gennaio 1997
* @author
Donato Cappetta <cappetta@diiie.unisa.it>
*/
public
class DeviceGUI extends
Frame implements device.server.ID_Message
{
/**
* La classe
puo essere caricata da un applet o dalla
* riga
di comando.
*/
private
boolean inAnApplet = true;
/**
* Se la
connesione va a buon fine viene settata connectOk.
*/
private
boolean isConnect = false;
/**
* Socket
per I/O di rete.
*/
private
Socket socket = null;
/**
* Indirizzo
url della risorsa ControllableDevice da gestire.
*/
private
String urlString = null;
/**
* Porta
riservata alla risorsa ControllableDevice;
*/
private
int port = 4444;
/**
* Stream
per i dati di input.
*/
protected
ObjectInputStream is = null;
/**
* Stream
per i dati di output.
*/
protected
ObjectOutputStream os = null;
/**
* Area
di testo per eventuali messaggi.
*/
protected
TextArea ta = null;
/**
* Barra
del menu per eventuali menu.
*/
protected
MenuBar mb = null;
/**
* Oggetto
per i dati in input.
*/
protected
Object objInput = null;
/**
* Oggetto
per i dati di output.
*/
protected
Object objOutput = null;
/**
* Il costruttore
crea un layout a bordi con un'area di testo
* a 'sud'
*/
public
DeviceGUI() {
this.setLayout(new
BorderLayout());
mb = new
MenuBar();
ta = new
TextArea(2,20);
ta.setEditable(false);
this.add("South",
ta);
ta.setText("DeviceGUI
v.0.9 - Gennaio 1997 by Donato Cappetta ");
} //end
costruttore DeviceGUI()
/**
* Metodo
che inizializza l'url e la porta con cui stabilire la connesione.
* @param
urlString Stringa URL del dispositivo elettronico da controllare.
* @param
port Porta a cui il client si deve connettere per ottenere il servizio.
*/
public
void init(String urlString, int
port) {
this.urlString
= urlString;
this.port
= port;
}
/**
* Metodo
che si occupa della connesione con il server.
* Crea
un nouvo socket con i paramenti url, port e associa
* gli
stream di I/O del socket a is e os.
*
* @Exception
UnknownHostException se l'Host e sconosciuto.
* @Exception
IOException errore nella creazione degli stream di I/O.
*/
private
void connect() throws UnknownHostException,
IOException {
try
{
ta.setText("Connect
to: " + urlString + ":" + port);
ta.appendText('' + "Attendere
...");
socket = new
Socket(urlString, port);
isConnect = true;
os = new
ObjectOutputStream(socket.getOutputStream());
try
{
is = new
ObjectInputStream(socket.getInputStream());
} catch(StreamCorruptedException
sce) {
throw
sce;
} catch
(IOException ioe) {
throw
ioe;
}
} catch(UnknownHostException
uhe) {
throw
uhe;
} catch(IOException
ioe) {
throw
ioe;
}
} //end
connect()
/**
* Metodo
che si occupa di disconnettere.
* Chiude
gli stream di I/O e il socket.
* @Exception
IOException eccezione durante la disconnesione.
*/
private
void disconnect() throws IOException {
try
{
ta.appendText(''+ "Disconnect
!!");
is.close();
os.close();
socket.close();
isConnect = false;
} catch(IOException
ioe) {
throw
ioe;
}
} //end
disconnect
/**
* Metodo
che tenta la connesione con il server.
* Se la
connesione va a buon fine e il dispostivo e
* disponibile
per il controllo ritorna 'true'.
* @param
stringDevice Nome del dispostivo da controllare.
* @return
'true' o 'false' se il disposito e disponibile o meno per
* il controllo.
*/
public
boolean startDevice(String stringDevice) {
String stringIn = null;
byte
ID_Input;
try
{
this.connect();
} catch(UnknownHostException
uhe) {
ta.appendText(''+ "Host
sconosciuto: " + uhe.getMessage());
return
false;
} catch
(IOException ioe) {
ta.appendText(''+ "Eccezione
di I/O con il server: " + ioe.getMessage());
return
false;
} catch
(Exception e) {
ta.appendText(''+ "Eccezione
con il server: " + e.getMessage());
return
false;
}
//se la
connesione va a buon fine
//attende
ib byte di acknowledgment
try
{
ID_Input = is.readByte();
if
(ID_Input == ID_ACK) {
ta.appendText(''+ "Acknowledgment
ok ! ");
} else
{
//ritorna
ta.appendText(''+ "Errore
di Acknowledgment--> " + ID_Input);
return
false;
}
//invia
stringa che rappresenta il dispositivo da controllare
ta.appendText(''+ "Dispositivo
da controllare -->" + stringDevice);
os.writeUTF(stringDevice);
os.flush();
} catch(IOException
e){
ta.appendText(''+ "Problemi
di connessione ...");
return
false;
}
//attende
una risposta di ok o stop dal server.
try
{
ID_Input = is.readByte();
stringIn = is.readUTF();
} catch(IOException
ioe){
ta.appendText(''+ "Problemi
di connessione ...");
return
false;
}
//analizza
la risposta
switch(ID_Input)
{
case(ID_OKDEVICE):
ta.appendText(''+ "Dispositivo
Ok --> " + stringIn);
return
true;
case(ID_EXCEPTION):
ta.appendText(''+ "Eccezione
dal dispositivo --> " + stringIn);
return
false;
case(ID_STOP):
ta.appendText(''+ "Stop
--> " + stringIn);
return
false;
default:
ta.appendText(''+ "Comando
sconosciuto -->" + stringIn);
return
false;
} //end
switch()
} //end
startDevice()
/**
* Metodo
che chiude la connessione con il server e rilascia il
* dispositivo
*/
public
void stopDevice() {
try
{
this.disconnect();
} catch
(IOException ioe) {
// ta.appendText('\n'+
"Eccezione di I/O durante la disconnesione: " + ioe.getMessage());
} catch
(Exception e) {
// ta.appendText('\n'+
"Eccezione durante la disconnessione: " + e.getMessage());
}
} //end
stopDevice()
/**
* La classe
DeviceGUI puo' essere caricata da un applet
* o dalla
linea di comando.
* @param
bool Valore 'true' o 'false'.
*/
public
void inAnApplet(boolean
bool) {
inAnApplet = bool;
}
/**
* @return
inAnApplet.
*/
public
boolean inAnApplet() {
return
inAnApplet;
}
public
boolean handleEvent (Event event) {
if
(event.id == Event.WINDOW_DESTROY) {
if
(isConnect) {
try
{
this.disconnect();
} catch(IOException
ioe) {}
}
if
(inAnApplet) {
dispose();
} else
{
System.exit(0);
}
}
return
super.handleEvent(event);
} //end
handleEvent()
} //end
class DeviceGUI.
B.3 Il package "corrente"
L’implementazione delle classi per il controllo di strumenti che si
interfacciano con bus VXI e IEEE 488 non è stata inserita in un
package e per default esse fanno parte del package che è la directory
corrente in cui sono poste. Fanno parte della stessa directory le librerie
dinamiche (DLL) implementate in linguaggio C.
In questo package "corrente" si trovano: la classe IeeeVxi
(sottoclasse di ControllableDevice) che
viene caricata dinamicamente dal Server insieme alla libreria implementata
in linguaggio C di cui ne vengono riportati i sorgenti, le classi IeeeVxiGUI
(sottoclasse di DeviceGUI) e IeeeVxiPanel
che rappresentano rispettivamente il client e l’interfaccia utente del
client, le classi DeviceDataInput e DeviceDataOutput
per i dati in input e output dagli strumenti ed infine il file HTML che
carica la classe AppletGUI la quale consente
di eseguire IeeeVxiGUI come applet.
La classe IeeeVxi
/*
* @(#)
IeeeVxi.java 0.9beta Gennaio 1997 - by Donato Cappetta
*/
import
device.server.ServerDevice;
/**
* Classe
concreta di ControllableDevice.
*
* @see
java.lang.Object
* @version
0.9beta Gennaio 1997
* @author
Donato Cappetta <cappetta@diiie.unisa.it>
*/
public
class IeeeVxi extends
device.ControllableDevice {
static
final String stringDLL = "IeeeVxi";
private
String stringPath = "/public";
/**
* Il dispositivo
inizialmente non e in uso.
*/
private
boolean inUse;
/**
* Il dispositivo
in genere non e condivisibile.
*/
private
boolean isShareble;
/**
* Costruttore
*/
public
IeeeVxi () {
inUse = false;
isShareble = false;
}
/**
* Metodo
che informa se il dispositivo e gia'in uso.
* @return
boolean Dispositivo in uso o meno.
*/
public
boolean inUse(){
return
inUse;
}
/**
* Metodo
che informa se il dispositivo puo' essere condiviso
* fra
piu utenti.
* @return
isShareble.
*/
public
boolean isShareble() {
return
isShareble;
}
/**
* Metodo
che inizializza e istanzia le risorse per
* un nuovo
utente.
*/
public
synchronized void
open() {
if
(!inUse) {
inUse = true;
}
} //end
open()
/**
* Metodo
che chiude e rilascia le risorse.
*/
public
void close() {
if
(!isShareble) {
inUse = false;
}
} //end
close()
/**
* Metodi
nativi implementati in linguaggio C
*/
public
native void leggiInput(String
bus, String strumento, String comando,
String query, String nomeFile,
String salvaInFile);
public
native String leggiStatus();
public
native String leggiVxiStatus();
public
native String leggiRisposta();
public
native void inviaAlloStrumento();
public
native void initVXILibrary();
public
native void closeVXILibrary();
/**
* Metodo
che rappresenta i comandi che possono essere
* impartiti
al dispositivo.
*
* @param
obj Oggetto che informa il dispositivo le operazioni da compiere.
* @return
Risultato dell'operazione.
*/
public
synchronized Object execute(Object obj) {
int
size = 0;
String queryRisposta = "s";
String queryFile = "s";
DeviceDataInput ddi = (DeviceDataInput)obj;
if
(!ddi.checkRisposta) {
queryRisposta = "n";
}
if
(ddi.nomeFile.equals("NULL")) {
queryFile = "n";
}
//chiamate
ai metodi nativi
leggiInput(ddi.bus,ddi.strumento,ddi.comando,
queryRisposta, ddi.nomeFile,queryFile);
initVXILibrary();
inviaAlloStrumento();
DeviceDataOutput ddo = new
DeviceDataOutput();
if
(ddi.bus.equals("IEEE")) {
ddo.statusByteIn = leggiStatus();
} else
{
ddo.statusByteIn = leggiVxiStatus();
}
//se si
attende risposta
if
(ddi.checkRisposta) {
ddo.risposta = leggiRisposta();
if
(ddi.bus.equals("IEEE")) {
ddo.statusByteOut = leggiStatus();
} else
{
ddo.statusByteOut = leggiVxiStatus();
} //end
if-else
//se il
risultato è stato salvato in file ...
if
(!ddi.nomeFile.equals("NULL")) {
ServerDevice.ta.appendText("Lettura
del file .. " + '\n');
java.io.File f = null;
java.io.FileInputStream fis
= null;
try
{
f = new
java.io.File(stringPath, ddi.nomeFile);
fis = new
java.io.FileInputStream(f);
size = fis.available();
ddo.b = new
byte[size];
fis.read(ddo.b);
fis.close();
} catch
(java.io.FileNotFoundException fnfe) {
//ServerDevice.ta.appendText("File
non trovato: " + fnfe.getMessage() + '\n');
} catch
(java.io.IOException ioe) {
//ServerDevice.ta.appendText("Impossibile
leggere dal file: " + ioe.getMessage() + '\n');
} catch
(Exception e) {
//ServerDevice.ta.appendText("Eccezione
nell'accesso al file: " + e.getMessage() + '\n');
} //end
try-catch()
} //end
if.
} else
{
ddo.risposta = "";
ddo.statusByteOut = "";
}
closeVXILibrary();
return
ddo;
}
/**
* Carica
la libreria dinamica all'avvio.
*/
static
{
try
{
System.loadLibrary(stringDLL);
} catch(java.lang.UnsatisfiedLinkError
ule) {
throw
ule;
}
}
} //end
class IeeeVxi.
La classe IeeeVxiGUI
/*
* @(#)
IeeeVxiGUI.java 0.9beta Gennaio 1997 - by Donato Cappetta
*/
import
java.awt.*;
import
java.io.*;
/**
* Classe
per il controllo di dispositivi elettronici
* basati
su bus VXI e IEEE.
* @see
java.lang.Object
* @version
0.9beta Gennaio 1997
* @author
Donato Cappetta <cappetta@diiie.unisa.it>
*/
public
class IeeeVxiGUI extends
device.client.DeviceGUI {
private
String stringDevice = "IeeeVxi";
private
String stringPath = "./file";
private
MenuItem connectMenu, disconnectMenu, infoMenu;
private
IeeeVxiPanel panel = new IeeeVxiPanel();
public
IeeeVxiGUI() {
super();
Menu m1 = new
Menu ("Device");
connectMenu = new
MenuItem ("Apri sessione");
disconnectMenu = new
MenuItem ("Chiudi sessione");
MenuItem lineMenu = new
MenuItem("-");
infoMenu = new
MenuItem("Info...");
disconnectMenu.disable();
m1.add(connectMenu);
m1.add(disconnectMenu);
m1.add(lineMenu);
m1.add(infoMenu);
mb.add(m1);
setMenuBar(mb);
panel.disable();
super.add("Center",
panel);
ta.appendText('' + "Per
connettersi: Device>Apri sessione.");
this.makeDir(stringPath);
} //end
construttore IeeeVxiGUI()
/**
* Metodo
che crea una directory (se non esiste)
* in cui
verranno salvati eventuali file.
*/
private
void makeDir(String s) {
try
{
File f = new
File(s);
boolean
b = f.mkdir();
} catch
(Exception e) {
ta.appendText('' + "Impossibile
creare la directory " + s + ", "+ e.getMessage());
}
} //end
makeDir()
/**
* Metodo
che incapsula i dati contenuti nei campi del pannello in
* un oggetto
e lo spedisce al server.
*/
private
void sendAction (DeviceDataInput ddi) throws
IOException {
panel.textFieldStatusByte.setText("");
panel.textFieldRisposta.setText("Attendere
...");
ddi.bus = panel.choiceBus.getSelectedItem();
if
(ddi.bus == "VXI"){
ddi.strumento = panel.textFieldStrumentoVXI.getText();
} else
{
ddi.strumento = panel.listSceltaStrumentoIEEE.getSelectedItem();
}
if
(panel.checkboxFile.getState()) {
ddi.nomeFile = panel.textFieldNomeFile.getText();
} else
{
ddi.nomeFile = "NULL";
}
ddi.comando = panel.textFieldComando.getText();
ddi.letturaByte = panel.textFieldLetturaByte.getText();
ddi.checkRisposta = panel.checkboxRisposta.getState();
try
{
os.writeObject(ddi);
os.flush();
} catch(IOException
ioe) {
throw
ioe;
}
} //end
sendAction()
/**
* Metodo
che 'azzera' tutti i campi del pannello.
*/
private
void cancelAction() {
panel.textFieldComando.setText("
");
panel.textFieldLetturaByte.setText("
");
panel.textFieldNomeFile.setText("
");
panel.textFieldStatusByte.setText("
");
panel.textFieldRisposta.setText("
");
panel.textFieldStrumentoVXI.setText("
");
} //end
cancelAction()
/**
* Metodo
che visualizza i dati provenienti dal server sul pannello
* o li
salva in un file.
*/
private
void readResult(DeviceDataOutput ddo) {
panel.textFieldStatusByte.setText("
" + ddo.statusByteIn + "; "+ ddo.statusByteOut);
panel.textFieldRisposta.setText(ddo.risposta);
if
(panel.checkboxFile.getState()) {
ta.setText("Scrittura
dei dati nel file. Attendere ... ");
File f = null;
FileOutputStream fos = null;
try
{
f = new
File(stringPath, panel.textFieldNomeFile.getText());
fos = new
FileOutputStream(f);
fos.write(ddo.b);
fos.close();
ta.appendText("Fatto.
");
ta.appendText ('' + "Dati
salvati in: " + f.getPath());
} catch(IOException
ioe) {
ta.appendText ('' + "Eccezione
di I/O nel file: " + ioe.getMessage());
} catch
(Exception e) {
ta.appendText ('' + "Impossibile
salvare nel file. " + e.getMessage());
}
} //end
if
} //end
readResul()
/**
* Azioni
dell'utente.
*/
public
boolean action (Event event, Object arg) {
if
(event.target instanceof Button) {
ta.setText("");
String label = (String)arg;
if
(label.equals("Send")) {
try
{
DeviceDataInput ddi = new
DeviceDataInput();
sendAction(ddi);
DeviceDataOutput ddo = (DeviceDataOutput)is.readObject();
readResult(ddo);
} catch
(ClassNotFoundException cnfe) {
} catch
(IOException ioe) {
ta.appendText('' + "Eccezione:
" + ioe.getMessage());
super.stopDevice();
panel.disable();
connectMenu.enable();
disconnectMenu.disable();
}
} else
if (label.equals("Cancel"))
{
cancelAction();
}
return
true;
}
if
(event.target instanceof MenuItem) {
if
(event.target == connectMenu) {
boolean
startBoolean = super.startDevice(stringDevice);
if
(startBoolean) {
connectMenu.disable();
disconnectMenu.enable();
panel.enable();
} else
{
super.stopDevice();
}
} else
if(event.target == disconnectMenu) {
disconnectMenu.disable();
connectMenu.enable();
panel.disable();
super.stopDevice();
} else
if (event.target == infoMenu) {
ta.appendText(''+ "IeeeVxi
v.0.9 - Gennaio 1997 - . Per informazioni contattare: " + ''
+ "<cappetta@diiie.unisa.it>
oppure <piegari@diiie.unisa.it>. ");
}
return
true;
}
return
false;
} //end
action()
} //end
class IeeeVxiGUI.
La classe IeeeVxiPanel
/*
* @(#)
IeeeVxiPanel.java v.0.9beta Gennaio 1997 - Donato Cappetta
*/
//package
import
java.awt.*;
/**
* Classe
che visualizza un panello per il controllo di
* dispositivi
che si basano su bus VXI e IEEE.
*
* @see
java.lang.Object
* @version
0.9beta Gennaio 1997
* @author
Donato Cappetta <cappetta@diiie.unisa.it>
*/
public
class IeeeVxiPanel extends
Panel {
java.awt.Choice choiceBus;
java.awt.List listSceltaStrumentoIEEE;
java.awt.TextField textFieldComando;
java.awt.TextField textFieldLetturaByte;
java.awt.TextField textFieldNomeFile;
java.awt.TextField textFieldStatusByte;
java.awt.TextField textFieldRisposta;
java.awt.TextField textFieldStrumentoVXI;
java.awt.Label labelSceltaBus;
java.awt.Label labelStrumentoIEEE;
java.awt.Label labelComando;
java.awt.Label labelLetturaByte;
java.awt.Label labelNomeFile;
java.awt.Label labelStatusByte;
java.awt.Label labelRisposta;
java.awt.Label labelStrumentoVXI;
java.awt.Button send;
java.awt.Button cancel;
java.awt.Checkbox checkboxRisposta;
java.awt.Checkbox checkboxFile;
public
IeeeVxiPanel() {
setLayout(null);
setBackground(Color.lightGray);
resize(insets().left + insets().right
+ 431,insets().top + insets().bottom + 267);
choiceBus = new
java.awt.Choice();
choiceBus.addItem("VXI");
choiceBus.addItem("IEEE");
choiceBus.reshape(insets().left
+ 39,insets().top + 36,95,75);
add(choiceBus);
listSceltaStrumentoIEEE = new
java.awt.List(0,false);
listSceltaStrumentoIEEE.addItem("GPIB0");
listSceltaStrumentoIEEE.addItem("FLUKE45");
listSceltaStrumentoIEEE.addItem("PM5193");
listSceltaStrumentoIEEE.addItem("AWG2020");
listSceltaStrumentoIEEE.addItem("TDS520");
listSceltaStrumentoIEEE.reshape(insets().left
+ 178,insets().top + 36,95,107);
listSceltaStrumentoIEEE.disable();
add(listSceltaStrumentoIEEE);
textFieldComando = new
java.awt.TextField();
textFieldComando.setText("Comando");
textFieldComando.reshape(insets().left
+ 322,insets().top + 39,153,23);
add(textFieldComando);
textFieldLetturaByte = new
java.awt.TextField();
textFieldLetturaByte.setText("byte");
textFieldLetturaByte.reshape(insets().left
+ 322,insets().top + 99,153,23);
add(textFieldLetturaByte);
textFieldNomeFile = new
java.awt.TextField();
textFieldNomeFile.setText("NomeFile");
textFieldNomeFile.disable();
textFieldNomeFile.reshape(insets().left
+ 39,insets().top + 173,95,24);
add(textFieldNomeFile);
textFieldStatusByte = new
java.awt.TextField();
textFieldStatusByte.setEditable(false);
textFieldStatusByte.setText("StatusByte");
textFieldStatusByte.reshape(insets().left
+ 39,insets().top + 230,300,24);
add(textFieldStatusByte);
textFieldStrumentoVXI = new
java.awt.TextField();
textFieldStrumentoVXI.setText("StrumentoVXI");
textFieldStrumentoVXI.reshape(insets().left
+ 178,insets().top + 173,95,24);
add(textFieldStrumentoVXI);
textFieldRisposta = new
java.awt.TextField();
textFieldRisposta.setEditable(false);
textFieldRisposta.setText("Risposta");
textFieldRisposta.reshape(insets().left
+ 39,insets().top + 281,300,24);
add(textFieldRisposta);
labelSceltaBus = new
java.awt.Label("Scelta Bus");
labelSceltaBus.reshape(insets().left
+ 39,insets().top + 18,80,15);
add(labelSceltaBus);
labelStrumentoIEEE = new
java.awt.Label("Strumento IEEE");
labelStrumentoIEEE.reshape(insets().left
+ 178,insets().top + 18,95,15);
add(labelStrumentoIEEE);
labelComando = new
java.awt.Label("Comando");
labelComando.reshape(insets().left
+ 322,insets().top + 18,84,15);
add(labelComando);
labelLetturaByte = new
java.awt.Label("Lettura Byte");
labelLetturaByte.reshape(insets().left
+ 322,insets().top + 78,84,15);
add(labelLetturaByte);
labelStrumentoVXI = new
java.awt.Label("Strumento VXI");
labelStrumentoVXI.reshape(insets().left
+ 178,insets().top + 154,84,15);
add(labelStrumentoVXI);
labelNomeFile = new
java.awt.Label("Nome File");
labelNomeFile.reshape(insets().left
+ 39,insets().top + 154,84,15);
add(labelNomeFile);
labelStatusByte = new
java.awt.Label("Status Byte");
labelStatusByte.reshape(insets().left
+ 39,insets().top + 210,80,15);
add(labelStatusByte);
labelRisposta = new
java.awt.Label("Risposta");
labelRisposta.reshape(insets().left
+ 39,insets().top + 261,70,15);
add(labelRisposta);
send = new
java.awt.Button("Send");
send.reshape(insets().left +
391,insets().top + 230,84,26);
add(send);
cancel = new
java.awt.Button("Cancel");
cancel.reshape(insets().left
+ 391,insets().top + 281,84,26);
add(cancel);
checkboxRisposta = new
java.awt.Checkbox("Attendi Risposta");
checkboxRisposta.reshape(insets().left
+ 39,insets().top + 80,112,19);
add(checkboxRisposta);
checkboxFile = new
java.awt.Checkbox("Salva in File");
checkboxFile.reshape(insets().left
+ 39,insets().top + 110,112,18);
add(checkboxFile);
} //end
costruttore IeeeVxiPanel()
public
boolean action(Event event, Object arg) {
if
(event.target instanceof java.awt.Choice)
{
String label = (String)arg;
if
(label.equals("VXI")) {
listSceltaStrumentoIEEE.disable();
textFieldStrumentoVXI.enable();
} else
if (label.equals("IEEE"))
{
listSceltaStrumentoIEEE.enable();
textFieldStrumentoVXI.disable();
}
return
true;
}
if
(event.target instanceof java.awt.Checkbox)
{
if
(event.target == checkboxFile){
if
(checkboxFile.getState()) {
textFieldNomeFile.enable();
//checkboxRisposta.setState(true);
} else
{
textFieldNomeFile.disable();
}
} else
if(event.target == checkboxRisposta) {
}
return
true;
}
return
false;
} //end
action()
} //end
class IeeeVxiPanel.
La classe DeviceDataInput
/*
* @(#)
DeviceDataInput.java 0.9beta - by Donato Cappetta
*
*/
//package
//import
/**
* Classe
che incapsula i dati in input al dispositivo.
*
* @see
java.lang.Object
* @see
classiCorrelate
* @version
0.9beta Gennaio 1997
* @author
Donato Cappetta <cappetta@diiie.unisa.it>
*/
public
class DeviceDataInput implements
java.io.Serializable {
String bus = "";
String strumento = "";
String comando = "";
String letturaByte = "";
String nomeFile = "";
boolean
checkRisposta = false;
}
La classe DeviceDataOutput
/*
* @(#)
DeviceDataOutput.java 0.9beta - by Donato Cappetta
*/
//package
//import
/**
* Classe
che incapsula i dati in output al dispositivo.
*
* @see
java.lang.Object
* @version
0.9beta Gennaio 1997
* @author
Donato Cappetta <cappetta@diiie.unisa.it>
*/
public
class DeviceDataOutput implements
java.io.Serializable {
String statusByteIn = "";
String statusByteOut = "";
String risposta = "";
byte[]
b = null;
}
Il file IeeeVxiNative.c
/*
* IeeeVxiNative.c
Gennaio 1997 - by Piergiuseppe Piegari, Donato Cappetta.
*/
#define
VXINT
#define
_PROTOTYPES_
#define
BINARY_COMPATIBLE
#define
_I386_
#include
<nivxi.h>
#include
<windows.h>
#include
<stdio.h>
#include
<stdlib.h>
#include
<conio.h>
#include
<string.h>
#include
<decl-32.h>
#include
"IeeeVxi.h"
typedef
struct {
char
bus[4]; /* Tipo di bus
*/
char
instrum[10]; /* Strumento
*/
char
com[255]; /* Comando
da inviare */
int
status; /* status byte */
char
query[2]; /* Attesa
risposta */
char
nomfile[12]; /* Nome
file */
char
risposta[255]; /* Risposta
strum */
char
salvainfile[2]; /* Attesa
risposta */
} comando;
comando order;
int
length,query;
int
ret,retcount;
char
buf[100];
char
*com;
char
k;
char
riga[255],stab[17];
int
brd;
void
IeeeVxi_leggiInput(struct HIeeeVxi *this,struct
Hjava_lang_String *bus,
struct
Hjava_lang_String *strumento,struct Hjava_lang_String
*comando,
struct
Hjava_lang_String *query,struct Hjava_lang_String
*nomeFile,
struct
Hjava_lang_String *salvaInFile){
unsigned
int i,kk,j;
int
intero;
char
stringa[15],stringa1[15];
sprintf(order.bus,"");
sprintf(order.instrum,"");
sprintf(order.com,"");
sprintf(order.query,"");
sprintf(order.nomfile,"");
sprintf(order.risposta,"");
sprintf(order.salvainfile,"");
com = allocCString(comando);
sprintf(order.bus,makeCString(bus));
strcpy(order.instrum,makeCString(strumento));
sprintf(order.query,makeCString(query));
sprintf(order.nomfile,makeCString(nomeFile));
sprintf(order.salvainfile,makeCString(salvaInFile));
i=0;
j=0;
while
(i < strlen(com)){
if
(com[i]=='\')
{
if
(com[i+1]=='x')
{
for
(kk=0;kk<strlen(com)-i;kk++)
stringa[kk]=com[i+kk+2];
sscanf(stringa,"%x",&intero);
itoa(intero,stringa1,16);
i+=strlen(stringa1)+1;
j+=strlen(stringa1)+1;
sprintf(stringa1,"%d",intero);
com[i]=(char)
intero;
} else
if (com[i+1]=='o')
{
for
(kk=0;kk<strlen(com)-i;kk++)
stringa[kk]=com[i+kk+2];
sscanf(stringa,"%o",&intero);
itoa(intero,stringa1,8);
i+=strlen(stringa1)+1;
j+=strlen(stringa1)+1;
sprintf(stringa1,"%d",intero);
com[i]=(char)
intero;
} else
if (com[i+1]<='9'
&& com[i+1]>='0')
{
for
(kk=0;kk<strlen(com)-i;kk++)
stringa[kk]=com[i+kk+1];
sscanf(stringa,"%d",&intero);
itoa(intero,stringa1,10);
i+=strlen(stringa1);
j+=strlen(stringa1);
com[i]=(char)
intero;
}
order.com[i-j]=com[i];
i++;
} else
{
order.com[i-j]=com[i];
i++;
}
}
order.com[i] = '';
free(com);
} /*end
leggiinput()*/
void
IeeeVxi_inviaAlloStrumento(struct HIeeeVxi
*this){
if
(order.bus[0] == 'I')
{
ibclr(32000);
brd=ibfind(order.instrum);
ibonl(brd,0);
ibonl(brd,1);
if
(brd == 32000)
{
ibsic(brd);
ibsre(brd,1);
ibcmd(brd,order.com,strlen(order.com));
}
else
{
ibwrt(brd,order.com,strlen(order.com));
}
}
else
if
(order.bus[0] == 'V')
{
k=atoi(order.instrum);
strcat(order.com,"\n");
ret = WSwrt(k,order.com,strlen(order.com),0,&retcount);
}
if
(order.query[0] == 's')
{
query = 1;
}
}
struct
Hjava_lang_String *IeeeVxi_leggiStatus(struct
HIeeeVxi *this){
char
app[50];
strcpy(app,"
<");
if
(ibsta & ERR ) strcat(app," ERR");
if
(ibsta & TIMO) strcat(app," TIMO");
if
(ibsta & END ) strcat(app," END");
if
(ibsta & SRQI) strcat(app," SRQI");
if
(ibsta & RQS ) strcat(app," RQS");
if
(ibsta & CMPL) strcat(app," CMPL");
if
(ibsta & LOK ) strcat(app," LOK");
if
(ibsta & REM ) strcat(app," REM");
if
(ibsta & CIC ) strcat(app," CIC");
if
(ibsta & ATN ) strcat(app," ATN");
if
(ibsta & TACS) strcat(app," TACS");
if
(ibsta & LACS) strcat(app," LACS");
if
(ibsta & DTAS) strcat(app," DTAS");
if
(ibsta & DCAS) strcat(app," DCAS");
strcat(app,"
>");
if
(ibsta & ERR ) {
strcat(app,"
");
if
(iberr == EDVR) strcat(app," EDVR <DOS Error>\n");
if
(iberr == ECIC) strcat(app," ECIC <No CIC>\n");
if
(iberr == ENOL) strcat(app," ENOL <No Listener>\n");
if
(iberr == EADR) strcat(app," EADR <Address error>\n");
if
(iberr == EARG) strcat(app," EARG <Invalid argument>\n");
if
(iberr == ESAC) strcat(app," ESAC <Not Sys Ctrlr>\n");
if
(iberr == EABO) strcat(app," EABO <Op. aborted>\n");
if
(iberr == ENEB) strcat(app," ENEB <No GPIB board>\n");
if
(iberr == EOIP) strcat(app," EOIP <Async I/O in
prg>");
if
(iberr == ECAP) strcat(app," ECAP <No capability>\n");
if
(iberr == EFSO) strcat(app," EFSO <File sys. error>\n");
if
(iberr == EBUS) strcat(app," EBUS <Command error>\n");
if
(iberr == ESTB) strcat(app," ESTB <Status byte
lost>");
if
(iberr == ESRQ) strcat(app," ESRQ <SRQ stuck on>\n");
if
(iberr == ETAB) strcat(app," ETAB <Table Overflow>\n");
}
return
makeJavaString(app, strlen(app));
} /* end
leggistatus()*/
struct
Hjava_lang_String *IeeeVxi_leggiVxiStatus(struct
HIeeeVxi *this){
#define
ERRVXI (1<<15)
#define
WRviol (1<<14)
#define
RRviol (1<<13)
#define
DORviol (1<<12)
#define
DIRviol (1<<11)
#define
RdProtErr (1<<10)
#define
UnSupCom (1<<9)
#define
TIMOVXI (1<<8)
#define
BERR (1<<7)
#define
MQE (1<<6)
#define
InvalidLA (1<<5)
#define
ForcedAbort (1<<4)
#define
DirDorAbort (1<<3)
#define
TC (1<<2)
#define
ENDVXI (1<<1)
#define
CMPLVXI (1<<0)
int16 retbus,controller;
BusStatus status;
char
app[255];
strcpy(app,"
<");
if
(ret & CMPLVXI ) strcat(app," CMPL");
if
(ret & ENDVXI ) strcat(app," END");
if
(ret & TC ) strcat(app," TC");
if
(ret & DirDorAbort) strcat(app," DirDorAbort");
strcat(app,"
>");
if
(ret & ERRVXI )
{
strcat(app,"
ERR: ");
if
(ret & WRviol) strcat(app," WRviol: Write Ready
protocol violation during tranfer.");
if
(ret & RRviol ) strcat(app," RRviol: Read Ready
protocol violation during tranfer.");
if
(ret & DORviol) strcat(app," DORviol: Data Out
Ready protocol violation.");
if
(ret & DIRviol ) strcat(app," DIRviol: Data in
Ready protocol violation.");
if
(ret & RdProtErr) strcat(app," RdProtErr: Read
protocol error.");
if
(ret & UnSupCom ) strcat(app," UnSupCom: Device
not support the command.");
if
(ret & TIMOVXI ) strcat(app," TIMO: Time out.");
if
(ret & BERR ) strcat(app," BERR: Bus error occurred
during tranfer.");
if
(ret & MQE ) strcat(app," MQE: Multiple query
error occurred during tranfer.");
if
(ret & InvalidLA) strcat(app," InvalidLA: invalid
LA specified.");
if
(ret & ForcedAbort) strcat(app," ForcedAbort:
User abort occurred during I/O.");
strcat(app,"
");
}
controller = -1;
retbus = GetVXIbusStatus(controller,&status);
if
(status.BusError) strcat(app," BusError.\n");
if
(status.Sysfail ) strcat(app," Sysfail.\n");
if
(status.ACfail) strcat(app," ACfail.\n");
if
(status.SignalIn ) strcat(app," SignalIn.\n");
if
(status.VXIints) strcat(app," VXIints.\n");
if
(status.ECLtrigs ) strcat(app," ECLtrigs.\n");
if
(status.TTLtrigs ) strcat(app," TTLtrigs.\n");
return
makeJavaString(app, strlen(app));
}
struct
Hjava_lang_String *IeeeVxi_leggiRisposta(struct
HIeeeVxi *this){
char
path[100];
strcpy(path,"c:\\public\\");
if
(order.bus[0] == 'I')
{
if
(order.salvainfile[0] == 'n')
{
ibrd(brd,order.risposta,255);
}
else
{
strcat(path,order.nomfile);
ibrdf(brd,path);
}
}
else
{
k=atoi(order.instrum);
if
(order.salvainfile[0] == 'n')
{
ret = WSrd(k,order.risposta,1000,1,&retcount);
order.risposta[retcount]='0';
}
else
{
strcat(path,order.nomfile);
ret = WSrdf(k,path,6000000,1,&retcount);
}
}
return
makeJavaString(order.risposta, strlen(order.risposta));
} /* end
leggirisposta()*/
void
IeeeVxi_initVXILibrary(struct HIeeeVxi *this)
{
ret = InitVXIlibrary();
}
void
IeeeVxi_closeVXILibrary(struct HIeeeVxi *this){
ret = CloseVXIlibrary();
}
Il file IeeeVxi.c
/* DO
NOT EDIT THIS FILE - it is machine generated */
#include
<StubPreamble.h>
/* Stubs
for class IeeeVxi */
/* SYMBOL:
"IeeeVxi/leggiInput(Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;)V",
Java_IeeeVxi_leggiInput_stub */
__declspec(dllexport)
stack_item *Java_IeeeVxi_leggiInput_stub(stack_item *_P_,struct
execenv *_EE_) {
extern
void IeeeVxi_leggiInput(void
*,void *,void
*,void *,void
*,void *,void
*);
(void)
IeeeVxi_leggiInput(_P_[0].p,((_P_[1].p)),((_P_[2].p)),((_P_[3].p)),((_P_[4].p)),((_P_[5].p)),((_P_[6].p)));
return
_P_;
}
/* SYMBOL:
"IeeeVxi/leggiStatus()Ljava/lang/String;", Java_IeeeVxi_leggiStatus_stub
*/
__declspec(dllexport)
stack_item *Java_IeeeVxi_leggiStatus_stub(stack_item *_P_,struct
execenv *_EE_) {
extern
void* IeeeVxi_leggiStatus(void
*);
_P_[0].p
= IeeeVxi_leggiStatus(_P_[0].p);
return
_P_ + 1;
}
/* SYMBOL:
"IeeeVxi/leggiVxiStatus()Ljava/lang/String;", Java_IeeeVxi_leggiVxiStatus_stub
*/
__declspec(dllexport)
stack_item *Java_IeeeVxi_leggiVxiStatus_stub(stack_item *_P_,struct
execenv *_EE_) {
extern
void* IeeeVxi_leggiVxiStatus(void
*);
_P_[0].p
= IeeeVxi_leggiVxiStatus(_P_[0].p);
return
_P_ + 1;
}
/* SYMBOL:
"IeeeVxi/leggiRisposta()Ljava/lang/String;", Java_IeeeVxi_leggiRisposta_stub
*/
__declspec(dllexport)
stack_item *Java_IeeeVxi_leggiRisposta_stub(stack_item *_P_,struct
execenv *_EE_) {
extern
void* IeeeVxi_leggiRisposta(void
*);
_P_[0].p
= IeeeVxi_leggiRisposta(_P_[0].p);
return
_P_ + 1;
}
/* SYMBOL:
"IeeeVxi/inviaAlloStrumento()V", Java_IeeeVxi_inviaAlloStrumento_stub */
__declspec(dllexport)
stack_item *Java_IeeeVxi_inviaAlloStrumento_stub(stack_item *_P_,struct
execenv *_EE_) {
extern
void IeeeVxi_inviaAlloStrumento(void
*);
(void)
IeeeVxi_inviaAlloStrumento(_P_[0].p);
return
_P_;
}
/* SYMBOL:
"IeeeVxi/initVXILibrary()V", Java_IeeeVxi_initVXILibrary_stub */
__declspec(dllexport)
stack_item *Java_IeeeVxi_initVXILibrary_stub(stack_item *_P_,struct
execenv *_EE_) {
extern
void IeeeVxi_initVXILibrary(void
*);
(void)
IeeeVxi_initVXILibrary(_P_[0].p);
return
_P_;
}
/* SYMBOL:
"IeeeVxi/closeVXILibrary()V", Java_IeeeVxi_closeVXILibrary_stub */
__declspec(dllexport)
stack_item *Java_IeeeVxi_closeVXILibrary_stub(stack_item *_P_,struct
execenv *_EE_) {
extern
void IeeeVxi_closeVXILibrary(void
*);
(void)
IeeeVxi_closeVXILibrary(_P_[0].p);
return
_P_;
}
Il file IeeeVxi.h
/* DO
NOT EDIT THIS FILE - it is machine generated */
#include
<native.h>
/* Header
for class IeeeVxi */
#ifndef
_Included_IeeeVxi
#define
_Included_IeeeVxi
#pragma pack(4)
typedef
struct ClassIeeeVxi {
#undef
IeeeVxi_stringDLL
#define
IeeeVxi_stringDLL 115L
/*boolean*/
long inUse;
/*boolean*/
long isShareble;
} ClassIeeeVxi;
HandleTo(IeeeVxi);
#pragma pack()
#ifdef
__cplusplus
extern
"C" {
#endif
struct
Hjava_lang_String;
extern
void IeeeVxi_leggiInput(struct
HIeeeVxi *,struct Hjava_lang_String *,struct
Hjava_lang_String *,struct Hjava_lang_String
*,struct Hjava_lang_String *,struct
Hjava_lang_String *,struct Hjava_lang_String
*);
extern
struct Hjava_lang_String *IeeeVxi_leggiStatus(struct
HIeeeVxi *);
extern
struct Hjava_lang_String *IeeeVxi_leggiVxiStatus(struct
HIeeeVxi *);
extern
struct Hjava_lang_String *IeeeVxi_leggiRisposta(struct
HIeeeVxi *);
extern
void IeeeVxi_inviaAlloStrumento(struct
HIeeeVxi *);
extern
void IeeeVxi_initVXILibrary(struct
HIeeeVxi *);
extern
void IeeeVxi_closeVXILibrary(struct
HIeeeVxi *);
#ifdef
__cplusplus
}
#endif
#endif
Il file AppletGUI.html
<HTML>
<HEAD>
<TITLE>AppletGUI</TITLE>
</HEAD>
<P>Un
applet visualizza un pulsante, cliccando sul
pulsante l'applet carica
una classe che gli viene passata
come parametro dalla pagina HTML.
</P>
<P><APPLET
CODE="device.client.AppletGUI.class" CODEBASE=
"..\dev" WIDTH=250
HEIGHT=60 NAME="AppletGUI">
<PARAM NAME = "portId"
VALUE = "4444">
<PARAM NAME = "classGUI"
VALUE = "IeeeVxiGUI">
<PARAM NAME = "titleGUI"
VALUE = "Pannello VXI">
<PARAM NAME = "buttonText"
VALUE = "Apri pannello ">
<B>
<FONT
COLOR="#FF0000">
Qui si vedrebbe un applet,
se il browser supportasse Java.
</FONT></B>
</APPLET></P>
</BODY>
</HTML>