Adding dynamic line chart to JPanel in existing JFrame using JFreeChart <java> - java

I made an application that would show me Max, Minimum, and Average ping when I click "start" in my JFrame application. I made a white box so I could fit a dynamically changing line graph that will be in the same window as my stats, and will update at the same rate as my stats (1 second).
No matter how much I google, everybody seems to understand the JFreeChart sample code. I do not understand how to implement that at all. Other tutorials show just the graph as a standalone in its own window.
I hope somebody can help me. Here is my code for the JFrame as of now:
private void startButtonMouseClicked(java.awt.event.MouseEvent evt) {
String host = hostName.getText();
ScheduledExecutorService exec = Executors.newSingleThreadScheduledExecutor();
exec.scheduleAtFixedRate(new Runnable(){
#Override
public void run(){
try {
NetworkAnalyzer.pingCheck(host);
} catch (IOException ex) {
Logger.getLogger(NetworkAnalyzerwindow.class.getName()).log(Level.SEVERE, null, ex);
}
}
}, 0, 1, TimeUnit.SECONDS);
And here is my pingCheck:
public class NetworkAnalyzer {
static int count=0;
static long max_time = 0;
static long min_time = 0;
static long avg_time = 0;
public static void pingCheck(String host) throws IOException{
String time = "";
//command to execute
String pingCmd = "ping " + host + " -t " + "-n 1";
//gets runtime to execute command
Runtime runtime = Runtime.getRuntime();
try {
Process process = runtime.exec(pingCmd);
//gets inputstream to read the output of the cocmmand
BufferedReader in = new BufferedReader(new InputStreamReader(process.getInputStream()));
//read outputs
String inputLine = in.readLine();
while((inputLine != null)) {
if (inputLine.length() > 0 && inputLine.contains("time")){
time = inputLine.substring(inputLine.indexOf("time"));
break;
}
inputLine = in.readLine();
}
/* if(inputLine.contains("timed")){
System.out.print("Request timed out. Try another domain:");
pingCheck(time);
}*/
time = time.replaceAll("[^0-9]+", " ");
time = time.substring(0, Math.min(time.length(), 3));
time = time.replaceAll(" ", "");
System.out.println("ping:" + time);
//ping calcs
count++;
Long ping;
ping = Long.parseLong(time);
//for avg
//max ping
if( count == 1 || ping >= max_time)
max_time = ping;
//min ping
if(count == 1 || ping <= min_time)
min_time = ping;
//avg ping
if (count > 0)
avg_time = (avg_time*(count-1)+ping)/count;
NetworkAnalyzerwindow.maxPing.setText("Max: " + max_time + "ms");
NetworkAnalyzerwindow.minPing.setText("Min: " + min_time + "ms");
NetworkAnalyzerwindow.avgPing.setText("Avg: " + avg_time + "ms");
} catch(IOException | NumberFormatException ex){
JOptionPane.showMessageDialog(null, ex);
}
}
I just want to add a dynamically changing graph that would take the ping values and graph them. Can somebody actually help me and not link me to one of the tutorials that only shows how to make a graph by itself.
Here is what the app looks like when running(I would like the graph in the white box. I could make the box bigger):
http://imgur.com/kgYCoW2

Using ProcessBuilder, shown here, execute the ping command in your doInBackground() implementation of a SwingWorker. Parse the output, and publish() the results. Update the dataset in your process() implementation, and the chart will update itself in response. An example using JFreeChart is shown here.
Can you explain a bit more?
Starting with the first example, replace
ProcessBuilder pb = new ProcessBuilder("ls", "-lR", "/");
with
ProcessBuilder pb = new ProcessBuilder("ping", "-c", "3", "example.com");
to get a convenient display of the standard output of ping. In outline, your process() in the second example might look like this:
#Override
protected void process(java.util.List<String> messages) {
for (String message : messages) {
textArea.append(message + "\n");
// parse x, y from message
series.add(x, y);
}
}

Related

Runtime.exec() the executable library not work in non root

i have a code :
private static String writeCommandToConsole(Process proc, String command, boolean ignoreError) throws Exception {
byte[] tmpArray = new byte[1024];
proc.getOutputStream().write((command + "\n").getBytes());
proc.getOutputStream().flush();
int bytesRead;
if (proc.getErrorStream().available() > 0) {
if ((bytesRead = proc.getErrorStream().read(tmpArray)) > 1) {
Log.e(LOG_TAG, new String(tmpArray, 0, bytesRead));
if (!ignoreError)
throw new Exception(new String(tmpArray, 0, bytesRead));
}
}
if (proc.getInputStream().available() > 0) {
bytesRead = proc.getInputStream().read(tmpArray);
Log.i(LOG_TAG, new String(tmpArray, 0, bytesRead));
}
return new String(tmpArray);
}
public static void Changes(Context con, int fNums, String fNames, int is, boolean bools, String strs) {
final String fNum = String.valueOf(fNums);
final String fName = fNames;
final String i = String.valueOf(is);
final String str = strs;
final String bool = bools ? "true" : "false";
final String path = pathExecutable + " " + fNum + " \"" + fName + "\" " + i + " " + bool + " \"" + str + "\"";
new Thread(new Runnable() {
#Override
public void run() {
try {
if (isRoot) {
Process proc = Runtime.getRuntime().exec(new String[]{"su"});
writeCommandToConsole(proc, path, true);
} else {
Process proc = Runtime.getRuntime().exec(path);
proc.wait();
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
}).start();
}
for root is work well (my phone is rooted) .. but for non root it not work (use parallel space, virtualXposed,etc in non root phone) .. in non root only work in virtual machine which have a root (vmos,x8 sabdbox etc).
i was try use processBuilder but have a same result .. executable lib seem not get into the target ..
how to write a correct runtime.exec to make it work on non root phone (use parallel space or any cloner without virtual machine with root include) ? or is it any way to make it posible to run executable lib without su command ?
solved .. i change non root command into
Process proc = Runtime.getRuntime().exec(new String[]{"sh"});
writeCommandToConsole(proc, path, true);
and it run well in some virtual app ..

Is there any way to add a "button" to the Windows Notification Area using Java

I have made a small workout reminder app that reminds me at the top of every hour to do some workouts -- Is there any way to add some buttons to this saying "I did it" / "I skipped it?" or something? Source code below, but probably not relevant to the question at hand:
import java.awt.*;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Random;
public class WorkoutReminder {
static final String workouts[] = {
"Pushups", "Curls", "Squats", "Crunches", "Lat raise", "Kneeling hammer Press", "Reverse pushups",
"Ab roller"
};
static final int reps[] = {
10,14,15,17,20
};
public static void main(String args[])throws AWTException, InterruptedException{
if(SystemTray.isSupported()) {
WorkoutReminder wr = new WorkoutReminder();
wr.displayReminder();
}
else{
System.out.println("Run this on windows plz <3");
}
}
private static void displayReminder() throws AWTException, InterruptedException{
while (true) {
DateTimeFormatter dtfm = DateTimeFormatter.ofPattern("mm");
DateTimeFormatter dtfh = DateTimeFormatter.ofPattern("HH");
LocalDateTime currentTime = LocalDateTime.now();
String min = dtfm.format(currentTime);
int hour = Integer.parseInt(dtfh.format(currentTime));
System.out.print(min);
if(min.equals("00") && ( hour >=9 && hour <= 21)) {
Random rand = new Random();
String workout = workouts[Math.abs(rand.nextInt() % workouts.length)];
int rep = reps[Math.abs(rand.nextInt() % reps.length)];
SystemTray st = SystemTray.getSystemTray();
Image logo = Toolkit.getDefaultToolkit().createImage("image.png");
TrayIcon trayIcon = new TrayIcon(logo, "Workout you fat slob");
trayIcon.setImageAutoSize(true);
String iconText = "Workout reminder";
String workoutText = "Let's get it: " + workout + " for " + rep + " reps\n";
System.out.print(" --" + workoutText);
trayIcon.setToolTip("YEEEET");
st.add(trayIcon);
trayIcon.displayMessage(workoutText, iconText, TrayIcon.MessageType.INFO);
Thread.sleep(60000);
}
else{
System.out.print(" - " + (60-Integer.parseInt(min)) + " minutes left\n");
Thread.sleep(60000);
}
}
}
}
I don't know if you can do this in Java directly (maybe you can, I just don't know), but what you could do is call a powershell script from java that can do this.
For more info on creating these scripts: https://eddiejackson.net/wp/?p=18877

How to read percentage from ffmpeg command in java?

I am trying to convert video file to specific format by executing ffmpeg command. In that process I want to read percentage by using timepattern format. Somehow I am not able to do it.
I have tried using the below code. Specially I am getting null in the while loop condition.
import java.io.*;
import java.util.Scanner;
import java.util.regex.Pattern;
class Test {
public static void main(String[] args) throws IOException {
ProcessBuilder pb = new ProcessBuilder("ffmpeg","-i","in.webm","out.mp4");
final Process p = pb.start();
new Thread() {
public void run() {
Scanner sc = new Scanner(p.getErrorStream());
// Find duration
Pattern durPattern = Pattern.compile("(?<=Duration: )[^,]*");
String dur = sc.findWithinHorizon(durPattern, 0);
if (dur == null)
throw new RuntimeException("Could not parse duration.");
String[] hms = dur.split(":");
double totalSecs = Integer.parseInt(hms[0]) * 3600
+ Integer.parseInt(hms[1]) * 60
+ Double.parseDouble(hms[2]);
System.out.println("Total duration: " + totalSecs + " seconds.");
// Find time as long as possible.
Pattern timePattern = Pattern.compile("(?<=time=)[\\d.]*");
String match;
while (null != (match = sc.findWithinHorizon(timePattern, 0))) {
double progress = Double.parseDouble(match) / totalSecs;
System.out.printf("Progress: %.2f%%%n", progress * 100);
}
}
}.start();
}
}
I am expecting a value in the while condition, but it coming as null.enter code here

Java to Arduino communication out of sync - leap motion

I'm trying to control a robotic arm with a leap motion controller. Right now I'm just controlling two servos. I'm using java to read data from the leap motion, process and format it, and send it to the Arduino. The Arduino just receives the data, translates it, and sends it to the servos.
The format that I send the data to the Arduino in is, in string form:
z-rotation:shoulderPos:elbowAngle:wristAngle:clawPos
with each of these variables formatted with leading zeroes so that exactly 19 bytes are always sent to the Arduino at a time.
The issue is that data seems to be being lost in communication between the java on my laptop and the Arduino. If I send one command string, "000:180:000:000:000"
for example, the Arduino tells me that it's received "000:180:000:000:000"
and it correctly sends "000" to one servo and "180" to the second servo.
If I send a string of nine commands:
000:000:000:000:000180:000:000:000:000000:000:000:000:000180:000:000:000:000000:000:000:000:000180:000:000:000:000000:000:000:000:000180:000:000:000:000
The Arduino tells me that it's received all of the commands individually and it correctly sends all of the commands to the servos (evident by the twitching of the servos) and ends with sending "000" to both servos.
However, when I run my code with the leap motion, which effectively constantly transmits strings of 19 bytes to the Arduino, the servos just begin to twitch, moving between 0, 180, and the position that I'm sending to them. When I move my hand closer to the 100 position, the twitching servos have a net movement towards the 100 position, but never actually reaches it. The Arduino tells me that it's receiving the commands correctly for a few seconds before beginning to receive distorted messages like "0:180:0000:0018:00". I can only assume that the transmission and reception of commands are getting out of sync, but I'm not sure.
Here's my Java code:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.text.DecimalFormat;
import java.util.ArrayList;
import com.leapmotion.leap.*;
import gnu.io.CommPort;
import gnu.io.CommPortIdentifier;
import gnu.io.SerialPort;
import gnu.io.SerialPortEvent;
import gnu.io.SerialPortEventListener;
class SampleListenerMain extends Listener {
//define position lock booleans
public boolean leftLock = false;
public boolean rightLock = false;
String data = "";
static DecimalFormat df = new DecimalFormat("000");
//Displacement variables
double deltaX, deltaY, deltaZ, angle;
public void onInit(Controller controller) {
System.out.println("Initialized");
}
public void onConnect(Controller controller) {
System.out.println("Connected");
controller.enableGesture(Gesture.Type.TYPE_CIRCLE);
controller.enableGesture(Gesture.Type.TYPE_KEY_TAP);
}
public void onDisconnect(Controller controller) {
System.out.println("Disconnected");
}
public void onExit(Controller controller) {
System.out.println("Exited");
}
public void onFrame(Controller controller) {
//Define position variables
double shoulderAngle, elbowAngle, wristPos, clawPos, zRotationPos, wristAngle;
//Define object variables
//Frame
Frame frame = controller.frame();
//Hands
Hand leftHand = frame.hands().leftmost();
Hand rightHand = frame.hands().rightmost();
//Arms
Arm leftArm = leftHand.arm();
Arm rightArm = rightHand.arm();
/* Control of robotic arm with Z-rotation based on the left hand, arm 'wrist' position based on the wrist,
* arm 'elbow position based on the elbow, and claw based on the fingers. 'Shoulder' is based on the left elbow
*/
//Control position locks for left hand controls and right hand controls
//Gesture gesture = new Gesture(gesture);
for(Gesture gesture : frame.gestures()) {
HandList handsForGesture = gesture.hands();
switch(gesture.type()) {
case TYPE_KEY_TAP:
System.out.println("Key tap from" + handsForGesture + " Hand");
try {
wait(500);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
leftLock = !leftLock;
break;
default:
System.out.println("Unrecognized gesture");
break;
}
}
//'Shoulder' control
//find angle between the left elbow and the left wrist center
Vector leftElbow = leftArm.elbowPosition();
Vector leftWrist = leftArm.wristPosition();
deltaZ = leftElbow.getZ() - leftWrist.getZ();
deltaY = leftElbow.getY() - leftWrist.getY();
angle = Math.atan(deltaY/deltaZ);
//map angle so servo can understand it
shoulderAngle = leapArm.map(angle, 0, 90, 0, 180);
//System.out.println("ShoulderPos: " + shoulderAngle);
//Write position to 'shoulder'
//Z-rotation control
Vector leftHandPos = leftHand.palmPosition();
//rotate z-axis with speed proportional to left hand X position
//map X position to motor power
zRotationPos = leapArm.map(leftHandPos.getX(), -230, 230, 0, 180);
//System.out.println("zRotationPos: " + zRotationPos);
data += df.format(zRotationPos);
data += ":" + df.format(shoulderAngle);
//write power to rotational servo
//'elbow' control
//find angle between the right elbow and right wrist center
Vector rightElbow = rightArm.elbowPosition();
Vector rightWrist = rightArm.wristPosition();
//refresh deltas and angle
deltaZ = rightElbow.getZ() - rightWrist.getZ();
deltaY = rightElbow.getY() - rightWrist.getY();
angle = Math.atan(deltaY/deltaZ);
//map angle so the servo can understand it
elbowAngle = leapArm.map(angle, -1.25, 0, 0, 180);
data+= ":" + df.format(elbowAngle);
//System.out.println("ElbowPos: " + elbowAngle);
//'wrist' control
//update vectors
rightWrist = rightArm.wristPosition();
Vector rightHandPos = rightHand.palmPosition();
//update deltas
deltaZ = rightWrist.getZ() - rightHandPos.getZ();
deltaY = rightWrist.getY() - rightHandPos.getY();
System.out.println("Wrist pos: " + rightWrist.getX() + ", " + rightWrist.getY() + ", " + rightWrist.getZ());
System.out.println("Right hand pos: " + rightHandPos.getX() + ", " + rightHandPos.getY() + ", " + rightHandPos.getZ());
angle = Math.atan(deltaY/deltaZ);
wristAngle = leapArm.map(angle, -0.5, 0.5, 0, 180);
data += ":" + df.format(wristAngle);
//System.out.println("wristAngle: " + wristAngle + " degrees");
//pinch control
//define fingers
FingerList fingerList = rightHand.fingers().fingerType(Finger.Type.TYPE_INDEX);
Finger rightIndexFinger = fingerList.get(0);
fingerList = rightHand.fingers().fingerType(Finger.Type.TYPE_THUMB);
Finger rightThumb = fingerList.get(0);
//find the distance between the bones to detect pinch
Vector rightIndexDistal = rightIndexFinger.bone(Bone.Type.TYPE_DISTAL).center();
Vector rightThumbDistal = rightThumb.bone(Bone.Type.TYPE_DISTAL).center();
//Calculate distance between joints
double distalDistance = Math.sqrt(Math.pow((rightIndexDistal.getX()-rightThumbDistal.getX()),2) + Math.pow((rightIndexDistal.getY()-rightThumbDistal.getY()),2) + Math.pow((rightIndexDistal.getZ()-rightThumbDistal.getZ()),2));
if(distalDistance <= 10) {
clawPos = 180;
} else {
clawPos = 0;
}
data += ":" + df.format(clawPos);
System.out.println("ClawPos: " + clawPos);
/* Write data to arduino
* FORMAT: z-rotation:shoulderPos:elbowAngle:wristAngle:clawPos
*/
System.out.println("Data: " + data);
/* wait for arduino to catch up ~30 packets/sec
* basically see how long the arduino takes to process one packet and flush the receiving arrays to prevent 'pollution'.
*/
try {
Thread.sleep(50);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//send to arduino
leapArm.writeToArduino(data);
System.out.println("Sent");
}
}
public class leapArm implements SerialPortEventListener {
public static double map(double input, double in_min, double in_max, double out_min, double out_max) {
return ((input - in_min) * (out_max - out_min) / (in_max - in_min)) + out_min;
}
static OutputStream out = null;
static BufferedReader input;
public static void main(String[] args) {
//Connect to COM port
try
{
//Device
(new leapArm()).connect("/dev/cu.usbmodem14101");
Thread.sleep(3000);
//leapArm.writeToArduino("000:000:000:000:000180:000:000:000:000000:000:000:000:000180:000:000:000:000000:000:000:000:000180:000:000:000:000000:000:000:000:000180:000:000:000:000");
//System.out.println("sent");
}
catch ( Exception e )
{
e.printStackTrace();
System.exit(0);
}
// Create a sample listener and controller
SampleListenerMain listener = new SampleListenerMain();
Controller controller = new Controller();
// Have the sample listener receive events from the controller
controller.addListener(listener);
// Keep this process running until Enter is pressed
System.out.println("Press Enter to quit...");
try {
System.in.read();
} catch (IOException e) {
e.printStackTrace();
}
// Remove the sample listener when done
controller.removeListener(listener);
}
void connect ( String portName ) throws Exception {
CommPortIdentifier portIdentifier = CommPortIdentifier.getPortIdentifier(portName);
if ( portIdentifier.isCurrentlyOwned() )
{
System.out.println("Error: Port is currently in use");
}
else
{
CommPort commPort = portIdentifier.open(this.getClass().getName(),2000);
if ( commPort instanceof SerialPort )
{
SerialPort serialPort = (SerialPort) commPort;
serialPort.setSerialPortParams(4800,SerialPort.DATABITS_8,SerialPort.STOPBITS_1,
SerialPort.PARITY_NONE);
out = serialPort.getOutputStream();
//input = new BufferedReader(new InputStreamReader(serialPort.getInputStream()));
// add event listeners
try {
serialPort.addEventListener(this);
serialPort.notifyOnDataAvailable(true);
} catch (Exception e) {
System.err.println(e.toString());
}
}
else
{
System.out.println("Selected port is not a Serial Port");
}
}
}
public static void writeToArduino(String data)
{
String tmpStr = data;
byte bytes[] = tmpStr.getBytes();
try {
/*System.out.println("Sending Bytes: ");
for(int i = 0; i<bytes.length; i++) {
System.out.println(bytes[i]);
}*/
out.write(bytes);
} catch (IOException e) { }
}
public synchronized void serialEvent(SerialPortEvent oEvent) {
if (oEvent.getEventType() == SerialPortEvent.DATA_AVAILABLE) {
try {
String inputLine=input.readLine();
System.out.println("Received: " + inputLine);
} catch (Exception e) {
System.err.println(e.toString());
}
}
// Ignore all the other eventTypes, but you should consider the other ones.
}
}
And here's my Arduino code:
#include <SoftwareSerial.h>
#include <Servo.h>
Servo shoulder1, shoulder2;
SoftwareSerial mySerial(5,3); //RX, TX
char *strings[19];
char chars[19];
int loopno = 0;
byte index = 0;
void setup() {
// put your setup code here, to run once:
Serial.begin(4800);
mySerial.begin(9600);
mySerial.println("Started");
shoulder1.attach(2);
shoulder2.attach(4);
chars[19] = NULL;
}
void loop() {
// put your main code here, to run repeatedly:
if(Serial.available()>18) {
loopno++;
Serial.readBytes(chars, 19);
/*for(int i = 0; i< sizeof(chars); i++) {
mySerial.print("Character ");
mySerial.print(i);
mySerial.print(": ");
mySerial.println(chars[i]);
}*/
String str(chars);
/*mySerial.print("In string form: ");
mySerial.println(str);*/
char* ptr = NULL;
index = 0;
ptr = strtok(chars, ":");
while(ptr != NULL) {
/* mySerial.print("Pointer: ");
mySerial.println(ptr);*/
strings[index] = ptr;
index++;
ptr = strtok(NULL, ":");
}
//mySerial.print("shoulder1: ");
mySerial.println(atoi(strings[0]));
/*mySerial.print("shoulder2: ");
mySerial.println(atoi(strings[0]));
mySerial.print("Loop no: ");*/
mySerial.println(loopno);
shoulder1.write(atoi(strings[0]));
shoulder2.write(atoi(strings[1]));
}
flush();
}
void flush() {
for(int i = 0; i<19; i++) {
chars[i] = NULL;
strings[i] = NULL;
}
}
And here's the circuit that I'm using (The top Arduino is used for serial readout and debugging)
I'm very confused as to why this is happening. I've tried:
Decreasing the baud rate (115200 to 4800).
Sending commands one at a time or in small groups as described earlier.
Commenting out all debugging and unnecessary print statements to decrease processing time and reduce the amount of Serial calls in the Arduino program.
Commenting out all print statements in the Java code as well as rewriting my formatting and transmission code with an eye for effifiency to increase data collection -> transmission speed.
I'd appreciate it if anyone has experience with this or knows what the probelem could be!
Thanks,
Gabe
Edit:
I messed around with it when I got home and I think I might have isolated (one of) the issue(s). When I have all my debugging print statements uncommented and I send the arduino `
Tests.writeToArduino("000:000:000:000:000000:000:000:000:000180:000:000:000:000"); Tests.writeToArduino("180:000:000:000:000000:000:000:000:000000:000:000:000:000");
Tests.writeToArduino("000:000:000:000:000000:000:000:000:000000:000:000:000:000");
Tests.writeToArduino("180:000:000:000:000000:000:000:000:000000:000:000:000:000");, it starts to give me weird feedback starting at loop 7:
However, when I run my code with all the debugging statements commented out except for the first data value and the loop number, it is able to successfully keep track of 51 loops worth of data:
Tests.writeToArduino("000:000:000:000:000000:000:000:000:000180:000:000:000:000");
Tests.writeToArduino("180:000:000:000:000000:000:000:000:000000:000:000:000:000");
Tests.writeToArduino("000:000:000:000:000000:000:000:000:000000:000:000:000:000");
Tests.writeToArduino("180:000:000:000:000000:000:000:000:000000:000:000:000:000");
Tests.writeToArduino("000:000:000:000:000000:000:000:000:000000:000:000:000:000");
Tests.writeToArduino("180:000:000:000:000000:000:000:000:000000:000:000:000:000");
Tests.writeToArduino("000:000:000:000:000000:000:000:000:000000:000:000:000:000");
Tests.writeToArduino("180:000:000:000:000000:000:000:000:000000:000:000:000:000");
Tests.writeToArduino("000:000:000:000:000000:000:000:000:000000:000:000:000:000");
Tests.writeToArduino("180:000:000:000:000000:000:000:000:000000:000:000:000:000");
Tests.writeToArduino("000:000:000:000:000000:000:000:000:000180:000:000:000:000");
Tests.writeToArduino("000:000:000:000:000000:000:000:000:000180:000:000:000:000");
Tests.writeToArduino("000:000:000:000:000000:000:000:000:000180:000:000:000:000");
Tests.writeToArduino("000:000:000:000:000000:000:000:000:000180:000:000:000:000");
Tests.writeToArduino("000:000:000:000:000000:000:000:000:000180:000:000:000:000");
Tests.writeToArduino("000:000:000:000:000000:000:000:000:000180:000:000:000:000");
Tests.writeToArduino("000:000:000:000:000000:000:000:000:000777:000:000:000:000");
gives me:
This leads me to believe that either data is being lost in serial communication, as softwareserial is known to have this issue (which would make sense because less readout -> less jumbled data), or that I might be running into memory issues on the Arduino. Could either of these be the case? I'm still having the original issue, just thought these insights might help.
I found the solution: my arduino code was taking ~30ms to go through one loop but my java-side code was looping faster than that. The 64 byte arduino serial buffer was getting filled up after a few loops, and, since 64 is not a multiple of the 19 bytes I was sending, the dropped bytes would mean that the number:number format would get messed up.
If it helps anyone, I just tracked the time of the arduino loop and added a 50ms delay to the java-side code so that the arduino-side can catch up.

java loop execution program stopped after certain time

public Test(){}
public void run() {
System.out.println("calls");
Map<String, Indexation> mi = new HashMap<>();
String[] spl = compo.split("[\\s#&.?$+-:_!^{}']+");
int ct = 0;
try {
System.out.println("calls Prep");
PreparedStatement p = GetConnexion.getPST("select * from mtg where ogvideo is null and title!=? and alfa!=? and st=? order by id desc limit 1");
PreparedStatement pu = GetConnexion.getPST("update mtg set st=? where id=?");
p.setString(1, "");
p.setString(2, "");
p.setInt(3, 0);
ResultSet r = p.executeQuery();
while (r.next()) {
int id = r.getInt("id");
pu.setInt(1, 2);
pu.setInt(2, id);
pu.executeUpdate();
System.out.println(id + "--------");
String title = r.getString("title");
String alfa = r.getString("alfa");
String compo = title + " " + alfa;
String url = r.getString("url");
compo = compo.toLowerCase();
String[] spl = compo.split("[.=#&,;x|<>!\\s\\-:_\\?\\p{P} \\t\\n\\r]+");
System.out.println("<--->");
for (String s : spl) {
System.out.println("+++++++++++++");
ct = getFrequencies(spl, s) + getOccu(url, s);
System.out.println("----coll----");
Indexation i = new Indexation(alfa, title, url, ct, s,
s + url);
if (s.length() > 2 &&
!getAllStpW().contains(s) &&
!getDirty().contains(s)) mi.put(s, i);
}
}
r.close();
p.close();
System.out.println("end");
} catch (Exception f) {
f.printStackTrace();
}
}
The program above is Test.java which I inherited from Thread.
I wanted to execute it in loop all the time in a linux server,
this is the bash script: test.sh
while true
do
java -Xms40m -Xmx712m -verbose:gc -jar test.jar
done
The execution of the script is good without any exceptions but after certain time it stopped and displays the id of the table and the message ++++++++++.
I have this a problem for a long time. I'm persuaded to kill the process id of the application each time!
What I should i do?

Categories