From 7db2461bff6ca917f397df62cdda2642b74b243d Mon Sep 17 00:00:00 2001 From: felix Date: Mon, 12 Feb 2007 19:21:57 +0000 Subject: [PATCH] Code aus dem c't Projekt Applet eingecheckt git-svn-id: https://www.internetallee.de/svn/bytewurf@2 a944a559-bf0e-0410-8ddc-85264b264b6c --- projekte/netzschalter/src/Communication.java | 375 +++++ projekte/netzschalter/src/GUI.java | 2230 ++++++++++++++++++++++++++ projekte/netzschalter/src/IOControl.java | 294 ++++ projekte/netzschalter/src/TimerEvent.java | 225 +++ 4 files changed, 3124 insertions(+) create mode 100644 projekte/netzschalter/src/Communication.java create mode 100644 projekte/netzschalter/src/GUI.java create mode 100644 projekte/netzschalter/src/IOControl.java create mode 100644 projekte/netzschalter/src/TimerEvent.java diff --git a/projekte/netzschalter/src/Communication.java b/projekte/netzschalter/src/Communication.java new file mode 100644 index 0000000..3fd3a52 --- /dev/null +++ b/projekte/netzschalter/src/Communication.java @@ -0,0 +1,375 @@ +/* + * File Communication.java + */ + +import java.io.BufferedReader; +//import java.io.BufferedWriter; +import java.io.DataInputStream; +import java.io.DataOutputStream; +import java.io.IOException; +import java.io.InputStreamReader; +import java.io.InterruptedIOException; +//import java.io.OutputStreamWriter; +import java.net.InetAddress; +import java.net.Socket; +import java.net.UnknownHostException; + +/** + * @author olz + * + * This class does the TCP/IP work to operate the XPort Most of the get and set + * methods herein follow the same pattern: Establish a connection, prepare a + * command, send this command and disconnect. + * + */ +public class Communication { + + /** connection to XPort */ + protected Socket socket = null; + + /** dis contains data provided by XPort */ + protected BufferedReader dis = null; + + protected DataInputStream dis2 =null; + + /** dos contains data sent to XPort */ + protected DataOutputStream dos=null; + + /** + * This method converts the given String ipa_str and the int port into a + * useable TCP/IP address and then calls a helper method tcpip_connect() to + * establish a connection to the XPort + * + * @param ipa_str + * @param port + * @throws IOException + * @throws Exception + */ + public void connect(String ipa_str, int port) throws IOException, Exception { + InetAddress ipa = null; + try { + ipa = InetAddress.getByName(ipa_str); + } catch (UnknownHostException UHEx) { + throw UHEx; + } catch (Exception Ex) { + throw Ex; + } + try { + tcpip_connect(ipa, port); + } catch (IOException IOEx) { + throw IOEx; + } catch (Exception Ex) { + throw Ex; + } + } + + /** + * this method will end the current connection to the XPort + * + * @throws IOException + * @throws Exception + */ + public synchronized void disconnect() throws IOException, Exception { + try { + tcpip_disconnect(); + } catch (IOException IOEx) { + throw IOEx; + } catch (Exception Ex) { + throw Ex; + } + } + + /** + * uses a TCP/IP connection to send a String to the XPort + * + * @param sendString + * @throws IOException + * @throws Exception + */ + public synchronized void send(String sendString) throws IOException, + Exception { + System.out.println(sendString); + try { + dos.writeBytes(sendString);//, 0, sendString.length()); + // write data to dos as String starting at String[0] + // and ending at String[String.length()] + } catch (IOException IOEx) { + throw IOEx; + } catch (Exception Ex) { + throw Ex; + } + try { + dos.flush(); // write dos to XPort + } catch (IOException IOEx) { + throw IOEx; + } catch (Exception Ex) { + throw Ex; + } + return; + } + + /** + * uses a TCP/IP connection to send a String to the XPort + * + * @param sendByte + * @throws IOException + * @throws Exception + */ + public synchronized void send(int sendByte[]) throws IOException, + Exception { + int dummy; + try { + for (int i = 0; i < sendByte.length; i++) { + dummy= sendByte[i] & 255; + dos.write(dummy); // bytewise write data to dos + } + } catch (IOException IOEx) { + throw IOEx; + } catch (Exception Ex) { + throw Ex; + } + try { + dos.flush(); // write dos to XPort + } catch (IOException IOEx) { + throw IOEx; + } catch (Exception Ex) { + throw Ex; + } + + return; + } + + /** + * closes the TCP/IP connection + * + * @throws IOException + * @throws Exception + */ + private void tcpip_disconnect() throws IOException, Exception { + if (socket.isConnected()) { + try { + dis.close(); // close input and output stream + dos.close(); // as well as the socket + socket.close(); + } catch (IOException IOEx) { + throw IOEx; + } catch (Exception Ex) { + throw Ex; + } + } + } + + /** + * reads data supplied by the XPort and returns a String + * + * @return + * @throws InterruptedIOException + * @throws IOException + * @throws Exception + */ + public String receiveString() throws InterruptedIOException, IOException, + Exception { + String antwort = ""; + int length=255; + byte[] in = new byte[length]; + + try { + dis.ready(); // check if data is available (actually redundant since + // the calling method from the GUI class already made + // this sure but better safe than sorry... :-) + } catch (IOException IOEx) { + throw IOEx; + } catch (Exception Ex) { + throw Ex; + } + + try { + + length = readBuffer(in,length); // call helper method to read from dis + antwort= new String(in,0,length); + } catch (IOException IOEx) { + throw IOEx; + } catch (Exception Ex) { + throw Ex; + } + return antwort; + } + + /** + * this method will read from DataInputStream dis, convert the chars read + * into ASCII and return its answer as a String + * + * @return + * @throws IOException + * @throws Exception + */ + public synchronized int readBuffer(int[] gelesen,int length) throws IOException, Exception { + int i=0; // init helper variables + //byte [] gelesen = new byte[length.intValue()]; + + while ((dis.ready())& (i1; i--) { + relais[i] = new Button("Rel "+ (i+1)); + relais[i].addActionListener(this); + relais[i].setEnabled(false); // buttons are not allowed until 1st showRelais() + c.gridx = col++; c.gridy = row; c.gridwidth = 1; c.gridheight = 1; + gbl.setConstraints(relais[i], c); + bPanel.add(relais[i]); + } + + getRelais = new Button("Read Relais"); + getRelais.addActionListener(this); + c.gridx = 4; c.gridy = row-1; c.gridwidth = 1; c.gridheight = 1; + gbl.setConstraints(getRelais, c); + bPanel.add(getRelais); + + // ------------------------------------- + row++; col=0; + + label = new Label("Start"); + c.gridx = col++; c.gridy = row; c.gridwidth = 1; c.gridheight = 1; + gbl.setConstraints(label, c); + bPanel.add(label); + + label = new Label("Cmd"); + c.gridx = col++; c.gridy = row; c.gridwidth = 1; c.gridheight = 1; + gbl.setConstraints(label, c); + bPanel.add(label); + + label = new Label("Data"); + c.gridx = col++; c.gridy = row; c.gridwidth = 1; c.gridheight = 1; + gbl.setConstraints(label, c); + bPanel.add(label); + + label = new Label("Stop"); + c.gridx = col++; c.gridy = row; c.gridwidth = 1; c.gridheight = 1; + gbl.setConstraints(label, c); + bPanel.add(label); + + // ------------------------------------- + row++; col=0; + + StartCodeField = new TextField(1); + StartCodeField.addActionListener(this); + StartCodeField.setText(Integer.toHexString(START_CODE)); + StartCodeField.setEditable(false); + c.gridx = col++; c.gridy = row; c.gridwidth = 1; c.gridheight = 1; + gbl.setConstraints(StartCodeField, c); + bPanel.add(StartCodeField); + + Command = new TextField(1); + Command.addActionListener(this); + Command.setText("80"); + c.gridx = col++; c.gridy = row; c.gridwidth = 1; c.gridheight = 1; + gbl.setConstraints(Command, c); + bPanel.add(Command); + + Data = new TextField(1); + Data.addActionListener(this); + Data.setText("30"); + c.gridx = col++; c.gridy = row; c.gridwidth = 1; c.gridheight = 1; + gbl.setConstraints(Data, c); + bPanel.add(Data); + + StopCodeField = new TextField(1); + StopCodeField.addActionListener(this); + StopCodeField.setText(Integer.toHexString(STOP_CODE)); + StopCodeField.setEditable(false); + c.gridx = col++; c.gridy = row; c.gridwidth = 1; c.gridheight = 1; + gbl.setConstraints(StopCodeField, c); + bPanel.add(StopCodeField); + + sendCommand = new Button(); + sendCommand.setLabel("send command"); + sendCommand.addActionListener(this); + c.gridx = col++; c.gridy = row; c.gridwidth = 1; c.gridheight = 1; + gbl.setConstraints(sendCommand, c); + bPanel.add(sendCommand); + + label = new Label("Channel"); + c.gridx = col++; c.gridy = row; c.gridwidth = 1; c.gridheight = 1; + c.fill = GridBagConstraints.NONE; + gbl.setConstraints(label, c); + bPanel.add(label); + + adcChannel = new TextField(2); + adcChannel.setText("0"); + c.gridx = col++; c.gridy = row; c.gridwidth = 1; c.gridheight = 1; + c.fill = GridBagConstraints.NONE; + gbl.setConstraints(adcChannel, c); + bPanel.add(adcChannel); + + useFilter = new Checkbox("Filter?", false); + c.gridx = col++; c.gridy = row; c.gridwidth = 1; c.gridheight = 1; + c.fill = GridBagConstraints.BOTH; + gbl.setConstraints(useFilter, c); + bPanel.add(useFilter); + + + getSamples = new Button("Sample"); + getSamples.addActionListener(this); + c.gridx = col++; c.gridy = row; c.gridwidth = 1; c.gridheight = 1; + gbl.setConstraints(getSamples, c); + bPanel.add(getSamples); + + } + + +/* + * Construct Connection Panel + */ + private void constructXPortPanel(){ + GridBagLayout gbl = new GridBagLayout(); + xPortPannel.setLayout(gbl); + + GridBagConstraints c = new GridBagConstraints(); + // ein paar defaults einstellen; + c.fill = GridBagConstraints.BOTH; // wie Komponente Bereich füllen soll + c.weightx = 90; // Breite + c.weighty = 120; // Höhe + c.insets = new Insets(0,5,10,15); // Abstände definieren + + Label label = new Label("IP-Adresse"); + c.gridx = 0; c.gridy = 0; c.gridwidth = 2; c.gridheight = 1; + gbl.setConstraints(label, c); + xPortPannel.add(label); + + IPAdresse = new TextField(5); + c.gridx = 0; c.gridy = 1; c.gridwidth = 2; c.gridheight = 1; + gbl.setConstraints(IPAdresse, c); + xPortPannel.add(IPAdresse); + + label = new Label("Port"); + c.gridx = 2; c.gridy = 0; c.gridwidth = 2; c.gridheight = 1; + gbl.setConstraints(label, c); + xPortPannel.add(label); + + PortField = new TextField(5); + PortField.setText(Integer.toString(bridgePort)); + c.gridx = 2; c.gridy = 1; c.gridwidth = 2; c.gridheight = 1; + gbl.setConstraints(PortField, c); + xPortPannel.add(PortField); + + + + Connect = new Button(); + Connect.setLabel("Connect to XPort"); + Connect.addActionListener(this); + c.gridx = 0; c.gridy = 2; c.gridwidth = 2; c.gridheight = 1; + gbl.setConstraints(Connect, c); + xPortPannel.add(Connect); + + Disconnect = new Button(); + Disconnect.setLabel("Disconnect"); + Disconnect.addActionListener(this); + c.gridx = 2; c.gridy = 2; c.gridwidth = 2; c.gridheight = 1; + gbl.setConstraints(Disconnect, c); + xPortPannel.add(Disconnect); + + } + /* + * setzt das I/O Panel zusammen + */ + private void constructAPanel(){ + int col, row; + + GridBagLayout gbl = new GridBagLayout(); + aPanel.setLayout(gbl); + + GridBagConstraints c = new GridBagConstraints(); + // ein paar defaults einstellen; + c.fill = GridBagConstraints.BOTH; // wie Komponente Bereich füllen soll + c.weightx = 90; // Breite + c.weighty = 100; // Höhe + c.insets = new Insets(0,5,10,15); // Abstände definieren + + col=0; row=0; + + Label label = new Label("XPort I/O Pins"); + c.gridx = col++; c.gridy = row; c.gridwidth = 1; c.gridheight = 1; + gbl.setConstraints(label, c); + aPanel.add(label); + + aPanelToBPanel = new Button(); + aPanelToBPanel.setLabel("Switch to B-module control"); + aPanelToBPanel.addActionListener(this); + c.gridx = col++; c.gridy = row; c.gridwidth = 4; c.gridheight = 1; + gbl.setConstraints(aPanelToBPanel, c); + aPanel.add(aPanelToBPanel); + + + // ------------------------------------- + row++; col=0; + + label = new Label("Value"); + c.gridx = col++; c.gridy = row; c.gridwidth = 1; c.gridheight = 1; + gbl.setConstraints(label, c); + aPanel.add(label); + + setCPins = new Button(); + setCPins.setLabel("Set"); + setCPins.addActionListener(this); + c.gridx = col++; c.gridy = row; c.gridwidth = 1; c.gridheight = 1; + gbl.setConstraints(setCPins, c); + aPanel.add(setCPins); + + + CPins = new Checkbox[NUMCPINS]; + for (int i = 0; i < NUMCPINS; i++) { + CPins[i] = new Checkbox("CP" + (i + 1), false); + c.gridx = col++; c.gridy = row; c.gridwidth = 1; c.gridheight = 1; + gbl.setConstraints(CPins[i], c); + aPanel.add(CPins[i]); + } + + getCPins = new Button(); + getCPins.setLabel("Read"); + getCPins.addActionListener(this); + c.gridx = col++; c.gridy = row; c.gridwidth = 1; c.gridheight = 1; + gbl.setConstraints(getCPins, c); + aPanel.add(getCPins); + + // ------------------------------------- + row++; col=0; + + label = new Label("Direction"); + c.gridx = col++; c.gridy = row; c.gridwidth = 1; c.gridheight = 1; + gbl.setConstraints(label, c); + aPanel.add(label); + + setCPinDir = new Button(); + setCPinDir.setLabel("Set"); + setCPinDir.addActionListener(this); + c.gridx = col++; c.gridy = row; c.gridwidth = 1; c.gridheight = 1; + gbl.setConstraints(setCPinDir, c); + aPanel.add(setCPinDir); + + CPinDir = new Checkbox[NUMCPINS]; + for (int i = 0; i < NUMCPINS; i++) { + CPinDir[i] = new Checkbox("CP" + (i + 1), false); + c.gridx = col++; c.gridy = row; c.gridwidth = 1; c.gridheight = 1; + gbl.setConstraints(CPinDir[i], c); + aPanel.add(CPinDir[i]); + } + + getCPinDir = new Button(); + getCPinDir.setLabel("Read"); + getCPinDir.addActionListener(this); + c.gridx = col++; c.gridy = row; c.gridwidth = 1; c.gridheight = 1; + gbl.setConstraints(getCPinDir, c); + aPanel.add(getCPinDir); + + + } + + + /* + * setzt das Terminal Panel zusammen + */ + private void constructTerminalPanel(){ + int col, row; + + GridBagLayout gbl = new GridBagLayout(); + terminalPanel.setLayout(gbl); + + GridBagConstraints c = new GridBagConstraints(); + // ein paar defaults einstellen; + c.fill = GridBagConstraints.BOTH; // wie Komponente Bereich füllen soll + c.weightx = 90; // Breite + c.weighty = 100; // Höhe + c.insets = new Insets(0,5,10,15); // Abstände definieren + + col=0; row=0; + + + Label label = new Label("Data to COM"); + c.gridx = col++; c.gridy = row; c.gridwidth = 1; c.gridheight = 1; + gbl.setConstraints(label, c); + terminalPanel.add(label); + + eingabeFeld = new TextField(12); + eingabeFeld.addActionListener(this); + c.gridx = col++; c.gridy = row; c.gridwidth = 4; c.gridheight = 1; + gbl.setConstraints(eingabeFeld, c); + terminalPanel.add(eingabeFeld); + + // ------------------------------------- + row++; col=0; + + label = new Label("Output from COM"); + c.gridx = col++; c.gridy = row; c.gridwidth = 1; c.gridheight = 1; + gbl.setConstraints(label, c); + terminalPanel.add(label); + + showASCII = new Checkbox("Decode Readable Chars?", false); + c.gridx = 4; c.gridy = row; c.gridwidth = 1; c.gridheight = 1; + gbl.setConstraints(showASCII, c); + terminalPanel.add(showASCII); + + + // ------------------------------------- + row++; col=0; + + ausgabeFeld = new TextArea(10, 50); + ausgabeFeld.setText(""); + ausgabeFeld.setEditable(false); + c.gridx = col++; c.gridy = row; c.gridwidth = 5; c.gridheight = 1; + gbl.setConstraints(ausgabeFeld, c); + terminalPanel.add(ausgabeFeld); + } + + + /** + * This method will display all the GUI's elements on the Applet and preset + * them with a number of values. It does not perform any actions other than + * that. Since it's name is init() and we've got an Applet here, it's + * automatically run by the JRE. + */ + public void init() { + int col, row; + + GridBagLayout gbl = new GridBagLayout(); + this.setLayout(gbl); + + GridBagConstraints c = new GridBagConstraints(); + // ein paar defaults einstellen; + c.fill = GridBagConstraints.BOTH; // wie Komponente Bereich füllen soll + c.weightx = 90; // Breite + c.weighty = 120; // Höhe + c.insets = new Insets(0,5,10,15); // Abstände definieren + + // Zur Verinfachung kommt jede Funktionsgruppe in ihr eigenes Panel + + // ------------------------------------- + col=0; row=0; + + Label label = new Label("c't-Netz-Schalter"); + c.gridx = col++; c.gridy = row; c.gridwidth = 1; c.gridheight = 1; + gbl.setConstraints(label, c); + this.add(label); + + // ------------------------------------- + row++; col=0; + + // Dieses Panel kümmert sich um den Verbindungsaufbau zum XPort + xPortPannel = new Panel(); + c.gridx = col++; c.gridy = row; c.gridwidth = 1; c.gridheight = 1; + gbl.setConstraints(xPortPannel, c); + this.add(xPortPannel); + constructXPortPanel(); + xPortPannel.setBackground(new Color(200,200,200)); + + // ------------------------------------- + row++; col=0; + + // Dieses Panel enthält die Steuerung der I/O-Pins des XPports + aPanel = new Panel(); + c.gridx = col++; c.gridy = row; c.gridwidth = 1; c.gridheight = 1; + gbl.setConstraints(aPanel, c); + this.add(aPanel); + constructAPanel(); + aPanel.setBackground(new Color(200,200,200)); + aPanel.setVisible(false); // since we start with the B panel, we hide + // the A panel from the user + + // ------------------------------------- + row++; col=0; + + // Alles zur Steuerung des B-Moduls + bPanel = new Panel(); + c.gridx = col; c.gridy = row; c.gridwidth = 1; c.gridheight = 1; + gbl.setConstraints(bPanel, c); + this.add(bPanel); + constructBPanel(); + bPanel.setBackground(new Color(200,200,200)); + bPanel.setVisible(false); // since we start with the A panel, we hide + // the B panel from the user + + // Timer-Modul + timerPanel = new Panel(); + c.gridx = col; c.gridy = row; c.gridwidth = 1; c.gridheight = 1; + + gbl.setConstraints(timerPanel, c); + this.add(timerPanel); + constructTimerPanel(); + timerPanel.setBackground(new Color(200,200,200)); + // timerPanel.setVisible(false); // since we start with the A panel, we hide + // the B panel from the user + + // ------------------------------------- + row++; col=0; + + terminalPanel = new Panel(); + c.gridx = col++; c.gridy = row; c.gridwidth = 1; c.gridheight = 1; + gbl.setConstraints(terminalPanel, c); + this.add(terminalPanel); + constructTerminalPanel(); + terminalPanel.setBackground(new Color(200,200,200)); + + // ------------------------------------- + row++; col=0; + + label = new Label("Status"); + c.gridx = col++; c.gridy = row; c.gridwidth = 1; c.gridheight = 1; + gbl.setConstraints(label, c); + this.add(label); + + + + // ------------------------------------- + row++; col=0; + + statusFeld = new TextArea(8, 30); + statusFeld.setEditable(false); + statusFeld.setText(""); + statusFeld.setForeground(Color.red); + c.gridx = col++; c.gridy = row; c.gridwidth = 1; c.gridheight = 1; + gbl.setConstraints(statusFeld, c); + this.add(statusFeld); + + + + /* ChangeTab = new Button(); + ChangeTab.setLabel("Switch to B-module control"); + ChangeTab.addActionListener(this); + c.gridx = col++; c.gridy = row; c.gridwidth = 1; c.gridheight = 1; + gbl.setConstraints(ChangeTab, c); + this.add(ChangeTab); + */ + IOControl1 = new IOControl(); + + + + + this.setSize(1024, 768); + this.doLayout(); + } + + /** + * This method is responsible for some additional initialisations and + * presetting values. Basically, it could be integrated into init() without + * any major trouble. + */ + public void start() { + + try { // intercept problems with wrong or invalid IP addresses and ports + // that's why we're using a try statement here + // this.getCodeBase() will return the Applet's IP, including + // "http://". + // However, we only want the pure IP address, so we use substring() + // to + // extract the numbers. + IPAdresse.setText(this.getCodeBase().toString().substring(7, + this.getCodeBase().toString().length() - 1)); + IPAdresse.setText("192.168.123.200"); + append(statusFeld,"Current IP = " + IPAdresse.getText()); // display ip address + } catch (NullPointerException NPEx) { + System.err.println("NullPointerException occured"); + PortField.setText("0"); // default port for serial interface control + } + // create a new instance of a Communication object to allow control of + // the XPort + XPort = new Communication(); + append(statusFeld,"Applet initialised, ready to connect..."); + Disconnect.setEnabled(false); // keep the user from using the + // "Disconnect" button while + // not connected + ReadThread = new InputReadThread(); // initialise a thread and start + // waiting for data from the XPort + } + + /** + * This method will just test if the value entered in the field PortField is + * a number or not. + * + * @return + */ + private boolean port_auswert() { + try { + Integer.parseInt(PortField.getText()); + } catch (NumberFormatException NFEx) { + ausgabeFeld + .append("Entered port has invalid format - please correct!\n"); + return false; + } + return true; + } + + /** + * This method will establish a connection to the XPort via the entered IP + * address and port. Its second purpose is to enable and disable GUI + * elements which are needed respectively not needed while a connection is + * established. + */ + private void connect() { + append(statusFeld,"Trying to connect..."); + if (!port_auswert()) { // if no valid port is stated, stop immediately + append(statusFeld,"Invalid port!"); + return; + } else + // well, let's see if the IP address is valid... + // if it is, start a connection! + try { + int port = Integer.parseInt(PortField.getText()); + append(statusFeld,"Connecting to " + IPAdresse.getText() + + " at port " + port); + // call the "real" connection method + XPort.connect(IPAdresse.getText(), port); + + Connect.setEnabled(false); // allow user only to use button + // "Disconnect" + Disconnect.setEnabled(true); + IPAdresse.setEditable(false); + PortField.setEditable(false); + // display some status info + append(statusFeld,"Connection successfully established."); + append(statusFeld,"Setting up reading loop."); + + wasConnected = true; + isConnected = true; + + ReadThread = new InputReadThread(); // initialise a thread and start + ReadThread.gui=this; + ReadThread.start(); + + getCPinDir(); + + return; + } + // If any error occurs, display it and stop connecting. + catch (IOException IOEx) { + append(statusFeld,"I/O error while connecting: " + IOEx); + } catch (Exception Ex) { + append(statusFeld,"Error while connecting: " + Ex); + Ex.printStackTrace(); + } + } + + /** + * Will call LEDauswert() to check which LEDs are to be toggled and sends + * this value to the XPort. + */ + private void setCPins() { + int pin, bitValue; + LockButtons(); + try { + controlAntwort = IOControl1.toggle(IPAdresse.getText(), LEDauswert()); + } catch (IOException IOEx) { + append(statusFeld,"I/O error while toggling LEDs: " + IOEx); + } catch (Exception Ex) { + append(statusFeld,"Error while toggling LEDs: " + Ex); + } + + for (pin = 0, bitValue = 1; pin < NUMCPINS; pin++) { + if ((controlAntwort[pin/8] & bitValue) != 0) { // compare if bit is set + CPins[pin].setState(true); // Pin is high + } else { + CPins[pin].setState(false); // Pin is Low + } + bitValue= (bitValue <<1) % 256; + } + + UnlockButtons(); + } + + /** + * Allows toggling the XPort's I/O directions between incoming and outgoing. + * This method itself only sends the checkboxes' values to the XPort's + * respective method, toggleDirection(). + * + */ + private void setCPinDir() { + int pin, bitValue; + LockButtons(); + try { + controlAntwort = IOControl1.toggleDirection(IPAdresse.getText(), + IOauswert()); + } catch (IOException IOEx) { + append(statusFeld,"I/O error while toggling I/O directions: " + IOEx); + } catch (Exception Ex) { + append(statusFeld,"Error while toggling I/O directions: " + Ex); + } + for (pin = 0, bitValue = 1; pin < NUMCPINS; pin++) { + if ((controlAntwort[pin/8] & bitValue) != 0) { // compare if bit is set + CPinDir[pin].setState(true); // Pin is an Output + CPins[pin].setEnabled(true); // Changes to PIN allowed + } else { + CPinDir[pin].setState(false); // Pin is an Input + CPins[pin].setEnabled(false); // Changes to PIN not allowed + } + bitValue= (bitValue <<1) % 256; + } + + getCPinDir(); + } + + /** + * Will ask the XPort how which I/O pins are availbale to user + */ + private void getCPinFunctions() { + int pin, bitValue; + LockButtons(); + try { + controlAntwort = IOControl1.getFunc(IPAdresse.getText()); + } catch (IOException IOEx) { + append(statusFeld,"I/O error while getting I/O functions: " + IOEx); + } catch (Exception Ex) { + append(statusFeld,"Error while getting I/O functions: " + Ex); + } + + for (pin = 0, bitValue = 1; pin < NUMCPINS; pin++) { + if ((controlAntwort[pin/8] & bitValue) != 0) { // compare if bit is set + CPinDir[pin].setEnabled(true); // Pin is available + CPins[pin].setEnabled(true); // Changes to PIN allowed + } else { + CPinDir[pin].setEnabled(false); // Pin is not available + CPins[pin].setEnabled(false); // Changes to PIN not allowed + } + bitValue= (bitValue <<1) % 256; + } + UnlockButtons(); + } + + /** + * reads the XPort's I/O directions and displays them on an output field. + * There is no need to read more than bits 0 to 2 from byte 0 since the + * XPort does not have more than three I/O pins. + */ + private void getCPinDir() { + int pin, bitValue; + + LockButtons(); + try { + controlAntwort = IOControl1.getDir(IPAdresse.getText()); + } catch (IOException IOEx) { + append(statusFeld,"I/O error while getting I/O directions: " + IOEx); + } catch (Exception Ex) { + append(statusFeld,"Error while getting I/O directions: " + Ex); + } + + for (pin = 0, bitValue = 1; pin < NUMCPINS; pin++) { + if ((controlAntwort[pin/8] & bitValue) != 0) { // compare if bit is set + CPinDir[pin].setState(true); // Pin is an Output + CPins[pin].setEnabled(true); // Changes to PIN allowed + } else { + CPinDir[pin].setState(false); // Pin is an Input + CPins[pin].setEnabled(false); // Changes to PIN not allowed + } + bitValue= (bitValue <<1) % 256; + } + UnlockButtons(); + } + + /** + * reads the XPort's I/O pin's current state and displays them. + */ + private void getCPins() { + int pin, bitValue; + + LockButtons(); + try { + controlAntwort = IOControl1.getCurrentState(IPAdresse.getText()); + } catch (IOException IOEx) { + append(statusFeld,"I/O error while getting current states: " + IOEx); + } catch (Exception Ex) { + append(statusFeld,"Error while getting current states: " + Ex); + } + + for (pin = 0, bitValue = 1; pin < NUMCPINS; pin++) { + if ((controlAntwort[pin/8] & bitValue) != 0) { // compare if bit is set + CPins[pin].setState(true); // Pin is high + } else { + CPins[pin].setState(false); // Pin is Low + } + bitValue= (bitValue <<1) % 256; + } + + + UnlockButtons(); + } + + /* + * Sends the System Date & Time to B-Modul + */ + private void timerSetDateTime(){ + Calendar cal = Calendar.getInstance(); + + append(statusFeld,"Setting Date in c't-Netzschalter to: "+cal.getTime()); + + int[] date = { + (int)cal.get(Calendar.DAY_OF_MONTH), + (int)cal.get(Calendar.MONTH)+1, + (int)(cal.get(Calendar.YEAR) >> 8), + (int)(cal.get(Calendar.YEAR) & 255), + (int)(cal.get(Calendar.DAY_OF_WEEK))}; + + int[] time = { + (int)cal.get(Calendar.HOUR_OF_DAY), + (int)cal.get(Calendar.MINUTE), + (int)cal.get(Calendar.SECOND)}; + + + try { + transmitCommand(CMD_SETDATE, date); + transmitCommand(CMD_SETTIME, time); + } catch (IOException IOEx) { + append(statusFeld,"I/O error while setting Date and Time: " + IOEx); + } catch (Exception Ex) { + append(statusFeld,"Error while setting Date and Time: " + Ex); + } + } + + /* Read an Event from B-Module */ + private void timerRead(){ + int[] data={0}; + int[] answer= new int[CMD_LENGTH]; + int[] eventData= new int[TimerEvent.SIZE]; + + data[0]=(int) Integer.valueOf("000000"+timerEventNr.getText(), 16).intValue() ; + try { + transmitCommand(CMD_GETEVENT, data, answer, eventData ); + + timerEvents.setText("of "+answer[2]+" Events"); + + timerEvent= new TimerEvent(eventData); + append(statusFeld,timerEvent.toString()); + + timerChannel.setText(""+timerEvent.getChannel()); + timerData.setText(""+timerEvent.getData()); + + timerSpecial.setState(timerEvent.getSpecial()); + + timerDay.setText(""+timerEvent.getDay()); + if (timerEvent.getDay() != TimerEvent.DONTCARE){ + timerDay.setEditable(true); + timerDayDontCare.setState(true); + } else { + timerDay.setEditable(false); + timerDayDontCare.setState(false); + } + + timerMonth.setText(""+timerEvent.getMonth()); + if (timerEvent.getMonth() != TimerEvent.DONTCARE){ + timerMonth.setEditable(true); + timerMonthDontCare.setState(true); + } else { + timerMonth.setEditable(false); + timerMonthDontCare.setState(false); + } + + + timerYear.setText(""+timerEvent.getYear()); + if (timerEvent.getYear() != TimerEvent.DONTCARE){ + timerYear.setEditable(true); + timerYearDontCare.setState(true); + } else { + timerYear.setEditable(false); + timerYearDontCare.setState(false); + } + + timerHour.setText(""+timerEvent.getHour()); + if (timerEvent.getHour() != TimerEvent.DONTCARE){ + timerHour.setEditable(true); + timerHourDontCare.setState(true); + } else { + timerHour.setEditable(false); + timerHourDontCare.setState(false); + } + + timerMinute.setText(""+timerEvent.getMinute()); + if (timerEvent.getMinute() != TimerEvent.DONTCARE){ + timerMinute.setEditable(true); + timerMinuteDontCare.setState(true); + } else { + timerMinute.setEditable(false); + timerMinuteDontCare.setState(false); + } + + timerSecond.setText(""+timerEvent.getSecond()); + if (timerEvent.getSecond() != TimerEvent.DONTCARE){ + timerSecond.setEditable(true); + timerSecondDontCare.setState(true); + } else { + timerSecond.setEditable(false); + timerSecondDontCare.setState(false); + } + + timerWeekday.setText(""+timerEvent.getWeekday()); + if (timerEvent.getWeekday() != TimerEvent.DONTCARE){ + timerWeekday.setEditable(true); + timerWeekdayDontCare.setState(true); + } else { + timerWeekday.setEditable(false); + timerWeekdayDontCare.setState(false); + } + + + } catch (IOException IOEx) { + append(statusFeld,"I/O error while reading Event: " + IOEx); + } catch (Exception Ex) { + append(statusFeld,"Error while reading Event: " + Ex); + } + } + + /* Writean Event to B-Module */ + private void timerWrite(){ + int[] answer = new int[CMD_LENGTH]; + timerEvent= new TimerEvent(); + + // First load all values from GUI to TimerEvent + timerEvent= new TimerEvent(); + + timerEvent.setChannel( Integer.valueOf(timerChannel.getText()).intValue() ); + timerEvent.setData( Integer.valueOf(timerData.getText()).intValue() ); + timerEvent.setSpecial(timerSpecial.getState()); + + if (timerDayDontCare.getState()== true) + timerEvent.setDay ( Integer.valueOf(timerDay.getText()).intValue() ); + else + timerEvent.setDay (TimerEvent.DONTCARE); + + if (timerMonthDontCare.getState()== true) + timerEvent.setMonth( Integer.valueOf(timerMonth.getText()).intValue() ); + else + timerEvent.setMonth (TimerEvent.DONTCARE); + + if (timerYearDontCare.getState()== true) + timerEvent.setYear ( Integer.valueOf(timerYear.getText()).intValue() ); + else + timerEvent.setYear(TimerEvent.DONTCARE); + + if (timerHourDontCare.getState()== true) + timerEvent.setHour ( Integer.valueOf(timerHour.getText()).intValue() ); + else + timerEvent.setHour(TimerEvent.DONTCARE); + + if (timerMinuteDontCare.getState()== true) + timerEvent.setMinute( Integer.valueOf(timerMinute.getText()).intValue() ); + else + timerEvent.setMinute(TimerEvent.DONTCARE); + + if (timerSecondDontCare.getState()== true) + timerEvent.setSecond ( Integer.valueOf(timerSecond.getText()).intValue() ); + else + timerEvent.setSecond(TimerEvent.DONTCARE); + + if (timerWeekdayDontCare.getState()== true) + timerEvent.setWeekday ( Integer.valueOf(timerWeekday.getText()).intValue() ); + else + timerEvent.setWeekday(TimerEvent.DONTCARE); + + + int[] data={0}; + + data[0]=(int) Integer.valueOf("000000"+timerEventNr.getText(), 16).intValue() ; + try { + transmitCommand(CMD_SETEVENT, data, answer, null, timerEvent.getSerial()); + + } catch (IOException IOEx) { + append(statusFeld,"I/O error while writing Event: " + IOEx); + } catch (Exception Ex) { + append(statusFeld,"Error while writing Event: " + Ex); + } + + timerEvents.setText("of "+answer[2]+" Events"); + + + } + + /* + * Deletes a timerEvent + */ + private void timerDelete(){ + int[] data={0}; + int[] answer= new int[CMD_LENGTH]; + + data[0]=(int) Integer.valueOf("000000"+timerEventNr.getText(), 16).intValue() ; + try { + transmitCommand(CMD_DELETEEVENT, data, answer); + + timerEvents.setText("of "+answer[2]+" Events"); + + if ((data[0] == answer[2])& (data[0]>0)){ + data[0]--; + timerEventNr.setText(""+data[0]); + } + timerRead(); + + } catch (IOException IOEx) { + append(statusFeld,"I/O error while deleting Event: " + IOEx); + } catch (Exception Ex) { + append(statusFeld,"Error while deleting Event: " + Ex); + } + } + + /** + * will end the connection to the XPort and re-enable the GUI elements faded + * out while the connection existed. + * + */ + private void disconnect() { + append(statusFeld,"Trying to disconnect..."); + try { + XPort.disconnect(); // end connection and stop reading thread. + ReadThread.interrupt(); + isConnected = false; // update connection flags + wasConnected = false; + } catch (IOException IOEx) { + append(statusFeld,"I/O error during disconnect: " + IOEx); + } catch (Exception Ex) { + append(statusFeld,"General error during disconnect: " + Ex); + } + + Connect.setEnabled(true); // re-activate GUI elements + Disconnect.setEnabled(false); // and re-allow user to change IP address + IPAdresse.setEditable(true); // and port + PortField.setEditable(true); + + append(statusFeld,"Connection closed."); + } + + /** + * This method reads the input field after hitting enter and sends its + * content to the XPort. The string read is also displayed on the output + * textfield, preceded by >>. + */ + private void sendText() { + try { + String sendString = eingabeFeld.getText(); + XPort.send(sendString); + append(ausgabeFeld,"\n>> " + sendString); + } catch (IOException IOEx) { + append(statusFeld,"I/O error while reading: " + IOEx); + } catch (Exception Ex) { + append(statusFeld,"Error while reading: " + Ex); + } + eingabeFeld.setText(""); + eingabeFeld.requestFocus(); + } + + /** + * Overrides ActionListener's actionPerformed(). To keep this method halfway + * simple and not too complex, it only calls other methods to do the actual + * work. + */ + public void actionPerformed(ActionEvent e) throws NullPointerException { + if (e.getActionCommand() == Connect.getLabel()) { // Buttion "Connect" + // was clicked + connect(); + return; + } + if (e.getActionCommand() == Disconnect.getLabel()) { + // user wants to end the connection to the XPort + disconnect(); + return; + } + + if (e.getActionCommand() == aPanelToBPanel.getLabel()) { + // switch from A panel to B panel and vice versa + changePanel('B'); + return; + } + if (e.getActionCommand() == bPanelToTimerPanel.getLabel()) { + // switch from A panel to B panel and vice versa + changePanel('C'); + return; + } + if (e.getActionCommand() == timerPanelToAPanel.getLabel()) { + // switch from A panel to B panel and vice versa + changePanel('A'); + return; + } + + + if (e.getActionCommand() == setCPins.getLabel()) { + // user wants to toggle some LEDs + setCPins(); + return; + } + + if (e.getActionCommand() == getCPins.getLabel()) { + // user wants to know how many pins are available + getCPins(); + return; + } + if (e.getActionCommand() == setCPinDir.getLabel()) { + // user wants to change I/O directions + setCPinDir(); + return; + } + + if (e.getActionCommand() == getCPinDir.getLabel()) { + // user wants to get the I/O directions updated + getCPinFunctions(); + getCPinDir(); + return; + } + if (e.getActionCommand() == sendCommand.getLabel()) { + // user wants to send a command to the B-Module + sendCommand(); + return; + } + + if (e.getSource() == eingabeFeld) { + // user wants to send some command to the XPort + sendText(); + } + + if (e.getActionCommand() == getRelais.getLabel()) { + bReadRelais(); + } + + if (e.getActionCommand() == getSamples.getLabel()) { + bReadSamples(); + } + + if (e.getActionCommand() == timerSetDateTime.getLabel()) { + timerSetDateTime(); + } + + if (e.getActionCommand() == timerRead.getLabel()) { + timerRead(); + } + + if (e.getActionCommand() == timerWrite.getLabel()) { + timerWrite(); + } + + if (e.getActionCommand() == timerDelete.getLabel()) { + timerDelete(); + } + + + for (int i=0; i< NUMRELAIS; i++){ + if (e.getActionCommand() == relais[i].getLabel()) { + switchRelais(i); + } + } + } + + /* + * Displays the values of relaisValues + */ + private void showRelais(){ + for (int i=0; i< NUMRELAIS; i++){ + if ((relaisValues & (1< 0) + relais[i].setBackground(Color.yellow); + else + relais[i].setBackground(Color.gray); + relais[i].setEnabled(true); // buttons are allowed after 1st update + } + } + + /* + * Reads 64 AD-Samples from B-Module + */ + synchronized private void bReadSamples(){ + int[] data = new int[1]; + int[] dataAntwort = new int[64*7]; + int[] answer = new int[CMD_LENGTH]; + + data[0]=(int) Integer.valueOf("000000"+adcChannel.getText(), 16).intValue() ; + + if (useFilter.getState()) + data[0]+=0x80; // Wenn der Filter verwendet werden soll, dann Bit 7 setzen + + try { + transmitCommand(CMD_READADC_64,data,answer,dataAntwort); + } catch (IOException IOEx) { + append(statusFeld,"I/O error while reading Samples: " + IOEx); + } catch (Exception Ex) { + append(statusFeld,"Error while reading Samples: " + Ex); + } + + byte[] byteData= new byte[dataAntwort.length]; + for (int i=0; i 0){ // 50 Hz Filter an? + max= 11000; min= -max; + } else { + max= 1024; min= 0; + } + oszilloskop.setData(samples,min,max); + } + + + /* + * Reads the current State of the Relais + */ + synchronized private void bReadRelais(){ + int[] antwort = new int[CMD_LENGTH]; + + try{ + transmitCommand(CMD_READRELAIS,null,antwort); + } catch (IOException IOEx) { + append(statusFeld,"I/O error while Reading Relais: " + IOEx); + } catch (Exception Ex) { + append(statusFeld,"Error while Reading Relais: " + Ex); + } + + relaisValues =antwort[2]; + + showRelais(); + + } + + + /** + * Toggles one of the Relais + * @param i The Relais + */ + synchronized private void switchRelais(int channel) { + int[] data = { 0}; + int[] answer = new int[CMD_LENGTH]; + + + // First ask for State of Relais + try { + transmitCommand(CMD_READRELAIS,data,answer); + + data[0]=answer[2]; + + // alle anderen Relais lassen, wie sie waren + data[0] &= (~(1 << channel)); + + // den einen Kanal Invertieren und dann dazupacken + data[0] += (~relaisValues) & (1 << channel); + + transmitCommand(CMD_SETRELAIS,data,answer); + + relaisValues=answer[2]; + + } catch (IOException IOEx) { + append(statusFeld,"I/O error while switching Relais: " + IOEx); + } catch (Exception Ex) { + append(statusFeld,"Error while switching Relais: " + Ex); + } + + showRelais(); + + } + + + + /** + * Will lock the GUI's buttons during execution of a command to keep the + * user from doing stupid things. + */ + + private void LockButtons() { + setCPins.setEnabled(false); + getCPins.setEnabled(false); + + setCPinDir.setEnabled(false); + getCPinDir.setEnabled(false); +// getState.setEnabled(false); + return; + } + + /** After execution of a command, re-enables the GUI's buttons */ + private void UnlockButtons() { + setCPins.setEnabled(true); + getCPins.setEnabled(true); + + getCPinDir.setEnabled(true); + setCPinDir.setEnabled(true); +// getState.setEnabled(true); + return; + } + + /** + * Will determine which LEDs are to be set. Just a helper method for + * toggleLED(). + */ + private int LEDauswert() { + int activeLEDs = 0; + int bitv = 1; + for (int i = 0; i < NUMCPINS; i++) { + if (CPins[i].getState()) { + activeLEDs |= bitv; + } + bitv <<= 1; + } + return activeLEDs; + } + + /** + * Will determine which I/O directions are to be changed. Another helper + * method. + * + * @return + */ + private int IOauswert() { + int activePins = 0; + int bitv = 1; + for (int i = 0; i < NUMCPINS; i++) { + if (CPinDir[i].getState()) { + activePins |= bitv; + } + bitv <<= 1; + } + return activePins; + } + + private void transmitCommand(int command, int[] data) throws Exception{ + transmitCommand(command, data, null); + } + + private void transmitCommand(int command, int[] data, int[] answer) throws Exception{ + transmitCommand(command,data,answer,null); + } + + /* Transmit data and expects retour data before the regular answer of B-Module + * length of retour-data is spefified by retour.length + */ + private void transmitCommand(int command, int[] data, int[] answer, int[] retour) throws Exception{ + transmitCommand(command,data,answer,retour,null); + } + + /* Transmit data and expects retour data before the regular answer of B-Module + * length of retour-data is spefified by retour.length + * length of data to xport is specified by payload.length + */ + private void transmitCommand(int command, int[] data, int[] answer, int[] retour, int[] payload) throws Exception{ + int[] fullCommand = new int [CMD_LENGTH]; + int length; + + if (data!=null) + length=data.length; + else + length=0; + + // construct Command + fullCommand[0]= START_CODE; fullCommand[CMD_LENGTH-1]=STOP_CODE; + fullCommand[1]= command; + for (int i=2; i 0x20 && s[i] < 0x7e) // add readable chars + gelesen += new Character((char) s[i]).toString(); + // else // add non-readable chars as bytes in brackets + // gelesen += " (0x" + Integer.toHexString(s[i])+ ") "; + + } + } else // Show message as Hex + gelesen += " (0x" + Integer.toHexString(s[i])+ ") "; + } + return gelesen; + } + + + + public void run() { + int length=512; + int[] gelesen= new int[length]; + + try { // since we need to handle some possible exceptions, + + while (!isInterrupted()) { // run while needed + + + if (!pause){ + // check if data is available + + if (! XPort.DataReady()) { // wait while no data + sleep(10); + } else { + // receive data, + length=XPort.readBuffer(gelesen,length); + // display it + append(ausgabeFeld,parseString(gelesen,length)); + // clear the input field + eingabeFeld.setText(""); + } + } + + } + + } catch (InterruptedException iEx){ +// append(statusFeld,"Read-Loop, Interrupted: " + iEx); + } catch (Exception ex) { + append(statusFeld,"Error in Read-Loop, Dying: " + ex); + } + } + } + + + private class Oszilloskop extends Panel{ + + private int[] data= null; + private int min=0; + private int max=0; + private int maxAmplitude=0; + + public Dimension getMinimumSize(){ + return new Dimension(200,100); + } + + public void paint(Graphics g) { + Graphics2D g2 = (Graphics2D) g; + g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); + Dimension d = getSize(); + FontMetrics fontMetrics = g2.getFontMetrics(); + int gridWidth = d.width / 6; + int gridHeight = d.height / 2; + + int x,y; +// fontMetrics = pickFont(g2, "Filled and Stroked GeneralPath", + // gridWidth); + setBackground(Color.black); + + Color fg3D = Color.white; + + g2.setPaint(fg3D); + g2.drawRect(0, 0, d.width - 1, d.height - 1); + //g2.drawRect(3, 3, d.width - 7, d.height - 7); + + + if (data!= null){ + // factor zum Skalieren + float yscale= (float)(d.height-2)/ (float)maxAmplitude; + int offset= (int)(-(min *yscale)+2); + + float xscale= (float)d.width/(float)data.length; + + // Beschriftung und Achsen + g2.setPaint(Color.yellow); + + String label = new Integer(min).toString(); + g2.drawString(label, d.width-fontMetrics.stringWidth(label), d.height-2 ); + + label=new Integer(max).toString(); + g2.drawString(label, d.width-fontMetrics.stringWidth(label),fontMetrics.getHeight()); + + if (min <0){ + y=d.height-offset; + label = "0"; + g2.drawString(label, d.width-fontMetrics.stringWidth(label), y +fontMetrics.getHeight()/2); + + g2.draw(new Line2D.Double(1, y,d.width-2-fontMetrics.stringWidth("0"),y)); + } + // Horizontal Line all 8 samples + for (int i=8; i<64; i+=8){ + g2.draw(new Line2D.Double(i*xscale, 1,i*xscale,d.height-2)); + } + + x=0; + y=d.height-((int)(data[0]*yscale)+offset); + int oldx,oldy; + + + // Daten + g2.setPaint(Color.green); + for (int i=1; i< data.length-1; i++){ + oldx=x; oldy=y; + x=(int)(i*xscale); y=d.height-((int)(data[i]*yscale)+offset); + g2.draw(new Line2D.Double(oldx, oldy,x,y)); + } + + } + g2.setPaint(Color.black); + + } + /** + * @param data The data to set. + */ + public void setData(int[] data,int min, int max) { + this.data = new int[data.length]; + this.min=min; + this.max=max; + + for (int i=0; i this.data[i]) min=this.data[i]; +// if (max< this.data[i]) max=this.data[i]; + } + maxAmplitude=max-min; + + repaint(); + } + } + + /* (non-Javadoc) + * @see java.awt.event.ItemListener#itemStateChanged(java.awt.event.ItemEvent) + */ + public void itemStateChanged(ItemEvent event) { + if (timerHourDontCare.getState()== true) timerHour.setEditable(true); + else timerHour.setEditable(false); + + if (timerMinuteDontCare.getState()== true) timerMinute.setEditable(true); + else timerMinute.setEditable(false); + + if (timerSecondDontCare.getState()== true) timerSecond.setEditable(true); + else timerSecond.setEditable(false); + + if (timerDayDontCare.getState()== true) timerDay.setEditable(true); + else timerDay.setEditable(false); + + if (timerMonthDontCare.getState()== true) timerMonth.setEditable(true); + else timerMonth.setEditable(false); + + if (timerYearDontCare.getState()== true) timerYear.setEditable(true); + else timerYear.setEditable(false); + + if (timerWeekdayDontCare.getState()== true) timerWeekday.setEditable(true); + else timerWeekday.setEditable(false); + } + +} + + + diff --git a/projekte/netzschalter/src/IOControl.java b/projekte/netzschalter/src/IOControl.java new file mode 100644 index 0000000..0f2fba2 --- /dev/null +++ b/projekte/netzschalter/src/IOControl.java @@ -0,0 +1,294 @@ +/* + * File IOControl.java + */ + +import java.io.IOException; + +/** + * @author olz + * + * TODO To change the template for this generated type comment go to Window - + * Preferences - Java - Code Generation - Code and Comments + */ +/** + * This class will be responsible for all sorts of I/O and LED controls. + * + * @author olz + * + * TODO To change the template for this generated type comment go to Window - + * Preferences - Java - Code Generation - Code and Comments + */ +public class IOControl { + + /** + * this static byte contains a value to select all the XPort's LEDs( decimal + * 7 = bin 00000111; Bits 0 to 2 are set + */ + private static final byte maxLEDLo = (byte) 0xFF; // new for WiPort, really + // 7; + + private static final byte maxLEDHi = 0x07; // noch! :) 7; + + /** + * this static int states the port on which the XPort's I/O settings are + * changed + */ + private static final int IOPort = 0x77f0; + + /** this static int states the length of an XPort's answer in bytes */ + private static final int cmdLength = 5; // was 9 = Wrong! --plymo-- 26.12.2004 + + // XPort Commands fixed as bytes + /** this static byte is set to the value of GetFunction + * Checks which Pins are availbale to user and not used for RTS and Co. + * */ + private static final byte cmdGetFunc = 0x10; + + /** this static byte is set to the value of GetDirections */ + private static final byte cmdGetDir = 0x11; + + /** this static byte is set to the value of Get Active Levels */ + private static final byte cmdGetActLvl = 0x12; + + /** this static byte is set to the value of Get Current State */ + private static final byte cmdGetCurrState = 0x13; + + /** this static byte is set to the value of Set Direction */ + private static final byte cmdSetDir = 0x19; + + /** this static byte is set to the value of Set Active Level */ + private static final byte cmdsetActLvl = 0x1a; + + /** this static byte is set to the value of Set Current State */ + private static final byte cmdSetCurrState = 0x1b; + + /** initialisation of variable antwort, which will return the XPort's antwort */ + byte[] antwort = { 0, 0, 0, 0, 0 }; + + /** + * initialisation of variable antwort_null, which be used to reset antwort. + * In case of errors, antwort will remain 0,0,0,0,0 so that error handling + * is possible + */ + byte[] antwort_null = { 0, 0, 0, 0, 0 }; + + /** this instance will control the XPort for this class */ + private Communication XPort1; + + /** + * this method will read out and return the current states of the I/O pins + * + * @param ipa + * @return + * @throws IOException + * @throws Exception + */ + public byte[] getActiveLevel(String ipa) throws IOException, Exception { + + int[] command = { cmdGetActLvl, 0, 0, 0, 0, // no parameters needed + 0, 0, 0, 0 }; + antwort = antwort_null; + try { + antwort = sendCommand(ipa, IOPort, command, cmdLength); + } catch (IOException IOEx) { + throw IOEx; + } catch (Exception Ex) { + throw Ex; + } + return antwort; + } + + /** + * this method will switch the I/O pins' directions according to the + * parameter + * + * @param ipa + * @param NumLed + * @return + * @throws IOException + * @throws Exception + */ + public byte[] toggleDirection(String ipa, int NumLed) throws IOException, + Exception { + + int[] command = { cmdSetDir, maxLEDLo, maxLEDHi, 0, 0, + (byte) (NumLed & maxLEDLo), (byte) ((NumLed >> 8) & maxLEDHi), 0, 0 }; + + antwort = antwort_null; + try { + antwort = sendCommand(ipa, IOPort, command, cmdLength); + } catch (IOException IOEx) { + throw IOEx; + } catch (Exception Ex) { + throw Ex; + } + return antwort; + } + + /** + * will read out and return the I/O pins' current states + * + * @param ipa + * @return + * @throws IOException + * @throws Exception + */ + public byte[] getCurrentState(String ipa) throws IOException, Exception { + int[] command = { cmdGetCurrState, 0, 0, 0, 0, // no parameters needed + 0, 0, 0, 0 }; + antwort = antwort_null; + try { + antwort = sendCommand(ipa, IOPort, command, cmdLength); + } catch (IOException IOEx) { + throw IOEx; + } catch (Exception Ex) { + throw Ex; + } + return antwort; + + } + + /** + * will establish a connection according to the parameters ipa and port + * + * @param ipa + * @param port + * @throws IOException + * @throws Exception + */ + public void connectLED(String ipa, int port) throws IOException, Exception { + XPort1 = new Communication(); // preparing a new connection + try { + XPort1.connect(ipa, port); + // connecting to new XPort instance on LED switching port + } catch (IOException IOEx) { + throw IOEx; + } catch (Exception Ex) { + throw Ex; + } + } + + /** + * will toggle LEDs on and off acccording to its parameter's value + * + * @param ipa - IPAddress + * @param NumLed - Bit-Coded which LED to turn ON or OFF + * @return - antwort array ob 5 bytes + * @throws IOException + * @throws Exception + */ + public byte[] toggle(String ipa, int NumLed) throws IOException, Exception { + + byte ValueLedLo = 0; + byte ValueLedHi = 0; + ValueLedLo = (byte) NumLed; + ValueLedHi = (byte) (NumLed >> 8); + System.out.println("Toggle Anfang"); + int[] command = { cmdSetCurrState, maxLEDLo, maxLEDHi, 0, 0, // maxLED + // sets + // all + // LEDs + // ready + // for + // change + ValueLedLo, ValueLedHi, 0, 0 }; // toggles the LEDs on / off + // according to the value + antwort = antwort_null; + try { + antwort = sendCommand(ipa, IOPort, command, cmdLength); + } catch (IOException IOEx) { + throw IOEx; + } catch (Exception Ex) { + throw Ex; + } + return antwort; + } + + /** + * will connect to the XPort located at the IP ipa and the port port, then + * send a command as given in command[], end the connection and return the + * answer + * + * @param ipa + * @param port + * @param command + * @param length + * @return + * @throws IOException + * @throws Exception + */ + public byte[] sendCommand(String ipa, int port, int[] command, int length) + throws IOException, Exception { + connectLED(ipa, port); + try { + XPort1.send(command); + } catch (IOException IOEx) { + throw IOEx; + } catch (Exception Ex) { + throw Ex; + } + try { + antwort = (XPort1.receiveByteArray(length)); + } catch (IOException IOEx) { + throw IOEx; + } catch (Exception Ex) { + throw Ex; + } + try { + XPort1.disconnect(); + } catch (IOException IOEx) { + throw IOEx; + } catch (Exception Ex) { + throw Ex; + } + + return antwort; + } + + /** + * will receive the number of I/O pins available on the XPort + * + * @param ipa + * @return + * @throws IOException + * @throws Exception + */ + public byte[] getFunc(String ipa) throws IOException, Exception { + + int[] command = { cmdGetFunc, 0, 0, 0, 0, // no paramters needed + 0, 0, 0, 0 }; + antwort = antwort_null; + try { + antwort = sendCommand(ipa, IOPort, command, cmdLength); + } catch (IOException IOEx) { + throw IOEx; + } catch (Exception Ex) { + throw Ex; + } + return antwort; + + } + + /** + * reads the I/O pins' directions from the XPort and returns them + * + * @param ipa + * @return + * @throws IOException + * @throws Exception + */ + public byte[] getDir(String ipa) throws IOException, Exception { + + //System.out.println("ToggleOn Anfang"); + int[] command = { cmdGetDir, 0, 0, 0, 0, 0, 0, 0, 0 }; + antwort = antwort_null; + try { + antwort = sendCommand(ipa, IOPort, command, cmdLength); + } catch (IOException IOEx) { + throw IOEx; + } catch (Exception Ex) { + throw Ex; + } + return antwort; + } +} diff --git a/projekte/netzschalter/src/TimerEvent.java b/projekte/netzschalter/src/TimerEvent.java new file mode 100644 index 0000000..565359a --- /dev/null +++ b/projekte/netzschalter/src/TimerEvent.java @@ -0,0 +1,225 @@ +/* + * Created on 04.10.2005 + * + * TODO To change the template for this generated file go to + * Window - Preferences - Java - Code Style - Code Templates + */ + +/** + * @author bbe + * + * Container for an Event + */ + +public class TimerEvent { + + private int special; // Special Event oder nicht? + private int channel; // Maske für die betroffenen Kanäle + private int data; // Werte für die betroffenen Kanäle + + private int second; // Zeitpunkt des Ereignisses + private int minute; // wird ein Feld nicht benutzt, steht es + private int hour; // auf DONTCARE + private int day; + private int month; + private int year; // Achtung das Jahr 255 bedeutet DONTCARE + private int weekday; + + public static int DONTCARE = 255; + public static int SIZE = 10; + + /** + * + */ + public TimerEvent() { + super(); + } + /* Create an Event from serial Data */ + public TimerEvent(int[] newData){ + super(); + timerFromSerial(newData); + } + + /* Initializes an event from a serial data Stream */ + public void timerFromSerial(int[] newData){ + int i=0; + + second= newData[i++]; + minute= newData[i++]; + hour= newData[i++]; + day= newData[i++]; + month= newData[i++]; + year= newData[i++] + newData[i++]*256; + weekday=newData[i++]; + + special= (newData[i]>>7) & 1; + channel= newData[i++] & 0x7F; + data= newData[i++]; + + } + + public String toString(){ + String str = ""; + + if (day==DONTCARE) str+="XX."; else str+=day+"."; + if (month==DONTCARE) str+="XX."; else str+=month+"."; + if (year==DONTCARE) str+="XXXX "; else str+=year+" "; + + str+=weekday+" "; + + if (hour==DONTCARE) str+="XX:"; else str+=day+":"; + if (minute==DONTCARE) str+="XX:"; else str+=minute+":"; + if (second==DONTCARE) str+="XXXX "; else str+=second+" "; + + str+="Type: "+special+" Ch: "+channel+" Value: "+data; + return str; + } + + public int[] getSerial(){ + int[] serial = new int[SIZE]; + + int i=0; + + serial[i++]= second; // Zeitpunkt des Ereignisses + serial[i++]= minute; // wird ein Feld nicht benutzt, steht es + serial[i++]= hour; // auf DONTCARE + serial[i++]= day; + serial[i++]= month; + serial[i++]= year & 0xFF; // Achtung das Jahr 255 bedeutet DONTCARE + serial[i++]= (year /256) &0xFF; // Achtung das Jahr 255 bedeutet DONTCARE + + serial[i++]=weekday; + + serial[i++]= (channel & 0x7F) | ((special << 7) & 0x80); // Maske für die betroffenen Kanäle + serial[i++]= data; // Werte für die betroffenen Kanäle + + + return serial; + } + /** + * @return Returns the channel. + */ + public int getChannel() { + return channel; + } + /** + * @param channel The channel to set. + */ + public void setChannel(int channel) { + this.channel = channel; + } + /** + * @return Returns the data. + */ + public int getData() { + return data; + } + /** + * @param data The data to set. + */ + public void setData(int data) { + this.data = data; + } + /** + * @return Returns the day. + */ + public int getDay() { + return day; + } + /** + * @param day The day to set. + */ + public void setDay(int day) { + this.day = day; + } + /** + * @return Returns the hour. + */ + public int getHour() { + return hour; + } + /** + * @param hour The hour to set. + */ + public void setHour(int hour) { + this.hour = hour; + } + /** + * @return Returns the minute. + */ + public int getMinute() { + return minute; + } + /** + * @param minute The minute to set. + */ + public void setMinute(int minute) { + this.minute = minute; + } + /** + * @return Returns the month. + */ + public int getMonth() { + return month; + } + /** + * @param month The month to set. + */ + public void setMonth(int month) { + this.month = month; + } + /** + * @return Returns the second. + */ + public int getSecond() { + return second; + } + /** + * @param second The second to set. + */ + public void setSecond(int second) { + this.second = second; + } + /** + * @return Returns the year. + */ + public int getYear() { + return year; + } + /** + * @param year The year to set. + */ + public void setYear(int year) { + this.year = year; + } + /** + * @return Returns the weekday. + */ + public int getWeekday() { + return weekday; + } + /** + * @param weekday The weekday to set. + */ + public void setWeekday(int weekday) { + this.weekday = weekday; + } + /** + * @return Returns the special. + */ + public boolean getSpecial() { + if (special==0) + return false; + else + return true; + } + /** + * @param special The special to set. + */ + public void setSpecial(boolean special) { + if (special==true) + this.special = 1; + else + this.special = 0; + } +} -- 2.11.0