Compare commits

..

5 Commits

3 changed files with 82 additions and 242 deletions

View File

@ -7,6 +7,8 @@
<uses-permission android:name="android.permission.BLUETOOTH_CONNECT" /> <uses-permission android:name="android.permission.BLUETOOTH_CONNECT" />
<uses-permission android:name="android.permission.BLUETOOTH_SCAN" />
<application <application
android:allowBackup="true" android:allowBackup="true"
android:dataExtractionRules="@xml/data_extraction_rules" android:dataExtractionRules="@xml/data_extraction_rules"

View File

@ -1,5 +1,6 @@
package pt.epvc.lazzycofee; package pt.epvc.lazzycofee;
import android.Manifest;
import android.bluetooth.BluetoothAdapter; import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice; import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket; import android.bluetooth.BluetoothSocket;
@ -8,6 +9,7 @@ import android.content.pm.PackageManager;
import android.os.Bundle; import android.os.Bundle;
import android.os.Handler; import android.os.Handler;
import android.os.SystemClock; import android.os.SystemClock;
import android.util.Log;
import android.view.View; import android.view.View;
import android.view.WindowManager; import android.view.WindowManager;
import android.widget.AdapterView; import android.widget.AdapterView;
@ -35,21 +37,12 @@ import java.util.UUID;
public class MainActivity extends AppCompatActivity { public class MainActivity extends AppCompatActivity {
private ImageButton cafeCurto;
private ImageButton cafeMédio;
private ImageButton cafeLongo;
private Switch conetar;
private BluetoothAdapter mBTAdapter; private BluetoothAdapter mBTAdapter;
private Set<BluetoothDevice> mPairedDevices;
private ArrayAdapter<String> mBTArrayAdapter;
private ListView mDevicesListView;
private Handler mHandler; // Our main handler that will receive callback notifications
private ConnectedThread mConnectedThread; // bluetooth background worker thread to send and receive data private ConnectedThread mConnectedThread; // bluetooth background worker thread to send and receive data
private BluetoothSocket mBTSocket = null; // bi-directional client-to-client data path private BluetoothSocket mBTSocket = null; // bi-directional client-to-client data path
private static final UUID BTMODULEUUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB"); private static final UUID BTMODULEUUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
private final static int REQUEST_ENABLE_BT = 1; // used to identify adding bluetooth names private final static int REQUEST_ENABLE_BT = 1; // used to identify adding bluetooth names
private final static int MESSAGE_READ = 2; // used in bluetooth handler to identify message update private boolean bluetoothDenied = false;
private final static int CONNECTING_STATUS = 3; // used in bluetooth handler to identify message status
@Override @Override
@ -62,60 +55,19 @@ public class MainActivity extends AppCompatActivity {
v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom); v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom);
return insets; return insets;
}); });
cafeCurto = (ImageButton) findViewById(R.id.cafeCurto); if (ActivityCompat.checkSelfPermission(this, Manifest.permission.BLUETOOTH_CONNECT) != PackageManager.PERMISSION_GRANTED) {
cafeMédio = (ImageButton) findViewById(R.id.cafeMedio); ActivityCompat.requestPermissions(this,
cafeLongo = (ImageButton) findViewById(R.id.cafeLongo); new String[]{Manifest.permission.BLUETOOTH_CONNECT, Manifest.permission.BLUETOOTH_SCAN},
2);
}
mBTArrayAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1);
mBTAdapter = BluetoothAdapter.getDefaultAdapter(); // get a handle on the bluetooth radio mBTAdapter = BluetoothAdapter.getDefaultAdapter(); // get a handle on the bluetooth radio
mHandler = new Handler() {
public void handleMessage(android.os.Message msg) {
if (msg.what == MESSAGE_READ) {
String readMessage = null;
try {
readMessage = new String((byte[]) msg.obj, "UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
//mReadBuffer.setText(readMessage);
}
if (msg.what == CONNECTING_STATUS) {
if (msg.arg1 == 1)
Toast.makeText(MainActivity.this, "Connected to Device: " + (String) (msg.obj), Toast.LENGTH_SHORT).show();
//mBluetoothStatus.setText("Connected to Device: " + (String)(msg.obj));
else
Toast.makeText(MainActivity.this, "Connection Failed", Toast.LENGTH_SHORT).show();
//mBluetoothStatus.setText("Connection Failed");
}
}
};
if (mBTArrayAdapter == null) {
// Device does not support Bluetooth
//mBluetoothStatus.setText("Status: Bluetooth not found");
Toast.makeText(MainActivity.this, "Bluetooth device not found!", Toast.LENGTH_SHORT).show();
} else {
conetar = (Switch) findViewById(R.id.conetar);
conetar.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (conetar.isChecked()) {
Toast.makeText(MainActivity.this, "Conetado", Toast.LENGTH_SHORT).show();
ligarBluetooth();
} else {
Toast.makeText(MainActivity.this, "Desconetado", Toast.LENGTH_SHORT).show();
desligarBluetooth();
}
}
});
}
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN); getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
ligarBluetooth(); if (ActivityCompat.checkSelfPermission(this, Manifest.permission.BLUETOOTH_CONNECT)
!= PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.BLUETOOTH_CONNECT, Manifest.permission.BLUETOOTH_SCAN},
2);
}
} }
public void cafeCurto(View view) { public void cafeCurto(View view) {
@ -144,17 +96,19 @@ public class MainActivity extends AppCompatActivity {
} }
public void ligarBluetooth() { public void ligarBluetooth() {
if (mBTAdapter == null) {
runOnUiThread(() ->
Toast.makeText(MainActivity.this, "Dispositivo não suporta Bluetooth", Toast.LENGTH_LONG).show()
);
return;
}
mBTAdapter = BluetoothAdapter.getDefaultAdapter(); mBTAdapter = BluetoothAdapter.getDefaultAdapter();
if (!mBTAdapter.isEnabled()) { if (!mBTAdapter.isEnabled()) {
Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE); Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT); startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
//mBluetoothStatus.setText("Bluetooth enabled");
Toast.makeText(MainActivity.this, "Bluetooth turned on", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(MainActivity.this, "Bluetooth is already on", Toast.LENGTH_SHORT).show();
} }
//listarAparelhos(); else{
final String address = "98:D3:21:FC:7F:DF"; final String address = "98:D3:21:FC:7F:DF";
new Thread() { new Thread() {
public void run() { public void run() {
@ -166,43 +120,34 @@ public class MainActivity extends AppCompatActivity {
mBTSocket = createBluetoothSocket(device); mBTSocket = createBluetoothSocket(device);
} catch (IOException e) { } catch (IOException e) {
fail = true; fail = true;
Toast.makeText(getBaseContext(), "Socket creation failed", Toast.LENGTH_SHORT).show(); Log.d("bluetooth","Socket creation failed");
} }
// Establish the Bluetooth socket connection.
try { try {
if (ActivityCompat.checkSelfPermission(MainActivity.this, android.Manifest.permission.BLUETOOTH_CONNECT) != PackageManager.PERMISSION_GRANTED) { if (ActivityCompat.checkSelfPermission(MainActivity.this, android.Manifest.permission.BLUETOOTH_CONNECT) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
// ActivityCompat#requestPermissions
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more details.
return; return;
} }
mBTAdapter.cancelDiscovery();
mBTSocket.connect(); mBTSocket.connect();
} catch (IOException e) { } catch (IOException e) {
try { try {
fail = true; fail = true;
mBTSocket.close(); mBTSocket.close();
mHandler.obtainMessage(CONNECTING_STATUS, -1, -1)
.sendToTarget();
} catch (IOException e2) { } catch (IOException e2) {
//insert code to deal with this Log.d("bluetooth","Socket creation failed");
Toast.makeText(getBaseContext(), "Socket creation failed", Toast.LENGTH_SHORT).show();
} }
} }
if (fail == false) { if (fail == false) {
mConnectedThread = new ConnectedThread(mBTSocket); mConnectedThread = new ConnectedThread(mBTSocket);
mConnectedThread.start(); mConnectedThread.start();
mHandler.obtainMessage(CONNECTING_STATUS, 1, -1, "ASD")
.sendToTarget();
} }
} }
}.start(); }.start();
} }
}
@Override @Override
protected void onActivityResult(int requestCode, int resultCode, Intent Data) { protected void onActivityResult(int requestCode, int resultCode, Intent Data) {
// Check which request we're responding to // Check which request we're responding to
@ -210,170 +155,72 @@ public class MainActivity extends AppCompatActivity {
if (requestCode == REQUEST_ENABLE_BT) { if (requestCode == REQUEST_ENABLE_BT) {
// Make sure the request was successful // Make sure the request was successful
if (resultCode == RESULT_OK) { if (resultCode == RESULT_OK) {
// The user picked a contact. ligarBluetooth();
// The Intent's data Uri identifies which contact was selected. Toast.makeText(this, "Bluetooth Ligado", Toast.LENGTH_SHORT).show();
//mBluetoothStatus.setText("Enabled"); } else {
Toast.makeText(this, "Enabled", Toast.LENGTH_SHORT).show(); bluetoothDenied = true;
} else Toast.makeText(this, "A App Precisa de Bluetooth para Funcionar", Toast.LENGTH_SHORT).show();
Toast.makeText(this, "Disabled", Toast.LENGTH_SHORT).show(); finish();
//mBluetoothStatus.setText("Disabled"); }
} }
} }
public void listarAparelhos() {
if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.BLUETOOTH_CONNECT) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
// ActivityCompat#requestPermissions
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more details.
return;
}
mPairedDevices = mBTAdapter.getBondedDevices();
if (mBTAdapter.isEnabled()) {
// put it's one to the adapter
for (BluetoothDevice device : mPairedDevices)
mBTArrayAdapter.add(device.getName() + "\n" + device.getAddress());
Toast.makeText(getApplicationContext(), "Show Paired Devices", Toast.LENGTH_SHORT).show();
} else
Toast.makeText(getApplicationContext(), "Bluetooth not on", Toast.LENGTH_SHORT).show();
}
public void desligarBluetooth() {
//mBTAdapter.disable(); // turn off
//mBluetoothStatus.setText("Bluetooth disabled");
Toast.makeText(MainActivity.this, "Bluetooth turned Off", Toast.LENGTH_SHORT).show();
}
private AdapterView.OnItemClickListener mDeviceClickListener = new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> av, View v, int arg2, long arg3) {
if (!mBTAdapter.isEnabled()) {
Toast.makeText(getBaseContext(), "Bluetooth not on", Toast.LENGTH_SHORT).show();
return;
}
Toast.makeText(MainActivity.this, "Connecting...", Toast.LENGTH_SHORT).show();
//mBluetoothStatus.setText("Connecting...");
// Get the device MAC address, which is the last 17 chars in the View
String info = ((TextView) v).getText().toString();
final String address = info.substring(info.length() - 17);
final String name = info.substring(0, info.length() - 17);
// Spawn a new thread to avoid blocking the GUI one
new Thread() {
public void run() {
boolean fail = false;
BluetoothDevice device = mBTAdapter.getRemoteDevice(address);
try {
mBTSocket = createBluetoothSocket(device);
} catch (IOException e) {
fail = true;
Toast.makeText(getBaseContext(), "Socket creation failed", Toast.LENGTH_SHORT).show();
}
// Establish the Bluetooth socket connection.
try {
if (ActivityCompat.checkSelfPermission(MainActivity.this, android.Manifest.permission.BLUETOOTH_CONNECT) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
// ActivityCompat#requestPermissions
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more details.
return;
}
mBTSocket.connect();
} catch (IOException e) {
try {
fail = true;
mBTSocket.close();
mHandler.obtainMessage(CONNECTING_STATUS, -1, -1)
.sendToTarget();
} catch (IOException e2) {
//insert code to deal with this
Toast.makeText(getBaseContext(), "Socket creation failed", Toast.LENGTH_SHORT).show();
}
}
if (fail == false) {
mConnectedThread = new ConnectedThread(mBTSocket);
mConnectedThread.start();
mHandler.obtainMessage(CONNECTING_STATUS, 1, -1, name)
.sendToTarget();
}
}
}.start();
}
};
private BluetoothSocket createBluetoothSocket(BluetoothDevice device) throws IOException { private BluetoothSocket createBluetoothSocket(BluetoothDevice device) throws IOException {
if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.BLUETOOTH_CONNECT) != PackageManager.PERMISSION_GRANTED) { if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.BLUETOOTH_CONNECT) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
// ActivityCompat#requestPermissions
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more details.
} }
return device.createRfcommSocketToServiceRecord(BTMODULEUUID); return device.createRfcommSocketToServiceRecord(BTMODULEUUID);
//creates secure outgoing connection with BT device using UUID
} }
private class ConnectedThread extends Thread { private class ConnectedThread extends Thread {
private final BluetoothSocket mmSocket;
private final InputStream mmInStream;
private final OutputStream mmOutStream; private final OutputStream mmOutStream;
public ConnectedThread(BluetoothSocket socket) { public ConnectedThread(BluetoothSocket socket) {
mmSocket = socket;
InputStream tmpIn = null;
OutputStream tmpOut = null; OutputStream tmpOut = null;
// Get the input and output streams, using temp objects because
// member streams are final
try { try {
tmpIn = socket.getInputStream();
tmpOut = socket.getOutputStream(); tmpOut = socket.getOutputStream();
} catch (IOException e) { } catch (IOException e) {
Log.e("Bluetooth", "Erro ao obter OutputStream", e);
} }
mmInStream = tmpIn;
mmOutStream = tmpOut; mmOutStream = tmpOut;
} }
public void run() {
byte[] buffer = new byte[1024]; // buffer store for the stream
int bytes; // bytes returned from read()
// Keep listening to the InputStream until an exception occurs
while (true) {
try {
// Read from the InputStream
bytes = mmInStream.available();
if (bytes != 0) {
SystemClock.sleep(100); //pause and wait for rest of data. Adjust this depending on your sending speed.
bytes = mmInStream.available(); // how many bytes are ready to be read?
bytes = mmInStream.read(buffer, 0, bytes); // record how many bytes we actually read
mHandler.obtainMessage(MESSAGE_READ, bytes, -1, buffer)
.sendToTarget(); // Send the obtained bytes to the UI activity
}
} catch (IOException e) {
e.printStackTrace();
break;
}
}
}
public void enviarComando(String input){ public void enviarComando(String input){
byte[] bytes = input.getBytes(); //converts entered String into bytes byte[] bytes = input.getBytes(); //converts entered String into bytes
try { try {
mmOutStream.write(bytes); mmOutStream.write(bytes);
} catch (IOException e) { } } catch (IOException e) {
Log.e("Bluetooth", "Erro ao obter OutputStream", e);
}
}
}
private void desligarBluetooth() {
try {
if (mConnectedThread != null) {
mConnectedThread.interrupt();
}
if (mBTSocket != null) {
mBTSocket.close();
mBTSocket = null;
}
} catch (IOException e) {
Log.e("Bluetooth", "Erro ao desligar", e);
}
}
@Override
protected void onPause() {
super.onPause();
desligarBluetooth();
}
@Override
protected void onResume() {
super.onResume();
if ((mBTSocket == null || !mBTSocket.isConnected()) && !bluetoothDenied) {
ligarBluetooth();
} }
} }
} }

View File

@ -20,16 +20,7 @@
android:layout_alignParentTop="true" android:layout_alignParentTop="true"
android:layout_margin="16sp"/> android:layout_margin="16sp"/>
<Switch
android:id="@+id/conetar"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:layout_margin="30dp"
android:text="@string/ligarmaquina"
android:textColor="#745426"
android:textSize="13pt"/>
<LinearLayout <LinearLayout
android:id="@+id/botoes" android:id="@+id/botoes"
android:layout_marginTop="150dp" android:layout_marginTop="150dp"