I am using the javax.comm package to read some data off the serial port.
The data is to be displayed on a SWT a text widget. I have added an
eventListener to the serial port object and made notifyOnDataAvailable
true, so that my app gets notified when data arrives. Anyway, on the
event handler, I try to append the newly read data to the text widget,
but it does not append the read value with text widget. But when i try to print the same in console it does that perfectly. I have a similar app
written in AWT and it doesn't have this problem. Does it have anything
to do with the way SWT handles the main thread? Is there a way around my
problem?
Here is my code -
public void serialEvent(SerialPortEvent evt) {
if (evt.getEventType() == SerialPortEvent.DATA_AVAILABLE)
{
try
{
byte singleData = (byte)input.read();
// READING THE SERIAL PORT VALUE HERE IN
// TEXT AREA CALLED txtLog
if (singleData != NEW_LINE_ASCII)
{
logText = new String(new byte[] {singleData});
// System.out.print(logText);
txtLog.append(logText);
}
else
{
txtLog.append("\n");
}
}
catch (Exception e)
{
logText = "Failed to read data. (" + e.toString() + ")";
txtLog.setForeground(Color.red);
txtLog.append(logText + "\n");
}
}
}
Related
I would just like to ask if how do u listen to a external input forever while u can do events like button clicking, texfield typing, etc.
Like it listens every second, and if it receives a data, it will do something. If it doesnt receive data then it continues to listen for data.
While it listens, I can do events like I mentioned above.
Sorry for my bad english.
The only good way to read from a stream is in a separate thread. For a silly example, if you wanted to update a label with the last byte read, something like this might work:
static void startListening(DataInputStream inputStream, JLabel label) {
new Thread(() -> {
try {
while (true) {
int i = inputStream.read();
if (i < 0) {
updateText(label, "Closed");
break;
} else {
updateText(label, "Latest byte: " + i);
}
}
} catch (Exception e) {
updateText(label, "Error: " + e);
}
}).start();
}
static void updateText(JLabel label, String text) {
SwingUtilities.invokeLater(() -> label.setText(text));
}
I have an RFID usb reader for Windows which acts as an external keyboard. When plugged into my laptop the reader transmits a number (0014671609) when an RFID object is scanned (like you would type in the number on a real keyboard).
My goal is to make an Android app which also prints the number when a RFID object is scanned.
Currently, I can connect to the device and when I scan something I get a response, but I have trouble reading the response. Here is my code:
public void run() {
try {
int packetSize = deviceEndpoint.getMaxPacketSize();
ByteBuffer buffer = ByteBuffer.allocate(packetSize);
UsbRequest outRequest = new UsbRequest();
outRequest.initialize(deviceConnection, deviceEndpoint);
outRequest.queue(buffer, 1);
if (deviceConnection.requestWait() == outRequest) {
UsbRequest inRequest = new UsbRequest();
inRequest.initialize(deviceConnection, deviceEndpoint);
if(inRequest.queue(buffer, packetSize) == true){
deviceConnection.requestWait();
// get response data
byte[] data = buffer.array();
System.out.println("Response: " + new String(data, "UTF-8"));
}
}
} catch (Exception ex) {
System.out.println("ERROR: " + ex.getMessage().toString());
}
}
The reponse:
Response: ����'����������
in android you can use the dispatchKeyEvent in your main activity.
I have a similar setup except with a barcode scanner which transmits a barcode as if i would enter it with an external keyboard.
#Override
public boolean dispatchKeyEvent(KeyEvent event) {
System.out.println(event.getAction() + " " + event.getKeyCode() + " - " + (char) event.getUnicodeChar());
return true;
}
this should help you if you want to get the information. you should only know when the RFID sequence finished. does it transmit a suffix which you can look out for?
remember that this method catches all key events: key up as well as key down. you should filter for this.
EDIT I have it working now thanks to the comments below. I also explained what I fixed in the comments. Thanks for the help guys.
Im working on a multiplayer game in java. It's coming along pretty well so far, but Im having an issue with the server sending information to the client. The process should be that, the server receives information from the client and interprets what it's supposed to do. In this case, the client sends a chat message to the server split with commas. "chat,Bob,the message is here."
At this point in time, the server should essentially send back that same information to the client that sent the message. Somehow, along the way though, the ByteBuffer which is what is housing the information gets corrupted?
The following is the pertinent code for the server:
// Read the data
SocketChannel sc = (SocketChannel) key.channel();
// interpret
int bytesEchoed = 0;
while (true) {
//Clears this buffer.
echoBuffer.clear();
int number_of_bytes;
String message = new String(echoBuffer.array());
String[] splits = message.split(",");
try {
number_of_bytes = sc.read(echoBuffer);
} catch (java.io.IOException e) {
key.cancel();
number_of_bytes = -1;
}
//-----------Interpret Packets--------------------
//-------------Chat-----------------
if (splits[0].contentEquals("chat")) {
//do chat shit
String name = splits[1];
String text = splits[2];
String sendBack = "chat," + name + "," + text + ","+"\r";
System.out.println(sendBack);
if (splits[0].equals("chat")) {
echoBuffer.clear();
echoBuffer.put(sendBack.getBytes());
}
}
//
if (number_of_bytes <= 0) {
break;
}
//
//
echoBuffer.flip();
sc.write(echoBuffer);
bytesEchoed += number_of_bytes;
}
System.out.println("Echoed " + bytesEchoed + " from " + sc);
// once a key is handled, it needs to be removed
it.remove();
}
}
}
}
Can anyone tell me what I am messing up?
I wasn't doing clear() before I was putting the sendBack string to the bytebuffer, and that was adding the text to the end of the buffer, instead of the beginning. Also, on the client side I was using readLine() to get the incoming data, but there was no carriage return "\r" or new line "\n" on the outgoing server data, resulting in my client reading nothing. Those two things fixed, have it working properly.
I'm using the (id12 innovations) RFID read with a Raspberry Pi.
Using the PI4J java library and it's serial example, I'm able to read some data like (5002CF13C6) i'm not sure what this data is! it suppose to get this number (0002948115).
here's is my code:
// create an instance of the serial communications class
final Serial serial = SerialFactory.createInstance();
// create and register the serial data listener
serial.addListener(new SerialDataListener() {
#Override
public void dataReceived(SerialDataEvent event) {
//-----------
System.out.print("\n" + event.getData());
//-----------
}
});
try {
// open the default serial port provided on the GPIO header
serial.open("/dev/ttyAMA0", 9600);
// continuous loop to keep the program running until the user terminates the program
for (;;) {
try {
} catch (IllegalStateException ex) {
ex.printStackTrace();
}
try {
// wait 1 second before continuing
Thread.sleep(1000);
} catch (InterruptedException ex) {
Logger.getLogger(Rfid.class.getName()).log(Level.SEVERE, null, ex);
}
}
} catch (SerialPortException ex) {
System.out.println("e: RFID setup failed : " + ex.getMessage());
}
what should i do to event.getData() in order to be able to read the real data?
event.getData(), is returning to you exactly what the id12 chip is saying on the serial port. The data is a 10 character string representation of a hexadecimal number, followed by a 2 character checksum.
The behavior is specified in the id12 datasheet, which can be quickly found on google, or here: http://dlnmh9ip6v2uc.cloudfront.net/datasheets/Sensors/ID/ID-2LA,%20ID-12LA,%20ID-20LA(2013-4-10).pdf . In the linked PDF, it is page 4.
If you would like some help parsing this data in java, please supply some actual read data, and the corresponding expected values belonging to that read data.
Good afternoon everybody!
I'm trying to create a simnple messagging application but I cannot find a solution to a big issue. Exactely there are two, big issues.
Here the code:
#Override
public void run() {
String incoming;
try {
while (true) {
if (!connected)
break;
// READING
if (reader.ready() && (incoming = reader.readLine()) != null) {
notifier.putCommand(incoming, this);
incoming = null;
}
// WRITING
synchronized (messagges) {
for (String message : messagges) {
System.out.println("SENDING MESSAGE TO CLIENT: " + message);
writer.println(message);
}
messagges.clear();
}
writer.println("b");
}
} catch (IOException e) {
MyLogger.log(e);
}
}
Problems:
If I don't every time write junk text to the client (writer.println("b")) I cannot read any message on the BufferedReader, sent from it. How is that possible?!
On client side I see only lots of "b" but anything sent inside the statement for (writer.println(message)). It's really strange, because when I print on the server SENDING MESSAGE TO CLIENT: [...] I see it in the console, but then the message is not sent.
What could it be the problem?
You need to read about how buffering works, and, in particular, learn to use the flush() method to instruct a buffered writer to actually send the data.