Communicate with USB device on Android - java

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.

Related

Sending data from arduino to java

Hello im working on a project for myself. i have serveral RFID cards. I want to send a RFID code(cardID) to my arduino and then scan a random rfid card. if the sent RFID code and the one scaned are matching i want to send back a string/number or just one byte back to my java programm.
so far sending to my arduino and checking the RFID card is working fine however im stuck at sending something back to my java programm.
i was thinking about using serielConnection but tbh its very difficult to understand.
can someone help me out ?
thanks in advance
my java code
package test;
import java.io.IOException;
import com.fazecast.jSerialComm.SerialPort;
public class Startup {
public static void main(String[] args) throws IOException, InterruptedException {
SerialPort sp = SerialPort.getCommPort("COM4"); // device name TODO: must be changed
sp.setComPortParameters(115200, 8, 33, 34); // 9600,8,1,0default connection settings for Arduino
sp.setComPortTimeouts(SerialPort.TIMEOUT_WRITE_BLOCKING, 0, 0); // block until bytes can be written
if (sp.openPort()) {
System.out.println("Port is open :)");
} else {
System.out.println("Failed to open port :(");
return;
}
/*for (Integer i = 0; i < 5; ++i) {
sp.getOutputStream().write(i.byteValue());
sp.getOutputStream().flush();
System.out.println("Sent number: " + i);
Thread.sleep(4000); //default 1000
}
*/
//rfid tag 0x82,130
//rfid card 118
Integer i = 0;//0x82,130
sp.getOutputStream().write(i.byteValue());
sp.getOutputStream().flush();
System.out.println("Sent number: " + i);
Thread.sleep(8000);
if (sp.closePort()) {
System.out.println("Port is closed :)");
} else {
System.out.println("Failed to close port :(");
return;
}
//from arduino
}
}
arduino code:
#include <SPI.h>
#include <MFRC522.h>
#define RST_PIN 26
#define SS_PIN 5
#define MISO_PIN 19
#define MOSI_PIN 23
#define SCK_PIN 18
byte incomingByte = Serial.read();
MFRC522 mfrc522(SS_PIN, RST_PIN);
MFRC522::MIFARE_Key key;
void setup() {
Serial.begin(115200); // Initialize serial communications with the PC
pinMode(16,OUTPUT);
pinMode(21,OUTPUT);
while (!Serial); // Do nothing if no serial port is opened (added for Arduinos based on ATMEGA32U4)
SPI.begin(SCK_PIN, MISO_PIN, MOSI_PIN);
mfrc522.PCD_Init(); // Init MFRC522
delay(40); // Optional delay. Some board do need more time after init to be ready, see Readme
mfrc522.PCD_DumpVersionToSerial(); // Show details of PCD - MFRC522 Card Reader details
//dump_byte_array(key.keyByte, MFRC522::MF_KEY_SIZE);
}
void loop() {
if ( ! mfrc522.PICC_IsNewCardPresent()) {
return;
}
if ( ! mfrc522.PICC_ReadCardSerial()) {
return;
}
if(Serial.available() > 0){
byte incomingByte = Serial.read();
if (mfrc522.uid.uidByte[0] == incomingByte )/*&&*/ //それぞれ読んだカードの値と比較したい16進数の値を比較
)
{
digitalWrite(16,HIGH);
delay(5000);
digitalWrite(16,LOW);
delay(50);
}
else{
digitalWrite(21,HIGH);
delay(2000);
digitalWrite(21,LOW);
}
}
}
as i understand so far, for the arduino i just have to add this to send data from the arduino
SerielWrite(a number);
what is giving me a headache is how to receive it in java.
i already know that i need rxtx or jseriel libary for my java code.
i also already tryed some examples to recieve a number but it didnt work at all.
does someone maybe has a very easy code to receive a number in java ?
To recieve data in java from the arduino, you need a SerialDataListener to listen for data on the Serial Port. This can be done by creating a class which implements the SerialDataListener interface. This examples just prints to the console whatever data is read from the Serial Port but you can make it do whatever you'd like.
import com.fazecast.jSerialComm.*;
public class ComPortListener implements SerialPortDataListener {
private static String bufferReadToString = ""; // empty, but not null
private static int cutoffASCII = 10; // ASCII code of the character used for cut-off between received messages
#Override
public int getListeningEvents() {
return SerialPort.LISTENING_EVENT_DATA_AVAILABLE; //returns data on the Serial Port
}
#Override
public void serialEvent(SerialPortEvent event) {
byte[] buffer = new byte[event.getSerialPort().bytesAvailable()];
event.getSerialPort().readBytes(buffer, buffer.length);
String s = new String(buffer);
bufferReadToString = bufferReadToString.concat(s); //converts the bytes read from the Serial port to a string
if ((bufferReadToString.indexOf(cutoffASCII) + 1) > 0) {
System.out.println(bufferReadToString); //prints out the recived data
}
}
}
To use this, add the following code to your Startup class
if (sp.openPort()) {
System.out.println("Port is open :)");
ComPortListener listenerObject = new ComPortListener(); //creates new listener object
serialPort.addDataListener(listenerObject);
}

how to read the serial port on SWT text widget

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");
}
}
}

Receiving data from Terminal connected with USB->RS232

I'm developing a java application that need communicate with a terminal connected with a usb-to-rs232 converter!!
Right now I can connect with device and send data! I can be sure that the terminal receive the data sent because a led glow when the terminal receive something!
I'm using JSSC (Link: https://code.google.com/p/java-simple-serial-connector/wiki/jSSC_examples)... but for some reason I never never never receive any data FROM the Terminal.
My code (JSSC code):
public class Main
{
static SerialPort serialPort;
public static void main(String[] args) throws InterruptedException
{
serialPort = new SerialPort("COM7");
try
{
serialPort.openPort();//Open port
serialPort.setParams(9600, 8, 1, 0);//Set params
int mask = SerialPort.MASK_RXCHAR + SerialPort.MASK_CTS + SerialPort.MASK_DSR;//Prepare mask
serialPort.setEventsMask(mask);//Set mask
serialPort.addEventListener(new SerialPortReader());//Add SerialPortEventListener
serialPort.writeByte( (byte)0x02 );
TimeUnit.SECONDS.sleep( 10 );
byte[] b = serialPort.readBytes();
System.out.println( "bytes " + b );
}
catch (SerialPortException ex)
{
System.out.println(ex);
}
}
/*
* In this class must implement the method serialEvent, through it we learn about
* events that happened to our port. But we will not report on all events but only
* those that we put in the mask. In this case the arrival of the data and change the
* status lines CTS and DSR
*/
static class SerialPortReader implements SerialPortEventListener
{
public void serialEvent(SerialPortEvent event)
{
System.out.println( "Event raised!" );
if(event.isRXCHAR())
{//If data is available
if(event.getEventValue() == 10)
{//Check bytes count in the input buffer
//Read data, if 10 bytes available
try
{
byte buffer[] = serialPort.readBytes(10);
}
catch (SerialPortException ex)
{
System.out.println(ex);
}
}
}
else if(event.isCTS())
{//If CTS line has changed state
if(event.getEventValue() == 1)
{//If line is ON
System.out.println("CTS - ON");
}
else
{
System.out.println("CTS - OFF");
}
}
else if(event.isDSR())
{///If DSR line has changed state
if(event.getEventValue() == 1)
{//If line is ON
System.out.println("DSR - ON");
}
else
{
System.out.println("DSR - OFF");
}
}
}
}
}
Can anyone help me with this issue?
Did you intend to use hardware flow control with USB-UART. If yes, try setting DTR followed by RTS. This tells 1st end that 2nd end is ready for communication. Further does 10 bytes are not received or no data is received at all. Also consider another serial port communication library like scm http://www.embeddedunveiled.com/

My server is sending the information to my client twice. I dont know why

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.

Trying to get data from textfield to ouputstream for a chat program in Java

i'm working on a simple GUI chat program in Java. The goal is for the user to choose whether to host a server or to connect as a client. All of this works. The problem I'm having is letting either the client or the server chat. ideally, the user or the server can type into the textField and hit enter (or press the send button), and then the message will be sent to every client that is connected. During execution, the server runs an infinite while loop where it waits for more clients. The problem I'm having is two-fold:
1) I'm not sure if the way I'm passing the string to the inputstream is right, and 2) I don't know when I can have the server receive and then re-send the data, since it waits at server.accept().
here's the run method:
public void run()
{
conversationBox.appendText("Session Start.\n");
inputBox.requestFocus();
while (!kill)
{
if (isServer)
{
conversationBox.appendText("Server starting on port " + port + "\n");
conversationBox.appendText("Waiting for clients...\n");
startServer();
}
if (isClient)
{
conversationBox.appendText("Starting connection to host " + host + " on port " + port + "\n");
startClient();
}
}
}
here's the startClient method:
public void startClient()
{
try
{
Socket c = new Socket(host, port);
in = new Scanner(c.getInputStream());
out = new PrintWriter(c.getOutputStream());
while (true)
{
if (in.hasNext())
{
Chat.conversationBox.appendText("You Said: " + message);
out.println("Client Said: " + message);
out.flush();
}
}
}
catch (Exception e)
{
e.printStackTrace();
}
}
and here's the startServer method:
public void startServer()
{
try
{
server = new ServerSocket(port);
while (true)
{
s = server.accept();
conversationBox.appendText("Client connected from " + s.getLocalAddress().getHostName() + "\n");
}
}
catch (Exception e)
{
conversationBox.appendText("An error occurred.\n");
e.printStackTrace();
isServer = false;
reEnableAll();
}
}
And finally, here's the part of actionPerformed where I get the data and (attempt) to write it to the outputstream:
if (o == sendButton || o == inputBox)
{
if(inputBox.getText() != "")
{
out.println(inputBox.getText());
inputBox.setText("");
}
}
I guess my question is: How can I rearrange my methods so that the server can wait for text from the client and then send it back to all the clients? And, how do I send the text from the client to the server?
Among the problems with this code:
You keep creating clients and servers. Surely you should only do one of each?
You are performing blocking network operations on the event thread instead of in a separate thread.
You are looping at EOS via while (true) ... if in.hasNext(). This should be while (in.hasNext()) ...
You are accepting a socket and not apparently doing anything with it. It looks like you can only handle one client at a time. You should start a new thread to handle each accepted socket.

Categories