Skip to content

Commit

Permalink
Merge pull request #8 from opetany93/corrections-to-reading-frame-in-…
Browse files Browse the repository at this point in the history
…separate-thread

further improvements
  • Loading branch information
tainfante authored Dec 13, 2017
2 parents 31dc407 + 615c299 commit 8cabf0c
Show file tree
Hide file tree
Showing 4 changed files with 106 additions and 77 deletions.
2 changes: 1 addition & 1 deletion .idea/misc.xml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

12 changes: 9 additions & 3 deletions src/application/Main.java
Original file line number Diff line number Diff line change
Expand Up @@ -5,22 +5,28 @@
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.stage.Stage;
import port.PortReader;

public class Main extends Application {
public class Main extends Application
{

@Override
public void start(Stage primaryStage) throws Exception{
public void start(Stage primaryStage) throws Exception
{
Parent root = FXMLLoader.load(getClass().getResource("/mainwindow/mainWindowLayout.fxml"));
primaryStage.setTitle("Real Time Serial Plotter");
primaryStage.setScene(new Scene(root, 640, 480));
primaryStage.setMinHeight(450.0);
primaryStage.setMinWidth(620.0);

primaryStage.setOnCloseRequest(event -> PortReader.getInstance().setStopReading(true));

primaryStage.show();
}


public static void main(String[] args) {
public static void main(String[] args)
{
launch(args);
}
}
32 changes: 17 additions & 15 deletions src/port/Port.java
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,11 @@ public class Port

volatile boolean stopReading = false;

public void setStopReading(boolean stopReading)
{
this.stopReading = stopReading;
}

Port()
{

Expand Down Expand Up @@ -39,26 +44,23 @@ public void send(byte[] buffer)
}
}

byte readByte() throws Exception
int readByte(byte[] oneChar)
{
byte[] oneChar = new byte[1];

if(null != serialPort)
{
if ( serialPort.isOpen() )
{
if ( -1 < serialPort.readBytes(oneChar, 1) )
{
return oneChar[0];
}
else
{
oneChar[0] = 1;
}
return serialPort.readBytes(oneChar, 1);
}
else
{
return -1;
}
}

throw new Exception("Port is closed.");
else
{
return -1;
}
}

public boolean open(String serialPortName, int dataBits, int stopBits, int parityBits)
Expand All @@ -68,7 +70,7 @@ public boolean open(String serialPortName, int dataBits, int stopBits, int parit
serialPort = SerialPort.getCommPort(serialPortName);
serialPort.setComPortParameters(baudRate, dataBits, stopBits, parityBits);

serialPort.setComPortTimeouts(SerialPort.TIMEOUT_READ_BLOCKING, 0, 0);
serialPort.setComPortTimeouts(SerialPort.TIMEOUT_READ_BLOCKING, 1, 0);

stopReading = false;

Expand All @@ -94,7 +96,7 @@ public boolean close()
{
stopReading = true;

//serialPort = null;
serialPort = null;
}
}

Expand Down
137 changes: 79 additions & 58 deletions src/port/PortReader.java
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
package port;

import mainwindow.Log;
import classes.Frame;

import java.util.ArrayList;
import java.util.concurrent.LinkedBlockingQueue;

public class PortReader extends Port
{
Expand All @@ -11,15 +12,19 @@ public class PortReader extends Port
private static final byte STOP_BYTE = (byte) 0xD2;
private static final byte CHG_BYTE = (byte) 0xA5;

private static final byte MAX_FRAME_SIZE = 100;
/* maximum is 8 channels where every channel has 1 int value which value it is contained in 4 bytes,
so all maximum number of bytes will be 4*8 + one byte of size */
private static final byte MAX_FRAME_SIZE = 33;

private static volatile PortReader PortReaderINSTANCE;

private ArrayList<Byte> bufferIn;
private LinkedBlockingQueue<Frame> frameBuffer;

private PortReader()
{

bufferIn = new ArrayList<>();
frameBuffer = new LinkedBlockingQueue<>();
}

public static PortReader getInstance()
Expand All @@ -37,76 +42,80 @@ public static PortReader getInstance()
return PortReaderINSTANCE;
}

private int readFrame() throws Exception
private Frame readFrame()
{
byte element = 0; // variable for read one byte
short cntBytes = 0;
int readedBytes = 0;
byte[] element = new byte[1];

boolean listening = true;
boolean wasStarted = false;

Frame frame = null;

while ((START_BYTE & 0xFF) != (element & 0xFF)) // & 0xFF <- to obtain a unsigned value
if(!bufferIn.isEmpty())
{
element = readByte();
bufferIn.clear();
}

bufferIn.clear();

while (listening)
{
element = readByte(); // read one byte
if ( 0 > readByte(element) ) // read one byte
{
break;
}

if ((STOP_BYTE & 0xFF) == (element & 0xFF)) // if element == STOP byte then decode received frame
if ((STOP_BYTE & 0xFF) == (element[0] & 0xFF)) // if element == STOP byte then decode received frame
{
if (0 != bufferIn.size())
if (!bufferIn.isEmpty())
{
// ========================== for debug =====================================
StringBuilder receivedData = new StringBuilder("Received data: ");
bufferIn = decodePayload(bufferIn);

for (Byte el : bufferIn)
// TODO: validate data

try
{
Short t = (short)(el & 0xFF);
frame = mapToFrame(bufferIn);

receivedData.append(t.toString()).append(" ");
listening = false;
}
catch (Exception e)
{
e.printStackTrace();
wasStarted = false;
bufferIn.clear();
cntBytes = 0;
}

Log.getInstance().log(receivedData.toString());
// ============================================================================


readedBytes = decodePayload();


// place for interface to handle of data
}

listening = false;
else
{
wasStarted = false;
}
}
else if ((START_BYTE & 0xFF) == (element & 0xFF)) //if element == START byte then start listening again
else if ((START_BYTE & 0xFF) == (element[0] & 0xFF)) //if element == START byte then start listening again
{
wasStarted = true;
bufferIn.clear();
}
else //else save element in buffer
else if(wasStarted) //else save element in buffer
{
if (cntBytes < MAX_FRAME_SIZE)
{
bufferIn.add(element);
bufferIn.add(element[0]);
cntBytes++;
}
else
{
bufferIn.clear();
cntBytes = 0;

listening = false;
wasStarted = false;
}
}
}

return readedBytes;
return frame;
}

private int decodePayload()
private ArrayList<Byte> decodePayload(ArrayList<Byte> bufferIn)
{
ArrayList<Byte> data = new ArrayList<>();

Expand All @@ -123,50 +132,62 @@ private int decodePayload()
}
}

bufferIn.clear();
bufferIn.addAll(data);
return data;
}

// ========================== for debug ================================
StringBuilder decodedData = new StringBuilder("Decoded data: ");
private Frame mapToFrame(ArrayList<Byte> bytes) throws Exception
{
ArrayList<Integer> mappedValues = new ArrayList<>();

for (Byte el : bufferIn)
{
Short t = (short)(el & 0xFF);
byte numberOfChannels = bytes.get(0);

decodedData.append(t.toString()).append(" ");
if ( (bytes.size() - 1) < numberOfChannels * 4 )
{
throw new Exception("Number of channels in frame was wrong.");
}

Log.getInstance().log(decodedData.toString());
// ======================================================================
for (int i = 0, k = 0; i < numberOfChannels; i++)
{
mappedValues.add( ((bytes.get(++k) & 0xFF) << 24) | ((bytes.get(++k) & 0xFF) << 16) | ((bytes.get(++k) & 0xFF) << 8) | (bytes.get(++k) & 0xFF));
}

return bufferIn.size();
return new Frame(mappedValues);
}

public void startReading()
{
// create a new thread and listen for frame, then display it in Log tab
Thread thread = new Thread(() ->
// create a new thread and listen for frame, then add to frame buffer
Thread readingThread = new Thread(() ->
{
System.out.println("Started reading thread.");

bufferIn = new ArrayList<>();

while(!stopReading)
while (!stopReading)
{
try
{
Log.getInstance().log("Overall received and decoded number of bytes: " + readFrame());
Frame frame = readFrame();

if ( null != frame )
{
frameBuffer.put(readFrame());
System.out.println("New frame is added.");
}
}
catch (Exception e)
catch (InterruptedException e)
{
break;
e.printStackTrace();
}
}

System.out.println("Stopped reading thread.");

});
thread.setName("Reading Thread");
thread.start();
readingThread.setName("FrameReadingThread");
readingThread.start();
}

public LinkedBlockingQueue<Frame> getFrameBuffer()
{
return frameBuffer;
}

}

0 comments on commit 8cabf0c

Please sign in to comment.