package com.moral.yunfushao.fragment; import android.bluetooth.BluetoothGatt; import android.bluetooth.BluetoothGattCharacteristic; import android.bluetooth.BluetoothGattService; import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.os.Handler; import android.support.annotation.Nullable; import android.text.TextUtils; import android.util.Log; import android.view.View; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.TextView; import com.clj.fastble.conn.BleCharacterCallback; import com.clj.fastble.exception.BleException; import com.lzy.okgo.cache.CacheMode; import com.moral.andbrickslib.utils.FastJsonTools; import com.moral.andbrickslib.utils.NumberUtils; import com.moral.andbrickslib.utils.StringUtils; import com.moral.andbrickslib.utils.TimeUtil; import com.moral.andbrickslib.utils.log.XLog; import com.moral.yunfushao.MainActivity; import com.moral.yunfushao.MainApp; import com.moral.yunfushao.R; import com.moral.yunfushao.activity.BLESearchActivity; import com.moral.yunfushao.activity.ChartActivity; import com.moral.yunfushao.base.BaseFragment; import com.moral.yunfushao.ble.BLECommon; import com.moral.yunfushao.ble.BluetoothService; import com.moral.yunfushao.common.API; import com.moral.yunfushao.common.AppConfig; import com.moral.yunfushao.httputils.HttpCallBack; import com.moral.yunfushao.httputils.HttpUtils; import com.moral.yunfushao.model.EventMessage; import com.moral.yunfushao.model.RecData; import com.moral.yunfushao.model.UpLoadParam; import com.moral.yunfushao.ui.PanelView; import org.greenrobot.eventbus.EventBus; import org.greenrobot.eventbus.Subscribe; import org.greenrobot.eventbus.ThreadMode; import java.util.ArrayList; import java.util.Calendar; import java.util.HashMap; import java.util.Timer; import java.util.TimerTask; /** * 辐射监测 * Created by haijiang on 2017/7/4. */ public class FragmentMonitor extends BaseFragment { private LinearLayout ll_status; private TextView tv_ljjl, tv_tishi, tv_desc, tv_shishi, tv_status; private PanelView pv; private ImageView iv_his, iv_status, iv_search; private BluetoothService mBluetoothService; private ArrayList realResult = new ArrayList<>(); //上传数据 private ArrayList submitResult = new ArrayList<>(); private ArrayList submitHisResult = new ArrayList<>(); //临时存储上传数据 private ArrayList submitTempResult = new ArrayList<>(); private Timer heartTimer, resTimer; Handler handler = new Handler(); /** * 接收 * * @param msg */ @Subscribe(threadMode = ThreadMode.MAIN, sticky = true) public void eventComing(EventMessage msg) { if (msg.getType() == AppConfig.GET_BLE_SERVICE) { pv.setStatusStr("检测中"); //发现服务 mBluetoothService = ((MainActivity) getActivity()).getBluetoothService(); if (mBluetoothService != null) { BluetoothGatt gatt = mBluetoothService.getGatt(); if (gatt != null) { //获取服务 for (final BluetoothGattService service : gatt.getServices()) { if (BLECommon.USR_SERVICE.equals(service.getUuid().toString())) { mBluetoothService.setService(service); break; } } //获取特征 for (BluetoothGattCharacteristic characteristic : mBluetoothService.getService().getCharacteristics()) { int charaProp = characteristic.getProperties(); if ((charaProp & BluetoothGattCharacteristic.PROPERTY_READ) > 0) { } if ((charaProp & BluetoothGattCharacteristic.PROPERTY_WRITE) > 0 || (charaProp & BluetoothGattCharacteristic.PROPERTY_WRITE_NO_RESPONSE) > 0) { mBluetoothService.setWirteCharacteristic(characteristic); } if ((charaProp & BluetoothGattCharacteristic.PROPERTY_NOTIFY) > 0) { mBluetoothService.setCharacteristic(characteristic); } } } /** * 收消息 */ mBluetoothService.notify( mBluetoothService.getCharacteristic().getService().getUuid().toString(), mBluetoothService.getCharacteristic().getUuid().toString(), new BleCharacterCallback() { @Override public void onSuccess(final BluetoothGattCharacteristic characteristic) { getActivity().runOnUiThread(new Runnable() { @Override public void run() { Log.d("haijiang", "收到消息====" + StringUtils.byteArrayToHexStr(characteristic.getValue())); String result = StringUtils.byteArrayToHexStr(characteristic.getValue()); //实时数据 parseCurrentData(result); parseHisData(result); } }); } @Override public void onFailure(final BleException exception) { } @Override public void onInitiatedResult(boolean result) { } }); /** * 一连上先发数据包 */ heart(); /** * 发送时间校准 */ handler.postDelayed(new Runnable() { @Override public void run() { checkTime(); } }, 2000); } } else if (msg.getType() == AppConfig.GET_BLE_DISCONNECT) { pv.setStatusStr("未连接"); pv.setPercent(0); tv_ljjl.setText("0"); tv_shishi.setText("0"); } else if (msg.getType() == AppConfig.CHANGE_SETTING) { if (timer != null) { timer.cancel(); timer = null; } submitTime = MainApp.theApp.sharedPreferencesUtil.getLoginInfo().getRefresh_frequency(); isupLoad = MainApp.theApp.sharedPreferencesUtil.getLoginInfo().getIs_open_upload(); doTask(); } } @Override public void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); EventBus.getDefault().register(this); } @Override public void onAttach(Context context) { super.onAttach(context); } @Override public void onDestroy() { super.onDestroy(); EventBus.getDefault().unregister(this); if (heartTimer != null) { heartTimer.cancel(); heartTimer = null; } if (timer != null) { timer.cancel(); timer = null; } } @Override protected int getLayoutId() { return R.layout.fragment_monitor_layout; } @Override protected void initViews() { pv = findView(R.id.pv); iv_his = findView(R.id.iv_his); tv_ljjl = findView(R.id.tv_ljjl); tv_tishi = findView(R.id.tv_tishi); tv_desc = findView(R.id.tv_desc); tv_shishi = findView(R.id.tv_shishi); tv_status = findView(R.id.tv_status); iv_status = findView(R.id.iv_status); ll_status = findView(R.id.ll_status); iv_search = findView(R.id.iv_search); } @Override protected void initListener() { pv.setOnClickListener(this); iv_his.setOnClickListener(this); // iv_search.setOnClickListener(this); } int submitTime; int isupLoad; @Override protected void initData() { submitTime = MainApp.theApp.sharedPreferencesUtil.getLoginInfo().getRefresh_frequency(); isupLoad = MainApp.theApp.sharedPreferencesUtil.getLoginInfo().getIs_open_upload(); doTask(); } @Override protected void processClick(View v) { Intent intent = null; switch (v.getId()) { case R.id.pv: if (MainApp.theApp.bleManager == null || !(MainApp.theApp.bleManager != null && MainApp.theApp.bleManager.isSupportBle())) { return; } intent = new Intent(getActivity(), BLESearchActivity.class); startActivity(intent); break; case R.id.iv_his: intent = new Intent(getActivity(), ChartActivity.class); startActivity(intent); break; case R.id.iv_search: // if(mBluetoothService==null){ // return; // } // if(mBluetoothService.getWirteCharacteristic()==null){ // return; // } // mBluetoothService.write(mBluetoothService.getWirteCharacteristic().getService().getUuid().toString(),mBluetoothService.getWirteCharacteristic().getUuid().toString(),BLECommon.BLE_SEARCH,null); break; } } @Override protected void onErrorPagerClick() { } Timer timer; private void doTask() { timer = new Timer(); timer.schedule(new TimerTask() { @Override public void run() { if (isupLoad == 1) { //上传数据 submitData(); } } }, 0, submitTime * 1000); } /** * 发送心跳包,每3分钟 */ private void heart() { heartTimer = new Timer(); heartTimer.schedule(new TimerTask() { @Override public void run() { //发送心跳 if (mBluetoothService == null) { return; } if (mBluetoothService.getWirteCharacteristic() == null) { return; } mBluetoothService.write(mBluetoothService.getWirteCharacteristic().getService().getUuid().toString(), mBluetoothService.getWirteCharacteristic().getUuid().toString(), BLECommon.BLE_HEART, null); } }, 0, 1000 * 60 * 3); } private long timeComplete = 0; private void checkResComplete(final String result) { resTimer = new Timer(); resTimer.schedule(new TimerTask() { @Override public void run() { if (!TextUtils.isEmpty(result) && result.startsWith("3A")) { timeComplete = 0; } else { timeComplete++; } if (timeComplete >= 120) { submitResData(); } } }, 0, 1000); } private void submitData() { //上传当前数据并清空 submitTempResult.addAll(submitResult); submitResult.clear(); HashMap params = new HashMap<>(); if (submitTempResult.size() == 0) { return; } UpLoadParam up = new UpLoadParam(); up.setUserid(MainApp.userId); up.setAddress(MainApp.address); up.setLat(MainApp.mLat); up.setLon(MainApp.mLon); up.setData(submitTempResult); params.put("data", FastJsonTools.toJson(up)); HttpUtils.doPost(API.UPLOAD, params, CacheMode.DEFAULT, false, new HttpCallBack() { @Override public void onSuccess(String res, String msg) { XLog.d("@@@@@@@@@@@@@@@@@@@@@@@@@@" + msg); submitTempResult.clear(); } @Override public void showLoadingDialog() { } @Override public void onFail(int errno, String s) { } }); } private void submitResData() { //上传当前数据并清空 HashMap params = new HashMap<>(); if (submitHisResult.size() == 0) { return; } UpLoadParam up = new UpLoadParam(); up.setUserid(MainApp.userId); up.setAddress(MainApp.address); up.setLat(MainApp.mLat); up.setLon(MainApp.mLon); up.setData(submitHisResult); params.put("data", FastJsonTools.toJson(up)); HttpUtils.doPost(API.UPLOAD, params, CacheMode.DEFAULT, false, new HttpCallBack() { @Override public void onSuccess(String res, String msg) { XLog.d("孕妇哨上传数据:" + msg); submitHisResult.clear(); if (resTimer != null) { resTimer.cancel(); resTimer = null; } } @Override public void showLoadingDialog() { } @Override public void onFail(int errno, String s) { } }); } /** * 头部实时数据状态显示 * * @param safe */ private void showStatus(boolean safe) { if (safe) { iv_status.setImageResource(R.mipmap.icon_safe); tv_status.setText("安全"); tv_status.setTextColor(getResources().getColor(R.color.green_txt)); ll_status.setBackgroundResource(R.mipmap.bg_conner_green); } else { iv_status.setImageResource(R.mipmap.icon_danger); tv_status.setText("危险"); tv_status.setTextColor(getResources().getColor(R.color.red_txt)); ll_status.setBackgroundResource(R.mipmap.bg_conner_red); } } /** * 解析实时数据 * * @param result */ private void parseCurrentData(String result) { if (result.startsWith("5A")) { realResult.clear(); realResult.add(result); } else { realResult.add(result); } String nowResult = ""; for (String s : realResult) { nowResult += s; } Log.d("haijiang", "收到消息===nowResult=" + nowResult); /** * 20个字节,5A开头 5B结尾 */ if (!TextUtils.isEmpty(nowResult) && nowResult.length() == 40 && nowResult.startsWith("5A") && nowResult.endsWith("5B")) { int shunshiValue = Integer.parseInt(nowResult.substring(24, 26), 16) * 256 + Integer.parseInt(nowResult.substring(26, 28), 16); int leijiValue = Integer.parseInt(nowResult.substring(28, 30), 16) * 1024 + Integer.parseInt(nowResult.substring(30, 32), 16) * 512 + Integer.parseInt(nowResult.substring(32, 34), 16) * 256 + Integer.parseInt(nowResult.substring(34, 36), 16); float level = (float) (shunshiValue / 10 * 0.01); XLog.d("辐射:" + shunshiValue + "|累计:" + leijiValue); tv_ljjl.setText(NumberUtils.getBigDecimalValue(leijiValue * 0.01, 3) + ""); double shishiValue = NumberUtils.getBigDecimalValue((shunshiValue) / 100.0, 3); tv_shishi.setText(shishiValue + ""); /** * 保存数据至内存 */ RecData data = new RecData(); data.setValue(shishiValue); data.setTime(TimeUtil.getCurrentDate("yyyy-MM-dd HH:mm:ss")); submitResult.add(data); if (level >= 0 && level < 15) { pv.setPercent(level / 50); tv_tishi.setText("当前辐射安全"); tv_desc.setText("您所处位置辐射安全\n处于安全区域,可以长时间逗留!"); showStatus(true); } else if (level >= 15 && level < 26) { pv.setPercent(level / 50); tv_tishi.setText("当前辐射轻微"); tv_desc.setText("您所处位置辐射轻微\n不利于您的健康,请远离到安全区域!"); showStatus(true); } else if (level >= 26 && level < 65) { showStatus(false); tv_tishi.setText("当前辐射偏高"); tv_desc.setText("您所处位置辐射偏高\n不利于您的健康,请远离到安全区域!"); if (level <= 45) { pv.setPercent(level / 50); } else { pv.setPercent(0.9f); } } else if (level >= 65) { showStatus(false); tv_tishi.setText("当前辐射超标"); tv_desc.setText("您所处位置辐射超标\n不利于您的健康,请远离到安全区域!"); pv.setPercent(1.0f); } realResult.clear(); } } /** * 孕妇哨连接后上传的数据 */ private void parseHisData(String result) { if (!TextUtils.isEmpty(result) && result.length() == 16 && result.startsWith("3A") && result.endsWith("3B")) { if (submitHisResult.size() == 0) { //开启定时器检查 checkResComplete(result); } String year = "20" + Integer.parseInt(result.substring(2, 4), 16); String month = Integer.parseInt(result.substring(4, 6), 16) + ""; String day = Integer.parseInt(result.substring(6, 8), 16) + ""; String hour = Integer.parseInt(result.substring(8, 10), 16) + ""; int resValue = Integer.parseInt(result.substring(10, 12), 16) * 256 + Integer.parseInt(result.substring(12, 14), 16); RecData data = new RecData(); StringBuilder time = new StringBuilder(); //yyyy-MM-dd HH:mm:ss time.append(year).append("-").append(month).append("-").append(day).append(" ").append(hour).append(":00:00"); Log.d("haijiang", "=====time=====" + time.toString()); data.setTime(time.toString()); data.setValue(NumberUtils.getBigDecimalValue((resValue) / 100.0, 3)); submitHisResult.add(data); } } /** * 时间校准 */ private void checkTime() { if (mBluetoothService == null) { return; } if (mBluetoothService.getWirteCharacteristic() == null) { return; } StringBuilder blesb = new StringBuilder(); blesb.append("4A"); Calendar now = Calendar.getInstance(); blesb.append(toHex(Integer.toHexString((now.get(Calendar.YEAR) - 2000)))); blesb.append(toHex(Integer.toHexString((now.get(Calendar.MONTH) + 1)))); blesb.append(toHex(Integer.toHexString((now.get(Calendar.DAY_OF_MONTH))))); blesb.append(toHex(Integer.toHexString((now.get(Calendar.HOUR_OF_DAY))))); blesb.append(toHex(Integer.toHexString((now.get(Calendar.MINUTE))))); blesb.append("4B"); mBluetoothService.write(mBluetoothService.getWirteCharacteristic().getService().getUuid().toString(), mBluetoothService.getWirteCharacteristic().getUuid().toString(), blesb.toString(), null); } private String toHex(String s) { if (s.length() == 1) { return "0" + s; } else { return s; } } }