0
# Multi-Message Processing
1
2
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.
3
4
## PanamaHitek_MultiMessage Class
5
6
```java { .api }
7
public class PanamaHitek_MultiMessage {
8
public PanamaHitek_MultiMessage(int inputMessages, PanamaHitek_Arduino arduinoObject);
9
}
10
```
11
12
Creates a multi-message handler for processing a specified number of messages from Arduino.
13
14
**Parameters:**
15
- `inputMessages` - Number of expected messages to process simultaneously
16
- `arduinoObject` - An already configured `PanamaHitek_Arduino` instance
17
18
## Data Reception Methods
19
20
### Check Reception Completion
21
22
```java { .api }
23
public boolean dataReceptionCompleted() throws ArduinoException, SerialPortException;
24
```
25
26
Checks if all expected messages have been received and processed.
27
28
**Returns:** `true` if all messages have been received, `false` otherwise
29
30
**Throws:**
31
- `ArduinoException` - If there are Arduino communication issues
32
- `SerialPortException` - If there are serial port communication errors
33
34
### Retrieve Individual Messages
35
36
```java { .api }
37
public String getMessage(int index) throws IndexOutOfBoundsException;
38
```
39
40
Gets the message at the specified index position.
41
42
**Parameters:**
43
- `index` - Zero-based index of the message to retrieve
44
45
**Returns:** String message at the specified index
46
47
**Throws:**
48
- `IndexOutOfBoundsException` - If the index is invalid
49
50
### Get All Messages
51
52
```java { .api }
53
public List<String> getMessageList();
54
```
55
56
Returns a list containing all received messages.
57
58
**Returns:** `List<String>` containing all processed messages
59
60
## Buffer Management
61
62
### Clear Message Buffer
63
64
```java { .api }
65
public void flushBuffer();
66
```
67
68
Clears the internal message buffer, removing all stored messages.
69
70
## Usage Examples
71
72
### Basic Multi-Message Reception
73
74
```java
75
import com.panamahitek.PanamaHitek_Arduino;
76
import com.panamahitek.PanamaHitek_MultiMessage;
77
import com.panamahitek.ArduinoException;
78
import jssc.*;
79
80
public class MultiMessageExample {
81
82
public void processMultipleMessages() {
83
PanamaHitek_Arduino arduino = new PanamaHitek_Arduino();
84
85
try {
86
// Establish connection for receiving data
87
arduino.arduinoRX("COM3", 9600, new SerialPortEventListener() {
88
@Override
89
public void serialEvent(SerialPortEvent event) {
90
// Event handling for data reception
91
}
92
});
93
94
// Create multi-message handler for 3 simultaneous messages
95
PanamaHitek_MultiMessage multiMessage = new PanamaHitek_MultiMessage(3, arduino);
96
97
// Wait for all messages to be received
98
while (!multiMessage.dataReceptionCompleted()) {
99
Thread.sleep(100); // Brief pause to avoid busy waiting
100
}
101
102
// Process received messages
103
System.out.println("All messages received:");
104
for (int i = 0; i < 3; i++) {
105
String message = multiMessage.getMessage(i);
106
System.out.println("Message " + (i + 1) + ": " + message);
107
}
108
109
} catch (ArduinoException | SerialPortException | InterruptedException ex) {
110
System.err.println("Error: " + ex.getMessage());
111
}
112
}
113
}
114
```
115
116
### Sensor Data Processing
117
118
```java
119
import java.util.List;
120
121
public class SensorDataProcessor {
122
123
private PanamaHitek_Arduino arduino;
124
private PanamaHitek_MultiMessage sensorReader;
125
126
public void setupSensorReading() throws ArduinoException {
127
arduino = new PanamaHitek_Arduino();
128
129
// Configure for sensor data reception
130
arduino.arduinoRX("COM3", 9600, new SerialPortEventListener() {
131
@Override
132
public void serialEvent(SerialPortEvent event) {
133
if (event.isRXCHAR() && event.getEventValue() > 0) {
134
// Handle incoming sensor data
135
processSensorEvent();
136
}
137
}
138
});
139
140
// Expecting data from 4 sensors: temperature, humidity, light, pressure
141
sensorReader = new PanamaHitek_MultiMessage(4, arduino);
142
}
143
144
public void processSensorData() {
145
try {
146
// Request sensor readings from Arduino
147
arduino.sendData("READ_ALL_SENSORS");
148
149
// Wait for all sensor data to arrive
150
while (!sensorReader.dataReceptionCompleted()) {
151
Thread.sleep(50);
152
}
153
154
// Extract sensor values
155
double temperature = Double.parseDouble(sensorReader.getMessage(0));
156
double humidity = Double.parseDouble(sensorReader.getMessage(1));
157
int lightLevel = Integer.parseInt(sensorReader.getMessage(2));
158
double pressure = Double.parseDouble(sensorReader.getMessage(3));
159
160
// Process the sensor data
161
System.out.println("Sensor Readings:");
162
System.out.println("Temperature: " + temperature + "°C");
163
System.out.println("Humidity: " + humidity + "%");
164
System.out.println("Light Level: " + lightLevel);
165
System.out.println("Pressure: " + pressure + " hPa");
166
167
// Clear buffer for next reading cycle
168
sensorReader.flushBuffer();
169
170
} catch (ArduinoException | SerialPortException | InterruptedException ex) {
171
System.err.println("Sensor reading error: " + ex.getMessage());
172
} catch (NumberFormatException ex) {
173
System.err.println("Invalid sensor data format: " + ex.getMessage());
174
}
175
}
176
177
private void processSensorEvent() {
178
// Handle individual sensor data events
179
try {
180
if (sensorReader.dataReceptionCompleted()) {
181
processSensorData();
182
}
183
} catch (Exception ex) {
184
System.err.println("Event processing error: " + ex.getMessage());
185
}
186
}
187
}
188
```
189
190
### Real-time Data Monitoring
191
192
```java
193
import java.util.concurrent.ScheduledExecutorService;
194
import java.util.concurrent.Executors;
195
import java.util.concurrent.TimeUnit;
196
197
public class RealTimeMonitor {
198
199
private PanamaHitek_Arduino arduino;
200
private PanamaHitek_MultiMessage dataCollector;
201
private ScheduledExecutorService scheduler;
202
203
public void startMonitoring() throws ArduinoException {
204
arduino = new PanamaHitek_Arduino();
205
arduino.arduinoRXTX("COM3", 9600, new SerialPortEventListener() {
206
@Override
207
public void serialEvent(SerialPortEvent event) {
208
// Handle incoming data events
209
}
210
});
211
212
// Monitor 5 different data streams
213
dataCollector = new PanamaHitek_MultiMessage(5, arduino);
214
215
// Start periodic monitoring
216
scheduler = Executors.newScheduledThreadPool(1);
217
scheduler.scheduleAtFixedRate(this::collectData, 0, 1, TimeUnit.SECONDS);
218
}
219
220
private void collectData() {
221
try {
222
// Request fresh data
223
arduino.sendData("GET_REALTIME_DATA");
224
225
// Wait for data with timeout
226
int timeout = 0;
227
while (!dataCollector.dataReceptionCompleted() && timeout < 50) {
228
Thread.sleep(20);
229
timeout++;
230
}
231
232
if (dataCollector.dataReceptionCompleted()) {
233
// Process all received messages
234
List<String> messages = dataCollector.getMessageList();
235
236
System.out.println("Real-time data collection:");
237
for (int i = 0; i < messages.size(); i++) {
238
System.out.println("Stream " + (i + 1) + ": " + messages.get(i));
239
}
240
241
// Prepare for next collection cycle
242
dataCollector.flushBuffer();
243
} else {
244
System.err.println("Data collection timeout");
245
}
246
247
} catch (Exception ex) {
248
System.err.println("Monitoring error: " + ex.getMessage());
249
}
250
}
251
252
public void stopMonitoring() {
253
if (scheduler != null) {
254
scheduler.shutdown();
255
}
256
try {
257
arduino.killArduinoConnection();
258
} catch (ArduinoException ex) {
259
System.err.println("Error stopping monitor: " + ex.getMessage());
260
}
261
}
262
}
263
```
264
265
### Message Validation and Processing
266
267
```java
268
public class MessageValidator {
269
270
private PanamaHitek_MultiMessage messageHandler;
271
272
public void processValidatedMessages(PanamaHitek_Arduino arduino, int expectedMessages) {
273
messageHandler = new PanamaHitek_MultiMessage(expectedMessages, arduino);
274
275
try {
276
// Wait for all messages
277
while (!messageHandler.dataReceptionCompleted()) {
278
Thread.sleep(10);
279
}
280
281
// Validate and process each message
282
for (int i = 0; i < expectedMessages; i++) {
283
try {
284
String message = messageHandler.getMessage(i);
285
286
if (isValidMessage(message)) {
287
processValidMessage(i, message);
288
} else {
289
System.err.println("Invalid message at index " + i + ": " + message);
290
}
291
292
} catch (IndexOutOfBoundsException ex) {
293
System.err.println("Message index " + i + " not available");
294
}
295
}
296
297
// Get all messages for batch processing
298
List<String> allMessages = messageHandler.getMessageList();
299
if (allMessages.size() == expectedMessages) {
300
performBatchProcessing(allMessages);
301
}
302
303
} catch (ArduinoException | SerialPortException | InterruptedException ex) {
304
System.err.println("Message processing error: " + ex.getMessage());
305
} finally {
306
messageHandler.flushBuffer();
307
}
308
}
309
310
private boolean isValidMessage(String message) {
311
// Implement message validation logic
312
return message != null && !message.trim().isEmpty() && message.length() > 0;
313
}
314
315
private void processValidMessage(int index, String message) {
316
System.out.println("Processing valid message " + index + ": " + message);
317
// Implement specific message processing logic
318
}
319
320
private void performBatchProcessing(List<String> messages) {
321
System.out.println("Performing batch processing on " + messages.size() + " messages");
322
// Implement batch processing logic
323
}
324
}
325
```
326
327
## Best Practices
328
329
1. **Initialize Arduino connection first** before creating the multi-message handler
330
2. **Use appropriate timeout handling** when waiting for data reception completion
331
3. **Clear buffer regularly** using `flushBuffer()` to prevent memory accumulation
332
4. **Handle exceptions properly** for both Arduino and serial port errors
333
5. **Validate message content** before processing to ensure data integrity
334
6. **Consider message ordering** - messages are stored in the order they are received
335
7. **Implement proper cleanup** in finally blocks or shutdown hooks