I am new to this and I am trying to make a simple program that will send a command to the arduino and then send a response back to java via xbee. I am able to send command to arduino but I am unable to read a response from it. I am using XBee S2C with API-2 configuration. How can I read the response from the arduino in my java?
Here is my code for java:
public class Transmitdataxbee {
private static final String PORT = "COM8";
private static final int BAUD_RATE = 9600;
private static RemoteXBeeDevice myremote;
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
XBeeDevice myDevice = new XBeeDevice(PORT, BAUD_RATE);
Scanner input_rpi = new Scanner(System.in);
String data;
try {
myDevice.open();
XBeeNetwork myXBeeNetwork = myDevice.getNetwork();
myXBeeNetwork.setDiscoveryTimeout(10000);
myXBeeNetwork.startDiscoveryProcess();
while (myXBeeNetwork.isDiscoveryRunning()) {
System.out.println("Discovering devices...");
}
myremote = myXBeeNetwork.getDevice(new XBee64BitAddress("0013A20041768E48"));
String nodeIdentifier = myremote.getNodeID();
System.out.print("Node ID: ");
System.out.println(nodeIdentifier);
System.out.println("Enter Command");
data = input_rpi.next();
myDevice.sendData(myremote, data.getBytes());
System.out.println("Current timeout: " + myDevice.getReceiveTimeout() + "milliseconds");
//read from arduino
XBeeMessage edMessage = myDevice.readDataFrom(myremote);
String data_ed = edMessage.getDataString();
System.out.println(data_ed);
} catch (XBeeException e) {
e.printStackTrace(System.out);
myDevice.close();
System.exit(1);
}
}
}
and this is my code for arudino
#include <XBee.h>
XBee xbee = XBee();
ZBRxResponse rx = ZBRxResponse();
XBeeAddress64 test = XBeeAddress64(0x0013A200, 0x41768E6E);
ModemStatusResponse msr = ModemStatusResponse();
uint8_t data;
char cmd1[9];
String cmd;
char d_ata;
int j = 0;
int icount = 0;
int count = 32;
void setup() {
Serial.begin(9600);
Serial2.begin(9600);
xbee.setSerial(Serial2);
xbee.setAPImode(2);
Serial.println("Connecting....");
}
void loop() {
xbee.readPacket(50);
if (xbee.getResponse().isAvailable()){
Serial.println("Connected");
Serial.println("Getting Message...");
if (xbee.getResponse().getApiId() == ZB_RX_RESPONSE) {
xbee.getResponse().getZBRxResponse(rx);
Serial.println("Packet received!");
if(rx.getOption() == ZB_PACKET_ACKNOWLEDGED){
Serial.println("Packet acknowledged");
}
cmd = "";
Serial.println("Received Data: ");
for (int i = 0; i < rx.getDataLength(); i++) {
//print8Bits(rx.getData()[i]);
cmd1[i] = (char) rx.getData()[i];
cmd += cmd1[i];
Serial.println(cmd);
Serial.println();
}
if (cmd == "a") {
data = "l";
ZBTxRequest zbtx = ZBTxRequest(test,data, sizeof(data));
xbee.send(zbtx);
}
else if (cmd == "w"){
data = "u";
ZBTxRequest zbtx = ZBTxRequest(test,data, sizeof(data));
xbee.send(zbtx);
}
else if (cmd == "s"){
data = "d";
ZBTxRequest zbtx = ZBTxRequest(test,data, sizeof(data));
xbee.send(zbtx);
}
else if (cmd == "d"){
data = "r";
ZBTxRequest zbtx = ZBTxRequest(test,data, sizeof(data));
xbee.send(zbtx);
}
else{
data="e";
ZBTxRequest zbtx = ZBTxRequest(test,data, sizeof(data));
xbee.send(zbtx);
}
}
} else if (xbee.getResponse().isError()) {
// some kind of error happened, I put the stars in so
// it could easily be found
Serial.print("************************************* error code:");
Serial.println(xbee.getResponse().getErrorCode(),DEC);
}
}
After a few reasearches I found a piece of documentation from Digi that might help you.
As I thought in my first comment, the problem appears to come from the part where you try to read datas from the device.
According to this documentation : https://www.digi.com/resources/documentation/digidocs/90001438/reference/r_xb_java_lib_data_reception_callback.htm
You have to create a datalistener an register it to your XBeeDevice.
They even give you a few hints about XBeeMessage information.
I don't know your Java level but all the code is provided in the link above.
If you want to read more about listeners, check this : What is the purpose of a listener in Java?
Related
I am trying to record my vocals and then merge them with an audio file together using OPENSL ES Library. I found this GitHub sample called Native-Audio. It merges the two audios. But the background audio file is playing much faster than the actual rate in the final output.
Please use headphones to notice the difference.
Samples Links: Before and After
Also, it uses the files from the assets folder only. How can I manually select MP3 files from file manager?
private void mixAudio(){
try {
if (!(ContextCompat.checkSelfPermission(this, android.Manifest.permission.WRITE_EXTERNAL_STORAGE)
== PackageManager.PERMISSION_GRANTED) ||
!(ContextCompat.checkSelfPermission(this, android.Manifest.permission.READ_EXTERNAL_STORAGE)
== PackageManager.PERMISSION_GRANTED))
{
// Show rationale and request permission.
ActivityCompat.requestPermissions(this,
new String[]{android.Manifest.permission.READ_EXTERNAL_STORAGE, android.Manifest.permission.WRITE_EXTERNAL_STORAGE},
1000);
}
else {
buttonMix.setEnabled(false);
buttonMix.setText("MIXING....");
textViewMixPath.setText("");
buttonPlay.setEnabled(false);
buttonRecord.setEnabled(false);
buttonStart.setEnabled(false);
listView.setEnabled(false);
Thread thread = new Thread(new Runnable() {
#Override
public void run() {
try{
//final File file = new File(getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS) + "/" + "mix.wav");
//String baseDir = Environment.getExternalStorageDirectory().getAbsolutePath();
//File file = new File(baseDir + "/mix.wav");
String path = Environment.getExternalStorageDirectory().getPath() + "/VocalRecorder";
File fileParent = new File(path);
if (!fileParent.exists()){
fileParent.mkdir();
}
final File file = new File(fileParent.getPath() + "/mix.wav");
//String author = getApplicationContext().getPackageName() + ".provider";
//Uri videoUri = FileProvider.get(this, author, mediaFile);
//final File file = new File(getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS) + "/" + "mix.wav");
//MediaMuxer muxer = new MediaMuxer(file.getAbsolutePath(), MediaMuxer.OutputFormat.MUXER_OUTPUT_MPEG_4);
String beat = beats[selectedBeat];
//beat = beat.replace(".wav", ".mp3");
AssetFileDescriptor afd = getAssets().openFd(beat);
MediaCodec codec = null;
//ByteBuffer outputBuffer;
//short[] data; // data for the AudioTrack playback
//int outputBufferIndex = -1;
MediaMetadataRetriever mediaMetadataRetriever = new MediaMetadataRetriever();
mediaMetadataRetriever.setDataSource(afd.getFileDescriptor(), afd.getStartOffset(), afd.getLength());
String durationStr = mediaMetadataRetriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_DURATION);
final long duration = Long.parseLong(durationStr);
MediaExtractor extractor = new MediaExtractor();
extractor.setDataSource(afd.getFileDescriptor(), afd.getStartOffset(), afd.getLength());
// right now I am pointing to a URI but I have tested that both will
// play the media file using MediaPlayer
int sampleRate = 0;
int numChannels = 0;
int dstIndex = -1;
int numTracks = extractor.getTrackCount(); //This says 1
for (int i = 0; i < numTracks; ++i) { // so this will just run once
MediaFormat format = extractor.getTrackFormat(i); // getting info so it looks good so far
String mime = format.getString(MediaFormat.KEY_MIME); // "audio/mpeg"
if (mime.startsWith("audio/")) {
extractor.selectTrack(i);
codec = MediaCodec.createDecoderByType(mime);
codec.configure(format, null, null, 0);
//format.setString(MediaFormat.KEY_MIME, MediaFormat.MIMETYPE_AUDIO_AMR_NB);
//dstIndex = muxer.addTrack(format);
//writer.setFrameRate(format.getInteger(MediaFormat.KEY_SAMPLE_RATE));
//writer.setSamplesPerFrame(format.getInteger(MediaFormat.KEY_CHANNEL_COUNT));
//writer.setBitsPerSample(16);
sampleRate = format.getInteger(MediaFormat.KEY_SAMPLE_RATE);
numChannels = format.getInteger(MediaFormat.KEY_CHANNEL_COUNT);
break;
}
}
// Calculate the number of frames required for specified duration
long numFrames = (long)(duration * sampleRate/1000);
// Create a wav file with the name specified as the first argument
WavFile wavFile = WavFile.newWavFile(file, numChannels, numFrames, 16, sampleRate);
if (codec == null) {
throw new IllegalArgumentException("No decoder for file format");
}
//ByteBuffer[] inputBuffers = decoder.getInputBuffers();
//ByteBuffer[] outputBuffers = decoder.getOutputBuffers();
/*
Boolean eosReceived = false;
while (!eosReceived) {
int inIndex = decoder.dequeueInputBuffer(1000);
if (inIndex >= 0) {
ByteBuffer buffer = decoder.getInputBuffer(inIndex);
int sampleSize = extractor.readSampleData(buffer, 0);
if (sampleSize < 0) {
// We shouldn't stop the playback at this point, just pass the EOS
// flag to mDecoder, we will get it again from the
// dequeueOutputBuffer
Log.d("DecodeActivity", "InputBuffer BUFFER_FLAG_END_OF_STREAM");
decoder.queueInputBuffer(inIndex, 0, 0, 0, MediaCodec.BUFFER_FLAG_END_OF_STREAM);
} else {
decoder.queueInputBuffer(inIndex, 0, sampleSize, extractor.getSampleTime(), 0);
extractor.advance();
}
int outIndex = decoder.dequeueOutputBuffer(info, 1000);
switch (outIndex) {
case MediaCodec.INFO_OUTPUT_BUFFERS_CHANGED:
Log.d("DecodeActivity", "INFO_OUTPUT_BUFFERS_CHANGED");
//outputBuffers = decoder.getOutputBuffers();
break;
case MediaCodec.INFO_OUTPUT_FORMAT_CHANGED:
MediaFormat format = decoder.getOutputFormat();
Log.d("DecodeActivity", "New format " + format);
//audioTrack.setPlaybackRate(format.getInteger(MediaFormat.KEY_SAMPLE_RATE));
break;
case MediaCodec.INFO_TRY_AGAIN_LATER:
Log.d("DecodeActivity", "dequeueOutputBuffer timed out!");
break;
default:
ByteBuffer outBuffer = decoder.getOutputBuffer(outIndex);
Log.v("DecodeActivity", "We can't use this buffer but render it due to the API limit, " + outBuffer);
final byte[] chunk = new byte[info.size];
outBuffer.get(chunk); // Read the buffer all at once
outBuffer.clear(); // ** MUST DO!!! OTHERWISE THE NEXT TIME YOU GET THIS SAME BUFFER BAD THINGS WILL HAPPEN
//audioTrack.write(chunk, info.offset, info.offset + info.size); // AudioTrack write data
decoder.releaseOutputBuffer(outIndex, false);
break;
}
// All decoded frames have been rendered, we can stop playing now
if ((info.flags & MediaCodec.BUFFER_FLAG_END_OF_STREAM) != 0) {
Log.d("DecodeActivity", "OutputBuffer BUFFER_FLAG_END_OF_STREAM");
break;
}
}
}
*/
short recordedData[] = recordedData();
int recordMixStartIndex = -1;
//muxer.start();
codec.start();
Boolean sawInputEOS = false;
MediaCodec.BufferInfo info = new MediaCodec.BufferInfo();
MediaCodec.BufferInfo infoMux = new MediaCodec.BufferInfo();
int count = 0;
while (!sawInputEOS) {
int inputBufIndex = codec.dequeueInputBuffer(TIMEOUT_US);
Log.i(LOG_TAG, "inputBufIndex : " + inputBufIndex);
if (inputBufIndex >= 0) {
ByteBuffer dstBuf = codec.getInputBuffer(inputBufIndex);
int sampleSize = extractor.readSampleData(dstBuf, 0);
Log.i(LOG_TAG, "sampleSize : " + sampleSize);
long presentationTimeUs = 0;
if (sampleSize < 0) {
Log.i(LOG_TAG, "Saw input end of stream!");
sawInputEOS = true;
sampleSize = 0;
} else {
presentationTimeUs = extractor.getSampleTime();
Log.i(LOG_TAG, "presentationTimeUs " + presentationTimeUs);
}
codec.queueInputBuffer(inputBufIndex,
0, //offset
sampleSize,
presentationTimeUs,
sawInputEOS ? MediaCodec.BUFFER_FLAG_END_OF_STREAM : 0);
if (!sawInputEOS) {
Log.i(LOG_TAG, "extractor.advance()");
extractor.advance();
}
}
final int res = codec.dequeueOutputBuffer(info, TIMEOUT_US);
if (res >= 0) {
int outputBufIndex = res;
ByteBuffer buf = codec.getOutputBuffer(outputBufIndex);
//final byte[] chunk = new byte[info.size];
//buf.get(chunk); // Read the buffer all at once
short[] shortArray = new short[info.size/2];
buf.order(ByteOrder.LITTLE_ENDIAN).asShortBuffer().get(shortArray);
buf.clear(); // ** MUST DO!!! OTHERWISE THE NEXT TIME YOU GET THIS SAME BUFFER BAD THINGS WILL HAPPEN
if (shortArray.length > 0) {
//mAudioTrack.write(chunk, 0, chunk.length);
//infoMux.presentationTimeUs = info.presentationTimeUs;
//infoMux.flags = info.flags;
//muxer.writeSampleData(dstIndex, ByteBuffer.wrap(chunk),
// infoMux);
long []longData = new long[shortArray.length];
// Merge data with vocal
// Calculate the time
final long bufferTimer = info.presentationTimeUs/1000;
int vocalCount = 0;
for (int i = 0; i < shortArray.length; i ++) {
//writer.writeShortLittle(shortArray[i]);
long offsetTime = i*1000/(sampleRate*2); // 2 channels
Boolean mixed = false;
if ((offsetTime + bufferTimer > recordStartTime) && (offsetTime + bufferTimer <= recordStopTime + 500)){
if (recordMixStartIndex == -1){
recordMixStartIndex = 0;
}
if (recordMixStartIndex < recordedData.length){
//Log.i("TAG", "############ mix record data: " + recordMixStartIndex);
longData[i] = TPMixSamples((int)(recordedData[recordMixStartIndex]), (int)shortArray[i]/3);
if (vocalCount >= 3) {
recordMixStartIndex++;
vocalCount = 0;
}
else{
vocalCount ++;
}
mixed = true;
}
}
else {
// All done, set sawInputEOS to stop mixing
if (bufferTimer > recordStopTime + 500){
sawInputEOS = true;
}
}
if (!mixed) {
longData[i] = shortArray[i];
}
}
Log.i("TAG", "############ write frames: " + longData.length/2);
wavFile.writeFrames(longData, longData.length/2);
count ++;
if (count % 5 == 0){
runOnUiThread(new Runnable() {
#Override
public void run() {
long percent = bufferTimer*100/duration;
buttonMix.setText("MIXING..." + percent + "%");
}
});
}
}
codec.releaseOutputBuffer(outputBufIndex, false /* render */);
if ((info.flags & MediaCodec.BUFFER_FLAG_END_OF_STREAM) != 0) {
sawInputEOS = true;
}
} else if (res == MediaCodec.INFO_OUTPUT_BUFFERS_CHANGED) {
//codecOutputBuffers = codec.getOutputBuffers();
} else if (res == MediaCodec.INFO_OUTPUT_FORMAT_CHANGED) {
final MediaFormat oformat = codec.getOutputFormat();
Log.d(LOG_TAG, "Output format has changed to " + oformat);
//mAudioTrack.setPlaybackRate(oformat.getInteger(MediaFormat.KEY_SAMPLE_RATE));
}
}
// Close the wavFile
wavFile.close();
// muxer.stop();
// muxer.release();
codec.stop();
codec.release();
extractor.release();
runOnUiThread(new Runnable() {
#Override
public void run() {
buttonMix.setText("MIX DONE");
buttonPlay.setEnabled(true);
buttonRecord.setEnabled(true);
textViewMixPath.setText(file.getPath());
buttonStart.setEnabled(true);
listView.setEnabled(true);
}
});
}
catch (Exception e){
}
}
});
thread.start();
}
}
catch (Exception e){
e.printStackTrace();
}
}
private final int INT16_MIN = - 32768;
private final int INT16_MAX = 32767;
private long TPMixSamples(int a, int b) {
if (a > INT16_MAX) {a = INT16_MAX;}
if (a < INT16_MIN) {a = INT16_MIN;}
return
// If both samples are negative, mixed signal must have an amplitude between the lesser of A and B, and the minimum permissible negative amplitude
a < 0 && b < 0 ?
((int)a + (int)b) - (((int)a * (int)b)/INT16_MIN) :
// If both samples are positive, mixed signal must have an amplitude between the greater of A and B, and the maximum permissible positive amplitude
( a > 0 && b > 0 ?
((int)a + (int)b) - (((int)a * (int)b)/INT16_MAX)
// If samples are on opposite sides of the 0-crossing, mixed signal should reflect that samples cancel each other out somewhat
:
a + b);
}
/** Native methods, implemented in jni folder */
public static native void createEngine();
public static native void createBufferQueueAudioPlayer(int sampleRate, int samplesPerBuf);
/////
public static native boolean createAssetAudioPlayer(AssetManager assetManager, String filename);
// true == PLAYING, false == PAUSED
public static native void setPlayingAssetAudioPlayer(boolean isPlaying);
public static native int getDurationAssetAudioPlayer();
public static native int getCurrentPositionAssetAudioPlayer();
//////
public static native boolean createUriAudioPlayer(String uri);
public static native void setPlayingUriAudioPlayer(boolean isPlaying);
public static native void setLoopingUriAudioPlayer(boolean isLooping);
public static native void setChannelMuteUriAudioPlayer(int chan, boolean mute);
public static native void setChannelSoloUriAudioPlayer(int chan, boolean solo);
public static native int getNumChannelsUriAudioPlayer();
public static native void setVolumeUriAudioPlayer(int millibel);
public static native void setMuteUriAudioPlayer(boolean mute);
public static native void enableStereoPositionUriAudioPlayer(boolean enable);
public static native void setStereoPositionUriAudioPlayer(int permille);
public static native boolean selectClip(int which, int count);
public static native void stopClip();
public static native boolean enableReverb(boolean enabled);
public static native boolean createAudioRecorder();
public static native void startRecording();
public static native void stopRecording();
public static native void pauseRecording();
public static native void resumeRecording();
public static native short[] recordedData();
public static native double recordedDuration();
public static native void shutdown();
/** Load jni .so on initialization */
static {
System.loadLibrary("native-audio-jni");
}
I am sure this question is answered, I get all kinds of results when I search on it, but I just cant grasp this concept. This is a homework assignment and I prefer to understand which is why I am posting. The assignment is to read user credentials from a file, hash the password, and then if they match display contents of another file that associates with their role.
I wrote this in a single class and then discovered that the assignment calls for at least two classes. So it made sense to me to read the files in 1 class and do everything else in another. It worked very well as one class, but this is my first programming adventure and im only 6 classes in. I do not understand the basics as I should, so in your response if you can teach me why the code needs modified as it does I would be grateful. My code is as follows;
package it145_final;
import java.util.Scanner;
import java.io.IOException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
public class IT145_Final {
public static void main(String[] args) throws IOException, NoSuchAlgorithmException {
Scanner scnr = new Scanner(System.in);
Scanner fileIn = null;
int failedAttempts = 0;
int i = 0;
String q = "q";
// objects that I think I need???? Maybe??? but dont know how to get them from the FinalFiles class
FinalFiles fileAdmin = new FinalFiles();
FinalFiles fileVet = new FinalFiles();
FinalFiles fileZoo = new FinalFiles();
FinalFiles userA = new FinalFiles();
fileAdmin.file();
userA.file();
while (failedAttempts < 3)
{
System.out.println("Enter user name, or q to exit"); //get username
String userName = scnr.next();
if (userName.equalsIgnoreCase(q)) //option to terminiate
{
System.out.println("Logging Out");
break;
}
System.out.println("Enter password"); // get password
scnr.nextLine();
String userPassword = scnr.nextLine();
//The following takes the entered password and hashes it
String hashedPass = userPassword;
MessageDigest md = MessageDigest.getInstance("MD5");
md.update(hashedPass.getBytes());
byte[] digest = md.digest();
StringBuffer sb = new StringBuffer();
for (byte b : digest) {
sb.append(String.format("%02x", b & 0xff));
}
if (userName.equals(userA[i]) && sb.toString().equals(userA[i + 1]))
{
if (userA[i + 3].equals("admin"))
{
System.out.println(admin);
break;
}
else if (userA[i + 3].equals("veterinarian"))
{
System.out.println(veterinarian);
break;
}
else if (userA[i + 3].equals("zookeeper"))
{
System.out.println(zookeeper);
break;
}
else
{
System.out.println("Failed attempt");
failedAttempts ++;
}
}
if (userName.equals(userB[i]) && sb.toString().equals(userB[i + 1]))
{
if (userB[i + 3].equals("admin"))
{
System.out.println(admin);
break;
}
else if (userB[i + 3].equals("veterinarian"))
{
System.out.println(veterinarian);
break;
}
else if (userB[i + 3].equals("zookeeper"))
{
System.out.println(zookeeper);
break;
}
else
{
System.out.println("Failed attempt");
failedAttempts ++;
}
}
if (userName.equals(userC[i]) && sb.toString().equals(userC[i + 1]))
{
if (userC[i + 3].equals("admin"))
{
System.out.println(admin);
break;
}
else if (userC[i + 3].equals("veterinarian"))
{
System.out.println(veterinarian);
break;
}
else if (userC[i + 3].equals("zookeeper"))
{
System.out.println(zookeeper);
break;
}
else
{
System.out.println("Failed attempt");
failedAttempts ++;
}
}
if (userName.equals(userD[i]) && sb.toString().equals(userD[i + 1]))
{
if (userD[i + 3].equals("admin"))
{
System.out.println(admin);
break;
}
else if (userD[i + 3].equals("veterinarian"))
{
System.out.println(veterinarian);
break;
}
else if (userD[i + 3].equals("zookeeper"))
{
System.out.println(zookeeper);
break;
}
else
{
System.out.println("Failed attempt");
failedAttempts ++;
}
}
if (userName.equals(userE[i]) && sb.toString().equals(userE[i + 1]))
{
if (userE[i + 3].equals("admin"))
{
System.out.println(admin);
break;
}
else if (userE[i + 3].equals("veterinarian"))
{
System.out.println(veterinarian);
break;
}
else if (userE[i + 3].equals("zookeeper"))
{
System.out.println(zookeeper);
break;
}
else
{
System.out.println("Failed attempt");
failedAttempts ++;
}
}
if (userName.equals(userF[i]) && sb.toString().equals(userF[i + 1]))
{
if (userF[i + 3].equals("admin"))
{
System.out.println(admin);
break;
}
else if (userF[i + 3].equals("veterinarian"))
{
System.out.println(veterinarian);
break;
}
else if (userF[i + 3].equals("zookeeper"))
{
System.out.println(zookeeper);
break;
}
else
{
System.out.println("Failed attempt");
failedAttempts ++;
}
}
System.out.println("Login Failed");
failedAttempts++;
}
}
}
You can see I started to create some objects but I just cannot figure out how, or if thats even a good way, to get info from my other class.
And the class I created to read the files is;
package it145_final;
import java.io.File;
import java.io.IOException;
import java.util.Scanner;
public class FinalFiles {
public static void file() throws IOException{
String admin = "";
String veterinarian = "";
String zookeeper = "";
String[] userA = new String[4];
String[] userB = new String[4];
String[] userC = new String[4];
String[] userD = new String[4];
String[] userE = new String[4];
String[] userF = new String[4];
File file0 = new File("C:usercredentials.txt"); // Opens files
Scanner contents0 = new Scanner(file0);
File file1 = new File("C:admin.txt");
Scanner contents1 = new Scanner(file1);
File file2 = new File("C:veterinarian.txt");
Scanner contents2 = new Scanner(file2);
File file3 = new File("C:zookeeper.txt");
Scanner contents3 = new Scanner(file3);
// Following reads the files and assignes to variables as needed
while (contents1.hasNext())
{
admin += contents1.nextLine();
}
// System.out.println(admin); used to verify that admin was correct
while (contents2.hasNext())
{
veterinarian += contents2.nextLine();
}
while (contents3.hasNext())
{
zookeeper += contents3.nextLine();
}
while(contents0.hasNext())
{
String user1 = contents0.nextLine();//grabs the line from the file for each individual user
String user2 = contents0.nextLine();
String user3 = contents0.nextLine();
String user4 = contents0.nextLine();
String user5 = contents0.nextLine();
String user6 = contents0.nextLine();
userA = user1.split("\t");//takes information on user and breaks it into an array
userB = user2.split("\t");
userC = user3.split("\t");
userD = user4.split("\t");
userE = user5.split("\t");
userF = user6.split("\t");
System.out.println(userB[0]); //using for testing to make sure I am getting the correct info
System.out.println(userB[1]);
}
}
}
I know its not neat and tidy and I am sure there are better ways for me write something like this, I just did what I though of and what I know. I think if somebody could just show me how to pass those strings(admin, veterinarian, and zookeeper) along with the String[], userA userB etc. into my main it would work again and be sufficient for somebody with my skill level.
Cheers
Andy
As you are at entry level coding i would try to help you understand the logic a little which is essential to making a good application.
To make it easier for yourself you should think that each task needs a class. In your case you should have one class for obtaining the files and another for checking password. keep in mind that there is always one dominant class that launches the application and contains the main method.
In these individual classes you should create methods to break down the processes making the code more clear. In the password checking class you would want a method for each of these jobs (reading the files, encrypting password, decrypting password, checking the credentials against eachother).
Then return the value back to the first class. So it would look something like this.
class Main { //first class
public static void main(String[] args){
File = new File("file1"); //obtain file 1
File = new File("file2"); //obtain file 2
PasswordCheck checker = new PasswordCheck(); // call instance of second class
boolean credentialOk= passwordCheck.process(file1,file2)//calls method in second class and returns if the credentials match
}
}
class PasswordCheck { //second class
public passwordCheck(){
}//inistialise class
public boolean process(File file1, File file2){
}// method to process the files and returns if match succesfully or not
}
I have such a big problem with implementation the svm_predict function. I have trained svm, and prepare datatest. Both files are in .txt. file.Datatest are from LBP( Local Binary patterns) and it looks like:
-0.6448744548418511
-0.7862774302452588
1.7746263060948377
I'm loading it to the svm_predict function and at my console after compiling my program there is:
Accuracy = 0.0% (0/800) (classification)
So it's look like it can't read datatest?
import libsvm.*;
import java.io.*;
import java.util.*;
class svm_predict {
private static double atof(String s)
{
return Double.valueOf(s).doubleValue();
}
private static int atoi(String s)
{
return Integer.parseInt(s);
}
private static void predict(BufferedReader input, DataOutputStream output, svm_model model, int predict_probability) throws IOException
{
int correct = 0;
int total = 0;
double error = 0;
double sumv = 0, sumy = 0, sumvv = 0, sumyy = 0, sumvy = 0;
int svm_type=svm.svm_get_svm_type(model);
int nr_class=svm.svm_get_nr_class(model);
double[] prob_estimates=null;
if(predict_probability == 1)
{
if(svm_type == svm_parameter.EPSILON_SVR ||
svm_type == svm_parameter.NU_SVR)
{
System.out.print("Prob. model for test data: target value = predicted value + z,\nz: Laplace distribution e^(-|z|/sigma)/(2sigma),sigma="+svm.svm_get_svr_probability(model)+"\n");
}
else
{
int[] labels=new int[nr_class];
svm.svm_get_labels(model,labels);
prob_estimates = new double[nr_class];
output.writeBytes("labels");
for(int j=0;j<nr_class;j++)
output.writeBytes(" "+labels[j]);
output.writeBytes("\n");
}
}
while(true)
{
String line = input.readLine();
if(line == null) break;
StringTokenizer st = new StringTokenizer(line," \t\n\r\f:");
double target = atof(st.nextToken());
int m = st.countTokens()/2;
svm_node[] x = new svm_node[m];
for(int j=0;j<m;j++)
{
x[j] = new svm_node();
x[j].index = atoi(st.nextToken());
x[j].value = atof(st.nextToken());
}
double v;
if (predict_probability==1 && (svm_type==svm_parameter.C_SVC || svm_type==svm_parameter.NU_SVC))
{
v = svm.svm_predict_probability(model,x,prob_estimates);
output.writeBytes(v+" ");
for(int j=0;j<nr_class;j++)
output.writeBytes(prob_estimates[j]+" ");
output.writeBytes("\n");
}
else
{
v = svm.svm_predict(model,x);
output.writeBytes(v+"\n");
}
if(v == target)
++correct;
error += (v-target)*(v-target);
sumv += v;
sumy += target;
sumvv += v*v;
sumyy += target*target;
sumvy += v*target;
++total;
}
if(svm_type == svm_parameter.EPSILON_SVR ||
svm_type == svm_parameter.NU_SVR)
{
System.out.print("Mean squared error = "+error/total+" (regression)\n");
System.out.print("Squared correlation coefficient = "+
((total*sumvy-sumv*sumy)*(total*sumvy-sumv*sumy))/
((total*sumvv-sumv*sumv)*(total*sumyy-sumy*sumy))+
" (regression)\n");
}
else
System.out.print("Accuracy = "+(double)correct/total*100+
"% ("+correct+"/"+total+") (classification)\n");
}
private static void exit_with_help()
{
System.err.print("usage: svm_predict [options] test_file model_file output_file\n"
+"options:\n"
+"-b probability_estimates: whether to predict probability estimates, 0 or 1 (default 0); one-class SVM not supported yet\n");
System.exit(1);
}
public static void main(String argv[]) throws IOException
{
int i, predict_probability=0;
// parse options
for(i=0;i<argv.length;i++)
{
if(argv[i].charAt(0) != '-') break;
++i;
switch(argv[i-1].charAt(1))
{
case 'b':
predict_probability = atoi(argv[i]);
break;
default:
System.err.print("Unknown option: " + argv[i-1] + "\n");
exit_with_help();
}
}
if(i>=argv.length-2)
exit_with_help();
try
{
BufferedReader input = new BufferedReader(new FileReader(argv[i]));
DataOutputStream output = new DataOutputStream(new BufferedOutputStream(new FileOutputStream(argv[i+2])));
svm_model model = svm.svm_load_model(argv[i+1]);
if(predict_probability == 1)
{
if(svm.svm_check_probability_model(model)==0)
{
System.err.print("Model does not support probabiliy estimates\n");
System.exit(1);
}
}
else
{
if(svm.svm_check_probability_model(model)!=0)
{
System.out.print("Model supports probability estimates, but disabled in prediction.\n");
}
}
predict(input,output,model,predict_probability);
input.close();
output.close();
}
catch(FileNotFoundException e)
{
exit_with_help();
}
catch(ArrayIndexOutOfBoundsException e)
{
exit_with_help();
}
}
}
It's difficult to know becasue its a big process
make sure you follow their classification guide
the data should be scaled it seems it goes above 1 right now
I want to save a library for a small scale java application which stores technical manuals. Right now I am able to save the library to an external file but I am unable to load it back into the library itself, currently "-1" just gets printed to the console.
How can I solve this?
Here is my code:
//Choice 7: Load Library:
if(Menu.menuChoice == 7){
boolean loadYesNo = Console.readYesNo("\n\nThe manualKeeper app is able to load and display any 'Library.txt' files \nfound in your home folder directory.\n\nWould you like to load and display library? (Y/N):\n");
String fileName = "Library.bin";
if(loadYesNo==true){
try {
FileInputStream fileIs = new FileInputStream(fileName);
ObjectInputStream is = new ObjectInputStream(fileIs);
int x = is.read();
System.out.println(x);
is.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
Menu.displayMenu();
}
else if(loadYesNo==false){
System.out.println("\n\n--------------------------------------------------------------------------");
System.out.println("\n Library not loaded!\n");
System.out.println("--------------------------------------------------------------------------\n");
Menu.displayMenu();
}
}
//Choice 0: Exit the program:
if(Menu.menuChoice == 0){
if(Menu.menuChoice == 0){
if(Library.ManualList.size() > 0){
boolean saveYesNo = Console.readYesNo("\nThe manualKeeper app is able to save your current library to a '.txt' \nfile in your home folder directory (C:\\Users\\ 'YOUR NAME').\n\nWould you like to save the current library? (Y/N):\n");
String fileName = "Library.bin";
if(saveYesNo==true){
try {
FileOutputStream fileOs = new FileOutputStream(fileName);
ObjectOutputStream os = new ObjectOutputStream(fileOs);
for (int i = 0; i < Library.ManualList.size(); i++){
os.writeObject(Library.ManualList.get(i).displayManual());
os.close();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("DONE WRITING!");
} else if(saveYesNo==false){
System.out.println("\n\n--------------------------------------------------------------------------");
System.out.println("\n Library not saved!\n");
System.out.println("--------------------------------------------------------------------------\n");
break exit;
}
Menu.displayMenu();
}else if(Library.ManualList.isEmpty()){
Menu.displayMenu();
}
}
}
}
System.out.println("\n ~ You have exited the manualKeeper app! ~ ");
System.out.println("\n Developed by Oscar Moore - 2014 - UWL\n");
System.out.println("\n <3\n");
}
}
Here is also my library class:
package library;
import java.util.ArrayList;
public class Library {
public static int ManualChoice;
static String returnManualTitle;
static String status1 = "Available";
static String status2 = "Borrowed";
public static ArrayList<Manual> ManualList = new ArrayList<Manual>();
static ArrayList<Manual> borrowedManuals = new ArrayList<Manual>();
static void addManual(){
Manual newManual = new Manual();
newManual.createManual();
ManualList.add(newManual);
System.out.println("\n\n--------------------------------------------------------------------------");
System.out.println("\n Manual added to library!\n");
System.out.println("--------------------------------------------------------------------------\n");
}
static void displayManualList(){
if (ManualList.isEmpty()){
System.out.println("-------------------------------------------------------------");
System.out.println(Messages.empltyLibraryMessage + Messages.tryAgainMessage);
System.out.println("-------------------------------------------------------------");
Menu.menuChoice = 8;
} else {
System.out.printf("\n\nHere are the Manual/s currently stored in the library:\n\n\n");
for (int i = 0; i < ManualList.size(); i++){
System.out.printf("-------------------- Index Number: %s --------------------\n",i);
System.out.println(ManualList.get(i).displayManual());
System.out.println("---------------------------------------------------------\n");
}
}
}
static void displayBorrowedManuals(){
if (ManualList.isEmpty()){
System.out.println("-------------------------------------------------------------");
System.out.println(Messages.empltyLibraryMessage + Messages.tryAgainMessage);
System.out.println("-------------------------------------------------------------");
Menu.menuChoice = 8;
} else {
for (int i = 0; i < borrowedManuals.size(); i++){
System.out.printf("-------------------- Index Number: %s --------------------\n",i);
System.out.println(borrowedManuals.get(i).displayManual());
System.out.println("---------------------------------------------------------");
}
}
}
public static void borrowManual(){
displayManualList();
ManualChoice = (Console.readInteger(Messages.enterManualIndexMessage, Messages.ManualIndexNotInListMessage, 0, Library.ManualList.size() - 1));
borrowLoop:
while(Menu.menuChoice == 3){
if ((ManualList.get(ManualChoice).status.equalsIgnoreCase(status1)) && (ManualList.size() >= ManualChoice)){
ManualList.get(ManualChoice).status = "Borrowed";
ManualList.get(ManualChoice).borrower = User.userName;
ManualList.get(ManualChoice).borrowDate = "Today.";
ManualList.get(ManualChoice).returnDate = "In two weeks.";
borrowedManuals.add(ManualList.get(ManualChoice));
System.out.println("\n--------------------------------------------------------------------------");
System.out.println("\n Manual borrowed!\n");
System.out.println("--------------------------------------------------------------------------\n");
break borrowLoop;
}else if(ManualList.get(ManualChoice).status.equalsIgnoreCase(status2) && ManualList.size() >= ManualChoice){
System.out.println("\n--------------------------------------------------------------------------");
System.out.println("\n "
+ " The Manual you wish to borrow is already on loan.");
System.out.println("\n--------------------------------------------------------------------------\n");
break borrowLoop;
}else if(ManualChoice > ManualList.size()-1){
System.out.println(Messages.noSuchManualMessage);
break borrowLoop;
}
if(ManualList.size() > 1){
displayManualList();
}
else if(ManualList.size() == 1){
ManualList.get(ManualChoice).status = "Borrowed";
ManualList.get(ManualChoice).borrower = User.userName;
ManualList.get(ManualChoice).borrowDate = "Today.";
ManualList.get(ManualChoice).returnDate = "In two weeks.";
borrowedManuals.add(ManualList.get(ManualChoice));
System.out.printf("\n\n %s\n\n", ManualList.get(ManualChoice).displayManual());
System.out.println("Please return the Manual within two weeks!\n");
displayManualList();
}
}
Menu.displayMenu();
}
static void returnManual(){
System.out.printf("\n\nHere are the Manual/s currently out on loan:\n\n");
if(borrowedManuals.size() > 0){
for (int i = 0; i < borrowedManuals.size(); i++)
System.out.println(borrowedManuals.get(i).displayManual());
returnManualTitle = Console.readString(Messages.enterManualSerial, Messages.tooShortMessage, 3);
}
int x = 0;
boolean serialExistance = false;
while (x < ManualList.size()){
if (ManualList.get(x).serial.equalsIgnoreCase(returnManualTitle)){
ManualList.get(x).status = "Available";
ManualList.get(x).borrower = "N/A";
ManualList.get(x).borrowDate = "N/A";
ManualList.get(x).returnDate = "N/A";
int p = 0;
while (p < borrowedManuals.size()) {
Manual borrowed = borrowedManuals.get(p);
if (borrowed.serial.equalsIgnoreCase(returnManualTitle)) {
borrowedManuals.remove(p);
break;
}
p++;
}
System.out.println(Messages.successReturnMessage);
serialExistance = true;
break;
}
x = x+1;
}
if(serialExistance == false){
boolean repeatReturnManual = Console.readYesNo("\n--------------------------------------------------------------------------" + "\n\nThe Manual with the serial "+"\""+returnManualTitle +"\""+ " wasn't found!"
+"\n\nDo you want to try again? (Y/N):\n");
System.out.println("\n--------------------------------------------------------------------------");
if(repeatReturnManual){
returnManual();
}
}else if(serialExistance){
Menu.menuChoice = 8;
}
}
public static void removeManual(){
if(ManualList.size() >0){
displayManualList();
ManualChoice = Console.readInteger(Messages.enterRemoveManualIndex ,Messages.ManualIndexNotInListMessage, 0, ManualList.size());
int p = 0;
while (p < borrowedManuals.size()){
if (borrowedManuals.get(p).title.equalsIgnoreCase(returnManualTitle)){
borrowedManuals.remove(p);
}
}
ManualList.remove(ManualChoice);
System.out.print(Messages.successRemovedManualMessages);
Menu.menuChoice = 8;
}
}
static void emptyLibrary(){
System.out.println("\n WARNING!");
System.out.println("\n You have chosen to delete all Manuals in the library.\n");
System.out.println("--------------------------------------------------------------------------");
boolean emptyLibraryChoice = Console.readYesNo("\nAre you sure you wish to destroy the library? (Y/N): \n");
System.out.println("\n--------------------------------------------------------------------------\n");
if(emptyLibraryChoice){
Library.ManualList.clear();
System.out.println(Messages.successEmptyLibraryMesssage);
System.out.println("--------------------------------------------------------------------------\n");
Menu.menuChoice = 8;
}
}
}
You are using ObjectInputStream not in the intended manner. The correct way would be like:
ObjectInputStream is = new ObjectInputStream(fileIs);
Library x = (Library) is.readObject(); // change Library to the type of object you are reading
System.out.println(x);
You probably need to change Library, but I could not find out, what type of object you are reading.
i'm reading data from serial port for average interval say 1 second,and at the same time writing read data to textArea and textfile,problem is i'm not getting correct data at some time,may be because i'm doing all three process in a single program,how to do writing to text area and text file by separate thred?
this is my code:
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Iterator;
import java.util.TooManyListenersException;
import java.util.TreeMap;
import javax.comm.CommPortIdentifier;
import javax.comm.SerialPort;
import javax.comm.SerialPortEvent;
import javax.comm.SerialPortEventListener;
import javax.comm.UnsupportedCommOperationException;
import javax.swing.JOptionPane;
import com.pressure.constants.Constants;
import com.pressure.online.OnlineStartWindow;
public class SerailReader implements SerialPortEventListener {
// DECLARES INPUT STREAM TO READ SRIAL PORT
private InputStream inputStream;
// DECLARES PORT
private CommPortIdentifier port;
private SerialPort serialPort;
// DATE TO CREATE FILE NAME
private static final SimpleDateFormat SDF = new SimpleDateFormat("dd-MM-yy");
private int index = 0;
private File file;
private OnlineStartWindow onlineStartwindow;
private int[] tempIntArray = new int[233];
private int newData = 0;
private String outFolder;
private String filename = "0";
private FileWriter fileWriter;
private BufferedWriter buffOut;
private StringBuffer line;
private String packetFilename;
TreeMap<Integer, Float> channelMap = new TreeMap<Integer, Float>();
ThreadPrintsAndWrites p;
public FileWriter getFileWriter() {
return fileWriter;
}
public void setFileWriter(FileWriter fileWriter) {
this.fileWriter = fileWriter;
}
public BufferedWriter getBuffOut() {
return buffOut;
}
public void setBuffOut(BufferedWriter buffOut) {
this.buffOut = buffOut;
}
// SETTER GETTER TO OnlineStartwindow OBJECT
public OnlineStartWindow getOnlineStartwindow() {
return onlineStartwindow;
}
public void setOnlineStartwindow(OnlineStartWindow onlineStartwindow) {
this.onlineStartwindow = onlineStartwindow;
}
// SETTER GETTER TO SERIALPORT
public SerialPort getSerialPort() {
return serialPort;
}
public void setSerialPort(SerialPort serialPort) {
this.serialPort = serialPort;
}
// ********* connects to serial port ***********//
public void SerialReadmethod(OnlineStartWindow onlineStartwindow,
String outFolderPath) throws Exception {
setOnlineStartwindow(onlineStartwindow);
outFolder = outFolderPath;
// SELECTS PORT NAME SELECTED
port = CommPortIdentifier.getPortIdentifier(getOnlineStartwindow()
.getComPort());
System.out.println("port name " + port);
// CHEAK WETHER SELECTED PORT AVAILABLE OR NOT
if (port.getPortType() == CommPortIdentifier.PORT_SERIAL) {
if (port.getName().equals(getOnlineStartwindow().getComPort())) {
JOptionPane.showMessageDialog(null, "Successpully opened port",
"Online Dump", JOptionPane.INFORMATION_MESSAGE);
}
}
// OPENS SERAIL PORT
serialPort = (SerialPort) port.open("SimpleReadApp1111", 1000);
// OPENS SERIAL PORT INPUT STREAM TO READ DATA
try {
inputStream = serialPort.getInputStream();
} catch (IOException e) {
System.out.println("IO Exception");
}
// ADDS LISTNER TO SERIALPORT
try {
serialPort.addEventListener(this);
} catch (TooManyListenersException e) {
System.out.println("Tooo many Listener exception");
}
// EVENT GENERATED WHEN DATA WILL BE AVAILABELE ON SERIALPORT
// INPUTSTREAM
serialPort.notifyOnDataAvailable(true);
try {
// SETS SELECTED BAUDRATE
int BAUDRATE = Integer.parseInt((getOnlineStartwindow()
.getBaudRate()).trim());
// SETS SELECTED DATA BITS
int DATABITS = Integer.parseInt(getOnlineStartwindow()
.getDataBits().trim());
if (DATABITS == 8) {
DATABITS = SerialPort.DATABITS_8;
} else if (DATABITS == 7) {
DATABITS = SerialPort.DATABITS_7;
} else if (DATABITS == 6) {
DATABITS = SerialPort.DATABITS_6;
} else if (DATABITS == 5) {
DATABITS = SerialPort.DATABITS_5;
}
// SETS SELECTED STOPBITS
int STOPBITS = 0;
if (getOnlineStartwindow().getStopBits() == "1") {
STOPBITS = SerialPort.STOPBITS_1;
} else if (getOnlineStartwindow().getStopBits() == "1.5") {
STOPBITS = SerialPort.STOPBITS_1_5;
} else if (getOnlineStartwindow().getStopBits() == "2") {
STOPBITS = SerialPort.STOPBITS_2;
}
// SETS SELECTED PARITY
int PARITY = 0;
if (getOnlineStartwindow().getParity() == "NONE") {
PARITY = SerialPort.PARITY_NONE;
} else if (getOnlineStartwindow().getParity() == "EVEN") {
PARITY = SerialPort.PARITY_EVEN;
} else if (getOnlineStartwindow().getParity() == "ODD") {
PARITY = SerialPort.PARITY_ODD;
}
// SETS SELECTED FLOW CONTROL
int FLOWCONTROL = 0;
if (getOnlineStartwindow().getFlowControl() == "NONE") {
FLOWCONTROL = SerialPort.FLOWCONTROL_NONE;
} else if (getOnlineStartwindow().getFlowControl() == "XON/XOFF") {
FLOWCONTROL = SerialPort.FLOWCONTROL_XONXOFF_IN;
}
serialPort
.setSerialPortParams(BAUDRATE, DATABITS, STOPBITS, PARITY);
// no handshaking or other flow control
serialPort.setFlowControlMode(FLOWCONTROL);
} catch (UnsupportedCommOperationException e) {
System.out.println("UnSupported comm operation");
}
}
// *********this method will automaticaly calls when u get data on port and
// arranges packet from start frame to end frame *************//
public void serialEvent(SerialPortEvent event) {
// switch (event.getEventType()) {
//
// case SerialPortEvent.DATA_AVAILABLE:
if(event.getEventType()==SerialPortEvent.DATA_AVAILABLE){
//dataAvailabel = inputStream.available();
// READING DATA CHARECTER BY CHARECTER
while (newData != -1) {
try {
newData = inputStream.read();
if (newData == -1) {
break;
}
if (Constants.SF == (char) newData) {
index = 0;
// System.out.println("start frame");
}
tempIntArray[index] = newData;
if (Constants.EF == (char) newData) {
selectToDispalyAndWrite(tempIntArray);
// disp(tempIntArray);
}
index++;
} catch (IOException ex) {
System.err.println(ex);
// return;
}
}
// ///////////////// completes
}
}
// DISPLYS PACKET TO TEXT AREA AND CREATES .PSI FILE
public void selectToDispalyAndWrite(int[] readBufferArray) {
if (getOnlineStartwindow().getDump().isSelected()) {
packetFilename = Integer.toString(readBufferArray[1])
+ Integer.toString(readBufferArray[2])
+ Integer.toString(readBufferArray[3]);
try {
if (getOnlineStartwindow().getFileTypeSelection() == "text") {
displayAndWriteToTextFile(readBufferArray);
} else {
displayAndWriteToExcelFile(readBufferArray);
}
} catch (IOException e) {
e.printStackTrace();
}
} else {
printToTextArea(readBufferArray);
}
}
public void printToTextArea(int[] readBufferArray) {
int i = 0;
int portname = 0;
Float portval = 0.0f;
int len = 0;
i = 0;
writeloop: while (len != readBufferArray.length) {
// while ((char) readBufferArray[i] != Constants.EF) {
if ((char) readBufferArray[i] == Constants.SF) {
// WRITES DASH LINE TO TEXT AREA
getOnlineStartwindow()
.getTextArea()
.append(
"\r\n\r\n-----------------------------------------------------------------------\r\n");
getOnlineStartwindow().getTextArea().append(
"Time :" + readBufferArray[i + 4] + " Min "
+ readBufferArray[i + 5] + " Sec.");
getOnlineStartwindow()
.getTextArea()
.append(
"\r\n-----------------------------------------------------------------------\r\n");
}
if ((char) readBufferArray[i] == Constants.EF) {
for (Iterator<Integer> iterator = channelMap.keySet()
.iterator(); iterator.hasNext();) {
int key = iterator.next();
Float value = channelMap.get(key);
getOnlineStartwindow().getTextArea().append(
"Port_" + key + " " + value + "\r\n");
}
channelMap.clear();
break writeloop;
}
i++;
}
}
public void displayAndWriteToTextFile(int[] readBufferArray)
throws IOException {
int i = 0;
int portname = 0;
Float portval = 0.0f;
if (!(filename.equalsIgnoreCase(packetFilename))) {
filename = packetFilename;
if (buffOut != null && fileWriter != null) {
drawLine('*');
buffOut.close();
fileWriter.close();
}
// GET CURRENT DATE
Date date = new Date();
file = new File(outFolder + "\\" + SDF.format(date) + "-"
+ packetFilename + ".txt");
if (!file.exists()) {
fileWriter = new FileWriter(file, true);
buffOut = new BufferedWriter(fileWriter);
drawLine('*');
drawLine('*');
} else {
fileWriter = new FileWriter(file, true);
buffOut = new BufferedWriter(fileWriter);
}
}
// LOOP TO DISPLY ALL PORT NAME AND PRESSURE VALUES
int len = 0;
i = 0;
writeloop: while (len != readBufferArray.length) {
// while ((char) readBufferArray[i] != Constants.EF) {
if ((char) readBufferArray[i] == Constants.SF) {
// WRITES DASH LINE TO TEXT AREA
getOnlineStartwindow()
.getTextArea()
.append(
"\r\n\r\n-----------------------------------------------------------------------\r\n");
getOnlineStartwindow().getTextArea().append(
"Time :" + readBufferArray[i + 4] + " Min "
+ readBufferArray[i + 5] + " Sec.");
getOnlineStartwindow()
.getTextArea()
.append(
"\r\n-----------------------------------------------------------------------\r\n");
drawLine('-');
buffOut.write("TIME: " + readBufferArray[i + 4] + " Min "
+ readBufferArray[i + 5] + " Sec." + "\r\n\r\n");
}
if ((char) readBufferArray[i] == Constants.ST) {
portname = readBufferArray[i + 1];
portval = getFloatValue(i);
channelMap.put(portname, portval);
}
if ((char) readBufferArray[i] == Constants.EF) {
for (Iterator<Integer> iterator = channelMap.keySet()
.iterator(); iterator.hasNext();) {
int key = iterator.next();
Float value = channelMap.get(key);
getOnlineStartwindow().getTextArea().append(
"Port_" + key + " " + value + "\r\n");
}
channelMap.clear();
break writeloop;
}
i++;
}
}
}
Thanks in advance
Here an approach from a design standpoint.
Create a class type for the data. This will be a container (inherit the appropriate queue). And inside of this class as you set and get the data make sure you lock.
Create a new thread in main to start the serial port and read the messages. Pass the thread one object (your list class object). The serial port will chuck data into this list. This will be sets in the object.
You main thread (the window) will have a timer that fires and reads the data from queue. You may have to play with the timer some. You don't want it firing too often and eating all your processing time in the main window. However if it is too slow you may not be updating enough and getting messages out of the queue when they are available. This timer should get all of the data out the queue and display it.
The queue and the lock are the important part here. The queue will keep messages in order. The lock will make sure you don't try to write new data to your queue while you are in the middle of reading data.
I was under the impression that Java does not support serial port for Windows, it only does it for Solaris or Linux.
your class should implement the Runnable Interface. and create a thread that reads from the serial port in its run method.
The Main thread could do the writing part to the TextArea.
You may need to do some synchronization between the Main Thread and the Runnable so that writing to the TextArea/File only takes place after appropriate data has been read from the port.