Please forgive me if I am not be able to elaborate my problem clearly.
I am trying to communicate with usb device and the which is getting successfully done
but i want to read from the usb device.
the code for the transferring the command is as follows.
public final static String TAG = "UsbClient";
private UsbManager mUsbManager;
private final int VID = 0x1fc9;
private final int PID = 0x0003;
private int toggle = 0;
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main_dummy,
container, false);
mUsbManager = (UsbManager) getActivity().getSystemService(Context.USB_SERVICE);
mPermissionIntent = PendingIntent.getBroadcast(getActivity(), 0, new Intent(ACTION_USB_PERMISSION), 0);
IntentFilter filter = new IntentFilter(ACTION_USB_PERMISSION);
getActivity().registerReceiver(mUsbReceiver, filter);
HashMap<String, UsbDevice> devlist = mUsbManager.getDeviceList();
Iterator<UsbDevice> deviter = devlist.values().iterator();
while (deviter.hasNext()) {
UsbDevice d = deviter.next();
print("Found device: "
+ String.format("%04X:%04X", d.getVendorId(),
d.getProductId()));
if (d.getVendorId() == VID && d.getProductId() == PID) {
mUsbManager.requestPermission(d, mPermissionIntent);
}
}
The code for the Registered Receiver is
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() == VID && device.getProductId() == PID) {
print("Got permission for the device");
permissionGranted = true;
UsbInterface intf = device.getInterface(0);
conn = mUsbManager.openDevice(device);
//intf=device.getInterface(0);
conn.claimInterface(intf, true);
/* if (!conn.claimInterface(device.getInterface(1), true)) {
print("Could not claim the interface");
return;
}
*/
int i = conn.controlTransfer(0x21, 0x09, 0x0200, 0x0000, new byte[] { (byte) toggle }, 1, 0);
endpoint=device.getInterface(0).getEndpoint(0);
if (toggle == 0) {
toggle = 1;
}
else {
toggle = 0;
}
if ((i == 0) || (i==1)) {
print("transfer successful");
}
else {
print("transfer failed");
}
}
}
}
else {
print("permission denied for device " + device);
}
}
}
}
};
Now i wanted to know the procedure to read the data from the usb device that is attached to the android tablet Using OTG cable.
and one more thing how to obtain the endpoints for read and write to the usb device.
Thanks in advance.
Related
I have a listViewwhich will display a list of paired bluetooth devices. I wanna capture the state inorder to update the paired listView whenever a new request to pair with my device gets accepted.
So far I have tried listening to BluetoothDevice.ACTION_ACL_CONNECTED but to no avail.
protected void onCreate(Bundle savedInstanceState) {
...
IntentFilter filter1 = new IntentFilter(BluetoothDevice.ACTION_ACL_CONNECTED);
this.registerReceiver(mReceiver, filter1);
}
//The BroadcastReceiver that listens for bluetooth broadcasts
private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
if (BluetoothDevice.ACTION_ACL_CONNECTED.equals(action)) {
getPairedDevices(); // get paired devices and update listView
}
}
First, to scan pair and unpair device, you can you this code
public void scanDevices(){
IntentFilter filter = new IntentFilter();
filter.addAction(BluetoothDevice.ACTION_FOUND);
filter.addAction(BluetoothAdapter.ACTION_STATE_CHANGED);
filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
activity.registerReceiver(mReceiverScan, filter);
bluetoothAdapter.startDiscovery();
}
public void pair(BluetoothDevice device){
activity.registerReceiver(mPairReceiver, new IntentFilter(BluetoothDevice.ACTION_BOND_STATE_CHANGED));
devicePair=device;
try {
Method method = device.getClass().getMethod("createBond", (Class[]) null);
method.invoke(device, (Object[]) null);
} catch (Exception e) {
if(discoveryCallback!=null)
discoveryCallback.onError(e.getMessage());
}
}
public void unpair(BluetoothDevice device) {
devicePair=device;
try {
Method method = device.getClass().getMethod("removeBond", (Class[]) null);
method.invoke(device, (Object[]) null);
} catch (Exception e) {
if(discoveryCallback!=null)
discoveryCallback.onError(e.getMessage());
}
}
private BroadcastReceiver mReceiverScan = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
switch (action) {
case BluetoothAdapter.ACTION_STATE_CHANGED:
final int state = intent.getIntExtra(BluetoothAdapter.EXTRA_STATE, BluetoothAdapter.ERROR);
if (state == BluetoothAdapter.STATE_OFF) {
if (discoveryCallback != null)
discoveryCallback.onError("Bluetooth turned off");
}
break;
case BluetoothAdapter.ACTION_DISCOVERY_FINISHED:
context.unregisterReceiver(mReceiverScan);
if (discoveryCallback != null)
discoveryCallback.onFinish();
break;
case BluetoothDevice.ACTION_FOUND:
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
if (discoveryCallback != null)
discoveryCallback.onDevice(device);
break;
}
}
};
private final BroadcastReceiver mPairReceiver = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
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(discoveryCallback!=null)
discoveryCallback.onPair(devicePair);
} else if (state == BluetoothDevice.BOND_NONE && prevState == BluetoothDevice.BOND_BONDED){
if(discoveryCallback!=null)
discoveryCallback.onUnpair(devicePair);
}
}
}
};
Finally, you can add these device to a list as
public List<BluetoothDevice> getPairedDevices(){
List<BluetoothDevice> devices = new ArrayList<>();
for (BluetoothDevice blueDevice : bluetoothAdapter.getBondedDevices()) {
devices.add(blueDevice);
}
return devices;
}
Don't forget to add permission in AndroidManifet.xml file
<uses-permission android:name="android.permission.BLUETOOTH" />
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
This is a good library that I used is
https://github.com/omaflak/Bluetooth-Library
And this is a sample app to use the above lib.
https://github.com/omaflak/Bluetooth-Android
I am attempting to connect a PIC microprocessor to a tablet app via usb. A Send button should trigger the sending of a string consist of "$$$" to the PIC. By a process of elimination, it appears to work down to the "requestWait" line at the bottom. The button stays highlighted and the app appears to hang. I suspect that no answer is arriving for the requestWait and so it waits indefinitely. I would appreciate some help. I have looked at the AdbTest and Missile Launcher apps but there is too much going on in them for my level of Android expertise.
Added later:
Looking at the code for UsbRequest queue(..), result = native_queue_direct(...).
I gather that this is native code. Where do I find it please?
import java.nio.ByteBuffer;
import java.util.HashMap;
import java.util.Iterator;
import android.content.Context;
import android.hardware.usb.UsbDevice;
import android.hardware.usb.UsbDeviceConnection;
import android.hardware.usb.UsbInterface;
import android.hardware.usb.UsbManager;
import android.hardware.usb.UsbRequest;
import android.view.View;
import android.widget.Toast;
#Override
protected void onResume() {
super.onResume();
mManager = (UsbManager) getSystemService(Context.USB_SERVICE);
// check for existing devices
UsbDevice device;
HashMap<String, UsbDevice> deviceList = mManager.getDeviceList();
Iterator<UsbDevice> deviceIterator = deviceList.values().iterator();
while (deviceIterator.hasNext()) {
device = deviceIterator.next();
if (device.getVendorId() == 1027) {
UsbInterface intf = device.getInterface(0);
if (setUsbInterface(device, intf)) {
break;
}
}
}
private UsbManager mManager;
private UsbDevice mDevice;
private UsbDeviceConnection mDeviceConnection;
private UsbInterface mInterface;
private ScorerDevice mScorerDevice ;
// ***********************************
// Sets the current USB device and interface
private boolean setUsbInterface(UsbDevice device, UsbInterface intf) {
if (mDeviceConnection != null) {
if (mInterface != null) {
mDeviceConnection.releaseInterface(mInterface);
mInterface = null;
}
mDeviceConnection.close();
mDevice = null;
mDeviceConnection = null;
}
if (device != null && intf != null) {
UsbDeviceConnection connection = mManager.openDevice(device);
if (connection != null) {
if (connection.claimInterface(intf, true)) {
toast = Toast.makeText(getApplicationContext(), "claim interface succeeded", Toast.LENGTH_SHORT);
toast.show();
mDevice = device;
mDeviceConnection = connection;
mInterface = intf;
mScorerDevice = new ScorerDevice(this, mDeviceConnection, intf);
toast = Toast.makeText(getApplicationContext(), "USB started", Toast.LENGTH_SHORT);
toast.show();
mScorerDevice.start();
return true;
} else {
toast = Toast.makeText(getApplicationContext(), "claim interface failed", Toast.LENGTH_SHORT);
toast.show();
connection.close();
}
} else {
toast = Toast.makeText(getApplicationContext(), "USB failed", Toast.LENGTH_SHORT);
toast.show();
}
}
if (mDeviceConnection == null && mScorerDevice != null) {
mScorerDevice.stop();
mScorerDevice = null;
}
return false;
}
// ***********************************
public int onClick_Send(View view) {
String dollars = "$$$";
byte[] bytes = dollars.getBytes();
int len = bytes.length;
int offset = 0;
int PacketSize = mScorerDevice.mEndpointOut.getMaxPacketSize();
if ((len > PacketSize) || (offset < 0) || (len < 0) || ((offset + len) > bytes.length))
throw new IndexOutOfBoundsException();
ByteBuffer sendBuffer = ByteBuffer.allocate(PacketSize);
UsbRequest request = new UsbRequest();
Boolean ret = request.initialize(mDeviceConnection, mScorerDevice.mEndpointOut);
if (!ret ) {
return -1;
}
ret = request.queue(sendBuffer, len);
if (!ret ) {
return -1;
}
request = mDeviceConnection.requestWait();
if (request == null) {
return -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);
}
}
}
}
};
I try to connect my archos Titanium HD to my RAMBo (http://reprap.org/wiki/Rambo). At the moment i can connect to the device and I find the USB_DIR_IN but when i Read from the connection i get null. What am I doing wrong?
public void onReceive(Context context, Intent intent) {
EditText myfield = (EditText) findViewById(R.id.editText1);
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){
myfield.setText(myfield.getText()+"start connection");
UsbInterface intf = device.getInterface(0);
UsbManager mUsbManager=(UsbManager) getSystemService(Context.USB_SERVICE);
UsbDeviceConnection connection = mUsbManager.openDevice(device);
if(connection.claimInterface(intf, forceClaim)){
for(int i=0;i<intf.getEndpointCount();i++){
UsbEndpoint endpoint = intf.getEndpoint(i);
if(endpoint.getDirection()== UsbConstants.USB_DIR_IN){
myfield.setText(myfield.getText()+"endpoint zum lesen:"+i);
int ret=connection.bulkTransfer(endpoint, mybytes, 20, TIMEOUT);
myfield.setText(myfield.getText()+"ret"+ret+" "+Arrays.toString(mybytes)+"first read");
}
else if(endpoint.getDirection()==UsbConstants.USB_DIR_OUT){
myfield.setText(myfield.getText()+"endpoint zum schreiben"+i);
}
else{
myfield.setText(myfield.getText()+"irgendein endpoint");
}
}
}
else{
myfield.setText(myfield.getText()+"verbindung nicht möglich");
}
//call method to set up device cmmunication
}
}
else {
myfield.setText("Permission denied");
//Log.d(TAG, "permission denied for device " + device);
}
}
}
}
};
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?