diff --git a/res/layout/device_list.xml b/res/layout/device_list.xml
new file mode 100644
index 0000000..5ea97be
--- /dev/null
+++ b/res/layout/device_list.xml
@@ -0,0 +1,42 @@
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/res/layout/device_name.xml b/res/layout/device_name.xml
new file mode 100644
index 0000000..e31a95b
--- /dev/null
+++ b/res/layout/device_name.xml
@@ -0,0 +1,7 @@
+
+
\ No newline at end of file
diff --git a/res/menu/device_list.xml b/res/menu/device_list.xml
new file mode 100644
index 0000000..a609e0d
--- /dev/null
+++ b/res/menu/device_list.xml
@@ -0,0 +1,9 @@
+
diff --git a/res/values-w820dp/dimens.xml b/res/values-w820dp/dimens.xml
new file mode 100644
index 0000000..63fc816
--- /dev/null
+++ b/res/values-w820dp/dimens.xml
@@ -0,0 +1,6 @@
+
+
+ 64dp
+
diff --git a/res/values/dimens.xml b/res/values/dimens.xml
new file mode 100644
index 0000000..47c8224
--- /dev/null
+++ b/res/values/dimens.xml
@@ -0,0 +1,5 @@
+
+
+ 16dp
+ 16dp
+
diff --git a/res/values/strings.xml b/res/values/strings.xml
index da2b71c..5b2ed42 100644
--- a/res/values/strings.xml
+++ b/res/values/strings.xml
@@ -6,5 +6,8 @@
Use the slider or pinch the color picker to add or subtract blue for all possible hex colors.
Use the slider to add or subtract blue, creating all possible hex colors.
Random
-
+ DeviceListActivity
+ Hello world!
+ Settings
+
\ No newline at end of file
diff --git a/src/com/trevorshp/arduinocolor/DeviceListActivity.java b/src/com/trevorshp/arduinocolor/DeviceListActivity.java
new file mode 100644
index 0000000..8628837
--- /dev/null
+++ b/src/com/trevorshp/arduinocolor/DeviceListActivity.java
@@ -0,0 +1,178 @@
+package com.trevorshp.arduinocolor;
+
+import java.util.Set;
+
+import android.app.Activity;
+import android.bluetooth.BluetoothAdapter;
+import android.bluetooth.BluetoothDevice;
+import android.content.BroadcastReceiver;
+import android.content.Context;
+import android.content.Intent;
+import android.content.IntentFilter;
+import android.os.Bundle;
+import android.util.Log;
+import android.view.View;
+import android.view.Window;
+import android.view.View.OnClickListener;
+import android.widget.AdapterView;
+import android.widget.ArrayAdapter;
+import android.widget.Button;
+import android.widget.ListView;
+import android.widget.TextView;
+import android.widget.AdapterView.OnItemClickListener;
+
+public class DeviceListActivity extends Activity {
+ // Debugging
+ private static final String TAG = "DeviceListActivity";
+ private static final boolean D = true;
+
+ // Return Intent extra
+ public static String EXTRA_DEVICE_ADDRESS = "device_address";
+
+ // Member fields
+ private BluetoothAdapter mBtAdapter;
+ private ArrayAdapter mPairedDevicesArrayAdapter;
+ private ArrayAdapter mNewDevicesArrayAdapter;
+
+ @Override
+ protected void onCreate(Bundle savedInstanceState) {
+ super.onCreate(savedInstanceState);
+
+ // Setup the window
+ requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
+ setContentView(R.layout.device_list);
+
+ // Set result CANCELED incase the user backs out
+ setResult(Activity.RESULT_CANCELED);
+
+ // Initialize the button to perform device discovery
+ Button scanButton = (Button) findViewById(R.id.button_scan);
+ scanButton.setOnClickListener(new OnClickListener() {
+ public void onClick(View v) {
+ doDiscovery();
+ v.setVisibility(View.GONE);
+ }
+ });
+
+ // Initialize array adapters. One for already paired devices and
+ // one for newly discovered devices
+ mPairedDevicesArrayAdapter = new ArrayAdapter(this, R.layout.device_name);
+ mNewDevicesArrayAdapter = new ArrayAdapter(this, R.layout.device_name);
+
+ // Find and set up the ListView for paired devices
+ ListView pairedListView = (ListView) findViewById(R.id.paired_devices);
+ pairedListView.setAdapter(mPairedDevicesArrayAdapter);
+ pairedListView.setOnItemClickListener(mDeviceClickListener);
+
+ // Find and set up the ListView for newly discovered devices
+ ListView newDevicesListView = (ListView) findViewById(R.id.new_devices);
+ newDevicesListView.setAdapter(mNewDevicesArrayAdapter);
+ newDevicesListView.setOnItemClickListener(mDeviceClickListener);
+
+ // Register for broadcasts when a device is discovered
+ IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
+ this.registerReceiver(mReceiver, filter);
+
+ // Register for broadcasts when discovery has finished
+ filter = new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
+ this.registerReceiver(mReceiver, filter);
+
+ // Get the local Bluetooth adapter
+ mBtAdapter = BluetoothAdapter.getDefaultAdapter();
+
+ // Get a set of currently paired devices
+ Set pairedDevices = mBtAdapter.getBondedDevices();
+
+ // If there are paired devices, add each one to the ArrayAdapter
+ if (pairedDevices.size() > 0) {
+ findViewById(R.id.title_paired_devices).setVisibility(View.VISIBLE);
+ for (BluetoothDevice device : pairedDevices) {
+ mPairedDevicesArrayAdapter.add(device.getName() + "\n" + device.getAddress());
+ }
+ } else {
+ mPairedDevicesArrayAdapter.add("Nenhum dispositivo pareado");
+ }
+ }
+
+ @Override
+ protected void onDestroy() {
+ super.onDestroy();
+
+ // Make sure we're not doing discovery anymore
+ if (mBtAdapter != null) {
+ mBtAdapter.cancelDiscovery();
+ }
+
+ // Unregister broadcast listeners
+ this.unregisterReceiver(mReceiver);
+ }
+
+ /**
+ * Start device discover with the BluetoothAdapter
+ */
+ private void doDiscovery() {
+ if (D) Log.d(TAG, "doDiscovery()");
+
+ // Indicate scanning in the title
+ setProgressBarIndeterminateVisibility(true);
+ setTitle("Scaneando");
+
+ // Turn on sub-title for new devices
+ findViewById(R.id.title_new_devices).setVisibility(View.VISIBLE);
+
+ // If we're already discovering, stop it
+ if (mBtAdapter.isDiscovering()) {
+ mBtAdapter.cancelDiscovery();
+ }
+
+ // Request discover from BluetoothAdapter
+ mBtAdapter.startDiscovery();
+ }
+
+ // The on-click listener for all devices in the ListViews
+ private OnItemClickListener mDeviceClickListener = new OnItemClickListener() {
+ public void onItemClick(AdapterView> av, View v, int arg2, long arg3) {
+ // Cancel discovery because it's costly and we're about to connect
+ mBtAdapter.cancelDiscovery();
+
+ // Get the device MAC address, which is the last 17 chars in the View
+ String info = ((TextView) v).getText().toString();
+ String address = info.substring(info.length() - 17);
+
+ // Create the result Intent and include the MAC address
+ Intent intent = new Intent();
+ intent.putExtra(EXTRA_DEVICE_ADDRESS, address);
+
+ // Set result and finish this Activity
+ setResult(Activity.RESULT_OK, intent);
+ finish();
+ }
+ };
+
+ // The BroadcastReceiver that listens for discovered devices and
+ // changes the title when discovery is finished
+ private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
+ @Override
+ public void onReceive(Context context, Intent intent) {
+ String action = intent.getAction();
+
+ // When discovery finds a device
+ if (BluetoothDevice.ACTION_FOUND.equals(action)) {
+ // Get the BluetoothDevice object from the Intent
+ BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
+ // If it's already paired, skip it, because it's been listed already
+ if (device.getBondState() != BluetoothDevice.BOND_BONDED) {
+ mNewDevicesArrayAdapter.add(device.getName() + "\n" + device.getAddress());
+ }
+ // When discovery is finished, change the Activity title
+ } else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) {
+ setProgressBarIndeterminateVisibility(false);
+ setTitle("Selecione o dispositivo");
+ if (mNewDevicesArrayAdapter.getCount() == 0) {
+
+ mNewDevicesArrayAdapter.add("Nao encontrado");
+ }
+ }
+ }
+ };
+}
\ No newline at end of file
diff --git a/src/com/trevorshp/arduinocolor/MainActivity.java b/src/com/trevorshp/arduinocolor/MainActivity.java
index 134e6a5..c14587d 100644
--- a/src/com/trevorshp/arduinocolor/MainActivity.java
+++ b/src/com/trevorshp/arduinocolor/MainActivity.java
@@ -1,11 +1,12 @@
package com.trevorshp.arduinocolor;
-import java.io.IOException;
-
-import android.content.Context;
+import android.app.Activity;
+import android.bluetooth.BluetoothAdapter;
+import android.bluetooth.BluetoothDevice;
+import android.bluetooth.BluetoothSocket;
+import android.content.Intent;
import android.graphics.Color;
-import android.hardware.usb.UsbManager;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.util.DisplayMetrics;
@@ -17,24 +18,35 @@
import android.widget.SeekBar;
import android.widget.SeekBar.OnSeekBarChangeListener;
import android.widget.TextView;
+import android.widget.Toast;
-import com.hoho.android.usbserial.driver.UsbSerialDriver;
-import com.hoho.android.usbserial.driver.UsbSerialProber;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.OutputStream;
+import java.util.UUID;
-
public class MainActivity extends FragmentActivity implements OnTouchListener, OnSeekBarChangeListener {
- public final static String TAG = "AndroidColor";
+
+ public final static String TAG = "AndroidColor";
public ColorPickerView colorPicker;
private TextView text1;
private static final int blueStart = 100;
-
- private UsbManager usbManager;
- private UsbSerialDriver device;
-
- @Override
+ private final int REQUEST_CONNECT_DEVICE = 1;
+ private final int REQUEST_ENABLE_BT = 9;
+ private BluetoothAdapter mBluetoothAdapter = null;
+
+ private BluetoothSocket mmSocket = null;
+ private BluetoothDevice mmDevice = null;
+ private InputStream mmInStream = null;
+ private OutputStream mmOutStream = null;
+
+ private UUID myUUID = null;
+
+ @Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
+
setContentView(R.layout.activity_main);
LinearLayout layout = (LinearLayout) findViewById(R.id.color_picker_layout);
final int width = layout.getWidth();
@@ -53,52 +65,82 @@ protected void onCreate(Bundle savedInstanceState) {
seek.setProgress(blueStart);
seek.setMax(255);
seek.setOnSeekBarChangeListener(this);
-
- // Get UsbManager from Android.
- usbManager = (UsbManager) getSystemService(Context.USB_SERVICE);
- }
+
+ //Importante! Voce deve usar o UUID correto para o SPP - Serial Port Profile
+ myUUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
+
+ mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
+
+ if (mBluetoothAdapter == null) {
+ // Device does not support Bluetooth
+ Toast.makeText(this, "Estranho. Mas esse dispositivo nao suporta bluetooth :S", Toast.LENGTH_LONG).show();
+ } else {
+ if (!mBluetoothAdapter.isEnabled()) {
+ Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
+ this.startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
+ } else {
+ // Launch the DeviceListActivity to see devices and do scan
+ Intent serverIntent = new Intent(this, DeviceListActivity.class);
+ this.startActivityForResult(serverIntent, REQUEST_CONNECT_DEVICE);
+
+ }
+ }
+ }
+
+ public void onActivityResult(int requestCode, int resultCode, Intent data) {
+ switch (requestCode) {
+ case REQUEST_CONNECT_DEVICE:
+ if (resultCode== Activity.RESULT_OK) {
+ mBluetoothAdapter.cancelDiscovery();
+
+ String endereco = data.getExtras().getString(DeviceListActivity.EXTRA_DEVICE_ADDRESS);
+ Log.i("ConexaoBluetooth", "Endereco do Bluetooth: " + endereco);
+ mmDevice = mBluetoothAdapter.getRemoteDevice(endereco);
+
+ //send the color to the serial device
+ if (mmDevice != null) {
+ try {
+
+ System.out.println(mmDevice.getName());
+ // Cria o socket utilizando o UUID
+ mmSocket = mmDevice.createInsecureRfcommSocketToServiceRecord(myUUID);
+
+ // Conecta ao dispositivo escolhido
+ mmSocket.connect();
+
+ // Obtem os fluxos de entrada e saida que lidam com transmissões através do socket
+ mmInStream = mmSocket.getInputStream();
+ mmOutStream = mmSocket.getOutputStream();
+
+ } catch (Exception ex) {
+ Log.e("ConexaoBluetooth", ex.getLocalizedMessage(), ex);
+ Toast.makeText(this, "Ocorreu um erro no envio da mensagem!" + ex.getLocalizedMessage(), Toast.LENGTH_LONG).show();
+ }
+ }
+ }
+ break;
+ }
+ }
@Override
protected void onPause() {
super.onPause();
//check if the device is already closed
- if (device != null) {
+ if (mmSocket != null) {
try {
- device.close();
+ mmSocket.close();
} catch (IOException e) {
//we couldn't close the device, but there's nothing we can do about it!
}
//remove the reference to the device
- device = null;
+ mmSocket = null;
}
}
@Override
protected void onResume() {
super.onResume();
- //get a USB to Serial device object
- device = UsbSerialProber.acquire(usbManager);
- if (device == null) {
- //there is no device connected!
- Log.d(TAG, "No USB serial device connected.");
- } else {
- try {
- //open the device
- device.open();
- //set the communication speed
- device.setBaudRate(115200); //make sure this matches your device's setting!
- } catch (IOException err) {
- Log.e(TAG, "Error setting up USB device: " + err.getMessage(), err);
- try {
- //something failed, so try closing the device
- device.close();
- } catch (IOException err2) {
- //couldn't close, but there's nothing more to do!
- }
- device = null;
- return;
- }
- }
+
}
@Override
@@ -115,15 +157,43 @@ private void sendToArduino(int color){
dataToSend[i] = 0x0B;
}
}
- //send the color to the serial device
- if (device != null){
- try{
- device.write(dataToSend, 500);
- }
- catch (IOException e){
- Log.e(TAG, "couldn't write color bytes to serial device");
- }
- }
+
+ if (mmOutStream!=null) {
+ try {
+ // Saida:
+ // Envio de uma mensagem pelo .write
+ mmOutStream.write(dataToSend);
+
+ Log.i("sendToArduino", String.valueOf(dataToSend));
+
+ /*
+ // Entrada:
+ // bytes returnados da read()
+ //int bytes;
+ // buffer de memória para o fluxo
+ //byte[] read = new byte[1024];
+
+ // Continuar ouvindo o InputStream enquanto conectado
+ // O loop principal é dedicado a leitura do InputStream
+
+ while (true) {
+ try {
+ // Read from the InputStream
+ bytes = mmInStream.read(read);
+
+ String readMessage = new String(read);
+ Toast.makeText(this, readMessage, Toast.LENGTH_LONG).show();
+
+ } catch (IOException e) {
+ Toast.makeText(this, "Ocorreu um erro no recebimento da mensagem!", Toast.LENGTH_LONG).show();
+ }
+ }
+ */
+
+ } catch (IOException e) {
+ Toast.makeText(this, "Ocorreu um erro!", Toast.LENGTH_LONG).show();
+ }
+ }
}
// sets the text boxes' text and color background.