communication between android and fpga board - android

I am trying to transfer data from my android device to FPGA board. The android device supports the USB host mode and the connected FPGA board uses RS_232 port. So I got a USB-RS232 converter device(CP210x) for the connection. I coded the transfer as mentioned on this page: http://developer.android.com/guide/topics/connectivity/usb/host.html My code is:
public class MainActivity extends Activity
implements View.OnClickListener, Runnable {
private static final String TAG = "TransferData";
private Button sendB;
private UsbManager mUsbManager;
private UsbDevice mDevice;
private UsbDeviceConnection mConnection;
private UsbEndpoint mEndpointIntr;
private static final char DATA = 'A';
static UsbDevice device;
static int TIMEOUT = 0;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
sendB = (Button)findViewById(R.id.send);
sendB.setOnClickListener(this);
mUsbManager = (UsbManager)getSystemService(Context.USB_SERVICE);
}
#Override
public void onPause() {
super.onPause();
}
#Override
public void onResume() {
super.onResume();
Intent intent = getIntent();
Log.d(TAG, "intent: " + intent);
String action = intent.getAction();
device = (UsbDevice)intent.getParcelableExtra(UsbManager.EXTRA_DEVICE);
if (UsbManager.ACTION_USB_DEVICE_ATTACHED.equals(action)) {
setDevice(device);
} else if (UsbManager.ACTION_USB_DEVICE_DETACHED.equals(action)) {
if (mDevice != null && mDevice.equals(device)) {
setDevice(null);
}
}
}
#Override
public void onDestroy() {
super.onDestroy();
}
private void setDevice(UsbDevice device) {
Log.d(TAG, "setDevice " + device);
if (device.getInterfaceCount() != 1) {
Log.e(TAG, "could not find interface");
return;
}
else Log.w(TAG, "found interface");
UsbInterface intf = device.getInterface(0);
// device should have one endpoint
if (intf.getEndpointCount() == 0) {
Log.e(TAG, "could not find endpoint");
return;
}
else Log.w(TAG, "found endpoint");
// endpoint should be of type interrupt
Log.w("endpoint", "" + intf.getEndpointCount());
UsbEndpoint ep = intf.getEndpoint(1);
if (ep.getType() != UsbConstants.USB_ENDPOINT_XFER_BULK) {
Log.e(TAG, "endpoint is not interrupt type");
return;
}
else Log.w(TAG, "endpoint is interrupt");
mDevice = device;
mEndpointIntr = ep;
if (device != null) {
UsbDeviceConnection connection = mUsbManager.openDevice(device);
if (connection != null && connection.claimInterface(intf, true)) {
Log.d(TAG, "open SUCCESS");
mConnection = connection;
Thread thread = new Thread(this);
thread.start();
} else {
Log.d(TAG, "open FAIL");
mConnection = null;
}
}
}
private void sendCommand(char control) {
if (mConnection != null) {
byte[] message = new byte[1];
message[0] = (byte)control;
// Send command via a control request on endpoint zero
UsbInterface intf = device.getInterface(0);
UsbEndpoint endpoint = intf.getEndpoint(1);
mConnection.claimInterface(intf,true);
int res = mConnection.bulkTransfer(endpoint, message, message.length, TIMEOUT);
Log.w("data sent","result " + res);
}
}
public void onClick(View v) {
if (v == sendB) {
sendCommand(DATA);
}
}
#Override
public void run() {
ByteBuffer buffer = ByteBuffer.allocate(1);
UsbRequest request = new UsbRequest();
request.initialize(mConnection, mEndpointIntr);
byte status = -1;
request.queue(buffer, 1);
// send poll status command
sendCommand(DATA);
// wait for status event
if (mConnection.requestWait() == request) {
byte newStatus = buffer.get(0);
if (newStatus != status) {
Log.d(TAG, "got status " + newStatus);
status = newStatus;
}
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
}
} else {
Log.e(TAG, "requestWait failed, exiting");
}
}
I get success in opening device and I get send result as 1. But no data received is reflected as the FPGA board. What am I doing wromg?

Try to switch RX with TX on FPGA. Did other communcation work with this connection?
Is there a design on the FPGA which will serve the UART?

Related

Reading value of characteristic after connecting to service Bluetooth Low Energy Android

after the connection is established I want to read the value from the characteristic and save the value in a byte array.
Here is my function for the reading inside my BluetoothLeService:
public byte[] readWhiteAndIntensityCharacteristic() {
if (mBluetoothAdapter == null || mBluetoothGatt == null) {
Log.w(TAG, "BluetoothAdapter not initialized");
return null;
}
/*check if the service is available on the device*/
BluetoothGattService mCustomService = mBluetoothGatt.getService(UUID.fromString(UuidAdresssService));
if (mCustomService == null) {
Log.w(TAG, "Custom BLE Service not found");
return null;
}
/*get the read characteristic from the service*/
BluetoothGattCharacteristic mReadCharacteristic = mCustomService.getCharacteristic(UUID.fromString(UuidAdresssWhiteAndIntensityCharastic));
byte[] messageByte = mReadCharacteristic.getValue();
if (messageByte != null && messageByte.length > 0) {
final StringBuilder stringBuilder = new StringBuilder(messageByte.length);
for (byte byteChar : messageByte)
stringBuilder.append(String.format("%02X", byteChar));
s = "0x" + stringBuilder.toString();
Log.v("Scan Activity", s);
if (mBluetoothGatt.readCharacteristic(mReadCharacteristic) == false) {
Log.w(TAG, "Failed to read characteristic");
}
}
return messageByte;
}
This function get called inside my DeviceControlActivity:
public void getStartUpValue(){
Log.w(TAG, "Reading completed");}
if(mBluetoothLeService.readWhiteAndIntensityCharacteristic() == null)
{
Log.w(TAG, "FAILED Reading value failed");
}
startValue = mBluetoothLeService.readWhiteAndIntensityCharacteristic();
Log.w(TAG, "Reading completed");
}
I call the getStartUpValue function after the connection is established.
private final BroadcastReceiver mGattUpdateReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
final String action = intent.getAction();
if (BluetoothLeService.ACTION_GATT_CONNECTED.equals(action)) {
mConnected = true;
updateConnectionState(R.string.connected);
invalidateOptionsMenu();
} else if (BluetoothLeService.ACTION_GATT_DISCONNECTED.equals(action)) {
mConnected = false;
updateConnectionState(R.string.disconnected);
invalidateOptionsMenu();
clearUI();
} else if (BluetoothLeService.ACTION_GATT_SERVICES_DISCOVERED.equals(action)) {
// Show all the supported services and characteristics on the user interface.
mBluetoothLeService.getSupportedGattServices();
getStartUpValue();
} else if (BluetoothLeService.ACTION_DATA_AVAILABLE.equals(action)) {
displayData(intent.getStringExtra(BluetoothLeService.EXTRA_DATA));
}
}
};
The reading is failing everytime but sending values to the characteristic is no problem.
How can I fix this problem?
The solution is: mBluetoothGatt.readCharacteristic(mReadCharacteristic)
After the reading is finished a callback will be called.
Thanks to Andrew Vovk

BLuetooth Gatt Callback not working with new API for Lollipop

I currently have a method which writes to the BLE devices to beep it. My Bluetooth Callback goes as follows :
ReadCharacteristic rc = new ReadCharacteristic(context, ds.getMacAddress(), serviceUUID, UUID.fromString(myUUID), "") {
#Override
public void onRead() {
Log.w(TAG, "callDevice onRead");
try{Thread.sleep(1000);}catch(InterruptedException ex){}
WriteCharacteristic wc = new WriteCharacteristic(activity, context, getMacAddress(), serviceUUID, UUID.fromString(myUUID), ""){
#Override
public void onWrite(){
Log.w(TAG, "callDevice onWrite");
}
#Override
public void onError(){
Log.w(TAG, "callDevice onWrite-onError");
}
};
// Store data in writeBuffer
wc.writeCharacteristic(writeBuffer);
}
#Override
public void onError(){
Log.w(TAG, "callDevice onRead-onError");
}
};
rc.readCharacteristic();
My ReadCharacteristic implementation is as follows :
public class ReadCharacteristic extends BluetoothGattCallback {
public ReadCharacteristic(Context context, String macAddress, UUID service, UUID characteristic, Object tag) {
mMacAddress = macAddress;
mService = service;
mCharacteristic = characteristic;
mTag = tag;
mContext = context;
this.activity =activity;
final BluetoothManager bluetoothManager =
(BluetoothManager) mContext.getSystemService(Context.BLUETOOTH_SERVICE);
mBluetoothAdapter = bluetoothManager.getAdapter();
}
final private static String TAG = "ReadCharacteristic";
private Object mTag;
private String mMacAddress;
private UUID mService;
private UUID mCharacteristic;
private byte[] mValue;
private Activity activity;
private BluetoothAdapter mBluetoothAdapter;
private Context mContext;
private int retry = 5;
public String getMacAddress() {
return mMacAddress;
}
public UUID getService() {
return mService;
}
public UUID getCharacteristic() {
return mCharacteristic;
}
public byte[] getValue() { return mValue; }
public void onRead() {
Log.w(TAG, "onRead: " + getDataHex(getValue()));
}
public void onError() {
Log.w(TAG, "onError");
}
public void readCharacteristic(){
if (retry == 0)
{
onError();
return;
}
retry--;
final BluetoothDevice device = mBluetoothAdapter.getRemoteDevice(getMacAddress());
if (device != null) {
Log.w(TAG, "Starting Read [" + getService() + "|" + getCharacteristic() + "]");
final ReadCharacteristic rc = ReadCharacteristic.this;
device.connectGatt(mContext, false, rc);
}
}
#Override
public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) {
Log.w(TAG,"onConnectionStateChange [" + status + "|" + newState + "]");
if ((newState == 2)&&(status ==0)) {
gatt.discoverServices();
}
else{
Log.w(TAG, "[" + status + "]");
// gatt.disconnect();
gatt.close();
try
{
Thread.sleep(2000);
}
catch(Exception e)
{
}
readCharacteristic();
}
}
#Override
public void onServicesDiscovered(BluetoothGatt gatt, int status) {
Log.w(TAG,"onServicesDiscovered [" + status + "]");
BluetoothGattService bgs = gatt.getService(getService());
if (bgs != null) {
BluetoothGattCharacteristic bgc = bgs.getCharacteristic(getCharacteristic());
gatt.readCharacteristic(bgc);
}
}
#Override
public void onCharacteristicRead(BluetoothGatt gatt,
BluetoothGattCharacteristic characteristic,
int status) {
Log.w(TAG,"onCharacteristicRead [" + status + "]");
if (status == BluetoothGatt.GATT_SUCCESS) {
mValue = characteristic.getValue();
Log.w(TAG,"onCharacteristicRead [" + mValue + "]");
gatt.disconnect();
gatt.close();
onRead();
}
else {
gatt.disconnect();
gatt.close();
}
}
}
This current method works perfectly fine for devices running KitKat and below. But when I run the same function on Lollipop, it beeps the device a couple of times and then stops working. From then on wards, whenever I try to connect, it says the device is disconnected and gives me an error code of 257 in OnConnectionStateChanged method.
I also get this error whenever I call this method -
04-20 14:14:23.503 12329-12384/com.webble.xy W/BluetoothGatt﹕ Unhandled exception in callback
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.bluetooth.BluetoothGattCallback.onConnectionStateChange(android.bluetooth.BluetoothGatt, int, int)' on a null object reference
at android.bluetooth.BluetoothGatt$1.onClientConnectionState(BluetoothGatt.java:181)
at android.bluetooth.IBluetoothGattCallback$Stub.onTransact(IBluetoothGattCallback.java:70)
at android.os.Binder.execTransact(Binder.java:446)
IS there anyone who has faced the same problem? I never encountered the object to be null when ever I tried debugging.
The problem has been reported to Google as Issue 183108: NullPointerException in BluetoothGatt.java when disconnecting and closing.
A workaround is to call disconnect() when you want to close BLE connection - and then only call close() in the onConnectionStateChange callback:
public void shutdown() {
try {
mBluetoothGatt.disconnect();
} catch (Exception e) {
Log.d(TAG, "disconnect ignoring: " + e);
}
}
private final BluetoothGattCallback mGattCallback =
new BluetoothGattCallback() {
#Override
public void onConnectionStateChange(BluetoothGatt gatt,
int status, int newState) {
if (newState == BluetoothProfile.STATE_CONNECTED) {
} else if (newState == BluetoothProfile.STATE_DISCONNECTED) {
try {
gatt.close();
} catch (Exception e) {
Log.d(TAG, "close ignoring: " + e);
}
}
}
Here is my full source code (a class doing normal scan, directed scan - and discovering services):
public class BleObject {
public static final String ACTION_BLUETOOTH_ENABLED = "action.bluetooth.enabled";
public static final String ACTION_BLUETOOTH_DISABLED = "action.bluetooth.disabled";
public static final String ACTION_DEVICE_FOUND = "action.device.found";
public static final String ACTION_DEVICE_BONDED = "action.device.bonded";
public static final String ACTION_DEVICE_CONNECTED = "action.device.connected";
public static final String ACTION_DEVICE_DISCONNECTED = "action.device.disconnected";
public static final String ACTION_POSITION_READ = "action.position.read";
public static final String EXTRA_BLUETOOTH_DEVICE = "extra.bluetooth.device";
public static final String EXTRA_BLUETOOTH_RSSI = "extra.bluetooth.rssi";
private Context mContext;
private IntentFilter mIntentFilter;
private LocalBroadcastManager mBroadcastManager;
private BluetoothAdapter mBluetoothAdapter;
private BluetoothGatt mBluetoothGatt;
private BluetoothLeScanner mScanner;
private ScanSettings mSettings;
private List<ScanFilter> mScanFilters;
private Handler mConnectHandler;
public BleObject(Context context) {
mContext = context;
if (!context.getPackageManager().hasSystemFeature(PackageManager.FEATURE_BLUETOOTH_LE)) {
Log.d(TAG, "BLE not supported");
return;
}
BluetoothManager bluetoothManager = (BluetoothManager) context.getSystemService(Context.BLUETOOTH_SERVICE);
mBluetoothAdapter = bluetoothManager.getAdapter();
if (mBluetoothAdapter == null) {
Log.d(TAG, "BLE not accessible");
return;
}
mIntentFilter = new IntentFilter();
mIntentFilter.addAction(BluetoothAdapter.ACTION_STATE_CHANGED);
mIntentFilter.addAction(BluetoothDevice.ACTION_BOND_STATE_CHANGED);
mSettings = new ScanSettings.Builder().setScanMode(ScanSettings.SCAN_MODE_LOW_LATENCY).build();
mScanFilters = new ArrayList<ScanFilter>();
mConnectHandler = new Handler();
mBroadcastManager = LocalBroadcastManager.getInstance(context);
}
public boolean isEnabled() {
return (mBluetoothAdapter != null && mBluetoothAdapter.isEnabled());
}
private ScanCallback mScanCallback = new ScanCallback() {
#Override
public void onScanResult(int callbackType, ScanResult result) {
processResult(result);
}
#Override
public void onBatchScanResults(List<ScanResult> results) {
for (ScanResult result: results) {
processResult(result);
}
}
private void processResult(ScanResult result) {
if (result == null)
return;
BluetoothDevice device = result.getDevice();
if (device == null)
return;
Intent i = new Intent(Utils.ACTION_DEVICE_FOUND);
i.putExtra(Utils.EXTRA_BLUETOOTH_DEVICE, device);
i.putExtra(Utils.EXTRA_BLUETOOTH_RSSI, result.getRssi());
mBroadcastManager.sendBroadcast(i);
}
};
private final BluetoothGattCallback mGattCallback = new BluetoothGattCallback() {
#Override
public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) {
if (newState == BluetoothProfile.STATE_CONNECTED) {
if (gatt == null)
return;
BluetoothDevice device = gatt.getDevice();
if (device == null)
return;
Log.d(TAG, "BluetoothProfile.STATE_CONNECTED: " + device);
Intent i = new Intent(Utils.ACTION_DEVICE_CONNECTED);
i.putExtra(Utils.EXTRA_BLUETOOTH_DEVICE, device);
mBroadcastManager.sendBroadcast(i);
} else if (newState == BluetoothProfile.STATE_DISCONNECTED) {
Log.d(TAG, "BluetoothProfile.STATE_DISCONNECTED");
Intent i = new Intent(Utils.ACTION_DEVICE_DISCONNECTED);
mBroadcastManager.sendBroadcast(i);
// Issue 183108: https://code.google.com/p/android/issues/detail?id=183108
try {
gatt.close();
} catch (Exception e) {
Log.d(TAG, "close ignoring: " + e);
}
}
}
#Override
public void onServicesDiscovered(BluetoothGatt gatt, int status) {
if (gatt == null)
return;
for (BluetoothGattService service: gatt.getServices()) {
Log.d(TAG, "service: " + service.getUuid());
for (BluetoothGattCharacteristic chr: service.getCharacteristics()) {
Log.d(TAG, "char: " + chr.getUuid());
}
}
}
};
private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
final String action = intent.getAction();
if (BluetoothAdapter.ACTION_STATE_CHANGED.equals(action)) {
final int state = intent.getIntExtra(BluetoothAdapter.EXTRA_STATE, BluetoothAdapter.ERROR);
switch (state) {
case BluetoothAdapter.STATE_TURNING_OFF: {
Log.d(TAG, "BluetoothAdapter.STATE_TURNING_OFF");
break;
}
case BluetoothAdapter.STATE_OFF: {
Log.d(TAG, "BluetoothAdapter.STATE_OFF");
Intent i = new Intent(Utils.ACTION_BLUETOOTH_DISABLED);
mBroadcastManager.sendBroadcast(i);
break;
}
case BluetoothAdapter.STATE_TURNING_ON: {
Log.d(TAG, "BluetoothAdapter.STATE_TURNING_ON");
break;
}
case BluetoothAdapter.STATE_ON: {
Log.d(TAG, "BluetoothAdapter.STATE_ON");
Intent i = new Intent(Utils.ACTION_BLUETOOTH_ENABLED);
mBroadcastManager.sendBroadcast(i);
break;
}
}
} else if (BluetoothDevice.ACTION_BOND_STATE_CHANGED.equals(action)) {
final int state = intent.getIntExtra(BluetoothDevice.EXTRA_BOND_STATE, BluetoothDevice.ERROR);
final int prevState = intent.getIntExtra(BluetoothDevice.EXTRA_PREVIOUS_BOND_STATE, BluetoothDevice.ERROR);
if (state == BluetoothDevice.BOND_BONDED &&
prevState == BluetoothDevice.BOND_BONDING) {
if (mBluetoothGatt != null) {
BluetoothDevice device = mBluetoothGatt.getDevice();
if (device == null)
return;
Intent i = new Intent(Utils.ACTION_DEVICE_BONDED);
i.putExtra(Utils.EXTRA_BLUETOOTH_DEVICE, device);
mBroadcastManager.sendBroadcast(i);
}
}
}
}
};
// scan for all BLE devices nearby
public void startScanning() {
Log.d(TAG, "startScanning");
mScanFilters.clear();
// create the scanner here, rather than in init() -
// because otherwise app crashes when Bluetooth is switched on
mScanner = mBluetoothAdapter.getBluetoothLeScanner();
mScanner.startScan(mScanFilters, mSettings, mScanCallback);
}
// scan for a certain BLE device and after delay
public void startScanning(final String address) {
Log.d(TAG, "startScanning for " + address);
mScanFilters.clear();
mScanFilters.add(new ScanFilter.Builder().setDeviceAddress(address).build());
// create the scanner here, rather than in init() -
// because otherwise app crashes when Bluetooth is switched on
mScanner = mBluetoothAdapter.getBluetoothLeScanner();
mScanner.startScan(mScanFilters, mSettings, mScanCallback);
}
public void stopScanning() {
Log.d(TAG, "stopScanning");
if (mScanner != null) {
mScanner.stopScan(mScanCallback);
mScanner = null;
}
mScanFilters.clear();
}
public void connect(final BluetoothDevice device) {
Log.d(TAG, "connect: " + device.getAddress() + ", mBluetoothGatt: " + mBluetoothGatt);
mConnectHandler.post(new Runnable() {
#Override
public void run() {
setPin(device, Utils.PIN);
mBluetoothGatt = device.connectGatt(mContext, true, mGattCallback);
}
});
}
private void setPin(BluetoothDevice device, String pin) {
if (device == null || pin == null || pin.length() < 4)
return;
try {
device.setPin(pin.getBytes("UTF8"));
} catch (Exception e) {
Utils.logw("setPin ignoring: " + e);
}
}
// called on successful device connection and will toggle reading coordinates
public void discoverServices() {
if (mBluetoothGatt != null)
mBluetoothGatt.discoverServices();
}
public boolean isBonded(BluetoothDevice device) {
Set<BluetoothDevice> bondedDevices = mBluetoothAdapter.getBondedDevices();
if (bondedDevices == null || bondedDevices.size() == 0)
return false;
for (BluetoothDevice bondedDevice: bondedDevices) {
Log.d(TAG, "isBonded bondedDevice: " + bondedDevice);
if (bondedDevice.equals(device)) {
Log.d(TAG, "Found bonded device: " + device);
return true;
}
}
return false;
}
public void startup() {
try {
mContext.registerReceiver(mReceiver, mIntentFilter);
} catch (Exception e) {
Log.d(TAG, "registerReceiver ignoring: " + e);
}
}
public void shutdown() {
Log.d(TAG, "BleObject shutdown");
try {
mContext.unregisterReceiver(mReceiver);
} catch (Exception e) {
Log.d(TAG, "unregisterReceiver ignoring: " + e);
}
try {
stopScanning();
} catch (Exception e) {
Log.d(TAG, "stopScanning ignoring: " + e);
}
try {
mBluetoothGatt.disconnect();
} catch (Exception e) {
Log.d(TAG, "disconnect ignoring: " + e);
}
mConnectHandler.removeCallbacksAndMessages(null);
}
}
On each BLE event it broadcasts intents via LocalBroadcastManager.
Thanks for pointing the problem Shashank.
I have looked at the Google example and followed what they recommend, it works like a charm with my device.
You should call the close() function in your onUnbind and the disconnect() when you need to, for example when you quit your application.

How to retrieve packet in a VpnService

I have the following implementation of ToyVpnService which I got frome here
public class ToyVpnService extends VpnService implements Handler.Callback, Runnable {
private static final String TAG = "ToyVpnService";
private Handler mHandler;
private Thread mThread;
private ParcelFileDescriptor mInterface;
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
// The handler is only used to show messages.
if (mHandler == null) {
mHandler = new Handler(this);
}
// Stop the previous session by interrupting the thread.
if (mThread != null) {
mThread.interrupt();
}
// Start a new session by creating a new thread.
mThread = new Thread(this, "ToyVpnThread");
mThread.start();
return START_STICKY;
}
#Override
public void onDestroy() {
if (mThread != null) {
mThread.interrupt();
}
}
#Override
public boolean handleMessage(Message message) {
if (message != null) {
Toast.makeText(this, message.what, Toast.LENGTH_SHORT).show();
}
return true;
}
#Override
public synchronized void run() {
Log.i(TAG, "running vpnService");
try {
runVpnConnection();
} catch (Exception e) {
e.printStackTrace();
//Log.e(TAG, "Got " + e.toString());
} finally {
try {
mInterface.close();
} catch (Exception e) {
// ignore
}
mInterface = null;
mHandler.sendEmptyMessage(R.string.disconnected);
Log.i(TAG, "Exiting");
}
}
private boolean runVpnConnection() throws Exception {
configure();
FileInputStream in = new FileInputStream(mInterface.getFileDescriptor());
// Allocate the buffer for a single packet.
ByteBuffer packet = ByteBuffer.allocate(32767);
// We keep forwarding packets till something goes wrong.
while (true) {
// Assume that we did not make any progress in this iteration.
boolean idle = true;
// Read the outgoing packet from the input stream.
int length = in.read(packet.array());
if (length > 0) {
Log.i(TAG, "************new packet");
System.exit(-1);
while (packet.hasRemaining()) {
Log.i(TAG, "" + packet.get());
//System.out.print((char) packet.get());
}
packet.limit(length);
// tunnel.write(packet);
packet.clear();
// There might be more outgoing packets.
idle = false;
}
Thread.sleep(50);
}
}
public String getLocalIpAddress() {
try {
for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements(); ) {
NetworkInterface intf = en.nextElement();
for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements(); ) {
InetAddress inetAddress = enumIpAddr.nextElement();
Log.i(TAG, "****** INET ADDRESS ******");
Log.i(TAG, "address: " + inetAddress.getHostAddress());
Log.i(TAG, "hostname: " + inetAddress.getHostName());
Log.i(TAG, "address.toString(): " + inetAddress.getHostAddress().toString());
if (!inetAddress.isLoopbackAddress()) {
//IPAddresses.setText(inetAddress.getHostAddress().toString());
Log.i(TAG, "IS NOT LOOPBACK ADDRESS: " + inetAddress.getHostAddress().toString());
return inetAddress.getHostAddress().toString();
} else {
Log.i(TAG, "It is a loopback address");
}
}
}
} catch (SocketException ex) {
String LOG_TAG = null;
Log.e(LOG_TAG, ex.toString());
}
return null;
}
private void configure() throws Exception {
// If the old interface has exactly the same parameters, use it!
if (mInterface != null) {
Log.i(TAG, "Using the previous interface");
return;
}
// Configure a builder while parsing the parameters.
Builder builder = new Builder();
builder.setMtu(1500);
builder.addAddress(getLocalIpAddress(), 24);
try {
mInterface.close();
} catch (Exception e) {
// ignore
}
mInterface = builder.establish();
}
}
It seems to be receiving packets but I have no idea on how to read the data in the paclkets. the code seems to be incomplete (hence the tunnel.write(packet) that's commented out cause there isn't a variable tunnel). Is this the right way? or is there a better way of doing this?

android usb UsbDeviceConnection.bulkTransfer returns -1

I am trying to send commands to a POS printer from my android tablet. I have been able to get the basic connections wroking but now when I try to send data to the printer, the bulkTransfer returns -1. Please help me understand what is going on. The following is a modified broadcast receiver taken from the android site where I do all the data transfer.
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){
//call method to set up device communication
if(device.getVendorId() != 1659)
return;
UsbInterface intf = device.getInterface(0);
UsbEndpoint endpoint = intf.getEndpoint(0);
int direction = endpoint.getDirection();
UsbDeviceConnection connection = mUsbManager.openDevice(device);
connection.claimInterface(intf, forceClaim);
bytes = new byte[]{27, 64};
//**This returns -1 always**
int ret = connection.bulkTransfer(endpoint, bytes, bytes.length, TIMEOUT);
if(ret < 0)
{
Log.d("WTF", "Error happened!");
}
else if(ret == 0)
{
Log.d("WTF", "No data transferred!");
}
else
{
Log.d("WTF", "success!");
}
}
}
else {
Log.d(TAG, "permission denied for device " + device);
}
}
}
}
};

Android USB- "could not find endpoint"

I'm a beginner android programmer who is trying to set up some USB functionality with my tablet and a device. My program uses an Intent filter to find the device. I took the Android's MissileLauncherActivity.java example and rewrote it. I am getting a "could not find endpoint" error in logcat. Is there something wrong with my code, or could it be my device? LogCat is finding the error in the setDevice method where it is trying to find the OUT endpoint. Here is the code:
public class UsbTestActivity extends Activity implements Runnable {
private UsbManager mUsbManager;
private UsbDevice mDevice;
private UsbDeviceConnection mConnection;
private UsbEndpoint mEndpointIntr;
private static final String TAG = "UsbTestActivity";
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mUsbManager = (UsbManager)getSystemService(Context.USB_SERVICE);
}
#Override
public void onPause(){
super.onPause();
}
#Override
public void onResume(){
super.onResume();
Intent intent = getIntent();
Log.d(TAG, "intent: " + intent);
String action = intent.getAction();
UsbDevice device = (UsbDevice)intent.getParcelableExtra(UsbManager.EXTRA_DEVICE);
if (UsbManager.ACTION_USB_DEVICE_ATTACHED.equals(action)) {
setDevice(device);
} else if (UsbManager.ACTION_USB_DEVICE_DETACHED.equals(action)) {
if (mDevice != null && mDevice.equals(device)) {
setDevice(null);
}
}
}
#Override
public void onDestroy() {
super.onDestroy();
}
public void setDevice(UsbDevice device){
Log.d(TAG, "setDevice " + device);
if (device.getInterfaceCount() != 1) {
Log.e(TAG, "could not find interface");
return;
}
UsbInterface intf = device.getInterface(0);
// device should have one endpoint
if (intf.getEndpointCount() != 1) {
Log.e(TAG, "could not find endpoint");
return;
}
System.out.println("Got endpoint");
// endpoint should be of type interrupt
UsbEndpoint ep = intf.getEndpoint(0);
if (ep.getType() != UsbConstants.USB_ENDPOINT_XFER_INT) {
Log.e(TAG, "endpoint is not interrupt type");
return;
}
mDevice = device;
mEndpointIntr = ep;
if (device != null) {
UsbDeviceConnection connection = mUsbManager.openDevice(device);
if (connection != null && connection.claimInterface(intf, true)) {
Log.d(TAG, "open SUCCESS");
mConnection = connection;
Thread thread = new Thread(this);
thread.start();
} else {
Log.d(TAG, "open FAIL");
mConnection = null;
}
}
}
private void sendCommand(int control) {
synchronized (this) {
if (mConnection != null) {
byte[] message = new byte[1];
message[0] = (byte)control;
// Send command via a control request on endpoint zero
if(mConnection.controlTransfer(0x21, 0x9, 0x200, 0, message, message.length, 0) > 0){
Log.d(TAG, "Sending Failed");
}
}
}
}
public void run() {
ByteBuffer buffer = ByteBuffer.allocate(1);
UsbRequest request = new UsbRequest();
request.initialize(mConnection, mEndpointIntr);
byte status = -1;
while (true) {
// queue a request on the interrupt endpoint
request.queue(buffer, 1);
// send poll status command
if (mConnection.requestWait() == request) {
byte newStatus = buffer.get(0);
if (newStatus != status) {
Log.d(TAG, "got status " + newStatus);
status = newStatus;
sendCommand(7);
}
try {
Thread.sleep(100);
} catch (InterruptedException e) {
}
} else {
Log.e(TAG, "requestWait failed, exiting");
break;
}
}
}
}
// device should have one endpoint
if (intf.getEndpointCount() != 1) {
Log.e(TAG, "could not find endpoint");
return;
}
Looks like you are trying to work with a USB HID device and its OUT endpoint. But HID mandates the IN endpoint to be present - so getEndpointCount() will most likely return 2 instead of one. You will need to check which is the IN and which is OUT.

Categories

Resources