Sending and receiving data from an Android App via USB - 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;
}
}

Related

Android USB Otg printer

I am trying to print to usb printer zebra using the following code
As per documentation UsbDeviceConnection#bulkTransfer is value the length which is given in documentation ...#return length of data transferred (or zero) for success,or negative value for failure
My Code is below
package in.silentsudo.andoidprinter.usbprinter;
import android.app.Activity;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.hardware.usb.UsbDevice;
import android.hardware.usb.UsbDeviceConnection;
import android.hardware.usb.UsbEndpoint;
import android.hardware.usb.UsbInterface;
import android.hardware.usb.UsbManager;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.Map;
import in.silentsudo.andoidprinter.R;
public class MainActivity extends Activity {
private UsbManager mUsbManager;
private UsbDevice mUsbDevice;
private PendingIntent mPermissionIntent;
private UsbDeviceConnection usbConnection;
UsbEndpoint usbWriterEndpoint;
UsbInterface usbInterface;
private static final String ACTION_USB_PERMISSION = "in.silentsudo.usbprinter.USB_PERMISSION";
private StringBuffer logBuffer = new StringBuffer();
private TextView textView;
private Button button;
protected void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.activity_main);
textView = findViewById(R.id.txt_status);
button = findViewById(R.id.btn_print);
addLog("Creating usbConnection");
mUsbManager = (UsbManager) getSystemService(Context.USB_SERVICE);
String usbManagerString = mUsbManager == null ? "USBManager is null" : "USB manager is valid";
addLog(usbManagerString);
}
#Override
protected void onResume() {
super.onResume();
mPermissionIntent = PendingIntent.getBroadcast(this,
0,
new Intent(ACTION_USB_PERMISSION),
0);
IntentFilter filter = new IntentFilter(ACTION_USB_PERMISSION);
registerReceiver(mUsbReceiver, filter);
addLog("Registered received with filter :" + ACTION_USB_PERMISSION);
if (mUsbManager != null) {
if (mUsbManager.getDeviceList() != null && mUsbManager.getDeviceList().size() > 0) {
addLog("Total usb devices: " + mUsbManager.getDeviceList().size());
for (Map.Entry<String, UsbDevice> entry : mUsbManager.getDeviceList().entrySet()) {
addLog("\t" + entry.getKey() + " -> " + entry.getValue().getSerialNumber());
mUsbDevice = entry.getValue();
}
} else {
addLog("No device connected");
}
}
addLog("Waiting for usbConnection");
addLog("Setting up interfaces");
setUpInterfaces();
}
#Override
protected void onPause() {
super.onPause();
unregisterReceiver(mUsbReceiver);
if (usbConnection != null) {
usbConnection.releaseInterface(usbInterface);
}
}
public void setUpInterfaces() {
if (mUsbDevice != null) {
int interfaceCount = mUsbDevice.getInterfaceCount();
addLog("\b" + mUsbDevice.getSerialNumber() + " has total " + interfaceCount + "Interface count");
for (int i = 0; i < interfaceCount; i++) {
final UsbInterface usbInterface = mUsbDevice.getInterface(i);
addLog("\t\tusb at index " + i + " " + getInterfaceDataAsString(usbInterface));
final int endpointCount = usbInterface.getEndpointCount();
addLog("\t\t\t " + usbInterface.getId() + " has total " + endpointCount + " endpoints");
UsbEndpoint point0 = usbInterface.getEndpoint(0);
UsbEndpoint point1 = usbInterface.getEndpoint(1);
printUsbEndPointAsString(point0);
printUsbEndPointAsString(point1);
usbWriterEndpoint = point1;
this.usbInterface = usbInterface;
}
}
}
final String THREAD_TAG = "BG THREAD:-> ";
public boolean connectAndClaim() {
usbConnection = mUsbManager.openDevice(mUsbDevice);
if (usbConnection != null) {
Log.e("Connection:", " connected");
addLog("Device connected");
}
return usbConnection.claimInterface(usbInterface, true);
}
public void writeToPrinter(final String contentToBeWritten) {
Thread thread = new Thread(new Runnable() {
#Override
public void run() {
try {
addLog(THREAD_TAG + "Writing to usbConnection");
addLog(THREAD_TAG + " Content to be written `" + contentToBeWritten + "`");
addLog(THREAD_TAG + " Content size`" + contentToBeWritten.length() + "`");
byte[] bytes = contentToBeWritten.getBytes();
int b = usbConnection.bulkTransfer(usbWriterEndpoint, bytes, bytes.length, 50000);
addLog(THREAD_TAG + "Written status " + b);
addLog(THREAD_TAG + "Written to usbConnection");
} catch (Exception e) {
StringWriter sw = new StringWriter();
e.printStackTrace(new PrintWriter(sw));
String exceptionAsString = sw.toString();
addLog(THREAD_TAG + exceptionAsString);
}
}
});
thread.start();
}
private void printUsbEndPointAsString(UsbEndpoint point) {
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append(point.toString());
stringBuilder.append(", type" + point.getType());
stringBuilder.append(", direction" + point.getDirection());
addLog(stringBuilder.toString());
}
private String getInterfaceDataAsString(UsbInterface usbInterface) {
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append("id = " + usbInterface.getId());
stringBuilder.append(", iClass = " + usbInterface.getInterfaceClass());
stringBuilder.append(", protocol = " + usbInterface.getInterfaceProtocol());
stringBuilder.append(", priSubClassotocol = " + usbInterface.getInterfaceSubclass());
return stringBuilder.toString();
}
public void print(View view) {
String msg = "demo";
if (connectAndClaim()) {
addLog("Claim successful writing to printer");
writeToPrinter(msg);
} else {
addLog("Claim failure");
}
}
private final BroadcastReceiver mUsbReceiver = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
addLog("ACTION RECEIVED in USB RECEIVER : " + action);
if (ACTION_USB_PERMISSION.equals(action)) {
addLog("action if");
synchronized (this) {
mUsbDevice = (UsbDevice) intent.getParcelableExtra(UsbManager.EXTRA_DEVICE);
if (intent.getBooleanExtra(UsbManager.EXTRA_PERMISSION_GRANTED, false)) {
if (mUsbDevice != null) {
//call method to set up device communication
addLog("Device received from BROADCAST RECEIVER");
}
} else {
addLog("permission denied for device " + mUsbDevice.getSerialNumber());
}
}
} else {
addLog("action else");
}
}
};
private void addLog(final String msg) {
logBuffer.append(msg);
logBuffer.append("\n");
textView.post(new Runnable() {
#Override
public void run() {
textView.append(msg);
textView.append("\n");
}
});
}
}
I do not see any failure or error logs last message of the thread is also written successfully but contents are not written to printer.
Is there something i am doing wrong please check.
I think your setUpInterfaces() function is incorrect. That's not the way to loop through the endpoints and set the input and output endpoints. It is done like this,
for(i in 0..(usbDevice!!.interfaceCount - 1)){
val usbInterfac = usbDevice!!.getInterface(i)
if(usbInterfac.interfaceClass == UsbConstants.USB_CLASS_CDC_DATA) {
var tout: UsbEndpoint? = null
var tin: UsbEndpoint? = null
val endpointCount = usbInterfac.endpointCount
if (endpointCount >= 2) {
for (j in 0..(endpointCount - 1)) {
if (usbInterfac.getEndpoint(j).type == UsbConstants.USB_ENDPOINT_XFER_BULK) {
if (usbInterfac.getEndpoint(j).direction == UsbConstants.USB_DIR_OUT) {
tout = usbInterfac.getEndpoint(j)
} else if (usbInterfac.getEndpoint(j).direction == UsbConstants.USB_DIR_IN) {
tin = usbInterfac.getEndpoint(j)
}
}
}
if (tout != null && tin != null) {
usbInterface = usbInterfac
endpointOut = tout
endpointIn = tin
}
}
}
}
You are setting output endpoint incorrectly and hence, printer doesn't get your data. (Please don't mind, the solution is in Kotlin language)

How to scan and connect ble devices when app is in background in android?

I have developed an android application to scan ble devices and have done reading and writing the gatt characteristic when the app is in User Interaction. I want to keep the connection to perticular ble device and want to read-write gatt charecteristic when the app is in foreground and background.Here is my BluetoothLeService class.
public class BluetoothLeService extends Service
{
public static final String ACTION_DATA_AVAILABLE = "com.example.tracker.service.ACTION_DATA_AVAILABLE";
public static final String ACTION_GATT_CONNECTED = "com.example.tracker.service.ACTION_GATT_CONNECTED";
public static final String ACTION_GATT_DISCONNECTED = "com.example.tracker.service.ACTION_GATT_DISCONNECTED";
public static final String ACTION_GATT_RSSI_UPDATE = "com.example.tracker.service.ACTION_GATT_RSSI_UPDATE";
public static final String ACTION_GATT_SERVICES_DISCOVERED = "com.example.tracker.service.ACTION_GATT_SERVICES_DISCOVERED";
public static final String ACTION_GATT_WRITE_FAILED = "com.example.tracker.service.ACTION_GATT_WRITE_FAILED";
protected static final UUID CHARACTERISTIC_UPDATE_NOTIFICATION_DESCRIPTOR_UUID = UUID.fromString("00002902-0000-1000-8000-00805f9b34fb");
public static final String CHARACTERISTIC_UUID = "com.example.tracker.service.CHARACTERISTIC_UUID";
public static final String EXTRA_DATA = "com.example.tracker.service.EXTRA_DATA";
public static final String SIGNAL = "SIGNAL";
private static final String TAG = BluetoothLeService.class.getSimpleName();
private final IBinder mBinder = new LocalBinder();
private BluetoothAdapter mBluetoothAdapter;
private String mBluetoothDeviceAddress;
private BluetoothGatt mBluetoothGatt;
private BluetoothManager mBluetoothManager;
private BluetoothGattCharacteristic mFocusedCharacteristic;
private final BluetoothGattCallback mGattCallback = new BluetoothGattCallback() {
public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) {
if (newState == 2) {
BluetoothLeService.this.broadcastUpdate(BluetoothLeService.ACTION_GATT_CONNECTED);
Log.i(BluetoothLeService.TAG, "Connected to GATT server.");
Log.i("MyActivity", "Connected to GATT server.");
Log.i("MyActivity", "Attempting to start service discovery:" + BluetoothLeService.this.mBluetoothGatt.discoverServices());
} else if (newState == 0) {
String intentAction = BluetoothLeService.ACTION_GATT_DISCONNECTED;
Log.i("MyActivity", "Disconnected from GATT server.");
BluetoothLeService.this.broadcastUpdate(intentAction);
}
}
public void onServicesDiscovered(BluetoothGatt gatt, int status) {
if (status == 0) {
BluetoothLeService.this.broadcastUpdate(BluetoothLeService.ACTION_GATT_SERVICES_DISCOVERED);
} else {
Log.w("MyActivity", "onServicesDiscovered received: " + status);
}
}
public void onCharacteristicRead(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status) {
if (status == 0) {
BluetoothLeService.this.broadcastUpdate(BluetoothLeService.ACTION_DATA_AVAILABLE, characteristic);
Log.i("MyActivity", "Characteristic flags " + characteristic.getProperties());
BluetoothLeService.this.mFocusedCharacteristic = characteristic;
}
}
public void onCharacteristicWrite(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status) {
if (status == 0) {
BluetoothLeService.this.broadcastUpdate(BluetoothLeService.ACTION_DATA_AVAILABLE, characteristic);
if ((characteristic.getProperties() & 2) > 0) {
BluetoothLeService.this.readCharacteristic();
Log.i("MyActivity", "Characteristic permits read");
}
Log.i("MyActivity", "Characteristic was written");
return;
}
Log.i("MyActivity", "Failed to write characteristic");
BluetoothLeService.this.broadcastUpdate(BluetoothLeService.ACTION_GATT_WRITE_FAILED);
}
public void onReadRemoteRssi(BluetoothGatt gatt, int Rssi, int status) {
if (status == 0) {
BluetoothLeService.this.broadcastUpdate(BluetoothLeService.ACTION_GATT_RSSI_UPDATE, Rssi);
}
}
public void onCharacteristicChanged(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic) {
Log.i("MyActivity", "Characteristic has changed");
BluetoothLeService.this.broadcastUpdate(BluetoothLeService.ACTION_DATA_AVAILABLE, characteristic);
}
};
public class LocalBinder extends Binder {
public BluetoothLeService getService() {
return BluetoothLeService.this;
}
}
private void broadcastUpdate(String action) {
sendBroadcast(new Intent(action));
}
private void broadcastUpdate(String action, int Rssi) {
Intent intent = new Intent(action);
intent.putExtra(EXTRA_DATA, Rssi);
sendBroadcast(intent);
}
private void broadcastUpdate(String action, BluetoothGattCharacteristic characteristic) {
Intent intent = new Intent(action);
byte[] data = characteristic.getValue();
if (data != null && data.length > 0) {
StringBuilder stringBuilder = new StringBuilder(data.length);
int length = data.length;
for (int i = 0; i < length; i++) {
stringBuilder.append(String.format("%02X ", new Object[]{Byte.valueOf(data[i])}));
}
intent.putExtra(EXTRA_DATA, new StringBuilder(String.valueOf(new String(data))).append(" [ ").append(stringBuilder.toString()).toString());
intent.putExtra(CHARACTERISTIC_UUID, characteristic.getUuid().toString());
}
sendBroadcast(intent);
}
public IBinder onBind(Intent intent) {
return this.mBinder;
}
public boolean onUnbind(Intent intent) {
close();
return super.onUnbind(intent);
}
public boolean initialize() {
if (this.mBluetoothManager == null) {
this.mBluetoothManager = (BluetoothManager) getSystemService("bluetooth");
if (this.mBluetoothManager == null) {
Log.e(TAG, "Unable to initialize BluetoothManager.");
return false;
}
}
this.mBluetoothAdapter = this.mBluetoothManager.getAdapter();
if (this.mBluetoothAdapter != null) {
return true;
}
Log.e(TAG, "Unable to obtain a BluetoothAdapter.");
return false;
}
public boolean connect(String address) {
if (this.mBluetoothAdapter == null || address == null) {
Log.w(TAG, "BluetoothAdapter not initialized or unspecified address.");
return false;
} else if (this.mBluetoothDeviceAddress == null || !address.equals(this.mBluetoothDeviceAddress) || this.mBluetoothGatt == null) {
BluetoothDevice device = this.mBluetoothAdapter.getRemoteDevice(address);
if (device == null) {
Log.w(TAG, "LocalDevice not found. Unable to connect.");
return false;
}
this.mBluetoothGatt = device.connectGatt(this, false, this.mGattCallback);
Log.d(TAG, "Trying to create a new connection.");
this.mBluetoothDeviceAddress = address;
return true;
} else {
Log.d(TAG, "Trying to use an existing mBluetoothGatt for connection.");
if (this.mBluetoothGatt.connect()) {
return true;
}
return false;
}
}
public void disconnect() {
if (this.mBluetoothAdapter == null || this.mBluetoothGatt == null) {
Log.w(TAG, "BluetoothAdapter not initialized");
} else {
this.mBluetoothGatt.disconnect();
}
}
public void readRemoteRssi() {
if (this.mBluetoothAdapter == null || this.mBluetoothGatt == null) {
Log.w(TAG, "BluetoothAdapter not initialized");
} else {
this.mBluetoothGatt.readRemoteRssi();
}
}
public BluetoothGattCharacteristic CurrentCharacteristic() {
return this.mFocusedCharacteristic;
}
public String getCurrentCharacteristicUuid() {
return this.mFocusedCharacteristic.getUuid().toString();
}
public void writeCharacteristic(byte[] c) {
mFocusedCharacteristic.setValue(c);
if (mBluetoothGatt!=null && mFocusedCharacteristic!=null){
mBluetoothGatt.writeCharacteristic(mFocusedCharacteristic);
}
}
public void readCharacteristic() {
Log.i("MyActivity", "Read Characteristic");
this.mBluetoothGatt.readCharacteristic(this.mFocusedCharacteristic);
}
public void notifyCharacteristic() {
Log.i("MyActivity", "Notify Characteristic");
setCharacteristicNotification(this.mFocusedCharacteristic, true);
}
public void setCurrentCharacteristic(BluetoothGattCharacteristic characteristic) {
this.mFocusedCharacteristic = characteristic;
}
public void close() {
if (this.mBluetoothGatt != null) {
this.mBluetoothGatt.close();
this.mBluetoothGatt = null;
}
}
public void readCharacteristic(BluetoothGattCharacteristic characteristic) {
if (this.mBluetoothAdapter == null || this.mBluetoothGatt == null) {
Log.w(TAG, "BluetoothAdapter not initialized");
} else {
this.mBluetoothGatt.readCharacteristic(characteristic);
}
}
public boolean setCharacteristicNotification(BluetoothGattCharacteristic characteristic, boolean enable) {
Log.i("MyActivity", "setCharacteristicNotification");
this.mBluetoothGatt.setCharacteristicNotification(characteristic, enable);
BluetoothGattDescriptor descriptor = characteristic.getDescriptor(CHARACTERISTIC_UPDATE_NOTIFICATION_DESCRIPTOR_UUID);
descriptor.setValue(enable ? BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE : new byte[2]);
try {
Thread.sleep(200);
} catch (InterruptedException e) {
e.printStackTrace();
}
SystemClock.sleep(200);
return this.mBluetoothGatt.writeDescriptor(descriptor);
}
public List<BluetoothGattService> getSupportedGattServices() {
if (this.mBluetoothGatt == null) {
return null;
}
return this.mBluetoothGatt.getServices();
}
}
The API is the same regardless if your app is in the foreground or background. The only thing you need to do is to make sure the system doesn't kill the app when it is in the background. To do that, simply have a Foreground Service running somewhere in your app process.
Use service to scan and connect ble devices when application is in background in android.
package com.example.tracker.service;
import android.app.Service;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothGatt;
import android.bluetooth.BluetoothGattCharacteristic;
import android.bluetooth.BluetoothGattService;
import android.bluetooth.BluetoothManager;
import android.bluetooth.le.BluetoothLeScanner;
import android.bluetooth.le.ScanFilter;
import android.bluetooth.le.ScanSettings;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Handler;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.support.v4.widget.SwipeRefreshLayout;
import android.util.Log;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.SeekBar;
import android.widget.Toast;
import com.google.firebase.auth.FirebaseAuth;
import com.example.tracker.R;
import com.example.tracker.utils.SampleGattAttributes;
import com.example.tracker.utils.SharedPreferencesUtils;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.UUID;
import static com.example.tracker.constant.SharedFreferencesConstant.KEY_SP_MOBILE_NUMBER;
/**
* Created by Jprashant on 12/9/17.
*/
public class BackgroundService extends Service{
private int scanPeriod;
Context context;
String TAG="BackgroundService";
private BluetoothAdapter mBluetoothAdapter;
private boolean mScanning;
private Handler mHandler;
public String[] advDataTypes = new String[256];
ArrayList<BluetoothDevice> bluetoothDeviceArrayList=new ArrayList<>();
ArrayList<BluetoothDevice> bluetoothDeviceArrayListTwo=new ArrayList<>();
private static final int REQUEST_ENABLE_BT = 1;
// Stops scanning after 10 seconds.
private static final long SCAN_PERIOD = 10000;
/*Connect Ble Device*/
String deviceId;
public static String arrayDidOpnSec2;
BluetoothGattService gattService4;
public static ArrayList<BluetoothGattCharacteristic> lastCharacteristic;
// AlertDialog.Builder alertDialog;
private float avgRssi = 0.0f;
// private Dialog dialog;
private BluetoothLeService mBluetoothLeService;
private boolean mConnected = false;
private ArrayList<ArrayList<BluetoothGattCharacteristic>> mGattCharacteristics = new ArrayList();
//service and char uuid
private static final int TRACKER_ON_OFF = 2;
private static final UUID TRACER_TRIPPLE_PRESS_SERVICE=UUID.fromString("edfec62e-9910-0bac-5241-d8bda6932a2f");
private static final UUID TRACKER_TRIPPLE_PRESS_CHAR=UUID.fromString("772ae377-b3d2-4f8e-4042-5481d1e0098c");
private static final UUID IMMEDIATE_ALERT_UUID = UUID.fromString("00001802-0000-1000-8000-00805f9b34fb");
private static final UUID ALERT_LEVEL_UUID = UUID.fromString("00002a06-0000-1000-8000-00805f9b34fb");
private Button btnSMS;
public static String mDeviceName,mDeviceAddress,connectionStatus;
/*-------------------------------------------------------------------------------*/
public static final String PREFS_NAME = "PreferencesFile";
public int deviceCount = 0;
public String[] mData = new String[400];
private Handler mHandler1;
private ListView listItems;
/*--------for > 21--------------*/
private BluetoothLeScanner mLEScanner;
private ScanSettings settings;
private List<ScanFilter> filters;
private BluetoothGatt mGatt;
public BackgroundService() {
}
public BackgroundService(Context context) {
this.context = context;
}
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
// getting systems default ringtone
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(),"CALL YOUR METHOD",Toast.LENGTH_LONG).show();
mHandler = new Handler();
// Use this check to determine whether BLE is supported on the device. Then you can
// selectively disable BLE-related features.
if (!getPackageManager().hasSystemFeature(PackageManager.FEATURE_BLUETOOTH_LE)) {
Toast.makeText(context, R.string.ble_not_supported, Toast.LENGTH_SHORT).show();
}
// Initializes a Bluetooth adapter. For API level 18 and above, get a reference to
// BluetoothAdapter through BluetoothManager.
final BluetoothManager bluetoothManager = (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);
mBluetoothAdapter = bluetoothManager.getAdapter();
// Checks if Bluetooth is supported on the device.
if (mBluetoothAdapter == null) {
Toast.makeText(context, R.string.error_bluetooth_not_supported, Toast.LENGTH_SHORT).show();
return;
}
for (int i = 0; i < 256; i += REQUEST_ENABLE_BT) {
advDataTypes[i] = "Unknown Data Type";
}
advDataTypes[REQUEST_ENABLE_BT] = "Flags";
advDataTypes[2] = "Incomplete List of 16-bit Service Class UUIDs";
advDataTypes[3] = "Complete List of 16-bit Service Class UUIDs";
advDataTypes[4] = "Incomplete List of 32-bit Service Class UUIDs";
advDataTypes[5] = "Complete List of 32-bit Service Class UUIDs";
advDataTypes[6] = "Incomplete List of 128-bit Service Class UUIDs";
advDataTypes[7] = "Complete List of 128-bit Service Class UUIDs";
advDataTypes[8] = "Shortened Local Name";
advDataTypes[9] = "Complete Local Name";
advDataTypes[10] = "Tx Power Level";
advDataTypes[13] = "Class of LocalDevice";
advDataTypes[14] = "Simple Pairing Hash";
advDataTypes[15] = "Simple Pairing Randomizer R";
advDataTypes[16] = "LocalDevice ID";
advDataTypes[17] = "Security Manager Out of Band Flags";
advDataTypes[18] = "Slave Connection Interval Range";
advDataTypes[20] = "List of 16-bit Solicitaion UUIDs";
advDataTypes[21] = "List of 128-bit Solicitaion UUIDs";
advDataTypes[22] = "Service Data";
advDataTypes[23] = "Public Target Address";
advDataTypes[24] = "Random Target Address";
advDataTypes[25] = "Appearance";
advDataTypes[26] = "Advertising Interval";
advDataTypes[61] = "3D Information Data";
advDataTypes[255] = "Manufacturer Specific Data";
scanPeriod = getApplicationContext().getSharedPreferences(PREFS_NAME, 0).getInt("scan_interval", 6000);
scanTrackerDevices();
}
}, 10000);
return START_STICKY;
}
#Override
public void onDestroy() {
super.onDestroy();
}
public void scanTrackerDevices(){
Log.e(TAG,"scanTrackerDevices");
if (!mBluetoothAdapter.isEnabled()) {
if (!mBluetoothAdapter.isEnabled()) {
Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
}
}
scanLeDevice(true);
}
private void scanLeDevice(final boolean enable) {
bluetoothDeviceArrayList.clear();
if (enable) {
// Stops scanning after a pre-defined scan period.
mHandler.postDelayed(new Runnable() {
#Override
public void run() {
mScanning = false;
mBluetoothAdapter.stopLeScan(mLeScanCallback);
int arraySize=bluetoothDeviceArrayListTwo.size();
Log.e(TAG,"bluetoothDeviceArrayListTwo Size in scan :"+arraySize);
for (int i=0;i<bluetoothDeviceArrayListTwo.size();i++){
BluetoothDevice bluetoothDevice=bluetoothDeviceArrayListTwo.get(i);
Log.e(TAG,"Device Name in scan :"+bluetoothDevice.getName());
Log.e(TAG,"Device Address in scan :"+bluetoothDevice.getAddress());
if (i==0){
mBluetoothLeService.connect(bluetoothDevice.getAddress());
}
}
}
}, scanPeriod);
mScanning = true;
mBluetoothAdapter.startLeScan(mLeScanCallback);
} else {
mScanning = false;
mBluetoothAdapter.stopLeScan(mLeScanCallback);
}
}
private BluetoothAdapter.LeScanCallback mLeScanCallback = new BluetoothAdapter.LeScanCallback() {
public void onLeScan(final BluetoothDevice device, final int rssi, final byte[] scanRecord) {
String d = "";
String rd = "";
String h = "0123456789ABCDEF";
int ln = 0;
int i = 0;
while (i < scanRecord.length) {
int x = scanRecord[i] & 255;
rd = new StringBuilder(String.valueOf(rd)).append(h.substring(x / 16, (x / 16) + REQUEST_ENABLE_BT)).append(h.substring(x % 16, (x % 16) +REQUEST_ENABLE_BT)).toString();
if (i == ln) {
ln = (i + x) + REQUEST_ENABLE_BT;
if (x == 0) {
break;
}
d = new StringBuilder(String.valueOf(d)).append("\r\n Length: ").append(h.substring(x / 16, (x / 16) + REQUEST_ENABLE_BT)).append(h.substring(x % 16, (x % 16) +REQUEST_ENABLE_BT)).toString();
i += REQUEST_ENABLE_BT;
x = scanRecord[i] & 255;
d = new StringBuilder(String.valueOf(d)).append(", Type :").append(h.substring(x / 16, (x / 16) + REQUEST_ENABLE_BT)).append(h.substring(x % 16, (x % 16) + REQUEST_ENABLE_BT)).append(" = ").append(advDataTypes[x]).append(", Value: ").toString();
rd = new StringBuilder(String.valueOf(rd)).append(h.substring(x / 16, (x / 16) + REQUEST_ENABLE_BT)).append(h.substring(x % 16, (x % 16) + REQUEST_ENABLE_BT)).toString();
} else {
d = new StringBuilder(String.valueOf(d)).append(" ").append(h.substring(x / 16, (x / 16) + REQUEST_ENABLE_BT)).append(h.substring(x % 16, (x % 16) +REQUEST_ENABLE_BT)).toString();
}
i += REQUEST_ENABLE_BT;
}
Log.e(TAG,"UUID : "+device.getUuids());
String[] arrayDeviceName=String.valueOf(device.getName()).split(" ");
String deviceName0=arrayDeviceName[0];
bluetoothDeviceArrayListTwo.add(device);
}
};
/*-------------------Connect BLE---------------------------------------------*/
private Handler mHandler2;
public final BroadcastReceiver mGattUpdateReceiver = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent)
{
String action = intent.getAction();
if (BluetoothLeService.ACTION_GATT_CONNECTED.equals(action))
{
numberOfRssi = 0;
avgRssi = 0.0f;
mConnected = true;
updateConnectionState(R.string.connected);
mHandler2.postDelayed(startRssi, 300);
Log.e(TAG,"ACTION_GATT_CONNECTED");
}
else if (BluetoothLeService.ACTION_GATT_DISCONNECTED.equals(action)) {
mConnected = false;
updateConnectionState(R.string.disconnected);
Log.e(TAG,"ACTION_GATT_DISCONNECTED");
} else if (BluetoothLeService.ACTION_GATT_SERVICES_DISCOVERED.equals(action)) {
displayGattServicesForDimmer(mBluetoothLeService.getSupportedGattServices());// For dimmer
Log.e(TAG,"ACTION_GATT_SERVICES_DISCOVERED");
} else if (BluetoothLeService.ACTION_DATA_AVAILABLE.equals(action)) {
Log.e(TAG,"ACTION_DATA_AVAILABLE");
String unknownServiceString = context.getResources().getString(R.string.unknown_service);
displayDimmerData("<<" + SampleGattAttributes.lookup(intent.getStringExtra(BluetoothLeService.CHARACTERISTIC_UUID), unknownServiceString) + ">> Value: " + intent.getStringExtra(BluetoothLeService.EXTRA_DATA) + "]");
displayDimmer2(intent.getStringExtra(BluetoothLeService.EXTRA_DATA));
} else if (BluetoothLeService.ACTION_GATT_RSSI_UPDATE.equals(action)) {
updateRssi(intent.getIntExtra(BluetoothLeService.EXTRA_DATA, -400));
} else if (BluetoothLeService.ACTION_GATT_WRITE_FAILED.equals(action)) {
Log.e(TAG,"ACTION_GATT_WRITE_FAILED");
}
}
};
/*------------------------------------------------------------------------*/
#Override
public void onCreate() {
super.onCreate();
// -------------------Connect Ble--------------------------------------
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction(BluetoothLeService.ACTION_GATT_CONNECTED);
intentFilter.addAction(BluetoothLeService.ACTION_GATT_DISCONNECTED);
intentFilter.addAction(BluetoothLeService.ACTION_GATT_SERVICES_DISCOVERED);
intentFilter.addAction(BluetoothLeService.ACTION_DATA_AVAILABLE);
intentFilter.addAction(BluetoothLeService.ACTION_GATT_RSSI_UPDATE);
intentFilter.addAction(BluetoothLeService.ACTION_GATT_WRITE_FAILED);
Log.e(TAG,"OnResume()");
getApplicationContext().registerReceiver(mGattUpdateReceiver, intentFilter);
getApplicationContext().bindService(new Intent(getApplicationContext(), BluetoothLeService.class), mServiceConnection, 1);
mHandler2=new Handler();
}
private BluetoothGattCharacteristic mNotifyCharacteristic;
private final ServiceConnection mServiceConnection = new ServiceConnection() {
public void onServiceConnected(ComponentName componentName, IBinder service) {
mBluetoothLeService = ((BluetoothLeService.LocalBinder) service).getService();
if (!mBluetoothLeService.initialize()) {
Log.e(TAG, "Unable to initialize Bluetooth");
}
}
public void onServiceDisconnected(ComponentName componentName) {
mBluetoothLeService = null;
}
};
private boolean notificationActive = true;
private int numberOfRssi = 0;
private Runnable startRssi = new Runnable() {
public void run() {
if (mConnected) {
mBluetoothLeService.readRemoteRssi();
mHandler2.postDelayed(startRssi, 200);
}
}
};
public BluetoothGatt getmGatt() {
return mGatt;
}
//code from DeviceControlActivity
private void updateConnectionState(final int resourceId) {
connectionStatus= String.valueOf(resourceId);
Log.e(TAG,"Resource ID"+resourceId);
}
private void displayDimmerData(String data){
Log.e(TAG,"Display Data :"+data);
}
private void displayDimmer2(String data){
Log.e(TAG,"display Dimmer2"+data);
String sosString = data.substring(0, Math.min(data.length(), 3));
Log.e(TAG,"SOS String :"+sosString);
if (sosString.equals("SOS")){
Intent callIntent = new Intent(Intent.ACTION_CALL);
callIntent.setData(Uri.parse("tel:"+ SharedPreferencesUtils.getStringFromSharedPreferences(KEY_SP_MOBILE_NUMBER,getApplicationContext())));
callIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
getApplicationContext().startActivity(callIntent);
}
}
private void updateRssi(int data) {
if (data > -400) {
if (this.numberOfRssi > 10) {
this.avgRssi = ((9.0f * this.avgRssi) + ((float) data)) / 10.0f;
} else {
this.avgRssi = (this.avgRssi + ((float) data)) / 2.0f;
this.numberOfRssi++;
}
connectionStatus="Connected, RSSI:" + data + ", Avg:" + Math.round(this.avgRssi);
}
}
/*-------------------------disaplay gatt service for dimmer----------------------*/
private void displayGattServicesForDimmer(List<BluetoothGattService> gattServices) {
if (gattServices != null) {
String unknownServiceString = getResources().getString(R.string.unknown_service);
String unknownCharaString = getResources().getString(R.string.unknown_characteristic);
ArrayList<HashMap<String, String>> gattServiceData = new ArrayList();
ArrayList<ArrayList<HashMap<String, String>>> gattCharacteristicData = new ArrayList();
this.mGattCharacteristics = new ArrayList();
for (BluetoothGattService gattService : gattServices) {
HashMap<String, String> currentServiceData = new HashMap();
String uuid = gattService.getUuid().toString();
currentServiceData.put("NAME", SampleGattAttributes.lookup(uuid, unknownServiceString));
currentServiceData.put("UUID", uuid);
gattServiceData.add(currentServiceData);
ArrayList<HashMap<String, String>> gattCharacteristicGroupData = new ArrayList();
List<BluetoothGattCharacteristic> gattCharacteristics = gattService.getCharacteristics();
ArrayList<BluetoothGattCharacteristic> charas = new ArrayList();
for (BluetoothGattCharacteristic gattCharacteristic : gattCharacteristics) {
charas.add(gattCharacteristic);
HashMap<String, String> currentCharaData = new HashMap();
uuid = gattCharacteristic.getUuid().toString();
currentCharaData.put("NAME", "\t\t\t<<" + SampleGattAttributes.lookup(uuid, unknownCharaString) + ">>");
currentCharaData.put("UUID", "\t\t\tUUID: 0x" + uuid.substring(4, 8) + ", Properties: " + translateProperties(gattCharacteristic.getProperties()));
gattCharacteristicGroupData.add(currentCharaData);
Log.i(TAG,"CUrrent CHARACTERISTIC DATA"+currentCharaData);
Log.i(TAG,"UUID : "+uuid.substring(4, 8));
Log.i(TAG,"Proprties : "+gattCharacteristic.getProperties());
Log.i(TAG,"Translate Proprties : "+translateProperties(gattCharacteristic.getProperties()));
Log.i(TAG,"char list"+gattCharacteristicData.toString());
}
gattService4=gattService;
this.mGattCharacteristics.add(charas);
}
if (mGattCharacteristics.get(3)!=null) {
lastCharacteristic = new ArrayList<>(mGattCharacteristics.get(3));
enableNotifyOfCharcteristicForDimmer(lastCharacteristic);
}
}
}
private String translateProperties(int properties) {
String s = "";
if ((properties & 1) > 0) {
s = new StringBuilder(String.valueOf(s)).append("/Broadcast").toString();
}
if ((properties & 2) > 0) {
s = new StringBuilder(String.valueOf(s)).append("/Read").toString();
}
if ((properties & 4) > 0) {
s = new StringBuilder(String.valueOf(s)).append("/WriteWithoutResponse").toString();
}
if ((properties & 8) > 0) {
s = new StringBuilder(String.valueOf(s)).append("/Write").toString();
}
if ((properties & 16) > 0) {
s = new StringBuilder(String.valueOf(s)).append("/Notify").toString();
}
if ((properties & 32) > 0) {
s = new StringBuilder(String.valueOf(s)).append("/Indicate").toString();
}
if ((properties & 64) > 0) {
s = new StringBuilder(String.valueOf(s)).append("/SignedWrite").toString();
}
if ((properties & 128) > 0) {
s = new StringBuilder(String.valueOf(s)).append("/ExtendedProperties").toString();
}
if (s.length() > 1) {
return s.substring(1);
}
return s;
}
// Enable Characteristic for dimmer
public void enableNotifyOfCharcteristicForDimmer(ArrayList<BluetoothGattCharacteristic> lastCharacteristic){
if(mGattCharacteristics!=null) {
checkCharacteristicPresent(lastCharacteristic.get(0));
mBluetoothLeService.setCharacteristicNotification(lastCharacteristic.get(0), true);
notificationActive = true;
Log.e(TAG,"Characteristic index : "+0+":\nM GATT CHARACTERISTIC AT "+"Service 4 : CHAR"+ 0 +" :" +lastCharacteristic.get(0).toString());
checkCharacteristicPresent(lastCharacteristic.get(1));
mBluetoothLeService.setCharacteristicNotification(lastCharacteristic.get(1), true);
notificationActive = true;
Log.e(TAG,"Characteristic index : "+1+":\nM GATT CHARACTERISTIC AT "+"Service 4 : CHAR"+ 1 +" :" +lastCharacteristic.get(1).toString());
checkCharacteristicPresent(lastCharacteristic.get(2));
mBluetoothLeService.setCharacteristicNotification(lastCharacteristic.get(2), true);
notificationActive = true;
Log.e(TAG,"Characteristic index : "+2+":\nM GATT CHARACTERISTIC AT "+"Service 4 : CHAR"+ 2 +" :" +lastCharacteristic.get(2).toString());
checkCharacteristicPresent(lastCharacteristic.get(3));
mBluetoothLeService.setCharacteristicNotification(lastCharacteristic.get(3), true);
notificationActive = true;
Log.e(TAG,"Characteristic index : "+3+":\nM GATT CHARACTERISTIC AT "+"Service 4 : CHAR"+ 3 +" :" +lastCharacteristic.get(3).toString());
checkCharacteristicPresent(lastCharacteristic.get(4));
mBluetoothLeService.setCharacteristicNotification(lastCharacteristic.get(4), true);
notificationActive = true;
Log.e(TAG,"Characteristic index : "+4+":\nM GATT CHARACTERISTIC AT "+"Service 4 : CHAR"+ 4 +" :" +lastCharacteristic.get(4).toString());
checkCharacteristicPresent(lastCharacteristic.get(5));
mBluetoothLeService.setCharacteristicNotification(lastCharacteristic.get(5), true);
notificationActive = true;
Log.e(TAG,"Characteristic index : "+5+":\nM GATT CHARACTERISTIC AT "+"Service 4 : CHAR"+ 5 +" :" +lastCharacteristic.get(5).toString());
checkCharacteristicPresent(lastCharacteristic.get(2));
mBluetoothLeService.setCharacteristicNotification(lastCharacteristic.get(2), true);
notificationActive = true;
Log.e(TAG,"Characteristic index : "+2+":\nM GATT CHARACTERISTIC AT "+"Service 4 : CHAR"+ 2 +" :" +lastCharacteristic.get(2).toString());
}
}
// Check the type of characteristic i.e READ/WRITE/NOTIFY
public void checkCharacteristicPresent(BluetoothGattCharacteristic characteristic) {
int charaProp = characteristic.getProperties();
Log.e(TAG, "checkCharacteristicPresent Prop : " + charaProp);
mBluetoothLeService.setCurrentCharacteristic(characteristic);
if ((charaProp & 2) > 0) {
Log.e(TAG, "CharProp & 2 : " + charaProp);
mBluetoothLeService.readCharacteristic(characteristic);
}
if ((charaProp & 16) > 0) {
Log.e(TAG, "CharProp & 16 : " + charaProp);
mNotifyCharacteristic = characteristic;
} else {
if (mNotifyCharacteristic != null) {
mBluetoothLeService.setCharacteristicNotification(mNotifyCharacteristic, false);
mNotifyCharacteristic = null;
}
}
if ((charaProp & 8) > 0 || (charaProp & 4) > 0) {
Log.e(TAG, "CharProp & 4 : " + charaProp);
} else {
Log.e(TAG, "Else : " + charaProp);
}
}
}

android help debugging with Toast

I am trying to debug an app with eclipse. I am using the USB to connect to an accessory so USB in not Available to debug. I am using ADB connect to wirelessly debug, but with this app I have to unplug and plug in USB cable to get app to run and when I do this I lose connection to eclipse.
SO the only thing I can think is to try and use Toast to figure out what is going on in a class.
Maybe there is a better way?
But When I try to call toast app crashes.. I want to be able to toast messages in vaious methods like BroadcastReceiver, and ResumeAccessory
Call anyone tell me how to implement toast in this class?:
//
User must modify the below package with their package name
package com.UARTDemo;
import java.io.FileDescriptor;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import android.app.Activity;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.hardware.usb.UsbAccessory;
import android.hardware.usb.UsbManager;
import android.os.Handler;
import android.os.Message;
import android.os.ParcelFileDescriptor;
import android.util.Log;
/******************************FT311 GPIO interface class******************************************/
public class FT311UARTInterface extends Activity
{
private static final String ACTION_USB_PERMISSION = "com.UARTDemo.USB_PERMISSION";
public UsbManager usbmanager;
public UsbAccessory usbaccessory;
public PendingIntent mPermissionIntent;
public ParcelFileDescriptor filedescriptor;
public FileInputStream inputstream;
public FileOutputStream outputstream;
public boolean mPermissionRequestPending = true;
public handler_thread handlerThread;
private byte [] usbdata;
private byte [] writeusbdata;
private byte [] readBuffer; /*circular buffer*/
private int readcount;
private int totalBytes;
private int writeIndex;
private int readIndex;
private byte status;
private byte maxnumbytes = (byte)64;
public boolean datareceived = false;
/*constructor*/
public FT311UARTInterface(Context context){
super();
/*shall we start a thread here or what*/
usbdata = new byte[64];
writeusbdata = new byte[64];
/*128(make it 256, but looks like bytes should be enough)*/
readBuffer = new byte [maxnumbytes];
readIndex = 0;
writeIndex = 0;
/***********************USB handling******************************************/
usbmanager = (UsbManager) context.getSystemService(Context.USB_SERVICE);
// Log.d("LED", "usbmanager" +usbmanager);
mPermissionIntent = PendingIntent.getBroadcast(context, 0, new Intent(ACTION_USB_PERMISSION), 0);
IntentFilter filter = new IntentFilter(ACTION_USB_PERMISSION);
filter.addAction(UsbManager.ACTION_USB_ACCESSORY_DETACHED);
context.registerReceiver(mUsbReceiver, filter);
inputstream = null;
outputstream = null;
}
/*reset method*/
public void Reset()
{
/*create the packet*/
writeusbdata[0] = 0x49;
writeusbdata[1] = 0x00;
writeusbdata[2] = 0x00;
writeusbdata[3] = 0x00;
/*send the packet over the USB*/
SendPacket(4);
}
public void SetConfig(int baud, byte dataBits, byte stopBits,
byte parity, byte flowControl)
{
/*prepare the baud rate buffer*/
writeusbdata[0] = (byte)baud;
writeusbdata[1] = (byte)(baud >> 8);
writeusbdata[2] = (byte)(baud >> 16);
writeusbdata[3] = (byte)(baud >> 24);
/*data bits*/
writeusbdata[4] = dataBits;
/*stop bits*/
writeusbdata[5] = stopBits;
/*parity*/
writeusbdata[6] = parity;
/*flow control*/
writeusbdata[7] = flowControl;
/*send the UART configuration packet*/
SendPacket((int)8);
}
/*write data*/
public byte SendData(byte numBytes, char[] buffer)
{
status = 0x00; /*success by default*/
/*
* if num bytes are more than maximum limit
*/
if(numBytes < 1){
/*return the status with the error in the command*/
return status;
}
/*check for maximum limit*/
if(numBytes > 64){
numBytes = 64;
}
/*prepare the packet to be sent*/
for(int count = 0;count<numBytes;count++)
{
writeusbdata[count] = (byte)buffer[count];
}
SendPacket((int)numBytes);
return status;
}
/*read data*/
public byte ReadData(byte numBytes,char[] buffer, byte [] actualNumBytes)
{
status = 0x00; /*success by default*/
/*should be at least one byte to read*/
if((numBytes < 1) || (totalBytes == 0)){
actualNumBytes[0] = 0x00;
return status;
}
/*check for max limit*/
if(numBytes > 64){
numBytes = 64;
}
if(numBytes > 64){
numBytes = 64;
}
if(numBytes > totalBytes)
numBytes = (byte)totalBytes;
/*update the number of bytes available*/
totalBytes -= numBytes;
actualNumBytes[0] = numBytes;
/*copy to the user buffer*/
for(int count = 0; count<numBytes;count++)
{
buffer[count] = (char)readBuffer[readIndex];
readIndex++;
/*shouldnt read more than what is there in the buffer,
* so no need to check the overflow
*/
readIndex %= maxnumbytes;
}
return status;
}
/*method to send on USB*/
private void SendPacket(int numBytes)
{
try {
if(outputstream != null){
outputstream.write(writeusbdata, 0,numBytes);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/*resume accessory*/
public void ResumeAccessory()
{
// Intent intent = getIntent();
if (inputstream != null && outputstream != null) {
return;
}
UsbAccessory[] accessories = usbmanager.getAccessoryList();
UsbAccessory accessory = (accessories == null ? null : accessories[0]);
if (accessory != null) {
if (usbmanager.hasPermission(accessory)) {
OpenAccessory(accessory);
}
else
{
synchronized (mUsbReceiver) {
if (!mPermissionRequestPending) {
usbmanager.requestPermission(accessory,
mPermissionIntent);
mPermissionRequestPending = true;
}
}
}
} else {}
}
/*destroy accessory*/
public void DestroyAccessory(){
unregisterReceiver(mUsbReceiver);
CloseAccessory();
}
/*********************helper routines*************************************************/
public void OpenAccessory(UsbAccessory accessory)
{
filedescriptor = usbmanager.openAccessory(accessory);
if(filedescriptor != null){
usbaccessory = accessory;
FileDescriptor fd = filedescriptor.getFileDescriptor();
inputstream = new FileInputStream(fd);
outputstream = new FileOutputStream(fd);
/*check if any of them are null*/
if(inputstream == null || outputstream==null){
return;
}
}
handlerThread = new handler_thread(handler, inputstream);
handlerThread.start();
}
private void CloseAccessory()
{
try{
if(filedescriptor != null)
filedescriptor.close();
}catch (IOException e){}
try {
if(inputstream != null)
inputstream.close();
} catch(IOException e){}
try {
if(outputstream != null)
outputstream.close();
}catch(IOException e){}
/*FIXME, add the notfication also to close the application*/
filedescriptor = null;
inputstream = null;
outputstream = null;
System.exit(0);
}
/***********USB broadcast receiver*******************************************/
private final BroadcastReceiver mUsbReceiver = new BroadcastReceiver()
{
#Override
public void onReceive(Context context, Intent intent)
{
String action = intent.getAction();
if (ACTION_USB_PERMISSION.equals(action))
{
synchronized (this)
{
UsbAccessory accessory = (UsbAccessory) intent.getParcelableExtra(UsbManager.EXTRA_ACCESSORY);
if (intent.getBooleanExtra(UsbManager.EXTRA_PERMISSION_GRANTED, false))
{
OpenAccessory(accessory);
}
else
{
Log.d("LED", "permission denied for accessory "+ accessory);
}
mPermissionRequestPending = false;
}
}
else if (UsbManager.ACTION_USB_ACCESSORY_DETACHED.equals(action))
{
UsbAccessory accessory = (UsbAccessory)intent.getParcelableExtra(UsbManager.EXTRA_ACCESSORY);
if (accessory != null )//&& accessory.equals(usbaccessory))
{
CloseAccessory();
}
}else
{
Log.d("LED", "....");
}
}
};
final Handler handler = new Handler()
{
#Override
public void handleMessage(Message msg)
{
for(int count = 0;count<readcount;count++){
readBuffer[writeIndex] = usbdata[count];
/*move to the next write location*/
writeIndex++;
writeIndex %= maxnumbytes;
/*FIXME,check for overflow*/
//if(writeIndex == readIndex){
//}
}
/*caluclate the available bytes to read*/
if(writeIndex >= readIndex)
totalBytes = writeIndex-readIndex;
else
totalBytes = (maxnumbytes-readIndex)+writeIndex;
}
};
/*usb input data handler*/
private class handler_thread extends Thread {
Handler mHandler;
FileInputStream instream;
handler_thread(Handler h,FileInputStream stream ){
mHandler = h;
instream = stream;
}
public void run()
{
while(true)
{
Message msg = mHandler.obtainMessage();
try{
if(instream != null)
{
readcount = instream.read(usbdata,0,64);
if(readcount > 0)
{
datareceived = true;
msg.arg1 = usbdata[0];
msg.arg2 = usbdata[1];
}
mHandler.sendMessage(msg);
}
}catch (IOException e){}
}
}
}
}
Its better to use Log.d(TAG, text)
OR
In any subclass of activity you can do:
Toast.makeText(getApplicationContext(), "text", Toast.LENGTH_LONG).show();

communication between android and fpga board

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?

ADK AndroidAccessory Read Function on Arduino should be getting something, per DemoKit sketch?

I'm using a Freeduino (Arduino Uno compatible) with a Samsung Galaxy Tab 10.1 running ICS (4) and I have succeeded in writing from the Arduino to the Android, but I have not been able to read from the Android in the Arduino sketch.
Here's the Android class for the USB Accessory:
package com.kegui.test;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.FileDescriptor;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.StringWriter;
import java.io.Writer;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.util.ArrayList;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import com.kegui.test.Scripto;
import android.app.Activity;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.hardware.usb.UsbAccessory;
import android.hardware.usb.UsbManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.ParcelFileDescriptor;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
public class USBAccess extends Activity implements Runnable, OnClickListener {
private static final String ACTION_USB_PERMISSION = "com.google.android.DemoKit.action.USB_PERMISSION";
protected static final String TAG = "KegUI";
private UsbManager mUsbManager;
private PendingIntent mPermissionIntent;
private boolean mPermissionRequestPending;
private TextView debugtext = null;
private Button button1 = null;
private Button button2 = null;
private boolean button2visible = false;
UsbAccessory mAccessory;
ParcelFileDescriptor mFileDescriptor;
FileInputStream mInputStream;
FileOutputStream mOutputStream;
private static final int MESSAGE_BUTTON_PRESSED = 1;
private final BroadcastReceiver mUsbReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
Log.i("KegApp", "***********************Received*************************");
if (ACTION_USB_PERMISSION.equals(action)) {
synchronized (this) {
UsbAccessory accessory = (UsbAccessory) intent.getParcelableExtra(UsbManager.EXTRA_ACCESSORY);
if (intent.getBooleanExtra(
UsbManager.EXTRA_PERMISSION_GRANTED, false)) {
openAccessory(accessory);
} else {
Log.d(TAG, "permission denied for accessory "
+ accessory);
}
mPermissionRequestPending = false;
}
} else if (UsbManager.ACTION_USB_ACCESSORY_DETACHED.equals(action)) {
UsbAccessory accessory = (UsbAccessory) intent.getParcelableExtra(UsbManager.EXTRA_ACCESSORY);
if (accessory != null && accessory.equals(mAccessory)) {
closeAccessory();
}
}
}
};
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mUsbManager = (UsbManager) getSystemService(Context.USB_SERVICE);
mPermissionIntent = PendingIntent.getBroadcast(this, 0, new Intent(
ACTION_USB_PERMISSION), 0);
IntentFilter filter = new IntentFilter(ACTION_USB_PERMISSION);
filter.addAction(UsbManager.ACTION_USB_ACCESSORY_DETACHED);
setContentView(R.layout.main);
final Button button = (Button) findViewById(R.id.button1);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// Perform action on click
new TempUpdateTask().execute("testing");
}
});
registerReceiver(mUsbReceiver, filter);
Log.d(TAG,"on Create'd");
}
#Override
public void onResume() {
super.onResume();
if (mInputStream != null && mOutputStream != null) {
return;
}
UsbAccessory[] accessories = mUsbManager.getAccessoryList();
UsbAccessory accessory = (accessories == null ? null : accessories[0]);
if (accessory != null) {
if (mUsbManager.hasPermission(accessory)) {
openAccessory(accessory);
} else {
synchronized (mUsbReceiver) {
if (!mPermissionRequestPending) {
mUsbManager.requestPermission(accessory,
mPermissionIntent);
mPermissionRequestPending = true;
}
}
}
} else {
Log.d(TAG, "mAccessory is null");
}
}
#Override
public void onPause() {
super.onPause();
closeAccessory();
}
#Override
public void onDestroy() {
super.onDestroy();
unregisterReceiver(mUsbReceiver);
}
private void openAccessory(UsbAccessory accessory) {
mFileDescriptor = mUsbManager.openAccessory(accessory);
if (mFileDescriptor != null) {
mAccessory = accessory;
FileDescriptor fd = mFileDescriptor.getFileDescriptor();
mInputStream = new FileInputStream(fd);
mOutputStream = new FileOutputStream(fd);
Thread thread = new Thread(null, this, "KegApp");
thread.start();
//enableControls(true);
} else {
Log.d(TAG, "accessory open fail");
}
}
public void run() {
int ret = 0;
byte[] buffer = new byte[16384];
int i;
Log.i("KegApp", "***********************in run*************************");
while (ret >= 0) {
try {
ret = mInputStream.read(buffer); // this will be always positive, as long as the stream is not closed
} catch (IOException e) {
break;
}
i = 0;
while (i < ret) {
Message m = Message.obtain(messageHandler, MESSAGE_BUTTON_PRESSED);
m.obj = buffer[i];
messageHandler.sendMessage(m);
i++;
}
}
}
private void closeAccessory() {
//enableControls(false);
try {
if (mFileDescriptor != null) {
mFileDescriptor.close();
}
} catch (IOException e) {
} finally {
mFileDescriptor = null;
mAccessory = null;
}
}
public void sendCommand(FileOutputStream mStream) {
BufferedOutputStream bo = new BufferedOutputStream(mStream);
// if (mStream != null && message.length > 0) {
try {
Log.i("KegApp", "***********************sending command now*************************");
bo.write(1); //message, 0, 3);
} catch (IOException e) {
Log.e(TAG, "write failed", e);
}
// }
}
#Override
public void onClick(View v) {
// Send some message to Arduino board, e.g. "13"
Log.e(TAG, "write failed");
}
// Instantiating the Handler associated with the main thread.
private Handler messageHandler = new Handler() {
#Override
public void handleMessage(Message msg) {
Log.i("KegApp", "***********************message handler before " + msg.what + "************************");
try {
String load = msg.obj.toString();
Log.i("KegApp", "***********************in message handler*************************");
/*
if (button2visible==false) {
debugtext.setText("Received message: "+String.valueOf(load));
button2.setVisibility(View.VISIBLE);
button2visible = true;
} else {
debugtext.setText("");
button2.setVisibility(View.GONE);
button2visible = false;
}
*/
new TempUpdateTask().execute(load);
} catch (Exception e) {
Log.e(TAG, "message failed", e);
}
}
};
// UpdateData Asynchronously sends the value received from ADK Main Board.
// This is triggered by onReceive()
class TempUpdateTask extends AsyncTask<String, String, String> {
// Called to initiate the background activity
protected String doInBackground(String... sensorValue) {
try {
Log.i("KegApp", "***********************calling sendcommand*********************");
sendCommand(mOutputStream);
Log.i("KegApp", "*********************incoming-sensorValue*********************" );
ArduinoMessage arduinoMessage = new ArduinoMessage(sensorValue[0]);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
String returnString = String.valueOf(sensorValue[0]);//String.valueOf(sensorValue[0]) + " F";
publishProgress(String.valueOf(sensorValue[0]));
return (returnString); // This goes to result
}
// Called when there's a status to be updated
#Override
protected void onProgressUpdate(String... values) {
// Init TextView Widget to display ADC sensor value in numeric.
TextView tvAdcvalue = (TextView) findViewById(R.id.tvTemp);
tvAdcvalue.setText(String.valueOf(values[0]));
// Not used in this case
}
// Called once the background activity has completed
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
closeAccessory();
}
}
}
Here's my Arduino Sketch:
#include <FHB.h>
#include <Max3421e.h>
#include <Max3421e_constants.h>
#include <Max_LCD.h>
#include <Usb.h>
//FREEDUINO ONLY------------------------------------
//END FREEDUINO ONLY------------------------------------
int pin_light_sensor_1=A0;
int pin_output_sensor=9;
int currLightLevel=0;
//int prevLightLevel=0;
//int lightStableRange=90;
int delayTime=3000;
int loopCtr=0;
char cSTX=char(2);
char cSOH=char(1);
char cEOT=char(4);
char cGS=char(29);
char cRS=char(30);
char cCR=char(13);
char cLF=char(10);
//FREEDUINO ONLY------------------------------------
AndroidAccessory acc("Company Inc.",
"Kegbot5K datawriter",
"Kegbot 5000 data writer",
"1.0",
"http://companyinc.com",
"0000000012345678");
//END FREEDUINO ONLY------------------------------------
void setup()
{
pinMode(pin_light_sensor_1, INPUT);
pinMode(pin_output_sensor, OUTPUT);
Serial.begin(57600);
//FREEDUINO ONLY------------------------------------
Serial.println("pre-power");
acc.powerOn();
Serial.println("post-power");
//END FREEDUINO ONLY------------------------------------
}
void loop()
{
byte msg[3];
if (acc.isConnected()) {
currLightLevel = analogRead(pin_light_sensor_1);
//sysPrint(delayTime*loopCtr);
//sysPrint(",");
//sysPrint(currLightLevel);
writeDataMessage("LGH01", currLightLevel);
}
delay(1000);
if (acc.isConnected()) {
int len = acc.read(msg, sizeof(msg), 1);
Serial.println(len);
if (len > 0){
for (int index=0; index < len; index++){
digitalWrite(pin_output_sensor, 1);
delay(500);
digitalWrite(pin_output_sensor, 0);
}
}
}
loopCtr++;
delay(delayTime);
}
void writeHeader(String msgType)
{
sysPrint(cSTX);
sysPrint(cSTX);
sysPrint(cSOH);
sysPrint(msgType);
sysPrint(cGS);
}
void writeFooter()
{
sysPrint(cEOT);
sysPrintLn(cEOT);
}
void writeDataMessage(String sensorID, int value)
{
writeHeader("DATA");
sysPrint(sensorID);
sysPrint(cRS);
sysPrint(value);
writeFooter();
}
void writeAlarmMessage(String sensorID, String message)
//Do we need to enforce the 5 char sensorID here? I don't think so...
{
writeHeader("ALRM");
sysPrint(sensorID);
sysPrint(cRS);
sysPrint(message);
writeFooter();
}
void sysPrint(String whatToWrite)
{
int len=whatToWrite.length();
char str[len];
whatToWrite.toCharArray(str, len);
acc.write((void *)str, len);
// acc.write(&whatToWrite, whatToWrite.length());
}
void sysPrint(char whatToWrite)
{
acc.write((void *)whatToWrite, 1);
// acc.write(&whatToWrite, 1);
}
void sysPrint(int whatToWrite)
{
acc.write((void *)&whatToWrite, 1);
// acc.write(&whatToWrite, 1);
}
void sysPrintLn(String whatToWrite)
{
int len=whatToWrite.length();
char str[len];
whatToWrite.toCharArray(str, len);
acc.write((void *)str, len);
acc.write((void *)&cCR, 1);
acc.write((void *)&cLF, 1);
// acc.write(&whatToWrite, whatToWrite.length());
// acc.write(&cCR, 1);
// acc.write(&cLF, 1);
}
void sysPrintLn(char whatToWrite)
{
acc.write((void *)whatToWrite, 1);
acc.write((void *)&cCR, 1);
acc.write((void *)&cLF, 1);
// acc.write(&whatToWrite, 1);
// acc.write(&cCR, 1);
// acc.write(&cLF, 1);
}
The sendCommand function in the Android is logging that it was sent. The acc.read function is printing length to Serial output as -1, as in no input. Speaking of which, the Android logs do not show errors, so I'm thinking this might be an Arduino thing.
My Manifest has an Intent filter that's registering the device, although permissions might have something to do with it.
<intent-filter>
<action android:name="android.hardware.usb.action.USB_ACCESSORY_ATTACHED" />
</intent-filter>
<meta-data android:name="android.hardware.usb.action.USB_ACCESSORY_ATTACHED"
android:resource="#xml/accessory_filter" />
</activity>
Thanks in advance for any thoughts,
Sara
I have developed an RC helicopter that can be controlled using android by sending messages from the android to the arduino located on top of the Helicopter using Bluetooth Stick, i did not use usb yet for any project but when you are sending messages to the arduino you are using serial communication weather connected threw USB or Bluetooth i suggest to simply use Serial.read and every message you send to arduino end it with some symbol '#' for example just to separate messages and get the message character by character
this is the code to read the full message ended with '#' from the Serial port:
String getMessage()
{
String msg=""; //the message starts empty
byte ch; // the character that you use to construct the Message
byte d='#';// the separating symbol
if(Serial.available())// checks if there is a new message;
{
while(Serial.available() && Serial.peek()!=d)// while the message did not finish
{
ch=Serial.read();// get the character
msg+=(char)ch;//add the character to the message
delay(1);//wait for the next character
}
ch=Serial.read();// pop the '#' from the buffer
if(ch==d) // id finished
return msg;
else
return "NA";
}
else
return "NA"; // return "NA" if no message;
}
this function checks if there any message in the buffer if not it returns "NA".
if that did not help please inform.
Figured out what's going wrong - sendCommand is executing from the asynchronous TempTask so it doesn't get passed a valid reference to the FileOutputStream. I can execute sendCommand onClick from the main thread and receive on the Arduino just fine.

Categories

Resources