使用蓝牙测量血压

一. 关于连接仪器使用蓝牙进行测量 血压



public class BloodPressureCheckOperationActivity extends BaseActivity implements
  OnTopbarLeftButtonListener, OnTopbarRightButtonListener ,AsyncRequest {


private static final String REQUEST_POST_XUEYA_DATA = "request_post_xueya_data";

 public static final int SLEEP_RECEIVE_TIME = 100;// 100ms

 public static final int SLEEP_SEND_TIME = 100;// 再发送指令,延时100ms

 public static final int POWER_TOO_LOW = 3600;// 血压设备,电量低值

 // 发给血压计 (带校验码)
 private static final byte[] SEND_CHECK_POWER_PRESSURE = { (byte) 0xcc,
   (byte) 0x85, 0x02, 0x03, 0x04, 0x04, 0x00, 0x01 };// 查询电量
 private static final byte[] SEND_CONNECT_PRESSURE = { (byte) 0xcc,
   (byte) 0x85, 0x02, 0x03, 0x01, 0x01, 0x00, 0x01 };// 连接血压计
 private static final byte[] SEND_START_PRESSURE = { (byte) 0xcc,
   (byte) 0x85, 0x02, 0x03, 0x01, 0x02, 0x00, 0x02 };// 开始测量
 private static final byte[] SEND_STOP_PRESSURE = { (byte) 0xcc,
   (byte) 0x85, 0x02, 0x03, 0x01, 0x03, 0x00, 0x03 };// 停止测量
 private static final byte[] SEND_CLOSE_PRESSURE = { (byte) 0xcc,
   (byte) 0x85, 0x02, 0x03, 0x01, 0x04, 0x00, 0x04 };// 关手机


// 收到血压计之后(血压计还会回复指令)匹配是否成功的字节数组 (带校验码)
 private static final Byte[] RECEIVE_CHECK_POWER_PRESSURE = { (byte) 0xaa,
   (byte) 0x85, 0x02, 0x04, 0x04, 0x04 };// 查询电量(数组中没有放入校验码,和数据,共3个字节)
 private static final Byte[] RECEIVE_CONNECT_PRESSURE = { (byte) 0xaa,
   (byte) 0x85, 0x02, 0x03, 0x01, 0x01, 0x00, 0x01 };// 连接血压计
 private static final Byte[] RECEIVE_START_PRESSURE = { (byte) 0xaa,
   (byte) 0x85, 0x02, 0x03, 0x01, 0x02, 0x00, 0x02 };// 开始测量
 private static final Byte[] RECEIVE_STOP_PRESSURE = { (byte) 0xaa,
   (byte) 0x85, 0x02, 0x03, 0x01, 0x03, 0x00, 0x03 };// 停止测量
 private static final Byte[] RECEIVE_CLOSE_PRESSURE = { (byte) 0xaa,
   (byte) 0x85, 0x02, 0x03, 0x01, 0x04, 0x00, 0x04 };// 关手机

 // 收到血压计 (没有应答)
 private static final Byte[] RECEIVE_TEST_DATA_PRESSURE = { (byte) 0xaa,
   (byte) 0x85, 0x02, 0x08, 0x01, 0x05 };// 发送过程数据的前几个字节
 private static final Byte[] RECEIVE_TEST_RESULT_PRESSURE = { (byte) 0xaa,
   (byte) 0x85, 0x02, 0x0f, 0x01, 0x06 };// 发送测试结果数据
 private static final Byte[] RECEIVE_TEST_ERROR_PRESSURE = { (byte) 0xaa,
   (byte) 0x85, 0x02, 0x03, 0x01, 0x07 };// 发送了错误信息

 public static final int BLUE_TOOTH_STATE_SEARCHING = 10;// 正在查找
 public static final int BLUE_TOOTH_STATE_CONNECTED = 11;// 已连接
 public static final int BLUE_TOOTH_STATE_DIS_CONNECT = 12;// 已断开

 public static final int BLUE_TOOTH_SOCKET_CONNECT_FIRST = 0;// 第一次连接
 public static final int BLUE_TOOTH_SOCKET_CONNECT_SECURE = 1;// 安全socket连接
 public static final int BLUE_TOOTH_SOCKET_CONNECT_IN_SECURE = 2;// 不安全socket连接

 private static final int RECEIVE_DATA_ING = 13;// 接收过程数据13个字节
 private static final int RECEIVE_DATA_RESULT = 20;// 接收结果数据20个字节
 private static final int RECEIVE_DATA_ERROR = 8;// 血压计通信过程中返回错误信息
 private static final int RECEIVE_DATA_POWER = 9;// 血压计返回电量数据

 private static final int MSG_START_DATA_LIST = 100;
 private static final int MSG_MEASURE_EXCEPTION_FAIL = 101;

 private static final int MSG_CONNECT_SUCCESS = 200;
 private static final int MSG_CONNECT_FAIL = 201;

 private static final int MSG_POST_DATA_SUCCESS = 300;

 private static final int TAG_BTN_START_TEST = 10;
 private static final int TAG_BTN_STOP_TEST = 11;

 private static final String SPP_UUID = "00001101-0000-1000-8000-00805F9B34FB";// 蓝牙服务器的标识

 private static final String DEVICE_FRONT_STRING = "RBP";

 private static BloodPressureCheckOperationActivity mInstance = null;
 private static Object mLockObj = new Object();

 private BluetoothAdapter mBluetoothAdapter;
 private BluetoothDevice mBluetoothDevice;
 private BluetoothSocket mBluetoothSocket;

 private OutputStream mOutputStream;
 private InputStream mInInputStream;

 private boolean mStopReadThread = false;

 private ImageButton mBtImgBtn;
 private TextView mBtConStateTV, mBloodPreValueTV;
 private Button mStartBtn;

 // 接收
 private boolean mReceiveCheckPower = false;
 private boolean mReceiveConnect = false;
 private boolean mReceiveStart = false;
 public boolean mReceiveDataIng = false;
 private boolean mReceiveClosePhone = false;// 暂时不用

 private boolean mRequestStopTest = false;// 请求停止测量

 private ReceiveMessageThread mReceiveMessageThread = null;

 private boolean mIsStateOn = false;


private Timer mCheckBlueTimer;
 private boolean mCheckBlueFlag = false;
 private boolean mStartDiscovery = false;

 private String mUid;
 private String mName;
 private String mDepartment;
 private String mSickroom;
 private String mBednumber;
 private ArrayList<CheckItem> mArrayList = null;
 private LinearLayout mBloodPressureCheckLayout, mBloodPressureResultLayout;
 
 public static final long IMAGE_TARGET_SIZE_2MB = 20 * 1024;// 图片大小200K
 public static final String imageFilePath = Environment.getExternalStorageDirectory().getPath() + "/enuo/";
 private String path , idPic , timeFlag;
 private String imageFileName;
 public static final int BACK_CAMERA = 1000;

@Override
 public void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.main_blood_pressure_activity);

  LogUtilBase.LogD(null,
    "============================================================");
  LogUtilBase.LogD(null, "BloodPressureCheckOperationActivity onCreate");
  mInstance = this;
  init();
 }

private void init()

{

 registerReceiver();   // 注册广播

  checkBluetoothDevice();  检查设备连接

  // 改成每次开启搜索,不去连接已经连接过的设备,这样子,每次了解慢
  startDiscoveryBluetooth(true);// false


}


private void  registerReceiver()

{

 IntentFilter discoveryFilter = new IntentFilter(
    BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
  discoveryFilter.addAction(BluetoothDevice.ACTION_FOUND);
  discoveryFilter.addAction(BluetoothDevice.ACTION_BOND_STATE_CHANGED);
  registerReceiver(mBluetoothReceiver, discoveryFilter);

}

private void  checkBluetoothDevice()

{

  mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();// 获取本地蓝牙设备
  if (mBluetoothAdapter == null) {
   UIHelper.showToast(this, R.string.bluetooth_no, Gravity.CENTER);
   finish();
   return;
  }

  boolean bluetoothEnabled = mBluetoothAdapter.isEnabled();
  // 保存手机默认蓝牙开启状态
  AppConfig.setConfig(Const.PRESSURE_BLUETOOTH_STATE, bluetoothEnabled);

  if (!bluetoothEnabled) {
   UIHelper.showToast(this, R.string.bluetooth_ing, Gravity.CENTER);
   mBluetoothAdapter.enable();
  }
 


}



private void startDiscoveryBluetooth((Blooean  startSearch)

{


  boolean canBle = UtilityBase.canBle(this);
  LogUtilBase.LogD(null, "startDiscoveryBluetooth startSearch");
  LogUtilBase.LogD(null, "canBle=" + canBle);

  boolean flag = false;
  // 记录最新的连接设备名称
  String lastDeviceName = AppConfig.getConfigString(
    Const.BLUE_DEVICE_LAST_NAME, "");
  if (lastDeviceName.length() > 0 && !startSearch) {
   LogUtilBase.LogD(null, "startDiscoveryBluetooth false");

   Set<BluetoothDevice> pairedDevices = mBluetoothAdapter
     .getBondedDevices();
   if (pairedDevices != null && pairedDevices.size() > 0) {
    for (BluetoothDevice device : pairedDevices) {
     String name = device.getName();
     if (!StringUtilBase.stringIsEmpty(name)
       && name.equals(lastDeviceName)) {
      LogUtilBase.LogD(null,
        "startDiscoveryBluetooth deviceName=" + name);
      bondBluetoothDevice(device, true);
      flag = true;
      break;
     }
    }
   }
  }

  if (!flag) {
   new Thread(new Runnable() {

    @Override
    public void run() {
     LogUtilBase.LogD(null, "startDiscoveryBluetooth true");
     mIsStateOn = false;

     // int flag = 0;
     while (!mIsStateOn) {
      // flag ++;
      if (mBluetoothAdapter.getState() == BluetoothAdapter.STATE_ON) {
       mIsStateOn = true;
       mBluetoothAdapter.startDiscovery();

       mStartDiscovery = true;
       // startCheckBlueTimer();// 监控蓝牙搜索时间
       break;
      }

      // 如果用户禁止打开蓝牙.
      // if(flag >= 20)
      // {
      // mHandler.sendEmptyMessage(MSG_CONNECT_FAIL);
      // break;
      // }
     }
    }
   }).start();
  }
 


}

/*
  * 开始测量
  */
 private void sendStartTest() {

  // 防止用户频繁点击开始
  if (mReceiveMessageThread == null) {

   if (mBluetoothSocket == null) {
    mHandler.sendEmptyMessage(MSG_MEASURE_EXCEPTION_FAIL);
    return;
   }

   // 连接血压计
   boolean flag = sendTestMessage(SEND_CONNECT_PRESSURE);
   if (flag) {
    LogUtilBase.LogD(null, "sendStartTest");

    mStopReadThread = false;
    mReceiveCheckPower = false;
    startReceiveMessageThread();
   } else {
    mHandler.sendEmptyMessage(MSG_MEASURE_EXCEPTION_FAIL);
   }
  }
 }


/*
  * 停止测量
  */
 public void sendStopTest() {

  if (mBluetoothSocket == null) {
   mHandler.sendEmptyMessage(MSG_MEASURE_EXCEPTION_FAIL);
   return;
  }

  // mRequestStopTest = true;
  // sendTestMessage(SEND_STOP_PRESSURE);

  boolean flag = sendTestMessage(SEND_STOP_PRESSURE);
  if (flag) {
   LogUtilBase.LogD(null, "sendStopTest");
   mRequestStopTest = true;
  } else {
   mHandler.sendEmptyMessage(MSG_MEASURE_EXCEPTION_FAIL);
  }
 }

// 收到设备传过来的数据进行出来显示,上传


private void doWithTestData(ArrayList<Byte> dataList) {
  if (dataList != null && dataList.size() > 0) {
   int totalSize = dataList.size();

   // 收到连接血压计指令
   if (!mReceiveConnect) {
    boolean flag = false;
    if (totalSize == RECEIVE_CONNECT_PRESSURE.length) {
     for (int i = 0; i < RECEIVE_CONNECT_PRESSURE.length; i++) {
      if (!RECEIVE_CONNECT_PRESSURE[i]
        .equals(dataList.get(i))) {
       flag = true;
       break;
      }
     }
    }

    if (!flag) {
     mReceiveConnect = true;
     // 每次测量前查询 power
     sendTestMessage(SEND_CHECK_POWER_PRESSURE);

    } else {
     UIHelper.showToast(
       BloodPressureCheckOperationActivity.this,
       R.string.bluetooth_fail_receive_connect,
       Gravity.CENTER);
     LogUtilBase.LogD(null,
       "bluetooth_fail_receive_connect====>size="
         + totalSize);

     stopReceiveMessageThread();
     sendStopTestUI();
    }

    return;
   }

   // 查询电量
   if (!mReceiveCheckPower) {
    boolean flag = false;
    // 查询电量 返回数据 len = 9
    if (totalSize == RECEIVE_DATA_POWER) {
     for (int i = 0; i < RECEIVE_CHECK_POWER_PRESSURE.length; i++) {
      if (!RECEIVE_CHECK_POWER_PRESSURE[i].equals(dataList
        .get(i))) {
       flag = true;
       LogUtilBase.LogD(null,
         "bluetooth_fail_receive_check_power====>index="
           + i);
       break;
      }
     }
    }

    if (!flag) {

     String highString = UtilityBase.getHexStringByByte(dataList
       .get(totalSize - 3));
     String lowString = UtilityBase.getHexStringByByte(dataList
       .get(totalSize - 2));
     String hexString = highString + lowString;
     int power = Integer.parseInt(hexString, 16);

     LogUtilBase.LogD(null,
       "bluetooth_success_receive_check_power====>power="
         + power + "mv");

     // 电量低于3600时,提示用户
     if (power < POWER_TOO_LOW) {
      UIHelper.showToast(this,
        R.string.blood_pressure_device_no_power,
        Gravity.BOTTOM);
      stopReceiveMessageThread();
     } else {
      mReceiveCheckPower = true;
      // 开始测量
      LogUtilBase.LogD(null, "start_pressure-------启动测量");
      sendTestMessage(SEND_START_PRESSURE);
     }

    } else {
     LogUtilBase.LogD(null,
       "bluetooth_fail_receive_check_power====>size="
         + totalSize);

     stopReceiveMessageThread();
     sendStopTestUI();
    }

    return;
   }

   // 收到开始测量指令
   if (!mReceiveStart) {
    boolean flag = false;
    if (totalSize == RECEIVE_START_PRESSURE.length) {
     for (int i = 0; i < RECEIVE_START_PRESSURE.length; i++) {
      if (!RECEIVE_START_PRESSURE[i].equals(dataList.get(i))) {
       flag = true;
       break;
      }
     }

    }

    if (!flag) {
     mReceiveStart = true;
     sendStartTestUI();
     // 收到开始测量指令后,收到的都是过程数据,结果数据,错误数据
    } else {
     UIHelper.showToast(
       BloodPressureCheckOperationActivity.this,
       R.string.bluetooth_fail_receive_begin,
       Gravity.CENTER);
     LogUtilBase.LogD(null,
       "bluetooth_fail_receive_begin====>size="
         + totalSize);

     stopReceiveMessageThread();
     sendStopTestUI();
    }

    return;
   }

   // 收到停止测量指令
   if (mRequestStopTest && totalSize == RECEIVE_STOP_PRESSURE.length) {
    boolean flag = false;
    for (int i = 0; i < RECEIVE_STOP_PRESSURE.length; i++) {
     if (!RECEIVE_STOP_PRESSURE[i].equals(dataList.get(i))) {
      UIHelper.showToast(
        BloodPressureCheckOperationActivity.this,
        R.string.bluetooth_fail_receive_stop,
        Gravity.CENTER);
      LogUtilBase.LogD(null,
        "bluetooth_fail_receive_stop====>index=" + i);

      stopReceiveMessageThread();
      sendStopTestUI();
      flag = true;
      break;
     }
    }

    if (!flag) {
     // 停止测量,线程while循环结束
     stopReceiveMessageThread();
     sendStopTestUI();
    }

    return;
   }

   // ==============================================
   mReceiveDataIng = true;// 正在收数据

   boolean result = false;
   // TODO 处理血压测量过程中异常(错误数据 len = 8)
   if (totalSize == RECEIVE_DATA_ERROR) {
    // 字节数量为6个.
    boolean flag = false;
    for (int i = 0; i < RECEIVE_TEST_ERROR_PRESSURE.length; i++) {
     if (RECEIVE_TEST_ERROR_PRESSURE[i].equals(dataList.get(i))) {
      flag = true;
     } else {
      flag = false;
     }
    }

    if (flag) {
     byte error_state_a = 0x01;// 请检查血压计佩戴是否正确
     byte error_state_b = 0x02;// 血压计袖带过松或漏气
     byte error_state_c = 0x04;// 请保持安静 ,重新测量
     byte error_state_d = 0x07;// 血压计电量低,请充电
     // byte error_state_e = 0x15;// 测量出错,请重新测量
     if (dataList.get(6).equals(error_state_a)) {
      UIHelper.showToast(
        BloodPressureCheckOperationActivity.this,
        R.string.blood_pressure_state_is_right,
        Gravity.CENTER);
      LogUtilBase.LogD(null, "=====>请检查血压计佩戴是否正确 ");
     } else if (dataList.get(6).equals(error_state_b)) {
      UIHelper.showToast(
        BloodPressureCheckOperationActivity.this,
        R.string.blood_pressure_state_cuff_loose,
        Gravity.CENTER);
      LogUtilBase.LogD(null, "=====>血压计袖带过松或漏气");
     } else if (dataList.get(6).equals(error_state_c)) {
      UIHelper.showToast(
        BloodPressureCheckOperationActivity.this,
        R.string.blood_pressure_state_keep_quiet,
        Gravity.CENTER);
      LogUtilBase.LogD(null, "=====>请保持安静 重新测量 ");
     } else if (dataList.get(6).equals(error_state_d)) {
      UIHelper.showToast(
        BloodPressureCheckOperationActivity.this,
        R.string.blood_pressure_state_power_low,
        Gravity.CENTER);
      LogUtilBase.LogD(null, "=====>血压计电量低,请充电 ");
     } else {
      // 发送数据过程中,出现错误, 退出测量
      UIHelper.showToast(
        BloodPressureCheckOperationActivity.this,
        R.string.bluetooth_fail_receive_ing,
        Gravity.CENTER);
      LogUtilBase.LogD(
        null,
        "=====>bluetooth_fail_receive_ing 测量出错,请重新测量"
          + dataList.get(6) + "/ "
          + dataList.get(7));
     }

     stopReceiveMessageThread();
     sendStopTestUI();
    }
   }

   if (totalSize == RECEIVE_DATA_ING) {
    result = false;
   } else if (totalSize == RECEIVE_DATA_RESULT) {
    result = true;
   } else {
    // 可能会有丢包数据,不处理,不更新ui
    LogUtilBase.LogD(null,
      "发生丢包数据=========>>" + String.valueOf(totalSize));
    return;
   }

   if (result) {
    // TODO 结果判断异常处理
    for (int i = 0; i < RECEIVE_TEST_RESULT_PRESSURE.length; i++) {
     if (!dataList.get(i)
       .equals(RECEIVE_TEST_RESULT_PRESSURE[i])) {
      LogUtilBase.LogD(null,
        "发生错误数据=========>>" + dataList.toString());
      return;
     }
    }
    int pul_0 = UtilityBase.toTenInt((dataList.get(totalSize - 2)));
    int pul_1 = UtilityBase.toTenInt((dataList.get(totalSize - 3)));
    int dia_0 = UtilityBase.toTenInt((dataList.get(totalSize - 4)));
    int dia_1 = UtilityBase.toTenInt((dataList.get(totalSize - 5)));
    int sys_0 = UtilityBase.toTenInt((dataList.get(totalSize - 6)));
    int sys_1 = UtilityBase.toTenInt((dataList.get(totalSize - 7)));

    int pul = pul_1 ^ pul_0;
    int dia = dia_1 ^ dia_0;
    int sys = sys_1 ^ sys_0;

    LogUtilBase.LogD(null, "pul=========>>" + String.valueOf(pul));
    LogUtilBase.LogD(null, "dia=========>>" + String.valueOf(dia));
    LogUtilBase.LogD(null, "sys=========>>" + String.valueOf(sys));

    stopReceiveMessageThread();
    sendStopTestUI();

    // TODO 处理结果
    updateUI(false);
    TextView bloodPressureHighTV = (TextView) findViewById(R.id.bloodPressureHighTextView);
    TextView bloodPressureLowTV = (TextView) findViewById(R.id.bloodPressureLowTextView);
    TextView bloodPressureHeartTV = (TextView) findViewById(R.id.heartTextView);

    bloodPressureHighTV.setText(String.valueOf(sys));
    bloodPressureLowTV.setText(String.valueOf(dia));
    bloodPressureHeartTV.setText(String.valueOf(pul));
    
    String LHPress = "已检测  " + String.valueOf(sys) + "/" + String.valueOf(dia) + "mmHg" + "  " + String.valueOf(pul) + "bpm";
    
    for (int i = 1; i < JsonCacheUtils.PAGE_XUEYA + 1; i++) {
     File file = new File(JsonCacheUtils.pathXueYa + File.separator + "downLoadData_" + i + ".txt");
     if (file.exists()) {
      String jsonCache = JsonCacheUtils.readJsonCache(file).trim();
      mArrayList = JsonParserBase.parseJsonCheckMain(jsonCache , WebDataTypeBase.APP_XUEYA_CHECK_LIST);
      for(CheckItem ci : mArrayList){
       if (ci.uid.equals(mUid)) {
        ci.istest = LHPress;
       }
      }
      String savaJson = JsonCacheUtils.listToJsonStirng(mArrayList);
      JsonCacheUtils.writeJsonCache(savaJson, "downLoadData_" + i + ".txt" , JsonCacheUtils.pathXueYa);
     }
    }
    
    // TODO 上传数据
    postUpdateBloodPressureData(String.valueOf(sys),
      String.valueOf(dia), String.valueOf(pul));

   } else {
    // int d5 = UtilityBase.toTenInt(dataList
    // .get(totalSize - 7));
    int d4 = UtilityBase.toTenInt(dataList.get(totalSize - 6));
    // int d3 = UtilityBase.toTenInt(dataList
    // .get(totalSize - 5));
    // int d2 = UtilityBase.toTenInt(dataList
    // .get(totalSize - 4));
    int d1 = UtilityBase.toTenInt(dataList.get(totalSize - 3));
    // int d0 = UtilityBase.toTenInt(dataList
    // .get(totalSize - 2));

    int p = (d4 << 8) + (d4 ^ d1);
    LogUtilBase.LogD(null, "p=========>>" + String.valueOf(p));

    mBloodPreValueTV.setText(String.format("%03d", p));
   }
  } else {
   // ====================================
   // 这种情况不会出现,接收消息线程已判断,大于0才会进入handler
   // UIHelper.showToast(getApplicationContext(),
   // R.string.bluetooth_fail_receive_no, Gravity.CENTER);
  }
 

//  上传数据,并写入缓存


private void postUpdateBloodPressureData(String bloodPressureHighStr,
   String bloodPressureLowStr, String bloodPressureHeart) {

  JSONObject jsonObj = new JSONObject();
  JSONArray jsonArray = new JSONArray();

  JSONObject json = new JSONObject();
  try {

   json.put("uid", mUid);
   json.put("doctorid", LoginUtil.getEnuoDoctor(this).doctorId);
   json.put("bloodPressureHigh", bloodPressureHighStr);
   json.put("bloodPressureLow", bloodPressureLowStr);
   json.put("HeartRate", bloodPressureHeart);
   json.put("type", 1);
   json.put("time", System.currentTimeMillis());
   json.put("dateStr", DateUtilBase.stringFromDate(
     new Date(System.currentTimeMillis()),
     DateUtilBase.YEAR_MONTH_DAY));
   json.put("checkTime", System.currentTimeMillis());
   json.put("timeFlag", System.currentTimeMillis());
   json.put("updateState", 11);
   json.put("type", 0);// 手动录入1,设备检测 0
   json.put("dataType", 3);// 医生端 3

   jsonArray.put(json);
   jsonObj.put("myBloodPressures", jsonArray);
   LogUtilBase.LogD("my bloodPressure simple data",
     jsonArray.toString());

  } catch (JSONException e) {
   e.printStackTrace();
  }

  showProgressDialog();
  
  File file = new File(JsonCacheUtils.pathXueYa + File.separator + JsonCacheUtils.upLoadXueYaFileName);
  String jsonCahcheString = null;
  if (file.exists()) {
   jsonCahcheString = JsonCacheUtils.readJsonCache(file);
   JSONTokener jsonTok = new JSONTokener(jsonCahcheString);
   JSONArray jsonArray2= new JSONArray();
   JSONObject jsonObjCache = new JSONObject();
   try {
    JSONObject root = (JSONObject)jsonTok.nextValue();
    jsonArray2 = root.getJSONArray("myBloodPressures");
   } catch (JSONException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
   }
   jsonArray2.put(json);
   try {
    jsonObjCache.put("myBloodPressures", jsonArray2);
   } catch (JSONException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
   }
   JsonCacheUtils.writeJsonCache(jsonObjCache.toString(), JsonCacheUtils.upLoadXueYaFileName , JsonCacheUtils.pathXueYa);
   jsonCahcheString = JsonCacheUtils.readJsonCache(file);
  }else {
   JsonCacheUtils.writeJsonCache(jsonObj.toString(), JsonCacheUtils.upLoadXueYaFileName , JsonCacheUtils.pathXueYa);
   jsonCahcheString = JsonCacheUtils.readJsonCache(file);
  }
  
  if (!TextUtils.isEmpty(jsonCahcheString)) {
   WebApiBase.postDataReturnJson(SettingBase.postBloodPressureDataUrlCache(),
     jsonObj.toString(), BloodPressureCheckOperationActivity.this,
     REQUEST_POST_XUEYA_DATA);
  }
  
  // TODO 接口
//  WebApiBase.postDataReturnJson(SettingBase.postBloodPressureDataUrl(),
//    jsonObj.toString(), BloodPressureCheckOperationActivity.this,
//    REQUEST_POST_XUEYA_DATA);
 }


@SuppressLint("HandlerLeak")
 public Handler mHandler = new Handler() {

  @SuppressWarnings("unchecked")
  public void handleMessage(Message msg) {
   switch (msg.what) {
   case MSG_POST_DATA_SUCCESS:

    JsonResult result = (JsonResult) msg.obj;

    if (result != null && result.code == JsonResult.CODE_SUCCESS) {
//     JSONObject jsonObject = (JSONObject) result.data;
//     try {
//      idPic = jsonObject.getString("id");
//      timeFlag = jsonObject.getString("timeFlag");
//     } catch (JSONException e) {
//      // TODO Auto-generated catch block
//      e.printStackTrace();
//     }
     
      File file = new File(JsonCacheUtils.pathXueYa + File.separator + JsonCacheUtils.upLoadXueYaFileName);
      if (file.exists()) {
       file.delete();
      }
     
     UIHelper.showToast(
       BloodPressureCheckOperationActivity.this,
       R.string.record_result_save_success_info,
       Gravity.BOTTOM);
    } else {
     UIHelper.showToast(
       BloodPressureCheckOperationActivity.this,
       R.string.record_result_save_fail_info,
       Gravity.BOTTOM);
    }

    break;
   case MSG_START_DATA_LIST:
    ArrayList<Byte> dataList = (ArrayList<Byte>) msg.obj;
    doWithTestData(dataList);
    break;
   case MSG_CONNECT_SUCCESS:

    // old
    updateStartTestState();

    // new
    // 绑定完设备,自动查询电量,先发送连接设备指令
    // sendStartTest();

    // 建立连接后,禁止锁屏
    getWindow().addFlags(
      WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
    break;
   case MSG_CONNECT_FAIL:
    mBtImgBtn.setBackgroundResource(R.drawable.bluetooth_no_device);
    mBtConStateTV.setText(R.string.blood_pressure_no_device);
    break;
   case MSG_MEASURE_EXCEPTION_FAIL:

    // 收消息异常
    UIHelper.showToast(getApplicationContext(),
      R.string.blood_pressure_test_exception, Gravity.CENTER);

    stopReceiveMessageThread();
    sendStopTestUI();

    if (mInInputStream != null) {
     try {
      mInInputStream.close();
     } catch (IOException e) {
      e.printStackTrace();
     }
    }

    finish();
    break;
   default:
    break;
   }
  }
 };

//  接收数据

 private class ReceiveMessageThread extends Thread {
  @Override
  public void run() {
   synchronized (mLockObj) {

    if (mBluetoothSocket != null) {

     try {
      mInInputStream = mBluetoothSocket.getInputStream();

      ArrayList<Byte> dataList = new ArrayList<Byte>();
      byte[] buffer = null;
      int len = 0;

      int retryCount = 0;
      while (!mStopReadThread) {
       LogUtilBase
         .LogD(null,
           "===================================mStopReadThread while begin");

       dataList.clear();
       buffer = new byte[100];

       if (mInInputStream != null
         && mInInputStream.available() > 0) {
        LogUtilBase.LogD(null,
          "mInInputStream.available()="
            + mInInputStream.available());
        len = mInInputStream.read(buffer);
       } else {
        len = 0;
       }

       // 发送过程中数据为13字节,(发送过程中,有可能每次不是13个字节,4个字节
       // 9个字节两次发)发生丢包数据
       for (int i = 0; i < len; i++) {
        dataList.add(buffer[i]);
        LogUtilBase.LogD(
          null,
          UtilityBase
            .getHexStringByByte(buffer[i])
            + "=======>len=" + len);
       }

       if (len > 0) {
        mHandler.obtainMessage(MSG_START_DATA_LIST,
          dataList).sendToTarget();
        LogUtilBase.LogD(null,
          "==================================="
            + dataList.size());

        retryCount = 0;
       } else {
        // 如果正在收数据中
        if (mReceiveDataIng
          || mInInputStream.available() <= 0) {
         retryCount++;
         LogUtilBase
           .LogD(null,
             "=================================== len=0");
         if (retryCount >= 10 * 2) {// 收不到数据,再试执行20次接收数据,如果收不到,会报通信异常
          LogUtilBase.LogD(null,
            "ReceiveMessageThread  retryCount="
              + retryCount);
          mHandler.sendEmptyMessage(MSG_MEASURE_EXCEPTION_FAIL);
          break;
         }
        }
       }

       try {
        Thread.sleep(SLEEP_RECEIVE_TIME);
       } catch (InterruptedException e) {
        e.printStackTrace();
       }

       LogUtilBase
         .LogD(null,
           "===================================mStopReadThread while end");
      }
     } catch (IOException e) {
      e.printStackTrace();

      LogUtilBase.LogD(null,
        "ReceiveMessageThread  exception");
      mHandler.sendEmptyMessage(MSG_MEASURE_EXCEPTION_FAIL);
     }
    } else {
     LogUtilBase.LogD(null,
       "ReceiveMessageThread  mBluetoothSocket null");
     mHandler.sendEmptyMessage(MSG_MEASURE_EXCEPTION_FAIL);
    }
   }
  }
 }



private BroadcastReceiver mBluetoothReceiver = new BroadcastReceiver() {

  boolean isHaveDevice = false;

  @Override
  public void onReceive(Context context, Intent intent) {

   String action = intent.getAction();

   if (action.equals(BluetoothAdapter.ACTION_DISCOVERY_FINISHED)) {
    if (!isHaveDevice && mStartDiscovery) {
     LogUtilBase.LogD(null, "ACTION_DISCOVERY_FINISHED");
     mStartDiscovery = false;
     mBtImgBtn
       .setBackgroundResource(R.drawable.bluetooth_no_connect);
     mBtConStateTV.setText(R.string.blood_pressure_no_device);

     // stopCheckBlueTimer();
    }

   } else if (action.equals(BluetoothDevice.ACTION_FOUND)) {

    if (intent != null && !isHaveDevice) {
     BluetoothDevice device = intent
       .getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);

     if (device != null) {
      String name = device.getName();
      if (!StringUtilBase.stringIsEmpty(name)) {
       if (name.contains(DEVICE_FRONT_STRING)) {
        LogUtilBase.LogD(null, "ACTION_FOUND");

        isHaveDevice = true;
        // stopCheckBlueTimer();
        bondBluetoothDevice(device, false);
       }
      }
     }
    }

   } else if (action.equals(BluetoothDevice.ACTION_BOND_STATE_CHANGED)) {
    LogUtilBase.LogD(null, "ACTION_BOND_STATE_CHANGED");
    // LogUtilBase.LogD(null, mBluetoothDevice.getBondState() + "");

    if (mBluetoothDevice != null
      && mBluetoothDevice.getBondState() == BluetoothDevice.BOND_BONDED) {
     ConnectThread connectThread = new ConnectThread(
       mBluetoothDevice, false);
     if (!connectThread.isAlive()) {
      connectThread.start();
     }
    }
   }
  }
 };

 private void bondBluetoothDevice(BluetoothDevice device, boolean isOldDevice) {

  mBluetoothAdapter.cancelDiscovery();
  mBluetoothDevice = device;

  int bondState = mBluetoothDevice.getBondState();

  if (bondState == BluetoothDevice.BOND_BONDED) {
   new ConnectThread(mBluetoothDevice, isOldDevice).start();
  } else {
   try {
    Method createBondMethod = BluetoothDevice.class
      .getMethod("createBond");
    createBondMethod.invoke(mBluetoothDevice);
   } catch (Exception e) {
    e.printStackTrace();

    UIHelper.showToast(BloodPressureCheckOperationActivity.this,
      R.string.bluetooth_bond_fail, Gravity.CENTER);
    finish();
   }
  }
 }

 private class ConnectThread extends Thread {

  private BluetoothDevice tempDevice;
  private boolean tempIsOldDevice;

  public ConnectThread(BluetoothDevice device, boolean isOldDevice) {
   tempDevice = device;
   tempIsOldDevice = isOldDevice;
  }

  @Override
  public void run() {

   UUID uuid = UUID.fromString(SPP_UUID);

   // int socketConnectSecure = AppConfig.getConfigInt(
   // Const.BLUE_DEVICE_SOCKET_IN_SECURE,
   // BLUE_TOOTH_SOCKET_CONNECT_FIRST);

   boolean isConnected = false;
   // 先试一下createInsecureRfcommSocketToServiceRecord
   Method m;
   try {
//     m = tempDevice.getClass().getMethod("createRfcommSocket",
//     new Class[] { int.class });
//     mBluetoothSocket = (BluetoothSocket) m.invoke(tempDevice, 1);
//     mBluetoothAdapter.cancelDiscovery();
//     mBluetoothSocket.connect();
    mBluetoothSocket = tempDevice
      .createInsecureRfcommSocketToServiceRecord(uuid);
    mBluetoothSocket.connect();

    LogUtilBase.LogD(null, "ConnectThread no connect exception");
    isConnected = true;
   } catch (Exception e) {
    LogUtilBase.LogD(null,
      "ConnectThread createInsecureRfcommSocketToServiceRecord exception=====>>"
        + Log.getStackTraceString(e));
   }

   LogUtilBase.LogD(null,
     "ConnectThread createInsecureRfcommSocketToServiceRecord isConnected="
       + isConnected);

   if (isConnected) {
    // 记录最新的连接设备名称
    AppConfig.setConfig(Const.BLUE_DEVICE_LAST_NAME,
      tempDevice.getName());
    // AppConfig.setConfig(Const.BLUE_DEVICE_SOCKET_IN_SECURE,
    // BLUE_TOOTH_SOCKET_CONNECT_IN_SECURE);

    mHandler.obtainMessage(MSG_CONNECT_SUCCESS).sendToTarget();
   } else {
    // 再试一下 createRfcommSocketToServiceRecord
    try {
     mBluetoothSocket = tempDevice
       .createRfcommSocketToServiceRecord(uuid);
     mBluetoothSocket.connect();

     isConnected = true;
    } catch (IOException e) {
     LogUtilBase.LogD(null,
       "ConnectThread createRfcommSocketToServiceRecord exception=====>>"
         + Log.getStackTraceString(e));
     try {
      if (mBluetoothSocket != null) {
       mBluetoothSocket.close();
      }
     } catch (IOException e1) {
      e1.printStackTrace();
     }
    }

    LogUtilBase.LogD(null,
      "ConnectThread createRfcommSocketToServiceRecord isConnected="
        + isConnected);

    if (isConnected) {
     // 记录最新的连接设备名称
     AppConfig.setConfig(Const.BLUE_DEVICE_LAST_NAME,
       tempDevice.getName());
     // AppConfig.setConfig(Const.BLUE_DEVICE_SOCKET_IN_SECURE,
     // BLUE_TOOTH_SOCKET_CONNECT_SECURE);

     mHandler.obtainMessage(MSG_CONNECT_SUCCESS).sendToTarget();
    } else {
     if (tempIsOldDevice) {
      // 用的是旧的已经配对的设备,连接
      // 重新搜索新的,连接设备
      startDiscoveryBluetooth(true);
     } else {
      // 新搜索出来的,失败
      mHandler.obtainMessage(MSG_CONNECT_FAIL).sendToTarget();
     }
    }
   }
  }
 }


private boolean sendTestMessage(byte[] datas) {

  try {
   Thread.sleep(SLEEP_SEND_TIME);
  } catch (InterruptedException e2) {
   e2.printStackTrace();
  }

  if (mBluetoothSocket == null) {
   UIHelper.showToast(this, "蓝牙尚未连接", Gravity.CENTER);
   return false;
  }

  boolean flag = false;
  try {
   mOutputStream = mBluetoothSocket.getOutputStream();
   if (mOutputStream != null) {
    mOutputStream.flush();
    mOutputStream.write(datas);
    flag = true;
   }
  } catch (Exception e) {
   e.printStackTrace();
   try {
    if (mOutputStream != null) {
     mOutputStream.flush();
     mOutputStream.close();
    }
   } catch (IOException e1) {
    e1.printStackTrace();
   }
  }
  return flag;
 }















}


  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值