From e2c7c647d3d950d863a0eaa54765e087c6cf85a1 Mon Sep 17 00:00:00 2001 From: jia Date: Sun, 8 Sep 2024 21:50:14 +0800 Subject: [PATCH] =?UTF-8?q?=E8=93=9D=E7=89=99=E5=8A=9F=E8=83=BD=E6=B7=BB?= =?UTF-8?q?=E5=8A=A0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- iFish7/build.gradle | 1 + iFish7/src/main/AndroidManifest.xml | 6 + .../ifish/activity/BlueTooth2Activity.java | 2 + .../com/ifish/activity/BluetoothActivity.java | 353 ++++- .../activity/DeviceCameraListActivity.java | 2 + .../HotSpotConnentDeviceActivity.java | 6 + .../com/ifish/activity/LoadingActivity.java | 27 +- .../MainSix_4F_BlueControlActivity.java | 1299 +++++++++++++++++ .../com/ifish/activity/MainTabActivity.java | 2 + .../activity/newbind/BottomChoiceDialog.java | 19 +- .../ifish/activity/newbind/ConnectType.java | 3 +- .../newbind/NewBindDeviceActivity.java | 980 ++++++++++++- .../java/com/ifish/basebean/EventBean.java | 11 + .../com/ifish/baseclass/BaseApplication.java | 17 +- .../com/ifish/fragment/DeviceFragment.java | 287 +++- .../main/java/com/ifish/utils/AppUtil.java | 65 + .../main/java/com/ifish/utils/BLEManger.java | 520 +++++++ .../java/com/ifish/utils/BlueToothUtil.kt | 23 +- .../main/res/layout/activity_bluetooth.xml | 50 +- .../dialog_choose_connect_wifi_type.xml | 22 + 20 files changed, 3587 insertions(+), 108 deletions(-) create mode 100644 iFish7/src/main/java/com/ifish/activity/MainSix_4F_BlueControlActivity.java create mode 100644 iFish7/src/main/java/com/ifish/basebean/EventBean.java create mode 100644 iFish7/src/main/java/com/ifish/utils/BLEManger.java diff --git a/iFish7/build.gradle b/iFish7/build.gradle index c1e70262b..bb3afb8aa 100644 --- a/iFish7/build.gradle +++ b/iFish7/build.gradle @@ -169,6 +169,7 @@ dependencies { implementation 'com.tencent:mmkv:1.3.3' implementation("com.github.bumptech.glide:okhttp3-integration:4.11.0" ) + implementation 'com.github.Jasonchenlijian:FastBle:2.4.0' // // annotationProcessor 'com.github.bumptech.glide:compiler:3.7.0' diff --git a/iFish7/src/main/AndroidManifest.xml b/iFish7/src/main/AndroidManifest.xml index 2435574dd..95f47394e 100644 --- a/iFish7/src/main/AndroidManifest.xml +++ b/iFish7/src/main/AndroidManifest.xml @@ -21,6 +21,8 @@ + + @@ -791,6 +793,10 @@ android:name=".MainSix_4F_ControlActivity" android:launchMode="singleTop" android:theme="@style/Transparent" /> + ss = BleManager.getInstance().getAllConnectedDevice(); + if (ss!=null){ + ToastUtil.show(this,ss.size()+""); + for (BleDevice xx:ss){ + if (xx!=null && xx.getDevice()!=null && xx.getDevice().getName()!=null && xx.getDevice().getName().startsWith("ifish")){ + currentDevice = xx; + tvname.setText(xx.getDevice().getName()+"已连接"); + } + L.i("jjia-----conn----"+xx.getDevice().getName()); + } + } + a1.setOnClickListener(view -> { + tvname.setText(String.format("%s", BleManager.getInstance().isSupportBle())); + }); + + a2.setOnClickListener(view -> { + tvname.setText(String.format("%s", BleManager.getInstance().isBlueEnable())); + }); + + scan.setOnClickListener(view -> { + BleManager.getInstance().scan(new BleScanCallback() { + @Override + public void onScanFinished(List scanResultList) { + ToastUtil.show(BluetoothActivity.this,"扫描结束"); + } + + @Override + public void onScanStarted(boolean success) { + ToastUtil.show(BluetoothActivity.this,"开始扫描"); + } + + @Override + public void onScanning(BleDevice bleDevice) { + + if (bleDevice!=null && bleDevice.getDevice()!=null){ + BluetoothDevice bean = bleDevice.getDevice(); + if (!TextUtils.isEmpty(bean.getName()) && bean.getName().startsWith("ifish")){ + currentDevice = bleDevice; + tvname.setText(bean.getName()+bean.getAddress()); + BleManager.getInstance().cancelScan(); + } + L.i(bean.getName()+"jjia---------"+bean.getAddress()); + } + } + }); + }); + conn.setOnClickListener(view -> { + BleManager.getInstance().connect(currentDevice.getDevice().getAddress(), new BleGattCallback() { + @Override + public void onStartConnect() { + ToastUtil.show(BluetoothActivity.this,"开始连接"); + + } + + @Override + public void onConnectFail(BleDevice bleDevice, BleException exception) { + ToastUtil.show(BluetoothActivity.this,"连接失败"); + tvname.setText("连接失败"); + } + + @Override + public void onConnectSuccess(BleDevice bleDevice, BluetoothGatt gatt, int status) { + ToastUtil.show(BluetoothActivity.this,"连接成功"+bleDevice.getRssi()); + + tvname.setText("连接成功"+bleDevice.getRssi()); + BleManager.getInstance().setMtu(bleDevice, 512, new BleMtuChangedCallback() { + @Override + public void onSetMTUFailure(BleException exception) { + L.i("jjia-------MTU--"+exception.toString()); + } + + @Override + public void onMtuChanged(int mtu) { + L.i("jjia-------MTU--"+mtu); + } + }); + } + + @Override + public void onDisConnected(boolean isActiveDisConnected, BleDevice device, BluetoothGatt gatt, int status) { + ToastUtil.show(BluetoothActivity.this,"连接断开了"); + tvname.setText("连接断开了"); + } + }); + }); + tv_pair.setOnClickListener(view -> { + + doPostBindDevice(); + }); + + nofi.setOnClickListener(view -> { + BleManager.getInstance().notify(currentDevice, SERVICE_UUID, WRITE_UUID, new BleNotifyCallback() { + @Override + public void onNotifySuccess() { + ToastUtil.show(BluetoothActivity.this,"打开通知成功"); + tvname.setText("打开通知成功"); + } + + @Override + public void onNotifyFailure(BleException exception) { + ToastUtil.show(BluetoothActivity.this,"打开通知失败"); + tvname.setText("打开通知失败"); + } + + @Override + public void onCharacteristicChanged(byte[] data) { + if (data!=null && data.length>0){ + String ssx = ByteUtil.bytesToHexString(data); + tvname2.setText(ssx); + int check_code = data[1]; + int length = data[14]; + byte[] dataByte = new byte[length]; + for (int i = 0; i < dataByte.length; i++) { + dataByte[i] = data[i]; + } + + String device_mac = null; + Object object = ModelCodec.deCode(dataByte); + if (object!=null && object instanceof BackFunctionCode7_11){ + BackFunctionCode7_11 model = (BackFunctionCode7_11) object; + device_mac = ByteUtil.bytesToHexString(model.getSrc()); + tvname2.setText(device_mac); + }else { +// + } + L.i("jjia-------check_code-"+check_code); + L.i("jjia-------length-"+length); + L.i("jjia-------device_mac-"+device_mac); +// L.i("jjia-------通知--"+ss1); +// L.i("jjia-------通知--"+ss2); +// L.i("jjia-------通知--"+ss3); +// L.i("jjia-------通知--"+ss); + + } + } + }); + }); + + + write.setOnClickListener(view -> { + + String ssid = "CMDD"; + String pwd = "juanandyo"; + + OrderDeviceConnectModel model = OrderModel.OrderDeviceConnectModel(ssid, pwd);//设置正式环境域名 + byte[] data = ModelCodec.enCode(model);// + +// String s = new String(data); +// L.i("jjia-----------111-"+s); +// byte [] xx = HexUtil.hexStringToBytes(s); +// +// L.i("jjia-----------数据大小-"+data.length); +// L.i("jjia-----------222-"+xx.length); +// L.i("jjia-----------222-"+xx); +// try { +// L.i("jjia-----------222-"+new String(xx,"UTF-8")); +// } catch (UnsupportedEncodingException e) { +// throw new RuntimeException(e); +// } + BleManager.getInstance().write(currentDevice, SERVICE_UUID, WRITE_UUID, data,false, new BleWriteCallback() { + @Override + public void onWriteSuccess(int current, int total, byte[] justWrite) { + + try { + String aa = new String(justWrite,"UTF-8"); + String ssx = ByteUtil.bytesToHexString(justWrite); + L.i(current+"x"+total+"jjia--------------写成功-"+aa +"$"+ssx); + tvname.setText(current+"x"+total+"写成功-"+aa); + } catch (UnsupportedEncodingException e) { throw new RuntimeException(e); } -// BlueToothUtil.Companion.boundDevice(bluetoothDevice,MY_BLUETOOTH_UUID); + } - } + + @Override + public void onWriteFailure(BleException exception) { + tvname.setText("写失败-"+exception.toString()); + } + }); }); } + private void bleNotify(){ - BluetoothDevice bluetoothDevice = null; - BroadcastReceiver broadcastReceiver = new BroadcastReceiver() { - @SuppressLint("MissingPermission") - @Override - public void onReceive(Context context, Intent intent) { - if (BluetoothDevice.ACTION_FOUND .equals(intent.getAction())){ - BluetoothDevice device = null; + } - if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU){ - device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE,BluetoothDevice.class); - }else { - device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE); - } - if (device!=null && device.getBondState() ==10){ - String deviceName= device.getName(); - if (!TextUtils.isEmpty(deviceName) && - ( -// deviceName.contains("ifishly") || - deviceName.startsWith("ifishly") -// deviceName.contains("LE-Bose") + Device deviceObj; - ) - ){ - bluetoothDevice = device; - name.setText(deviceName); + private void doPostBindDevice() { + try { - ParcelUuid[] sss = device.getUuids(); - if (sss!=null && sss.length>0){ - for (ParcelUuid x:sss){ - if (x!=null){ - L.i(device.getName()+"蓝牙设备名称--Uuid--"+x.getUuid()); - } - } + HttpManager hm = HttpManager.getInstance(); + hm.bindDevice(new HttpListener>() { + private int result; - }else { - L.i("蓝牙设备名称--null0-"); - } - L.i("蓝牙设备名称-1-"+device.toString()); + @Override + public void success(BaseBean baseBean) { + result = baseBean.result; + if (result == Commons.NetWork.Success) { +// deviceObj = baseBean.data; +// deviceObj.setMacAddress(currentDevice.getMac()); +// /** +// //当服务器返回的设备控制器数和定时器数为null的时候 不跳转进入主界面 +// */ +// if (deviceObj.getControlAmount() == null || deviceObj.getTimerAmount() == null) { +// L.i("第一次获取空"); +// +// } } - L.i("蓝牙设备名称--"+device.getName()); } - }else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(intent.getAction())){ - ToastUtil.show(BluetoothActivity.this,"蓝牙搜索结束"); - } + + @Override + public void finish() { + } + + @Override + public void error(Exception e, String msg) { + result = Commons.NetWork.ERROR; + } + }, Commons.USER.getUserId(), "e4b06318fd98"); + } catch (Exception e) { + e.printStackTrace(); } - }; + } + } \ No newline at end of file diff --git a/iFish7/src/main/java/com/ifish/activity/DeviceCameraListActivity.java b/iFish7/src/main/java/com/ifish/activity/DeviceCameraListActivity.java index 5c1b22315..7c53cb7ab 100644 --- a/iFish7/src/main/java/com/ifish/activity/DeviceCameraListActivity.java +++ b/iFish7/src/main/java/com/ifish/activity/DeviceCameraListActivity.java @@ -25,6 +25,7 @@ import android.widget.AdapterView.OnItemClickListener; import android.widget.RelativeLayout; import android.widget.TextView; +import com.clj.fastble.BleManager; import com.ifish.adapter.GridViewCameraBaseAdapter; import com.ifish.adapter.GridViewDeviceBaseAdapter; import com.ifish.basebean.BaseBean; @@ -369,6 +370,7 @@ public class DeviceCameraListActivity extends BaseActivity { @Override public void success(BaseBean baseBean) { result = baseBean.result; + BleManager.getInstance().disconnectAllDevice(); } @Override diff --git a/iFish7/src/main/java/com/ifish/activity/HotSpotConnentDeviceActivity.java b/iFish7/src/main/java/com/ifish/activity/HotSpotConnentDeviceActivity.java index 8b37d4ae6..203a89b4e 100644 --- a/iFish7/src/main/java/com/ifish/activity/HotSpotConnentDeviceActivity.java +++ b/iFish7/src/main/java/com/ifish/activity/HotSpotConnentDeviceActivity.java @@ -150,7 +150,10 @@ public class HotSpotConnentDeviceActivity extends BaseActivity { Log.i("sssr", "222"); bys = dp.getData(); int check_code = bys[1]; + L.i("jjia---------bys--"+new String(bys)); + L.i("jjia---------check_code--"+check_code); int length = bys[14]; + L.i("jjia---------length--"+length); byte[] dataByte = new byte[length]; for (int i = 0; i < dataByte.length; i++) { dataByte[i] = bys[i]; @@ -317,6 +320,9 @@ public class HotSpotConnentDeviceActivity extends BaseActivity { * @return */ public boolean packageData(byte[] bytes, int check_code, String ip) { + L.i("jjia----data"+new String(bytes)); + L.i("jjia----check_code"+check_code); + L.i("jjia----ip"+ip); Object object = ModelCodec.deCode(bytes); if (object == null) { return false; diff --git a/iFish7/src/main/java/com/ifish/activity/LoadingActivity.java b/iFish7/src/main/java/com/ifish/activity/LoadingActivity.java index e0998404f..4005c4a99 100644 --- a/iFish7/src/main/java/com/ifish/activity/LoadingActivity.java +++ b/iFish7/src/main/java/com/ifish/activity/LoadingActivity.java @@ -46,6 +46,7 @@ import com.ifish.geewe.DeviceCamera; import com.ifish.permission.PermissionHelper; import com.ifish.utils.ActivityManager; import com.ifish.utils.AnimationUtil; +import com.ifish.utils.AppUtil; import com.ifish.utils.Commons; import com.ifish.utils.Commons.LoginSPKey; import com.ifish.utils.Commons.NetWork; @@ -112,11 +113,19 @@ public class LoadingActivity extends BaseActivityNotAnim { private static String firstShowPrivacy = "firstShowPrivacy"; String[] permission; - String[] permissionM = new String[]{android.Manifest.permission.CAMERA, android.Manifest.permission.ACCESS_FINE_LOCATION, android.Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE, android.Manifest.permission.READ_PHONE_STATE}; - - String[] permission13 = new String[]{android.Manifest.permission.CAMERA, android.Manifest.permission.ACCESS_FINE_LOCATION, android.Manifest.permission.READ_PHONE_STATE, - android.Manifest.permission.READ_MEDIA_IMAGES, - android.Manifest.permission.READ_MEDIA_VIDEO}; +// String[] permissionM = new String[]{ +// android.Manifest.permission.CAMERA, +// android.Manifest.permission.ACCESS_FINE_LOCATION, +// android.Manifest.permission.READ_EXTERNAL_STORAGE, +// Manifest.permission.WRITE_EXTERNAL_STORAGE, +// android.Manifest.permission.READ_PHONE_STATE}; +// +// String[] permission13 = new String[]{ +// android.Manifest.permission.CAMERA, +// android.Manifest.permission.ACCESS_FINE_LOCATION, +// android.Manifest.permission.READ_PHONE_STATE, +// android.Manifest.permission.READ_MEDIA_IMAGES, +// android.Manifest.permission.READ_MEDIA_VIDEO}; @Override @@ -129,13 +138,7 @@ public class LoadingActivity extends BaseActivityNotAnim { if (savedInstanceState != null) { setIntent(new Intent()); // 从堆栈恢复,不再重复解析之前的intent } - - if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) { - permission = permission13; - } else { - permission = permissionM; - } - + permission = AppUtil.getPermissionList(); permissionHelper = new PermissionHelper(LoadingActivity.this, permission, 250); Boolean showPrivacy = SPUtil.getInstance(getApplicationContext()).getBoolean(firstShowPrivacy, false); diff --git a/iFish7/src/main/java/com/ifish/activity/MainSix_4F_BlueControlActivity.java b/iFish7/src/main/java/com/ifish/activity/MainSix_4F_BlueControlActivity.java new file mode 100644 index 000000000..ce7f220b0 --- /dev/null +++ b/iFish7/src/main/java/com/ifish/activity/MainSix_4F_BlueControlActivity.java @@ -0,0 +1,1299 @@ +package com.ifish.activity; + +import static com.ifish.activity.MainTabActivity.map; + +import android.app.AlertDialog; +import android.app.Dialog; +import android.bluetooth.BluetoothDevice; +import android.content.DialogInterface; +import android.content.Intent; +import android.os.Bundle; +import android.os.CountDownTimer; +import android.os.Handler; +import android.text.TextUtils; +import android.view.View; +import android.view.Window; +import android.widget.Button; +import android.widget.ImageView; +import android.widget.LinearLayout; +import android.widget.TextView; + +import com.bumptech.glide.Glide; +import com.google.gson.Gson; +import com.google.gson.reflect.TypeToken; +import com.ifish.basebean.BaseBean; +import com.ifish.basebean.DeleteDevice; +import com.ifish.basebean.Device; +import com.ifish.basebean.ErrorReceiveObj; +import com.ifish.basebean.ErrorReceiveToast; +import com.ifish.basebean.ErrorSendObj; +import com.ifish.basebean.ErrorSendTimeSetting; +import com.ifish.basebean.ErrorSendToast; +import com.ifish.basebean.JpushDeleteDeviceMac; +import com.ifish.basebean.NetworkChangBean; +import com.ifish.basebean.RenameDevice; +import com.ifish.basebean.SetDevice; +import com.ifish.basebean.ShareDevice; +import com.ifish.basebean.UnBindDevice; +import com.ifish.baseclass.BaseGradeActivity; +import com.ifish.tcp.BackInfoModelSeven_2F_TimeSet; +import com.ifish.tcp.BackInfoModelSix_4F; +import com.ifish.tcp.BackInfoModelSix_4F_FeedFish; +import com.ifish.tcp.FishFeedType; +import com.ifish.tcp.TcpReceiveThread; +import com.ifish.tcp.TcpSendThread; +import com.ifish.utils.AnimationUtil; +import com.ifish.utils.BLEManger; +import com.ifish.utils.Commons; +import com.ifish.utils.HttpListener; +import com.ifish.utils.HttpManager; +import com.ifish.utils.L; +import com.ifish.utils.SPUtil; +import com.ifish.utils.ToastUtil; +import com.ifish.view.IosAlertDialog; +import com.ifish.view.PopWindowDevice_EventBus; +import com.ifish.view.SelectorImageView; +import com.ifish.view.SwipeRefreshLayout; +import com.ifish.wheelview.adapter.ArrayWheelAdapter; +import com.ifish.wheelview.view.WheelView; +import com.squareup.picasso.Picasso; + +import java.net.Socket; +import java.util.ArrayList; +import java.util.List; + +import de.greenrobot.event.EventBus; + +/** + * @author:zau18 + * @date: 2022/5/17 10:02 下午 新增加的 + * @description: 绚多6控 4f,5f 设备界面 + */ +public class MainSix_4F_BlueControlActivity extends BaseGradeActivity implements SwipeRefreshLayout.OnRefreshListener { + private SPUtil sp; + private ImageView title_img_right; + private SwipeRefreshLayout sw; + private SelectorImageView iv_control_1, iv_control_2, iv_control_3, iv_control_4, iv_control_5, iv_control_6, iv_control_7, iv_control_8; + private TextView tv_control_1, tv_control_2, tv_control_3, tv_control_4, tv_control_5, tv_control_6, tv_control_7, tv_control_8; + private TextView tv_iconName_1, tv_iconName_2, tv_iconName_3, tv_iconName_4, tv_iconName_5, tv_iconName_6, tv_iconName_7, tv_iconName_8; + private static final String hot_text = "- 加热 -"; + private static final String cold_text = "- 室内温度 -"; + private static final String wendu_text = "℃"; + private boolean isToast = true; + private boolean rl_setting_clickble = true; + private boolean isFirstAPP = false; + private boolean DeviceOnLine = false; + private String mac = ""; + private TextView tv_wendu, tv_typename, tv_dianliang; + private LinearLayout ll_dianliang, ll_wendu; + private CountDownTimer RefreshTimer; + private CountDownTimer WifiChangeTimer; + private CountDownTimer TcpTimer; + private HttpManager hm = HttpManager.getInstance(); + private Boolean isWaterDialog = false; + private BackInfoModelSix_4F backInfoModelSix_4F; + private Dialog waterTempDialog; + private int position = 0; + private TextView tv_humidity; + private TextView tv_setfish; + private TextView tv_setdian; + private boolean isClick_FeedFish = false; + private TextView tv_heatWendu; + + @Override + protected void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + setContentView(R.layout.main_six_4f_control_activity); + initView(); + initListener(); + init(); + LoginDevice(); + try { + initTitle(Commons.DEVICE.get(Commons.DevicePosition).getShowName()); + } catch (Exception e) { + e.printStackTrace(); + } + ImageView iv_logo = (ImageView) findViewById(R.id.iv_logo); + TextView tv_logo = (TextView) findViewById(R.id.tv_logo); + try { + tv_logo.setText(Commons.DEVICE.get(sp.getInt(Commons.LoginSPKey.Position, 0)).getVenderList().getBrandName()); + Picasso.with(MainSix_4F_BlueControlActivity.this).load(HttpManager.Store_URL + Commons.DEVICE.get(sp.getInt(Commons.LoginSPKey.Position, 0)).getVenderList().getLogo()).error(R.drawable.ifish_logo_default).into(iv_logo); + } catch (Exception e) { + e.printStackTrace(); + } + + } + + @Override + protected void onResume() { + super.onResume(); + try { + setTitle(Commons.DEVICE.get(Commons.DevicePosition).getShowName()); + } catch (Exception e1) { + Commons.DevicePosition = 0; + sp.putInt(Commons.LoginSPKey.Position, 0); + try { + setTitle(Commons.DEVICE.get(Commons.DevicePosition).getShowName()); + } catch (Exception e) { + e.printStackTrace(); + } + } + Commons.IS_EventBus = true; + if (isFirstAPP) { + if (DeviceOnLine) { + checkDevice(); + } else { + //设备已离线,登录设备 + LoginDevice(); + } + } + isFirstAPP = true; + getLocalIconName(); + } + + @Override + protected void onDestroy() { + isToast = false; + EventBus.getDefault().unregister(this); + closeSoket(); + stopAllTimer(); + super.onDestroy(); + } + + public void closeSoket() {//关闭soket + if (MainTabActivity.socket != null) { + try { + MainTabActivity.socket.close(); + } catch (Exception e) { + } + } + MainTabActivity.socket = null; + } + + private void stopAllTimer() { + StopWifiChangeTimer(); + stopRefreshTimer(); + stopTimer(); + } + + //发送查询设备温度 定时器的指令 + private void checkDevice() { + new Thread() { + @Override + public void run() { + super.run(); + map.put(Commons.FishKey.Key, Commons.FishKey.Query);//查询 + map.put(Commons.FishKey.Mac, mac); + TcpSendThread ts3 = new TcpSendThread(MainTabActivity.socket, map); + Thread thread3 = new Thread(ts3); + thread3.start(); + } + }.start(); + } + + /** + * 获取本地图标名字 + */ + public void getLocalIconName() { + String locatText = sp.getString(mac + Commons.LoginSPKey.ICONNAME); + //本地集合json字符串不为空才能进行转化 + if (!TextUtils.isEmpty(locatText)) { + List locatTextList = new ArrayList<>(); + try { + locatTextList = new Gson().fromJson(locatText, new TypeToken>() { + }.getType()); + if (locatTextList != null && locatTextList.size() == 8) { + if (!TextUtils.isEmpty(locatTextList.get(0))) { + tv_iconName_1.setText(locatTextList.get(0)); + } + if (!TextUtils.isEmpty(locatTextList.get(1))) { + tv_iconName_2.setText(locatTextList.get(1)); + } + if (!TextUtils.isEmpty(locatTextList.get(2))) { + tv_iconName_3.setText(locatTextList.get(2)); + } + if (!TextUtils.isEmpty(locatTextList.get(3))) { + tv_iconName_4.setText(locatTextList.get(3)); + } + if (!TextUtils.isEmpty(locatTextList.get(4))) { + tv_iconName_5.setText(locatTextList.get(4)); + } + if (!TextUtils.isEmpty(locatTextList.get(5))) { + tv_iconName_6.setText(locatTextList.get(5)); + } + if (!TextUtils.isEmpty(locatTextList.get(6))) { + tv_iconName_7.setText(locatTextList.get(6)); + } + if (!TextUtils.isEmpty(locatTextList.get(7))) { + tv_iconName_8.setText(locatTextList.get(7)); + } + } + } catch (Exception e) { + } + } + } + + private void initView() { + tv_setfish = findViewById(R.id.tv_setfish); + tv_setdian = findViewById(R.id.tv_setdian); + ImageView iv_bg1 = (ImageView) findViewById(R.id.iv_bg1); + ImageView iv_bg2 = (ImageView) findViewById(R.id.iv_bg2); + String type = Commons.DEVICE.get(Commons.DevicePosition).type; + if(Device.TYPE_5F.equals(type)){ //海水 + Glide.with(this).load(R.drawable.seven5f_bg1).into(iv_bg1); + Glide.with(this).load(R.drawable.seven5f_bg2).into(iv_bg2); + }else{ //淡水 + Glide.with(this).load(R.drawable.sevenbg1).into(iv_bg1); + Glide.with(this).load(R.drawable.sevenbg2).into(iv_bg2); + } + title_img_right = findMyViewById(R.id.title_img_right); + sw = findMyViewById(R.id.sw); + tv_offline = (TextView) findViewById(R.id.tv_offline); + tv_humidity = findMyViewById(R.id.tv_humidity); + iv_control_1 = findMyViewById(R.id.iv_control_1); + iv_control_2 = findMyViewById(R.id.iv_control_2); + iv_control_3 = findMyViewById(R.id.iv_control_3); + iv_control_4 = findMyViewById(R.id.iv_control_4); + iv_control_5 = findMyViewById(R.id.iv_control_5); + iv_control_6 = findMyViewById(R.id.iv_control_6); + iv_control_7 = findMyViewById(R.id.iv_control_7); + iv_control_8 = findMyViewById(R.id.iv_control_8); + tv_heatWendu = findViewById(R.id.tv_heatWendu); + tv_control_1 = findMyViewById(R.id.tv_control_1); + tv_control_2 = findMyViewById(R.id.tv_control_2); + tv_control_3 = findMyViewById(R.id.tv_control_3); + tv_control_4 = findMyViewById(R.id.tv_control_4); + tv_control_5 = findMyViewById(R.id.tv_control_5); + tv_control_6 = findMyViewById(R.id.tv_control_6); + tv_control_7 = findMyViewById(R.id.tv_control_7); + tv_control_8 = findMyViewById(R.id.tv_control_8); + tv_iconName_1 = findMyViewById(R.id.tv_iconName_1); + tv_iconName_2 = findMyViewById(R.id.tv_iconName_2); + tv_iconName_3 = findMyViewById(R.id.tv_iconName_3); + tv_iconName_4 = findMyViewById(R.id.tv_iconName_4); + tv_iconName_5 = findMyViewById(R.id.tv_iconName_5); + tv_iconName_6 = findMyViewById(R.id.tv_iconName_6); + tv_iconName_7 = findMyViewById(R.id.tv_iconName_7); + tv_iconName_8 = findMyViewById(R.id.tv_iconName_8); + tv_wendu = findMyViewById(R.id.tv_wendu); + tv_typename = findMyViewById(R.id.tv_typename); + tv_dianliang = findMyViewById(R.id.tv_dianliang); + ll_dianliang = findMyViewById(R.id.ll_dianliang); + ll_wendu = findMyViewById(R.id.ll_wendu); + ImageView iv_gif = findMyViewById(R.id.iv_gif); + Glide.with(MainSix_4F_BlueControlActivity.this).load(R.drawable.sevenloading).into(iv_gif); + ll_gif = findMyViewById(R.id.ll_gif); + + if(Device.TYPE_5F.equals(type)){ //海水 + iv_control_2.setSelectorDrawable(getDrawable(R.drawable.daifenqi_on)); + iv_control_2.setDefaultDrawable(getDrawable(R.drawable.daifenqi_off)); + tv_iconName_2.setText("蛋分器"); + }else{ //淡水 + iv_control_2.setSelectorDrawable(getDrawable(R.drawable.lamp0bon2)); + iv_control_2.setDefaultDrawable(getDrawable(R.drawable.lamp0boff2)); + tv_iconName_2.setText("增氧泵"); + } + } + + private void showgif() { + ll_gif.setVisibility(View.VISIBLE); + } + + private void hidegif() { + ll_gif.setVisibility(View.GONE); + } + + private LinearLayout ll_gif; + + private void initListener() { + tv_setfish.setOnClickListener(this); + tv_setdian.setOnClickListener(this); + title_img_right.setOnClickListener(this); + iv_control_1.setOnClickListener(this); + iv_control_2.setOnClickListener(this); + iv_control_3.setOnClickListener(this); + iv_control_4.setOnClickListener(this); + iv_control_5.setOnClickListener(this); + iv_control_6.setOnClickListener(this); + iv_control_7.setOnClickListener(this); + iv_control_8.setOnClickListener(this); +// findViewById(R.id.rl_typegone).setOnClickListener(this); + sw.setOnRefreshListener(this); + } + BluetoothDevice currentDevice; + private void init() { + EventBus.getDefault().register(this); + sp = SPUtil.getInstance(this); + isToast = true; + isFirstAPP = false; + try { + + currentDevice = BLEManger.getInstance().currentDevice; + if (currentDevice!=null){ + mac =currentDevice.getAddress(); + L.i("===============发现设备的mac" + mac); + if (!TextUtils.isEmpty(mac)){ + mac = mac.replace(":","").toLowerCase(); + } + } + } catch (Exception e) { + } + } + + //发送登录设备的指令 + private void LoginDevice() { + startRefreshTimer(); + new Thread() { + @Override + public void run() { + super.run(); + try { + if (MainTabActivity.socket == null) { + MainTabActivity.socket = new Socket(HttpManager.FISH_URL, HttpManager.FISH_URL_PORT); + L.i("===============新建的soket" + MainTabActivity.socket.getLocalPort()); + } + map.put(Commons.FishKey.Key, Commons.FishKey.Login);//登录 + map.put(Commons.FishKey.Mac, mac); + L.i("===============mac" + mac); + TcpReceiveThread tr = new TcpReceiveThread(MainTabActivity.socket); + Thread thread1 = new Thread(tr); + thread1.start(); + + TcpSendThread ts = new TcpSendThread(MainTabActivity.socket, map); + Thread thread2 = new Thread(ts); + thread2.start(); + } catch (Exception e) { + e.printStackTrace(); + } + } + }.start(); + } + + private void startRefreshTimer() { + if (RefreshTimer == null) { + RefreshTimer = new CountDownTimer(3500, 2000) { + @Override + public void onTick(long millisUntilFinished) { + } + + @Override + public void onFinish() { + rl_setting_clickble = true; + tv_wendu.setText(""); + sw.setRefreshing(false); + if (isToast) { + ToastUtil.showSpecial(MainSix_4F_BlueControlActivity.this, Commons.Text.Repost); + } + } + }; + } + RefreshTimer.start(); + } + + private void stopRefreshTimer() { + if (RefreshTimer != null) { + RefreshTimer.cancel(); + } + } + + private void StartWifiChangeTimer() { + if (WifiChangeTimer == null) { + WifiChangeTimer = new CountDownTimer(2500, 2000) { + @Override + public void onTick(long millisUntilFinished) { + } + + @Override + public void onFinish() { + LoginDevice(); + } + }; + } + WifiChangeTimer.start(); + } + + private void StopWifiChangeTimer() { + if (WifiChangeTimer != null) { + WifiChangeTimer.cancel(); + } + } + + private void startTimer() { + rl_setting_clickble = false; + if (TcpTimer == null) { + TcpTimer = new CountDownTimer(4000, 600) {//倒数4秒 没有反应则判断TCP指令失效 + @Override + public void onTick(long millisUntilFinished) { + } + + @Override + public void onFinish() {//倒计时结束 + resetIVFlag(); + isWaterDialog = false; + dismissProgressDialog(); + ToastUtil.showSpecial(MainSix_4F_BlueControlActivity.this, Commons.Text.Repost); + } + }; + } + TcpTimer.start(); + } + + //重置三个按钮所有状态 + private void resetIVFlag() { + rl_setting_clickble = true; + } + + private void stopTimer() { + if (TcpTimer != null) { + TcpTimer.cancel(); + } + } + + //设置温度校准返回 + public void onEventMainThread(BackInfoModelSeven_2F_TimeSet event){ + if (!DeviceOnLine) { + ToastUtil.show(MainSix_4F_BlueControlActivity.this, Commons.Text.OFFDevice); + return; + } + checkDevice(); //再次查询下温度 + } + + public void onEventMainThread(NetworkChangBean event) {//网络改变 + StartWifiChangeTimer(); + } + + public void onEventMainThread(ShareDevice event) {//分享鱼缸 + Intent i = new Intent(this, ShareActivity.class); + i.putExtra("deviceId", Commons.DEVICE.get(sp.getInt(Commons.LoginSPKey.Position, 0)).getDeviceId()); + startActivity(i); + AnimationUtil.startAnimation(this); + } + + public void onEventMainThread(SetDevice event) { + if (!DeviceOnLine) { + ToastUtil.show(MainSix_4F_BlueControlActivity.this, Commons.Text.OFFDevice); + return; + } + Intent i = new Intent(); + i.setClass(MainSix_4F_BlueControlActivity.this, TimeSettingSix_4F.class); + i.putExtra(TimeSettingSix_4F.BYTEOBJECT, backInfoModelSix_4F); + i.putExtra(TimeSettingSix_4F.MAC, mac); + startActivity(i); + AnimationUtil.startAnimation(MainSix_4F_BlueControlActivity.this); + } + + public void onEventMainThread(RenameDevice event) {//修改鱼缸名字 + Intent i = new Intent(this, ChangeDeviceName_2F_Activity.class); + i.putExtra("device", Commons.DEVICE.get(sp.getInt(Commons.LoginSPKey.Position, 0))); + i.putExtra("position", sp.getInt(Commons.LoginSPKey.Position, 0)); + startActivity(i); + AnimationUtil.startAnimation(this); + } + + public void onEventMainThread(DeleteDevice event) {//删除鱼缸 + delDevice(); + } + + //一键喂鱼查询返回 + public void onEventMainThread(BackInfoModelSix_4F_FeedFish event){ + if(isClick_FeedFish){ + isClick_FeedFish = false; + if(!event.isLight_select1() && !event.isLight_select2() && !event.isLight_select3() && !event.isLight_select4() && !event.isLight_select5() && !event.isLight_select6()){ //一个设备都没有关联 + //没有设置一键喂鱼,先去设置 + gotoSetFeedFishSetting(); + }else{ + //判断是否是立即开启还是关闭一键喂鱼 + showFeedFishStyleDialog(); + } + } + } + + private void gotoSetFeedFishSetting(){ + IosAlertDialog dialog = new IosAlertDialog(this).builder(); + dialog.setTitle("提示"); + dialog.setCancelable(true); + dialog.setMessage("是否需要设置喂鱼设置?"); + dialog.setNegativeButton("取消", new View.OnClickListener() { + @Override + public void onClick(View view) { + + } + }); + dialog.setPositiveButton("确认", new View.OnClickListener() { + @Override + public void onClick(View view) { + if (!DeviceOnLine) { + ToastUtil.show(MainSix_4F_BlueControlActivity.this, Commons.Text.OFFDevice); + return; + } + Intent intent1 = new Intent(MainSix_4F_BlueControlActivity.this,FeedFishSettingActivity.class); + intent1.putExtra(TimeSettingSix_4F.BYTEOBJECT,backInfoModelSix_4F); + intent1.putExtra(TimeSettingSix_4F.MAC, mac); + startActivity(intent1); + AnimationUtil.startAnimation(MainSix_4F_BlueControlActivity.this); + } + }); + dialog.show(); + } + + //是否立即开始喂鱼 + private void startFeedFishSoon(){ + IosAlertDialog dialog = new IosAlertDialog(this).builder(); + dialog.setTitle("提示"); + dialog.setCancelable(true); + dialog.setMessage("你确定要立即喂鱼吗?"); + dialog.setNegativeButton("取消", new View.OnClickListener() { + @Override + public void onClick(View view) { + + } + }); + dialog.setPositiveButton("确认", new View.OnClickListener() { + @Override + public void onClick(View view) { + openFishFeedingNow(FishFeedType.OPEN_FISH_FEED+"");//立即一键喂鱼 + new Handler().postDelayed(new Runnable() { + @Override + public void run() { + checkDevice();//查询下设置的状态 + } + },1000); + } + }); + dialog.show(); + } + + //接受6控查询返回的指令 + public void onEventMainThread(BackInfoModelSix_4F event) { + hidegif(); + dismissProgressDialog(); + dismissProgressDialogCancelble(); + tv_offline.setVisibility(View.GONE); + backInfoModelSix_4F = event; + DeviceOnLine = true; + resetIVFlag(); + stopAllTimer(); + rl_setting_clickble = true; + sw.setRefreshing(false); + tv_wendu.setText((float) event.getWendu() / 10 + ""); + if (isWaterDialog) { + if (waterTempDialog != null) { + waterTempDialog.dismiss(); + } + isWaterDialog = false; + } + if (waterTempDialog != null) { + if (waterTempDialog.isShowing()) { + if (iv_hot != null) { + if (Byte.toString(event.getOnoff7()).equals(Commons.FishKey.On)) { + iv_hot.toggle(true); + } else { + iv_hot.toggle(false); + } + } + } + } +// tv_dianliang.setText((float) event.getDianliang() / 10 + ""); + byte string1 = event.getOnoff1(); + byte string2 = event.getOnoff2(); + byte string3 = event.getOnoff3(); + byte string4 = event.getOnoff4(); + byte string5 = event.getOnoff5(); + byte string6 = event.getOnoff6(); + byte string7 = event.getHeatStatus(); + byte string8 = event.getSarkLamp(); + if (Byte.toString(string1).equals(Commons.FishKey.On)) { + iv_control_2.toggle(true); + } else { + iv_control_2.toggle(false); + } + + if (Byte.toString(string2).equals(Commons.FishKey.On)) { + iv_control_3.toggle(true); + } else { + iv_control_3.toggle(false); + } + if (Byte.toString(string3).equals(Commons.FishKey.On)) { + iv_control_4.toggle(true); + } else { + iv_control_4.toggle(false); + } + if (Byte.toString(string4).equals(Commons.FishKey.On)) { + iv_control_7.toggle(true); + } else { + iv_control_7.toggle(false); + } + if (Byte.toString(string5).equals(Commons.FishKey.On)) { + iv_control_1.toggle(true); + } else { + iv_control_1.toggle(false); + } + if (Byte.toString(string6).equals(Commons.FishKey.On)) { + iv_control_5.toggle(true); + } else { + iv_control_5.toggle(false); + } + if (Byte.toString(string7).equals(Commons.FishKey.On)) { + iv_control_8.toggle(true); + } else { + iv_control_8.toggle(false); + } + + short heatWendu = event.getHeatWendu(); + if(tv_heatWendu != null){ + if(heatWendu != 0){ + tv_heatWendu.setVisibility(View.VISIBLE); + tv_heatWendu.setText(event.getHeatWendu() / 10 + ""); + }else{ + tv_heatWendu.setVisibility(View.GONE); + } + } + + if (Byte.toString(string8).equals(Commons.FishKey.On)) { + iv_control_6.toggle(true); + } else { + iv_control_6.toggle(false); + } + String humidity = "0"; //水位报警提示 + if ("0".equals(humidity)) { + tv_humidity.setVisibility(View.GONE); + } else { + tv_humidity.setVisibility(View.VISIBLE); + } + //一键喂鱼是否开启 + byte feed_fish_s2m = event.getFeed_fish_s2m(); + if(Byte.toString(feed_fish_s2m).equals(Commons.FishKey.On)){ + tv_setfish.setBackground(getDrawable(R.drawable.select_bg)); + }else{ + tv_setfish.setBackground(getDrawable(R.drawable.select_un_bg)); + } + //电量功率 + if(event.getDianliang() != 0){ + tv_setdian.setVisibility(View.VISIBLE); + tv_setdian.setText((float) event.getDianliang() / 10 + "w"); + }else{ + tv_setdian.setVisibility(View.GONE); + } + } + + //接收到发送方出错的指令 + public void onEventMainThread(ErrorSendObj event) { + L.i("===========发送方异常============="); + errorDevice(); + } + + //接收到接受方出错的指令 + public void onEventMainThread(ErrorReceiveObj event) { + L.i("===========接收方异常============="); + errorDevice(); + } + + //接收到发送方出错的吐司 + public void onEventMainThread(ErrorSendToast event) { + errorDevice(); + } + + //接收到接受方出错的吐司 + public void onEventMainThread(ErrorReceiveToast event) { + errorDevice(); + } + + private void errorDevice() { + closeSoket(); + DeviceOnLine = false; + sw.setRefreshing(false); + Commons.IS_EventBus = true; + EventBus.getDefault().post(new ErrorSendTimeSetting());//提示设置界面已离线 + L.i("===========离线============="); + } + + //收到鱼缸解绑推送 + public void onEventMainThread(JpushDeleteDeviceMac event) { + if (mac.equals(event.mac)) { + ToastUtil.show(MainSix_4F_BlueControlActivity.this, "您已失去设备的控制权"); + finish(); + AnimationUtil.finishAnimation(this); + } + } + + //接收登录返回的指令 + public void onEventMainThread(Boolean event) { + if (event) { + checkDevice(); + DeviceOnLine = true; + } else { + stopRefreshTimer(); + OffLineDevice(); + } + isWaterDialog = false; + dismissProgressDialog(); + } + + private void OffLineDevice() {//设备离线的处理 + DeviceOnLine = false; + rl_setting_clickble = true; + sw.setRefreshing(false); + Commons.IS_EventBus = true; + EventBus.getDefault().post(new ErrorSendTimeSetting());//提示设置界面已离线 + tv_offline.setVisibility(View.VISIBLE); + } + + private TextView tv_offline; + + private void delDevice() { + for (int i = 0; i < Commons.DEVICE.size(); i++) { + if (mac.equals(Commons.DEVICE.get(i).getMacAddress())) { + position = i; + break; + } + } + AlertDialog.Builder dialog = new AlertDialog.Builder(MainSix_4F_BlueControlActivity.this, AlertDialog.THEME_HOLO_LIGHT); + dialog.setMessage("确认删除设备?"); + dialog.setPositiveButton("确定", new DialogInterface.OnClickListener() { + @Override + public void onClick( + DialogInterface dialog, + int which) { + showProgressDialog(); + hm.deleteDeviceUser(new HttpListener>() { + private int result; + + @Override + public void success(BaseBean baseBean) { + result = baseBean.result; + } + + @Override + public void finish() { + UIhandler.sendEmptyMessage(result); + } + + @Override + public void error(Exception e, String msg) { + result = Commons.NetWork.ERROR; + } + }, Commons.DEVICE.get(position).getDeviceId(), Commons.USER.getUserId()); + } + }); + dialog.setNegativeButton("取消", null); + dialog.show(); + } + + public Handler UIhandler = new Handler() { + public void handleMessage(android.os.Message msg) { + dismissProgressDialog(); + /** + * 1:修改成功 + 0:修改失败 + -4:请求验证失败,请重新登陆 + */ + switch (msg.what) { + case Commons.NetWork.Del: + case Commons.NetWork.Success: + for (int i = 0; i < Commons.DeviceCamera.size(); i++) { + if (Commons.DEVICE.get(position).getDeviceId().equals(Commons.DeviceCamera.get(i).deviceId)) { + Commons.DeviceCamera.remove(i); + break;//删除摄像头和鱼缸的关系 + } + } + Commons.DEVICE.remove(position); + if (Commons.DEVICE.size() == 0) {//当删除的是最后一个设备的时候,则回到解绑状态 隐藏聊天室 + EventBus.getDefault().post(new UnBindDevice()); + } else { + if (position <= Commons.DevicePosition) { + if (Commons.DevicePosition == 0) { + sp.putInt(Commons.LoginSPKey.Position, Commons.DevicePosition); + } else { + Commons.DevicePosition = Commons.DevicePosition - 1; + sp.putInt(Commons.LoginSPKey.Position, Commons.DevicePosition); + } + } + Commons.IS_CAMERA = false; + sp.putBoolean(Commons.LoginSPKey.IS_CAMERA, Commons.IS_CAMERA); + } + ToastUtil.show(MainSix_4F_BlueControlActivity.this, "删除成功"); + finish(); + AnimationUtil.finishAnimation(MainSix_4F_BlueControlActivity.this); + break; + case Commons.NetWork.Fail: + ToastUtil.show(MainSix_4F_BlueControlActivity.this, "删除失败"); + break; + case Commons.NetWork.ReLogin: + ToastUtil.show(MainSix_4F_BlueControlActivity.this, "请求验证失败 请重新登陆"); + Commons.clean(); + startActivity(new Intent(MainSix_4F_BlueControlActivity.this, LoadingActivity.class)); + break; + case Commons.NetWork.ERROR: + ToastUtil.show(MainSix_4F_BlueControlActivity.this, Commons.Text.ERROR); + break; + case Commons.NetWork.NotImplemented: + ToastUtil.show(MainSix_4F_BlueControlActivity.this, Commons.Text.Unknown); + break; + default: + ToastUtil.show(MainSix_4F_BlueControlActivity.this, Commons.Text.ServerException); + break; + } + + } + }; + + @Override + public void onRefresh() { + RefreshDevice(); + } + + //刷新设备 + private void RefreshDevice() { + rl_setting_clickble = false; + Commons.is_ShowSpecial = true; + LoginDevice(); + } + + //查询一键喂鱼设置 + private void getFeedFishSettings(){ + new Thread() { + @Override + public void run() { + super.run(); + map.put(Commons.FishKey.Key, Commons.FishKey.QueryFeedFish);//查询一键喂鱼 + map.put(Commons.FishKey.Mac, mac); + TcpSendThread tsf = new TcpSendThread(MainTabActivity.socket,map); + Thread thread3 = new Thread(tsf); + thread3.start(); + } + }.start(); + } + + //点击一键喂鱼按钮后的弹出框 + private void showFeedFishStyleDialog(){ + IosAlertDialog dialog = new IosAlertDialog(this).builder(); + dialog.setTitle("提示"); + dialog.setCancelable(true); + byte feed_fish_s2m = backInfoModelSix_4F.getFeed_fish_s2m(); + String option = null; + if(Byte.toString(feed_fish_s2m).equals(Commons.FishKey.On)){ //已经开启了 + dialog.setMessage("确认关闭一键喂鱼吗?"); + option = FishFeedType.CLOSE_FISH_FEED + ""; + }else{ + dialog.setMessage("确认开始一键喂鱼吗?"); + option = FishFeedType.OPEN_FISH_FEED + ""; + } + dialog.setNegativeButton("取消", new View.OnClickListener() { + @Override + public void onClick(View view) { + + } + }); + final String finalOption = option; + dialog.setPositiveButton("确认", new View.OnClickListener() { + @Override + public void onClick(View view) { + openFishFeedingNow(finalOption);//立即一键喂鱼 + new Handler().postDelayed(new Runnable() { + @Override + public void run() { + if(finalOption.equals(FishFeedType.CLOSE_FISH_FEED + "")){ + tv_setfish.setBackground(getDrawable(R.drawable.select_un_bg)); + }else{ + tv_setfish.setBackground(getDrawable(R.drawable.select_bg)); + } + } + },1000); + } + }); + dialog.show(); + } + + /** + * 立即执行一键喂鱼 + */ + private void openFishFeedingNow(final String feedType){ + new Thread() { + @Override + public void run() { + super.run(); + map.put(Commons.FishKey.Key, Commons.FishKey.OpenFishFeedingNow);//开启一键喂鱼 + map.put(Commons.FishKey.Mac, mac); + map.put(Commons.FishKey.OptionType,feedType); + TcpSendThread ts3 = new TcpSendThread(MainTabActivity.socket, map); + Thread thread3 = new Thread(ts3); + thread3.start(); + } + }.start(); + } + + @Override + public void onClick(View v) {//点击事件 + Intent i = new Intent(); + super.onClick(v); + switch (v.getId()) { +// case R.id.iv_right://定时设置 +// case R.id.tv_right: { +// if (rl_setting_clickble) { +// if (!DeviceOnLine) { +// ToastUtil.show(MainSeven_2F_ControlActivity.this, Commons.Text.OFFDevice); +// return; +// } +// i.setClass(MainSeven_2F_ControlActivity.this, TimeSettingFour_2B.class); +// i.putExtra(TimeSettingFour_2B.BYTEOBJECT, backQueryObjFour_2B); +// i.putExtra(TimeSettingFour_2B.MAC, mac); +// startActivity(i); +// AnimationUtil.startAnimation(MainSeven_2F_ControlActivity.this); +// } +// break; +// } + case R.id.tv_setfish: //一键喂鱼 + //先查询一键喂鱼设置 + isClick_FeedFish = true; + getFeedFishSettings(); + break; + case R.id.tv_setdian://电量统计 + //跳转到电量统计页面 + if (!DeviceOnLine) { + ToastUtil.show(MainSix_4F_BlueControlActivity.this, Commons.Text.OFFDevice); + return; + } + i.setClass(MainSix_4F_BlueControlActivity.this, DianLiangControlActivity.class); + i.putExtra(DianLiangControlActivity.BYTEOBJECT, backInfoModelSix_4F); + i.putExtra(DianLiangControlActivity.MAC, mac); + startActivity(i); + AnimationUtil.startAnimation(MainSix_4F_BlueControlActivity.this); + break; + case R.id.title_img_right: {//打开右侧泡泡窗口 + //是否展示“分享设备” + if (Commons.FishKey.On.equals(Commons.DEVICE.get(sp.getInt(Commons.LoginSPKey.Position, 0)).getIsMaster())) { + PopWindowDevice_EventBus popWindowDevice_eventBus = new PopWindowDevice_EventBus(MainSix_4F_BlueControlActivity.this, true); + popWindowDevice_eventBus.showPopupWindow(title_img_right); + popWindowDevice_eventBus.showSet(); + } else { + PopWindowDevice_EventBus popWindowDevice_eventBus = new PopWindowDevice_EventBus(MainSix_4F_BlueControlActivity.this, false); + popWindowDevice_eventBus.showPopupWindow(title_img_right); + popWindowDevice_eventBus.showSet(); + } + break; + } + case R.id.iv_control_1: { + if (rl_setting_clickble) { + rl_setting_clickble = false; + startTimer(); + showgif(); + if (!DeviceOnLine) {//离线就发登录指令 否则开关灯 + LoginDevice(); + } else { + if (!iv_control_1.isChecked()) { + OnDevice(5); + } else { + OFFDevice(5); + } + } + } + break; + } + case R.id.iv_control_2: { + if (rl_setting_clickble) { + rl_setting_clickble = false; + startTimer(); + showgif(); + if (!DeviceOnLine) {//离线就发登录指令 否则开关灯 + LoginDevice(); + } else { + if (!iv_control_2.isChecked()) { + OnDevice(1); + } else { + OFFDevice(1); + } + } + } + break; + } + case R.id.iv_control_3: { + if (rl_setting_clickble) { + rl_setting_clickble = false; + startTimer(); + showgif(); + if (!DeviceOnLine) {//离线就发登录指令 否则开关灯 + LoginDevice(); + } else { + if (!iv_control_3.isChecked()) { + OnDevice(2); + } else { + OFFDevice(2); + } + } + } + break; + } + case R.id.iv_control_4: { + if (rl_setting_clickble) { + rl_setting_clickble = false; + startTimer(); + showgif(); + if (!DeviceOnLine) {//离线就发登录指令 否则开关灯 + LoginDevice(); + } else { + if (!iv_control_4.isChecked()) { + OnDevice(3); + } else { + OFFDevice(3); + } + } + } + break; + } + case R.id.iv_control_5: { + if (rl_setting_clickble) { + rl_setting_clickble = false; + startTimer(); + showgif(); + if (!DeviceOnLine) {//离线就发登录指令 否则开关灯 + LoginDevice(); + } else { + if (!iv_control_5.isChecked()) { + OnDevice(6); + } else { + OFFDevice(6); + } + } + } + break; + } + case R.id.iv_control_6: { + if (rl_setting_clickble) { + rl_setting_clickble = false; + startTimer(); + showgif(); + if (!DeviceOnLine) {//离线就发登录指令 否则开关灯 + LoginDevice(); + } else { + if (!iv_control_6.isChecked()) { + SarkLampOn(); + } else { + SarkLampOff(); + } + } + } + break; + } + case R.id.iv_control_7: { + if (rl_setting_clickble) { + rl_setting_clickble = false; + startTimer(); + if (!DeviceOnLine) {//离线就发登录指令 否则开关灯 + showgif(); + LoginDevice(); + } else { + if (!iv_control_7.isChecked()) { + showgif(); + OnDevice(4); + } else { + showOffWaterDialog(4); + } + } + } + break; + } + case R.id.iv_control_8: { + if (rl_setting_clickble) { + rl_setting_clickble = false; + if (!DeviceOnLine) {//离线就发登录指令 否则开关灯 + showgif(); + startTimer(); + LoginDevice(); + } else { + //设置加热棒温度对话框 + showHeatWenduDialog(); + } + } + break; + } + case R.id.rl_typegone: { + if (ll_wendu.getVisibility() == View.VISIBLE) { + ll_dianliang.setVisibility(View.VISIBLE); + ll_wendu.setVisibility(View.GONE); + tv_typename.setText("当月电量"); + new Handler().postDelayed(new Runnable() { + @Override + public void run() { + ll_dianliang.setVisibility(View.GONE); + ll_wendu.setVisibility(View.VISIBLE); + tv_typename.setText("鱼缸温度"); + } + }, 3000); + } else { + ll_dianliang.setVisibility(View.GONE); + ll_wendu.setVisibility(View.VISIBLE); + tv_typename.setText("鱼缸温度"); + } + break; + } + } + + } + + private SelectorImageView iv_hot; + + private void showHeatWenduDialog() { + rl_setting_clickble = true; + final String[] temps = new String[51]; + for (int i = 0; i < 51; i++) { + temps[i] = (i + 1) + ""; + } + int currentItem = 0; + final WheelView wv_water; + Button bt_submit; + waterTempDialog = new Dialog(MainSix_4F_BlueControlActivity.this, R.style.HOLOMyDialogs); + waterTempDialog.setCancelable(true); + Window window = waterTempDialog.getWindow(); + window.setContentView(R.layout.setwatertemp_dialog); + wv_water = (WheelView) window.findViewById(R.id.wv_water); + bt_submit = (Button) window.findViewById(R.id.bt_submit); + iv_hot = (SelectorImageView) window.findViewById(R.id.iv_hot); + iv_hot.toggle(false); + wv_water.setViewAdapter(new ArrayWheelAdapter(MainSix_4F_BlueControlActivity.this, temps)); + waterTempDialog.show(); + if (backInfoModelSix_4F != null) { + if (Byte.toString(backInfoModelSix_4F.getOnoff7()).equals(Commons.FishKey.On)) { + iv_hot.toggle(true); + } else { + iv_hot.toggle(false); + } + String temp = backInfoModelSix_4F.getHeatWendu() / 10 + ""; + for (int i = 0; i < temps.length; i++) { + if (temp.equals(temps[i])) { + currentItem = i; + break; + } + } + if (currentItem == 0) {//如果默认设置第一个 就显示第一个温度 但是获取到的温度为空的话就显示20摄氏度 + if ("1".equals(temp)) { + wv_water.setCurrentItem(currentItem); + } else { + wv_water.setCurrentItem(20); + } + } else { + wv_water.setCurrentItem(currentItem); + } + } else { + wv_water.setCurrentItem(20); + } + iv_hot.setOnClickListener(new View.OnClickListener() { + @Override + public void onClick(View view) { + showProgressDialogCancelble(); + if (iv_hot.isChecked()) { + OFFDevice(7); + } else { + OnDevice(7); + } + } + }); + bt_submit.setOnClickListener(new View.OnClickListener() { + @Override + public void onClick(View v) { + isWaterDialog = true; + showgif(); + startTimer(); + setHotWater(temps[wv_water.getCurrentItem()]); + } + }); + } + + //发送控制设备开灯的指令 + private void OnDevice(final int timer_number) { + new Thread() { + @Override + public void run() { + super.run(); + MainTabActivity.spmap.put(Commons.FishKey.timer_number, timer_number); + map.put(Commons.FishKey.Key, Commons.FishKey.On);//开灯 + map.put(Commons.FishKey.Mac, mac); + TcpSendThread ts3 = new TcpSendThread(MainTabActivity.socket, map, MainTabActivity.spmap); + Thread thread3 = new Thread(ts3); + thread3.start(); + } + }.start(); + } + + //发送控制设备关灯的指令 + private void OFFDevice(final int timer_number) { + new Thread() { + @Override + public void run() { + super.run(); + MainTabActivity.spmap.put(Commons.FishKey.timer_number, timer_number); + map.put(Commons.FishKey.Key, Commons.FishKey.Off);//关灯 + map.put(Commons.FishKey.Mac, mac); + TcpSendThread ts3 = new TcpSendThread(MainTabActivity.socket, map, MainTabActivity.spmap); + Thread thread3 = new Thread(ts3); + thread3.start(); + } + }.start(); + } + + //柜灯开 + private void SarkLampOn() { + new Thread() { + @Override + public void run() { + super.run(); + map.put(Commons.FishKey.Key, Commons.FishKey.SarkLampOn);//柜灯开 + map.put(Commons.FishKey.Mac, mac); + TcpSendThread ts3 = new TcpSendThread(MainTabActivity.socket, map); + Thread thread3 = new Thread(ts3); + thread3.start(); + } + }.start(); + } + + //柜灯关 + private void SarkLampOff() { + new Thread() { + @Override + public void run() { + super.run(); + map.put(Commons.FishKey.Key, Commons.FishKey.SarkLampOff);//柜灯关 + map.put(Commons.FishKey.Mac, mac); + TcpSendThread ts3 = new TcpSendThread(MainTabActivity.socket, map); + Thread thread3 = new Thread(ts3); + thread3.start(); + } + }.start(); + } + + //设置加热棒温度 + private void setHotWater(final String hot_water_temp) { + new Thread() { + @Override + public void run() { + super.run(); + map.put(Commons.FishKey.Key, Commons.FishKey.HotWaterTemp); + map.put(Commons.FishKey.hot_water_temp, hot_water_temp); + map.put(Commons.FishKey.Mac, mac); + TcpSendThread ts3 = new TcpSendThread(MainTabActivity.socket, map); + Thread thread3 = new Thread(ts3); + thread3.start(); + } + }.start(); + } + + private void showOffWaterDialog(final int num) { + AlertDialog.Builder dialog = new AlertDialog.Builder(MainSix_4F_BlueControlActivity.this); + dialog.setTitle("提示"); + dialog.setCancelable(true); + dialog.setMessage("确认关闭循环泵"); + dialog.setNegativeButton("取消", new DialogInterface.OnClickListener() { + @Override + public void onClick(DialogInterface arg0, int arg1) { + } + }); + dialog.setPositiveButton("确认", new DialogInterface.OnClickListener() { + @Override + public void onClick(DialogInterface dialog, int which) { + dialog.dismiss(); + OFFDevice(num); + startTimer(); + } + }); + dialog.show(); + } +} diff --git a/iFish7/src/main/java/com/ifish/activity/MainTabActivity.java b/iFish7/src/main/java/com/ifish/activity/MainTabActivity.java index f665080d1..9cd15fada 100644 --- a/iFish7/src/main/java/com/ifish/activity/MainTabActivity.java +++ b/iFish7/src/main/java/com/ifish/activity/MainTabActivity.java @@ -368,6 +368,8 @@ public class MainTabActivity extends BaseFragmentActivity { } }; + + private void initView() { tabHost = (TabHost) findViewById(android.R.id.tabhost); tabHost.setup(); diff --git a/iFish7/src/main/java/com/ifish/activity/newbind/BottomChoiceDialog.java b/iFish7/src/main/java/com/ifish/activity/newbind/BottomChoiceDialog.java index 1ee732539..c6d684820 100644 --- a/iFish7/src/main/java/com/ifish/activity/newbind/BottomChoiceDialog.java +++ b/iFish7/src/main/java/com/ifish/activity/newbind/BottomChoiceDialog.java @@ -46,11 +46,13 @@ public class BottomChoiceDialog extends DialogFragment implements View.OnClickLi } private TextView tvSmartConfig; + private TextView tvBle; private TextView tvAP; private TextView tvAirKiss; private TextView tvCancel; private LinearLayout lineAirKiss; private LinearLayout lineSmartConfig; + private LinearLayout lineBle; private LinearLayout lineAP; @Nullable @@ -59,17 +61,20 @@ public class BottomChoiceDialog extends DialogFragment implements View.OnClickLi View view = inflater.inflate(R.layout.dialog_choose_connect_wifi_type, container, false); tvSmartConfig = (TextView) view.findViewById(R.id.tv_smartConfig); + tvBle = (TextView) view.findViewById(R.id.tv_ble); tvAP = (TextView) view.findViewById(R.id.tv_AP); tvAirKiss = (TextView) view.findViewById(R.id.tv_airkiss); tvCancel = (TextView) view.findViewById(R.id.tv_cancel); lineAirKiss = (LinearLayout) view.findViewById(R.id.line_airKiss); lineSmartConfig = (LinearLayout) view.findViewById(R.id.line_smartConfig); + lineBle = (LinearLayout) view.findViewById(R.id.line_ble); lineAP = (LinearLayout) view.findViewById(R.id.line_AP); tvSmartConfig.setOnClickListener(this); tvAP.setOnClickListener(this); tvAirKiss.setOnClickListener(this); tvCancel.setOnClickListener(this); + tvBle.setOnClickListener(this); switchChooseUI(curType); return view; @@ -120,6 +125,11 @@ public class BottomChoiceDialog extends DialogFragment implements View.OnClickLi chooseClickListener.smartConfigConnect(); dismissAllowingStateLoss(); break; + + case R.id.tv_ble: + chooseClickListener.bleConnect(); + dismissAllowingStateLoss(); + break; case R.id.tv_AP: chooseClickListener.APConnect(); dismissAllowingStateLoss(); @@ -137,12 +147,18 @@ public class BottomChoiceDialog extends DialogFragment implements View.OnClickLi public void switchChooseUI(ConnectType curConnectType) { lineAirKiss.setVisibility(View.VISIBLE); lineAP.setVisibility(View.VISIBLE); - lineSmartConfig.setVisibility(View.VISIBLE); + lineSmartConfig.setVisibility(View.GONE); + lineBle.setVisibility(View.VISIBLE); switch (curConnectType) { case SmartConfig: // 处理SmartConfig逻辑 lineSmartConfig.setVisibility(View.GONE); break; + + case BlueTooth: + // 处理SmartConfig逻辑 + lineBle.setVisibility(View.GONE); + break; case APConnect: // 处理APConnect逻辑 lineAP.setVisibility(View.GONE); @@ -161,6 +177,7 @@ public class BottomChoiceDialog extends DialogFragment implements View.OnClickLi void APConnect();//热点连接 void AirKissConnect();//airkiss连接 + void bleConnect();//airkiss连接 } public void setOnChooseClickListener(OnChooseClickListener shareClickListener) { diff --git a/iFish7/src/main/java/com/ifish/activity/newbind/ConnectType.java b/iFish7/src/main/java/com/ifish/activity/newbind/ConnectType.java index de31a8000..647e67f34 100644 --- a/iFish7/src/main/java/com/ifish/activity/newbind/ConnectType.java +++ b/iFish7/src/main/java/com/ifish/activity/newbind/ConnectType.java @@ -9,5 +9,6 @@ package com.ifish.activity.newbind; public enum ConnectType { APConnect, SmartConfig, - AirKiss + AirKiss, + BlueTooth } diff --git a/iFish7/src/main/java/com/ifish/activity/newbind/NewBindDeviceActivity.java b/iFish7/src/main/java/com/ifish/activity/newbind/NewBindDeviceActivity.java index c0d0aa0e8..ca0a2ddb0 100644 --- a/iFish7/src/main/java/com/ifish/activity/newbind/NewBindDeviceActivity.java +++ b/iFish7/src/main/java/com/ifish/activity/newbind/NewBindDeviceActivity.java @@ -4,42 +4,87 @@ import android.Manifest; import android.annotation.SuppressLint; import android.app.Activity; import android.app.AlertDialog; +import android.app.Dialog; +import android.app.ProgressDialog; +import android.bluetooth.BluetoothDevice; +import android.bluetooth.BluetoothGatt; import android.content.DialogInterface; import android.content.Intent; import android.content.pm.PackageManager; import android.os.Build; import android.os.Bundle; +import android.os.CountDownTimer; +import android.os.Handler; +import android.os.Message; import android.provider.Settings; import android.text.TextUtils; +import android.util.Log; import android.view.View; import android.widget.EditText; -import android.widget.FrameLayout; import android.widget.LinearLayout; -import android.widget.ProgressBar; import android.widget.TextView; import androidx.annotation.NonNull; import androidx.appcompat.app.AppCompatActivity; +import com.clj.fastble.BleManager; +import com.clj.fastble.callback.BleGattCallback; +import com.clj.fastble.callback.BleMtuChangedCallback; +import com.clj.fastble.callback.BleNotifyCallback; +import com.clj.fastble.callback.BleScanCallback; +import com.clj.fastble.callback.BleWriteCallback; +import com.clj.fastble.data.BleDevice; +import com.clj.fastble.exception.BleException; +import com.clj.fastble.scan.BleScanRuleConfig; import com.ifish.activity.BindCameraActivity; -import com.ifish.activity.BindDeviceChoiceActivity; import com.ifish.activity.BindTankActivity; import com.ifish.activity.BindTankPetActivity; +import com.ifish.activity.BlackListActivity; +import com.ifish.activity.LoadingActivity; +import com.ifish.activity.MainEightControlActivity; +import com.ifish.activity.MainFiveBDControlActivity; +import com.ifish.activity.MainFiveControlActivity; +import com.ifish.activity.MainFourControlActivity; +import com.ifish.activity.MainFour_2B_ControlActivity; +import com.ifish.activity.MainFour_3F_ControlActivity; +import com.ifish.activity.MainHot_3A_ControlActivity; +import com.ifish.activity.MainSeven_2F_ControlActivity; +import com.ifish.activity.MainSixControlActivity; +import com.ifish.activity.MainSix_2A_ControlActivity; +import com.ifish.activity.MainSix_4F_ControlActivity; +import com.ifish.activity.MainThree1CControlActivity; +import com.ifish.activity.MainThreeControlActivity; +import com.ifish.activity.MainTwoControlActivity; +import com.ifish.activity.MainZeroControlActivity; import com.ifish.activity.R; -import com.ifish.activity.TimeSettingFour; import com.ifish.activity.WebViewActivity; +import com.ifish.basebean.BaseBean; import com.ifish.basebean.ConnectMessageEvent; +import com.ifish.basebean.Device; +import com.ifish.baseclass.BaseGradeActivity; +import com.ifish.tcp.BackFunctionCode7_11; +import com.ifish.tcp.ModelCodec; +import com.ifish.tcp.OrderDeviceConnectModel; +import com.ifish.tcp.OrderModel; +import com.ifish.tcp.ResetDeviceModel; import com.ifish.utils.AnimationUtil; +import com.ifish.utils.BlueToothUtil; +import com.ifish.utils.ByteUtil; import com.ifish.utils.ClickUtil; import com.ifish.utils.Commons; +import com.ifish.utils.HttpListener; import com.ifish.utils.HttpManager; -import com.ifish.utils.KVUtil; import com.ifish.utils.L; import com.ifish.utils.SPUtil; import com.ifish.utils.ToastUtil; import com.ifish.utils.WifiAdmin; import com.lidroid.xutils.util.LogUtils; +import java.io.BufferedReader; +import java.io.InputStreamReader; +import java.util.List; +import java.util.UUID; + import de.greenrobot.event.EventBus; /** @@ -62,6 +107,8 @@ public class NewBindDeviceActivity extends AppCompatActivity { private TextView tvClickButton; private TextView tvConnectVideo; + private int nofity_type = 0; + //----------------变量区--------------------// private ConnectType curConnectType;//当前选择的连接类型 APConnect,SmartConfig,AirKiss @@ -74,23 +121,47 @@ public class NewBindDeviceActivity extends AppCompatActivity { private AirKissUtil airKissUtil; private String bssid = ""; private SPUtil sp; + private Dialog waterTempDialog; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_new_bind_device_choice); + + + sp=SPUtil.getInstance(this); + act = this; + connectDevice = new ConnectDevice(20000, 1000); initTitle(); initView(); initListener(); initWifiName(); checkWifiUtil = new CheckWifiUtil(); airKissUtil = new AirKissUtil(); + String type = getIntent().getStringExtra("type"); devicetype = getIntent().getStringExtra("devicetype"); L.i("jjia----------------devicetype="+devicetype); airKissUtil.init(this,devicetype); - //默认AP联网 - curConnectType = ConnectType.AirKiss; + + BleManager.getInstance().disconnectAllDevice(); + if ("bluetooth".equals(type)){ + curConnectType = ConnectType.BlueTooth; + }else { + //默认AP联网 + curConnectType = ConnectType.AirKiss; + } + switchUIConnectType(curConnectType); + + if ("bluetooth".equals(type)){ // 主动去联网 + + currentDevice = getIntent().getParcelableExtra("device"); + if (currentDevice!=null){ + showProgressDialogCancelble("开始连接蓝牙设备"); + connectBle(); + } + } + EventBus.getDefault().register(this); } @@ -114,8 +185,12 @@ public class NewBindDeviceActivity extends AppCompatActivity { // String pwd = KVUtil.getString(wifiname, ""); String pwd = sp.getString(wifiname, ""); tvWifiPwd.setText(pwd); + L.i(wifiname+"jjia---------name--1-"+pwd); } + + + } private void initTitle() { @@ -177,6 +252,12 @@ public class NewBindDeviceActivity extends AppCompatActivity { curConnectType = ConnectType.AirKiss; switchUIConnectType(curConnectType); } + + @Override + public void bleConnect() { + curConnectType = ConnectType.BlueTooth; + switchUIConnectType(curConnectType); + } }); } }); @@ -218,6 +299,18 @@ public class NewBindDeviceActivity extends AppCompatActivity { * * @param connectType */ + + private void changeView(boolean blue){ + if (blue){ + tvTips2.setVisibility(View.GONE); + tvTips3.setVisibility(View.GONE); + + + }else { + tvTips2.setVisibility(View.VISIBLE); + tvTips3.setVisibility(View.VISIBLE); + } + } public void switchUIConnectType(ConnectType connectType) { resetLayout(); showToast(connectType); @@ -230,6 +323,18 @@ public class NewBindDeviceActivity extends AppCompatActivity { tvTips.setText("1、插座仅支持2.4G的WiFi网络,不支持5G及双频合一的网络(需在路由器设置中分开)"); tvTips2.setText("2、先长按插座复位键3秒,松手后红灯绿灯同时闪烁以后,再点确定按钮。"); tvTips3.setText("3、如多次尝试一键联网都不成功,可切换其他联网方式,每次重新连接时插座需断一次电然后重新复位连接。"); + changeView(false); + break; + case BlueTooth: + findConencted(); + // 处理SmartConfig逻辑 + tvConnectType.setText("蓝牙联网"); + tvClickButton.setText("确定"); + tvConnectVideo.setVisibility(View.INVISIBLE); + tvTips.setText("1、插座仅支持2.4G的WiFi网络,不支持5G及双频合一的网络(需在路由器设置中分开)"); + tvTips2.setText("2、先长按插座复位键3秒,松手后红灯绿灯同时闪烁以后,再点确定按钮。"); + tvTips3.setText("3、如多次尝试一键联网都不成功,可切换其他联网方式,每次重新连接时插座需断一次电然后重新复位连接。"); + changeView(true); break; case APConnect: // 处理APConnect逻辑 @@ -238,6 +343,7 @@ public class NewBindDeviceActivity extends AppCompatActivity { tvTips.setText("1、插座仅支持2.4G的WiFi网络,不支持5G及双频合一的网络(需在路由器设置中分开)"); tvTips2.setText("2、先长按插座复位键13秒左右,松手后红灯绿灯同时熄灭,只有绿灯偶尔闪烁,再点下一步。"); tvTips3.setText("3、APP跳转到WLAN后,选择ifish-xxxx的网络,点击连接,密码是12345678,连好以后点击左上角返回箭头,耐心等待连接。"); + changeView(false); break; case AirKiss: tvConnectType.setText("一键联网"); @@ -246,6 +352,7 @@ public class NewBindDeviceActivity extends AppCompatActivity { tvTips2.setText("2、先长按插座复位键3秒,松手后红灯绿灯同时闪烁以后,再点确定按钮。"); tvTips3.setText("3、如多次尝试一键联网都不成功,可切换其他联网方式,每次重新连接时插座需断一次电然后重新复位连接。"); // 处理AirKiss逻辑 + changeView(false); break; } } @@ -260,6 +367,9 @@ public class NewBindDeviceActivity extends AppCompatActivity { case SmartConfig: ToastUtil.show(this, "切换到快捷联网"); break; + case BlueTooth: + ToastUtil.show(this, "切换到蓝牙联网"); + break; case APConnect: ToastUtil.show(this, "切换到AP联网"); break; @@ -310,6 +420,38 @@ public class NewBindDeviceActivity extends AppCompatActivity { startActivity(intent); AnimationUtil.startAnimation(NewBindDeviceActivity.this); finish(); + break; + case BlueTooth: + + boolean support = BleManager.getInstance().isSupportBle(); + if (!support){ + ToastUtil.show(NewBindDeviceActivity.this,"当前设备不支持低功耗蓝牙"); + } else { + boolean enable = BleManager.getInstance().isBlueEnable(); + if (enable){ + blueScan(); + }else { + AlertDialog.Builder dialog = new AlertDialog.Builder(NewBindDeviceActivity.this); + dialog.setCancelable(false); + dialog.setMessage("蓝牙没有打开,现在去申请打开蓝牙,请允许"); + dialog.setPositiveButton("我知道了", new DialogInterface.OnClickListener() { + @Override + public void onClick( + DialogInterface dialog, + int which) { + BlueToothUtil.openBlueTooth(NewBindDeviceActivity.this); + } + }); + dialog.setNegativeButton("拒绝", new DialogInterface.OnClickListener() { + @Override + public void onClick(DialogInterface dialog, int which) { + finish(); + } + }); + dialog.show(); + } + } + break; case APConnect: //开始AP连接 @@ -324,8 +466,42 @@ public class NewBindDeviceActivity extends AppCompatActivity { } } - private boolean isJump = false; + private void blueScan(){ + BleManager.getInstance().scan(new BleScanCallback() { + @Override + public void onScanFinished(List scanResultList) { + if (currentDevice!=null){ + connectBle(); + }else { + ToastUtil.show(NewBindDeviceActivity.this,"扫描结束,没有搜索到可用设备"); + dismissProgressDialogCancelble(); + } + } + + @Override + public void onScanStarted(boolean success) { +// ToastUtil.show(NewBindDeviceActivity.this,"开始扫描"); + showProgressDialogCancelble("正在搜索附近设备,请确保设备处于配网状态"); + } + + @SuppressLint("MissingPermission") + @Override + public void onScanning(BleDevice bleDevice) { + if (bleDevice!=null && bleDevice.getDevice()!=null){ + BluetoothDevice bean = bleDevice.getDevice(); + if (!TextUtils.isEmpty(bean.getName()) && bean.getName().startsWith("ifish")){ + currentDevice = bleDevice; +// tvname.setText(bean.getName()+bean.getAddress()); + BleManager.getInstance().cancelScan(); + } + L.i(bean.getName()+"jjia---------"+bean.getAddress()); + } + } + }); + } + private boolean isJump = false; + BleDevice currentDevice; /** * 1.跳转设置页面连接ifish-xxx的wifi,连接成功后返回 */ @@ -404,5 +580,793 @@ public class NewBindDeviceActivity extends AppCompatActivity { } } } + private String device_mac; + private void openNotify(){ + BleManager.getInstance().notify(currentDevice, SERVICE_UUID, WRITE_UUID, new BleNotifyCallback() { + @Override + public void onNotifySuccess() { + sendBleData(); + } + @Override + public void onNotifyFailure(BleException exception) { + dismissProgressDialogCancelble(); + } + + @Override + public void onCharacteristicChanged(byte[] data) { + + if (data!=null && data.length>0){ + int check_code = data[1]; + int length = data[14]; + byte[] dataByte = new byte[length]; + for (int i = 0; i < dataByte.length; i++) { + dataByte[i] = data[i]; + } + + Object object = ModelCodec.deCode(dataByte); + if (object!=null && object instanceof BackFunctionCode7_11){ + BackFunctionCode7_11 model = (BackFunctionCode7_11) object; + String status = ByteUtil.toHex(model.getStatus()); + device_mac = ByteUtil.bytesToHexString(model.getSrc()); + + + checkoutMac(device_mac); + switch (nofity_type){ + case 1: + break; + + case 2: + + break; + + default: + L.i(status+"jjia-------"+device_mac); + + break; + } + + + } else { + dismissProgressDialogCancelble(); +// BackFunctionCode7_11 model = (BackFunctionCode7_11) object; +// String status = ByteUtil.toHex(model.getStatus()); +// if ("01".equals(status)) { +// L.i("jjia-------重启成功-"+status); +// } + } + L.i("jjia-------check_code-"+check_code); + L.i("jjia-------length-"+length); + L.i("jjia-------device_mac-"+device_mac); + } + } + }); + } + + private void checkoutMac(String mac){ + + if (!TextUtils.isEmpty(mac)){ + boolean isSameName = false; + devicePosition = 0; + try { + if (Commons.DEVICE != null) { + if (Commons.DEVICE.size() != 0) { + for (int i = 0; i < Commons.DEVICE.size(); i++) { + if (mac.equals(Commons.DEVICE.get(i).getMacAddress())) { + devicePosition = i; + isSameName = true; + break; + } + } + } + } + } catch (Exception e) { + e.printStackTrace(); + } + + + if (isSameName){ + L.i("jjia-------------不包含"); + runOnUiThread(new Runnable() { + @Override + public void run() { + resetDevice(1); + } + }); + }else { + L.i("jjia-------------不包含"); + runOnUiThread(new Runnable() { + @Override + public void run() { + isContinue = true; + resetDevice(2); + } + }); + } + }else { + dismissProgressDialogCancelble(); + } + + + + + } + int devicePosition = 0; + private void sendBleData(){ + + String ssid = tvWifiName.getText().toString(); + String pwd = tvWifiPwd.getText().toString(); + + OrderDeviceConnectModel model = OrderModel.OrderDeviceConnectModel(ssid, pwd);//设置正式环境域名 + byte[] data = ModelCodec.enCode(model); + BleManager.getInstance().write(currentDevice, SERVICE_UUID, WRITE_UUID, data,false, new BleWriteCallback() { + @Override + public void onWriteSuccess(int current, int total, byte[] justWrite) { + + L.i("jjia-------------ssid 发送"); + } + + @Override + public void onWriteFailure(BleException exception) { + + } + }); + } + + private void resetDevice(int type){ + + dismissProgressDialogCancelble(); + if (1==type){ + toDevice(); + }else if (2==type){ + connectDevice.cancel(); + connectDevice.start(); + } + + +// ResetDeviceModel model = OrderModel.resetDevice();//设置正式环境域名 +// byte[] data = ModelCodec.enCode(model);//解析数据 +// L.i("jjia----------------开始重启设备"+type); +// BleManager.getInstance().write(currentDevice, SERVICE_UUID, WRITE_UUID, data,false, new BleWriteCallback() { +// @Override +// public void onWriteSuccess(int current, int total, byte[] justWrite) { +// +// L.i("jjia----------------设备重启成功"); +// if (1==type){ +// toDevice(); +// }else if (2==type){ +// connectDevice.cancel(); +// connectDevice.start(); +// } +// } +// +// @Override +// public void onWriteFailure(BleException exception) { +// L.i("jjia----------------设备重启写失败"); +// } +// }); + } + + public static final String SERVICE_UUID = "000000ff-0000-1000-8000-00805f9b34fb"; //蓝牙通讯服务 + public static final String READ_UUID = "0000ff01-0000-1000-8000-00805f9b34fb"; //读特征 + public static final String WRITE_UUID = "0000ff01-0000-1000-8000-00805f9b34fb"; //写特征 + + private void connectBle(){ + BleManager.getInstance().connect(currentDevice, new BleGattCallback() { + @Override + public void onStartConnect() { + setMessage("开始连接蓝牙设备"); + +// ToastUtil.show(NewBindDeviceActivity.this,"开始连接蓝牙设备"); + } + + @Override + public void onConnectFail(BleDevice bleDevice, BleException exception) { + ToastUtil.show(NewBindDeviceActivity.this,"连接蓝牙设备失败"); + dismissProgressDialogCancelble(); + } + + @Override + public void onConnectSuccess(BleDevice bleDevice, BluetoothGatt gatt, int status) { +// ToastUtil.show(NewBindDeviceActivity.this,"蓝牙连接成功"); + setMessage("蓝牙连接成功"); + BleManager.getInstance().setMtu(bleDevice, 512, new BleMtuChangedCallback() { + @Override + public void onSetMTUFailure(BleException exception) { + L.i("jjia-------MTU--"+exception.toString()); + dismissProgressDialogCancelble(); + } + + @Override + public void onMtuChanged(int mtu) { + L.i("jjia-------MTU--"+mtu); + openNotify(); + } + }); + } + + @Override + public void onDisConnected(boolean isActiveDisConnected, BleDevice device, BluetoothGatt gatt, int status) { + ToastUtil.show(NewBindDeviceActivity.this,"连接断开了"); + } + }); + } + + public void toDevice() { + Intent i = new Intent(); + try { + Integer controlAmount = Commons.DEVICE.get(devicePosition).getControlAmount(); + Integer timerAmount = Commons.DEVICE.get(devicePosition).getTimerAmount(); + String type = Commons.DEVICE.get(devicePosition).type; + if (Commons.FishKey.On.equals(Commons.DEVICE.get(devicePosition).isBlacklist)) {//黑名单 + i.setClass(NewBindDeviceActivity.this, BlackListActivity.class); + } else { + if (Device.TYPE_1C.equals(type)) { + i.setClass(NewBindDeviceActivity.this, MainThree1CControlActivity.class); + } else if (Device.TYPE_AA.equals(type)) { + i.setClass(NewBindDeviceActivity.this, MainFiveControlActivity.class); + } else if (Device.TYPE_BD.equals(type)) { + i.setClass(NewBindDeviceActivity.this, MainFiveBDControlActivity.class); + } else if (Device.TYPE_2A.equals(type)) { + i.setClass(NewBindDeviceActivity.this, MainSix_2A_ControlActivity.class); + } else if (Device.TYPE_2B.equals(type)) { + i.setClass(NewBindDeviceActivity.this, MainFour_2B_ControlActivity.class); + } else if (Device.TYPE_3A.equals(type)) { + i.setClass(NewBindDeviceActivity.this, MainHot_3A_ControlActivity.class); + } else if (Device.TYPE_2F.equals(type)) { + i.setClass(NewBindDeviceActivity.this, MainSeven_2F_ControlActivity.class); + } else if (Device.TYPE_3F.equals(type)) { + i.setClass(NewBindDeviceActivity.this, MainFour_3F_ControlActivity.class); + } else if (Device.TYPE_4F.equals(type) || Device.TYPE_5F.equals(type)){ + i.setClass(NewBindDeviceActivity.this, MainSix_4F_ControlActivity.class); + } else { + if (controlAmount == null) {//如果控制器返回空 则默认给三控的页面 + i.setClass(NewBindDeviceActivity.this, MainThreeControlActivity.class); + } else { + i.setClass(NewBindDeviceActivity.this, MainThreeControlActivity.class); + switch (controlAmount) { + case 0: { + i.setClass(NewBindDeviceActivity.this, MainZeroControlActivity.class); + break; + } + case 2: { + i.setClass(NewBindDeviceActivity.this, MainTwoControlActivity.class); + break; + } + case 3: { + i.setClass(NewBindDeviceActivity.this, MainThreeControlActivity.class); + break; + } + case 4: { + if (timerAmount == 6) { // 可丽爱 + i.setClass(NewBindDeviceActivity.this, MainFiveControlActivity.class); + } else {//4控 + i.setClass(NewBindDeviceActivity.this, MainFourControlActivity.class); + } + break; + } + case 5: { + if (6 == timerAmount) {//5控六定时器 询多页面 + i.setClass(NewBindDeviceActivity.this, MainSixControlActivity.class); + } + break; + } + case 8: { + i.setClass(NewBindDeviceActivity.this, MainEightControlActivity.class); + break; + } + default: { + i.setClass(NewBindDeviceActivity.this, MainThreeControlActivity.class); + break; + } + } + } + } + } + } catch (Exception e) { + i.setClass(NewBindDeviceActivity.this, MainThreeControlActivity.class); + } + i.putExtra(BaseGradeActivity.BINDDEVICE, true);//绑定成功增加经验 + startActivity(i); + AnimationUtil.startAnimation(NewBindDeviceActivity.this); + finish(); + } + private Activity act; + private ConnectDevice connectDevice; + private boolean isContinue = true; + public class ConnectDevice extends CountDownTimer { + + public ConnectDevice(long millisInFuture, long countDownInterval) { + super(millisInFuture, countDownInterval); + } + + @Override + public void onTick(long millisUntilFinished) { + long sum = millisUntilFinished / 1000 % 2; + if (sum == 0) { + if (!act.isFinishing() && isContinue) { + isNetWorkAvailable("www.baidu.com", new Comparable() { + + @Override + public int compareTo(Boolean available) { + if (available) { + // TODO 设备访问Internet正常 + isContinue = false; + connectDevice.cancel(); + doPostBindDevice(); + } + return 0; + } + }); + } + } + } + + @Override + public void onFinish() { + if (isContinue) { +// dismissProgressDialog(); + } + } + } + + public static void isNetWorkAvailable(final String address, final Comparable callback) { + final Handler handler = new Handler() { + + @Override + public void handleMessage(Message msg) { + super.handleMessage(msg); + if (callback != null) { + callback.compareTo(msg.arg1 == 0); + } + } + + }; + new Thread(new Runnable() { + + @Override + public void run() { + Runtime runtime = Runtime.getRuntime(); + Message msg = new Message(); + try { + Process pingProcess = runtime.exec("/system/bin/ping -c 1 " + address); + InputStreamReader isr = new InputStreamReader(pingProcess.getInputStream()); + BufferedReader buf = new BufferedReader(isr); + if (buf.readLine() == null) { + msg.arg1 = -1; + } else { + msg.arg1 = 0; + } + buf.close(); + isr.close(); + } catch (Exception e) { + msg.arg1 = -1; + e.printStackTrace(); + } finally { + runtime.gc(); + handler.sendMessage(msg); + } + } + + }).start(); + } + + private Device deviceObj; + private HttpManager hm = HttpManager.getInstance(); + private boolean deviceIsNull = false;///当服务器返回的设备控制器数和定时器数为null的时候 改变标记的值 不跳转进入主界面 + private int deviceIsNullNum = 0;//循环请求次数 + private CountDownTimer deviceIsNullTimer; + private void doPostBindDevice() { + try { + hm.bindDevice(new HttpListener>() { + private int result; + + @Override + public void success(BaseBean baseBean) { + result = baseBean.result; + if (result == Commons.NetWork.Success) { + deviceObj = baseBean.data; + deviceObj.setMacAddress(device_mac); + /** + //当服务器返回的设备控制器数和定时器数为null的时候 不跳转进入主界面 + */ + if (deviceObj.getControlAmount() == null || deviceObj.getTimerAmount() == null) { + L.i("第一次获取空"); + deviceIsNull = true; + deviceIsNullNum = 0; + startDeviceIsNullTimer();//启动倒计时 + } + } + } + + @Override + public void finish() { + doPostBindDeviceHandler.sendEmptyMessage(result); + } + + @Override + public void error(Exception e, String msg) { + result = Commons.NetWork.ERROR; + } + }, Commons.USER.getUserId(), device_mac); + } catch (Exception e) { + e.printStackTrace(); + } + } + + public void startDeviceIsNullTimer() { + if (deviceIsNullTimer == null) { + deviceIsNullTimer = new CountDownTimer(2000, 1000) { + @Override + public void onTick(long arg0) { + } + + @Override + public void onFinish() { + L.i("重新请求"); + //拿到设备id 去服务器查询 看看是否为空 + try { + hm.getSingleDeviceInf(new HttpListener>() { + private int result; + + @Override + public void success(BaseBean baseBean) { + result = baseBean.result; + deviceObj = baseBean.data; + } + + @Override + public void finish() { + deviceIsNullHandler.sendEmptyMessage(result); + } + + @Override + public void error(Exception e, String msg) { + result = Commons.NetWork.ERROR; + } + }, deviceObj.getDeviceId(), Commons.USER.getUserId()); + } catch (Exception e) { + e.printStackTrace(); + } + } + }; + } + deviceIsNullTimer.start(); + } + + @SuppressLint("HandlerLeak") + Handler doPostBindDeviceHandler = new Handler() { + public void handleMessage(Message msg) { +// dismissProgressDialog(); + switch (msg.what) { + /** + * 1:绑定成功 + 0:绑定失败 + -4:请求验证失败,请重新登陆 + -5:请求被舍弃,未执行 + */ + case Commons.NetWork.Success: + if (deviceIsNull) {//当服务器返回的设备控制器数和定时器数为null的时候 不跳转进入主界面 + return; + } + Commons.DEVICE.add(deviceObj); + try { + sp.putInt(Commons.LoginSPKey.Position, Commons.DEVICE.size() - 1); + Commons.DevicePosition = Commons.DEVICE.size() - 1; + } catch (Exception e) { + } + ToastUtil.show(NewBindDeviceActivity.this, "设备序号" + Commons.DevicePosition + "---" + Commons.DEVICE.size()); + Commons.IS_EventBus = true; + Commons.HAVE_DEVICE = true;//改变判断是否绑定的变量 + Commons.IS_CAMERA = false; + sp.putBoolean(Commons.LoginSPKey.IS_CAMERA, Commons.IS_CAMERA); + Intent i = new Intent(); + try { + Integer controlAmount = Commons.DEVICE.get(Commons.DevicePosition).getControlAmount(); + Integer timerAmount = Commons.DEVICE.get(Commons.DevicePosition).getTimerAmount(); + String type = Commons.DEVICE.get(Commons.DevicePosition).type; + if (Commons.FishKey.On.equals(Commons.DEVICE.get(Commons.DevicePosition).isBlacklist)) {//黑名单 + i.setClass(NewBindDeviceActivity.this, BlackListActivity.class); + } else { + if (Device.TYPE_1C.equals(type)) { + i.setClass(NewBindDeviceActivity.this, MainThree1CControlActivity.class); + } else if (Device.TYPE_AA.equals(type)) { + i.setClass(NewBindDeviceActivity.this, MainFiveControlActivity.class); + } else if (Device.TYPE_BD.equals(type)) { + i.setClass(NewBindDeviceActivity.this, MainFiveBDControlActivity.class); + } else if (Device.TYPE_2A.equals(type)) { + i.setClass(NewBindDeviceActivity.this, MainSix_2A_ControlActivity.class); + } else if (Device.TYPE_2B.equals(type)) { + i.setClass(NewBindDeviceActivity.this, MainFour_2B_ControlActivity.class); + } else if (Device.TYPE_3A.equals(type)) { + i.setClass(NewBindDeviceActivity.this, MainHot_3A_ControlActivity.class); + } else if (Device.TYPE_2F.equals(type)) { + i.setClass(NewBindDeviceActivity.this, MainSeven_2F_ControlActivity.class); + } else if (Device.TYPE_3F.equals(type)) { + i.setClass(NewBindDeviceActivity.this, MainFour_3F_ControlActivity.class); + } else if (Device.TYPE_4F.equals(type) || Device.TYPE_5F.equals(type)){ + i.setClass(NewBindDeviceActivity.this, MainSix_4F_ControlActivity.class); + } else { + if (controlAmount == null) {//如果控制器返回空 则默认给三控的页面 + i.setClass(NewBindDeviceActivity.this, MainThreeControlActivity.class); + } else { + i.setClass(NewBindDeviceActivity.this, MainThreeControlActivity.class); + switch (controlAmount) { + case 0: { + i.setClass(NewBindDeviceActivity.this, MainZeroControlActivity.class); + break; + } + case 2: { + i.setClass(NewBindDeviceActivity.this, MainTwoControlActivity.class); + break; + } + case 3: { + i.setClass(NewBindDeviceActivity.this, MainThreeControlActivity.class); + break; + } + case 4: { + if (timerAmount == 6) { // 可丽爱 + i.setClass(NewBindDeviceActivity.this, MainFiveControlActivity.class); + } else {//4控 + i.setClass(NewBindDeviceActivity.this, MainFourControlActivity.class); + } + break; + } + case 5: { + if (6 == timerAmount) {//5控六定时器 询多页面 + i.setClass(NewBindDeviceActivity.this, MainSixControlActivity.class); + } + break; + } + case 8: { + i.setClass(NewBindDeviceActivity.this, MainEightControlActivity.class); + break; + } + default: { + i.setClass(NewBindDeviceActivity.this, MainThreeControlActivity.class); + break; + } + } + } + } + + + } + } catch (Exception e) { + i.setClass(NewBindDeviceActivity.this, MainThreeControlActivity.class); + } + i.putExtra(BaseGradeActivity.BINDDEVICE, true);//绑定成功增加经验 + ToastUtil.show(NewBindDeviceActivity.this, "绑定设备成功"); + startActivity(i); + AnimationUtil.startAnimation(NewBindDeviceActivity.this); + EventBus.getDefault().post(new ConnectMessageEvent(1, "test")); + finish(); + L.i("===================绑定设备成功=" + device_mac); + break; + case Commons.NetWork.Fail: + ToastUtil.show(NewBindDeviceActivity.this, "绑定设备失败 请重试"); + EventBus.getDefault().post(new ConnectMessageEvent(-1, "fail")); + finish(); + break; + case Commons.NetWork.DEVICETYPEERROR: + ToastUtil.show(NewBindDeviceActivity.this, "设备类型不匹配,请重新选择入口绑定"); + finish(); + break; + case Commons.NetWork.ReLogin: + ToastUtil.show(getApplicationContext(), "请求验证失败 请重新登陆"); + Commons.clean(); + startActivity(new Intent(NewBindDeviceActivity.this, LoadingActivity.class)); + finish(); + break; + case Commons.NetWork.ERROR: + ToastUtil.show(getApplicationContext(), Commons.Text.ERROR); + finish(); + break; + case Commons.NetWork.NotImplemented: + ToastUtil.show(getApplicationContext(), Commons.Text.Unknown); + finish(); + break; + default: + ToastUtil.show(getApplicationContext(), Commons.Text.ServerException); + finish(); + break; + } + } + }; + + @SuppressLint("HandlerLeak") + Handler deviceIsNullHandler = new Handler() { + + + public void handleMessage(Message msg) { + L.i("请求结束"); + switch (msg.what) { + case Commons.NetWork.Success: + if (deviceObj.getControlAmount() == null || deviceObj.getTimerAmount() == null) { + deviceIsNullNum = deviceIsNullNum + 1; + if (deviceIsNullNum < 3) { + startDeviceIsNullTimer(); + } else { + ToastUtil.show(NewBindDeviceActivity.this, "绑定设备失败 请重试"); + } + return; + } + + boolean isSameName = false; + try { + if (Commons.DEVICE != null) { + if (Commons.DEVICE.size() != 0) { + for (int i = 0; i < Commons.DEVICE.size(); i++) { + if (device_mac.equals(Commons.DEVICE.get(i).getMacAddress())) { + sp.putInt(Commons.LoginSPKey.Position, i); + Commons.DevicePosition = i; + isSameName = true; + break; + } + } + } + } + } catch (Exception e) { + } + if (!isSameName) { + Commons.DEVICE.add(deviceObj); + try { + sp.putInt(Commons.LoginSPKey.Position, Commons.DEVICE.size() - 1); + Commons.DevicePosition = Commons.DEVICE.size() - 1; + } catch (Exception e) { + } + } + Commons.IS_EventBus = true; + Commons.HAVE_DEVICE = true;//改变判断是否绑定的变量 + Commons.IS_CAMERA = false; + sp.putBoolean(Commons.LoginSPKey.IS_CAMERA, Commons.IS_CAMERA); + Intent i = new Intent(); + try { + Integer controlAmount = Commons.DEVICE.get(Commons.DevicePosition).getControlAmount(); + Integer timerAmount = Commons.DEVICE.get(Commons.DevicePosition).getTimerAmount(); + String type = Commons.DEVICE.get(Commons.DevicePosition).type; + if (Commons.FishKey.On.equals(Commons.DEVICE.get(Commons.DevicePosition).isBlacklist)) {//黑名单 + i.setClass(NewBindDeviceActivity.this, BlackListActivity.class); + } else { + if (Device.TYPE_1C.equals(type)) { + i.setClass(NewBindDeviceActivity.this, MainThree1CControlActivity.class); + } else if (Device.TYPE_AA.equals(type)) { + i.setClass(NewBindDeviceActivity.this, MainFiveControlActivity.class); + } else if (Device.TYPE_BD.equals(type)) { + i.setClass(NewBindDeviceActivity.this, MainFiveBDControlActivity.class); + } else if (Device.TYPE_2A.equals(type)) { + i.setClass(NewBindDeviceActivity.this, MainSix_2A_ControlActivity.class); + } else if (Device.TYPE_2B.equals(type)) { + i.setClass(NewBindDeviceActivity.this, MainFour_2B_ControlActivity.class); + } else if (Device.TYPE_3A.equals(type)) { + i.setClass(NewBindDeviceActivity.this, MainHot_3A_ControlActivity.class); + } else if (Device.TYPE_2F.equals(type)) { + i.setClass(NewBindDeviceActivity.this, MainSeven_2F_ControlActivity.class); + } else if (Device.TYPE_3F.equals(type)) { + i.setClass(NewBindDeviceActivity.this, MainFour_3F_ControlActivity.class); + } else if (Device.TYPE_4F.equals(type) || Device.TYPE_5F.equals(type)){ + i.setClass(NewBindDeviceActivity.this, MainSix_4F_ControlActivity.class); + } else { + if (controlAmount == null) {//如果控制器返回空 则默认给三控的页面 + i.setClass(NewBindDeviceActivity.this, MainThreeControlActivity.class); + } else { + i.setClass(NewBindDeviceActivity.this, MainThreeControlActivity.class); + switch (controlAmount) { + case 0: { + i.setClass(NewBindDeviceActivity.this, MainZeroControlActivity.class); + break; + } + case 2: { + i.setClass(NewBindDeviceActivity.this, MainTwoControlActivity.class); + break; + } + case 3: { + i.setClass(NewBindDeviceActivity.this, MainThreeControlActivity.class); + break; + } + case 4: { + if (timerAmount == 6) { // 可丽爱 + i.setClass(NewBindDeviceActivity.this, MainFiveControlActivity.class); + } else {//4控 + i.setClass(NewBindDeviceActivity.this, MainFourControlActivity.class); + } + break; + } + case 5: { + if (6 == timerAmount) {//5控六定时器 询多页面 + i.setClass(NewBindDeviceActivity.this, MainSixControlActivity.class); + } + break; + } + case 8: { + i.setClass(NewBindDeviceActivity.this, MainEightControlActivity.class); + break; + } + default: { + i.setClass(NewBindDeviceActivity.this, MainThreeControlActivity.class); + break; + } + } + } + } + + + } + } catch (Exception e) { + i.setClass(NewBindDeviceActivity.this, MainThreeControlActivity.class); + } + i.putExtra(BaseGradeActivity.BINDDEVICE, true);//绑定成功增加经验 + ToastUtil.show(NewBindDeviceActivity.this, "绑定设备成功"); + startActivity(i); + AnimationUtil.startAnimation(NewBindDeviceActivity.this); + finish(); + L.i("===================绑定设备成功=" + device_mac); + break; + case Commons.NetWork.ERROR: + ToastUtil.show(NewBindDeviceActivity.this, Commons.Text.ERROR); + break; + case Commons.NetWork.Fail: + ToastUtil.show(NewBindDeviceActivity.this, Commons.Text.Repat); + break; + default: + ToastUtil.show(NewBindDeviceActivity.this, Commons.Text.ServerException); + break; + } + } + }; + + /** + * @param + * @Description: 加载进度条对话框 返回键可以取消对话框 + * @author Jacky dada + * @date 2015-9-4 上午9:24:21 + */ + + private ProgressDialog myProgressDialogCancelble; + protected void showProgressDialogCancelble(String msg) { + if (myProgressDialogCancelble == null) { + myProgressDialogCancelble = new ProgressDialog(this, ProgressDialog.THEME_HOLO_LIGHT); + myProgressDialogCancelble.setProgressStyle(ProgressDialog.STYLE_SPINNER); + myProgressDialogCancelble.setMessage(msg); + myProgressDialogCancelble.setIndeterminate(true); + myProgressDialogCancelble.setCancelable(false);//返回键可以取消 + } + myProgressDialogCancelble.show(); + } + + protected void setMessage(String msg) { + if (myProgressDialogCancelble == null) { + myProgressDialogCancelble.setMessage(msg); + } + } + + /** + * @param + * @Description: 隐藏进度条对话框 + * @author Jacky dada + * @date 2015-9-4 上午9:24:04 + */ + protected void dismissProgressDialogCancelble() { + if (myProgressDialogCancelble != null) { + myProgressDialogCancelble.dismiss(); + myProgressDialogCancelble = null; + } + } + + List deviceList; + + @SuppressLint("MissingPermission") + private void findConencted(){ + deviceList = BleManager.getInstance().getAllConnectedDevice(); + if (deviceList!=null && deviceList.size()>0){ + for (BleDevice item:deviceList){ + if (item!=null){ + L.i("jjia-----------"+item.getDevice().getName()); + } + } + + }else { + L.i("jjia--------没有连接的蓝牙---"); + } + } } \ No newline at end of file diff --git a/iFish7/src/main/java/com/ifish/basebean/EventBean.java b/iFish7/src/main/java/com/ifish/basebean/EventBean.java new file mode 100644 index 000000000..ccd5b8da4 --- /dev/null +++ b/iFish7/src/main/java/com/ifish/basebean/EventBean.java @@ -0,0 +1,11 @@ +package com.ifish.basebean; + +public class EventBean { + + public String name; + + public EventBean(String name){ + this.name = name; + } + +} diff --git a/iFish7/src/main/java/com/ifish/baseclass/BaseApplication.java b/iFish7/src/main/java/com/ifish/baseclass/BaseApplication.java index 51a242b89..8f97cfe35 100644 --- a/iFish7/src/main/java/com/ifish/baseclass/BaseApplication.java +++ b/iFish7/src/main/java/com/ifish/baseclass/BaseApplication.java @@ -29,6 +29,8 @@ import com.alibaba.sdk.android.push.PushControlService; import com.alibaba.sdk.android.push.huawei.HuaWeiRegister; import com.alibaba.sdk.android.push.noonesdk.PushServiceFactory; import com.alibaba.sdk.android.push.register.MiPushRegister; +import com.clj.fastble.BleManager; +import com.clj.fastble.scan.BleScanRuleConfig; import com.ifish.activity.BuildConfig; import com.ifish.utils.ImageDownLoader; import com.ifish.utils.KVUtil; @@ -43,6 +45,7 @@ import com.umeng.commonsdk.UMConfigure; import com.umeng.socialize.PlatformConfig; import java.security.SecureRandom; +import java.util.UUID; import java.util.concurrent.TimeUnit; import javax.net.ssl.HostnameVerifier; @@ -77,7 +80,7 @@ public class BaseApplication extends MultiDexApplication { public static String BASE = "https://app.ifish7.cn/";//正式环境 接口访问地址 // public static String BASE = "http://139.196.24.156:7080/";//测试环境 接口访问地址 public static String BASE_URL = BASE + "api/";// 接口URL - + public static final String SERVICE_UUID = "000000ff-0000-1000-8000-00805f9b34fb"; @Override public void onCreate() { super.onCreate(); @@ -94,6 +97,18 @@ public class BaseApplication extends MultiDexApplication { //初始化MMKV // KVUtil.init(this); initPicasso(); + + BleManager.getInstance().init(this); + + UUID[] uuids = {UUID.fromString(SERVICE_UUID)}; + BleScanRuleConfig scanRuleConfig = new BleScanRuleConfig.Builder() + .setServiceUuids(uuids) // 只扫描指定的服务的设备,可选 +// .setDeviceName(true, names) // 只扫描指定广播名的设备,可选 +// .setDeviceMac(mac) // 只扫描指定mac的设备,可选 +// .setAutoConnect(isAutoConnect) // 连接时的autoConnect参数,可选,默认false + .setScanTimeOut(20000) // 扫描超时时间,可选,默认10秒;小于等于0表示不限制扫描时间 + .build(); + BleManager.getInstance().initScanRule(scanRuleConfig); } /** diff --git a/iFish7/src/main/java/com/ifish/fragment/DeviceFragment.java b/iFish7/src/main/java/com/ifish/fragment/DeviceFragment.java index 5f6788090..c0af81de9 100644 --- a/iFish7/src/main/java/com/ifish/fragment/DeviceFragment.java +++ b/iFish7/src/main/java/com/ifish/fragment/DeviceFragment.java @@ -9,10 +9,13 @@ package com.ifish.fragment; import static android.Manifest.permission.WRITE_EXTERNAL_STORAGE; +import android.annotation.SuppressLint; import android.app.Activity; import android.app.AlertDialog; import android.app.Dialog; import android.app.NotificationManager; +import android.bluetooth.BluetoothDevice; +import android.bluetooth.BluetoothGatt; import android.content.ClipData; import android.content.ClipboardManager; import android.content.Context; @@ -50,10 +53,19 @@ import androidx.appcompat.app.AppCompatActivity; import androidx.core.app.ActivityCompat; import com.bumptech.glide.Glide; +import com.clj.fastble.BleManager; +import com.clj.fastble.callback.BleGattCallback; +import com.clj.fastble.callback.BleMtuChangedCallback; +import com.clj.fastble.callback.BleNotifyCallback; +import com.clj.fastble.callback.BleScanCallback; +import com.clj.fastble.callback.BleWriteCallback; +import com.clj.fastble.data.BleDevice; +import com.clj.fastble.exception.BleException; import com.ifish.activity.BindTwoDeviceActivity; import com.ifish.activity.BlackListActivity; import com.ifish.activity.DeviceInstructionActivity; import com.ifish.activity.InformationListActivity; +import com.ifish.activity.LookFishMineActivity; import com.ifish.activity.MainEightControlActivity; import com.ifish.activity.MainFiveBDControlActivity; import com.ifish.activity.MainFiveControlActivity; @@ -77,6 +89,8 @@ import com.ifish.activity.RecentContactsActivity; import com.ifish.activity.SignActivity; import com.ifish.activity.WebViewMessageActivity; import com.ifish.activity.WebViewTaobaoActivity; +import com.ifish.activity.newbind.ConnectType; +import com.ifish.activity.newbind.NewBindDeviceActivity; import com.ifish.adapter.CameraFragmentAdapter; import com.ifish.adapter.DeviceFragmentAdapter; import com.ifish.adapter.RollViewPagerAdapter; @@ -101,9 +115,15 @@ import com.ifish.geewe.GeeWeUser; import com.ifish.geewe.P2PListener; import com.ifish.geewe.SettingListener; import com.ifish.permission.PermissionHelper; +import com.ifish.tcp.BackFunctionCode7_11; +import com.ifish.tcp.ModelCodec; +import com.ifish.tcp.OrderDeviceConnectModel; +import com.ifish.tcp.OrderModel; import com.ifish.utils.ActivityManager; import com.ifish.utils.AnimationUtil; import com.ifish.utils.AppUtil; +import com.ifish.utils.BLEManger; +import com.ifish.utils.ByteUtil; import com.ifish.utils.Commons; import com.ifish.utils.Commons.LoginSPKey; import com.ifish.utils.Commons.NetWork; @@ -116,6 +136,7 @@ import com.ifish.utils.SPUtil; import com.ifish.utils.ScreenUtil; import com.ifish.utils.ToastUtil; import com.ifish.utils.UnreadCount; +import com.ifish.utils.WifiAdmin; import com.ifish.view.LevelDialog; import com.ifish.view.MyBGARefreshLayout; import com.ifish.view.MyListView; @@ -197,9 +218,9 @@ public class DeviceFragment extends BaseV4Fragment implements ObservableScrollVi private PermissionHelper permissionHelper; String[] permission; - String[] permissionM = new String[]{android.Manifest.permission.CAMERA, android.Manifest.permission.ACCESS_FINE_LOCATION, android.Manifest.permission.READ_EXTERNAL_STORAGE, WRITE_EXTERNAL_STORAGE, android.Manifest.permission.READ_PHONE_STATE}; - - String[] permission13 = new String[]{android.Manifest.permission.CAMERA, android.Manifest.permission.ACCESS_FINE_LOCATION, android.Manifest.permission.READ_PHONE_STATE}; +// String[] permissionM = new String[]{android.Manifest.permission.CAMERA, android.Manifest.permission.ACCESS_FINE_LOCATION, android.Manifest.permission.READ_EXTERNAL_STORAGE, WRITE_EXTERNAL_STORAGE, android.Manifest.permission.READ_PHONE_STATE}; +// +// String[] permission13 = new String[]{android.Manifest.permission.CAMERA, android.Manifest.permission.ACCESS_FINE_LOCATION, android.Manifest.permission.READ_PHONE_STATE}; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, @@ -222,14 +243,9 @@ public class DeviceFragment extends BaseV4Fragment implements ObservableScrollVi adInfos(); initInformation(); - if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) { - permission = permission13; - } else { - permission = permissionM; - } - + permission = AppUtil.getPermissionList(); permissionHelper = new PermissionHelper(DeviceFragment.this, permission, 250); - + initBooth(); return v; } @@ -237,6 +253,8 @@ public class DeviceFragment extends BaseV4Fragment implements ObservableScrollVi permissionHelper.request(new PermissionHelper.PermissionCallback() { @Override public void onPermissionGranted() { + + } @Override @@ -1153,6 +1171,9 @@ public class DeviceFragment extends BaseV4Fragment implements ObservableScrollVi Integer controlAmount = Commons.DEVICE.get(Commons.DevicePosition).getControlAmount(); Integer timerAmount = Commons.DEVICE.get(Commons.DevicePosition).getTimerAmount(); String type = Commons.DEVICE.get(Commons.DevicePosition).type; + + + L.i("jjia----------"+type); if (Commons.FishKey.On.equals(Commons.DEVICE.get(Commons.DevicePosition).isBlacklist)) {//黑名单 i.setClass(getActivity(), BlackListActivity.class); } else { @@ -1877,4 +1898,250 @@ public class DeviceFragment extends BaseV4Fragment implements ObservableScrollVi } firstResult = firstResult + HttpManager.PAGESIZE; } + public static final String SERVICE_UUID = "000000ff-0000-1000-8000-00805f9b34fb"; //蓝牙通讯服务 + public static final String READ_UUID = "0000ff01-0000-1000-8000-00805f9b34fb"; //读特征 + public static final String WRITE_UUID = "0000ff01-0000-1000-8000-00805f9b34fb"; //写特征 + String device_mac=null; + + private void sendBleData(){ + +// String ssid = tvWifiName.getText().toString(); +// String pwd = tvWifiPwd.getText().toString(); + + WifiAdmin wifiAdmin = new WifiAdmin(requireContext()); + String wifissid = wifiAdmin.getSSID(); + L.i("jjia 获取当前连接的wifi:" + wifissid); + wifissid = wifiAdmin.updateSsid(wifissid); + String wifiname = wifissid; + if (TextUtils.isEmpty(wifissid)) { + wifiname = ""; + } else { + if ("0x".equals(wifissid)) {//上次连接过wifi,但是中途断开,则会出现0x + wifiname = ""; + } + } +// tvWifiName.setText(wifiname); + L.i("jjia----------------wifiname="+wifiname); + String pwd = null; + if (!TextUtils.isEmpty(wifiname)) { +// String pwd = KVUtil.getString(wifiname, ""); + pwd = sp.getString(wifiname, ""); + + } + L.i(wifiname+"jjia---------name--1-"+pwd); + + + + OrderDeviceConnectModel model = OrderModel.OrderDeviceConnectModel(wifiname, pwd);//设置正式环境域名 + byte[] data = ModelCodec.enCode(model); + BleManager.getInstance().write(currentDevice, SERVICE_UUID, WRITE_UUID, data,false, new BleWriteCallback() { + @Override + public void onWriteSuccess(int current, int total, byte[] justWrite) { + L.i("jjia-------------ssid 发送"); + } + + @Override + public void onWriteFailure(BleException exception) { + + } + }); + } + + private void checkoutMac(String mac){ + + if (!TextUtils.isEmpty(mac)){ + boolean isSameName = false; + devicePosition = 0; + try { + if (Commons.DEVICE != null) { + if (Commons.DEVICE.size() != 0) { + for (int i = 0; i < Commons.DEVICE.size(); i++) { + if (mac.equals(Commons.DEVICE.get(i).getMacAddress())) { + devicePosition = i; + isSameName = true; + break; + } + } + } + } + } catch (Exception e) { + e.printStackTrace(); + } + + + if (!isSameName){ + L.i("jjia-------------不包含"); + requireActivity().runOnUiThread(new Runnable() { + @Override + public void run() { + // 检测页面 + AlertDialog.Builder dialog = new AlertDialog.Builder(requireContext(), AlertDialog.THEME_HOLO_LIGHT); + dialog.setCancelable(true); + dialog.setTitle("提示"); + dialog.setMessage("发现一个新设备是否去添加"); + dialog.setNegativeButton("取消", new DialogInterface.OnClickListener() { + @Override + public void onClick(DialogInterface arg0, int arg1) { + arg0.dismiss(); + } + }); + dialog.setPositiveButton("确定", (dialog1, which) -> { + dialog1.dismiss(); + Intent intent = new Intent(); + intent.setClass(requireActivity(), NewBindDeviceActivity.class); + intent.putExtra("title", "连接水族箱"); + intent.putExtra("type", "bluetooth"); + intent.putExtra("device", currentDevice); + startActivity(intent); + AnimationUtil.finishAnimation(requireActivity()); + }); + dialog.show(); + } + }); + } + } + } + private void openNotify(){ + BleManager.getInstance().notify(currentDevice, SERVICE_UUID, WRITE_UUID, new BleNotifyCallback() { + @Override + public void onNotifySuccess() { + sendBleData(); + } + + @Override + public void onNotifyFailure(BleException exception) { + dismissProgressDialogCancelble(); + } + + @Override + public void onCharacteristicChanged(byte[] data) { + + if (data!=null && data.length>0){ + int check_code = data[1]; + int length = data[14]; + byte[] dataByte = new byte[length]; + for (int i = 0; i < dataByte.length; i++) { + dataByte[i] = data[i]; + } + + Object object = ModelCodec.deCode(dataByte); + if (object!=null && object instanceof BackFunctionCode7_11){ + BackFunctionCode7_11 model = (BackFunctionCode7_11) object; + device_mac = ByteUtil.bytesToHexString(model.getSrc()); + checkoutMac(device_mac); + + + } else { + } + L.i("jjia-------device_mac-"+device_mac); + } + } + }); + } + private void connectBle(){ + BleManager.getInstance().connect(currentDevice, new BleGattCallback() { + @Override + public void onStartConnect() { + + L.i("jjia---------conne------"); + } + + @Override + public void onConnectFail(BleDevice bleDevice, BleException exception) { + } + + @Override + public void onConnectSuccess(BleDevice bleDevice, BluetoothGatt gatt, int status) { +// ToastUtil.show(NewBindDeviceActivity.this,"蓝牙连接成功"); + BleManager.getInstance().setMtu(bleDevice, 512, new BleMtuChangedCallback() { + @Override + public void onSetMTUFailure(BleException exception) { + } + + @Override + public void onMtuChanged(int mtu) { + openNotify(); + } + }); + } + + @Override + public void onDisConnected(boolean isActiveDisConnected, BleDevice device, BluetoothGatt gatt, int status) { + } + }); + } + private void initBooth(){ + + boolean enable = BleManager.getInstance().isBlueEnable(); + if (enable) { +// BLEManger.getInstance().startDiscovery(true); + BleManager.getInstance().scan(new BleScanCallback() { + @Override + public void onScanFinished(List scanResultList) { + if (currentDevice!=null){ // 扫描结束,有设备 + L.i("jjia---------scan---end-2--"); + connectBle(); + }else { + L.i("jjia---------scan---end--1-"); + } + + } + + @Override + public void onScanStarted(boolean success) { + + } + + @SuppressLint("MissingPermission") + @Override + public void onScanning(BleDevice bleDevice) { + if (bleDevice!=null && bleDevice.getDevice()!=null){ + BluetoothDevice bean = bleDevice.getDevice(); + if (!TextUtils.isEmpty(bean.getName()) && bean.getName().startsWith("ifish")){ + currentDevice = bleDevice; + BleManager.getInstance().cancelScan(); + } + L.i(bean.getName()+"jjia------mac---"+bean.getAddress()); + } + } + }); + } + + } + BleDevice currentDevice; + Boolean lifecycle = true; + public void onEventMainThread(BluetoothDevice event) { + + L.i("jjia---------home---scan---"); + if (BLEManger.getInstance().isHome && event!=null && lifecycle){ // 搜索到蓝牙了 + + // 检测页面 + AlertDialog.Builder dialog = new AlertDialog.Builder(requireContext(), AlertDialog.THEME_HOLO_LIGHT); + dialog.setCancelable(true); + dialog.setTitle("提示"); + dialog.setMessage("发现一个新设备是否去添加"); + dialog.setNegativeButton("取消", new DialogInterface.OnClickListener() { + @Override + public void onClick(DialogInterface arg0, int arg1) { + arg0.dismiss(); + } + }); + dialog.setPositiveButton("确定", (dialog1, which) -> { + dialog1.dismiss(); + Intent intent = new Intent(); + intent.setClass(requireActivity(), NewBindDeviceActivity.class); + intent.putExtra("title", "连接水族箱"); + intent.putExtra("type", "bluetooth"); + startActivity(intent); + AnimationUtil.finishAnimation(requireActivity()); + }); + dialog.show(); + } + } + + @Override + public void onPause() { + super.onPause(); + lifecycle = false; + } } diff --git a/iFish7/src/main/java/com/ifish/utils/AppUtil.java b/iFish7/src/main/java/com/ifish/utils/AppUtil.java index d56620565..f6e15768d 100644 --- a/iFish7/src/main/java/com/ifish/utils/AppUtil.java +++ b/iFish7/src/main/java/com/ifish/utils/AppUtil.java @@ -1,13 +1,20 @@ package com.ifish.utils; +import android.bluetooth.BluetoothAdapter; +import android.bluetooth.BluetoothManager; import android.content.ComponentName; +import android.content.Context; import android.content.Intent; import android.net.Uri; import android.os.Build; +import android.util.Log; import androidx.activity.ComponentActivity; import androidx.appcompat.app.AppCompatActivity; +import java.util.ArrayList; +import java.util.List; + public class AppUtil { @@ -141,4 +148,62 @@ public class AppUtil { toPermission(context); } } + + /** + * 检测手机是否支持4.0蓝牙 + * @param context 上下文 + * @return true--支持4.0 false--不支持4.0 + */ + private boolean checkBle(Context context){ + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) { //API 18 Android 4.3 + BluetoothManager bluetoothManager = (BluetoothManager) context.getSystemService(Context.BLUETOOTH_SERVICE); + if(bluetoothManager == null){ + return false; + } + BluetoothAdapter bluetooth4Adapter = bluetoothManager.getAdapter(); //BLUETOOTH权限 + if(bluetooth4Adapter == null){ + return false; + }else{ + L.i("该设备支持蓝牙4.0"); + return true; + } + }else{ + return false; + } + } + + + public static String [] getPermissionList(){ + List perList = new ArrayList<>(); + perList.add(android.Manifest.permission.CAMERA); + perList.add(android.Manifest.permission.ACCESS_FINE_LOCATION); + perList.add(android.Manifest.permission.READ_PHONE_STATE); + perList.add(android.Manifest.permission.BLUETOOTH); + perList.add(android.Manifest.permission.ACCESS_COARSE_LOCATION); + perList.add(android.Manifest.permission.ACCESS_FINE_LOCATION); + + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) { + perList.add(android.Manifest.permission.READ_MEDIA_IMAGES); + perList.add(android.Manifest.permission.READ_MEDIA_VIDEO); + perList.add(android.Manifest.permission.BLUETOOTH_SCAN); + perList.add(android.Manifest.permission.BLUETOOTH_ADVERTISE); + perList.add(android.Manifest.permission.BLUETOOTH_CONNECT); + } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S){ + perList.add(android.Manifest.permission.BLUETOOTH_SCAN); + perList.add(android.Manifest.permission.BLUETOOTH_ADVERTISE); + perList.add(android.Manifest.permission.BLUETOOTH_CONNECT); + perList.add(android.Manifest.permission.READ_EXTERNAL_STORAGE); + perList.add(android.Manifest.permission.WRITE_EXTERNAL_STORAGE); + }else { + perList.add(android.Manifest.permission.READ_EXTERNAL_STORAGE); + perList.add(android.Manifest.permission.WRITE_EXTERNAL_STORAGE); + } + int size = perList.size(); + String [] permissions = new String[size]; + + for (int i = 0;i" + bluetoothDevice.getAddress()+"---"+rssi); + + } +// L.d(bluetoothDevice.getName() + "--jjia---toher>" + bluetoothDevice.getAddress()+"---"+rssi); +// BLEDevice bleDevice = new BLEDevice(bluetoothDevice,rssi); +// if(onDeviceSearchListener != null){ +// onDeviceSearchListener.onDeviceFound(bleDevice); //扫描到设备回调 +// } + } + }; + + @SuppressLint("MissingPermission") + public void stopScan(){ + if (bluetoothAdapter!=null){ + bluetoothAdapter.stopLeScan(leScanCallback); + } + } + + @SuppressLint("MissingPermission") + public void connect(AppCompatActivity activity){ + if (currentDevice!=null){ + currentDevice.connectGatt(activity,false,bluetoothGattCallback); + } + + } + + //连接/通讯结果回调 + @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR2) + private BluetoothGattCallback bluetoothGattCallback = new BluetoothGattCallback() { + //连接状态回调-连接成功/断开连接 + @SuppressLint("MissingPermission") + @Override + public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) { + super.onConnectionStateChange(gatt, status, newState); + L.d("jjia-----status:" + status); + L.d("jjia------newState:" + newState); + // GATT的链接状态回调 + switch (newState){ + case BluetoothGatt.STATE_CONNECTED: + L.d("jjia----蓝牙连接成功"); + gatt.discoverServices(); // 去发现服务 + break; + + case BluetoothGatt.STATE_DISCONNECTED: + //青空系统缓存 + ClsUtils.refreshDeviceCache(gatt); + L.d("jjia----蓝牙连接失败"); + gatt.close();//断开连接释放连接 + + if (status == 133){ + L.d("jjia----无法连接"); + }else if (status == 62){ + L.d("jjia----连接成功服务没有发现"); + }else if(status ==0){ + L.d("jjia----0正常断开 回调"); + }else if(status ==8){ + L.d("jjia----距离太远或者无法供电而断开"); + } + break; + + case BluetoothGatt.STATE_CONNECTING: + L.d("jjia----正在连接中。。。。。"); + break; + + case BluetoothGatt.STATE_DISCONNECTING: + L.d("jjia----正在断开中。。。。。"); + break; + } + BluetoothDevice bluetoothDevice = gatt.getDevice(); + L.d("jjia连接的设备:" + bluetoothDevice.getName() + " " + bluetoothDevice.getAddress()); + +// isConnectIng = false; +// //移除连接超时 +// mHandler.removeCallbacks(connectOutTimeRunnable); +// +// if(newState == BluetoothGatt.STATE_CONNECTED){ +// L.d("jjia连接成功"); +// //连接成功去发现服务 +// gatt.discoverServices(); +// //设置发现服务超时时间 +// mHandler.postDelayed(serviceDiscoverOutTimeRunnable,MAX_CONNECT_TIME); +// +// if(onBleConnectListener != null){ +// onBleConnectListener.onConnectSuccess(gatt,bluetoothDevice,status); //连接成功回调 +// } +// }else if(newState == BluetoothGatt.STATE_DISCONNECTED) { +// //清空系统缓存 +// ClsUtils.refreshDeviceCache(gatt); +// Log.e(TAG, "断开连接status:" + status); +// gatt.close(); //断开连接释放连接 +// +// if(status == 133){ +// //无法连接 +// if(onBleConnectListener != null){ +// gatt.close(); +// onBleConnectListener.onConnectFailure(gatt,bluetoothDevice,"连接异常!",status); //133连接异常 异常断开 +// L.d("jjia连接失败status:" + status + " " + bluetoothDevice.getAddress()); +// } +// }else if(status == 62){ +// //成功连接没有发现服务断开 +// if(onBleConnectListener != null){ +// gatt.close(); +// onBleConnectListener.onConnectFailure(gatt,bluetoothDevice,"连接成功服务未发现断开!",status); //62没有发现服务 异常断开 +// L.d("jjia连接成功服务未发现断开status:" + status); +// } +// +// }else if(status == 0){ +// if(onBleConnectListener != null){ +// onBleConnectListener.onDisConnectSuccess(gatt,bluetoothDevice,status); //0正常断开 回调 +// } +// }else if(status == 8){ +// //因为距离远或者电池无法供电断开连接 +// // 已经成功发现服务 +// if(onBleConnectListener != null){ +// onBleConnectListener.onDisConnectSuccess(gatt,bluetoothDevice,status); //8断电断开 回调 +// } +// }else if(status == 34){ +// if(onBleConnectListener != null){ +// onBleConnectListener.onDisConnectSuccess(gatt,bluetoothDevice,status); //34断开 +// } +// }else { +// //其它断开连接 +// if(onBleConnectListener != null){ +// onBleConnectListener.onDisConnectSuccess(gatt,bluetoothDevice,status); //其它断开 +// } +// } +// }else if(newState == BluetoothGatt.STATE_CONNECTING){ +// L.d("jjia正在连接..."); +// if(onBleConnectListener != null){ +// onBleConnectListener.onConnecting(gatt,bluetoothDevice); //正在连接回调 +// } +// }else if(newState == BluetoothGatt.STATE_DISCONNECTING){ +// L.d("jjia正在断开..."); +// if(onBleConnectListener != null){ +// onBleConnectListener.onDisConnecting(gatt,bluetoothDevice); //正在断开回调 +// } +// } + } + + + + + ///////////////////////////////////////// 打开通知 ////////////////////////////////////////// + + /** + * 设置读特征接收通知 + * @param enable 为true打开通知 + * @param gatt 连接 + * @param characteristic 特征 + */ + @SuppressLint("MissingPermission") + public void enableNotification(boolean enable, BluetoothGatt gatt, BluetoothGattCharacteristic characteristic){ + if(gatt == null){ + L.i("jjia------enableNotification-->gatt == null"); + return; + } + if(characteristic == null){ + L.i("jjia------enableNotification-->characteristic == null"); + return; + } + //这一步必须要有,否则接收不到通知 + gatt.setCharacteristicNotification(characteristic,enable); + } + //发现服务 + //获取GATT服务发现后的回调 + @SuppressLint("MissingPermission") + @Override + public void onServicesDiscovered(BluetoothGatt gatt, int status) { + super.onServicesDiscovered(gatt, status); + + if (status == BluetoothGatt.GATT_SUCCESS){ + + mGatt = gatt; + + L.i("jjia------GATT_SUCCESS---services"); //服务发现 + + if (gatt.getServices()!=null){ + L.i("jjia-----find---services"+gatt.getServices().size()); //服务发现 + for (BluetoothGattService bluetoothGattService : gatt.getServices()) { + if (bluetoothGattService!=null ){ + String UID = bluetoothGattService.getUuid().toString(); + if (!TextUtils.isEmpty(UID) && SERVICE_UUID.equals(UID)){ + service = bluetoothGattService; + L.i("jjia------Service_UUID:" + bluetoothGattService.getUuid()); // 我们可以遍历到该蓝牙设备的全部Service对象。然后通过比较Service的UUID,我们可以区分该服务是属于什么业务的 + for (BluetoothGattCharacteristic characteristic : bluetoothGattService.getCharacteristics()) { + L.i("jjia------characteristic-UUID:" + characteristic.getUuid()); + if (characteristic!=null && !TextUtils.isEmpty(characteristic.getUuid().toString()) && WRITE_UUID.equals(characteristic.getUuid().toString())){ + + write = characteristic; + read = characteristic; + + //打开读通知 + enableNotification(true, gatt, read); + + //重点中重点,需要重新设置 + List descriptors = write.getDescriptors(); + for (BluetoothGattDescriptor descriptor : descriptors) { + descriptor.setValue(BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE); + gatt.writeDescriptor(descriptor); + } + } + } + } + + } + + + EventBean eventBean = new EventBean("blue_ok"); + EventBus.getDefault().post(eventBean); +// +// if (SERVICE_UUID.equals(bluetoothGattService.getUuid().toString())) { +// +// for (BluetoothGattCharacteristic characteristic : bluetoothGattService.getCharacteristics()) { +// L.i("jjia------characteristic-UUID:" + characteristic.getUuid()); +//// prepareBroadcastDataNotify(gatt, characteristic); //给满足条件的属性配置上消息通知 +// } +// return;//结束循环操作 +// } + } + + + }else { + L.i("jjia------no---services"); //服务发现 + } + + } + //移除发现服务超时 +// mHandler.removeCallbacks(serviceDiscoverOutTimeRunnable); +// L.d("jjia移除发现服务超时"); +// +// L.d("jjia发现服务"); +// +// //配置服务信息 +// if(setupService(gatt,serviceUUID,readUUID,writeUUID)){ +// if(onBleConnectListener != null){ +// onBleConnectListener.onServiceDiscoverySucceed(gatt,gatt.getDevice(),status); //成功发现服务回调 +// } +// }else{ +// if(onBleConnectListener != null){ +// onBleConnectListener.onServiceDiscoveryFailed(gatt,gatt.getDevice(),"获取服务特征异常"); //发现服务失败回调 +// } +// } + } + + @Override + public void onCharacteristicRead(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status) { + super.onCharacteristicRead(gatt, characteristic, status); + L.d("jjia-------------读status: " + status); + } + + //向蓝牙设备写入数据结果回调 + @Override + public void onCharacteristicWrite(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status) { + super.onCharacteristicWrite(gatt, characteristic, status); + + + byte [] bb = characteristic.getValue(); + L.i(characteristic.getUuid()+"jjia---------------向蓝牙设备写入数据结果回调--"+new String(bb)); + L.i(status+"jjia---------------向蓝牙设备写入数据结果回调--"+BluetoothGatt.GATT_SUCCESS); +// if(characteristic.getValue() == null){ +// L.d("jjiacharacteristic.getValue() == null"); +// return; +// } +// //将收到的字节数组转换成十六进制字符串 +// String msg = TypeConversion.bytes2HexString(characteristic.getValue(),characteristic.getValue().length); +// if(status == BluetoothGatt.GATT_SUCCESS){ +// //写入成功 +// L.d("jjia写入成功:" + msg); +// if(onBleConnectListener != null){ +// onBleConnectListener.onWriteSuccess(gatt,gatt.getDevice(),characteristic.getValue()); //写入成功回调 +// } +// +// }else if(status == BluetoothGatt.GATT_FAILURE){ +// //写入失败 +// L.d("jjia写入失败:" + msg); +// if(onBleConnectListener != null){ +// onBleConnectListener.onWriteFailure(gatt,gatt.getDevice(),characteristic.getValue(),"写入失败"); //写入失败回调 +// } +// }else if(status == BluetoothGatt.GATT_WRITE_NOT_PERMITTED){ +// //没有权限 +// L.d("jjia没有权限!"); +// } + } + + //读取蓝牙设备发出来的数据回调 + @Override + public void onCharacteristicChanged(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic) { + super.onCharacteristicChanged(gatt, characteristic); + + //接收数据 + byte[] bytes = characteristic.getValue(); + + L.i(characteristic.getUuid()+"jjia---------------读取蓝牙设备发出来的数据回调--"); +// Log.w("TAG","收到数据str:" + TypeConversion.bytes2HexString(bytes,bytes.length)); +// if(onBleConnectListener != null){ +// onBleConnectListener.onReceiveMessage(gatt,gatt.getDevice(),characteristic,characteristic.getValue()); //接收数据回调 +// } + } + + @Override + public void onDescriptorRead(BluetoothGatt gatt, BluetoothGattDescriptor descriptor, int status) { + super.onDescriptorRead(gatt, descriptor, status); + } + + @Override + public void onDescriptorWrite(BluetoothGatt gatt, BluetoothGattDescriptor descriptor, int status) { + super.onDescriptorWrite(gatt, descriptor, status); + } + + @Override + public void onReliableWriteCompleted(BluetoothGatt gatt, int status) { + super.onReliableWriteCompleted(gatt, status); + L.d("jjiaonReliableWriteCompleted"); + } + + @Override + public void onReadRemoteRssi(BluetoothGatt gatt, int rssi, int status) { + super.onReadRemoteRssi(gatt, rssi, status); +// if(status == BluetoothGatt.GATT_SUCCESS){ +// L.d("jjia读取RSSI值成功,RSSI值:" + rssi + ",status" + status); +// if(onBleConnectListener != null){ +// onBleConnectListener.onReadRssi(gatt,rssi,status); //成功读取连接的信号强度回调 +// } +// }else if(status == BluetoothGatt.GATT_FAILURE){ +// L.d("jjia读取RSSI值失败,status:" + status); +// } + } + + //修改MTU值结果回调 + @Override + public void onMtuChanged(BluetoothGatt gatt, int mtu, int status) { + super.onMtuChanged(gatt, mtu, status); + ///设置mtu值,即bluetoothGatt.requestMtu()时触发,提示该操作是否成功 +// if(status == BluetoothGatt.GATT_SUCCESS){ //设置MTU成功 +// //MTU默认取的是23,当收到 onMtuChanged 后,会根据传递的值修改MTU,注意由于传输用掉3字节,因此传递的值需要减3。 +// //mtu - 3 +// L.d("jjia设置MTU成功,新的MTU值:" + (mtu-3) + ",status" + status); +// if(onBleConnectListener != null){ +// onBleConnectListener.onMTUSetSuccess("设置后新的MTU值 = " + (mtu-3) + " status = " + status,mtu - 3); //MTU设置成功 +// } +// +// }else if(status == BluetoothGatt.GATT_FAILURE){ //设置MTU失败 +// L.d("jjia设置MTU值失败:" + (mtu-3) + ",status" + status); +// if(onBleConnectListener != null){ +// onBleConnectListener.onMTUSetFailure("设置MTU值失败:" + (mtu-3) + " status:" + status); //MTU设置失败 +// } +// } + + } + }; + + public static final String SERVICE_UUID = "000000ff-0000-1000-8000-00805f9b34fb"; //蓝牙通讯服务 + public static final String READ_UUID = "0000ff01-0000-1000-8000-00805f9b34fb"; //读特征 + public static final String WRITE_UUID = "0000ff01-0000-1000-8000-00805f9b34fb"; //写特征 + BluetoothGattService service; + BluetoothGattCharacteristic read; + BluetoothGattCharacteristic write; + BluetoothGatt mGatt ; + + @SuppressLint("MissingPermission") + public void sendData(byte [] data){ + if (write!=null){ + L.d("jjia------send--------"); + write.setValue(data); + mGatt.writeCharacteristic(write); + } + + } +//00002b29-0000-1000-8000-00805f9b34fb // 写 + + + /** + * 设置读特征接收通知 + * @param enable 为true打开通知 + * @param gatt 连接 + * @param characteristic 特征 + */ + @SuppressLint("MissingPermission") + @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR2) + public void enableNotification(boolean enable, BluetoothGatt gatt, BluetoothGattCharacteristic characteristic){ + if(gatt == null){ + L.i("jjia---------enableNotification-->gatt == null"); + return; + } + if(characteristic == null){ + L.i("jjia--------enableNotification-->characteristic == null"); + return; + } + //这一步必须要有,否则接收不到通知 + gatt.setCharacteristicNotification(characteristic,enable); + } + + + public static final String CLIENT_CHARACTERISTIC_CONFIG = "00002902-0000-1000-8000-00805f9b34fb"; + + @SuppressLint("MissingPermission") + private void setAutoReceiveData(BluetoothGatt gatt,BluetoothGattService linkLossService,BluetoothGattCharacteristic data,BluetoothGattDescriptor defaultDescriptor) { + try { +// BluetoothGattService linkLossService = gatt.getService(SERVICE_UUID); +// BluetoothGattCharacteristic data = linkLossService.getCharacteristic(CHARACTERISTIC_UUID); +// BluetoothGattDescriptor defaultDescriptor = data.getDescriptor(UUID.fromString(CLIENT_CHARACTERISTIC_CONFIG)); + if (null != defaultDescriptor) { + defaultDescriptor.setValue(BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE); + gatt.writeDescriptor(defaultDescriptor); + } + gatt.setCharacteristicNotification(data, true); + } catch (Exception e) { +// BleLogUtils.appendLog("setAutoReceiveData:" + e.getMessage()); + } + } +} diff --git a/iFish7/src/main/java/com/ifish/utils/BlueToothUtil.kt b/iFish7/src/main/java/com/ifish/utils/BlueToothUtil.kt index 86503c099..ed084529f 100644 --- a/iFish7/src/main/java/com/ifish/utils/BlueToothUtil.kt +++ b/iFish7/src/main/java/com/ifish/utils/BlueToothUtil.kt @@ -1,27 +1,20 @@ package com.ifish.utils import android.annotation.SuppressLint -import android.bluetooth.BluetoothDevice -import java.util.UUID +import android.bluetooth.BluetoothAdapter +import android.content.Context +import android.content.Intent class BlueToothUtil { companion object{ - @SuppressLint("MissingPermission") - fun boundDevice(devicex: BluetoothDevice?,ii:String){ - var method = BluetoothDevice::class.java.getMethod("createBond") - method.invoke(devicex) - var clientSocket = devicex!!.createRfcommSocketToServiceRecord(UUID.fromString(ii)) - clientSocket.connect() - } + @JvmStatic @SuppressLint("MissingPermission") - fun boundDevice2(devicex: BluetoothDevice?){ - devicex - var method = BluetoothDevice::class.java.getMethod("createBond") - method.invoke(devicex) - var clientSocket = devicex!!.createRfcommSocketToServiceRecord(UUID.randomUUID()) - clientSocket.connect() + fun openBlueTooth(context: Context){ + L.i("jjia-----提示用户去打开手机蓝牙") + val enableBtIntent = Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE) + context.startActivity(enableBtIntent) } } } \ No newline at end of file diff --git a/iFish7/src/main/res/layout/activity_bluetooth.xml b/iFish7/src/main/res/layout/activity_bluetooth.xml index e809c9357..f938aacc4 100644 --- a/iFish7/src/main/res/layout/activity_bluetooth.xml +++ b/iFish7/src/main/res/layout/activity_bluetooth.xml @@ -14,11 +14,59 @@ android:id="@+id/tv_name" android:layout_width="match_parent" android:layout_height="wrap_content"/> - +