CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/maven-com-panamahitek--panama-hitek-arduino

Java library for serial communication between Java applications and Arduino boards with data visualization and export capabilities

Overview
Eval results
Files

data-management.mddocs/

Data Management

The PanamaHitek_DataBuffer class provides comprehensive data organization, table visualization, and export functionality. It handles structured data storage with type safety, Excel export capabilities, and Swing GUI integration for data display.

PanamaHitek_DataBuffer Class

public class PanamaHitek_DataBuffer {
    public PanamaHitek_DataBuffer();
}

Creates an empty data buffer for storing and organizing data.

Column Management

Add Data Column

public void addColumn(int index, String variableName, Object dataType);

Adds a new data column with a specified data type at the given index.

Parameters:

  • index - Column position (zero-based)
  • variableName - Name of the column
  • dataType - Data type class (e.g., String.class, Integer.class, Double.class)

Add Time Column

public void addTimeColumn(int index, String variableName);

Adds a timestamp column that automatically captures current date/time when data is added.

Parameters:

  • index - Column position
  • variableName - Name of the time column

Date Format Configuration

public void setDateFormat(String format);
public void setDateFormat(SimpleDateFormat format);

Configures the date format for timestamp columns.

Parameters:

  • format - Date format string (e.g., "yyyy-MM-dd HH:mm:ss") or SimpleDateFormat object

Data Manipulation

Add Data Values

public void addValue(int column, Object value) throws Exception;

Adds a value to the specified column in the current row.

Parameters:

  • column - Column index
  • value - Value to add (must match column data type)

Throws:

  • Exception - If value type doesn't match column type or column doesn't exist

Complete Row Entry

public void printRow();

Finishes the current row and prepares for the next row entry.

Clear Data

public void clearBuffer();

Removes all data from the buffer, keeping column structure intact.

Data Access

Buffer Information

public int getRowCount();
public int getColumnCount();
public List<Object> getClassList();
public List<String> getVariableList();
public List<List<Object>> getMainBuffer();
public int getTimeColumn();

Methods for accessing buffer metadata and structure.

Sheet Configuration

public String getSheetName();
public void setSheetName(String sheetName);

Configure Excel sheet name for export operations.

Export Functionality

Excel Export

public void exportExcelFile() throws FileNotFoundException, IOException;
public void exportExcelFile(String path);

Export buffer data to Excel format. The first method shows a file dialog, while the second exports to a specific path.

Parameters:

  • path - Full file path for Excel export

Throws:

  • FileNotFoundException - If the export path is invalid
  • IOException - If file writing fails

GUI Integration

Table Display

public void insertToPanel(JPanel panel);
public JTable getTable();
public JScrollPane getScrollPane();

Methods for integrating the data buffer into Swing GUIs.

Table Operations

public void sortColumn(int column, boolean ascending);

Sorts the data table by the specified column.

Parameters:

  • column - Column index to sort by
  • ascending - true for ascending, false for descending order

Event Handling

Data Insertion Events

public void addEventListener(DataInsertionListener listener);
public void removeEventListener();

Add or remove event listeners for data insertion notifications.

Usage Examples

Basic Data Buffer Setup

import com.panamahitek.PanamaHitek_DataBuffer;
import java.text.SimpleDateFormat;

public class BasicDataBufferExample {

    public void setupDataBuffer() {
        PanamaHitek_DataBuffer buffer = new PanamaHitek_DataBuffer();

        // Configure sheet name
        buffer.setSheetName("Sensor_Data");

        // Set date format for timestamps
        buffer.setDateFormat("yyyy-MM-dd HH:mm:ss");

        try {
            // Add columns
            buffer.addTimeColumn(0, "Timestamp");
            buffer.addColumn(1, "Temperature", Double.class);
            buffer.addColumn(2, "Humidity", Double.class);
            buffer.addColumn(3, "SensorID", String.class);

            // Add some data rows
            buffer.addValue(1, 23.5);
            buffer.addValue(2, 65.2);
            buffer.addValue(3, "DHT22_01");
            buffer.printRow(); // Complete first row

            buffer.addValue(1, 24.1);
            buffer.addValue(2, 63.8);
            buffer.addValue(3, "DHT22_01");
            buffer.printRow(); // Complete second row

            System.out.println("Rows: " + buffer.getRowCount());
            System.out.println("Columns: " + buffer.getColumnCount());

        } catch (Exception ex) {
            System.err.println("Data buffer error: " + ex.getMessage());
        }
    }
}

Arduino Data Logging

import com.panamahitek.PanamaHitek_Arduino;
import com.panamahitek.PanamaHitek_DataBuffer;
import com.panamahitek.ArduinoException;
import jssc.*;

public class ArduinoDataLogger {

    private PanamaHitek_Arduino arduino;
    private PanamaHitek_DataBuffer dataLogger;

    public void setupLogging() throws ArduinoException {
        arduino = new PanamaHitek_Arduino();
        dataLogger = new PanamaHitek_DataBuffer();

        // Setup data buffer structure
        dataLogger.setSheetName("Arduino_Sensor_Log");
        dataLogger.setDateFormat("yyyy-MM-dd HH:mm:ss.SSS");

        try {
            // Define logging columns
            dataLogger.addTimeColumn(0, "Timestamp");
            dataLogger.addColumn(1, "Temperature", Double.class);
            dataLogger.addColumn(2, "Light_Level", Integer.class);
            dataLogger.addColumn(3, "Motion_Detected", Boolean.class);
            dataLogger.addColumn(4, "Battery_Voltage", Double.class);

        } catch (Exception ex) {
            System.err.println("Logger setup error: " + ex.getMessage());
        }

        // Setup Arduino connection
        arduino.arduinoRX("COM3", 9600, new SerialPortEventListener() {
            @Override
            public void serialEvent(SerialPortEvent event) {
                if (event.isRXCHAR()) {
                    processArduinoData();
                }
            }
        });
    }

    private void processArduinoData() {
        try {
            if (arduino.isMessageAvailable()) {
                String data = arduino.printMessage();
                parseAndLogData(data);
            }
        } catch (SerialPortException | ArduinoException ex) {
            System.err.println("Data processing error: " + ex.getMessage());
        }
    }

    private void parseAndLogData(String rawData) {
        try {
            // Expected format: "TEMP:25.3,LIGHT:1023,MOTION:1,BATTERY:3.7"
            String[] parts = rawData.split(",");

            for (String part : parts) {
                String[] keyValue = part.split(":");
                String key = keyValue[0].trim();
                String value = keyValue[1].trim();

                switch (key) {
                    case "TEMP":
                        dataLogger.addValue(1, Double.parseDouble(value));
                        break;
                    case "LIGHT":
                        dataLogger.addValue(2, Integer.parseInt(value));
                        break;
                    case "MOTION":
                        dataLogger.addValue(3, value.equals("1"));
                        break;
                    case "BATTERY":
                        dataLogger.addValue(4, Double.parseDouble(value));
                        break;
                }
            }

            // Complete the row
            dataLogger.printRow();

            // Auto-export every 100 rows
            if (dataLogger.getRowCount() % 100 == 0) {
                autoExportData();
            }

        } catch (Exception ex) {
            System.err.println("Data parsing error: " + ex.getMessage());
        }
    }

    private void autoExportData() {
        try {
            String filename = "arduino_log_" + System.currentTimeMillis() + ".xlsx";
            dataLogger.exportExcelFile(filename);
            System.out.println("Auto-exported to: " + filename);
        } catch (Exception ex) {
            System.err.println("Auto-export error: " + ex.getMessage());
        }
    }

    public void exportLogData() {
        try {
            dataLogger.exportExcelFile(); // Shows file dialog
        } catch (Exception ex) {
            System.err.println("Export error: " + ex.getMessage());
        }
    }
}

GUI Integration with Event Handling

import com.panamahitek.events.*;
import javax.swing.*;
import java.awt.*;

public class DataBufferGUIExample extends JFrame {

    private PanamaHitek_DataBuffer buffer;
    private JLabel statusLabel;

    public DataBufferGUIExample() {
        setupGUI();
        setupDataBuffer();
    }

    private void setupGUI() {
        setTitle("Data Buffer Display");
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setLayout(new BorderLayout());

        // Status label
        statusLabel = new JLabel("Rows: 0");
        add(statusLabel, BorderLayout.NORTH);

        // Export button
        JButton exportButton = new JButton("Export to Excel");
        exportButton.addActionListener(e -> exportData());
        add(exportButton, BorderLayout.SOUTH);

        setSize(600, 400);
        setLocationRelativeTo(null);
    }

    private void setupDataBuffer() {
        buffer = new PanamaHitek_DataBuffer();

        try {
            // Setup columns
            buffer.addTimeColumn(0, "Time");
            buffer.addColumn(1, "Value1", Double.class);
            buffer.addColumn(2, "Value2", Integer.class);
            buffer.addColumn(3, "Description", String.class);

            // Add event listener for data changes
            buffer.addEventListener(new DataInsertionListener() {
                @Override
                public void onDataInsertion(DataInsertionEvent ev) {
                    SwingUtilities.invokeLater(() -> {
                        statusLabel.setText("Rows: " + buffer.getRowCount());
                    });
                }
            });

            // Insert table into GUI
            JPanel centerPanel = new JPanel(new BorderLayout());
            buffer.insertToPanel(centerPanel);
            add(centerPanel, BorderLayout.CENTER);

            // Add some sample data
            addSampleData();

        } catch (Exception ex) {
            JOptionPane.showMessageDialog(this, "Setup error: " + ex.getMessage());
        }
    }

    private void addSampleData() {
        try {
            for (int i = 0; i < 10; i++) {
                buffer.addValue(1, Math.random() * 100);
                buffer.addValue(2, (int) (Math.random() * 1000));
                buffer.addValue(3, "Sample " + (i + 1));
                buffer.printRow();
            }
        } catch (Exception ex) {
            JOptionPane.showMessageDialog(this, "Data error: " + ex.getMessage());
        }
    }

    private void exportData() {
        try {
            buffer.exportExcelFile();
            JOptionPane.showMessageDialog(this, "Data exported successfully!");
        } catch (Exception ex) {
            JOptionPane.showMessageDialog(this, "Export error: " + ex.getMessage());
        }
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> {
            new DataBufferGUIExample().setVisible(true);
        });
    }
}

Advanced Data Processing

import java.util.List;

public class AdvancedDataProcessor {

    private PanamaHitek_DataBuffer buffer;

    public void performAdvancedOperations() {
        buffer = new PanamaHitek_DataBuffer();

        try {
            // Setup complex data structure
            buffer.addTimeColumn(0, "Timestamp");
            buffer.addColumn(1, "Sensor1", Double.class);
            buffer.addColumn(2, "Sensor2", Double.class);
            buffer.addColumn(3, "Calculated", Double.class);
            buffer.addColumn(4, "Status", String.class);

            // Add data with calculations
            for (int i = 0; i < 50; i++) {
                double sensor1 = Math.random() * 100;
                double sensor2 = Math.random() * 50;
                double calculated = (sensor1 + sensor2) / 2;
                String status = calculated > 50 ? "HIGH" : "LOW";

                buffer.addValue(1, sensor1);
                buffer.addValue(2, sensor2);
                buffer.addValue(3, calculated);
                buffer.addValue(4, status);
                buffer.printRow();
            }

            // Access raw data for analysis
            List<List<Object>> rawData = buffer.getMainBuffer();
            System.out.println("Total data points: " + rawData.size());

            // Get column information
            List<String> columnNames = buffer.getVariableList();
            List<Object> columnTypes = buffer.getClassList();

            System.out.println("Column structure:");
            for (int i = 0; i < columnNames.size(); i++) {
                System.out.println(columnNames.get(i) + " (" +
                    columnTypes.get(i).toString() + ")");
            }

            // Sort by calculated values (descending)
            buffer.sortColumn(3, false);

            // Export with custom sheet name
            buffer.setSheetName("Advanced_Analysis_" + System.currentTimeMillis());
            buffer.exportExcelFile("advanced_data_analysis.xlsx");

        } catch (Exception ex) {
            System.err.println("Advanced processing error: " + ex.getMessage());
        }
    }
}

Event System

DataInsertionEvent

public class DataInsertionEvent {
    public DataInsertionEvent(Object source, PanamaHitek_DataBuffer buffer);
    public PanamaHitek_DataBuffer getBuffer();
}

DataInsertionListener Interface

public interface DataInsertionListener {
    void onDataInsertion(DataInsertionEvent ev);
}

Best Practices

  1. Define column structure first before adding any data
  2. Use appropriate data types for columns to ensure type safety
  3. Handle exceptions properly when adding values or exporting
  4. Call printRow() after adding all values for a complete row
  5. Configure date formats before adding timestamp data
  6. Use event listeners for real-time GUI updates
  7. Sort data before exporting for better organization
  8. Clean up resources by removing event listeners when done

Install with Tessl CLI

npx tessl i tessl/maven-com-panamahitek--panama-hitek-arduino

docs

data-management.md

exception-handling.md

index.md

multi-message.md

serial-communication.md

visualization.md

tile.json