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(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="";
}

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 = 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);
            }
        }
    }

}

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;
    }

}

最后上图:

------------------------------------------------------------------------------------------------------------

最后谁将本文从首页移除死全家(诅咒有效期2天)

最后的最后,如有人按上面设计做出的插板或者在制作过程中,发生一切事故或意外本人一概不负责。。。

时间: 2024-11-09 11:50:49

1000多块整个插板,arduino + android 蓝牙插板的实现--屌丝版的相关文章

Android蓝牙自动配对Demo,亲测好使!!!

蓝牙自动配对,即搜索到其它蓝牙设备之后直接进行配对,不需要弹出配对确认框或者密钥输入框. 转载请注明出处http://blog.csdn.net/qq_25827845/article/details/52400782 经过最近一段时间得研究,针对网上给出的案例.总结了一个亲测好使的Demo. 说明如下: 1.本Demo用来连接蓝牙设备HC-05,如果你要连接其他蓝牙设备,注意修改相关名字以及修改设备初试pin值. 2.将Demo安装在Android手机上,点击按钮,可以实现与目标蓝牙设备的自动

Android 蓝牙开发之搜索、配对、连接、通信大全

        蓝牙( Bluetooth®):是一种无线技术标准,可实现固定设备.移动设备和楼宇个人域网之间的短距离数据 交换(使用2.4-2.485GHz的ISM波段的UHF无线电波).蓝牙设备最多可以同时和7个其它蓝牙设备建立连接,进 行通信,当然并不是每一个蓝牙都可以达到最大值.下面,我们从蓝牙的基本概念开始,一步一步开始了解蓝牙. 基本概念: 安卓平台提供对蓝牙的通讯栈的支持,允许设别和其他的设备进行无线传输数据.应用程序层通过安卓API来调用蓝牙的相关功 能,这些API使程序无线连接

Android蓝牙自动配对Demo,亲测好使!!!(转)

蓝牙自动配对,即搜索到其它蓝牙设备之后直接进行配对,不需要弹出配对确认框或者密钥输入框. 转载请注明出处http://blog.csdn.net/qq_25827845/article/details/52400782 源码下载地址:https://github.com/chaohuangtianjie994/BlueTooth-AutoPair 经过最近一段时间得研究,针对网上给出的案例.总结了一个亲测好使的Demo. 说明如下: 1.本Demo用来连接蓝牙设备HC-05,如果你要连接其他蓝牙

[Android]蓝牙系统

1.1 蓝牙技术简介 蓝牙(Bleuetooth)原是十世纪统一了丹麦的一个国王的名字,现取其"统一"的含义,用来意在统一无线局域网通讯的标准的蓝牙技术.蓝牙技 术是爱立信,IBM,Intel等世界5家著名大公司在1998年联合推出的一项无线通讯规范.随后成立的蓝牙技术特殊兴趣组织(SIG)来负责该技术的 开发和技术协议的制定,如今全世界已有1800多家公司加盟该组织,最近微软公司也正式加盟并成为SIG组织的领导成员之一.它以低成本的近距离无线连接 为基础,为移动通信设备建立一个短程无

ym——物联网入口之一Android蓝牙4.0

如果还有同学不知道蓝牙4.0可以做什么请查看Android+蓝牙 4.0 将带来什么?,现在可以穿戴设备也大多用的是蓝牙4.0,如 智能体质秤,智能手环,智能血压计等等. 安卓4.3(API 18)为BLE的核心功能提供平台支持和API,App可以利用它来发现设备.查询服务和读写特性.相比传统的蓝牙,BLE更显著的特点是低功耗.这一优点使android App可以与具有低功耗要求的BLE设备通信,如近距离传感器.心脏速率监视器.健身设备等. 关键术语和概念 Generic Attribute P

Android 蓝牙模块

前天想找个蓝牙录音程序,发现居然没有!没办法,就自己动手DIY了.一些关键代码摘出来,希望对大家有用.    本代码基于android 2.2以上.IOS就不要问我了,不越狱的IOS设备,蓝牙除了用蓝牙耳机,再就是IOS设备之间联机游戏,不可理喻! 一.初始化添加权限:<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /><uses-permission android:

Android蓝牙4.0之玩爆智能穿戴、家具(二)【进阶篇】

闲话中心 这几天最大的事可能就是美国总统的上任,双十一,还有乐视股价了,乍一看,好像和我们没什么关系,其实肯定是有的了,要不然他也成不了新闻啊,有一点我们得改变,就是我们必须要希望我们自己国家的企业能过强大,我们必须支持他们,哪怕他做的不够好,这个问题其实就像一个国家一样,我们都知道许多政策是不合理的,或者说有很多制度是坑人的,但是我们不能因为这些而不爱我们的国家,那么企业也是一样,就拿乐视来说,股价跌了,公司遇到资金问题了,你看看这些媒体都在报道什么,全是负面消息,马上倒闭了,或者说是撑不住了

Android 蓝牙通信

Android 蓝牙传文件比较常见,但是官方也给出了基于蓝牙通讯做了个聊天室的sample,BluetoothChat.有兴趣的可以下载看下,很有意思.通讯那块用了特殊的BluetoothSocket.思路跟一般socket通讯一样.必须有服务端和客户端.sample有三个类:BluetoothChat,BluetoothChatService,DeviceListActivity. BluetoothChat是主界面,可以看到聊天的内容,BluetoothChatService是功能类,实现了

《Arduino+Android互动智作:初入物联网》高清书签中文版

<Arduino+Android互动智作:初入物联网>高清书签中文版: ARDUINO+ANDROID互动智作 内容介绍: <Arduino+Android互动智作>是作者Simon Monk在Arduino应用上的又一次跨越,他采用12个示例项目成功地向读者们展示了如何将Arduino和Android结合起来,以完成许多单靠Arduino或者Android根本无法完成的任务.对于Arduino爱好者而言,可以通过对<Arduino+Android互动智作>的学习将An