I need to read/write to a smart-card using a smart-card reader attached to an Android phone by USB.
Is this possible with native APIs or do I have to install other libraries?
Thank you
In java the communication takes place using package javax.smarcard which is not available for Android so take a look here for getting an idea as to how you can communicate or send/receive APDU (smartcard command).
Using the USB Host API to connect :
:
//Allows you to enumerate and communicate with connected USB devices.
UsbManager mUsbManager = (UsbManager) getSystemService(Context.USB_SERVICE);
//Explicitly asking for permission
final String ACTION_USB_PERMISSION = "com.android.example.USB_PERMISSION";
PendingIntent mPermissionIntent = PendingIntent.getBroadcast(this, 0, new Intent(ACTION_USB_PERMISSION), 0);
HashMap<String, UsbDevice> deviceList = mUsbManager.getDeviceList();
UsbDevice device = deviceList.get("//the device you want to work with");
if (device != null) {
mUsbManager.requestPermission(device, mPermissionIntent);
}
And now you will need endpoints, simply send an APDU (smartcard command) over the bulk-out endpoint and expect to receive a response APDU over the bulk-in endpoint.
Code to get endpoints ::
UsbEndpoint epOut = null, epIn = null;
UsbInterface usbInterface;
UsbDeviceConnection connection = mUsbManager.openDevice(device);
for (int i = 0; i < device.getInterfaceCount(); i++) {
usbInterface = device.getInterface(i);
connection.claimInterface(usbInterface, true);
for (int j = 0; j < usbInterface.getEndpointCount(); j++) {
UsbEndpoint ep = usbInterface.getEndpoint(j);
if (ep.getType() == UsbConstants.USB_ENDPOINT_XFER_BULK) {
if (ep.getDirection() == UsbConstants.USB_DIR_OUT) {
// from host to device
epOut = ep;
} else if (ep.getDirection() == UsbConstants.USB_DIR_IN) {
// from device to host
epIn = ep;
}
}
}
}
To send commands use this :
public void write(UsbDeviceConnection connection, UsbEndpoint epOut, byte[] command) {
result = new StringBuilder();
connection.bulkTransfer(epOut, command, command.length, TIMEOUT);
//For Printing logs you can use result variable
for (byte bb : command) {
result.append(String.format(" %02X ", bb));
}
}
And to read data or send binary read you can use this code:
public int read(UsbDeviceConnection connection, UsbEndpoint epIn) {
result = new StringBuilder();
final byte[] buffer = new byte[epIn.getMaxPacketSize()];
int byteCount = 0;
byteCount = connection.bulkTransfer(epIn, buffer, buffer.length, TIMEOUT);
//For Printing logs you can use result variable
if (byteCount >= 0) {
for (byte bb : buffer) {
result.append(String.format(" %02X ", bb));
}
//Buffer received was : result.toString()
} else {
//Something went wrong as count was : " + byteCount
}
return byteCount;
}
Now let's take an example of this command like the one here: 62000000000000000000 How you can send this is :
write(connection, epOut, "62000000000000000000");
Now after you have successfully sent the APDU command, you can read the response using :
read(connection, epIn);
And receive something like
80 18000000 00 00 00 00 00 3BBF11008131FE45455041000000000000000000000000F1
Now the response received in the code here will be in the result variable of read() method.And likewise you can write your own commands for communicating.
Sadly there is no abstraction layer like PC/SC in the native Android system. But you can utilize Android USB library to talk directly to the USB smart card reader.
I am struggling on how to capture the audio stream from connected USB microphone. I have tried to use the MediaCapture with MediaRecorder.AudioSource.MIC as source which worked but recording quality isn't quite usable for me and you can't be sure if the audio source is really USB or the built in device microphone. What I need is to use the USB audio feature but so far I am unable to make any progress.
To use third-party libraries is overkill for me since I need to only receive the stream of audio data from the microphone, the rest of the processing is already done and working, only the audio source is the issue.
What I need to do is:
Check if there is USB microphone connected to the device.
Find out what characteristics this device has (supported sampling rates, channels etc.)
Record audio data
What I've done so far:
Generate a list of connected USB device which class is UsbConstants.USB_CLASS_AUDIO
private static final String ACTION_USB_PERMISSION = PACKAGE_NAME + ".USB_PERMISSION";
private UsbManager mUsbManAndroid;
private Map<String, UsbDevice> mAndroidDeviceMap;
private PendingIntent mPermissionIntent;
private ArrayList<UsbDeviceListItem> getUSBDevicesList() {
// Enumerate USB devices
mAndroidDeviceMap = mUsbManAndroid.getDeviceList();
ArrayList<UsbDeviceListItem> usbDevicesList = new ArrayList<>();
for (String key : mAndroidDeviceMap.keySet()) {
UsbDevice device = mAndroidDeviceMap.get(key);
// Check the device class
if (device.getDeviceClass() == UsbConstants.USB_CLASS_AUDIO) {
usbDevicesList.add(usbDeviceToListItem(key, device));
} else if (device.getDeviceClass() == UsbConstants.USB_CLASS_PER_INTERFACE) {
UsbInterface interface;
for (int i = 0; i < device.getInterfaceCount(); i++) {
// Check if at least one interface is audio
interface = device.getInterface(i);
if (interface != null && interface.getInterfaceClass() == UsbConstants.USB_CLASS_AUDIO) {
usbDevicesList.add(usbDeviceToSysBusUsbDevice(key, device));
break;
}
}
}
}
/////////////////////////////////////////////////////////
// Here goes some code to identify the device using
// linux shell commands if device SDK version is older
// than 21 (Lollipop). In older versions of Android
// we can't get device's Vendor and Device names using
// Android API, we need to use some linux shell commands.
/////////////////////////////////////////////////////////
return usbDevicesList;
}
Request permission for selected usb device from the list:
mUsbDeviceList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
UsbDeviceListItem usbDeviceItem = (UsbDeviceListItem) mUsbDeviceList.getItemAtPosition(i);
UsbDevice device = mAndroidDeviceMap.get(usbDeviceItem.getDevicePath());
manager.requestPermission(device, mPermissionIntent);
}
});
Permission broadcast receiver:
private final BroadcastReceiver mUsbReceiver = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (ACTION_USB_PERMISSION.equals(action)) {
synchronized (this) {
UsbDevice device = intent.getParcelableExtra(UsbManager.EXTRA_DEVICE);
if (intent.getBooleanExtra(UsbManager.EXTRA_PERMISSION_GRANTED, false)) {
if(device != null){
streamFromUsbDevice(device)
}
}
else {
Toast.makeText(SensorActivity.this, "Permission denied for device " + device,
Toast.LENGTH_SHORT).show();
}
}
}
}
};
Sample method for reading data from the USB device
private void streamFromUSBDevice(UsbDevice device) {
UsbEndpoint endpoint;
UsbInterface usbInterface;
////////////////////////////////////////////////////////////////
// Here was code for finding the first audio interface with its
// endpoint. But because I failed to make it work I was manually
// getting them by index.
////////////////////////////////////////////////////////////////
usbInterface = device.getInterface(2);
endpoint = usbInterface.getEndpoint(0);
if (endpoint == null) {
Log.i(TAG, getString(R.string.endpoint_not_found));
notifyUser(R.string.endpoint_not_found);
return;
}
Log.i(TAG, R.string.connecting_to_usb_device);
notifyUser(R.string.connecting_to_usb_device);
UsbDeviceConnection connection = manager.openDevice(device);
connection.claimInterface(usbInterface, true);
while (true) {
if (!isRecording) {
// Close the connection to the usb device
connection.close();
notifyUser(R.string.status_idle);
break;
}
UsbRequest request = new UsbRequest();
request.initialize(connection, endpoint);
byte[] buffer = new byte[endpoint.getMaxPacketSize()];
final ByteBuffer buf = ByteBuffer.wrap(buffer);
Log.i(TAG, "Requesting queue...");
if (!request.queue(buf, buffer.length)) {
Log.e(TAG, getString(R.string.error_queue_request)));
notifyUser(R.string.error_queue_request);
isRecording = false;
break;
}
Log.i(TAG, "Requesting response...");
final UsbRequest response = connection.requestWait();
if (response == null) {
Log.e(TAG, "Null response!");
notifyUser(R.string.null_response);
isRecording = false;
break;
}
final int nRead = buf.position();
if (nRead > 0) {
Log.i(TAG, "Streaming " + nRead + " bytes to UI");
Bundle args = new Bundle();
args.putShortArray(ARG_RECORDED_DATA, byte2short(buffer));
sendMessageToUI(SHOW_AUDIO_DATA_PACKET, args, null);
} else {
Log.e(TAG, "No data in buffer!");
notifyUser(R.string_empty_buffer);
isRecording = false;
break;
}
}
}
What I am getting from this is that request.queue() is always returning false.
I have also attempted to use the connection.bulkTransfer(endpoint, buffer, buffer.length, 0); method but the result is always -1.
If someone was in similar situation please help.
P.S. The error I am receiving in the log is: UsbRequestJNI: request is closed in native_queue.
I need your help, I'm trying to read some directory and trying to copy it to another place.
Now I can connect to usb host and read the usb specifications but i canĀ“t read the information on the usb to copy it.
this is my code
if (ACTION_USB_PERMISSION.equals(action)) {
synchronized (this) {
UsbDevice device = (UsbDevice) intent.getParcelableExtra(UsbManager.EXTRA_DEVICE);
if (intent.getBooleanExtra(UsbManager.EXTRA_PERMISSION_GRANTED, false)) {
if (device != null) {
//call method to set up device communication
byte[] bytes = new byte[0];
int TIMEOUT = 0;
boolean forceClaim = true;
intf = device.getInterface(0);
UsbEndpoint endpoint = intf.getEndpoint(0);
connection = manager.openDevice(device);
connection.claimInterface(intf, forceClaim);
bytes=connection.getRawDescriptors();
Toast.makeText(context,"PERMISO CONCEDIDO",Toast.LENGTH_SHORT).show();
ArrayList<String>directorios=new ArrayList<>();
directorios=ObtnerDirectorios("/storage/UsbDriveA");
String dir="";
for(int i=0; i<directorios.size();i++){
dir+=directorios.get(i)+"\n";
}
infotext.setText(dir);
}
} else {
Toast.makeText(context,"PERMISO DENEGADO",Toast.LENGTH_SHORT).show();
}
}
}
I read the google documentation and I think t have to use a bulktransfer and control transfer but I'm not sure.
Could you help me?
Thanks
I consider trying to compile a certain C-programm which allows the control of Gembird SilverShield power outlets via USB for android. On my android HDMI TV-stick this would be very useful. There is an open project for this. It works under Linux and depends on libusb. The target platform is android ICS. I want to develop on Ubuntu Linux. What are the chances I get it working? What are the required steps. Setup android SDK, NDK, crosscompiler ... There is an older question here, related to libusb on android but no information how. Is it maybe easier to port the application to androids own usb library?
Libusb can work on a non-rooted android (provided the device supports USB host ... this is VERY important as not all devices do). You need to use the standard android USB stack. You can then get a device descriptor from the USBDevice and pass that over to libusb.
Unfortunately you also need to modify libusb. Fortunately other people have explained how you need to modify LibUSB.
LibUSB has been modified here.
Good luck!
Edit:
First you need to define a broadcast receiver:
private final BroadcastReceiver mUsbReceiver = new BroadcastReceiver()
{
public void onReceive(Context context, Intent intent)
{
String action = intent.getAction();
if (ACTION_USB_PERMISSION.equals(action))
{
synchronized (this)
{
UsbDevice device = (UsbDevice)intent.getParcelableExtra(UsbManager.EXTRA_DEVICE);
if (intent.getBooleanExtra(UsbManager.EXTRA_PERMISSION_GRANTED, false))
{
if(device != null)
{
UsbDeviceConnection deviceConnection = mUsbManager.openDevice( device );
Log.d( "USB", deviceConnection.getSerial() );
}
}
else
{
Log.d( "USB", "permission denied for device " + device);
}
}
}
}
}
Now you need to create a USBManager and enumerate the devices:
mUsbManager = (UsbManager) getSystemService( Context.USB_SERVICE );
HashMap< String, UsbDevice > stringDeviceMap = mUsbManager.getDeviceList();
Collection< UsbDevice > usbDevices = stringDeviceMap.values();
mPermissionIntent = PendingIntent.getBroadcast(this, 0, new Intent( ACTION_USB_PERMISSION ), 0 );
IntentFilter filter = new IntentFilter(ACTION_USB_PERMISSION);
registerReceiver( mUsbReceiver, filter );
Iterator< UsbDevice > usbDeviceIter = usbDevices.iterator();
while( usbDeviceIter.hasNext() )
{
if ( USBDeviceValid( usbDevice ) )
{
// Request permission to access the device.
mUsbManager.requestPermission( usbDevice, mPermissionIntent );
// Open the device.
UsbDeviceConnection connection = mUsbManager.openDevice( usbDevice );
int fd = connection.getFileDescriptor();
// Now pass the file descriptor to libusb through a native call.
}
}
Edit 2:
Getting libusb to build is just a matter of putting the files somewhere handy (I put them in jni/libusb) and then adding the following lines to your Android.mk:
include $(CLEAR_VARS)
LOCAL_MODULE := libusb
LOCAL_SRC_FILES := libusb/core.c libusb/descriptor.c libusb/io.c libusb/sync.c libusb/os/linux_usbfs.c
LOCAL_LDLIBS := -llog
include $(BUILD_SHARED_LIBRARY)
The solution I implemented is to open the USB device using the Java APIs and then using the file descriptor with libusb.I used libusb from openni project by primesense(https://github.com/OpenNI/OpenNI2)
Code bits:
Opening the device(Using swig):
int LibUsbAndroid::android_open(libusb_device *device, libusb_device_handle **devHandle)
{
int fd = USBJNICallbacks::getCallback()->getDeviceFd(device->bus_number, device->device_address);
__android_log_print(ANDROID_LOG_VERBOSE,"USB","Got FD:%d",fd);
if(fd==-1)
{
__android_log_print(ANDROID_LOG_ERROR,"USB","android_open, bad fd");
return -1;
}
return libusb_open(device, devHandle, fd);
}
Opening the device in JAVA code(Not running on main thread!):
public int getDeviceFd(int busNumber, int deviceAddress) {
UsbDevice device = findDevice(busNumber, deviceAddress);
if(device!=null)
{
mReceivedPermission = false;
PermissionRequester pr = new PermissionRequester(device);
pr.run();
if(!mUsbManager.hasPermission(device))
{
Log.v("USB", "Requesting permissiom to device");
mPermissionIntent = PendingIntent.getBroadcast(mContext, 0, new Intent(ACTION_USB_PERMISSION), 0);
IntentFilter filterPermission = new IntentFilter(ACTION_USB_PERMISSION);
mContext.registerReceiver(mUsbPermissionReceiver, filterPermission);
mUsbManager.requestPermission(device, mPermissionIntent);
}
else
{
Log.v("USB", "Already has permission");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
mReceivedPermission = true;
Log.v("USB", "Opening device");
OpenDevice od = openDevice(device);
Log.v("USB", "Adding to open devices");
mOpenDevices.put(""+busNumber+"/"+deviceAddress, od);
}
Log.v("USB", "Waiting for permission");
waitForPermissionResult();
OpenDevice od = mOpenDevices.get(""+busNumber+"/"+deviceAddress);
if(od!=null)
{
Log.v("USB", "Getting FD");
int result = od.mConnection.getFileDescriptor();
Log.i("USB","USB File desc:"+result);
return result;
}
else
{
Log.v("USB", "Error getting FD");
return -1;
}
}
return -1;
}
Permission handling code:
private BroadcastReceiver mUsbPermissionReceiver=new BroadcastReceiver(){
#Override
public void onReceive(Context context, Intent intent) {
Log.v("USB", "Received permission result");
String action = intent.getAction();
if (ACTION_USB_PERMISSION.equals(action)) {
synchronized (this) {
UsbDevice device = (UsbDevice)intent.getParcelableExtra(UsbManager.EXTRA_DEVICE);
if (intent.getBooleanExtra(UsbManager.EXTRA_PERMISSION_GRANTED, false)) {
Log.v("USB", "Received permission result OK");
if(device != null){
Log.v("USB", "Device OK");
mContext.unregisterReceiver(this);
Log.v("USB", "Openning device");
OpenDevice od = openDevice(device);
Log.v("USB", "Adding to open device list");
mOpenDevices.put(""+od.mBus+"/"+od.mAddress,od);
Log.v("USB", "Received permission is true");
mReceivedPermission = true;
}
else {
Log.d(TAG, "permission denied for device " + device);
}
}
}
}
}
};
Open function:
public OpenDevice openDevice(UsbDevice device) {
UsbDeviceConnection connection = mUsbManager.openDevice(device);
Log.i("USB","Device name="+device.getDeviceName());
int bus = getBusNumber(device.getDeviceName());
int address = getAddress(device.getDeviceName());
return new OpenDevice(device, connection, bus, address);
}
USB lib change(core.c):
int API_EXPORTED libusb_open(libusb_device *dev,
libusb_device_handle **handle, int fd)
{
struct libusb_context *ctx = DEVICE_CTX(dev);
struct libusb_device_handle *_handle;
size_t priv_size = usbi_backend->device_handle_priv_size;
int r;
usbi_dbg("open %d.%d", dev->bus_number, dev->device_address);
_handle = malloc(sizeof(*_handle) + priv_size);
if (!_handle)
return LIBUSB_ERROR_NO_MEM;
r = usbi_mutex_init(&_handle->lock, NULL);
if (r) {
free(_handle);
return LIBUSB_ERROR_OTHER;
}
_handle->dev = libusb_ref_device(dev);
_handle->claimed_interfaces = 0;
memset(&_handle->os_priv, 0, priv_size);
r = usbi_backend->open(_handle,fd);
if (r < 0) {
usbi_dbg("open %d.%d returns %d", dev->bus_number, dev->device_address, r);
libusb_unref_device(dev);
usbi_mutex_destroy(&_handle->lock);
free(_handle);
return r;
}
usbi_mutex_lock(&ctx->open_devs_lock);
list_add(&_handle->list, &ctx->open_devs);
usbi_mutex_unlock(&ctx->open_devs_lock);
*handle = _handle;
/* At this point, we want to interrupt any existing event handlers so
* that they realise the addition of the new device's poll fd. One
* example when this is desirable is if the user is running a separate
* dedicated libusb events handling thread, which is running with a long
* or infinite timeout. We want to interrupt that iteration of the loop,
* so that it picks up the new fd, and then continues. */
usbi_fd_notification(ctx);
return 0;
}
op_open(libusb_fs.c) change:
static int op_open(struct libusb_device_handle *handle, int fd)
{
struct linux_device_handle_priv *hpriv = _device_handle_priv(handle);
char filename[PATH_MAX];
_get_usbfs_path(handle->dev, filename);
usbi_dbg("opening %s", filename);
hpriv->fd = fd;
if (hpriv->fd < 0) {
if (errno == EACCES) {
usbi_err(HANDLE_CTX(handle), "libusb couldn't open USB device %s: "
"Permission denied.", filename);
usbi_err(HANDLE_CTX(handle),
"libusb requires write access to USB device nodes.");
return LIBUSB_ERROR_ACCESS;
} else if (errno == ENOENT) {
usbi_err(HANDLE_CTX(handle), "libusb couldn't open USB device %s: "
"No such file or directory.", filename);
return LIBUSB_ERROR_NO_DEVICE;
} else {
usbi_err(HANDLE_CTX(handle),
"open failed, code %d errno %d", hpriv->fd, errno);
return LIBUSB_ERROR_IO;
}
}
return usbi_add_pollfd(HANDLE_CTX(handle), hpriv->fd, POLLOUT);
}
Even if you get it compiled, Android is probably not going to let you access the USB device through libusb unless your device is rooted. If it is feasible to port your app to Android's native USB stack, that would almost certainly be a more stable solution.
You can also try to use android serial port api
Here is example of serial port init.
private FileDescriptor mFd;
private FileInputStream mFileInputStream;
private FileOutputStream mFileOutputStream;
public SerialPort(File device, int baudrate, int flags) throws SecurityException, IOException {
/* Check access permission */
if (!device.canRead() || !device.canWrite()) {
try {
/* Missing read/write permission, trying to chmod the file */
Process su;
su = Runtime.getRuntime().exec("/system/bin/su");
String cmd = "chmod 666 " + device.getAbsolutePath() + "\n"
+ "exit\n";
su.getOutputStream().write(cmd.getBytes());
if ((su.waitFor() != 0) || !device.canRead()
|| !device.canWrite()) {
throw new SecurityException();
}
} catch (Exception e) {
e.printStackTrace();
throw new SecurityException();
}
}
mFd = open("/dev/ttyACM0", 9600, 0);
if (mFd == null) {
Log.e(TAG, "native open returns null");
throw new IOException();
}
mFileInputStream = new FileInputStream(mFd);
mFileOutputStream = new FileOutputStream(mFd);
}
So did it with use devices on USB host.
I have problems when I when to send messages via USB from the board to the devicersa.
Hardware:
Arduino ADK 2011
Samsung Galaxy S3, Android 4.1.2
The problem is the read method in the Android app never terminates and makes the thread get stuck:
mFileDescriptor = mUsbManager.openAccessory(accessory);
if (mFileDescriptor != null) {
mAccessory = accessory;
FileDescriptor fd = mFileDescriptor.getFileDescriptor();
Log.d(TAG, "openAccessory(): FileDescriptor instanciated. valid " + fd.valid());
mInputStream = new FileInputStream(fd);
mOutputStream = new FileOutputStream(fd);
new Thread(null, new Runnable() {
#Override
public void run() {
int ret = 0;
byte[] buffer = new byte[255];
while (ret >= 0 && mInputStream != null) {
try {
// never terminates
ret = mInputStream.read(buffer);
} catch (IOException e) {
Log.e(TAG, "openAccessory(): Could not read inputStream: " + e);
e.printStackTrace();
break;
}
} ...
The connection works fine since I use the special USB-library. When I connect the device the app opens automatically very well. But with logs I see it never passes the read command. Also the Arduinio monitor says that:
Device addressed... Requesting device descriptor.
found possible device. swithcing to serial mode
device supports protcol 1 or above
found android acessory device
config desc
interface desc
interface desc
2
4
Sending message...
Done
disconnect
The ADK sends messages, to the device in the loop (once):
sntmsg[0] = COMMAND_TEXT;
sntmsg[1] = TARGET_DEFAULT;
sntmsg[2] = 25;
for (int i = 0; i < 25; i++) {
sntmsg[3 + i] = hello[i];
}
// schreiben (buffer, length)
Serial.println("Sending message...");
acc.write(sntmsg, 3 + 25);
Serial.println("Done");
done = true;
delay(250);
Now I figured out the problem might be the disconnect. Immedeately after running through the first loop in the Arduiino code it prints disconnect to the monitor. The code in the libraries of AndroidAccessory.cpp is:
bool AndroidAccessory::isConnected(void)
{
USB_DEVICE_DESCRIPTOR *devDesc = (USB_DEVICE_DESCRIPTOR *) descBuff;
byte err;
max.Task();
usb.Task();
if (!connected &&
usb.getUsbTaskState() >= USB_STATE_CONFIGURING &&
usb.getUsbTaskState() != USB_STATE_RUNNING) {
Serial.print("\nDevice addressed... ");
Serial.print("Requesting device descriptor.\n");
err = usb.getDevDescr(1, 0, 0x12, (char *) devDesc);
if (err) {
Serial.print("\nDevice descriptor cannot be retrieved. Trying again\n");
return false;
}
if (isAccessoryDevice(devDesc)) {
Serial.print("found android acessory device\n");
connected = configureAndroid();
} else {
Serial.print("found possible device. swithcing to serial mode\n");
switchDevice(1);
}
} else if (usb.getUsbTaskState() == USB_DETACHED_SUBSTATE_WAIT_FOR_DEVICE) {
if (connected)
Serial.println("disconnect\n");
connected = false;
}
return connected;
}
So in the second loop this method returns false, even though the smartphone is still connected via usb. Do you know why it thinks it is dosconnected after the first loop iteration?
Thanks,
FL