package com.example.demo.dao;
import com.fazecast.jSerialComm.SerialPort;
import org.springframework.stereotype.Component;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
@Component
public class GetData {
public int[] ReadConventionalData() throws InterruptedException {
SerialPort port = SerialPort.getCommPort("COM9");
port.openPort();
port.setComPortParameters(115200, 8, 1, 0);
int[] array = new int[3];
StringBuilder sb = new StringBuilder();
try {
while (true) {
if (port.bytesAvailable() > 0) {
byte[] buffer = new byte[port.bytesAvailable()];
port.readBytes(buffer, buffer.length);
sb.append(new String(buffer));
// Ensure we have a complete set of data
String data = sb.toString();
if (data.contains("X:") && data.contains("Y:") && data.contains("Z:")) {
String[] parts = data.split("[XYZ]+");
if (parts.length >= 4) {
try {
int xValue = Integer.parseInt(parts[1].replaceAll("[^0-9-]", "").trim());
int yValue = Integer.parseInt(parts[2].replaceAll("[^0-9-]", "").trim());
// Extract zValue safely
String zString = parts[3].substring(0, Math.min(5, parts[3].length())).replaceAll("[^0-9-]", "").trim();
int zValue = Integer.parseInt(zString);
array[0] = xValue;
array[1] = yValue;
array[2] = zValue;
System.out.println("X: " + xValue + ", Y: " + yValue + ", Z: " + zValue);
// Remove processed data
sb.delete(0, sb.indexOf("Z:") + 2);
port.closePort();
return array;
} catch (NumberFormatException | StringIndexOutOfBoundsException e) {
System.err.println("Error parsing data: " + e.getMessage());
// Handle the exception if needed
sb.delete(0, sb.indexOf("Z:") + 2); // Remove faulty data
}
}
}
}
Thread.sleep(100); // Adjust sleep time as necessary
}
} finally {
port.closePort(); // Ensure port is closed in all cases
}
}
}