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

multi-message.mddocs/

Multi-Message Processing

The PanamaHitek_MultiMessage class is designed for reading multiple data inputs from Arduino simultaneously. It allows receiving multiple data readings from different sensors without implementing complex logical sequences to distinguish between them.

PanamaHitek_MultiMessage Class

public class PanamaHitek_MultiMessage {
    public PanamaHitek_MultiMessage(int inputMessages, PanamaHitek_Arduino arduinoObject);
}

Creates a multi-message handler for processing a specified number of messages from Arduino.

Parameters:

  • inputMessages - Number of expected messages to process simultaneously
  • arduinoObject - An already configured PanamaHitek_Arduino instance

Data Reception Methods

Check Reception Completion

public boolean dataReceptionCompleted() throws ArduinoException, SerialPortException;

Checks if all expected messages have been received and processed.

Returns: true if all messages have been received, false otherwise

Throws:

  • ArduinoException - If there are Arduino communication issues
  • SerialPortException - If there are serial port communication errors

Retrieve Individual Messages

public String getMessage(int index) throws IndexOutOfBoundsException;

Gets the message at the specified index position.

Parameters:

  • index - Zero-based index of the message to retrieve

Returns: String message at the specified index

Throws:

  • IndexOutOfBoundsException - If the index is invalid

Get All Messages

public List<String> getMessageList();

Returns a list containing all received messages.

Returns: List<String> containing all processed messages

Buffer Management

Clear Message Buffer

public void flushBuffer();

Clears the internal message buffer, removing all stored messages.

Usage Examples

Basic Multi-Message Reception

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

public class MultiMessageExample {

    public void processMultipleMessages() {
        PanamaHitek_Arduino arduino = new PanamaHitek_Arduino();

        try {
            // Establish connection for receiving data
            arduino.arduinoRX("COM3", 9600, new SerialPortEventListener() {
                @Override
                public void serialEvent(SerialPortEvent event) {
                    // Event handling for data reception
                }
            });

            // Create multi-message handler for 3 simultaneous messages
            PanamaHitek_MultiMessage multiMessage = new PanamaHitek_MultiMessage(3, arduino);

            // Wait for all messages to be received
            while (!multiMessage.dataReceptionCompleted()) {
                Thread.sleep(100); // Brief pause to avoid busy waiting
            }

            // Process received messages
            System.out.println("All messages received:");
            for (int i = 0; i < 3; i++) {
                String message = multiMessage.getMessage(i);
                System.out.println("Message " + (i + 1) + ": " + message);
            }

        } catch (ArduinoException | SerialPortException | InterruptedException ex) {
            System.err.println("Error: " + ex.getMessage());
        }
    }
}

Sensor Data Processing

import java.util.List;

public class SensorDataProcessor {

    private PanamaHitek_Arduino arduino;
    private PanamaHitek_MultiMessage sensorReader;

    public void setupSensorReading() throws ArduinoException {
        arduino = new PanamaHitek_Arduino();

        // Configure for sensor data reception
        arduino.arduinoRX("COM3", 9600, new SerialPortEventListener() {
            @Override
            public void serialEvent(SerialPortEvent event) {
                if (event.isRXCHAR() && event.getEventValue() > 0) {
                    // Handle incoming sensor data
                    processSensorEvent();
                }
            }
        });

        // Expecting data from 4 sensors: temperature, humidity, light, pressure
        sensorReader = new PanamaHitek_MultiMessage(4, arduino);
    }

    public void processSensorData() {
        try {
            // Request sensor readings from Arduino
            arduino.sendData("READ_ALL_SENSORS");

            // Wait for all sensor data to arrive
            while (!sensorReader.dataReceptionCompleted()) {
                Thread.sleep(50);
            }

            // Extract sensor values
            double temperature = Double.parseDouble(sensorReader.getMessage(0));
            double humidity = Double.parseDouble(sensorReader.getMessage(1));
            int lightLevel = Integer.parseInt(sensorReader.getMessage(2));
            double pressure = Double.parseDouble(sensorReader.getMessage(3));

            // Process the sensor data
            System.out.println("Sensor Readings:");
            System.out.println("Temperature: " + temperature + "°C");
            System.out.println("Humidity: " + humidity + "%");
            System.out.println("Light Level: " + lightLevel);
            System.out.println("Pressure: " + pressure + " hPa");

            // Clear buffer for next reading cycle
            sensorReader.flushBuffer();

        } catch (ArduinoException | SerialPortException | InterruptedException ex) {
            System.err.println("Sensor reading error: " + ex.getMessage());
        } catch (NumberFormatException ex) {
            System.err.println("Invalid sensor data format: " + ex.getMessage());
        }
    }

    private void processSensorEvent() {
        // Handle individual sensor data events
        try {
            if (sensorReader.dataReceptionCompleted()) {
                processSensorData();
            }
        } catch (Exception ex) {
            System.err.println("Event processing error: " + ex.getMessage());
        }
    }
}

Real-time Data Monitoring

import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

public class RealTimeMonitor {

    private PanamaHitek_Arduino arduino;
    private PanamaHitek_MultiMessage dataCollector;
    private ScheduledExecutorService scheduler;

    public void startMonitoring() throws ArduinoException {
        arduino = new PanamaHitek_Arduino();
        arduino.arduinoRXTX("COM3", 9600, new SerialPortEventListener() {
            @Override
            public void serialEvent(SerialPortEvent event) {
                // Handle incoming data events
            }
        });

        // Monitor 5 different data streams
        dataCollector = new PanamaHitek_MultiMessage(5, arduino);

        // Start periodic monitoring
        scheduler = Executors.newScheduledThreadPool(1);
        scheduler.scheduleAtFixedRate(this::collectData, 0, 1, TimeUnit.SECONDS);
    }

    private void collectData() {
        try {
            // Request fresh data
            arduino.sendData("GET_REALTIME_DATA");

            // Wait for data with timeout
            int timeout = 0;
            while (!dataCollector.dataReceptionCompleted() && timeout < 50) {
                Thread.sleep(20);
                timeout++;
            }

            if (dataCollector.dataReceptionCompleted()) {
                // Process all received messages
                List<String> messages = dataCollector.getMessageList();

                System.out.println("Real-time data collection:");
                for (int i = 0; i < messages.size(); i++) {
                    System.out.println("Stream " + (i + 1) + ": " + messages.get(i));
                }

                // Prepare for next collection cycle
                dataCollector.flushBuffer();
            } else {
                System.err.println("Data collection timeout");
            }

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

    public void stopMonitoring() {
        if (scheduler != null) {
            scheduler.shutdown();
        }
        try {
            arduino.killArduinoConnection();
        } catch (ArduinoException ex) {
            System.err.println("Error stopping monitor: " + ex.getMessage());
        }
    }
}

Message Validation and Processing

public class MessageValidator {

    private PanamaHitek_MultiMessage messageHandler;

    public void processValidatedMessages(PanamaHitek_Arduino arduino, int expectedMessages) {
        messageHandler = new PanamaHitek_MultiMessage(expectedMessages, arduino);

        try {
            // Wait for all messages
            while (!messageHandler.dataReceptionCompleted()) {
                Thread.sleep(10);
            }

            // Validate and process each message
            for (int i = 0; i < expectedMessages; i++) {
                try {
                    String message = messageHandler.getMessage(i);

                    if (isValidMessage(message)) {
                        processValidMessage(i, message);
                    } else {
                        System.err.println("Invalid message at index " + i + ": " + message);
                    }

                } catch (IndexOutOfBoundsException ex) {
                    System.err.println("Message index " + i + " not available");
                }
            }

            // Get all messages for batch processing
            List<String> allMessages = messageHandler.getMessageList();
            if (allMessages.size() == expectedMessages) {
                performBatchProcessing(allMessages);
            }

        } catch (ArduinoException | SerialPortException | InterruptedException ex) {
            System.err.println("Message processing error: " + ex.getMessage());
        } finally {
            messageHandler.flushBuffer();
        }
    }

    private boolean isValidMessage(String message) {
        // Implement message validation logic
        return message != null && !message.trim().isEmpty() && message.length() > 0;
    }

    private void processValidMessage(int index, String message) {
        System.out.println("Processing valid message " + index + ": " + message);
        // Implement specific message processing logic
    }

    private void performBatchProcessing(List<String> messages) {
        System.out.println("Performing batch processing on " + messages.size() + " messages");
        // Implement batch processing logic
    }
}

Best Practices

  1. Initialize Arduino connection first before creating the multi-message handler
  2. Use appropriate timeout handling when waiting for data reception completion
  3. Clear buffer regularly using flushBuffer() to prevent memory accumulation
  4. Handle exceptions properly for both Arduino and serial port errors
  5. Validate message content before processing to ensure data integrity
  6. Consider message ordering - messages are stored in the order they are received
  7. Implement proper cleanup in finally blocks or shutdown hooks

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