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);
}
}
}
}
};
Related
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
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.
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?
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.