AutoBlindz

wellofflimpetΚινητά – Ασύρματες Τεχνολογίες

14 Δεκ 2013 (πριν από 3 χρόνια και 5 μήνες)

89 εμφανίσεις

/*


* Copyright (C) 2013 Home Blue Automation


*


* This work is licensed under a Creative Commons Attribution
-
Non
commercial
-
Share Alike 3.0 Unported License.


* See the following website for more information:


* http://creativecommons.org/licenses/
by
-
nc
-
sa/3.0/


*


*/


package com.powergearperformance.autoblindz;


import java.io.IOException;

import java.io.OutputStream;

import java.nio.ByteBuffer;

import java.util.UUID;


import com.powergearperformance.autoblindz.R.drawable;


import an
droid.app.Activity;

import android.app.AlertDialog;

import android.app.ProgressDialog;

import android.bluetooth.BluetoothAdapter;

import android.bluetooth.BluetoothDevice;

import android.bluetooth.BluetoothSocket;

import android.content.Context;

imp
ort android.content.DialogInterface;

import android.content.DialogInterface.OnClickListener;

import android.content.Intent;

import android.net.Uri;

import android.os.Bundle;

import android.os.Handler;

import android.os.Message;

import android.view.L
ayoutInflater;

import android.view.Menu;

import android.view.MenuInflater;

import android.view.MenuItem;

import android.view.MotionEvent;

import android.view.View;

import android.view.View.OnTouchListener;

import android.widget.Button;

import andro
id.widget.TextView;

import android.widget.Toast;

import android.widget.ToggleButton;

import android.widget.SeekBar;

import android.widget.SeekBar.OnSeekBarChangeListener;


@SuppressWarnings("unused")

public class AutoBlindz extends Activity {



//

Intent request codes


private static final int REQUEST_CONNECT_DEVICE = 1;


private static final int REQUEST_ENABLE_BT = 2;



// Program variables


private byte AttinyOut;


private byte[] Control;


private boolean connectStat = false;


private boo
lean lightStat = false;


private Button open_button;


private Button close_button;


private Button connect_button;


private ToggleButton lights_button;


private Button fan_button;


private AlertDialog aboutAlert;


private View aboutView;


private V
iew controlView;


private TextView device_status;


private TextView seekbar_title;


private TextView seekbar_progress;


OnClickListener myClickListener;


ProgressDialog myProgressDialog;


private Toast failToast;


private Handler mHandler;


private

SeekBar lightbright;



// Blue tooth Stuff


private BluetoothAdapter mBluetoothAdapter = null;


private BluetoothSocket btSocket = null;


private OutputStream outStream = null;


private ConnectThread mConnectThread = null;


private String deviceAdd
ress = null;


private String deviceName = null;


// Well known SPP UUID (will *probably* map to RFCOMM channel 1
(default) if


// not in use);


private static final UUID SPP_UUID = UUID




.fromString("00001101
-
0000
-
1000
-
8000
-
00805F9B34FB");


private

static final int GONE = 0;


protected static final int VISIBLE = 1;


private int fanCount=1; //initialize to 1; turn on fan when button
pressed



/** Called when the activity is first created. */


@Override


public void onCreate(Bundle savedInstanc
eState) {



super.onCreate(savedInstanceState);




// Create main button view



LayoutInflater inflater = (LayoutInflater)
getSystemService(Context.LAYOUT_INFLATER_SERVICE);



aboutView = inflater.inflate(R.layout.aboutview, null);



controlView = in
flater.inflate(R.layout.main, null);



controlView.setKeepScreenOn(true);



setContentView(controlView);




// Finds device text view



device_status = (TextView) findViewById(R.id.device_status);



seekbar_title = (TextView) findViewById(R.id.seekba
r_title);



seekbar_progress = (TextView)
findViewById(R.id.seekbar_progress);









// Finds buttons in layout file



open_button = (Button) findViewById(R.id.open_button);



close_button = (Button) findViewById(R.id.close_button);



connect_butt
on = (Button) findViewById(R.id.connect_button);



lights_button = (ToggleButton)
findViewById(R.id.lights_button);



fan_button = (Button) findViewById(R.id.fan_button);




// Find SeekBar Slider



lightbright = (SeekBar) findViewById(R.id.lightbrigh
t);






// Handle click events from help and info dialogs



myClickListener = new DialogInterface.OnClickListener() {




// @Override




public void onClick(DialogInterface dialog, int which) {





switch (which) {





case DialogInterface.BUTTON_P
OSITIVE:






dialog.dismiss();






break;





case DialogInterface.BUTTON_NEUTRAL:






// Display website






Intent browserIntent = new Intent(








"android.intent.action.VIEW",








Uri.parse(getResources().getString(










R.string.w
ebsite_url)));






startActivity(browserIntent);






break;





default:






dialog.dismiss();





}




}



};




myProgressDialog = new ProgressDialog(this);



failToast = Toast.makeText(this, R.string.failedToConnect,





Toast.LENGTH_SHORT
);




mHandler = new Handler() {




@Override




public void handleMessage(Message msg) {





if (myProgressDialog.isShowing()) {






myProgressDialog.dismiss();





}






// Check if blue tooth connection was made to
selected device





if (ms
g.what == 1) {






// Set button to display current status






connectStat = true;






connect_button.setText(R.string.connected);






device_status.setText("Connected to: " +
deviceName);







// Reset the AutoBlindz






AttinyOut = 0;






write(AttinyOut);





} else {






// Connection failed






failToast.show();





}




}



};




// Create about dialog



AlertDialog.Builder builder = new AlertDialog.Builder(this);



builder.setView(aboutView)





.setCancelable(true)





.
setTitle(







getResources().getString(R.string.app_name) + " "









+
getResources().getString(R.string.appVersion))





.setIcon(R.drawable.homeblue)





.setPositiveButton(getResources().getString(R.string.okButton),







myClickListener)





.setNeutralButton(







getResources().getString(R.string.websiteButton),







myClickListener);



aboutAlert = builder.create();




// Check whether bluetooth adapter exists



mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();



if (mBlu
etoothAdapter == null) {




Toast.makeText(this, R.string.no_bt_device,
Toast.LENGTH_LONG)






.show();




finish();




return;



}




// If BT is not on, request that it be enabled.



if (!mBluetoothAdapter.isEnabled()) {




Intent enableIntent
= new Intent(






BluetoothAdapter.ACTION_REQUEST_ENABLE);




startActivityForResult(enableIntent, REQUEST_ENABLE_BT);



}




/******************************************************************
****




* B




*/




// Connect to Blue tooth Module



connect_button.setOnClickListener(new View.OnClickListener()
{





// Override




public void onClick(View v) {






if (connectStat) {






// Attempt to disconnect from the device






disconnect();





} else {






// Attempt to connect to
the device






connect();





}




}



});




// Turn on Lights to Blue tooth Module



lights_button.setOnClickListener(new View.OnClickListener() {





// @Override




public void onClick(View v) {





//AttinyOut=0;




if (connectStat==true)
{





if (lightStat==false) {






seekbar_title.setVisibility(View.VISIBLE);






seekbar_progress.setVisibility(View.VISIBLE);






lightbright.setVisibility(View.VISIBLE);






Control =new byte[2];






Control[0]=(byte)(76);






Control[1]=(by
te)(84);






lights_button.setText(R.string.LightsOFF);






writeByte(Control);






lightStat = true;





} else if (lightStat==true){






seekbar_title.setVisibility(View.GONE);






seekbar_progress.setVisibility(View.GONE);






lightbright.s
etVisibility(View.GONE);






Control =new byte[2];






Control[0]=(byte)(76);






Control[1]=(byte)(70);






lights_button.setText(R.string.lightsON);






writeByte(Control);






lightStat = false;





}




}





}



});




// Turn on Fa
n and control motor speed





fan_button.setOnClickListener(new
View.OnClickListener() {







// @Override






public void onClick(View v) {













if (connectStat==true){








//Sets fan to low speed







if (fanCount==1) {








Contr
ol =new byte[2];








Control[0]=(byte)(76);








Control[1]=(byte)(87);








fan_button.setText(R.string.fanLow);








writeByte(Control);






















} //Sets fan to Medium speed







else if (fanCount==2){








Control =new b
yte[2];








Control[0]=(byte)(77);








Control[1]=(byte)(68);








fan_button.setText(R.string.fanMed);








writeByte(Control);















}







// Sets fan to high speed







else if (fanCount==3){








Control =new byte[2];








Control[0]=(byte)(72);








Control[1]=(byte)(71);








fan_button.setText(R.string.fanHigh);








fanCount=
-
1; //reset count to
turn off fan on next click








writeByte(Control);








}







// turns off fan







else if (fanCoun
t==0) {








Control =new byte[2];








Control[0]=(byte)(79);








Control[1]=(byte)(70);








fan_button.setText(R.string.fanOn);








writeByte(Control);







}






}







fanCount++;






}










});



// Open blinds



open
_button.setOnTouchListener(new OnTouchListener() {








//@Override




public boolean onTouch(View v, MotionEvent event) {





if(event.getAction()==MotionEvent.ACTION_DOWN)





{





((Button)findViewById(R.id.open_button)).setBackgroundResource(R
.dr
awable.blackon);





//AttinyOut = (byte)(85); // Send as decimal 85,
hex is 55





Control =new byte[2];





Control[0]=(byte)(85);





Control[1]=(byte)(80);





writeByte(Control);





return true;





}





if(event.getAction()==MotionEvent.
ACTION_UP){






((Button)findViewById(R.id.open_button)).setBackgroundResource(R.dr
awable.black_btn);





//AttinyOut = (byte) (83);





Control =new byte[2];





Control[0]= (byte)(83);





Control[1]= (byte)(80); //ascii 'P'





writeByte(Control)
;





return true;





}





return false;




}



});




// Close blinds



close_button.setOnTouchListener(new OnTouchListener() {





// @Override




public boolean onTouch(View v, MotionEvent event) {





if(event.getAction()==MotionEvent.ACT
ION_DOWN)





{





((Button)findViewById(R.id.close_button)).setBackgroundResource(R.d
rawable.blackon);





//AttinyOut = (byte)(68); // Send as decimal 68,
hex is 44





Control =new byte[2];





Control[0]= (byte)(68);





Control[1]= (byte)(78);





writeByte(Control);





return true;





}





if(event.getAction()==MotionEvent.ACTION_UP){






((Button)findViewById(R.id.close_button)).setBackgroundResource(R.d
rawable.black_btn);





//AttinyOut = (byte)(83);





Control =new byte[2];





Control[0]= (byte)(83);





Control[1]= (byte)(80);





writeByte(Control);





return true;





}





return false;




}



});






lightbright.setOnSeekBarChangeListener(new
OnSeekBarChangeListener() {




public void onProgressChanged(SeekBar
seekBar, int
progress,






boolean fromUser) {






//switch (progress)






//{






if (progress <= 75){







seekbar_progress.setText("Low Brightness");






}






else if (progress >= 76 & progress <=160)






{







seekbar_progress.
setText("Medium
Brightness");






}






else if (progress >= 161)






{







seekbar_progress.setText("High
Brightness");






}





AttinyOut = (byte)(progress);





write(AttinyOut);




}





public void onStartTrackingTouch(SeekBar see
kBar) {





// TODO Auto
-
generated method stub




}





public void onStopTrackingTouch(SeekBar seekBar) {





// TODO Auto
-
generated method stub




}



});



}



/** Thread used to connect to a specified Bluetooth Device */


public class Conne
ctThread extends Thread {



private String address;



private boolean connectionStatus;




ConnectThread(String MACaddress) {




address = MACaddress;




connectionStatus = true;



}




public void run() {




// When this returns, it will 'know'
about the server,




// via it's MAC address.




try {





BluetoothDevice device = mBluetoothAdapter







.getRemoteDevice(address);






// We need two things before we can successfully
connect





// (authentication issues aside): a MAC address,

which we





// already have, and an RFCOMM channel.





// Because RFCOMM channels (aka ports) are limited
in





// number, Android doesn't allow you to use them
directly;





// instead you request a RFCOMM mapping based on a
service





// ID. In

our case, we will use the well
-
known SPP
Service





// ID. This ID is in UUID (GUID to you
Microsofties)





// format. Given the UUID, Android will handle the





// mapping for you. Generally, this will return
RFCOMM 1,





// but not always; it de
pends what other BlueTooth
services





// are in use on your Android device.





try {






btSocket = device








.createRfcommSocketToServiceRecord(SPP_UUID);





} catch (IOException e) {






connectionStatus = false;





}




} catch (Illeg
alArgumentException e) {





connectionStatus = false;




}





// Discovery may be going on, e.g., if you're running a




// 'scan for devices' search from your handset's
Bluetooth




// settings, so we call cancelDiscovery(). It doesn't
hurt




//

to call it, but it might hurt not to... discovery is
a




// heavyweight process; you don't want it in progress
when




// a connection attempt is made.




mBluetoothAdapter.cancelDiscovery();





// Blocking connect, for a simple client nothing else

can




// happen until a successful connection is made, so we




// don't care if it blocks.




try {





btSocket.connect();




} catch (IOException e1) {





try {






btSocket.close();





} catch (IOException e2) {





}




}





// Creat
e a data stream so we can talk to server.




try {





outStream = btSocket.getOutputStream();




} catch (IOException e2) {





connectionStatus = false;




}





// Send final result




if (connectionStatus) {





mHandler.sendEmptyMessage(1);




} else {





mHandler.sendEmptyMessage(0);




}



}


}



public void onActivityResult(int requestCode, int resultCode,
Intent data) {



switch (requestCode) {



case REQUEST_CONNECT_DEVICE:




// When DeviceListActivity returns with a device to

connect




if (resultCode == Activity.RESULT_OK) {





// Show please wait dialog





myProgressDialog = ProgressDialog.show(this,
getResources()







.getString(R.string.pleaseWait),
getResources()







.getString(R.string.makingConnectionString),

true);






// Get the device MAC address





deviceAddress = data.getExtras().getString(







DeviceListActivity.EXTRA_DEVICE_ADDRESS);





deviceName = data.getExtras().getString(







DeviceListActivity.EXTRA_DEVICE_NAME);





// Connect to de
vice with specified MAC address





mConnectThread = new ConnectThread(deviceAddress);





mConnectThread.start();





} else {





// Failure retrieving MAC address





Toast.makeText(this, R.string.macFailed,
Toast.LENGTH_SHORT)







.show();




}




break;



case REQUEST_ENABLE_BT:




// When the request to enable Bluetooth returns




if (resultCode == Activity.RESULT_OK) {





// Bluetooth is now enabled




} else {





// User did not enable Bluetooth or an error
occured





Toast.make
Text(this,
R.string.bt_not_enabled_leaving,







Toast.LENGTH_SHORT).show();





finish();




}



}


}



public void write(byte data) {



if (outStream != null) {




try {





outStream.write(data);




} catch (IOException e) {




}



}


}


public void writeByte(byte[] data)


{ if (outStream != null) {



try {




outStream.write(Control);



} catch (IOException e) {







}



}


}




public void emptyOutStream() {



if (outStream != null) {




try {





outStream.flush();




} catch (IOException e) {




}



}


}



public void connect() {



// Launch the DeviceListActivity to see devices and do scan



Intent serverIntent = new Intent(this,
DeviceListActivity.class);



startActivityForResult(serverIntent, REQUEST_CONNEC
T_DEVICE);


}



public void disconnect() {



if (outStream != null) {




try {





//AttinyOut = (byte) (83);





Control =new byte[2];





Control[0]= (byte)(83);





Control[1]= (byte)(80);





writeByte(Control);





outStream.close();





c
onnectStat = false;





connect_button.setText(R.string.disconnected);





//fan_button.setText(R.string.fanOn);





device_status.setText("Connected to: ");





} catch (IOException e) {




}



}


}



@Override


public boolean onCreateOptionsMe
nu(Menu menu) {



MenuInflater inflater = getMenuInflater();



inflater.inflate(R.menu.option_menu, menu);



return true;


}



@Override


public boolean onOptionsItemSelected(MenuItem item) {



switch (item.getItemId()) {



case R.id.about:




//

Show info about the author (that's me!)




aboutAlert.show();




return true;



}



return false;


}



@Override


public void onResume() {



super.onResume();



}



@Override


public void onDestroy() {



emptyOutStream();



disconnect();



super.onDestroy();


}

}