儿子有一堆充电玩具,基本上都是锂电池,经常插上去充电忘了到时拔下来,所以需要一块能设置接通时间的插板以保障电池的安全。
首先需要一块插板,接着需要一个继电器,然后采用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(9600); pinMode(powerPin,OUTPUT); digitalWrite(powerPin,LOW); Clock.turnOnAlarm(1); 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<10)return "0" +(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="20" +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(5,24); year =dateTime.substring(2,4).toInt(); month =dateTime.substring(5,7).toInt(); date=dateTime.substring(8,10).toInt(); hour=dateTime.substring(11,13).toInt(); minute=dateTime.substring(14,16).toInt(); second=dateTime.substring(17,19).toInt(); dayOfWeek=dateTime.substring(20,21).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=0;address<43;address++){ EEPROM.write(address,(byte)ReceivedCache[address]); //Serial.print((char)EEPROM.read(address)); } //Serial.println(""); String bTime=ReceivedCache.substring(5,24); String eTime=ReceivedCache.substring(24,43); 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=0; String tmp=""; char readChar=' '; for(int address=0;address<5;address++){ readChar=(char)EEPROM.read(address); tmp +=readChar; } if(tmp!="SetF:"){ return ""; } tmp=""; for(int address=5;address<43;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(0,19); ETime=tmp.substring(19,38); return true; } } //read Serial data and hand command // void handleCmd(){ char readChar=' '; while(Serial.available()>0){ readChar=(char)Serial.read(); ReceivedCache =ReceivedCache+ (String)readChar; //delayMicroseconds(10); } //Serial.println("ABC"); // Serial.println(ReceivedCache); if(ReceivedCache.startsWith("GetT:")){ handleGetTime(); ReceivedCache=ReceivedCache.substring(5); }else if(ReceivedCache.startsWith("SetT:")){ //like->SetT:2015-07-24 16:54:23,7 if(ReceivedCache.length()>=26){ handleSetTime(); ReceivedCache=ReceivedCache.substring(26); } }else if(ReceivedCache.startsWith("GetS:")){ Serial.println("OK:"+(String)isFire); ReceivedCache=ReceivedCache.substring(5); }else if(ReceivedCache.startsWith("GetF:")){ handleGetFire(); ReceivedCache=ReceivedCache.substring(5); }else if(ReceivedCache.startsWith("SetF:")){ if(ReceivedCache.length()>=43){ handleSetFire(); ReceivedCache=ReceivedCache.substring(43); } }else if(ReceivedCache.startsWith("GetC:")){ int temperature=Clock.getTemperature(); Serial.println("OK:" +(String)temperature); ReceivedCache=ReceivedCache.substring(5); } else{ if(ReceivedCache.length()>=5){ ReceivedCache=""; } } if(readChar=='/n')ReceivedCache=""; }View Code
蓝牙操作部分是参考官方提供的蓝牙串口聊天室,蓝牙操作跟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 = 0; // we're doing nothing public static final int STATE_LISTEN = 1; // now listening for incoming connections public static final int STATE_CONNECTING = 2; // now initiating an outgoing connection public static final int STATE_CONNECTED = 3; // 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, -1).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[1024]; 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,0,bytes); buffString +=msg; int indexOfNewLine= buffString.indexOf("/n"); if(indexOfNewLine>=0){ String frameString= buffString.substring(0, indexOfNewLine+1); buffString=buffString.substring(indexOfNewLine+1); mHandler.obtainMessage(MainActivity.MESSAGE_READ, bytes, -1, frameString) .sendToTarget(); } if(buffString.length()>1024){ 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, -1, -1, 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); } } } }View Code
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 = 1; public static final int MESSAGE_READ = 2; public static final int MESSAGE_WRITE = 3; public static final int MESSAGE_DEVICE_NAME = 4; public static final int MESSAGE_TOAST = 5; public static final int MESSAGE_SETF_ENABLE=6; public static final int MESSAGE_SETT_ENABLE=7; // 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 = 1; private static final int REQUEST_CONNECT_DEVICE_INSECURE = 2; private static final int REQUEST_ENABLE_BT = 3; private static final int CALLBACK_SETBTIME=1; private static final int CALLBACK_SETETIME=2; // 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)>0){ 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; } } }, 2000); } 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; } } }, 2000); } //========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(100); }catch(Exception e){} MainActivity.this.sendMessage("GetS:"); try{ Thread.sleep(100); }catch(Exception e){} MainActivity.this.sendMessage("GetC:"); try{ Thread.sleep(100); }catch(Exception e){} MainActivity.this.sendMessage("GetF:"); try{ Thread.sleep(100); }catch(Exception e){} } }, 0,1000); } @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() > 0) { // 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(0); } } //========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() >=7){ msg=msg.trim(); boolean isSuccess=false; if(msg.startsWith("OK-"))isSuccess=true; msg=msg.substring(3); if(msg.startsWith("SetT:")){ Toast.makeText(getApplicationContext(), isSuccess ? "时间同步成功" : "时间同步失败",Toast.LENGTH_SHORT).show(); }else if(msg.startsWith("SetF:")) { String err=msg.substring(5); Toast.makeText(getApplicationContext(), isSuccess ? "定时设置成功" : "定时设置失败:" + err,Toast.LENGTH_SHORT).show(); if(isSuccess){ setTips(); } }else if(msg.startsWith("GetT:")){ txtTime.setText(msg.substring(5)); }else if(msg.startsWith("GetS:")) { String status=msg.substring(5); txtStatus.setText( "1".equals(status) ?"开" :"关"); }else if(msg.startsWith("GetC:")) { String c=msg.substring(5); txtTemperature.setText(c); }else if (msg.startsWith("GetF:")) { if(isSuccess && msg.length()>=43){ String bTime=msg.substring(5,24); String eTime=msg.substring(24,43); 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)<0){ txtTips.setText("定时设置:执行时段已过"); txtTips.setTextColor(Color.rgb(0xaa, 0xaa, 0xaa)); }else if(bTime.compareTo(now)>0) { //还未开始 long duration= DateUtil.getSeconds(now, bTime); int bHour=(int)( duration / (60 * 60)); int bMinutes=(int)( (duration - (bHour * 3600)) / 60); duration= DateUtil.getSeconds(bTime, eTime); int eHour=(int)( duration / (60 * 60)); int eMinutes=(int)( (duration - (eHour * 3600)) / 60); 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 / (60 * 60)); int minutes=(int)( (duration - (hour * 3600)) / 60); 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, 300); 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 == 1){ if (params[0] instanceof Date) { Date setTime = (Date) params[0]; 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; } }View Code
------------------------------------------------------------------------------------------------------------
最后的最后,如有人按上面设计做出的插板或者在制作过程中,发生一切事故或意外本人一概不负责。。。