anroid 之蓝牙开发

本文介绍了一款蓝牙集成Demo的应用实现,详细讲解了如何处理蓝牙设备的连接配对、根据协议发送指令、解析从机返回的数据并绘制UI界面等内容。通过具体的代码示例展示了蓝牙数据交互的具体流程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >


Index: DeviceConnectActivity.java
===================================================================
--- DeviceConnectActivity.java (revision 0)
+++ DeviceConnectActivity.java (revision 3)
@@ -0,0 +1,863 @@
+package com.bm.oncallpad.activity;
+
+import java.io.UnsupportedEncodingException;
+import java.util.ArrayList;
+import java.util.LinkedHashMap;
+import java.util.UUID;
+
+import javax.xml.transform.Templates;
+
+import org.json.JSONArray;
+import org.json.JSONException;
+import org.json.JSONObject;
+
+import cn.novacomm.ble.iGate;
+import cn.novacomm.ble.iGateCallBacks;
+import cn.novacomm.ble.iGateCallBacks.iGateHostState;
+
+import com.android.pc.ioc.inject.InjectHttpErr;
+import com.android.pc.ioc.inject.InjectHttpOk;
+import com.android.pc.ioc.internet.FastHttpHander;
+import com.android.pc.ioc.internet.InternetConfig;
+import com.android.pc.ioc.internet.ResponseEntity;
+import com.bm.oncallpad.R;
+import com.bm.oncallpad.R.id;
+import com.bm.oncallpad.R.layout;
+import com.bm.oncallpad.R.menu;
+import com.bm.oncallpad.app.App;
+import com.bm.oncallpad.app.Constant;
+import com.bm.oncallpad.utils.ToastUtil;
+import com.bm.oncallpad.view.DialogHelper;
+import com.bm.oncallpad.view.NewSelectDialog;
+import android.app.Activity;
+import android.bluetooth.BluetoothAdapter;
+import android.bluetooth.BluetoothDevice;
+import android.content.BroadcastReceiver;
+import android.content.Context;
+import android.content.Intent;
+import android.content.IntentFilter;
+import android.os.Bundle;
+import android.os.Handler;
+import android.os.Message;
+import android.text.method.ScrollingMovementMethod;
+import android.util.Log;
+import android.view.Menu;
+import android.view.MenuItem;
+import android.view.View;
+import android.view.View.OnClickListener;
+import android.widget.Button;
+import android.widget.ImageView;
+import android.widget.TextView;
+import android.widget.Toast;
+/**
+ *
+ * Copyright © 2015 蓝色互动. All rights reserved.
+ *
+ * @Description 蓝牙集成Demo 只需要处理蓝牙设备的连接 配对 根据协议发送指令 解析从机返回的数据 绘制UI界面即可 指令具体见协议文档
+ * @author huqijie
+ * @date 2015-5-23
+ */
+public class DeviceConnectActivity extends Activity implements iGateCallBacks {
+
+ private static final int ENABLE_BT_REQUEST_ID = 1;
+ // 蓝牙设备的状态
+ private TextView mIGateState;
+ public static Handler handler;
+ private DialogHelper dialogHelper;
+ private DialogHelper device_dialogHelper;
+ private int search_flag = 0;
+ private int device_type,link_device_num=0,mid_ok=0;
+
+ private String Mid = "";
+ String content_N = "";
+ String date = "", values = "", remark = "";
+ private int connect_flag = 0; // 判断蓝牙设备是否连接上了
+ private int i = 0;
+ private Button go_btn;
+ // 获得Mid密令
+ // private String get_mid_secret;
+ private String R_secret, D_secret, K_secret, N_secret;
+ private String[] str = new String[5];
+ // 发送指令
+ private Button send_iv;
+ private int N_num, N_acount;
+ private TextView scan_tv;
+ private int bouned_flag=0;//绑定的标示
+
+ private static final int GETGLUCOSE = 1100;
+ private static final int PUTDATA = 100;
+
+ private ArrayList<String> mConnectedBluetoothDevicesAddress = new ArrayList<String>();
+ private int sendIndex = 0;
+ private iGate mIgate = null;
+ private String device_address;
+ //int got_N_flag = 0;
+ private Button btn_xuetangkongzhi, btn_chiyaotixing;
+
+ private ImageView iv_back;
+ // 蓝牙匹配连接
+ private BroadcastReceiver mPairIntentReceiver;
+ BluetoothDevice aDevice;
+
+ @Override
+ protected void onCreate(Bundle savedInstanceState) {
+ super.onCreate(savedInstanceState);
+ setContentView(R.layout.activity_device_connect);
+
+ mPairIntentReceiver = new BroadcastReceiver() {
+ public void onReceive(Context context, Intent intent) {
+ if (BluetoothDevice.ACTION_BOND_STATE_CHANGED.equals(intent.getAction())) {
+ int bondState = intent.getIntExtra(BluetoothDevice.EXTRA_BOND_STATE, -1);
+ BluetoothDevice aDevice = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
+ if (bondState == BluetoothDevice.BOND_BONDED) {
+ mIgate.iGateDeviceSetPairState(aDevice.getAddress(), true);
+ }
+ }
+ }
+ };
+ init();
+
+ /*handler = new Handler() {
+ public void handleMessage(Message msg) {
+ switch (msg.what) {
+ case 3:
+ String spStr[] = content_N.split("&");
+ Log.e("jason", getJsonData(spStr));
+ putDataByDevice(App.getInstance().getUserInfoBean().getUserID(), getJsonData(spStr));
+ break;
+ default:
+ break;
+ }
+ }
+ };*/
+
+ send_iv.setOnClickListener(new OnClickListener() {
+ @Override
+ public void onClick(View v) {
+ device_type=2;
+ mid_ok=0;
+ Mid="";
+ link_device_num=0;
+ if(bouned_flag==1){
+ device_dialogHelper.startProgressDialog();
+ device_dialogHelper.setDialogMessage("获取设备Mid");
+ }
+ sendOrder("&T1 " + CRC16_Modbus("&T1 ", 4));
+ //sendOrder("&T3 " + CRC16_Modbus("&T3 ", 4));
+ // sendOrder("&TB " + CRC16_Modbus("&TB ", 4));
+ /* sendOrder("&T3 " + CRC16_Modbus("&T3 ", 4));
+ sendOrder("&T1 " + CRC16_Modbus("&T1 ", 4));
+ sendOrder("&T2 " + CRC16_Modbus("&T2 ", 4));
+ sendOrder("&T4 " + CRC16_Modbus("&T4 ", 4));
+ sendOrder("&T5 " + CRC16_Modbus("&T5 ", 4));
+ sendOrder("&T6 " + CRC16_Modbus("&T6 ", 4));
+ sendOrder("&T7 " + CRC16_Modbus("&T7 ", 4));
+ sendOrder("&T8 " + CRC16_Modbus("&T8 ", 4));
+ sendOrder("&TA " + CRC16_Modbus("&TA ", 4));
+ sendOrder("&TB " + CRC16_Modbus("&TB ", 4));
+ sendOrder("&TC " + CRC16_Modbus("&TC ", 4));
+ sendOrder("&TD " + CRC16_Modbus("&TD ", 4));
+ sendOrder("&TE " + CRC16_Modbus("&TE ", 4));
+ sendOrder("&TF " + CRC16_Modbus("&TF ", 4));*/
+
+ }
+ });
+
+ }
+
+ @Override
+ protected void onResume() {
+ super.onResume();
+ // 是否自动连接 这里设为自动连接
+ mIgate.initialize(true);
+ IntentFilter bluetoothPairFilter = new IntentFilter();
+ bluetoothPairFilter.addAction(BluetoothDevice.ACTION_BOND_STATE_CHANGED);
+ registerReceiver(mPairIntentReceiver, bluetoothPairFilter);
+ mIgate.startScanning(false);
+ }
+ @Override
+ protected void onPause() {
+ super.onPause();
+ // 记得在对应的生命周期里处理广播
+ unregisterReceiver(mPairIntentReceiver);
+ }
+
+ /**
+ *
+ * @Description 对keyback按键的处理
+ * @author 高骅
+ * @see android.app.Activity#onBackPressed()
+ */
+ @Override
+ public void onBackPressed() {
+
+ for (int i = 0; i < mConnectedBluetoothDevicesAddress.size(); i++) {
+ mIgate.iGateDeviceDisconnect(mConnectedBluetoothDevicesAddress.get(i));
+ }
+ if (mIgate.getIGateState() == iGateCallBacks.iGateHostState.iGateHostStateSearching) {
+ mIgate.stopScanning();
+ }
+ super.onBackPressed();
+ String P_secret = "&P1 " + CRC16_Modbus("&P1 ", 4);
+ sendOrder(P_secret);
+ Log.e("gggggggggggg", "gggggggggg");
+ }
+
+ /**
+ * 蓝牙状态变化的回调方法
+ *
+ */
+ public void iGateHostDidUpdateState(final iGateHostState state) {
+ switch (state) {
+ case iGateHostStatePoweredOff:
+ Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
+ startActivityForResult(enableBtIntent, ENABLE_BT_REQUEST_ID);
+ ToastUtil.getInterface().showToast(this, "电源关闭", 1);
+ case iGateHostStateIdle:
+ mIGateState.setText("设备闲置中");
+ break;
+ case iGateHostStateSearching:
+ mIGateState.setText("正在搜索...");
+ break;
+ case iGateHostStateInit:
+ break;
+ case iGateHostStateConnecting:
+ mIGateState.setText("连接中...");
+ break;
+ default:
+ break;
+ }
+ /*
+ // adding to the UI have to happen in UI thread
+ runOnUiThread(new Runnable() {
+ @Override
+ public void run() {
+ switch (mIgate.getIGateState()) {
+ case iGateHostStateIdle:
+ if (mConnectedBluetoothDevicesAddress.size() == 0) {
+
+ } else {
+ //listConnectedDevices();
+ }
+ break;
+ case iGateHostStateSearching:
+ // mIGateState.setText("正在搜索...");
+ break;
+ default:
+ break;
+ }
+
+ }
+ });*/
+ }
+
+ /**
+ * 搜索到蓝牙的回调方法
+ *
+ */
+ public void iGateDeviceFound(final String bluetoothAddress, final int rssi, final byte[] record) {
+ runOnUiThread(new Runnable() {
+ @Override
+ public void run() {
+ Log.e("连接设备中", "连接设备中");
+ mIGateState.setText("连接中...");
+ mIgate.stopScanning();
+ device_address = bluetoothAddress;
+ Log.e("address", bluetoothAddress);
+ mIgate.iGateDeviceConnect(bluetoothAddress);
+ }
+ });
+ }
+
+ /**
+ * 蓝牙连接的回调方法
+ *
+ */
+ public void iGateDeviceConnected(final String bluetoothAddress) {
+ /*if (!mConnectedBluetoothDevicesAddress.contains(bluetoothAddress)) {
+ mConnectedBluetoothDevicesAddress.add(bluetoothAddress);
+ }*/
+ runOnUiThread(new Runnable() {
+ @Override
+ public void run() {
+ Log.e("绑定中", "绑定中");
+ Log.e("connect_address", bluetoothAddress);
+ mIGateState.setText("绑定中...");
+ mIgate.iGateDeviceBondService(bluetoothAddress);
+ }
+ });
+ }
+
+ @Override
+ protected void onDestroy() {
+ // TODO Auto-generated method stub
+ super.onDestroy();
+ /* mIgate.iGateDeviceSetPairState(device_address, false);
+ mIgate = null;*/
+ }
+
+ /**
+ * 蓝牙成功绑定的回调方法
+ *
+ */
+ public void iGateDeviceServiceBonded(final String bluetoothAddress) {
+ // got_N_flag = 0;
+ N_acount = 0;
+ content_N = "";
+ Log.e("已绑定", "已绑定");
+
+ runOnUiThread(new Runnable() {
+ @Override
+ public void run() {
+ Log.e("~~~DeviceBonded", "DeviceBonded");
+ bouned_flag=1;
+ listConnectedDevices();
+ }
+ });
+ }
+
+ /**
+ * 蓝牙断开连接的回调接口
+ *
+ */
+ public void iGateDeviceDisConnected(final String bluetoothAddress) {
+ mIgate.iGateDeviceDisconnect(bluetoothAddress);
+ //mConnectedBluetoothDevicesAddress.remove(bluetoothAddress);
+ runOnUiThread(new Runnable() {
+ @Override
+ public void run() {
+ /*if (mConnectedBluetoothDevicesAddress.size() > 0) {
+ String allConnectedDevices = new String();
+ for (int i = 0; i < mConnectedBluetoothDevicesAddress.size(); i++) {
+ allConnectedDevices += " " + mConnectedBluetoothDevicesAddress.get(i);
+ }
+
+ } else {*/
+ bouned_flag=0;
+ mIGateState.setText("连接已断开");
+ // mIgate.startScanning(false);
+ if (dialogHelper != null) {
+ dialogHelper.stopProgressDialog();
+ }
+ if (device_dialogHelper != null) {
+ device_dialogHelper.stopProgressDialog();
+ }
+ ToastUtil.getInterface().showToast(DeviceConnectActivity.this, "断开连接", 1);
+
+ //}
+ }
+ });
+ }
+
+ /**
+ * 发送指令的回调方法,接收发送指令返回的数据
+ *
+ */
+ public void iGateDeviceReceivedData(final String bluetoothAddress, final byte[] data) {
+ try {
+ final String tmpValue = new String(data, "UTF-8");
+
+ runOnUiThread(new Runnable() {
+ @Override
+ public void run() {
+ // Log.e("device_type_num", "num="+link_device_num);
+ Log.e("tmpvalues~~~~~~", tmpValue);
+ if ("&M".equals(tmpValue.substring(0, 2)) && (!("&M0".equals(tmpValue.substring(0, 3))))) {
+ Log.e("rightmid", "rightmid");
+ if (device_dialogHelper != null) {
+ device_dialogHelper.stopProgressDialog();
+ }
+ Mid = tmpValue;
+ mid_ok=1;
+ getGlucoseByDate(Mid.substring(2, 13));
+ }
+ if ("&M0".equals(tmpValue.substring(0, 3))) {
+ Log.e("devicenum", "^^^^^"+link_device_num);
+ Log.e("devicetype~~", tmpValue+" "+device_type);
+ if(link_device_num<2){
+ if(device_type==1){
+ sendOrder("&T1 " + CRC16_Modbus("&T1 ", 4));
+ device_type++;
+ Log.e("test_num", "testnum="+device_type);
+ }
+ else if(device_type==2){
+ sendOrder("&T2 " + CRC16_Modbus("&T2 ", 4));
+ device_type++;
+ Log.e("test_num", "testnum="+device_type);
+ }
+ else if(device_type==3){
+ sendOrder("&T3 " + CRC16_Modbus("&T3 ", 4));
+ device_type++;
+ Log.e("test_num", "testnum="+device_type);
+ }
+ else if(device_type==4){
+ sendOrder("&T4 " + CRC16_Modbus("&T4 ", 4));
+ device_type++;
+ Log.e("test_num", "testnum="+device_type);
+ }
+ else if(device_type==5){
+ sendOrder("&T5 " + CRC16_Modbus("&T5 ", 4));
+ device_type++;
+ Log.e("test_num", "testnum="+device_type);
+ }
+ else if(device_type==6){
+ sendOrder("&T6 " + CRC16_Modbus("&T6 ", 4));
+ device_type++;
+ Log.e("test_num", "testnum="+device_type);
+ }
+ else if(device_type==7){
+ sendOrder("&T7 " + CRC16_Modbus("&T7 ", 4));
+ device_type++;
+ Log.e("test_num", "testnum="+device_type);
+ }
+ else if(device_type==8){
+ sendOrder("&T8 " + CRC16_Modbus("&T8 ", 4));
+ device_type++;
+ Log.e("test_num", "testnum="+device_type);
+ }
+ else if(device_type==9){
+ sendOrder("&T9 " + CRC16_Modbus("&T9 ", 4));
+ device_type++;
+ Log.e("test_num", "testnum="+device_type);
+ }
+ else if(device_type==10){
+ sendOrder("&TA " + CRC16_Modbus("&TA ", 4));
+ device_type++;
+ Log.e("test_num", "testnum="+device_type);
+ }
+ else if(device_type==11){
+ sendOrder("&TB " + CRC16_Modbus("&TB ", 4));
+ device_type++;
+ Log.e("test_num", "testnum="+device_type);
+ }
+ else if(device_type==12){
+ sendOrder("&TC " + CRC16_Modbus("&TC ", 4));
+ device_type++;
+ Log.e("test_num", "testnum="+device_type);
+ }
+ else if(device_type==13){
+ sendOrder("&TD " + CRC16_Modbus("&TD ", 4));
+ device_type++;
+ Log.e("test_num", "testnum="+device_type);
+ }
+ else if(device_type==14){
+ sendOrder("&TE " + CRC16_Modbus("&TE ", 4));
+ device_type++;
+ Log.e("test_num", "testnum="+device_type);
+ }
+ else if(device_type==15){
+ sendOrder("&TF " + CRC16_Modbus("&TF ", 4));
+ device_type=1;
+ link_device_num++;
+ Log.e("test_num", "testnum="+device_type);
+ }
+ }else {
+ if (device_dialogHelper != null) {
+ device_dialogHelper.stopProgressDialog();
+ }
+ ToastUtil.getInterface().showToast(DeviceConnectActivity.this, "没找到相应的血糖设备!", 1);
+ }
+
+ }
+
+ if ("&D1".equals(tmpValue.substring(0, 3))) {
+ // content_D = tmpValue;
+ /*
+ * ThreadSendR threadSendR=new ThreadSendR(); new
+ * Thread(threadSendR).start();
+ */
+ R_secret = "&R" + values + " " + CRC16_Modbus("&R" + values + " ", ("&R" + values + " ").length());
+ sendOrder(R_secret);
+
+ }
+ if ("&R1".equals(tmpValue.substring(0, 3))) {
+ // content_R = tmpValue;
+ /*
+ * ThreadSendK threadSendK=new ThreadSendK(); new
+ * Thread(threadSendK).start();
+ */
+ K_secret = "&K" + remark + " " + CRC16_Modbus("&K" + remark + " ", ("&K" + remark + " ").length());
+ sendOrder(K_secret);
+ }
+ if ("&K1".equals(tmpValue.substring(0, 3))) {
+ // content_K = tmpValue;
+ N_secret = "&N " + CRC16_Modbus("&N ", 3);
+ sendOrder(N_secret);
+ //ThreadSendN threadSendN = new ThreadSendN();
+ //new Thread(threadSendN).start();
+ }
+ if ("&N".equals(tmpValue.substring(0, 2))) {
+ content_N = content_N + tmpValue;
+ if (tmpValue.length() > 15) { // 这里是判断返回的是否是血糖数据,15只是一个字符串长度的范围值,没有实际意义
+ // N_num=Integer.parseInt(content_N.substring(2,
+ // content_N.indexOf(" ")));
+ ++N_acount;
+ //content_N = content_N + tmpValue;
+ }
+ if (tmpValue.length() < 10&&(N_acount>0)) { // 这里是判断返回的N数据是否是最后一条,和第一条是否是血糖数据,9只是一个字符串长度的范围值,没有实际意义
+ // got_N_flag = 1;
+ Log.e("length", " "+tmpValue.length());
+ String spStr[] = content_N.split("&");
+ Log.e("jason", getJsonData(spStr));
+ putDataByDevice(App.getInstance().getUser().getUserid(), getJsonData(spStr));
+ Log.e("memeda", "yiyiyaya");
+ }
+ // Log.e("flag", "flag=" + got_N_flag);
+ Log.e("tmpvalue", tmpValue.substring(2, 3));
+ Log.e("N_account", "num=" + N_acount);
+ Log.e("N_num", "num=" + N_num);
+ // DeviceLinkActivity.this.finish();
+ // putDataByDevice("c225775b-986f-4636-83c1-a47901025e59");
+ }
+ if ("&Z".equals(tmpValue.substring(0, 2)) || "&z".equals(tmpValue.substring(0, 2))) {
+ if (dialogHelper != null) {
+ dialogHelper.stopProgressDialog();
+ }
+ if (device_dialogHelper != null) {
+ device_dialogHelper.stopProgressDialog();
+ }
+ String P_secret = "&P1 " + CRC16_Modbus("&P1 ", 4);
+ sendOrder(P_secret);
+ ToastUtil.getInterface().showToast(DeviceConnectActivity.this, "数据CRC校验失败", 1);
+ //DeviceLinkActivity.this.finish();
+ }
+
+ }
+ });
+ } catch (UnsupportedEncodingException e) {
+ e.printStackTrace();
+ }
+ }
+
+ public void iGateDeviceUpdateRssi(final String bluetoothAddress, final int rssi) {
+ Log.i("------", String.format("Rssi report %s,%d", mIgate.iGateDeviceGetName(bluetoothAddress), rssi));
+ }
+
+ public void iGateDeviceLinkLossAlertLevelReport(final String bluetoothAddress, byte alertLevel) {
+ Log.i("------", String.format("Link loss alert level %s,%d", bluetoothAddress, alertLevel));
+ }
+
+ public void iGateDeviceTxPowerReport(final String bluetoothAddress, byte txPower) {
+ Log.i("------", String.format("Tx Power %s,%d", bluetoothAddress, txPower));
+ }
+
+ private void listConnectedDevices() {
+
+ String allConnectedDevices = new String();
+ /*for (int i = 0; i < mConnectedBluetoothDevicesAddress.size(); i++) {
+ allConnectedDevices += " " + mConnectedBluetoothDevicesAddress.get(i);
+ }*/
+ mIGateState.setText("已绑定,请点击下载");
+ connect_flag = 1;
+ Log.e("11111111111", "1111111111111");
+ }
+
+ //初始化
+ public void init() {
+ dialogHelper = new DialogHelper(this);
+ device_dialogHelper=new DialogHelper(this);
+ send_iv = (Button) findViewById(R.id.send_btn);
+ iv_back = (ImageView) this.findViewById(R.id.turn_left_iv);
+ scan_tv=(TextView)this.findViewById(R.id.scan_tv);
+
+ /**
+ * 扫描按钮的点击事件
+ *
+ */
+ scan_tv.setOnClickListener(new OnClickListener() {
+ @Override
+ public void onClick(View v) {
+ // TODO Auto-generated method stub
+ if (mIgate.getIGateState()==iGateHostState.iGateHostStateSearching) {
+
+
+ } else {
+ mIgate.startScanning(false);
+ }
+
+
+ }
+ });
+
+ /**
+ * 返回按钮的点击事件
+ *
+ */
+ iv_back.setOnClickListener(new OnClickListener() {
+ @Override
+ public void onClick(View v) {
+ for (int i = 0; i < mConnectedBluetoothDevicesAddress.size(); i++) {
+ mIgate.iGateDeviceDisconnect(mConnectedBluetoothDevicesAddress.get(i));
+ }
+ if (mIgate.getIGateState() == iGateCallBacks.iGateHostState.iGateHostStateSearching) {
+ mIgate.stopScanning();
+ }
+ String P_secret = "&P1 " + CRC16_Modbus("&P1 ", 4);
+ sendOrder(P_secret);
+ DeviceConnectActivity.this.finish();
+ }
+ });
+ btn_xuetangkongzhi = (Button) this.findViewById(R.id.control_glucose_btn);
+ btn_xuetangkongzhi.setOnClickListener(new OnClickListener() {
+
+ @Override
+ public void onClick(View v) {
+ Intent intent=new Intent();
+ intent.putExtra("show_flag", 1);
+ intent.setClass(DeviceConnectActivity.this,BloodSugarManageActivity.class);
+ startActivity(intent);
+ finish();
+ }
+ });
+
+ btn_chiyaotixing = (Button)this.findViewById(R.id.alarm_setting_btn);
+ btn_chiyaotixing.setOnClickListener(new OnClickListener() {
+
+ @Override
+ public void onClick(View v) {
+ Intent intent=new Intent();
+ intent.putExtra("show_flag", 2);
+ intent.setClass(DeviceConnectActivity.this,BloodSugarManageActivity.class);
+ startActivity(intent);
+ finish();
+ }
+ });
+ mIGateState = (TextView) findViewById(R.id.state_tv);
+ // 参数:上下文对象 UUID 回调接口
+ mIgate = new iGate(this, UUID.fromString("C14D2C0A-401F-B7A9-841F-E2E93B80F631"), this);
+ // mIgate.startScanning(false);
+ }
+
+ /*private class ThreadSendN implements Runnable {
+
+ public void run() {
+ // TODO Auto-generated method stub
+ N_secret = "&N " + CRC16_Modbus("&N ", 3);
+ sendOrder(N_secret);
+ try {
+ while (got_N_flag == 0) {
+ // Log.e("111111111111", "flag="+got_N_flag);
+ Thread.sleep(100);
+ }
+ } catch (Exception e) {
+ e.printStackTrace();
+ }
+ Message msgMessage = new Message();
+ handler.sendMessage(msgMessage);
+ msgMessage = handler.obtainMessage(3);
+ handler.sendMessage(msgMessage);
+ }
+ }
+ */
+
+ /**
+ * CRC校验方法
+ *
+ */
+ public int CRC16_Modbus(String str, int len) {
+
+ int crc = 0xFFFF;
+ int i, j;
+ for (j = 0; j < len; j++) {
+ crc = crc ^ (str.charAt(j));
+ for (i = 0; i < 8; i++) {
+ if ((crc & 0x0001) > 0) {
+ crc = crc >> 1;
+ crc = crc ^ 0xa001;
+ } else
+ crc = crc >> 1;
+ }
+ }
+ return (crc);
+ }
+
+ /**
+ * 发送指令方法
+ *
+ */
+ public void sendOrder(String message) {/*
+ if (sendIndex < mConnectedBluetoothDevicesAddress.size()) {
+ mIgate.iGateDeviceSendData(mConnectedBluetoothDevicesAddress.get(sendIndex), message.getBytes());
+ Log.e("<size", "<size");
+ } else {
+ sendIndex = 0;
+ if (mConnectedBluetoothDevicesAddress.size() > 0) {
+ mIgate.iGateDeviceSendData(mConnectedBluetoothDevicesAddress.get(sendIndex), message.getBytes());
+ Log.e(">size", ">size");
+ }
+ }
+ sendIndex++;
+ if (sendIndex == mConnectedBluetoothDevicesAddress.size()) {
+ sendIndex = 0;
+ Log.e("=size", "=size");
+ }
+ */
+ mIgate.iGateDeviceSendData(device_address, message.getBytes());
+ }
+
+
+ /**
+ * 获得数据库最新一条血糖记录
+ *
+ */
+ public void getGlucoseByDate(String meterid) {
+ dialogHelper.startProgressDialog();
+ dialogHelper.setDialogMessage("正在获取血糖数据..");
+ InternetConfig config = new InternetConfig();
+ config.setKey(GETGLUCOSE);
+ LinkedHashMap<String, String> params = new LinkedHashMap<String, String>();
+ params.put("userId", App.getInstance().getUser().getUserid());
+ params.put("meterId", meterid);
+ String url = Constant.URL.GLUCOSE;
+
+ FastHttpHander.ajaxWebServer(url, "GetGlucoseByDate", params, config, DeviceConnectActivity.this);
+ }
+
+ /**
+ * 蓝牙提交数据
+ *
+ */
+ public void putDataByDevice(String uid, String data_str) {
+
+ InternetConfig config = new InternetConfig();
+ config.setKey(PUTDATA);
+ LinkedHashMap<String, String> params = new LinkedHashMap<String, String>();
+ params.put("u_Id", uid);
+ params.put("data", data_str);
+ String url = Constant.URL.GLUCOSE;
+
+ FastHttpHander.ajaxWebServer(url, "InsertGlucoseCopy", params, config, DeviceConnectActivity.this);
+ }
+
+ @InjectHttpOk
+ private void Ok(ResponseEntity entity) {
+ // TODO Auto-generated method stub
+
+ String jsonString = entity.getContentAsString();
+ switch (entity.getKey()) {
+
+ case GETGLUCOSE:
+
+ try {
+ JSONObject jsonObject = new JSONObject(jsonString);
+ Log.e("json_1111111", jsonString);
+ String status = jsonObject.optString("status");
+ String msg = jsonObject.optString("msg");
+ String data_str = jsonObject.optString("data");
+ if (status.equals("0")) {
+ JSONObject data_obj = new JSONObject(data_str);
+ date = data_obj.optString("MeasureTimeFormat");
+ remark = data_obj.optString("Mark");
+ values = data_obj.optString("MeasureValueOldFormat");
+
+ Log.e("date1111111", date);
+ Log.e("value1111111", values);
+ Log.e("remark1111111", remark);
+ Log.e("oldvalus1111111", data_obj.optString("MeasureValueOldFormat"));
+
+
+ D_secret = "&D" + splitDate(date) + " " + CRC16_Modbus("&D" + splitDate(date) + " ", 13);
+ sendOrder(D_secret);
+
+ } else {
+ //ThreadSendN threadSendN = new ThreadSendN();
+ //new Thread(threadSendN).start();
+ N_secret = "&N " + CRC16_Modbus("&N ", 3);
+ sendOrder(N_secret);
+ }
+ } catch (Exception e) {
+ // TODO: handle exception
+ }
+ break;
+
+ case PUTDATA:
+ if (dialogHelper != null) {
+ dialogHelper.stopProgressDialog();
+ }
+ try {
+ JSONObject jsonObject = new JSONObject(jsonString);
+ String status = jsonObject.optString("status");
+ String msg = jsonObject.optString("msg");
+ if (status.equals("0")) {
+ ToastUtil.getInterface().showToast(DeviceConnectActivity.this, "蓝牙数据下载成功," + N_acount + "条新增记录", 1);
+ String P_secret = "&P1 " + CRC16_Modbus("&P1 ", 4);
+ sendOrder(P_secret);
+ }
+ } catch (Exception e) {
+ // TODO: handle exception
+ }
+ break;
+ }
+
+ }
+
+ @InjectHttpErr
+ private void loginErr(ResponseEntity entry) {
+ // TODO Auto-generated method stub
+ if (dialogHelper != null) {
+ dialogHelper.stopProgressDialog();
+ }
+ ToastUtil.getInterface().showToast(DeviceConnectActivity.this, "网络出错", 1);
+ }
+
+ /**
+ *
+ * @author huqijie
+ * @Description 生成JSON
+ * @return String
+ * @date 2015-6-2 下午5:27:49
+ */
+ private String getJsonData(String spStr[]) {
+ JSONArray data_array = new JSONArray();
+ try {
+ for (int i = 2; i < (spStr.length - 1); i++) {
+ if (spStr[i].length() > 15) {
+ Log.e("&&&&&&&&", spStr[i]);
+ JSONObject data = new JSONObject();
+ data.put("MeasureTimeFormat", "20" + spStr[i].substring(5, 7) + "-" + spStr[i].substring(1, 3) + "-" + spStr[i].substring(3, 5) + " " + spStr[i].substring(7, 9) + ":" + spStr[i].substring(9, 11));
+ // data.put("MeasureTimeFormat","2015-06-03 23:21");
+ data.put("MeasureValueOldFormat", spStr[i].substring(spStr[i].indexOf(" ") + 1, spStr[i].indexOf(" ", spStr[i].indexOf(" ") + 1)));
+ Log.e("TTTTTTTTTTTTT", spStr[i].substring(spStr[i].indexOf(" ") + 1, spStr[i].indexOf(" ", spStr[i].indexOf(" ") + 1)));
+ // data.put("MeasureValueOldFormat","180");
+ data.put("MeasureValueFormat", "" + (Double.valueOf(spStr[i].substring(spStr[i].indexOf(" ") + 1, spStr[i].indexOf(" ", spStr[i].indexOf(" ") + 1))) / 18));
+ // data.put("MeasureValue","320");
+ data.put("PeriodType", "3");
+ data.put("Mark", spStr[i].substring(spStr[i].indexOf(" ", spStr[i].indexOf(" ") + 1), spStr[i].indexOf(" ", spStr[i].indexOf(" ") + 1) + 1));
+ data.put("MeterId", Mid.substring(2, 13));
+ data_array.put(data);
+ }
+ }
+ } catch (JSONException e) {
+ // TODO Auto-generated catch block
+ e.printStackTrace();
+ }
+
+ return data_array.toString();
+ }
+
+ //截取日期蓝牙返回格式的日期
+ public String splitDate(String date_str) {
+
+ String month, year, day, h, m, new_date;
+ year = date_str.substring(2, 4);
+ month = date_str.substring(date_str.indexOf("年") + 1, date_str.indexOf("月"));
+ day = date_str.substring(date_str.indexOf("月") + 1, date_str.indexOf("日"));
+ h = date_str.substring(date_str.indexOf(" ") + 1, date_str.indexOf(":"));
+ m = date_str.substring(date_str.indexOf(":") + 1, date_str.indexOf(":", date_str.indexOf(":") + 1));
+ if (month.length() == 1) {
+ month = "0" + month;
+ }
+ if (day.length() == 1) {
+ day = "0" + day;
+ }
+ if (h.length() == 1) {
+ h = "0" + h;
+ }
+ if (m.length() == 1) {
+ m = "0" + m;
+ }
+ new_date = month + day + year + h + m;
+ return new_date;
+ }
+
+}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值