Java tutorial
package LoggerGUI; /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ /** * * @author carl */ import java.awt.BorderLayout; import java.awt.Color; import java.awt.FlowLayout; import javax.swing.JFrame; import javax.swing.BorderFactory; import javax.swing.JPanel; import org.jfree.chart.ChartPanel; import org.jfree.chart.JFreeChart; import org.jfree.chart.axis.DateAxis; import org.jfree.chart.axis.NumberAxis; import org.jfree.chart.axis.ValueAxis; import org.jfree.chart.plot.CombinedDomainXYPlot; import org.jfree.chart.plot.XYPlot; import org.jfree.chart.renderer.xy.XYLineAndShapeRenderer; import org.jfree.data.time.Millisecond; import org.jfree.data.time.TimeSeries; import org.jfree.data.time.TimeSeriesCollection; import org.jfree.ui.ApplicationFrame; import org.jfree.ui.RefineryUtilities; import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.OutputStream; import gnu.io.CommPortIdentifier; import gnu.io.SerialPort; import gnu.io.SerialPortEvent; import gnu.io.SerialPortEventListener; import java.util.Enumeration; import java.io.*; import org.jfree.chart.plot.PlotOrientation; public class DataLogger extends JFrame implements SerialPortEventListener { DataLogger(String title) { this(title); } /** * The number of subplots. */ public static final int INPUT_COUNT = 4; /** * The datasets. */ private TimeSeriesCollection[] datasets; /** * The most recent value added to series 1. */ private static double[] lastValue = new double[INPUT_COUNT]; } SerialPort serialPort; /** * The port we're normally going to use. */ private static final String PORT_NAMES[] = { // "/dev/tty.usbserial-A9007UX1", // Mac OS X // "/dev/ttyUSB0", // Linux "COM13" // Windows }; /** * A BufferedReader which will be fed by a InputStreamReader converting the * bytes into characters making the displayed results codepage independent */ private BufferedReader input; /** * The output stream to the port */ private OutputStream output; /** * Milliseconds to block while waiting for port open */ private static final int TIME_OUT = 2000; /** * Default bits per second for COM port. */ private static final int DATA_RATE = 9600; private static int point_count = 0; public static int getPointCount() { return point_count; } public DataLogger(String title) { super(title); initialize(); final CombinedDomainXYPlot plot = new CombinedDomainXYPlot(new DateAxis("Time")); this.datasets = new TimeSeriesCollection[INPUT_COUNT]; this.lastValue[0] = 100.0; this.lastValue[1] = 100.0; this.lastValue[2] = 100.0; this.lastValue[3] = 100.0; final TimeSeries s0 = new TimeSeries("A0", Millisecond.class); final TimeSeries s1 = new TimeSeries("A1", Millisecond.class); final TimeSeries s2 = new TimeSeries("A2", Millisecond.class); final TimeSeries s3 = new TimeSeries("A3", Millisecond.class); this.datasets[0] = new TimeSeriesCollection(s0); this.datasets[1] = new TimeSeriesCollection(s1); this.datasets[2] = new TimeSeriesCollection(s2); this.datasets[3] = new TimeSeriesCollection(s3); final NumberAxis rangeAxis = new NumberAxis("ADC Signal"); rangeAxis.setAutoRangeIncludesZero(false); XYPlot subplot; XYLineAndShapeRenderer renderer = new XYLineAndShapeRenderer(true,false); XYLineAndShapeRenderer renderer1 = new XYLineAndShapeRenderer(true,false); XYLineAndShapeRenderer renderer2 = new XYLineAndShapeRenderer(true,false); XYLineAndShapeRenderer renderer3 = new XYLineAndShapeRenderer(true,false); subplot= new XYPlot( new TimeSeriesCollection(), null, rangeAxis, new XYLineAndShapeRenderer(true,false) ); plot.add(subplot); renderer.setBaseShapesVisible(false); renderer.setSeriesPaint(0, Color.red); subplot.setDataset(0,datasets[0]); subplot.setRenderer(0,renderer); renderer1.setBaseShapesVisible(false); renderer1.setSeriesPaint(0, Color.blue); subplot.setDataset(1,datasets[1]); subplot.setRenderer(1,renderer1); renderer2.setBaseShapesVisible(false); renderer2.setSeriesPaint(0, Color.black); subplot.setDataset(2,datasets[2]); subplot.setRenderer(2,renderer2); subplot.getRendererForDataset(subplot.getDataset(0)).setSeriesPaint(0, Color.red); subplot.getRendererForDataset(subplot.getDataset(1)).setSeriesPaint(1, Color.blue); subplot.getRendererForDataset(subplot.getDataset(2)).setSeriesPaint(2, Color.black); renderer3.setBaseShapesVisible(false); renderer3.setSeriesPaint(0, Color.green); subplot.setDataset(3,datasets[3]); subplot.setRenderer(3,renderer3); final JFreeChart chart = new JFreeChart("Data Logger", plot); chart.setBorderPaint(Color.black); chart.setBorderVisible(true); chart.setBackgroundPaint(Color.white); plot.setBackgroundPaint(Color.lightGray); plot.setDomainGridlinePaint(Color.white); plot.setRangeGridlinePaint(Color.white); final ValueAxis axis = plot.getDomainAxis(); axis.setAutoRange(true); axis.setFixedAutoRange(20000.0); // 60 seconds final JPanel content = new JPanel(new BorderLayout()); final ChartPanel chartPanel = new ChartPanel(chart); content.add(chartPanel); final JPanel buttonPanel = new JPanel(new FlowLayout()); content.add(buttonPanel, BorderLayout.NORTH); chartPanel.setPreferredSize(new java.awt.Dimension(600, 600)); chartPanel.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5)); setContentPane(content); } public void initialize() { CommPortIdentifier portId = null; Enumeration portEnum = CommPortIdentifier.getPortIdentifiers(); //First, Find an instance of serial port as set in PORT_NAMES. while (portEnum.hasMoreElements()) { CommPortIdentifier currPortId = (CommPortIdentifier) portEnum.nextElement(); for (String portName : PORT_NAMES) { if (currPortId.getName().equals(portName)) { portId = currPortId; break; } } } if (portId == null) { System.out.println("Could not find COM port."); return; } try { // open serial port, and use class name for the appName. serialPort = (SerialPort) portId.open(this.getClass().getName(), TIME_OUT); // set port parameters serialPort.setSerialPortParams(DATA_RATE, SerialPort.DATABITS_8, SerialPort.STOPBITS_1, SerialPort.PARITY_NONE); // open the streams input = new BufferedReader(new InputStreamReader(serialPort.getInputStream())); output = serialPort.getOutputStream(); // add event listeners serialPort.addEventListener(this); serialPort.notifyOnDataAvailable(true); } catch (Exception e) { System.err.println("Excepction initilize=" + e.toString()); } } /** * This should be called when you stop using the port. This will prevent * port locking on platforms like Linux. */ public synchronized void close() { if (serialPort != null) { serialPort.removeEventListener(); serialPort.close(); } } /** * Handle an event on the serial port. Read the data and print it. */ @Override public synchronized void serialEvent(SerialPortEvent oEvent) { if (oEvent.getEventType() == SerialPortEvent.DATA_AVAILABLE) { try { String inputLine = input.readLine(); String[] inputLine_string_array = inputLine.split("\t"); //System.out.println(inputLine_string_array.length); while(inputLine_string_array.length!= 4) { inputLine = input.readLine(); inputLine_string_array = inputLine.split("\t"); System.out.println(inputLine_string_array.length); } this.lastValue[0] = new Double(inputLine_string_array[0]).doubleValue(); this.lastValue[1] = new Double(inputLine_string_array[1]).doubleValue(); this.lastValue[2] = new Double(inputLine_string_array[2]).doubleValue(); this.lastValue[3] = new Double(inputLine_string_array[3]).doubleValue(); this.datasets[0].getSeries(0).add(new Millisecond(), this.lastValue[0]); this.datasets[1].getSeries(0).add(new Millisecond(), this.lastValue[1]); this.datasets[2].getSeries(0).add(new Millisecond(), this.lastValue[2]); this.datasets[3].getSeries(0).add(new Millisecond(), this.lastValue[3]); System.out.print(lastValue[0]); System.out.print(":"); System.out.print(lastValue[1]); System.out.print(":"); System.out.print(lastValue[2]); System.out.print(":"); System.out.println(lastValue[3]); try (PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("myfile.txt", true)))) { out.print(lastValue[0]); out.print("\t"); out.print(lastValue[1]); out.print("\t"); out.print(lastValue[2]); out.print("\t"); out.println(lastValue[3]); point_count = point_count + 1; System.out.println("Point Count = "+point_count); if (point_count == 100) { //close(); } } catch (IOException e) { //exception handling left as an exercise for the reader } } catch (Exception e) { System.err.println("Excep serialEvent=" + e.toString()); } } // Ignore all the other eventTypes, but you should consider the other ones. } /* public static void main(String[] args) throws Exception { final DataLogger demo = new DataLogger("Data Logger"); demo.pack(); RefineryUtilities.centerFrameOnScreen(demo); demo.setVisible(true); } */ }