Is there a way to log the binary data send to the tranceive method of a NFC tag? https://developer.android.com/reference/android/nfc/tech/NfcV.html#transceive(byte[])
I am trying to find the last few missing pieces in a protocol and it would help if I could listen to the data getting sent.
I'm guessing that:
You want to monitor the APDUs/bytes sent from an app you have installed.
You've already searched for info about that specific protocol and found nothing.
At the Logcat, no relevant info is shown (by default).
Looking up at the transceive source code
public byte[] transceive(byte[] data) throws IOException {
return transceive(data, true);
}
which redirects to:
byte[] transceive(byte[] data, boolean raw) throws IOException {
checkConnected();
try {
TransceiveResult result = mTag.getTagService().transceive(mTag.getServiceHandle(),
data, raw);
if (result == null) {
throw new IOException("transceive failed");
} else {
return result.getResponseOrThrow();
}
} catch (RemoteException e) {
Log.e(TAG, "NFC service dead", e);
throw new IOException("NFC service died");
}
}
Which goes on to the TransceiveResult class.
My best bet (if you wish to get to the very end) is to recompile an Android source code that prints out the data input'd to the byte[] transceive(byte[] data) function. Good luck.
EDIT: Another option I happened to realise is to use an APDU sniffer, although I legitimately don't know how legal this option is.
Related
I would like to create an application which can connect to a Bluetooth Headset via the Hands Free Protocol (HFP). I followed the Android example and have now a BluetoothSocket with its Input and OutputStream. Below you see my read and write methods (read method is executed by another Thread)
public void read() {
while (true) {
Log.d("ME", "Waiting for data");
try { // read until Exception is thrown
numBytes = inStream.read(dataBuffer);
String str = new String(dataBuffer,0,numBytes);
msgHandler.obtainMessage(numBytes, str).sendToTarget();
} catch (Exception e) {
Log.d("ME", "Input stream was disconnected", e);
break; // BluetoothDevice was disconnected => Exit
}
}
}
public void write(byte[] bytes) {
try {
outStream.write(bytes);
outStream.flush();
Log.e("ME", "Wrote: " + new String(bytes));
} catch (IOException e) {
Log.e("ME", "Error occurred when sending data", e);
}
}
When the connection is opened the Bluetooth headset sends AT+BRSF=191 over the InputStream. I tried to response with +BRSF:20\r but here is my problem. After that the device does not send any other data over the InputStream. It does not come to an Exception - it's more like the device does not know how to responde to my message. Do I send the wrong data? I have all the information from here: (HF = Hands-Free Unit AG = Audio Gateway)
Do you have any ideas what I did wrong? Have I missed something?
EDIT: These are my write calls:
write("+BRSF: 191\r");
write("OK\r");
You were missing the OK response. According to this document, the OK-code consists of a windows-style newline (CR LF), the literal OK and then another newline.
Do note that other commands are terminated by a carriage return only. For more information on the hands-free protocol, you can refer to that very document you linked in your post.
Example code:
public static final String OK = statusCode("OK")
public static final String ERROR = statusCode("ERROR")
public static String statusCode(String code) {
return "\r\n" + code + "\r\n";
}
public static String command(String cmd) {
return cmd + "\r";
}
Now you can use OK and ERROR in your code as constants, and you can use the statusCode method for other status codes.
I am using this example to communicate between arduino and android, and it works well.
The problem is that i would make sure all data has been received before outputting it.
As it is now android will simply output everything when it is being received.
I need to collect whatever is received so that i for example can compare it to another string.
Currently it works like this
UsbSerialInterface.UsbReadCallback mCallback = new UsbSerialInterface.UsbReadCallback() { //Defining a Callback which triggers whenever data is read.
#Override
public void onReceivedData(byte[] arg0) {
String data = null;
try {
data = new String(arg0, "UTF-8");
data.concat("/n");
tvAppend(textView, data);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
};
And arduino:
void setup()
{
Serial.begin(9600);
}
void loop()
{
char c;
if(Serial.available())
{
c = Serial.read();
Serial.print(c);
}
}
Example:
Sent to arduino:
TEST
Received from arduino:
TEST
However in reality its more like this
Sent to arduino:
TEST
Received from arduino:
T E ST
So the received "TEST" will come in bytes of one or two which then needs to be gathered into a string.
I assume the reason for this is due to the rate/speed of incoming bytes so that it will just output it as soon as it gets the data.
I would like to make sure that all incoming data is received before I output it, so that I can work with the incoming data.
In theory in need something like while(serial.available())... for android.
Any help is appreciated
I'm developing an Android real-time-data app that sends data (floats and ints) to a server on the local subnet via a TCP socket. The problem I'm facing is that after sending some data simultaneously the socket doesn't send anymore data at all. I debugged the app and it shows that data is being sent but doesn't show up on the server. After this happens if I close the connection the server doesn't even get the notification that the connection has been terminated which it should according to my design model. Meanwhile I get an exception on the app saying it can not write to a broken pipe. This tells me that the problem is with the app because I also did test using a desktop app and I can send huge amounts of data to the server and it gets delivered.
And please keep in mind that the data size I'm talking about here is 252 bytes per packet.
Here's my class I'm using. (This runs in an AsyncTask object )
public class Network
{
private Socket handle;
public static enum TASK
{
TASK_CONNECT, TASK_SEND, TASK_CLOSE
}
public Network()
{
}
public String lastError = "";
public boolean Connect(String host, int port)
{
try
{
lastError = "Connecting to server.";
handle = new Socket(host, port);
handle.setTcpNoDelay(true); //
handle.setSendBufferSize(SIZE_OF_PACKET); ///==> These don't seem to help at all
handle.setKeepAlive(true); ///
return true;
}catch(IOException e)
{
lastError += e.getMessage() != null ? " "+ e.getMessage() : "";
return false;
}
}
private void err(String e){
System.err.println(e);
}
private boolean SendPacket(byte buffer[])
{
OutputStream oStream = null;
err("sending: " + buffer.length + " bytes");
try
{
lastError = "Obtaining output stream.";
oStream = handle.getOutputStream();
lastError = "Error sending data.";
oStream.write(buffer);
oStream.flush();
return true;
}catch(Exception e)
{
lastError += e.getMessage() != null ? " "+ e.getMessage() : "";
}
return false;
}
public void Close()
{
try{ handle.close(); handle = null; }catch(Exception e){} // swallow exception
}
}
I send my data in a loop depending on how many numbers I have. I tried a Google search but didn't find anything relevant. Has anyone experienced this before? It's making me mad now.
EDIT: Wireshark shows incoming "red" packets that don't reach the desktop app (server)
Look at this picture.
You can see the first few have Len > 0 the red ones have 0.
I think it's time Google interfaced the USB so we can use it. At least that'd would have been my first option.
Should you not be calling oStream.close() after you flush the stream, given that you never use it again?
Also, you say that this is being run in an AsyncTask object. Is it possible that multiple threads could be attempting to send packets at the same time? If so, you might need some form of synchronisation around the SendPacket method.
Ok. I solved the issue by using UDP instead. Thank you all.
But I still didn't find the source of the problem.
So I have TCP server in Windows that is programmed in C++ and a client in JAVA, Android 4.0.4.
In Android, I connect like this:
public boolean sendConnectRequest()
{
while (isSocketConnected == false)
{
try {
if(comSocket == null)
comSocket = new Socket("192.168.0.1",1531);
isSocketConnected = comSocket.isConnected();
if (isSocketConnected) {
out = comSocket.getOutputStream();
in = comSocket.getInputStream();
}
else
comSocket.close();
}
catch (IOException ex)
{
Log.e("TCP Error", ex.getLocalizedMessage());
}
}
return true;
}
I typically have no problems with this code on the first connection to the server.
When i disconnect from the server, I call this:
public void closeConnection() {
if (comSocket != null)
{
try {
comSocket.close();
isSocketConnected = false;
if (out != null)
out.close();
if (in != null)
out.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
So here is the problem... I hit the home button on the smartphone, which places the program in pause. I start the program again and it calls the resume function in activity, which in turn starts the process toward reconnection. The connection is attempted and i get no errors. However, my Windows server records no connection. In Windows, I know that I am still blocked at:
SOCKET connectionSocket = accept(tcpNetworkData->socket, (struct sockaddr*)&from, &fromlen);
I believe this is normal. When I am in debug mode on the Android side, I notice that it returns immediately from the line: comSocket = new Socket("192.168.0.1",1531); This should indicate to me that a connection is made.
If you follow me so far... I should also say that if I shut the server down, the client resets by closing the connection and opening a new one. This time the comSocket = new Socket("192.168.0.1",1531) does not block as it should and the execution keeps going. This is obviously wrong. I think it is a resource release problem but why? With Winsock you can solve this problem with this line of code:
int so_reuseaddr = TRUE;
setsockopt(networkData->socket, SOL_SOCKET, SO_REUSEADDR, (const char*)&so_reuseaddr,sizeof(so_reuseaddr));
Can you do something similar with Android or do you have to? Thank you for your help!
According to the javadoc the connection is established once you call the constructor.
Socket(InetAddress address, int port)
Creates a stream socket and connects it to the specified port number at the specified IP address.
When you press the home button, your app goes in background but it does not get killed immediately, so your comSocket might be not null when you get back to your application. In that case you are not calling the constructor again, thus you are not reconnecting to the server. What you should do is
if(comSocket == null){
comSocket = new Socket("192.168.0.1",1531);
}else{
comSocket.connect(new InetSocketAddress("192.168.0.1",1531));
}
(and please please place the curly brackets :-) )
Something to keep in mind is that the isConnected() method isn't very reliable for detecting when the remote side has closed the connection, (here is an example).
You have to figure this out by reading or writing on the associated Input/Output Streams.
Try using PrintWriter.checkError(), which will return true as soon as the client can no longer connect to the server.
So this is the weirdest thing ever to happen to me during programing. Yes I'm no pro at programing, but I'm learning as I go. I've got an app talking to a server, a socket in the main thread, reading is done in a separate class and thread and writing in a separate class with asynctask.
The problem is LocationManager. I could talk to server and write/read commands just fine, I implemented the LocationManager and its listener.
I then proceeded to implement a method to update my textview with the new coordinates on locatinChanged. So far so good. Thing is when I use the Emulator control in eclipse and send coordinates the app crashed with a stringOutOfBoundsException (I've programed for 3 years now never seen this). I looked at the code stepped through it and so on. Read the stacktrace, logcat, console and everywhere I could think of but it got me nowhere. Until I finally went to the readerthread which looks like this:
public class ReaderThread extends Thread {
public void run() {
new Thread(new Runnable(){
public void run(){
try {
//Establish a bufferedreader to read from the socket/server.
in = new BufferedReader(new InputStreamReader(socket.getInputStream()), 8 * 1024);
}
catch(Exception e) { e.printStackTrace(); }
//As long as connect is true.
while (connected) {
String line;
try {
//Try to read a line from the reader.
line = in.readLine();
System.out.println(in.readLine());
if (in == null) {
//No one has sent a message yet.
System.out.println("No data recieved");
}
else {
int i = 0;
//As long as someone is sending messages.
while((line = in.readLine()) != null ){
//Make a new Message.
Message msg;
msg = new Message();
//Set the object to the input line.
msg.obj = line;
//Set an id so it can be identified in the main class and used in a switch.
msg.what = i;
System.out.println("i is: "+i);
//Send the message to the handler.
Main.this.h.sendMessage(msg);
}
}
}
catch (Exception e) {
System.out.println(e.getMessage());
}
}
}
}).start();
}
The variable i is in an if statement depending on what the server sent but I cut that out as it has nothing to do with this problem.
The problem is the freaking catch. When the catch is IOException, the app crashes. Out of dumb luck I changed this to Exception and printed e.message to catch the error and see what caused it. Thing is this change fixed it. How can switching IOException to just plain Exception fix a problem like this?
Its like with IOException the program says: "hey your not gonna catch the error but there is no error" but with Exception it says "Well now you could catch it so I'll proceed".
My app is working but I just can't grasp this, why and how does this happen?
You're essentially telling the application to catch the base Exception class. This means that any type of error will be caught, since all exception classes descend from that base type. Since StringOutOfBoundsException does not descend from IOException it was not being caught before and the error was not being caught. Instead of catching all exceptions, you might try the following:
try {
// Your code here...
} catch (IOException e) {
Log.e(TAG, "Caught an IOException!", e);
} catch (StringOutOfBoundsException e) {
Log.e(TAG, "Caught a string out of bounds Exception!", e);
}
I'm unable to determine what is actually throwing the StringOutOfBoundsException to begin with. It may be in the if statement that you cut out of your example.
while (connected) {
String line;
try {
//Try to read a line from the reader.
line = in.readLine();
System.out.println(in.readLine());
if (in == null) {
//No one has sent a message yet.
System.out.println("No data recieved");
}
The test for in == null is in a funny location. You should receive a NullPointerException if that test were to ever return true by nature of calling methods on it a few lines earlier. Obviously something is a little funny with this code.
You fail to save the return value from in.readLine() the second time you call it. I hope it did not contain anything useful. (Though, since you print the line, you obviously wanted to know what data it contained.)
Whatever that line was (from the first call to in.readLine()), it gets thrown away; there's nothing else in the loop that uses it before it is over-written on this line:
while((line = in.readLine()) != null ){
At this point, the two lines that you read are gone forever.
I'm not entirely sure what should be done to fix this; if it were me, I'd be sorely tempted to start over with a sheet of paper and sketch out what the method should be doing without looking at the existing code, then compare the sketch against the code to see which cases each one has overlooked.