Serial to USB Android application with health device - android

I am creating an Android application to let communicate my Galaxy Tablet with an health device, via serial to USB connection.
The code I implemented does not work! neither the OUT nor IN communication starts
Does someone has any idea?
public void recordData(View _view){
text = (TextView)findViewById(R.id.textView1);
manager=(UsbManager) getSystemService(Context.USB_SERVICE);
PendingIntent mPermissionIntent = PendingIntent.getBroadcast(this, 0, new Intent(ACTION_USB_PERMISSION), 0);
IntentFilter filter = new IntentFilter(ACTION_USB_PERMISSION);
registerReceiver(mUsbReceiver, filter);
HashMap<String, UsbDevice> deviceList = manager.getDeviceList();
Iterator<UsbDevice> deviceIterator = deviceList.values().iterator();
while(deviceIterator.hasNext()){
UsbDevice device = deviceIterator.next();
manager.requestPermission(device, mPermissionIntent);
text.setText(text.getText()+"\n"+device.getDeviceName());
}
}
private UsbManager manager=null;
private boolean forceClaim = true;
private UsbDeviceConnection connection;
private UsbEndpoint input = null,output=null;
private static final String ACTION_USB_PERMISSION = "com.android.example.USB_PERMISSION";
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) {
isRecording=true;
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
UsbInterface intf = device.getInterface(0);
connection = manager.openDevice(device);
connection.claimInterface(intf, forceClaim);
//connection settings
int op= connection.controlTransfer(0x40, 0, 0, 0, null, 0, 0);// reset //0x40
int op2= connection.controlTransfer(0x40, 0, 1, 0, null, 0, 0);//clear Rx
int op3= connection.controlTransfer(0x40, 0, 2, 0, null, 0, 0);// clear Tx
int op3b= connection.controlTransfer(0x40, 0x02, 0x0000, 0, null, 0, 0);//control flow
int op4= connection.controlTransfer(0x40, 0x03, 0x001A, 0, null, 0, 0);// baud rate 115200
int op5= connection.controlTransfer(0x40, 0x04, 0x0008, 0, null, 0, 0);//8 bit
int endPts = intf.getEndpointCount();
for(int e = 0; e < endPts; e++){
UsbEndpoint endpoint = intf.getEndpoint(e);
endpoint.getAttributes();
if( endpoint.getType() == UsbConstants.USB_ENDPOINT_XFER_BULK){
if(endpoint.getDirection() == UsbConstants.USB_DIR_IN){
input = endpoint;
Log.d("Endpoint", "Got input");
}else if(endpoint.getDirection() == UsbConstants.USB_DIR_OUT){
output = endpoint;
Log.d("Endpoint", "Got output");
}
}
}
text.setText(text.getText()+"\nOut= "+String.valueOf(output.getEndpointNumber()));
text.setText(text.getText()+"\nIn= "+String.valueOf(input.getEndpointNumber()));
byte [] buffer = {77}; // M\n in ascii
for (int i = 0; i < buffer.length; ++i)
{
connection.bulkTransfer(output, new byte[] {buffer[i]}, 1, 0);
}
read();
}
}
else {
//error
}
}
}
}
};
//read thread
private void read() {
Runnable r = new Runnable() {
byte[] buffer = new byte[64];
byte[] buffer2;
public void run() {
while (isRecording) {
{
int op = connection.bulkTransfer(input, buffer, 64, 0);
if (op > 2) {
buffer2 = new byte[op];
for (int i = 0; i < op - 2; ++i) {
buffer2[i] = buffer[i+2];
text.setText(text.getText()+"\n"+String.valueOf(buffer2[i]));
}
}
}
}
}
};
Thread t = new Thread(r);
t.start();
Thank you very much!

Before trying to send the bytes you have to control the transaction first:
Use:
// for writing to USB with 9600 baudrate
connection.controlTransfer(0x00000000, 0x03, 0x4138, 0, null, 0, 0);
and
// for reading from USB with 9600 baudrate
connection.controlTransfer(0x00000080, 0x03, 0x4138, 0, null, 0, 0);
Reference:
http://developer.android.com/guide/topics/connectivity/usb/host.html
http://developer.android.com/reference/android/hardware/usb/UsbConstants.html

Related

Problem with Arduino Circuit (RGB Led with potentiometers and push button

This is the circuit that i made: the request is a button that when i push it switch on the rgb led with 3 potentiometers:
This is the code that i've written:
// C++ code
int analogPin = A0;
int potVal = 0;
int button = 0;
void setup()
{
pinMode(13, INPUT);
pinMode(11, OUTPUT);
pinMode(10, OUTPUT);
pinMode(9, OUTPUT);
Serial.begin(9600);
}
void loop()
{
potVal= analogRead(analogPin); //reads the potentiometer fro, 0-1023
button = digitalRead(2); // reads the button
if (button == HIGH)
{
analogWrite(11, 230); //0 -255
analogWrite(10, 100);
analogWrite(9, 13);
delay(potVal);
analogWrite(11, 80); //0 -255
analogWrite(10, 100);
analogWrite(9, 13);
delay(potVal);
analogWrite(11, 20); //0 -255
analogWrite(10, 200);
analogWrite(9, 13);
delay(potVal);
Serial.print("Pushbutton = ");
Serial.println(button);
Serial.print("Delay = ");
Serial.println(potVal);
}
else
{
analogWrite(11, 0);
analogWrite(10, 0);
analogWrite(9, 0);
Serial.print("Pushbutton = ");
Serial.println(button);
Serial.print("Delay = ");
Serial.println(potVal);
}
}
However I continue to have problems with it and I have no idea why. I've tried to follow all the links but how can I manage these 3 potentiometers? Thanks in advance!

Start VPN Connection

I want to develop an App for some internal Company stuff. However this needs VPN connection with a .p12 certificate.
Is there a way, that I can open a VPN connection in the App with this certificate? Or maybe an easier possibility automatically open the VPN App and connect to the chosen VPN.
Yes you can do by following:
Intent intent = VpnService.prepare(StatePermissionActivity.this);
if (intent != null) {
startActivityForResult(intent, 0);
}
Make a VPN Service:
public class UtilityVpnService extends VpnService {
//https://android.googlesource.com/platform/frameworks/base/+/master/core/java/android/net/VpnService.java
// http://stackoverflow.com/questions/32173374/packet-sent-but-cannot-received-packets
Builder builder;
private ParcelFileDescriptor mInterface;
private Thread mThread;
private IBinder mBinder = new MyBinder();
public static String VPN_STATE = "VPN_STATE";
public static int VPN_SERVICE_STOPPED = 1;
public static int VPN_SERVICE_STARTED = 2;
public static int VPN_SERVICE_RESUMED = 3;
public static int BLOCK_SINGLE_APP = 4;
public static int ALLOW_SINGLE_APP = 5;
public static int PACKAGE_NAME = 6;
public UtilityVpnService() {
}
#Override
public void onCreate() {
Context context = this;
Notification notification;
Intent notificationIntent = new Intent();
notificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0,
notificationIntent, 0);
NotificationCompat.Builder bBuilder = new NotificationCompat.Builder(context);
Intent vpnIntent = new Intent(context, UtilityVpnService.class);
context.startService(vpnIntent);
notification = bBuilder.build();
notification.flags |= Notification.FLAG_FOREGROUND_SERVICE;
notification.flags |= Notification.FLAG_NO_CLEAR;
notification.flags |= Notification.FLAG_ONGOING_EVENT;
startForeground(54312, notification);
super.onCreate();
}
#Override
public IBinder onBind(Intent intent) {
return mBinder;
}
#Override
public void onRebind(Intent intent) {
super.onRebind(intent);
}
#Override
public boolean onUnbind(Intent intent) {
return true;
}
public class MyBinder extends Binder {
public UtilityVpnService getService() {
return UtilityVpnService.this;
}
}
public void closeVpnInterface() {
try {
if (mInterface != null) {
mInterface.close();
}
} catch (Exception ex) {
ex.printStackTrace();
}
stopSelf();
}
#Override
public void onTaskRemoved(Intent rootIntent) {
Intent restartService = new Intent(getApplicationContext(), this.getClass());
restartService.setPackage(getPackageName());
PendingIntent restartServicePI = PendingIntent.getService(getApplicationContext(), 1, restartService,
PendingIntent.FLAG_ONE_SHOT);
//Restart the service once it has been killed android
AlarmManager alarmService = (AlarmManager) getApplicationContext().getSystemService(Context.ALARM_SERVICE);
alarmService.set(AlarmManager.ELAPSED_REALTIME, SystemClock.elapsedRealtime() + 100, restartServicePI);
alarmService.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), 1000, restartServicePI);
}
#Override
public void onTrimMemory(int level) {
super.onTrimMemory(level);
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Context context = this;
initilizeVpnBuilder();
if (!CheckServiceIsRunning.isMyServiceRunning(RunningAppsIdentify.class, this)) {
Intent vpnIntent = new Intent(context, RunningAppsIdentify.class);
context.startService(vpnIntent);
}
return START_STICKY;
}
private void initilizeVpnBuilder() {
mThread = new Thread(new Thread() {
#Override
public void run() {
try {
// try {
// if (builder != null) {
// mInterface.close();
// }
// } catch (Exception ex) {
// ex.printStackTrace();
// }
// Configure the tunnel and get the interface.
// Build VPN service
builder = new Builder();
builder.setSession(getString(R.string.app_name));
// VPN address
builder.addAddress("10.1.10.1", 32);
builder.addAddress("fd00:1:fd00:1:fd00:1:fd00:1", 128);
// DNS address
builder.addDnsServer("8.8.8.8");
// Add Route
builder.addRoute("0.0.0.0", 0);
builder.addRoute("0:0:0:0:0:0:0:0", 0);
//Setting Applications which are allowed Internet
// and isInternetAllowed = True
List<AppsModel> list = AppsModel.getAppsAllowedForInternet();
for (int i = 0; i < list.size(); i++) {
builder.addDisallowedApplication(list.get(i).getAppPackage());
}
//Establish interface
mInterface = builder.establish();
// Add list of allowed applications
// Packets to be sent are queued in this input stream.
FileInputStream inputStream = new FileInputStream(mInterface.getFileDescriptor());
// Packets recieved need to be written to this output stream.
FileOutputStream outputStream = new FileOutputStream(mInterface.getFileDescriptor());
DatagramChannel tunnel = DatagramChannel.open();
tunnel.connect(new InetSocketAddress("127.0.0.1", 8087));
protect(tunnel.socket());
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
reader.mark(123);
reader.markSupported();
ByteBuffer packet = ByteBuffer.allocate(32767);
//byte[] bytes = extract(inputStream);
//byteBuffer.put(bytes,0,bytes.length);
// We keep forwarding packets till something goes wrong.
while (true) {
// Assume that we did not make any progress in this iteration.
try {
//Utils.getWifiSpeed(UtilityVpnService.this);
// Read the outgoing packet from the input stream.
int length = inputStream.read(packet.array());
if (length > 0) {
//Log.d("packet received", "" + length);
packet.limit(length);
tunnel.write(packet);
// Getting info about the packet..
//debugPacket(packet);
packet.clear();
// reading incoming packet from tunnel.
length = tunnel.read(packet);
if (length > 0) {
outputStream.write(packet.array());
packet.clear();
}
}
} catch (IOException ex) {
ex.printStackTrace();
}
// String line = reader.readLine();
// if (line != null)
// Log.d("line", "" + line);
// Instructions
//get packet with in
//put packet to tunnel
//get packet from tunnel
// return packet with out
Thread.sleep(100);
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
});
mThread.start();
}
#Override
public void onRevoke() {
super.onRevoke();
stopSelf();
}
private void debugPacket(ByteBuffer packet) {
int buffer = packet.get();
int version;
int headerlength;
version = buffer >> 4;
headerlength = buffer & 0x0F;
headerlength *= 4;
Log.d("Tag", "IP Version:" + version);
Log.d("Tag", "Header Length:" + headerlength);
String status = "";
status += "Header Length:" + headerlength;
buffer = packet.get(); //DSCP + EN
buffer = packet.getChar(); //Total Length
Log.d("Tag", "Total Length:" + buffer);
buffer = packet.getChar(); //Identification
buffer = packet.getChar(); //Flags + Fragment Offset
buffer = packet.get(); //Time to Live
buffer = packet.get(); //Protocol
Log.d("Tag", "Protocol:" + buffer);
status += " Protocol:" + buffer;
buffer = packet.getChar(); //Header checksum
String sourceIP = "";
buffer = packet.get(); //Source IP 1st Octet
sourceIP += ((int) buffer) & 0xFF;
sourceIP += ".";
buffer = packet.get(); //Source IP 2nd Octet
sourceIP += ((int) buffer) & 0xFF;
sourceIP += ".";
buffer = packet.get(); //Source IP 3rd Octet
sourceIP += ((int) buffer) & 0xFF;
sourceIP += ".";
buffer = packet.get(); //Source IP 4th Octet
sourceIP += ((int) buffer) & 0xFF;
Log.d("Tag", "Source IP:" + sourceIP);
status += " Source IP:" + sourceIP;
String destIP = "";
buffer = packet.get(); //Destination IP 1st Octet
destIP += ((int) buffer) & 0xFF;
destIP += ".";
buffer = packet.get(); //Destination IP 2nd Octet
destIP += ((int) buffer) & 0xFF;
destIP += ".";
buffer = packet.get(); //Destination IP 3rd Octet
destIP += ((int) buffer) & 0xFF;
destIP += ".";
buffer = packet.get(); //Destination IP 4th Octet
destIP += ((int) buffer) & 0xFF;
Log.d("Tag", "Destination IP:" + destIP);
status += " Destination IP:" + destIP;
try {
InetAddress addr = InetAddress.getByName(destIP);
String host = addr.getHostName();
Log.d("Tag", "Hostname:" + host);
} catch (UnknownHostException e) {
Log.d("Tag", "Unknown host");
}
}
#Override
public void onDestroy() {
if (mThread != null) {
mThread.interrupt();
}
super.onDestroy();
}
}
startService on onActivityResult()

BulkTransfer & Android USB API

I have a program in which I attempt to attach my android device to a webcam via USB. I'm having trouble with a few things, namely properly transferring data. I've tried using bulkTransfer and there seems to be no recognition of it being used. I've been trying to find examples that may assist me such as here but none are helping me - their structure seems to be better than mine but whenever I switch my program crashes on load.
I'm fairly confident my bytes declaration is also incorrect and I should be somehow forwarding my data there, but I'm unsure how. Any help in terms of how to data transfer and how to structure my code would be appreciated.
Some declarations:
private byte[] bytes = {1,2};
private static int TIMEOUT = 0;
private boolean forceClaim = true;
In On Create:
UsbDevice device = (UsbDevice) getIntent().getParcelableExtra(UsbManager.EXTRA_DEVICE);
UsbManager mUsbManager = (UsbManager) getSystemService(Context.USB_SERVICE);
HashMap<String, UsbDevice> deviceList = mUsbManager.getDeviceList();
Iterator<UsbDevice> deviceIterator = deviceList.values().iterator();
while(deviceIterator.hasNext()) {
device = deviceIterator.next();
PendingIntent mPermissionIntent = PendingIntent.getBroadcast(this,0,new Intent(ACTION_USB_PERMISSION), 0);
IntentFilter filter = new IntentFilter(ACTION_USB_PERMISSION);
registerReceiver(mUsbReceiver, filter);
mUsbManager.requestPermission(device, mPermissionIntent);
UsbDeviceConnection connection = mUsbManager.openDevice(device);
Log.d("CAM Connection", " " + connection);
Log.d("CAM UsbManager", " " + mUsbManager);
Log.d("CAM Device", " " + device);
UsbInterface intf = device.getInterface(0);
Log.d("CAM_INTF Interface!!!!", " " + intf );
UsbEndpoint endpoint = intf.getEndpoint(0);
Log.d("CAM_END Endpoint", " " + endpoint );
connection.claimInterface(intf, forceClaim);
StringBuilder sb = new StringBuilder();
if(connection.bulkTransfer(endpoint,bytes,bytes.length,TIMEOUT) < 2)
Log.d("test", "");
//Log.d("BULK", ""+ connection.bulkTransfer(endpoint, bytes, bytes.length, TIMEOUT)); //do in another thread
}
Additional relevant code:
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(EXTRA_PERMISSION_GRANTED, false)) {
if(device != null){
//call method to set up device communication
}
}
else {
Log.d("Deny:", "permission denied for device " + device);
}
}
}
}
};
one of your problem is on finding endpoints. endpoint0 is for controlling task and you should find the appropriate IN and OUT endpoints in your code.
UsbInterface usbInterfaceTemp = null;
usbInterface = null;
endpointIN = null;
endpointOUT = null;
for (int i = 0; i < usbGotPermiDVC.getInterfaceCount(); i++) {
usbInterfaceTemp = usbGotPermiDVC.getInterface(i);
if (usbInterfaceTemp.getEndpointCount() >= 2) {
for (int j = 0; j < usbInterfaceTemp.getEndpointCount(); j++) {
UsbEndpoint usbEndpointTemp = usbInterfaceTemp.getEndpoint(j);
if (usbEndpointTemp.getType() == UsbConstants.USB_ENDPOINT_XFER_BULK) {
if (usbEndpointTemp.getDirection() == UsbConstants.USB_DIR_IN) {
endpointIN = usbEndpointTemp;
} else if (usbEndpointTemp.getDirection() == UsbConstants.USB_DIR_OUT) {
endpointOUT = usbEndpointTemp;
}
}
}
}
}
if (endpointIN != null && endpointOUT != null) {
usbInterface = usbInterfaceTemp;
}
if (usbInterface == null) {
return;
}
usbDeviceConnection = usbManager.openDevice(usbSelectedDevice);
if (!(usbDeviceConnection != null && usbDeviceConnection.claimInterface(usbInterface, true))) {
usbDeviceConnection = null;
return;
}
usbDeviceConnection.controlTransfer(0x21, 34, 0, 0, null, 0, 0);
usbDeviceConnection.controlTransfer(0x21, 32, 0, 0, new byte[]{(byte) 0x80,
0x25, 0x00, 0x00, 0x00, 0x00, 0x08}, 7, 0);
Toast.makeText(getApplicationContext(), "Device opened and Interface claimed!", Toast.LENGTH_SHORT).show();
in which usbGotPermiDVC is the device that got the permission to access via USB.

Data transfer from USB(prolific) to android device

I found a question posted for reading of USB data for FTDI devices.
Transferring data USB
I used this code for prolific device, and the usb can be detected, etc except that the the conn.bulkTransfer() gives a -1.
private class UsbRunnable implements Runnable {
private final UsbDevice mDevice;
UsbRunnable(UsbDevice dev) {
mDevice = dev;
}
public void run() {//here the main USB functionality is implemented
UsbDeviceConnection conn = mUsbManager.openDevice(mDevice);
if (!conn.claimInterface(mDevice.getInterface(1), true)) {
l("in run(), no connection");
return;
}
l("in run(), connection");
conn.controlTransfer(0x40, 0, 0, 0, null, 0, 0);// reset
// mConnection.controlTransfer(0×40,
// 0, 1, 0, null, 0,
// 0);//clear Rx
conn.controlTransfer(0x40, 0, 2, 0, null, 0, 0);// clear Tx
conn.controlTransfer(0x40, 0x02, 0x0000, 0, null, 0, 0);// flow
// control
// none
conn.controlTransfer(0x40, 0x03, 0xC04E, 0, null, 0, 0);// baudrate
// 38400
conn.controlTransfer(0x40, 0x04, 0x0008, 0, null, 0, 0);// data bit
// 8, parity
// none,
// stop bit
// 1, tx off
UsbEndpoint epIN = null;
UsbEndpoint epOUT = null;
byte counter=0;
//conn.bulkTransfer(epOUT, new byte[]{msData}, 1, 0);
UsbInterface usbIf = mDevice.getInterface(0);
for (int i = 0; i < usbIf.getEndpointCount(); i++) {
l("EP: "
+ String.format("0x%02X", usbIf.getEndpoint(i)
.getAddress()));
l("Type:"+usbIf.getEndpoint(i).getType());
if (usbIf.getEndpoint(i).getType() == UsbConstants.USB_ENDPOINT_XFER_INT) {
l("Bulk Endpoint");
l("direction: "+usbIf.getEndpoint(i).getDirection());
if (usbIf.getEndpoint(i).getDirection() == UsbConstants.USB_DIR_IN)
epIN = usbIf.getEndpoint(i);
}
else l("no bulk");
l("epIN: "+epIN.toString());
}
for (;;) {// this is the main loop for transferring
try {
Thread.sleep(100);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// This is where it is meant to receive
byte[] buffer = new byte[38400];
StringBuilder str = new StringBuilder();
l("bulk transfer thing: " + conn.bulkTransfer(epIN, buffer, 38400, 1000));
if (conn.bulkTransfer(epIN, buffer, 38400, 1000) > 0 ) {
l("bulk transfer is success");
for (int i = 2; i < 64; i++) {
if (buffer[i] != 0) {
str.append((char) buffer[i]);
} else {
l(str);
break;
}
}
}
// this shows the complete string
l(str);
if (mStop) {
mConnectionHandler.onUsbStopped();
return;
}
l("sent " + counter);
counter++;
counter = (byte) (counter % 16);
}
}
}
// END MAIN LOOP
private BroadcastReceiver mPermissionReceiver = new PermissionReceiver(
new IPermissionListener() {
public void onPermissionDenied(UsbDevice d) {
l("Permission denied on " + d.getDeviceId());
}
});
private static interface IPermissionListener {
void onPermissionDenied(UsbDevice d);
}
public final static String TAG = "USBController";
private void l(Object msg) {
Log.d(TAG, ">==< " + msg.toString() + " >==<");
}
private void e(Object msg) {
Log.e(TAG, ">==< " + msg.toString() + " >==<");
}
Can anyone tell me what changes I need to make? Thank you in advance.
There are several issues.
I assume that the commented out line is where you're having problems. You may want to reformat your code indentation and supply more information. In any case, assuming that your issue is occurring here:
byte counter=0;
//conn.bulkTransfer(epOUT, new byte[]{msData}, 1, 0);
The immediate problem that I see - epOut, the endpoint to which you are sending data is null. So of course it will fail. You're sending data to nothing. I followed the link that you posted to the example code that you copied, they have a line showing:
epOUT = usbIf.getEndpoint(i);
I would strongly suggest at the very least, you first make sure you understand the original code or have it working in your own program before you start making changes. DON'T just copy the above line of code to "fix" your problem.

Transferring data USB

I am trying to send and receive data over USB, my device, the Acer Iconia A500 has everything needed to connect to the device and everything, that is fine and works properly, but when I try sending and receiving data it doesn't behave as expected. This is my code
for( ; ; ) { //this is the main loop for transferring
String get = "$getPos";
byte[] getBytes = get.getBytes();
conn.bulkTransfer( epOUT, getBytes, getBytes.length, 500 );
try {
Thread.sleep( 500 );
byte[] buffer = new byte[4096];
conn.bulkTransfer( epIN, buffer, 4096, 500 );
StringBuilder byStr = new StringBuilder();
for( int i = 0; i < buffer.length; i++ ) {
if( buffer[i] != 0 ) {
byStr.append( buffer[i] + ", " );
}
}
l( byStr );
}
catch( InterruptedException e ) {
e.printStackTrace();
}
if( mStop ) {
mStopped = true;
return;
}
l( "sent " + counter );
counter++;
counter = (byte)( counter % 16 );
}
Its meant to return an Array of bytes about 80 characters long but it only returns two bytes back which are 1 and 96, if there was a error on the USB devices end it would still return a few more then two. Is my code even close to correct? I based it of the USB to serial article by serverbox.
I was trying to send data over the wrong baud rate.
Here's the code that works. Posting it for everyone who is using FTDI devices and needs help.
private Runnable mLoop = new Runnable() {
#Override
public void run() {
UsbDevice dev = sDevice;
if (dev == null)
return;
UsbManager usbm = (UsbManager) getSystemService(USB_SERVICE);
UsbDeviceConnection conn = usbm.openDevice(dev);
l("Interface Count: " + dev.getInterfaceCount());
l("Using "
+ String.format("%04X:%04X", sDevice.getVendorId(),
sDevice.getProductId()));
if (!conn.claimInterface(dev.getInterface(0), true))
return;
conn.controlTransfer(0x40, 0, 0, 0, null, 0, 0);// reset
// mConnection.controlTransfer(0×40,
// 0, 1, 0, null, 0,
// 0);//clear Rx
conn.controlTransfer(0x40, 0, 2, 0, null, 0, 0);// clear Tx
conn.controlTransfer(0x40, 0x02, 0x0000, 0, null, 0, 0);// flow
// control
// none
conn.controlTransfer(0x40, 0x03, 0x0034, 0, null, 0, 0);// baudrate
// 57600
conn.controlTransfer(0x40, 0x04, 0x0008, 0, null, 0, 0);// data bit
// 8, parity
// none,
// stop bit
// 1, tx off
UsbEndpoint epIN = null;
UsbEndpoint epOUT = null;
byte counter = 0;
UsbInterface usbIf = dev.getInterface(0);
for (int i = 0; i < usbIf.getEndpointCount(); i++) {
l("EP: "
+ String.format("0x%02X", usbIf.getEndpoint(i)
.getAddress()));
if (usbIf.getEndpoint(i).getType() == UsbConstants.USB_ENDPOINT_XFER_BULK) {
l("Bulk Endpoint");
if (usbIf.getEndpoint(i).getDirection() == UsbConstants.USB_DIR_IN)
epIN = usbIf.getEndpoint(i);
else
epOUT = usbIf.getEndpoint(i);
} else {
l("Not Bulk");
}
}
for (;;) {// this is the main loop for transferring
try {
Thread.sleep(100);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
String get = "$fDump G" + "\n";
l("Sending: " + get);
byte[] by = get.getBytes();
// This is where it sends
l("out " + conn.bulkTransfer(epOUT, by, by.length, 500));
// This is where it is meant to receive
byte[] buffer = new byte[4096];
StringBuilder str = new StringBuilder();
if (conn.bulkTransfer(epIN, buffer, 4096, 500) >= 0) {
for (int i = 2; i < 4096; i++) {
if (buffer[i] != 0) {
str.append((char) buffer[i]);
} else {
l(str);
break;
}
}
}
// this shows the complete string
l(str);
if (mStop) {
mStopped = true;
return;
}
l("sent " + counter);
counter++;
counter = (byte) (counter % 16);
}
}
};

Categories

Resources