1000多块整个插板,arduino + android 蓝牙插板的实现--屌丝版
需求描述
儿子有一堆充电玩具,基本上都是锂电池,经常插上去充电忘了到时拔下来,所以需要一块能设置接通时间的插板以保障电池的安全。
硬件设计:
首先需要一块插板,接着需要一个继电器,然后采用arduino r3 uno 加 一个时钟模块来控制时间,最后配一个蓝牙模块,通过手机进行时间的设定。
时钟模块:DS3231 AT24C32, 采用I2C链接arduino板上 ,SCL->A5,SDA->A4,VCC->VCC,GND->GND。
蓝牙模块:HC-06, 使用用arduino的软串口,RXT->9,TXD->8,VCC->VCC,GND->GND,后来发现这款没蓝牙链接,会一直有报警,不知道能不能关,声音不大,但是挺烦的。
继续电器:220V 10A,3个脚那种,将公共端与常开端连入220V电源。
Arduino: R3 Uno 板,发现45块的山寨,还没25块的山寨好用,啥情况。
电源模块: 220VAC -> 5VDC ,用的是精密431那款,不小心摔了2下居然还能用,太意外,这里要吐槽下淘宝上卖android外接电源适配器的,没一个好用的,
有一个刚插上就烧的,太无良了。
辅助材料:扎带,胶水,PC板(用的是聚碳酸脂板,耐火,diy的东西安全重要啊),各种型号螺丝。
使用工具:这个是消费的大头,电烙铁(第一次使用是大学那个无良的电子社团,收了28块钱,结果就叫我进去用电烙铁拆了2个电容就没有任何音讯了,哥记住你了。。。),
电转,加各类转头(直接买了个360的电转工具箱),钢钜(拿来切割PC板,后来发现这个是本项目里最难的,昨天淘宝里定了330的切割机)
软件设计
arduino端:主要是串口接收手机发来的命令,并返回,代码如下:
/*
DS3231_test.pde
Eric Ayars
4/11 Test/demo of read routines for a DS3231 RTC. Turn on the serial monitor after loading this to check if things are
working as they should. */ #include <DS3231.h>
#include <Wire.h>
#include <EEPROM.h> #define powerPin 7
DS3231 Clock; String ReceivedCache="";
String BTime="2010-07-24 11:15:00";
String ETime="2010-07-24 11:15:00";
boolean isFire=false; void setup() {
// Start the I2C interface
Wire.begin();
Clock.setClockMode(false);
Serial.begin();
pinMode(powerPin,OUTPUT);
digitalWrite(powerPin,LOW);
Clock.turnOnAlarm();
RetrieveFireSet();
} void loop() { handleCmd();
checkFire();
} void checkFire(){
String dateTime=GetTime();
if(dateTime>=BTime && dateTime<=ETime){
digitalWrite(powerPin,HIGH);
isFire=true;
}else{
digitalWrite(powerPin,LOW);
isFire=false;
}
} String formatNum(int a){
if(a<)return "" +(String)a;
return (String)a;
} String GetTime(){
bool Century=false;
bool h12=false;
bool PM=false;
int second,minute,hour,date,month,year,temperature;
second=Clock.getSecond();
minute=Clock.getMinute();
hour=Clock.getHour(h12, PM);
date=Clock.getDate();
month=Clock.getMonth(Century);
year=Clock.getYear(); String dateTime="" +formatNum(year) +"-"
+formatNum(month) +"-"
+formatNum(date) +" "
+formatNum(hour) +":"
+formatNum(minute)+":"
+formatNum(second);
return dateTime;
} void handleGetTime(){ String dateTime=GetTime();
Serial.println("OK:"+dateTime); }
void handleSetTime(){ int second,minute,hour,date,month,year,dayOfWeek;
String dateTime=ReceivedCache.substring(,); year =dateTime.substring(,).toInt();
month =dateTime.substring(,).toInt();
date=dateTime.substring(,).toInt(); hour=dateTime.substring(,).toInt();
minute=dateTime.substring(,).toInt();
second=dateTime.substring(,).toInt();
dayOfWeek=dateTime.substring(,).toInt();
Clock.setSecond(second);//Set the second
Clock.setMinute(minute);//Set the minute
Clock.setHour(hour); //Set the hour
Clock.setDoW(dayOfWeek); //Set the day of the week
Clock.setDate(date); //Set the date of the month
Clock.setMonth(month); //Set the month of the year
Clock.setYear(year); //Set the year (Last two digits of the year) Serial.println("OK:");
} void handleGetFire(){
String tmp=_ReadFireSet();
if(tmp==""){
Serial.println("EE:fire time not set!");
}else{
Serial.println("OK:" + tmp);
}
} void handleSetFire(){ for(int address=;address<;address++){
EEPROM.write(address,(byte)ReceivedCache[address]);
//Serial.print((char)EEPROM.read(address));
}
//Serial.println("");
String bTime=ReceivedCache.substring(,);
String eTime=ReceivedCache.substring(,);
bool flag=RetrieveFireSet();
// Serial.println("flag:" + (String)flag);
if(flag && (bTime==BTime && eTime==ETime)){
Serial.println("OK:");
}else{
Serial.println("EE:Set Fail");
}
} String _ReadFireSet(){
int address=;
String tmp="";
char readChar=' ';
for(int address=;address<;address++){
readChar=(char)EEPROM.read(address);
tmp +=readChar;
} if(tmp!="SetF:"){
return "";
} tmp="";
for(int address=;address<;address++){
readChar=(char)EEPROM.read(address);
tmp +=readChar;
}
//Serial.println(tmp);
return tmp;
} bool RetrieveFireSet(){
String tmp=_ReadFireSet();
if(tmp==""){
return false;
}else{
BTime=tmp.substring(,);
ETime=tmp.substring(,);
return true;
}
} //read Serial data and hand command
//
void handleCmd(){
char readChar=' '; while(Serial.available()>){
readChar=(char)Serial.read();
ReceivedCache =ReceivedCache+ (String)readChar;
//delayMicroseconds(10);
}
//Serial.println("ABC");
// Serial.println(ReceivedCache);
if(ReceivedCache.startsWith("GetT:")){
handleGetTime();
ReceivedCache=ReceivedCache.substring(); }else if(ReceivedCache.startsWith("SetT:")){
//like->SetT:2015-07-24 16:54:23,7
if(ReceivedCache.length()>=){
handleSetTime();
ReceivedCache=ReceivedCache.substring();
}
}else if(ReceivedCache.startsWith("GetS:")){
Serial.println("OK:"+(String)isFire);
ReceivedCache=ReceivedCache.substring();
}else if(ReceivedCache.startsWith("GetF:")){
handleGetFire();
ReceivedCache=ReceivedCache.substring();
}else if(ReceivedCache.startsWith("SetF:")){
if(ReceivedCache.length()>=){
handleSetFire();
ReceivedCache=ReceivedCache.substring();
}
}else if(ReceivedCache.startsWith("GetC:")){
int temperature=Clock.getTemperature();
Serial.println("OK:" +(String)temperature);
ReceivedCache=ReceivedCache.substring();
}
else{
if(ReceivedCache.length()>=){
ReceivedCache="";
}
} if(readChar=='\n')ReceivedCache="";
}
android 端:
蓝牙操作部分是参考官方提供的蓝牙串口聊天室,蓝牙操作跟socket差不多,有个蓝牙串口服务协议(程序里体现就一段GUID)用来识别蓝牙链接提供的服务类型,一个标识吧了。
主要代码:
package cn.fustudio.mangospile; import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.UUID; import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log; public class BluetoothService {
// Debugging
private static final String TAG = "BluetoothService";
private static final boolean D = true; // Name for the SDP record when creating server socket
private static final String NAME_SECURE = "BluetoothSecure";
private static final String NAME_INSECURE = "BluetoothInsecure"; // Unique UUID for this application
private static final UUID MY_UUID_SECURE =UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
//UUID.fromString("fa87c0d0-afac-11de-8a39-0800200c9a66");
private static final UUID MY_UUID_INSECURE =UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
//UUID.fromString("8ce255c0-200a-11e0-ac64-0800200c9a66"); // Member fields
private final BluetoothAdapter mAdapter;
private final Handler mHandler;
private ConnectThread mConnectThread;
private ConnectedThread mConnectedThread;
private int mState; // Constants that indicate the current connection state
public static final int STATE_NONE = ; // we're doing nothing
public static final int STATE_LISTEN = ; // now listening for incoming connections
public static final int STATE_CONNECTING = ; // now initiating an outgoing connection
public static final int STATE_CONNECTED = ; // now connected to a remote device public BluetoothService(Context context, Handler handler) {
//ff hh
mAdapter = BluetoothAdapter.getDefaultAdapter();
mState = STATE_NONE;
mHandler = handler; } /**
* Set the current state of the chat connection
* @param state An integer defining the current connection state
*/
private synchronized void setState(int state) {
if (D) Log.d(TAG, "setState() " + mState + " -> " + state);
mState = state; // Give the new state to the Handler so the UI Activity can update
mHandler.obtainMessage(MainActivity.MESSAGE_STATE_CHANGE, state, -).sendToTarget();
} /**
* Return the current connection state. */
public synchronized int getState() {
return mState;
} /**
* Start the chat service. Specifically start AcceptThread to begin a
* session in listening (server) mode. Called by the Activity onResume() */
public synchronized void start() {
if (D) Log.d(TAG, "start"); // Cancel any thread attempting to make a connection
if (mConnectThread != null) {mConnectThread.cancel(); mConnectThread = null;} // Cancel any thread currently running a connection
if (mConnectedThread != null) {mConnectedThread.cancel(); mConnectedThread = null;} setState(STATE_LISTEN);
} /**
* Start the ConnectThread to initiate a connection to a remote device.
* @param device The BluetoothDevice to connect
* @param secure Socket Security type - Secure (true) , Insecure (false)
*/
public synchronized void connect(BluetoothDevice device, boolean secure) {
if (D) Log.d(TAG, "connect to: " + device); // Cancel any thread attempting to make a connection
if (mState == STATE_CONNECTING) {
if (mConnectThread != null) {mConnectThread.cancel(); mConnectThread = null;}
} // Cancel any thread currently running a connection
if (mConnectedThread != null) {mConnectedThread.cancel(); mConnectedThread = null;} // Start the thread to connect with the given device
mConnectThread = new ConnectThread(device, secure);
mConnectThread.start();
setState(STATE_CONNECTING);
} /**
* Start the ConnectedThread to begin managing a Bluetooth connection
* @param socket The BluetoothSocket on which the connection was made
* @param device The BluetoothDevice that has been connected
*/
public synchronized void connected(BluetoothSocket socket, BluetoothDevice
device, final String socketType) {
if (D) Log.d(TAG, "connected, Socket Type:" + socketType); // Cancel the thread that completed the connection
if (mConnectThread != null) {mConnectThread.cancel(); mConnectThread = null;} // Cancel any thread currently running a connection
if (mConnectedThread != null) {mConnectedThread.cancel(); mConnectedThread = null;} // Start the thread to manage the connection and perform transmissions
mConnectedThread = new ConnectedThread(socket, socketType);
mConnectedThread.start(); // Send the name of the connected device back to the UI Activity
Message msg = mHandler.obtainMessage(MainActivity.MESSAGE_DEVICE_NAME);
Bundle bundle = new Bundle();
bundle.putString(MainActivity.DEVICE_NAME, device.getName());
msg.setData(bundle);
mHandler.sendMessage(msg); setState(STATE_CONNECTED);
} /**
* Stop all threads
*/
public synchronized void stop() {
if (D) Log.d(TAG, "stop"); if (mConnectThread != null) {
mConnectThread.cancel();
mConnectThread = null;
} if (mConnectedThread != null) {
mConnectedThread.cancel();
mConnectedThread = null;
} setState(STATE_NONE);
} /**
* Write to the ConnectedThread in an unsynchronized manner
* @param out The bytes to write
* @see ConnectedThread#write(byte[])
*/
public void write(byte[] out) {
// Create temporary object
ConnectedThread r;
// Synchronize a copy of the ConnectedThread
synchronized (this) {
if (mState != STATE_CONNECTED) return;
r = mConnectedThread;
}
// Perform the write unsynchronized
r.write(out);
} /**
* Indicate that the connection attempt failed and notify the UI Activity.
*/
private void connectionFailed() {
// Send a failure message back to the Activity
Message msg = mHandler.obtainMessage(MainActivity.MESSAGE_TOAST);
Bundle bundle = new Bundle();
bundle.putString(MainActivity.TOAST, "Unable to connect device");
msg.setData(bundle);
mHandler.sendMessage(msg); // Start the service over to restart listening mode
BluetoothService.this.start();
} /**
* Indicate that the connection was lost and notify the UI Activity.
*/
private void connectionLost() {
// Send a failure message back to the Activity
Message msg = mHandler.obtainMessage(MainActivity.MESSAGE_TOAST);
Bundle bundle = new Bundle();
bundle.putString(MainActivity.TOAST, "Device connection was lost");
msg.setData(bundle);
mHandler.sendMessage(msg); // Start the service over to restart listening mode
BluetoothService.this.start();
} /**
* This thread runs while attempting to make an outgoing connection
* with a device. It runs straight through; the connection either
* succeeds or fails.
*/
private class ConnectThread extends Thread {
private final BluetoothSocket mmSocket;
private final BluetoothDevice mmDevice;
private String mSocketType; public ConnectThread(BluetoothDevice device, boolean secure) {
mmDevice = device;
BluetoothSocket tmp = null;
mSocketType = secure ? "Secure" : "Insecure"; // Get a BluetoothSocket for a connection with the
// given BluetoothDevice
try {
if (secure) {
tmp = device.createRfcommSocketToServiceRecord(
MY_UUID_SECURE);
} else {
tmp = device.createInsecureRfcommSocketToServiceRecord(
MY_UUID_INSECURE);
}
} catch (IOException e) {
Log.e(TAG, "Socket Type: " + mSocketType + "create() failed", e);
}
mmSocket = tmp;
} public void run() {
Log.i(TAG, "BEGIN mConnectThread SocketType:" + mSocketType);
setName("ConnectThread" + mSocketType); // Always cancel discovery because it will slow down a connection
mAdapter.cancelDiscovery(); // Make a connection to the BluetoothSocket
try {
// This is a blocking call and will only return on a
// successful connection or an exception
mmSocket.connect();
} catch (IOException e) {
// Close the socket
try {
mmSocket.close();
} catch (IOException e2) {
Log.e(TAG, "unable to close() " + mSocketType +
" socket during connection failure", e2);
}
connectionFailed();
return;
} // Reset the ConnectThread because we're done
synchronized (BluetoothService.this) {
mConnectThread = null;
} // Start the connected thread
connected(mmSocket, mmDevice, mSocketType);
} public void cancel() {
try {
mmSocket.close();
} catch (IOException e) {
Log.e(TAG, "close() of connect " + mSocketType + " socket failed", e);
}
}
} /**
* This thread runs during a connection with a remote device.
* It handles all incoming and outgoing transmissions.
*/
private class ConnectedThread extends Thread {
private final BluetoothSocket mmSocket;
private final InputStream mmInStream;
private final OutputStream mmOutStream; public ConnectedThread(BluetoothSocket socket, String socketType) {
Log.d(TAG, "create ConnectedThread: " + socketType);
mmSocket = socket;
InputStream tmpIn = null;
OutputStream tmpOut = null; // Get the BluetoothSocket input and output streams
try {
tmpIn = socket.getInputStream();
tmpOut = socket.getOutputStream();
} catch (IOException e) {
Log.e(TAG, "temp sockets not created", e);
} mmInStream = tmpIn;
mmOutStream = tmpOut;
} public void run() {
Log.i(TAG, "BEGIN mConnectedThread");
byte[] buffer = new byte[];
int bytes;
String buffString="";
// Keep listening to the InputStream while connected
while (true) {
try {
// Read from the InputStream
bytes = mmInStream.read(buffer);
String msg=new String(buffer,,bytes);
buffString +=msg;
int indexOfNewLine= buffString.indexOf("\n");
if(indexOfNewLine>=){
String frameString= buffString.substring(, indexOfNewLine+);
buffString=buffString.substring(indexOfNewLine+); mHandler.obtainMessage(MainActivity.MESSAGE_READ, bytes, -, frameString)
.sendToTarget();
}
if(buffString.length()>){
buffString="";
}
// Send the obtained bytes to the UI Activity
// mHandler.obtainMessage(BluetoothChat.MESSAGE_READ, bytes, -1, buffer)
// .sendToTarget(); } catch (IOException e) {
Log.e(TAG, "disconnected", e);
connectionLost();
break;
}
}
} /**
* Write to the connected OutStream.
* @param buffer The bytes to write
*/
public void write(byte[] buffer) {
try {
mmOutStream.write(buffer); // Share the sent message back to the UI Activity
mHandler.obtainMessage(MainActivity.MESSAGE_WRITE, -, -, buffer)
.sendToTarget();
} catch (IOException e) {
Log.e(TAG, "Exception during write", e);
}
} public void cancel() {
try {
mmSocket.close();
} catch (IOException e) {
Log.e(TAG, "close() of connect socket failed", e);
}
}
} }
package cn.fustudio.mangospile; import java.util.Date; import java.util.Timer;
import java.util.TimerTask; import cn.fustudio.mangospile.CDateTimeChooseDialog.ICallback; import android.R.bool;
import android.R.string;
import android.app.Activity;
import android.app.ActionBar;
import android.app.Fragment;
import android.app.ProgressDialog;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.format.DateUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import android.os.Build; public class MainActivity extends Activity implements ICallback,OnClickListener { // Debugging
private static final String TAG = "BluetoothChat";
private static final boolean D = true; // Message types sent from the BluetoothChatService Handler
public static final int MESSAGE_STATE_CHANGE = ;
public static final int MESSAGE_READ = ;
public static final int MESSAGE_WRITE = ;
public static final int MESSAGE_DEVICE_NAME = ;
public static final int MESSAGE_TOAST = ;
public static final int MESSAGE_SETF_ENABLE=;
public static final int MESSAGE_SETT_ENABLE=;
// Key names received from the BluetoothChatService Handler
public static final String DEVICE_NAME = "device_name";
public static final String TOAST = "toast"; // Intent request codes
private static final int REQUEST_CONNECT_DEVICE_SECURE = ;
private static final int REQUEST_CONNECT_DEVICE_INSECURE = ;
private static final int REQUEST_ENABLE_BT = ; private static final int CALLBACK_SETBTIME=;
private static final int CALLBACK_SETETIME=;
// Name of the connected device
private String mConnectedDeviceName = null; // String buffer for outgoing messages
private StringBuffer mOutStringBuffer;
// Local Bluetooth adapter
private BluetoothAdapter mBluetoothAdapter = null;
// Member object for the chat services
private BluetoothService mService = null;
private Timer mTimer=new Timer(); private Button btnSyncTime=null;
private Button btnSetF=null;
private TextView txtTime=null;
private TextView txtBTime=null;
private TextView txtETime=null;
private TextView txtStatus=null;
private TextView txtTemperature=null;
private TextView txtTips=null; private Date getFBTime=null;
private Date getFETime=null; @Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main); mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter(); // If the adapter is null, then Bluetooth is not supported
if (mBluetoothAdapter == null) {
Toast.makeText(this, "Bluetooth is not available", Toast.LENGTH_LONG).show();
finish();
return;
} init(); } private void init(){ btnSyncTime=(Button)findViewById(R.id.btnSyncTime);
btnSyncTime.setOnClickListener(this);
btnSetF=(Button)findViewById(R.id.btnSetF);
btnSetF.setOnClickListener(this);
txtTime=(TextView)findViewById(R.id.txtTime);
txtBTime=(TextView)findViewById(R.id.txtBTime);
txtBTime.setOnClickListener(this);
txtETime=(TextView)findViewById(R.id.txtETime);
txtETime.setOnClickListener(this);
txtStatus=(TextView)findViewById(R.id.txtStatus);
txtTemperature=(TextView)findViewById(R.id.txtTemperature);
txtTips=(TextView)findViewById(R.id.txtTips); }
/* Begin Upload file */
private ProgressDialog dialog;
@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
if(arg0.getId()==R.id.btnSyncTime){
syncTime(); }else if(arg0.getId()==R.id.btnSetF){
setF();
}else if(arg0.getId()==R.id.txtBTime){
String dString=txtBTime.getText().toString();
Date dateV= DateUtil.parse(dString,new Date());
new CDateTimeChooseDialog(this, CALLBACK_SETBTIME,"开始时间","确定", dateV, this).show();
}else if(arg0.getId()==R.id.txtETime) {
String dString=txtETime.getText().toString();
Date dateV= DateUtil.parse(dString,new Date());
new CDateTimeChooseDialog(this, CALLBACK_SETETIME,"结束时间","确定", dateV, this).show();
} } private void setF(){
if(mService.getState()!=BluetoothService.STATE_CONNECTED){
Toast.makeText(this, "请先链接设备", Toast.LENGTH_LONG).show();
return;
}
String bTimeStr=txtBTime.getText().toString();
String eTimeStr=txtETime.getText().toString();
if("...".equals(bTimeStr) || "...".equals(eTimeStr)){
Toast.makeText(this, "请先输入开始结束时间", Toast.LENGTH_LONG).show();
return ;
} Date bTime=null;
Date eTime=null; try{
bTime=DateUtil.parse(bTimeStr);
eTime=DateUtil.parse(eTimeStr);
}catch(Exception e){
Toast.makeText(this, "时间字符解析错误", Toast.LENGTH_LONG).show();
return;
} if(bTime.compareTo(eTime)>){
Toast.makeText(this, "开始时间大于结束时间", Toast.LENGTH_LONG).show();
return ;
} btnSetF.setEnabled(false);
String cmd="SetF:"+bTimeStr+eTimeStr ;
sendMessage(cmd);
dialog = ProgressDialog.show(MainActivity.this, null,
"执行命令...");
Timer timer=new Timer();
timer.schedule(new TimerTask() { @Override
public void run() {
mHandler.obtainMessage(MESSAGE_SETF_ENABLE,"").sendToTarget();
// TODO Auto-generated method stub
if(dialog!=null){
dialog.dismiss();
dialog=null;
}
}
}, );
}
private void syncTime() {
if(mService.getState()!=BluetoothService.STATE_CONNECTED){
Toast.makeText(this, "请先链接设备", Toast.LENGTH_LONG).show();
return;
}
btnSyncTime.setEnabled(false);
String cmd="SetT:"+DateUtil.formatLong(new Date())+"," +DateUtil.getWOfD(new Date());
sendMessage(cmd);
dialog = ProgressDialog.show(MainActivity.this, null,
"执行命令...");
Timer timer=new Timer();
timer.schedule(new TimerTask() { @Override
public void run() {
mHandler.obtainMessage(MESSAGE_SETT_ENABLE,"").sendToTarget();
// TODO Auto-generated method stub
if(dialog!=null){
dialog.dismiss();
dialog=null;
} }
}, );
} //========Activity Life Cir
@Override
public void onStart() {
super.onStart();
if(D) Log.e(TAG, "++ ON START ++"); // If BT is not on, request that it be enabled.
// setupChat() will then be called during onActivityResult
if (!mBluetoothAdapter.isEnabled()) {
Intent enableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableIntent, REQUEST_ENABLE_BT);
// Otherwise, setup the chat session
} else {
if (mService == null) setupService();
}
} @Override
public synchronized void onResume() {
super.onResume();
if(D) Log.e(TAG, "+ ON RESUME +"); // Performing this check in onResume() covers the case in which BT was
// not enabled during onStart(), so we were paused to enable it...
// onResume() will be called when ACTION_REQUEST_ENABLE activity returns.
if (mService != null) {
// Only if the state is STATE_NONE, do we know that we haven't started already
if (mService.getState() == BluetoothService.STATE_NONE) {
// Start the Bluetooth chat services
mService.start();
}
}
} private void setupService() {
Log.d(TAG, "setupService()");
// Initialize the BluetoothChatService to perform bluetooth connections
mService = new BluetoothService(this, mHandler); // Initialize the buffer for outgoing messages
mOutStringBuffer = new StringBuffer(""); //定时任务
mTimer.schedule(new TimerTask() { @Override
public void run() {
// TODO Auto-generated method stub
if(mService==null || mService.getState()!=BluetoothService.STATE_CONNECTED) return;
MainActivity.this.sendMessage("GetT:");
try{ Thread.sleep(); }catch(Exception e){}
MainActivity.this.sendMessage("GetS:");
try{ Thread.sleep(); }catch(Exception e){}
MainActivity.this.sendMessage("GetC:");
try{ Thread.sleep(); }catch(Exception e){}
MainActivity.this.sendMessage("GetF:");
try{ Thread.sleep(); }catch(Exception e){}
}
}, ,);
} @Override
public synchronized void onPause() {
super.onPause();
if(D) Log.e(TAG, "- ON PAUSE -");
} @Override
public void onStop() {
super.onStop();
if(D) Log.e(TAG, "-- ON STOP --");
} @Override
public void onDestroy() {
super.onDestroy();
if(mTimer!=null)mTimer.cancel();
// Stop the Bluetooth chat services
if (mService != null) mService.stop(); if(D) Log.e(TAG, "--- ON DESTROY ---");
} //========End Activity //========Send Msg
private void sendMessage(String message) {
// Check that we're actually connected before trying anything
if (mService.getState() != BluetoothService.STATE_CONNECTED) {
Toast.makeText(this, "未链接到设备", Toast.LENGTH_SHORT).show();
return;
} // Check that there's actually something to send
if (message.length() > ) {
// Get the message bytes and tell the BluetoothChatService to write
byte[] send = message.getBytes();
mService.write(send); // Reset out string buffer to zero and clear the edit text field
mOutStringBuffer.setLength(); }
}
//========End Send Msg //=======Handle========
// The Handler that gets information back from the BluetoothChatService
private final Handler mHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
switch (msg.what) {
case MESSAGE_STATE_CHANGE:
if(D) Log.i(TAG, "MESSAGE_STATE_CHANGE: " + msg.arg1);
switch (msg.arg1) {
case BluetoothService.STATE_CONNECTED:
MainActivity.this.setTitle("链接到设备->" + mConnectedDeviceName); break;
case BluetoothService.STATE_CONNECTING:
MainActivity.this.setTitle("正在建立链接...");
break;
case BluetoothService.STATE_LISTEN:
MainActivity.this.setTitle("未链接-待命");
break;
case BluetoothService.STATE_NONE:
MainActivity.this.setTitle("未链接-初始");
break;
}
break;
case MESSAGE_WRITE:
byte[] writeBuf = (byte[]) msg.obj;
// construct a string from the buffer
String writeMessage = new String(writeBuf); break;
case MESSAGE_READ:
//byte[] readBuf = (byte[]) msg.obj;
// construct a string from the valid bytes in the buffer
//String readMessage = new String(readBuf, 0, msg.arg1);
//mConversationArrayAdapter.add(mConnectedDeviceName+": " + readMessage);
Log.d(TAG, msg.obj.toString());
//Toast.makeText(getApplicationContext(),mConnectedDeviceName+": " + msg.obj.toString(),Toast.LENGTH_LONG).show();
handleMessageRead(msg.obj.toString());
break;
case MESSAGE_DEVICE_NAME:
// save the connected device's name
mConnectedDeviceName = msg.getData().getString(DEVICE_NAME);
Toast.makeText(getApplicationContext(), "Connected to "
+ mConnectedDeviceName, Toast.LENGTH_SHORT).show();
break;
case MESSAGE_SETF_ENABLE:
btnSetF.setEnabled(true);
break;
case MESSAGE_SETT_ENABLE:
btnSyncTime.setEnabled(true);
break;
case MESSAGE_TOAST:
Toast.makeText(getApplicationContext(), msg.getData().getString(TOAST),
Toast.LENGTH_SHORT).show();
break;
}
}
};
private void handleMessageRead(String msg)
{
if(msg!=null && msg.length() >=){
msg=msg.trim();
boolean isSuccess=false;
if(msg.startsWith("OK-"))isSuccess=true;
msg=msg.substring();
if(msg.startsWith("SetT:")){
Toast.makeText(getApplicationContext(), isSuccess ? "时间同步成功" : "时间同步失败",Toast.LENGTH_SHORT).show();
}else if(msg.startsWith("SetF:"))
{
String err=msg.substring();
Toast.makeText(getApplicationContext(), isSuccess ? "定时设置成功" : "定时设置失败:" + err,Toast.LENGTH_SHORT).show();
if(isSuccess){
setTips();
}
}else if(msg.startsWith("GetT:")){
txtTime.setText(msg.substring());
}else if(msg.startsWith("GetS:")) {
String status=msg.substring();
txtStatus.setText( "".equals(status) ?"开" :"关");
}else if(msg.startsWith("GetC:")) {
String c=msg.substring();
txtTemperature.setText(c);
}else if (msg.startsWith("GetF:")) {
if(isSuccess && msg.length()>=){ String bTime=msg.substring(,);
String eTime=msg.substring(,); try{
getFBTime=DateUtil.parse(bTime);
getFETime=DateUtil.parse(eTime); }catch(Exception e){} if("...".equals(txtBTime.getText().toString())
&&
"...".equals(txtETime.getText().toString())
)
{
txtBTime.setText(bTime);
txtETime.setText(eTime); }
setTips();
}
} if(dialog!=null){
dialog.dismiss();
dialog=null;
}
} } private void setTips() {
Date now=null;
Date bTime=null;
Date eTime=null;
try{
now=DateUtil.parse(txtTime.getText().toString());
if(getFBTime!=null){
bTime=getFBTime;
}else {
bTime=DateUtil.parse(txtBTime.getText().toString());
}
if(getFETime!=null){
eTime=getFETime;
}else{
eTime=DateUtil.parse(txtETime.getText().toString());
}
}catch(Exception e){
Toast.makeText(this, "时间字符解析错误,请重新设置开始结束时间", Toast.LENGTH_LONG).show();
return;
} if(eTime.compareTo(now)<){
txtTips.setText("定时设置:执行时段已过");
txtTips.setTextColor(Color.rgb(0xaa, 0xaa, 0xaa));
}else if(bTime.compareTo(now)>) {
//还未开始 long duration= DateUtil.getSeconds(now, bTime);
int bHour=(int)( duration / ( * ));
int bMinutes=(int)( (duration - (bHour * )) / ); duration= DateUtil.getSeconds(bTime, eTime);
int eHour=(int)( duration / ( * ));
int eMinutes=(int)( (duration - (eHour * )) / ); String msg="定时设置:"+ bHour+"小时"+bMinutes+"分钟后开始,持续"+eHour+"小时"+eMinutes+"分钟";
txtTips.setText(msg); txtTips.setTextColor(Color.rgb(0x00, 0x00, 0xee)); }else {
//已经开始
long duration= DateUtil.getSeconds(now, eTime);
int hour=(int)( duration / ( * ));
int minutes=(int)( (duration - (hour * )) / );
txtTips.setText("定时设置:已经开始,"+hour+"小时"+minutes+"分钟后结束");
txtTips.setTextColor(Color.rgb(0x00, 0xee, 0x00));
}
}
private void ensureDiscoverable() {
if(D) Log.d(TAG, "ensure discoverable");
if (mBluetoothAdapter.getScanMode() !=
BluetoothAdapter.SCAN_MODE_CONNECTABLE_DISCOVERABLE) {
Intent discoverableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
discoverableIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, );
startActivity(discoverableIntent);
}
} private void connectDevice(Intent data, boolean secure) {
// Get the device MAC address
String address = data.getExtras()
.getString(DeviceListActivity.EXTRA_DEVICE_ADDRESS);
// Get the BLuetoothDevice object
BluetoothDevice device = mBluetoothAdapter.getRemoteDevice(address);
// Attempt to connect to the device
mService.connect(device, secure);
}
//=======End handle //=========onActivityResult
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if(D) Log.d(TAG, "onActivityResult " + resultCode);
switch (requestCode) {
case REQUEST_CONNECT_DEVICE_SECURE:
// When DeviceListActivity returns with a device to connect
if (resultCode == Activity.RESULT_OK) {
connectDevice(data, true);
}
break;
case REQUEST_CONNECT_DEVICE_INSECURE:
// When DeviceListActivity returns with a device to connect
if (resultCode == Activity.RESULT_OK) {
connectDevice(data, false);
}
break;
case REQUEST_ENABLE_BT:
// When the request to enable Bluetooth returns
if (resultCode == Activity.RESULT_OK) {
// Bluetooth is now enabled, so set up a chat session
setupService();
} else {
// User did not enable Bluetooth or an error occured
Log.d(TAG, "BT not enabled");
Toast.makeText(this, "蓝牙不可用", Toast.LENGTH_SHORT).show();
finish();
}
}
} //=========EndonActivityResult==
//=========DateTime pick call back
@Override
public void callback(int callbackType, Object... params) {
//活动时间
if( params != null && params.length == ){
if (params[] instanceof Date) {
Date setTime = (Date) params[];
long currentTime = System.currentTimeMillis() ;
if(callbackType==CALLBACK_SETBTIME){
txtBTime.setText(DateUtil.formatLong(setTime));
} else if(callbackType==CALLBACK_SETETIME) {
txtETime.setText(DateUtil.formatLong(setTime)); }else {
Toast.makeText(this, "异常", Toast.LENGTH_LONG).show();
}
}
} }
//=========End DateTime pick call back
@Override
public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
} @Override
public boolean onOptionsItemSelected(MenuItem item) {
Intent serverIntent = null;
switch (item.getItemId()) {
case R.id.secure_connect_scan:
// Launch the DeviceListActivity to see devices and do scan
serverIntent = new Intent(this, DeviceListActivity.class);
startActivityForResult(serverIntent, REQUEST_CONNECT_DEVICE_SECURE);
return true;
case R.id.insecure_connect_scan:
// Launch the DeviceListActivity to see devices and do scan
serverIntent = new Intent(this, DeviceListActivity.class);
startActivityForResult(serverIntent, REQUEST_CONNECT_DEVICE_INSECURE);
return true;
case R.id.discoverable:
// Ensure this device is discoverable by others
ensureDiscoverable();
return true;
case R.id.exit:
finish();
return true;
}
return false;
} }
最后上图:
------------------------------------------------------------------------------------------------------------
最后谁将本文从首页移除死全家(诅咒有效期2天)
最后的最后,如有人按上面设计做出的插板或者在制作过程中,发生一切事故或意外本人一概不负责。。。
1000多块整个插板,arduino + android 蓝牙插板的实现--屌丝版的更多相关文章
- Android 蓝牙开发之搜索、配对、连接、通信大全
蓝牙( Bluetooth®):是一种无线技术标准,可实现固定设备.移动设备和楼宇个人域网之间的短距离数据 交换(使用2.4-2.485GHz的ISM波段的UHF无线电波).蓝牙设备最 ...
- Android蓝牙自动配对Demo,亲测好使!!!
蓝牙自动配对,即搜索到其它蓝牙设备之后直接进行配对,不需要弹出配对确认框或者密钥输入框. 转载请注明出处http://blog.csdn.net/qq_25827845/article/details ...
- Android蓝牙自动配对Demo,亲测好使!!!(转)
蓝牙自动配对,即搜索到其它蓝牙设备之后直接进行配对,不需要弹出配对确认框或者密钥输入框. 转载请注明出处http://blog.csdn.net/qq_25827845/article/details ...
- ym——物联网入口之中的一个Android蓝牙4.0
转载请注明本文出自Cym的博客(http://blog.csdn.net/cym492224103),谢谢支持! 假设还有同学不知道蓝牙4.0能够做什么请查看Android+蓝牙 4.0 将带来什么? ...
- Android 蓝牙串口通信工具类 SerialPortUtil 3.0.+
建议使用4.+版本,避免一些不必要的bug.4.+版本文档地址:https://www.cnblogs.com/shanya/articles/16062256.html SerialPortUtil ...
- android蓝牙打印机
您还未登录!|登录|注册|帮助 首页 业界 移动 云计算 研发 论坛 博客 下载 更多 reality_jie的专栏 编程的过程是一种微妙的享受 目录视图 摘要视图 订阅 CSDN2013 ...
- Android蓝牙实例(和单片机蓝牙模块通信)
最近做毕设,需要写一个简单的蓝牙APP进行交互,在网上也找了很多资料,终于给搞定了,这里分享一下^_^. 1.Android蓝牙编程 蓝牙3.0及以下版本编程需要使用UUID,UUID是通用唯一识别码 ...
- Android 蓝牙4.0 BLE
Android ble (Bluetooth Low Energy) 蓝牙4.0,也就是说API level >= 18,且支持蓝牙4.0的手机才可以使用. BLE是蓝牙4.0的核心Profil ...
- android 蓝牙4.0 开发介绍
最近一直在研究一个蓝牙功能 由于本人是菜鸟 学起来比较忙 一直搞了好久才弄懂 , 网上对蓝牙4.0也就是几个个dome 抄来抄去,全是英文注解 , 对英语不好的朋友来说 真是硬伤 , 一些没必要的描 ...
随机推荐
- 使用jquery.more.js来实现点击底部更多后, 底部加载出新的数据
<div class="bus-nav-bar ft12"> <div class="navt bor-r-c pos-rel {if $int == ...
- javascript 浮点数加减乘除计算会有问题, 整理了以下代码来规避这个问题
/* * js数学计算 add by yan */ /** ** 加法函数,用来得到精确的加法结果 ** 说明:javascript的加法结果会有误差,在两个浮点数相加的时候会比较明显.这个函数返回较 ...
- Mysql 游标使用
BEGIN #shopsId 商家ID #accountDay 10位日期 -- 定义一个或者多个 变量来接收 游标查询的列值 DECLARE receiptContentId INT; -- 遍历数 ...
- springMVC学习记录2-使用注解配置
前面说了一下使用xml配置springmvc,下面再说说注解配置.项目如下: 业务很简单,主页和输入用户名和密码进行登陆的页面. 看一下springmvc的配置文件: <?xml version ...
- 使用CXF发布的WebService报错:org.apache.cxf.interceptor.Fault: The given SOAPAction does not match an operation
场景:JAVA语言使用CXF搭建WebService发布报错 错误信息:org.apache.cxf.interceptor.Fault: The given SOAPAction does not ...
- Java properties文件用法
package com.suyang.properties; import java.io.FileInputStream; import java.io.FileNotFoundException; ...
- Conductor Task Workers
由远程worker执行的conductor任务通过HTTP端点进行通信以轮询任务并更新执行状态. conductor提供了轮询任务的框架,管理执行线程并将执行状态更新回服务器.该框架提供了Java和P ...
- redis安装和命令使用
前言: redis是一个key-value的存储系统,value支持string.list.set.zset.hash五种类型,且支持数据的本地存储 一.安装redis 前提:linux下需要安装 ...
- html标签对应的英文原文(转载)
标签 对应英文 说明 <!--> / 注释 <!DOCTYPE> document type 文档类型 <a> anchor 超链接 <abbr> a ...
- Python3 tuple 函数
Python3 tuple 函数 Python3 内置函数 描述 tuple 函数将列表转换为元组.. 语法 以下是 tuple 的语法: tuple( seq ) 参数 seq -- 要转换为元组 ...