Skip to content

Instantly share code, notes, and snippets.

@abdul-rehman-2050
Created December 7, 2017 10:35
Show Gist options
  • Save abdul-rehman-2050/ed2e9ac17c3185e1af7cd9dea5fdcf0c to your computer and use it in GitHub Desktop.
Save abdul-rehman-2050/ed2e9ac17c3185e1af7cd9dea5fdcf0c to your computer and use it in GitHub Desktop.
package com.bluetooth.home.auto;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.lang.reflect.Method;
import java.util.UUID;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.app.Activity;
import android.app.AlertDialog;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.DialogInterface;
import android.content.Intent;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.SeekBar;
import android.widget.SeekBar.OnSeekBarChangeListener;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity {
Handler h;
final int RECIEVE_MESSAGE = 1; // Status for Handler
private BluetoothAdapter btAdapter = null;
private BluetoothDevice hardwareDevice = null;
private boolean isHardwareConnected = false;
private BluetoothSocket btSocket = null;
private Button btn_connectBT=null;
private Button btn_d1on = null;
private Button btn_d1of,btn_d2of,btn_d3of,btn_d4of,btn_d2on,btn_d3on,btn_d4on;
private TextView tv_status=null;
private StringBuilder sb = new StringBuilder();
private ConnectedThread mConnectedThread;
private SeekBar pwmseekBar;
private SeekBar ppmseekBar;
// SPP UUID service
private static final UUID MY_UUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
private static final String TAG = "BT::example01";
// MAC-address of Bluetooth module (you must edit this line)
private static String address = "98:D3:31:70:64:77";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//------------------------------------------------------
btn_connectBT = (Button)findViewById(R.id.button1);
btn_d1on = (Button)findViewById(R.id.button2);
btn_d2on = (Button)findViewById(R.id.button3);
btn_d3on = (Button)findViewById(R.id.button4);
btn_d4on = (Button)findViewById(R.id.button5);
btn_d1of = (Button)findViewById(R.id.button6);
btn_d2of = (Button)findViewById(R.id.button7);
btn_d3of = (Button)findViewById(R.id.button8);
btn_d4of = (Button)findViewById(R.id.button9);
tv_status = (TextView)findViewById(R.id.textView1);
ppmseekBar = (SeekBar)findViewById(R.id.seekBar1);
pwmseekBar = (SeekBar)findViewById(R.id.seekBar2);
//------------------------------------------------------
h = new Handler() {
public void handleMessage(android.os.Message msg) {
switch (msg.what) {
case RECIEVE_MESSAGE: // if receive massage
byte[] readBuf = (byte[]) msg.obj;
String strIncom = new String(readBuf, 0, msg.arg1); // create string from bytes array
//Toast.makeText(getBaseContext(), strIncom, Toast.LENGTH_SHORT).show();
sb.append(strIncom); // append string
int endOfLineIndex = sb.indexOf("\r\n"); // determine the end-of-line
if (endOfLineIndex > 0) { // if end-of-line,
String sbprint = sb.substring(0, endOfLineIndex); // extract string
sb.delete(0, sb.length()); // and clear
tv_status.setText("Data from Arduino: " + sbprint); // update TextView
}
//Log.d(TAG, "...String:"+ sb.toString() + "Byte:" + msg.arg1 + "...");
break;
}
};
};
//----------------------------------------------------------------------------
pwmseekBar.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {
int progress = 0;
@Override
public void onStopTrackingTouch(SeekBar arg0) {
String str = "FAN: " + progress + "/" + pwmseekBar.getMax();
Toast.makeText(getApplicationContext(), str, Toast.LENGTH_SHORT).show();
if(progress>0){
progress=progress+50;
}
mConnectedThread.write("F"+progress+",");
}
@Override
public void onStartTrackingTouch(SeekBar arg0) {
// TODO Auto-generated method stub
}
@Override
public void onProgressChanged(SeekBar arg0, int arg1, boolean arg2) {
progress = arg1;
}
});
//-----------------------------------------------------------------------------
//----------------------------------------------------------------------------
ppmseekBar.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {
int progress = 0;
@Override
public void onStopTrackingTouch(SeekBar arg0) {
String str = "BULB: " + progress + "/" + ppmseekBar.getMax();
Toast.makeText(getApplicationContext(), str, Toast.LENGTH_SHORT).show();
mConnectedThread.write("B"+progress+",");
}
@Override
public void onStartTrackingTouch(SeekBar arg0) {
// TODO Auto-generated method stub
}
@Override
public void onProgressChanged(SeekBar arg0, int arg1, boolean arg2) {
progress = arg1;
}
});
//----------------------------------------------------------------------------
btn_connectBT.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
if(isHardwareConnected==false)
{
TryConnect();
btn_connectBT.setText("Disconnect");
}else
{
DisconnectBT();
btn_connectBT.setText("Connect");
}
}
});
//-----------------------------------------------------------------------------
btAdapter = BluetoothAdapter.getDefaultAdapter();
checkBTState();
hardwareDevice = btAdapter.getRemoteDevice(address);
if(hardwareDevice.getAddress().equalsIgnoreCase(address))
{
showMessageBox("Hardware Found", "found");
}
else
{
showMessageBox("Hardware is not Paired", "Error");
}
TryConnect();
if(isHardwareConnected)
{
btn_connectBT.setText("Disconnect");
}
else
{
btn_connectBT.setText("Try Connect");
}
//===========================================================
btn_d1on.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
mConnectedThread.write("2");
}
});
//-------------------------------------------------------------
btn_d2on.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
mConnectedThread.write("4");
}
});
//-------------------------------------------------------------
btn_d3on.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
mConnectedThread.write("6");
}
});
//-------------------------------------------------------------
btn_d4on.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
mConnectedThread.write("8");
}
});
//-------------------------------------------------------------
//-------------------------------------------------------------
btn_d1of.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
mConnectedThread.write("1");
}
});
//-------------------------------------------------------------
btn_d2of.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
mConnectedThread.write("3");
}
});
//-------------------------------------------------------------
btn_d3of.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
mConnectedThread.write("5");
}
});
//-------------------------------------------------------------
btn_d4of.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
mConnectedThread.write("7");
}
});
//-------------------------------------------------------------
}//onCreate ends here
//================================================================================
private void DisconnectBT()
{
Log.d(TAG, "...In onPause()...");
try {
btSocket.close();
} catch (IOException e2) {
finish();
}
isHardwareConnected = false;
}
private void TryConnect()
{
// Two things are needed to make a connection:
// A MAC address, which we got above.
// A Service ID or UUID. In this case we are using the
// UUID for SPP.
try {
btSocket = createBluetoothSocket(hardwareDevice);
} catch (IOException e) {
showMessageBox(e.getMessage(), "socket create Error");
isHardwareConnected=false;
finish();
}
// Discovery is resource intensive. Make sure it isn't going on
// when you attempt to connect and pass your message.
// btAdapter.cancelDiscovery();
// Establish the connection. This will block until it connects.
Log.d(TAG, "...Connecting...");
try {
btSocket.connect();
showMessageBox("Connection ok", "Connected");
} catch (IOException e) {
try {
btSocket.close();
} catch (IOException e2) {
showMessageBox(e.getMessage(), "Exeption::connect");
}
}
// Create a data stream so we can talk to server.
Log.d(TAG, "...Create Socket...");
isHardwareConnected=true;
mConnectedThread = new ConnectedThread(btSocket);
mConnectedThread.start();
}
private void checkBTState() {
if (btAdapter == null) {
showMessageBox("Bluetooth Not supported...", "Fatal Error");
finish();
}
if (!btAdapter.isEnabled()) {
Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent, 1);
}
}
@Override
public void onPause() {
super.onPause();
DisconnectBT();
}
private BluetoothSocket createBluetoothSocket(BluetoothDevice device) throws IOException {
if(Build.VERSION.SDK_INT >= 10){
try {
final Method m = device.getClass().getMethod("createInsecureRfcommSocketToServiceRecord", new Class[] { UUID.class });
return (BluetoothSocket) m.invoke(device, MY_UUID);
} catch (Exception e) {
Log.e(TAG, "Could not create Insecure RFComm Connection",e);
}
}
return device.createRfcommSocketToServiceRecord(MY_UUID);
}
//======================================================================================
public void showMessageBox(String Msg,String titleText )
{
AlertDialog alertDialog = new AlertDialog.Builder(MainActivity.this).create();
alertDialog.setTitle(titleText);
alertDialog.setMessage(Msg);
alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
//here you can add functions
} });
alertDialog.show();
}
//==========================================================================================
private class ConnectedThread extends Thread {
private final InputStream mmInStream;
private final OutputStream mmOutStream;
public ConnectedThread(BluetoothSocket socket) {
InputStream tmpIn = null;
OutputStream tmpOut = null;
// Get the input and output streams, using temp objects because
// member streams are final
try {
tmpIn = socket.getInputStream();
tmpOut = socket.getOutputStream();
} catch (IOException e) { }
mmInStream = tmpIn;
mmOutStream = tmpOut;
}
public void run() {
byte[] buffer = new byte[256]; // 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.read(buffer); // Get number of bytes and message in "buffer"
h.obtainMessage(RECIEVE_MESSAGE, bytes, -1, buffer).sendToTarget(); // Send to message queue Handler
} catch (IOException e) {
break;
}
}
}
/* Call this from the main activity to send data to the remote device */
public void write(String message) {
Log.d(TAG, "...Data to send: " + message + "...");
byte[] msgBuffer = message.getBytes();
try {
mmOutStream.write(msgBuffer);
} catch (IOException e) {
Log.d(TAG, "...Error data send: " + e.getMessage() + "...");
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment