1

我目前正在开发一个通过蓝牙与串行设备通信的应用程序。我以打开与蓝牙设备的连接的方式实现了它。它似乎连接良好。当它执行 reader.readline() 时,它似乎挂起。它永远不会回来。设备本身在响应时会返回以下内容。

RD,97,101,100,41613,3000,3,0,153,153,4120,161,4,0​​,97,102,103,220,20,493,4568,3 000,100,0,100,5,

这就是我所期待的。但是我需要让 reader.rea 超时

package com.clarke.android.smartflow;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.Set;
import java.util.TimerTask;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;

import org.apache.http.util.EncodingUtils;

import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.os.Handler;
import android.os.Looper;
import android.util.Log;

import com.xyx.android.activity.Main;
import com.xyx.android.errors.ErrorService;
import com.xyx.android.events.EventDeviceDetail;


public class SmartFlowService {

    private static final String CLASSTAG = SmartFlowService.class.getSimpleName();
    private static final String DEVICE_NAME = "FireFlyBP"; //FireFlyBP-70D0


    private static BluetoothSocket bluetoothSocket;
    private static BufferedWriter writer = null;
    private static BufferedReader reader = null;
    private static BluetoothAdapter bluetoothAdapter;
    private static BluetoothDevice bluetoothDevice = null;      
    private static boolean isConnected = false;
    static Handler mSendHandler = new Handler(); 

    private InputStream mmInStream;

    //private final OutputStream mmOutStream;


    private static ArrayList<SmartFlowListener> listeners = new ArrayList<SmartFlowListener>();

    public static void addSmartFlowListener(SmartFlowListener listener) {
        listeners.add(listener);
    }

    public static void removeSmartFlowListener(SmartFlowListener listener) {
        listeners.remove(listener);
    }

    private static void fireSmartFlowEvent(EventDeviceDetail eventDeviceDetail) {
        SmartFlowEvent smartFlowEvent = new SmartFlowEvent(SmartFlowService.class, eventDeviceDetail);
        for (Iterator<SmartFlowListener> iterator = listeners.iterator(); iterator.hasNext(); ) {
            SmartFlowListener listener = iterator.next();
            listener.onSmartFlowEvent(smartFlowEvent);
        }
    }

    public static void connect() throws Exception {
        Log.d(Main.LOGTAG, CLASSTAG +" connect");


        bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        Set<BluetoothDevice> pairedDevices = bluetoothAdapter.getBondedDevices();
        for (Iterator<BluetoothDevice> iterator = pairedDevices.iterator(); iterator.hasNext(); ) {
            BluetoothDevice bd = iterator.next();
            Log.d(Main.LOGTAG, CLASSTAG +" found device "+ bd.getName());
            if (bd.getName().startsWith(DEVICE_NAME)) {
                Log.d(Main.LOGTAG, CLASSTAG +" using device "+ bd.getName() +" "+ bd.getBluetoothClass().toString());
                bluetoothDevice = bd;
            }
        }


        if (bluetoothDevice != null) { 
            //socket = bd.createRfcommSocketToServiceRecord(java.util.UUID.fromString("00001101-0000-1000-8000-00805F9B34FB"));
            Method m = bluetoothDevice.getClass().getMethod("createRfcommSocket", new Class[]{int.class}); 
            bluetoothSocket = (BluetoothSocket)m.invoke(bluetoothDevice, Integer.valueOf(1));
            bluetoothSocket.connect();
            isConnected = true;
        } else {
            throw new Exception("Could not find bluetooth device");
        }
    }

    public static String sendR() throws Exception {

        return send("R");
    }

    public static String sendS(Integer targetRate, Integer pcOffCode) throws Exception {
        StringBuffer sb = new StringBuffer();
        sb.append("S,");
        if (targetRate != null) {
            sb.append(targetRate);
            sb.append(",");
        }
        if (pcOffCode != null) {
            sb.append(pcOffCode);
        }
        sb.append("\r\n");
        return send(sb.toString());
    }

    public static String send(String request) throws Exception {
        Log.d(Main.LOGTAG, CLASSTAG +" send");
        String response = null;
        InputStream mmInStream;
        StringBuilder swriter = new StringBuilder();
        //int swriter = 0;

        try {
            connect();
            if (isConnected) {
                writer = new BufferedWriter(new OutputStreamWriter(bluetoothSocket.getOutputStream()));
                reader = new BufferedReader(new InputStreamReader(bluetoothSocket.getInputStream()));

                writer.write(request);
                writer.flush();

                response = reader.readLine();
                // Keep listening to the InputStream while connected
                fireSmartFlowEvent(new EventDeviceDetail(response));
                Log.d(Main.LOGTAG, CLASSTAG +" send "+ response);
                Log.d(Main.LOGTAG, CLASSTAG +" send "+ response);
                bluetoothSocket.close();
                isConnected=false;
            } else {
                throw new Exception("No Bluetooth connection");
            }                           
            //bluetoothSocket.close();


        } catch (Exception e) {
            Log.e(Main.LOGTAG, CLASSTAG +" send", e);
            fireSmartFlowEvent(new EventDeviceDetail(e));           
            isConnected = false; //force a reconnection retry
            throw e;
        }
        return response;
    }

    public static void close() {
        Log.d(Main.LOGTAG, CLASSTAG +" close");
        try
        {
            if (writer != null) { writer.close(); }
            if (reader != null) { reader.close(); }
            if (bluetoothSocket != null) { bluetoothSocket.close(); }
            isConnected = false;
        }
        catch (Throwable t)
        {
            Log.d(Main.LOGTAG, CLASSTAG +" close", t);
            ErrorService.log(t);
        }
    }
}
4

0 回答 0