diff --git a/app/libs/device-release.aar b/app/libs/device-release.aar index 326dbae..11e3129 100644 Binary files a/app/libs/device-release.aar and b/app/libs/device-release.aar differ diff --git a/app/src/main/AndroidManifest.xml b/app/src/main/AndroidManifest.xml index 2ff83d9..2326241 100644 --- a/app/src/main/AndroidManifest.xml +++ b/app/src/main/AndroidManifest.xml @@ -260,6 +260,20 @@ android:exported="true" android:hardwareAccelerated="true" android:windowSoftInputMode="adjustUnspecified|stateHidden" /> + + \ No newline at end of file diff --git a/app/src/main/java/com/project/survey/ui/base/BaseSurveyNewActivity.java b/app/src/main/java/com/project/survey/ui/base/BaseSurveyNewActivity.java index 61c1680..2260f50 100644 --- a/app/src/main/java/com/project/survey/ui/base/BaseSurveyNewActivity.java +++ b/app/src/main/java/com/project/survey/ui/base/BaseSurveyNewActivity.java @@ -216,14 +216,15 @@ public abstract class BaseSurveyNewActivity extends ColorfulActivity implements //激光 if (Device.getInstance().deviceType == DeviceTypeEnum.DEVICE_TYPE_TS) { tsSettingDialogUtils.showTotalStationSettingDialog(); - } else { - startActivity(new Intent(this, SatelliteStatusActivity.class)); } +// else { +// startActivity(new Intent(this, SatelliteStatusActivity.class)); +// } }); - baseSurveyActivityUtils.activityBaseSurveyBinding.llRtkStatus.setOnClickListener(v -> { - DeviceConnectUtil.startDeviceConnected(this, baseSurveyActivityUtils.activityBaseSurveyBinding); - }); +// baseSurveyActivityUtils.activityBaseSurveyBinding.llRtkStatus.setOnClickListener(v -> { +// DeviceConnectUtil.startDeviceConnected(this, baseSurveyActivityUtils.activityBaseSurveyBinding); +// }); animUtil = new AnimUtil(); diff --git a/app/src/main/java/com/project/survey/ui/home/InstrumentFragment.kt b/app/src/main/java/com/project/survey/ui/home/InstrumentFragment.kt index 91a31e2..a8e6ad5 100644 --- a/app/src/main/java/com/project/survey/ui/home/InstrumentFragment.kt +++ b/app/src/main/java/com/project/survey/ui/home/InstrumentFragment.kt @@ -8,8 +8,6 @@ import blankj.utilcode.util.AppUtils import com.bingce.device.Device import com.bingce.device.enums.ConnectTypeEnum import com.bingce.device.enums.DeviceTypeEnum -import com.bingce.device.ui.ConnectRtkActivity -import com.bingce.device.ui.ConnectTSActivity import com.bingce.rtk.command.RTK import com.bingce.rtk.config.GnssConfigManager import com.project.survey.R @@ -25,8 +23,10 @@ import com.project.survey.ui.instrument.basestationtranslation.RtkBaseCorrectAct import com.project.survey.ui.instrument.coordinatesystem.BingCeCoordinateSystemActivity import com.project.survey.ui.instrument.mobilestationmode.GnssConfigSetActivity import com.project.survey.ui.instrument.mobilestationmode.base.RtkPointCorrectActivity +import com.project.survey.ui.instrument.rtk.ConnectRtkActivity import com.project.survey.ui.instrument.satellitosis.SatelliteStatusActivity import com.project.survey.ui.instrument.setupstation.InstrumentSetFragmentSetupStationTypeUtils +import com.project.survey.ui.instrument.totalstation.ConnectTSActivity import com.project.survey.util.ActivityNavUtil import com.project.survey.util.SPUtils @@ -64,11 +64,11 @@ class InstrumentFragment : BaseBindingFragment() { override fun initListener() { //全站仪联机 mBinding.itemConnectTotalStation.setOnClickNoRepeatListener { - ConnectTSActivity.start(mContext) + ConnectTSActivity.start() } //RTK联机 mBinding.itemConnectRTK.setOnClickNoRepeatListener { - ConnectRtkActivity.start(this) + ConnectRtkActivity.start() } //卫星状态 mBinding.itemSatelliteStatus.setOnClickNoRepeatListener { @@ -125,7 +125,7 @@ class InstrumentFragment : BaseBindingFragment() { private fun startBaseStationTranslation() { if (!AppUtils.isAppDebug()) { if (Device.getInstance().deviceType == DeviceTypeEnum.DEVICE_TYPE_TS) { - toast(R.string.please_choose_rtk_instrument) + toast("请选择RTK仪器连接后继续") return } if (Device.getInstance().connectType == ConnectTypeEnum.CONNECT_TYPE_PHONE_LOCATION) { diff --git a/app/src/main/java/com/project/survey/ui/instrument/coordinatesystem/fragment/CoordinateSystemContainerFragment.java b/app/src/main/java/com/project/survey/ui/instrument/coordinatesystem/fragment/CoordinateSystemContainerFragment.java index af2bd6c..06a257a 100644 --- a/app/src/main/java/com/project/survey/ui/instrument/coordinatesystem/fragment/CoordinateSystemContainerFragment.java +++ b/app/src/main/java/com/project/survey/ui/instrument/coordinatesystem/fragment/CoordinateSystemContainerFragment.java @@ -25,8 +25,14 @@ import com.bingce.coordlib.util.CoordinateSystemUtil; import com.bingce.data.cache.AbstractCachedObserver; import com.bingce.data.database.CoordinateSystemDb; import com.bingce.data.database.DBQueryConstant; +import com.bingce.data.database.KeyValueDb; +import com.bingce.data.database.ProjectDb; import com.bingce.data.surveyor.designdata.coordinate.CoordinateSystemConstants; import com.bingce.data.surveyor.designdata.coordinate.CoordinateSystemRecord; +import com.bingce.data.surveyor.designdata.kv.KeyValueConstants; +import com.bingce.data.surveyor.designdata.kv.KeyValueRecord; +import com.bingce.data.surveyor.designdata.project.ProjectConstants; +import com.bingce.data.surveyor.designdata.project.ProjectRecord; import com.bingce.device.Device; import com.bingce.device.ui.coordinatesystem.event.UpdateCoordinateSystemEvent; import com.bingce.device.ui.coordinatesystem.fragment.AbstractCoordinateSystemContainerFragment; @@ -39,6 +45,7 @@ import com.bingce.device.ui.coordinatesystem.fragment.GridTransformFragment; import com.bingce.device.ui.coordinatesystem.fragment.ProjectionFragment; import com.bingce.device.ui.utils.CoordSysShareUtil; import com.bingce.dialog.DialogUtils; +import com.bingce.error.BingCeErrorCode; import com.bingce.event.SingleMessageEvent; import com.bingce.surveyorBase.R; import com.bingce.ui.coordinatesystem.PresetCoordinateSystemV2Activity; @@ -197,21 +204,20 @@ public class CoordinateSystemContainerFragment extends AbstractCoordinateSystemC } else { ThreadPoolUtil.execute(() -> { //搜索当前坐标系 -// KeyValueRecord currentProjectConfig = KeyValueDb.getInstance().findData(KeyValueConstants.KEY_CURRENT_PROJECT_ID); -// if (currentProjectConfig == null) { -// BingCeErrorCode.toast(BingCeErrorCode.NO_CURRENT_PROJECT); -// return; -// } -// ProjectRecord currentProjectRecord = ProjectDb.getInstance() -// .rawQueryData(DBQueryConstant.findById(ProjectConstants.DB_NAME, currentProjectConfig.value)); -// if (currentProjectRecord == null) { -// BingCeErrorCode.toast(BingCeErrorCode.NO_FOUND_PROJECT_BY_ID); -// return; -// } -// currentProjectRecord.coordinateSystem = coordinateSystem; -// ProjectDb.getInstance().save(currentProjectRecord); - - // TODO: 2024/8/15 存坐标系 + KeyValueRecord currentProjectConfig = KeyValueDb.getInstance().findData(KeyValueConstants.KEY_CURRENT_PROJECT_ID); + if (currentProjectConfig == null) { + BingCeErrorCode.toast(BingCeErrorCode.NO_CURRENT_PROJECT); + return; + } + // 存坐标系 + ProjectRecord currentProjectRecord = ProjectDb.getInstance() + .rawQueryData(DBQueryConstant.findById(ProjectConstants.DB_NAME, currentProjectConfig.value)); + if (currentProjectRecord == null) { + BingCeErrorCode.toast(BingCeErrorCode.NO_FOUND_PROJECT_BY_ID); + return; + } + currentProjectRecord.coordinateSystem = coordinateSystem; + ProjectDb.getInstance().save(currentProjectRecord); //切换线路 ThreadPoolUtil.executeInMain(success); }); diff --git a/app/src/main/java/com/project/survey/ui/instrument/rtk/ConnectRtkActivity.java b/app/src/main/java/com/project/survey/ui/instrument/rtk/ConnectRtkActivity.java new file mode 100644 index 0000000..154ec3b --- /dev/null +++ b/app/src/main/java/com/project/survey/ui/instrument/rtk/ConnectRtkActivity.java @@ -0,0 +1,1085 @@ +package com.project.survey.ui.instrument.rtk; + +import android.annotation.SuppressLint; +import android.app.Activity; +import android.app.AlertDialog; +import android.bluetooth.BluetoothAdapter; +import android.bluetooth.BluetoothDevice; +import android.content.BroadcastReceiver; +import android.content.Context; +import android.content.DialogInterface; +import android.content.Intent; +import android.content.IntentFilter; +import android.content.SharedPreferences; +import android.os.Build; +import android.os.Bundle; +import android.util.Log; +import android.view.Menu; +import android.view.MenuItem; +import android.view.View; +import android.widget.AdapterView; +import android.widget.ArrayAdapter; +import android.widget.Button; +import android.widget.LinearLayout; +import android.widget.ListView; +import android.widget.Spinner; +import android.widget.TextView; + +import androidx.annotation.NonNull; +import androidx.appcompat.widget.Toolbar; +import androidx.fragment.app.Fragment; +import androidx.preference.PreferenceManager; + +import com.afollestad.materialdialogs.DialogAction; +import com.afollestad.materialdialogs.MaterialDialog; +import com.bingce.AppChannel; +import com.bingce.coordlib.model.Coordinate; +import com.bingce.coordlib.util.CoordUtil; +import com.bingce.device.Device; +import com.bingce.device.enums.ConnectTypeEnum; +import com.bingce.device.enums.DeviceTypeEnum; +import com.bingce.device.service.comm.ble.BleService; +import com.bingce.device.service.comm.emulator.EmulatorService; +import com.bingce.device.service.comm.localgps.LocationService; +import com.bingce.device.service.comm.localgps.NativePositioningService; +import com.bingce.device.service.comm.messenger.QxwzMessengerService; +import com.bingce.device.service.comm.socket.TsSocketService; +import com.bingce.device.service.comm.spp.BTService; +import com.bingce.device.ui.ToolCommDebugActivity; +import com.bingce.device.ui.utils.DeviceUtil; +import com.bingce.event.SingleMessageEvent; +import com.bingce.rtk.command.RTK; +import com.bingce.rtk.command.qxwz.QxwzRTK; +import com.bingce.rtk.enums.RTKEnum; +import com.bingce.rtk.event.RtkCmdSendOverEvent; +import com.bingce.rtk.gnss.Gnss; +import com.bingce.rtk.model.GnssPosition; +import com.bingce.rtk.util.RtkUtil; +import com.bingce.totalstation.TotalStation; +import com.bingce.utils.AppUtil; +import com.bingce.utils.ClipboardUtils; +import com.bingce.utils.ThreadPoolUtil; +import com.bingce.utils.Util; +import com.hjq.permissions.OnPermissionCallback; +import com.hjq.permissions.Permission; +import com.hjq.permissions.XXPermissions; +import com.leon.lib.settingview.LSettingItem; +import com.project.survey.R; + +import org.greenrobot.eventbus.EventBus; +import org.greenrobot.eventbus.Subscribe; +import org.greenrobot.eventbus.ThreadMode; +import org.polaric.colorful.ColorfulActivity; + +import java.lang.reflect.Method; +import java.util.List; +import java.util.Set; + +import blankj.utilcode.util.ActivityUtils; +import blankj.utilcode.util.AppUtils; +import blankj.utilcode.util.ServiceUtils; +import blankj.utilcode.util.ToastUtils; +import blankj.utilcode.util.Utils; +import clj.fastble.BleManager; +import clj.fastble.callback.BleScanCallback; +import clj.fastble.data.BleDevice; +import clj.fastble.data.BleScanState; +import clj.fastble.scan.BleScanner; +import device.ui.Rid; +import device.ui.Rmenu; +import device.ui.Rstring; + +public class ConnectRtkActivity extends ColorfulActivity { + private static final int RC_LOCATION_PERM_SCAN = 128; + private static final int RC_LOCATION_PERM_CONNECT = 129; + private static final int RC_BLUETOOTH_PERM_SCAN = 130; + private static final int RC_BLUETOOTH_PERM_CONNECT = 131; + private static final int REQUEST_ENABLE_BT = 3; + private int currentRequestCode = -1; + private BluetoothAdapter mBtAdapter; + private ArrayAdapter mPairedDevicesArrayAdapter; + private ArrayAdapter mNewDevicesArrayAdapter; + private Toolbar mToolbar; + private LinearLayout layoutPairedDevices; + private LinearLayout layoutNewDevices; + private LinearLayout layoutEmulator; + private Spinner mSpinner1, mSpinner2; + private ListView mPairedListView; + private ListView mNewDevicesListView; + private Button mBtnConnect; + private PublicReceiver publicReceiver; + private TextView mTextViewOneKeyFixAds; + private TextView mTextViewTitleRtkType; + private LSettingItem item_starting_latitude, item_starting_longitude, item_starting_altitude, item_switch_random_direction, item_starting_direction, item_move_speed; + private boolean gnssServerReady = false; + + @Override + protected void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + setContentView(R.layout.activity_connect_rtk); + mToolbar = findViewById(Rid.toolbar()); + layoutPairedDevices = findViewById(Rid.activity_connect_rtk_layout_paired_devices()); + layoutNewDevices = findViewById(Rid.activity_connect_rtk_layout_new_devices()); + layoutEmulator = findViewById(Rid.activity_connect_rtk_layout_emulator()); + mSpinner1 = findViewById(Rid.activity_connect_rtk_spinner_connection_type()); + mSpinner2 = findViewById(Rid.activity_connect_rtk_spinner_rtk_type()); + mPairedListView = findViewById(Rid.activity_connect_rtk_paired_devices()); + mNewDevicesListView = findViewById(Rid.activity_connect_rtk_new_devices()); + mBtnConnect = findViewById(Rid.activity_connect_rtk_btn_connect()); + mTextViewOneKeyFixAds = findViewById(Rid.activity_connect_rtk_tv_one_key_fix_ads()); + mTextViewTitleRtkType = findViewById(Rid.activity_connect_rtk_title_rtk_type()); + item_starting_latitude = findViewById(Rid.activity_connect_rtk_layout_emulator_start_latitude()); + item_starting_longitude = findViewById(Rid.activity_connect_rtk_layout_emulator_start_longitude()); + item_starting_altitude = findViewById(Rid.activity_connect_rtk_layout_emulator_start_altitude()); + item_switch_random_direction = findViewById(Rid.activity_connect_rtk_layout_emulator_switch_random_direction()); + item_starting_direction = findViewById(Rid.activity_connect_rtk_layout_emulator_start_direction()); + item_move_speed = findViewById(Rid.activity_connect_rtk_layout_emulator_speed()); + + setSupportActionBar(mToolbar); + if (getSupportActionBar() != null) getSupportActionBar().setDisplayHomeAsUpEnabled(true); + EventBus.getDefault().register(this); + +// boolean fromOneKeyFix = getIntent().getBooleanExtra("fromOneKeyFix", false); +// if (fromOneKeyFix +// || AppChannel.customChannel == AppChannel.CUSTOM_FJD +// || AppChannel.customChannel == AppChannel.CUSTOM_COMNAV +// || AppChannel.customChannel == AppChannel.CUSTOM_SURVEY_SPACE +// || AppChannel.customChannel == AppChannel.CUSTOM_SURVEY_SPACE_INTERNATIONAL) + mTextViewOneKeyFixAds.setVisibility(View.GONE); + + //当存在公共广播和私有广播时,都要声明,而且:1,先声明公共广播;2,私有action要在公共和私有里都addAction;3,接收是在公共接收器里处理结果的;4,先注销私有,再注销公共;但是会接收到两次广播 + publicReceiver = new PublicReceiver(); + IntentFilter filter = new IntentFilter(); + filter.addAction(BluetoothDevice.ACTION_FOUND);// 当一个设备被发现时,需要注册一个广播 + filter.addAction(BluetoothDevice.ACTION_BOND_STATE_CHANGED);// 千寻蓝牙配对完成 + filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);// 当显示检查完毕的时候,需要注册一个广播 + registerReceiver(publicReceiver, filter); + + // 初始化ArrayAdapter,一个是已经配对的设备,一个是新发现的设备 + mPairedDevicesArrayAdapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_single_choice); + mNewDevicesArrayAdapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_single_choice); + + // 检测并设置已配对的设备ListView + mPairedListView.setAdapter(mPairedDevicesArrayAdapter); + mPairedListView.setChoiceMode(ListView.CHOICE_MODE_SINGLE); + mPairedListView.setOnItemClickListener(new AdapterView.OnItemClickListener() { + @Override + public void onItemClick(AdapterView parent, View view, int position, long id) { + mNewDevicesListView.clearChoices(); + } + }); + + // 检查并设置行发现的蓝牙设备ListView + mNewDevicesListView.setAdapter(mNewDevicesArrayAdapter); + mNewDevicesListView.setChoiceMode(ListView.CHOICE_MODE_SINGLE); + mNewDevicesListView.setOnItemClickListener(new AdapterView.OnItemClickListener() { + @Override + public void onItemClick(AdapterView parent, View view, int position, long id) { + mPairedListView.clearChoices(); + } + }); + + mSpinner1.setAdapter(new ArrayAdapter<>(this, android.R.layout.simple_spinner_dropdown_item, ConnectTypeEnum.getRtkSupportConnectTypeNames())); + mSpinner2.setAdapter(new ArrayAdapter<>(this, android.R.layout.simple_spinner_dropdown_item, RtkUtil.getSupportRTKEnumNames())); + + mSpinner1.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { + @Override + public void onItemSelected(AdapterView parent, View view, int position, long id) { + if (ConnectTypeEnum.getRtkSupportConnectTypes().contains(Device.getInstance().connectType)) { + Device.getInstance().connectType = ConnectTypeEnum.getRtkSupportConnectTypes().get(position); + } else { + Device.getInstance().connectType = ConnectTypeEnum.CONNECT_TYPE_SPP; + } + Util.putPreference("connectType", Device.getInstance().connectType.getValue()); + startService(); + updateBluetoothList(); + } + + @Override + public void onNothingSelected(AdapterView parent) { + + } + }); + + if (ConnectTypeEnum.getRtkSupportConnectTypes().contains(Device.getInstance().connectType)) { + mSpinner1.setSelection(ConnectTypeEnum.getRtkSupportConnectTypes().indexOf(Device.getInstance().connectType)); + } else { + mSpinner1.setSelection(0); + } + + mSpinner2.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { + @Override + public void onItemSelected(AdapterView parent, View view, int position, long id) { + Gnss.getInstance().lastRtkType = RTKEnum.values()[mSpinner2.getSelectedItemPosition()]; + Gnss.getInstance().save(); + + if (RTK.getInstance().getConnectTypeValue() == ConnectTypeEnum.CONNECT_TYPE_BLE.getValue()) { + if (ConnectTypeEnum.getRtkSupportConnectTypes().contains(ConnectTypeEnum.CONNECT_TYPE_BLE)) { + mSpinner1.setSelection(ConnectTypeEnum.getRtkSupportConnectTypes().indexOf(ConnectTypeEnum.CONNECT_TYPE_BLE)); + } else { + mSpinner1.setSelection(0); + } + } else if (RTK.getInstance() instanceof QxwzRTK) { + if (ConnectTypeEnum.getRtkSupportConnectTypes().contains(ConnectTypeEnum.CONNECT_TYPE_QXBT)) { + mSpinner1.setSelection(ConnectTypeEnum.getRtkSupportConnectTypes().indexOf(ConnectTypeEnum.CONNECT_TYPE_QXBT)); + } else { + mSpinner1.setSelection(0); + } + } + + Device.getInstance().deviceType = DeviceTypeEnum.DEVICE_TYPE_RTK; + Device.getInstance().deviceBrand = Gnss.getInstance().lastRtkType.getName(); + SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(ConnectRtkActivity.this); + SharedPreferences.Editor editor = prefs.edit(); + editor.putInt("deviceType", Device.getInstance().deviceType.getValue()); + editor.putString("deviceBrand", Device.getInstance().deviceBrand); + editor.apply(); + } + + @Override + public void onNothingSelected(AdapterView parent) { + + } + }); + + if (AppChannel.customChannel == AppChannel.CUSTOM_SURVEY_SPACE || AppChannel.customChannel == AppChannel.CUSTOM_SURVEY_SPACE_INTERNATIONAL) { + Gnss.getInstance().lastRtkType = RTKEnum.RTK_SURVEY_SPACE; + mSpinner2.setEnabled(false); + mSpinner2.setVisibility(View.GONE); + } else if (AppChannel.customChannel == AppChannel.CUSTOM_FJD) { + Gnss.getInstance().lastRtkType = RTKEnum.RTK_FJD; + mSpinner2.setEnabled(false); + mSpinner2.setVisibility(View.GONE); + } else if (AppChannel.customChannel == AppChannel.CUSTOM_COMNAV) { + Gnss.getInstance().lastRtkType = RTKEnum.RTK_COMNAV; + mSpinner2.setEnabled(false); + mSpinner2.setVisibility(View.GONE); + } + + int index2 = RtkUtil.getSupportRTKEnum().indexOf(Gnss.getInstance().lastRtkType); + if (index2 == -1) index2 = 0; + mSpinner2.setSelection(index2); + +// mTextViewOneKeyFixAds.setOnClickListener(new View.OnClickListener() { +// @Override +// public void onClick(View v) { +// finish(); +// EventBus.getDefault().post(new SingleMessageEvent("start_activity_one_key_fix")); +// } +// }); + + mBtnConnect.setText(Device.getInstance().isDeviceConnected()? "已连接": "连接"); + mBtnConnect.setOnClickListener(new View.OnClickListener() { + @Override + public void onClick(View view) { + cancelScan(); + //如果是从全站仪切换过来的,先停止全站仪的线程 + TotalStation.getInstance().stopAll(); + if (Device.getInstance().isDeviceConnected()) { + ToastUtils.showShort(Rstring.device_has_connected_please_try_after_disconnect()); + } else { + if (Device.getInstance().connectType == ConnectTypeEnum.CONNECT_TYPE_SPP + || Device.getInstance().connectType == ConnectTypeEnum.CONNECT_TYPE_BLE + || Device.getInstance().connectType == ConnectTypeEnum.CONNECT_TYPE_QXBT) { + String checkedInfo; + if (mPairedListView.getCheckedItemPosition() >= 0 && mPairedListView.getCheckedItemPosition() < mPairedDevicesArrayAdapter.getCount()) { + checkedInfo = mPairedDevicesArrayAdapter.getItem(mPairedListView.getCheckedItemPosition()); + } else if (mNewDevicesListView.getCheckedItemPosition() >= 0 && mNewDevicesListView.getCheckedItemPosition() < mNewDevicesArrayAdapter.getCount()) { + checkedInfo = mNewDevicesArrayAdapter.getItem(mNewDevicesListView.getCheckedItemPosition()); + } else { + ToastUtils.showShort(Rstring.please_choose_device_first()); + return; + } + // 得到mac地址 + String[] arr = checkedInfo.split("\n", 0); + if (arr.length != 2) { + return; + } + Device.getInstance().deviceBlueName = arr[0]; + Device.getInstance().deviceMacAddress = arr[1]; + Gnss.getInstance().getDevice().getBlue().setScanName(Device.getInstance().deviceBlueName); + Gnss.getInstance().getDevice().getBlue().setScanAddr(Device.getInstance().deviceMacAddress); + Gnss.getInstance().save(); + + if (DeviceUtil.checkIfNeedGnssServer()) { + if (DeviceUtil.checkIfGnssServerReady(ConnectRtkActivity.this)) {//先检查如果是千寻rtk,是否安装并打开了GnssServier + gnssServerReady = true; + } + } else { + requestLocationPermission(RC_LOCATION_PERM_CONNECT); + } + } else if (Device.getInstance().connectType == ConnectTypeEnum.CONNECT_TYPE_PHONE_LOCATION) { + Device.getInstance().deviceBlueName = getString(Rstring.phone_location()); + Device.getInstance().deviceBrand = getString(Rstring.phone_location()); + requestLocationPermission(RC_LOCATION_PERM_CONNECT); + } else if (Device.getInstance().connectType == ConnectTypeEnum.CONNECT_TYPE_EMULATOR) { + Device.getInstance().deviceBlueName = getString(Rstring.emulator_mode()); + Device.getInstance().deviceBrand = getString(Rstring.emulator_mode()); + try { + double lat = CoordUtil.dmsStringToRadian(item_starting_latitude.getRightText(), false); + double lon = CoordUtil.dmsStringToRadian(item_starting_longitude.getRightText(), false); + double alt = Double.parseDouble(item_starting_altitude.getRightText()); + float dir = 0; + if (!item_switch_random_direction.isChecked()) { + dir = (float) CoordUtil.dmsStringToRadian(item_starting_direction.getRightText(), false); + } + float speed = Float.parseFloat(item_move_speed.getRightText()); + + Device.getInstance().isEmulatorAngleRandom = item_switch_random_direction.isChecked(); + Device.getInstance().emulatorLat = lat; + Device.getInstance().emulatorLon = lon; + Device.getInstance().emulatorAlt = alt; + Device.getInstance().emulatorDirection = dir; + Device.getInstance().emulatorSpeed = speed; + + SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(ConnectRtkActivity.this); + SharedPreferences.Editor editor = prefs.edit(); + editor.putString("emulatorLat", Device.getInstance().emulatorLat + ""); + editor.putString("emulatorLon", Device.getInstance().emulatorLon + ""); + editor.putString("emulatorAlt", Device.getInstance().emulatorAlt + ""); + editor.putFloat("emulatorDirection", Device.getInstance().emulatorDirection); + editor.putFloat("emulatorSpeed", Device.getInstance().emulatorSpeed); + editor.putBoolean("isEmulatorAngleRandom", Device.getInstance().isEmulatorAngleRandom); + editor.apply(); + Device.getInstance().requestConnect(); + } catch (NumberFormatException ex) { + ToastUtils.showShort(Rstring.invalid_input()); + return; + } + } + SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(ConnectRtkActivity.this); + SharedPreferences.Editor editor = prefs.edit(); + editor.putString("deviceBlueName", Device.getInstance().deviceBlueName); + editor.putString("deviceMacAddress", Device.getInstance().deviceMacAddress); + editor.apply(); + + // why ? + GnssPosition.getInstance().setXyz(new Coordinate()); + } + } + }); + + item_switch_random_direction.setOnSettingItemClick(new LSettingItem.onSettingItemClick() { + @Override + public void click(boolean isChecked) { + if (isChecked) { + item_starting_direction.setVisibility(View.GONE); + } else { + item_starting_direction.setVisibility(View.VISIBLE); + } + } + }); + + View paster = findViewById(com.bingce.device.ui.R.id.activity_setup_station_input_btn_paste); + if (paster != null) { + paster.setOnClickListener(view -> { + CharSequence clipboardUtilsString = ClipboardUtils.getText(); + if (clipboardUtilsString != null) { + String pasteString = clipboardUtilsString.toString(); + String[] arr = pasteString.split(",", -2); + if (arr.length == 3) { + try { + if (item_starting_latitude != null) { + item_starting_latitude.setRightText(arr[0]); + } + if (item_starting_longitude != null) { + item_starting_longitude.setRightText(arr[1]); + } + if (item_starting_altitude != null) { + item_starting_altitude.setRightText(arr[2]); + } + ToastUtils.showShort(Rstring.have_pasted()); + } catch (NumberFormatException ex) { + ToastUtils.showShort(Rstring.paste_format_error()); + } catch (Exception ex) { + ex.printStackTrace(); + } + } else { + ToastUtils.showShort(Rstring.paste_format_error()); + } + } + }); + } + } + + private void startService() { + switch (Device.getInstance().connectType) { + case CONNECT_TYPE_BLE: + layoutPairedDevices.setVisibility(View.VISIBLE); + layoutNewDevices.setVisibility(View.GONE); + layoutEmulator.setVisibility(View.GONE); + mTextViewTitleRtkType.setVisibility(View.VISIBLE); + mSpinner2.setVisibility(View.VISIBLE); + ServiceUtils.stopService(BTService.class); + ServiceUtils.stopService(TsSocketService.class); + ServiceUtils.stopService(EmulatorService.class); + ServiceUtils.stopService(NativePositioningService.class); + ServiceUtils.stopService(LocationService.class); + if (!ServiceUtils.isServiceRunning(BleService.class) && XXPermissions.isGranted(this, Permission.BLUETOOTH_CONNECT)) { + ServiceUtils.startService(BleService.class); + } + break; + case CONNECT_TYPE_PHONE_LOCATION: + layoutPairedDevices.setVisibility(View.GONE); + layoutNewDevices.setVisibility(View.GONE); + layoutEmulator.setVisibility(View.GONE); + mTextViewTitleRtkType.setVisibility(View.GONE); + mSpinner2.setVisibility(View.GONE); + ServiceUtils.stopService(BleService.class); + ServiceUtils.stopService(TsSocketService.class); + ServiceUtils.stopService(EmulatorService.class); + ServiceUtils.stopService(BTService.class); + ServiceUtils.stopService(LocationService.class); + if (!ServiceUtils.isServiceRunning(NativePositioningService.class)) { + ServiceUtils.startService(NativePositioningService.class); + ThreadPoolUtil.execute(() -> Device.getInstance().requestConnect(), 500); + } + break; + case CONNECT_TYPE_EMULATOR: + layoutPairedDevices.setVisibility(View.GONE); + layoutNewDevices.setVisibility(View.GONE); + layoutEmulator.setVisibility(View.VISIBLE); + mTextViewTitleRtkType.setVisibility(View.GONE); + mSpinner2.setVisibility(View.GONE); + item_starting_latitude.setRightText(CoordUtil.radianToDmsDoubleString(Device.getInstance().emulatorLat, 6, false)); + item_starting_longitude.setRightText(CoordUtil.radianToDmsDoubleString(Device.getInstance().emulatorLon, 6, false)); + item_starting_altitude.setRightText(CoordUtil.formatDouble2String(Device.getInstance().emulatorAlt)); + item_switch_random_direction.setChecked(Device.getInstance().isEmulatorAngleRandom); + if (Device.getInstance().isEmulatorAngleRandom) { + item_starting_direction.setVisibility(View.GONE); + } else { + item_starting_direction.setVisibility(View.VISIBLE); + } + item_starting_direction.setRightText(CoordUtil.radianToDmsDoubleString(Device.getInstance().emulatorDirection, 6, false)); + item_move_speed.setRightText(CoordUtil.formatDouble2String(Device.getInstance().emulatorSpeed)); + ServiceUtils.stopService(BleService.class); + ServiceUtils.stopService(TsSocketService.class); + ServiceUtils.stopService(BTService.class); + ServiceUtils.stopService(LocationService.class); + ServiceUtils.stopService(NativePositioningService.class); + if (!ServiceUtils.isServiceRunning(EmulatorService.class)) { + ServiceUtils.startService(EmulatorService.class); + } + break; + case CONNECT_TYPE_QXBT: + layoutPairedDevices.setVisibility(View.VISIBLE); + layoutNewDevices.setVisibility(View.GONE); + layoutEmulator.setVisibility(View.GONE); + mTextViewTitleRtkType.setVisibility(View.VISIBLE); + mSpinner2.setVisibility(View.VISIBLE); + ServiceUtils.stopService(BleService.class); + ServiceUtils.stopService(TsSocketService.class); + ServiceUtils.stopService(EmulatorService.class); + ServiceUtils.stopService(LocationService.class); + ServiceUtils.stopService(NativePositioningService.class); + ServiceUtils.stopService(BTService.class); + break; + default://CONNECT_TYPE_SPP + layoutPairedDevices.setVisibility(View.VISIBLE); + layoutNewDevices.setVisibility(View.GONE); + layoutEmulator.setVisibility(View.GONE); + mTextViewTitleRtkType.setVisibility(View.VISIBLE); + mSpinner2.setVisibility(View.VISIBLE); + ServiceUtils.stopService(BleService.class); + ServiceUtils.stopService(TsSocketService.class); + ServiceUtils.stopService(EmulatorService.class); + ServiceUtils.stopService(LocationService.class); + ServiceUtils.stopService(NativePositioningService.class); + if (!ServiceUtils.isServiceRunning(BTService.class) && XXPermissions.isGranted(this, Permission.BLUETOOTH_CONNECT)) { + ServiceUtils.startService(BTService.class); + } + } + } + + @SuppressLint("MissingPermission") + private boolean updateBluetoothList() { + if (!XXPermissions.isGranted(this, Permission.BLUETOOTH_CONNECT, Permission.ACCESS_FINE_LOCATION)) { + return false; + } + if (BluetoothAdapter.getDefaultAdapter() == null) { + ToastUtils.showShort(Rstring.bluetooth_is_not_available()); + return false; + } else { + //监测蓝牙是否开启 + if (!BluetoothAdapter.getDefaultAdapter().isEnabled()) { + //打开蓝牙 + Intent enableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE); + startActivityForResult(enableIntent, REQUEST_ENABLE_BT); + return false; + } else { + Device.getInstance().requestSetupChat(); + cancelScan(); + if (Device.getInstance().connectType == ConnectTypeEnum.CONNECT_TYPE_SPP + || Device.getInstance().connectType == ConnectTypeEnum.CONNECT_TYPE_BLE + || Device.getInstance().connectType == ConnectTypeEnum.CONNECT_TYPE_QXBT) { + // 得到本地的蓝牙适配器 + mBtAdapter = BluetoothAdapter.getDefaultAdapter(); + if (mBtAdapter != null) { + // 得到一个已经匹配到本地适配器的BluetoothDevice类的对象集合 + Set pairedDevices = mBtAdapter.getBondedDevices(); + // 如果有配对成功的设备则添加到ArrayAdapter + if (!pairedDevices.isEmpty()) { + mPairedDevicesArrayAdapter.clear(); + for (BluetoothDevice device : pairedDevices) { + mPairedDevicesArrayAdapter.add(device.getName() + "\n" + device.getAddress()); + } + } else {// 否则添加一个没有被配对的字符串 + ToastUtils.showShort(Rstring.none_paired()); + } + + if (Device.getInstance().isDeviceConnected()) { + for (int i = 0; i < mPairedDevicesArrayAdapter.getCount(); i++) { + if (mPairedDevicesArrayAdapter.getItem(i) != null && mPairedDevicesArrayAdapter.getItem(i).endsWith(Device.getInstance().deviceMacAddress)) { + mPairedListView.setItemChecked(i, true); + ToastUtils.showShort(Rstring.device_has_connected()); + } else { + mPairedListView.setItemChecked(i, false); + } + } + } + } + } else { + mPairedDevicesArrayAdapter.clear(); + if (!"".equals(Device.getInstance().deviceBlueName) && !"".equals(Device.getInstance().deviceMacAddress)) { + mPairedDevicesArrayAdapter.add(Device.getInstance().deviceBlueName + "\n" + Device.getInstance().deviceMacAddress); + } + + if (Device.getInstance().isDeviceConnected()) { + mPairedListView.setItemChecked(0, true); + ToastUtils.showShort(Rstring.device_has_connected()); + } + } + return true; + } + } + } + + @Override + public boolean onCreateOptionsMenu(Menu menu) { + getMenuInflater().inflate(R.menu.menu_activity_connect_rtk, menu); + if (AppUtils.isAppDebug()) { + menu.findItem(Rid.menu_activity_connect_rtk_comm_debug()).setVisible(true); + } + return super.onCreateOptionsMenu(menu); + } + + @Override + public boolean onOptionsItemSelected(MenuItem item) { + int itemId = item.getItemId(); + if (itemId == android.R.id.home) { + finish(); + } else if (itemId == Rid.menu_activity_connect_rtk_scan()) { + mNewDevicesArrayAdapter.clear(); + requestLocationPermission(RC_LOCATION_PERM_SCAN); + } else if (itemId == Rid.menu_activity_connect_rtk_disconnect()) { + Device.getInstance().requestDisconnect(); + for (int i = 0; i < mPairedDevicesArrayAdapter.getCount(); i++) { + mPairedListView.setItemChecked(i, false); + } + for (int i = 0; i < mNewDevicesArrayAdapter.getCount(); i++) { + mNewDevicesListView.setItemChecked(i, false); + } + mBtnConnect.setText("连接"); + } else if (itemId == Rid.menu_activity_connect_rtk_comm_debug()) { + startActivity(new Intent(this, ToolCommDebugActivity.class)); + } +// else if (itemId == Rid.menu_activity_connect_rtk_help()) { +// if (Utils.getApp() instanceof IHelper) { +// ((IHelper) Utils.getApp()).onNavigation2RtkConnectHelp(); +// } +// } + return super.onOptionsItemSelected(item); + } + + + @Subscribe(threadMode = ThreadMode.MAIN) + public void onMessageEvent(RtkCmdSendOverEvent event) { + if (AppUtil.isForeground(this, this.getLocalClassName())) { + new AlertDialog.Builder(this) + .setTitle(Rstring.hint()) + .setMessage(Rstring.instrument_connection_completed()) + .setPositiveButton(Rstring.return_home_page(), new DialogInterface.OnClickListener() { + @Override + public void onClick(DialogInterface dialogInterface, int i) { + finish(); + } + }) + .setNegativeButton(Rstring.close(), null) + .show(); + } + } + + + @SuppressLint("MissingPermission") + @Override + protected void onDestroy() { + super.onDestroy();// 确保我们没有发现,检测设备 + if (XXPermissions.isGranted(this, Permission.BLUETOOTH_SCAN) && mBtAdapter != null && mBtAdapter.isDiscovering()) { + mBtAdapter.cancelDiscovery(); + } + // 设置显示进度条 + setSupportProgressBarIndeterminateVisibility(false); + + unregisterReceiver(publicReceiver); + + EventBus.getDefault().unregister(this); + } + + @SuppressLint("MissingPermission") + private void doDiscovery() { + if (!XXPermissions.isGranted(this, Permission.BLUETOOTH_SCAN)) { + return; + } + //先断开已有连接 + Device.getInstance().requestDisconnect(); + // 显示新设备的子标题 + layoutNewDevices.setVisibility(View.VISIBLE); + cancelScan(); + // 如果已经在请求现实了,那么就先停止 + if (Device.getInstance().connectType == ConnectTypeEnum.CONNECT_TYPE_SPP + || Device.getInstance().connectType == ConnectTypeEnum.CONNECT_TYPE_QXBT) { + // 请求从蓝牙适配器得到能够被发现的设备 + if (mBtAdapter != null) { + mBtAdapter.startDiscovery(); + } + ToastUtils.showLong(Rstring.scanning()); + } else if (Device.getInstance().connectType == ConnectTypeEnum.CONNECT_TYPE_BLE) { + BleScanner.getInstance().scan(null, null, null, false, 30000, new BleScanCallback() { + @Override + public void onScanFinished(List scanResultList) { + ToastUtils.showShort(com.bingce.device.ui.R.string.scan_complete); + } + + @Override + public void onScanStarted(boolean success) { + ToastUtils.showLong(Rstring.scanning()); + } + + @Override + public void onScanning(BleDevice bleDevice) { + if (bleDevice != null && bleDevice.getDevice().getBondState() != BluetoothDevice.BOND_BONDED) { + if (bleDevice.getName() == null) return; + String itemString = bleDevice.getName() + "\n" + bleDevice.getMac(); +// for (int i = 0; i < mPairedDevicesArrayAdapter.getCount(); i++) { +// if (itemString.equals(mPairedDevicesArrayAdapter.getItem(i))) { +// return; +// } +// } + int count = mNewDevicesArrayAdapter.getCount(); + if (count < 1) {//列表为空时,直接添加,不需要检查是否重复 + mNewDevicesArrayAdapter.add(itemString); + } else {//列表不为空时检查是否重复 + boolean has = false; + for (int j = 0; j < count; j++) { + if (itemString.equals(mNewDevicesArrayAdapter.getItem(j))) { + has = true; + break; + } + } + if (!has) { + mNewDevicesArrayAdapter.add(itemString); + } + } + } + } + }); + } + } + + /** + * 取消蓝牙扫描 + */ + @SuppressLint("MissingPermission") + private void cancelScan() { + if (!XXPermissions.isGranted(this, Permission.BLUETOOTH_SCAN)) { + return; + } + if (mBtAdapter != null && mBtAdapter.isDiscovering()) { + mBtAdapter.cancelDiscovery(); + } + if (BleManager.getInstance().getScanSate() == BleScanState.STATE_SCANNING) + BleManager.getInstance().cancelScan(); + } + + @SuppressLint("MissingPermission") + private void connect() { + if (Device.getInstance().connectType == ConnectTypeEnum.CONNECT_TYPE_SPP + || Device.getInstance().connectType == ConnectTypeEnum.CONNECT_TYPE_BLE + || Device.getInstance().connectType == ConnectTypeEnum.CONNECT_TYPE_QXBT) { + + ToastUtils.showShort(Rstring.connecting_please_wait()); + + if (RTK.getInstance() instanceof QxwzRTK) { + Device.getInstance().connectType = ConnectTypeEnum.CONNECT_TYPE_QXBT; + + BluetoothDevice device = mBtAdapter.getRemoteDevice(Device.getInstance().deviceMacAddress); + if (device.getBondState() == BluetoothDevice.BOND_BONDED) { + ServiceUtils.startService(QxwzMessengerService.class); + } else {//新设备,利用反射配对 + try { + createBond(device); + } catch (Exception e) { + e.printStackTrace(); + } + } + } else { + Device.getInstance().requestConnect(); + } + } else if (Device.getInstance().connectType == ConnectTypeEnum.CONNECT_TYPE_PHONE_LOCATION) { + Device.getInstance().requestConnect(); + } + } + + public void onActivityResult(int requestCode, int resultCode, Intent data) { + super.onActivityResult(requestCode, resultCode, data); + switch (requestCode) { + case REQUEST_ENABLE_BT: + if (resultCode == Activity.RESULT_OK) { + if (currentRequestCode == RC_BLUETOOTH_PERM_SCAN) { + requestBtScanPermission(); + } + } else { + Log.d("ConnectRtkActivity", "BT not enabled"); + ToastUtils.showShort(Rstring.bt_not_enabled()); + } + break; + } + if (requestCode == XXPermissions.REQUEST_CODE) { + switch (currentRequestCode) { + case RC_LOCATION_PERM_CONNECT: + if (XXPermissions.isGranted(this, Permission.ACCESS_FINE_LOCATION)) { + requestBtConnectPermission(); + } else { + ToastUtils.showLong(com.bingce.device.ui.R.string.bluetooth_connection_requires_positioning_permission_please_turn_it_on_manually); + } + break; + case RC_LOCATION_PERM_SCAN: + if (XXPermissions.isGranted(this, Permission.ACCESS_FINE_LOCATION)) { + requestBtScanPermission(); + } else { + ToastUtils.showLong(com.bingce.device.ui.R.string.bluetooth_scan_requires_positioning_permission_please_turn_it_on_manually); + } + break; + case RC_BLUETOOTH_PERM_CONNECT: + if (XXPermissions.isGranted(this, Permission.BLUETOOTH_CONNECT)) { + requestBtConnectPermission(); + } else { + ToastUtils.showLong(com.bingce.device.ui.R.string.bluetooth_connection_requires_positioning_permission_please_turn_it_on_manually); + } + break; + case RC_BLUETOOTH_PERM_SCAN: + if (XXPermissions.isGranted(this, Permission.BLUETOOTH_SCAN)) { + requestBtScanPermission(); + } else { + ToastUtils.showLong(com.bingce.device.ui.R.string.bluetooth_scan_requires_positioning_permission_please_turn_it_on_manually); + } + break; + } + } + } + + @Override + protected void onResume() { + super.onResume(); + if (gnssServerReady) { + new MaterialDialog.Builder(ConnectRtkActivity.this) + .title(Rstring.hint()) + .content(Rstring.you_need_start_gnss_server_for_communication()) + .positiveText(Rstring.started()) + .onPositive(new MaterialDialog.SingleButtonCallback() { + @Override + public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) { + requestLocationPermission(RC_LOCATION_PERM_CONNECT); + } + }) + .negativeText(Rstring.cancel()) + .dismissListener(new DialogInterface.OnDismissListener() { + @Override + public void onDismiss(DialogInterface dialog) { + gnssServerReady = false; + } + }) + .show(); + } + } + + @Override + protected void onNewIntent(Intent intent) { + super.onNewIntent(intent); + //本来南方、千寻RTK调用GnssServer后返回到这个界面,应该使用onNewIntent,但是个别手机无法成功执行,在onResume里成功率会更高 + } + + /** + * 连接蓝牙先请求打开定位权限 + */ + public void requestLocationPermission(int type) { + currentRequestCode = type; + if (XXPermissions.isGranted(this, Permission.ACCESS_FINE_LOCATION, Permission.ACCESS_COARSE_LOCATION)) { + switch (type) { + case RC_LOCATION_PERM_SCAN: + requestBtScanPermission(); + break; + case RC_LOCATION_PERM_CONNECT: + requestBtConnectPermission(); + break; + } + } else { + new MaterialDialog.Builder(this) + .title(Rstring.location_permission()) + .content(Rstring.bluetooth_need_location_permission()) + .canceledOnTouchOutside(false) + .positiveText(Rstring.to_allow()) + .negativeText(Rstring.refuse()) + .onPositive(new MaterialDialog.SingleButtonCallback() { + @Override + public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) { + XXPermissions.with(ConnectRtkActivity.this) + .permission(Permission.ACCESS_FINE_LOCATION, Permission.ACCESS_COARSE_LOCATION) + .request(new OnPermissionCallback() { + @Override + public void onGranted(List permissions, boolean all) { + if (all || permissions.contains(Permission.ACCESS_FINE_LOCATION)) { + startService(); + if (updateBluetoothList()) { + ThreadPoolUtil.executeInMain(new Runnable() { + @Override + public void run() { + switch (type) { + case RC_LOCATION_PERM_SCAN: + requestBtScanPermission(); + break; + case RC_LOCATION_PERM_CONNECT: + requestBtConnectPermission(); + break; + } + } + }, 500); + } + } + } + + @Override + public void onDenied(List permissions, boolean never) { + if (never) { + ToastUtils.showLong(com.bingce.device.ui.R.string.bluetooth_connection_requires_positioning_permission_please_turn_it_on_manually); + // 如果是被永久拒绝就跳转到应用权限系统设置页面 + XXPermissions.startPermissionActivity(ConnectRtkActivity.this, permissions); + } else { + requestLocationPermission(type); + } + } + }); + } + }) + .onNegative(new MaterialDialog.SingleButtonCallback() { + @Override + public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) { + ToastUtils.showShort(com.bingce.device.ui.R.string.bluetooth_need_location_permission); + } + }) + .show(); + } + } + + public void requestBtScanPermission() { + currentRequestCode = RC_BLUETOOTH_PERM_SCAN; + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) { + if (XXPermissions.isGranted(this, Permission.BLUETOOTH_SCAN, Permission.BLUETOOTH_CONNECT)) { + doDiscovery(); + } else { + new MaterialDialog.Builder(this) + .title(Rstring.bluetooth_scan_permission()) + .content(Rstring.bluetooth_scan_need_permission()) + .canceledOnTouchOutside(false) + .positiveText(Rstring.to_allow()) + .negativeText(Rstring.refuse()) + .onPositive(new MaterialDialog.SingleButtonCallback() { + @Override + public void onClick(@NonNull MaterialDialog materialDialog, @NonNull DialogAction dialogAction) { + XXPermissions.with(ConnectRtkActivity.this) + .permission(Permission.BLUETOOTH_SCAN, Permission.BLUETOOTH_CONNECT) + .request(new OnPermissionCallback() { + @Override + public void onGranted(List permissions, boolean all) { + if (all) { + startService(); + if (updateBluetoothList()) { + ThreadPoolUtil.executeInMain(new Runnable() { + @Override + public void run() { + doDiscovery(); + } + }, 500); + } + } else if (!permissions.contains(Permission.BLUETOOTH_SCAN)) { + requestBtScanPermission(); + } else if (!permissions.contains(Permission.BLUETOOTH_CONNECT)) { + requestBtConnectPermission(); + } + } + + @Override + public void onDenied(List permissions, boolean never) { + if (never) { + if (permissions.contains(Permission.BLUETOOTH_SCAN)) { + ToastUtils.showLong(com.bingce.device.ui.R.string.bluetooth_connection_requires_positioning_permission_please_turn_it_on_manually); + // 如果是被永久拒绝就跳转到应用权限系统设置页面 + XXPermissions.startPermissionActivity(ConnectRtkActivity.this, Permission.BLUETOOTH_SCAN); + } else if (permissions.contains(Permission.BLUETOOTH_CONNECT)) { + ToastUtils.showLong(com.bingce.device.ui.R.string.bluetooth_connection_requires_positioning_permission_please_turn_it_on_manually); + // 如果是被永久拒绝就跳转到应用权限系统设置页面 + XXPermissions.startPermissionActivity(ConnectRtkActivity.this, Permission.BLUETOOTH_CONNECT); + } + } else { + requestBtScanPermission(); + } + } + }); + } + }) + .onNegative(new MaterialDialog.SingleButtonCallback() { + @Override + public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) { + ToastUtils.showShort(com.bingce.device.ui.R.string.bluetooth_connect_need_permission); + } + }) + .show(); + + } + } else { + doDiscovery(); + } + } + + + public void requestBtConnectPermission() { + currentRequestCode = RC_BLUETOOTH_PERM_CONNECT; + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) { + if (XXPermissions.isGranted(this, Permission.BLUETOOTH_CONNECT)) { + connect(); + } else { + new MaterialDialog.Builder(this) + .title(Rstring.bluetooth_connect_permission()) + .content(Rstring.bluetooth_connect_need_permission()) + .canceledOnTouchOutside(false) + .positiveText(Rstring.to_allow()) + .negativeText(Rstring.refuse()) + .onPositive(new MaterialDialog.SingleButtonCallback() { + @Override + public void onClick(@NonNull MaterialDialog materialDialog, @NonNull DialogAction dialogAction) { + XXPermissions.with(ConnectRtkActivity.this) + .permission(Permission.BLUETOOTH_CONNECT) + .request(new OnPermissionCallback() { + @Override + public void onGranted(List permissions, boolean all) { + startService(); + if (updateBluetoothList()) { + ThreadPoolUtil.executeInMain(new Runnable() { + @Override + public void run() { + connect(); + } + }, 500); + } + } + + @Override + public void onDenied(List permissions, boolean never) { + if (never) { + ToastUtils.showLong(com.bingce.device.ui.R.string.bluetooth_connection_requires_positioning_permission_please_turn_it_on_manually); + // 如果是被永久拒绝就跳转到应用权限系统设置页面 + XXPermissions.startPermissionActivity(ConnectRtkActivity.this, Permission.BLUETOOTH_CONNECT); + } else { + requestBtConnectPermission(); + } + } + }); + } + }) + .onNegative(new MaterialDialog.SingleButtonCallback() { + @Override + public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) { + ToastUtils.showShort(com.bingce.device.ui.R.string.bluetooth_connect_need_permission); + } + }) + .show(); + } + } else { + connect(); + } + } + + class PublicReceiver extends BroadcastReceiver { + @SuppressLint("MissingPermission") + @Override + public void onReceive(Context context, Intent intent) { + String action = intent.getAction(); + // 当发现一个设备时 + if (BluetoothDevice.ACTION_FOUND.equals(action)) { + if (!XXPermissions.isGranted(ConnectRtkActivity.this, Permission.BLUETOOTH_CONNECT, Permission.ACCESS_FINE_LOCATION)) { + return; + } + // 从Intent得到蓝牙设备对象 + BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE); + // 如果已经配对,则跳过,因为他已经在设备列表中了 + if (device != null && device.getName() != null/* && device.getBondState() != BluetoothDevice.BOND_BONDED*/) { + // 显示新设备 + layoutNewDevices.setVisibility(View.VISIBLE); + // 否则添加到新设备列表 + int count = mNewDevicesArrayAdapter.getCount(); + String itemString = device.getName() + "\n" + device.getAddress(); + if (count < 1) {//列表为空时,直接添加,不需要检查是否重复 + mNewDevicesArrayAdapter.add(itemString); + } else {//列表不为空时检查是否重复 + boolean has = false; + for (int i = 0; i < count; i++) { + if (itemString.equals(mNewDevicesArrayAdapter.getItem(i))) { + has = true; + break; + } + } + if (!has) { + mNewDevicesArrayAdapter.add(itemString); + } + } + } + } else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) { + // 如果计数为0,则表示没有发现蓝牙 + if (mNewDevicesArrayAdapter.getCount() == 0) { + ToastUtils.showShort(Rstring.discovery_finished()); + } + } else if (BluetoothDevice.ACTION_BOND_STATE_CHANGED.equals(action)) { + //新设备使用千寻蓝牙时配对 + int state = intent.getIntExtra(BluetoothDevice.EXTRA_BOND_STATE, -1); + int prestate = intent.getIntExtra(BluetoothDevice.EXTRA_PREVIOUS_BOND_STATE, -1); + Log.d("ConnectRtkActivity", "ACTION_BOND_STATE_CHANGED" + ",state:" + state + ",prestate:" + prestate); + if (state == BluetoothDevice.BOND_BONDED && prestate == BluetoothDevice.BOND_BONDING) { + if (Device.getInstance().connectType == ConnectTypeEnum.CONNECT_TYPE_QXBT) { + ServiceUtils.startService(QxwzMessengerService.class); + Log.d("ConnectRtkActivity", "反射配对成功"); + } + } + } + } + } + + public static void start() { + ActivityUtils.startActivity(ConnectRtkActivity.class); + } + + /** + * 蓝牙配对 + * + * @param device + * @return + * @throws Exception + */ + public static boolean createBond(BluetoothDevice device) throws Exception { + Method createBondMethod = BluetoothDevice.class.getMethod("createBond"); + return (Boolean) createBondMethod.invoke(device); + } + + public interface IHelper { + void onNavigation2RtkConnectHelp(); + } +} diff --git a/app/src/main/java/com/project/survey/ui/instrument/totalstation/ConnectTSActivity.java b/app/src/main/java/com/project/survey/ui/instrument/totalstation/ConnectTSActivity.java new file mode 100644 index 0000000..1040f07 --- /dev/null +++ b/app/src/main/java/com/project/survey/ui/instrument/totalstation/ConnectTSActivity.java @@ -0,0 +1,1154 @@ +package com.project.survey.ui.instrument.totalstation; + +import android.annotation.SuppressLint; +import android.app.Activity; +import android.app.AlertDialog; +import android.bluetooth.BluetoothAdapter; +import android.bluetooth.BluetoothDevice; +import android.content.BroadcastReceiver; +import android.content.ComponentName; +import android.content.Context; +import android.content.DialogInterface; +import android.content.Intent; +import android.content.IntentFilter; +import android.content.SharedPreferences; +import android.graphics.Color; +import android.net.wifi.WifiManager; +import android.os.Build; +import android.os.Bundle; +import android.provider.Settings; +import android.util.Log; +import android.view.Menu; +import android.view.MenuItem; +import android.view.View; +import android.widget.AdapterView; +import android.widget.ArrayAdapter; +import android.widget.Button; +import android.widget.LinearLayout; +import android.widget.ListView; +import android.widget.Spinner; + +import androidx.annotation.NonNull; +import androidx.appcompat.widget.Toolbar; +import androidx.fragment.app.Fragment; +import androidx.preference.PreferenceManager; + +import com.afollestad.materialdialogs.DialogAction; +import com.afollestad.materialdialogs.MaterialDialog; +import com.bingce.AppChannel; +import com.bingce.coordlib.model.Coordinate; +import com.bingce.device.Device; +import com.bingce.device.enums.ConnectTypeEnum; +import com.bingce.device.enums.DeviceTypeEnum; +import com.bingce.device.service.comm.ble.BleService; +import com.bingce.device.service.comm.emulator.EmulatorService; +import com.bingce.device.service.comm.localgps.LocationService; +import com.bingce.device.service.comm.localgps.NativePositioningService; +import com.bingce.device.service.comm.otg.OTGCommService; +import com.bingce.device.service.comm.socket.TsSocketService; +import com.bingce.device.service.comm.spp.BTService; +import com.bingce.device.ui.ToolCommDebugActivity; +import com.bingce.event.OpenShortUrlEvent; +import com.bingce.rtk.gnss.Gnss; +import com.bingce.totalstation.TotalStation; +import com.bingce.totalstation.TsConfig; +import com.bingce.totalstation.TsListener; +import com.bingce.totalstation.enums.CommDelayEnum; +import com.bingce.totalstation.enums.SetupStationModeEnum; +import com.bingce.totalstation.enums.TotalStationEnum; +import com.bingce.totalstation.protocol.topcon.TopconInterface; +import com.bingce.totalstation.util.TsUtil; +import com.bingce.utils.RomUtil; +import com.bingce.utils.SoftKeyUtils; +import com.bingce.utils.ThreadPoolUtil; +import com.bingce.utils.Util; +import com.bingce.utils.ValidateUtil; +import com.hjq.permissions.OnPermissionCallback; +import com.hjq.permissions.Permission; +import com.hjq.permissions.XXPermissions; +import com.rengwuxian.materialedittext.MaterialEditText; + +import org.greenrobot.eventbus.EventBus; +import org.polaric.colorful.ColorfulActivity; + +import java.util.Arrays; +import java.util.List; +import java.util.Locale; +import java.util.Set; +import java.util.regex.Pattern; + +import blankj.utilcode.util.ActivityUtils; +import blankj.utilcode.util.AppUtils; +import blankj.utilcode.util.ServiceUtils; +import blankj.utilcode.util.StringUtils; +import blankj.utilcode.util.ToastUtils; +import blankj.utilcode.util.Utils; +import clj.fastble.BleManager; +import clj.fastble.callback.BleScanCallback; +import clj.fastble.data.BleDevice; +import clj.fastble.data.BleScanState; +import clj.fastble.scan.BleScanner; +import device.ui.Rid; +import device.ui.Rlayout; +import device.ui.Rmenu; +import device.ui.Rstring; + +public class ConnectTSActivity extends ColorfulActivity implements TsListener.TsTestListener { + private static final int RC_LOCATION_PERM_SCAN = 128; + private static final int RC_LOCATION_PERM_CONNECT = 129; + private static final int RC_BLUETOOTH_PERM_SCAN = 130; + private static final int RC_BLUETOOTH_PERM_CONNECT = 131; + private static final int REQUEST_ENABLE_BT = 3; + public static final int WIFI_AP_STATE_ENABLED = 13; + private int currentRequestCode = -1; + private BluetoothAdapter mBtAdapter; + private ArrayAdapter mPairedDevicesArrayAdapter; + private ArrayAdapter mNewDevicesArrayAdapter; + private MaterialEditText met_coord_prefix_x, met_coord_prefix_y, met_coord_prefix_z; + private PublicReceiver publicReceiver; + private Toolbar mToolbar; + private Spinner mSpinner1; + private Spinner mSpinner2; + private Spinner mSpinner3; + private ListView mPairedListView; + private LinearLayout layoutPairedDevices; + private ListView mNewDevicesListView; + private LinearLayout layoutNewDevices; + private MaterialEditText met_ip, met_port; + private MaterialEditText met_tp_com_blue_mac, met_otg_tp_com_mac; + private Button mBtnOpenHotspot, mBtnHotspotConnect; + private Button mBtnTpComConnect, mBtnOTGConnect; + private LinearLayout layoutWifiHotspotSetting, layoutTpComSetting, layoutOTGSetting; + private Button mBtnTest; + private Button mBtnGuide; + private Button mBtnTaobao; + + @SuppressLint("SourceLockedOrientationActivity") + @Override + protected void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + setContentView(Rlayout.activity_connect_total_station()); + mToolbar = findViewById(Rid.toolbar()); + mSpinner1 = findViewById(Rid.activity_connect_total_station_spinner_connect_type()); + mSpinner2 = findViewById(Rid.activity_connect_total_station_spinner_total_station_type()); + mSpinner3 = findViewById(Rid.activity_connect_total_station_spinner_com_delay()); + mPairedListView = findViewById(Rid.activity_connect_total_station_paired_devices()); + layoutPairedDevices = findViewById(Rid.activity_connect_total_station_layout_paired_devices()); + mNewDevicesListView = findViewById(Rid.activity_connect_total_station_new_devices()); + layoutNewDevices = findViewById(Rid.activity_connect_total_station_layout_new_devices()); + met_ip = findViewById(Rid.met_activity_connect_total_station_wifi_ip()); + met_port = findViewById(Rid.met_activity_connect_total_station_wifi_port()); + met_tp_com_blue_mac = findViewById(Rid.met_activity_connect_total_station_tp_com_bluetooth_mac()); + met_otg_tp_com_mac = findViewById(Rid.met_activity_connect_total_station_otg_tp_com_mac()); + mBtnOpenHotspot = findViewById(Rid.activity_connect_total_station_btn_wifi_hotspot_open()); + mBtnHotspotConnect = findViewById(Rid.activity_connect_total_station_btn_wifi_connect()); + mBtnTpComConnect = findViewById(Rid.activity_connect_total_station_btn_tp_com_connect()); + mBtnOTGConnect = findViewById(Rid.activity_connect_total_station_btn_otg_connect()); + layoutWifiHotspotSetting = findViewById(Rid.activity_connect_total_station_layout_wifi_setting()); + layoutTpComSetting = findViewById(Rid.activity_connect_total_station_layout_tp_com_setting()); + layoutOTGSetting = findViewById(Rid.activity_connect_total_station_layout_otg_setting()); + mBtnTest = findViewById(Rid.activity_connect_total_station_btn_test()); + mBtnGuide = findViewById(Rid.activity_connect_total_station_btn_guide()); + mBtnTaobao = findViewById(Rid.activity_connect_total_station_taobao()); + String packageName = getPackageName(); +// if ("com.bingce.controlnetwork.tj".equals(packageName) +// || "com.bingce.controlnetwork.tj.leveling".equals(packageName) +// || "com.bingce.controlnetwork.pla".equals(packageName)) { + mBtnGuide.setVisibility(View.GONE); + mBtnTaobao.setVisibility(View.GONE); +// } + + TsListener.getInstance().addTsTestListener(this); + + setSupportActionBar(mToolbar); + if (getSupportActionBar() != null) getSupportActionBar().setDisplayHomeAsUpEnabled(true); + + //当存在公共广播和私有广播时,都要声明,而且:1,先声明公共广播;2,私有action要在公共和私有里都addAction;3,接收是在公共接收器里处理结果的;4,先注销私有,再注销公共 + publicReceiver = new PublicReceiver(); + IntentFilter filter = new IntentFilter(); + filter.addAction(BluetoothDevice.ACTION_FOUND);// 当一个设备被发现时,需要注册一个广播 + filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);// 当显示检查完毕的时候,需要注册一个广播 + registerReceiver(publicReceiver, filter); + + mSpinner1.setAdapter(new ArrayAdapter<>(this, android.R.layout.simple_spinner_dropdown_item, ConnectTypeEnum.getTsSupportConnectTypeNames())); + mSpinner2.setAdapter(new ArrayAdapter<>(this, android.R.layout.simple_spinner_dropdown_item, TsUtil.getSupportTotalStationEnumNames())); + mSpinner3.setAdapter(new ArrayAdapter<>(this, android.R.layout.simple_spinner_dropdown_item, TsUtil.getCommDelayEnumNames())); + mBtnTest.setOnClickListener(listener); +// mBtnGuide.setOnClickListener(listener); +// mBtnTaobao.setOnClickListener(listener); + + // 初始化ArrayAdapter,一个是已经配对的设备,一个是新发现的设备 + mPairedDevicesArrayAdapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_single_choice); + mNewDevicesArrayAdapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_single_choice); + + // 检测并设置已配对的设备ListView + mPairedListView.setAdapter(mPairedDevicesArrayAdapter); + mPairedListView.setChoiceMode(ListView.CHOICE_MODE_SINGLE); + mPairedListView.setOnItemClickListener(mDeviceClickListener); + + // 检查并设置行发现的蓝牙设备ListView + mNewDevicesListView.setAdapter(mNewDevicesArrayAdapter); + mNewDevicesListView.setChoiceMode(ListView.CHOICE_MODE_SINGLE); + mNewDevicesListView.setOnItemClickListener(mDeviceClickListener); + + mSpinner1.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { + @Override + public void onItemSelected(AdapterView parent, View view, int position, long id) { + if (ConnectTypeEnum.getTsSupportConnectTypes().contains(Device.getInstance().connectType)) { + Device.getInstance().connectType = ConnectTypeEnum.getTsSupportConnectTypes().get(position); + } else { + Device.getInstance().connectType = ConnectTypeEnum.CONNECT_TYPE_SPP; + } + Util.putPreference("connectType", Device.getInstance().connectType.getValue()); + + startService(); + updateBluetoothList(); + } + + @Override + public void onNothingSelected(AdapterView parent) { + + } + }); + + if (TsConfig.getInstance().lastTsType.getConnectTypeValue() >= 0 && TsConfig.getInstance().lastTsType.getConnectTypeValue() < mSpinner1.getCount()) { + mSpinner1.setSelection(TsConfig.getInstance().lastTsType.getConnectTypeValue()); + } + + mSpinner2.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { + @Override + public void onItemSelected(AdapterView adapterView, View view, int position, long l) { + TsConfig.getInstance().lastTsType = TsUtil.getSupportTotalStationEnums().get(mSpinner2.getSelectedItemPosition()); + TsConfig.getInstance().save(); + + if (mSpinner1.getSelectedItemPosition() != 3) {//OTG + if (TsConfig.getInstance().lastTsType.getConnectTypeValue() >= 0 && TsConfig.getInstance().lastTsType.getConnectTypeValue() < mSpinner1.getCount()) { + mSpinner1.setSelection(TsConfig.getInstance().lastTsType.getConnectTypeValue()); + } + } + switch (TsConfig.getInstance().lastTsType) { + case TOTAL_STATION_HAIYUN_BOIF: + case TOTAL_STATION_RUIDE: + case TOTAL_STATION_GEODIMETER2: + case TOTAL_STATION_SOUTH_5XX_ANDROID_BT: + mSpinner3.setVisibility(View.VISIBLE); + break; + default: + mSpinner3.setVisibility(View.GONE); + } + if (TsConfig.getInstance().lastTsType == TotalStationEnum.TOTAL_STATION_TRIMBLE_TPCOM) { + if (Device.getInstance().connectType == ConnectTypeEnum.CONNECT_TYPE_OTG) { + met_otg_tp_com_mac.setVisibility(View.VISIBLE); + } else { + met_otg_tp_com_mac.setVisibility(View.GONE); + } + } else { + met_otg_tp_com_mac.setVisibility(View.GONE); + } + + Device.getInstance().deviceType = DeviceTypeEnum.DEVICE_TYPE_TS; + Device.getInstance().deviceBrand = TsConfig.getInstance().lastTsType.getName(); + SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(ConnectTSActivity.this); + SharedPreferences.Editor editor = prefs.edit(); + editor.putInt("deviceType", DeviceTypeEnum.DEVICE_TYPE_TS.getValue()); + editor.putString("deviceBrand", Device.getInstance().deviceBrand); + editor.apply(); + } + + @Override + public void onNothingSelected(AdapterView adapterView) { + + } + }); + + if (AppChannel.customChannel == AppChannel.CUSTOM_NMP) { + TsConfig.getInstance().lastTsType = TotalStationEnum.TOTAL_STATION_NEWMAP; + mSpinner2.setEnabled(false); + } else if (AppChannel.customChannel == AppChannel.CUSTOM_HUACE) { + TsConfig.getInstance().lastTsType = TotalStationEnum.TOTAL_STATION_HUACE; + mSpinner2.setEnabled(false); + } else if (AppChannel.customChannel == AppChannel.CUSTOM_UFO) { + TsConfig.getInstance().lastTsType = TotalStationEnum.TOTAL_STATION_UFO_T5; + mSpinner2.setEnabled(false); + } else if (AppChannel.customChannel == AppChannel.CUSTOM_PENTAX || AppChannel.customChannel == AppChannel.CUSTOM_PENTAX_INTERNATIONAL) { + TsConfig.getInstance().lastTsType = TotalStationEnum.TOTAL_STATION_PENTAX_X100; + mSpinner2.setEnabled(false); + } + + int index2 = TsUtil.getSupportTotalStationEnums().indexOf(TsConfig.getInstance().lastTsType); + if (index2 == -1) index2 = 0; + mSpinner2.setSelection(index2); + + int index3 = Arrays.asList(CommDelayEnum.values()).indexOf(TsConfig.getInstance().getCommDelay()); + if (index3 == -1) index3 = 0; + mSpinner3.setSelection(index3); + mSpinner3.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { + @Override + public void onItemSelected(AdapterView arg0, View arg1, int position, long id) { + TsConfig.getInstance().setCommDelay(CommDelayEnum.values()[position]); + TsConfig.getInstance().save(); + } + + @Override + public void onNothingSelected(AdapterView arg0) { + + } + }); + + met_ip.setText(TsConfig.getInstance().getIp()); + met_port.setText(String.format(Locale.US, "%d", TsConfig.getInstance().getPort())); + mBtnOpenHotspot.setOnClickListener((v) -> { + if (isWifiApOpen()) { + ToastUtils.showShort(Rstring.hotspot_open_success()); + } else { + //打开网络共享与热点设置页面 + if (RomUtil.isOppo() || RomUtil.isLenove() || RomUtil.isGionee()) { + //OPPO系统系统特殊,会让在Manifest.xml声明Settings$TetherSettingsActivity,现在让用户自己找热点界面,并开启 + ToastUtils.showShort(Rstring.find_tether_setting_and_open()); + startActivity(new Intent(Settings.ACTION_SETTINGS)); + } else { + Intent intent = new Intent(); + intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); + ComponentName comp = new ComponentName("com.android.settings", "com.android.settings.Settings$TetherSettingsActivity"); + intent.setComponent(comp); + startActivity(intent); + } + } + }); + + mBtnHotspotConnect.setOnClickListener(new View.OnClickListener() { + @Override + public void onClick(View v) { + if (!ValidateUtil.isIPAddress(met_ip.getText().toString().trim())) { + ToastUtils.showShort(Rstring.please_input_correct_ip()); + return; + } + try { + Integer.parseInt(met_port.getText().toString().trim()); + TsConfig.getInstance().setIp(met_ip.getText().toString().trim()); + TsConfig.getInstance().setPort(Integer.parseInt(met_port.getText().toString().trim())); + TsConfig.getInstance().save(); + } catch (NumberFormatException ex) { + ToastUtils.showShort(Rstring.please_input_correct_port()); + return; + } + if (isWifiApOpen()) { + ServiceUtils.stopService(EmulatorService.class); + ServiceUtils.stopService(LocationService.class); + ServiceUtils.stopService(NativePositioningService.class); + ServiceUtils.stopService(BTService.class); + ServiceUtils.stopService(BleService.class); + Device.getInstance().requestConnect(); + + Device.getInstance().deviceBlueName = TsConfig.getInstance().getIp(); + Device.getInstance().deviceMacAddress = ""; + SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(ConnectTSActivity.this); + SharedPreferences.Editor editor = prefs.edit(); + editor.putString("deviceBlueName", Device.getInstance().deviceBlueName); + editor.putString("deviceMacAddress", Device.getInstance().deviceMacAddress); + editor.apply(); + } else { + ToastUtils.showShort(Rstring.please_open_hotspot_first()); + } + } + }); + + met_tp_com_blue_mac.setText(TsConfig.getInstance().getTpComMac()); + mBtnTpComConnect.setOnClickListener(new View.OnClickListener() { + @Override + public void onClick(View v) { + if (!AppUtils.isAppInstalled("com.tpcom")) { + ToastUtils.showShort(Rstring.tp_com_not_installed()); + return; + } + String tpComMac = met_tp_com_blue_mac.getText().toString(); + if (!Pattern.matches("/^[A-F0-9]{2}(-[A-F0-9]{2}){5}$|^[A-F0-9]{2}(:[A-F0-9]{2}){5}$|^[A-F0-9]{12}$|^[A-F0-9]{4}(\\.[A-F0-9]{4}){2}$", tpComMac)) { + ToastUtils.showShort(Rstring.please_input_correct_mac()); + return; + } + TsConfig.getInstance().setIp("127.0.0.1"); + TsConfig.getInstance().setPort(8090); + TsConfig.getInstance().setTpComMac(tpComMac); + TsConfig.getInstance().save(); + Device.getInstance().requestConnect(); + + Device.getInstance().deviceBlueName = "TP COM"; + Device.getInstance().deviceMacAddress = tpComMac; + SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(ConnectTSActivity.this); + SharedPreferences.Editor editor = prefs.edit(); + editor.putString("deviceBlueName", Device.getInstance().deviceBlueName); + editor.putString("deviceMacAddress", Device.getInstance().deviceMacAddress); + editor.apply(); + } + }); + met_otg_tp_com_mac.setText(TsConfig.getInstance().getTpComMac()); + mBtnOTGConnect.setOnClickListener(new View.OnClickListener() { + @Override + public void onClick(View view) { + ServiceUtils.stopService(BTService.class); + ServiceUtils.stopService(BleService.class); + ServiceUtils.stopService(TsSocketService.class); + ServiceUtils.stopService(EmulatorService.class); + + if (TsConfig.getInstance().lastTsType == TotalStationEnum.TOTAL_STATION_TRIMBLE_TPCOM) { + String tpComMac = met_otg_tp_com_mac.getText().toString(); + if (!Pattern.matches("/^[A-F0-9]{2}(-[A-F0-9]{2}){5}$|^[A-F0-9]{2}(:[A-F0-9]{2}){5}$|^[A-F0-9]{12}$|^[A-F0-9]{4}(\\.[A-F0-9]{4}){2}$", tpComMac)) { + ToastUtils.showShort(Rstring.please_input_correct_mac()); + return; + } + TsConfig.getInstance().setIp("127.0.0.1"); + TsConfig.getInstance().setPort(8090); + TsConfig.getInstance().setTpComMac(tpComMac); + TsConfig.getInstance().save(); + } + Device.getInstance().requestConnect(); + + Device.getInstance().deviceBlueName = "OTG"; + Device.getInstance().deviceMacAddress = ""; + SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(ConnectTSActivity.this); + SharedPreferences.Editor editor = prefs.edit(); + editor.putString("deviceBlueName", Device.getInstance().deviceBlueName); + editor.putString("deviceMacAddress", Device.getInstance().deviceMacAddress); + editor.apply(); + } + }); + } + + private void startService() { + if (Device.getInstance().connectType == ConnectTypeEnum.CONNECT_TYPE_SPP) { + layoutPairedDevices.setVisibility(View.VISIBLE); + layoutNewDevices.setVisibility(View.GONE); + layoutWifiHotspotSetting.setVisibility(View.GONE); + layoutTpComSetting.setVisibility(View.GONE); + layoutOTGSetting.setVisibility(View.GONE); + ServiceUtils.stopService(BleService.class); + ServiceUtils.stopService(OTGCommService.class); + ServiceUtils.stopService(TsSocketService.class); + ServiceUtils.stopService(EmulatorService.class); + ServiceUtils.stopService(NativePositioningService.class); + if (!ServiceUtils.isServiceRunning(BTService.class) && XXPermissions.isGranted(this, Permission.BLUETOOTH_CONNECT)) { + ServiceUtils.startService(BTService.class); + } + } else if (Device.getInstance().connectType == ConnectTypeEnum.CONNECT_TYPE_BLE) { + layoutPairedDevices.setVisibility(View.VISIBLE); + layoutNewDevices.setVisibility(View.GONE); + layoutWifiHotspotSetting.setVisibility(View.GONE); + layoutTpComSetting.setVisibility(View.GONE); + layoutOTGSetting.setVisibility(View.GONE); + ServiceUtils.stopService(BTService.class); + ServiceUtils.stopService(OTGCommService.class); + ServiceUtils.stopService(TsSocketService.class); + ServiceUtils.stopService(EmulatorService.class); + ServiceUtils.stopService(NativePositioningService.class); + if (!ServiceUtils.isServiceRunning(BleService.class) && XXPermissions.isGranted(this, Permission.BLUETOOTH_CONNECT)) { + ServiceUtils.startService(BleService.class); + } + } else if (Device.getInstance().connectType == ConnectTypeEnum.CONNECT_TYPE_HOTSPOT) { + layoutPairedDevices.setVisibility(View.GONE); + layoutNewDevices.setVisibility(View.GONE); + layoutWifiHotspotSetting.setVisibility(View.VISIBLE); + layoutTpComSetting.setVisibility(View.GONE); + layoutOTGSetting.setVisibility(View.GONE); + ServiceUtils.stopService(BTService.class); + ServiceUtils.stopService(BleService.class); + ServiceUtils.stopService(OTGCommService.class); + ServiceUtils.stopService(EmulatorService.class); + ServiceUtils.stopService(NativePositioningService.class); + if (!ServiceUtils.isServiceRunning(TsSocketService.class)) { + ServiceUtils.startService(TsSocketService.class); + } + } else if (Device.getInstance().connectType == ConnectTypeEnum.CONNECT_TYPE_OTG) { + layoutPairedDevices.setVisibility(View.GONE); + layoutNewDevices.setVisibility(View.GONE); + layoutWifiHotspotSetting.setVisibility(View.GONE); + layoutTpComSetting.setVisibility(View.GONE); + layoutOTGSetting.setVisibility(View.VISIBLE); + if (TsConfig.getInstance().lastTsType == TotalStationEnum.TOTAL_STATION_TRIMBLE_TPCOM) { + met_otg_tp_com_mac.setVisibility(View.VISIBLE); + } else { + met_otg_tp_com_mac.setVisibility(View.GONE); + } + ServiceUtils.stopService(BTService.class); + ServiceUtils.stopService(BleService.class); + ServiceUtils.stopService(TsSocketService.class); + ServiceUtils.stopService(EmulatorService.class); + ServiceUtils.stopService(NativePositioningService.class); + if (!ServiceUtils.isServiceRunning(OTGCommService.class)) { + ServiceUtils.startService(OTGCommService.class); + } + } else if (Device.getInstance().connectType == ConnectTypeEnum.CONNECT_TYPE_TPCOM) { + layoutPairedDevices.setVisibility(View.GONE); + layoutNewDevices.setVisibility(View.GONE); + layoutWifiHotspotSetting.setVisibility(View.GONE); + layoutTpComSetting.setVisibility(View.VISIBLE); + layoutOTGSetting.setVisibility(View.GONE); + ServiceUtils.stopService(BTService.class); + ServiceUtils.stopService(BleService.class); + ServiceUtils.stopService(OTGCommService.class); + ServiceUtils.stopService(EmulatorService.class); + ServiceUtils.stopService(NativePositioningService.class); + if (!ServiceUtils.isServiceRunning(TsSocketService.class)) { + ServiceUtils.startService(TsSocketService.class); + } + } + } + + @SuppressLint("MissingPermission") + private boolean updateBluetoothList() { + if (!XXPermissions.isGranted(this, Permission.BLUETOOTH_CONNECT, Permission.ACCESS_FINE_LOCATION)) { + return false; + } + if (BluetoothAdapter.getDefaultAdapter() == null) { + ToastUtils.showLong(Rstring.bluetooth_is_not_available()); + return false; + } else { + //监测蓝牙是否开启 + if (!BluetoothAdapter.getDefaultAdapter().isEnabled()) { + //打开蓝牙 + Intent enableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE); + startActivityForResult(enableIntent, REQUEST_ENABLE_BT); + return false; + } else { + Device.getInstance().requestSetupChat(); + cancelScan(); + if (Device.getInstance().connectType == ConnectTypeEnum.CONNECT_TYPE_SPP) { + // 得到本地的蓝牙适配器 + mBtAdapter = BluetoothAdapter.getDefaultAdapter(); + if (mBtAdapter != null) { + // 得到一个已经匹配到本地适配器的BluetoothDevice类的对象集合 + Set pairedDevices = mBtAdapter.getBondedDevices(); + // 如果有配对成功的设备则添加到ArrayAdapter + if (pairedDevices.size() > 0) { + mPairedDevicesArrayAdapter.clear(); + for (BluetoothDevice device : pairedDevices) { + mPairedDevicesArrayAdapter.add(device.getName() + "\n" + device.getAddress()); + } + } else {// 否则添加一个没有被配对的字符串 + ToastUtils.showShort(Rstring.none_paired()); + } + + if (Device.getInstance().isDeviceConnected()) { + for (int i = 0; i < mPairedDevicesArrayAdapter.getCount(); i++) { + if (mPairedDevicesArrayAdapter.getItem(i) != null && mPairedDevicesArrayAdapter.getItem(i).endsWith(Device.getInstance().deviceMacAddress)) { + mPairedListView.setItemChecked(i, true); + ToastUtils.showShort(Rstring.device_has_connected()); + } else { + mPairedListView.setItemChecked(i, false); + } + } + } + } + } else { + mPairedDevicesArrayAdapter.clear(); + if (!"".equals(Device.getInstance().deviceBlueName) && !"".equals(Device.getInstance().deviceMacAddress)) { + mPairedDevicesArrayAdapter.add(Device.getInstance().deviceBlueName + "\n" + Device.getInstance().deviceMacAddress); + } + + if (Device.getInstance().isDeviceConnected()) { + mPairedListView.setItemChecked(0, true); + ToastUtils.showShort(Rstring.device_has_connected()); + } + } + return true; + } + } + } + + /** + * ListViews中所有设备的点击事件监听 + */ + private final AdapterView.OnItemClickListener mDeviceClickListener = new AdapterView.OnItemClickListener() { + public void onItemClick(AdapterView av, View v, int arg2, long arg3) { + cancelScan(); + //如果是从RTK切换过来的,先停止RTK的线程 +// if (!"com.bingce.controlnetwork".equals(getPackageName())) + Device.getInstance().rtkStopAllTimer(); + + if (Device.getInstance().isDeviceConnected()) { + ToastUtils.showShort(Rstring.device_has_connected()); + } else { + requestLocationPermission(RC_LOCATION_PERM_CONNECT); + } + } + }; + + @Override + public boolean onCreateOptionsMenu(Menu menu) { + getMenuInflater().inflate(Rmenu.menu_activity_connect_totalstaion(), menu); + if (AppUtils.isAppDebug()) { + menu.findItem(Rid.menu_activity_connect_totalstation_comm_debug()).setVisible(true); + } + return super.onCreateOptionsMenu(menu); + } + + @Override + public boolean onOptionsItemSelected(MenuItem item) { + int itemId = item.getItemId(); + if (itemId == android.R.id.home) { + finish(); + } else if (itemId == Rid.menu_activity_connect_totalstation_scan()) { + mNewDevicesArrayAdapter.clear(); + requestLocationPermission(RC_LOCATION_PERM_SCAN); + } else if (itemId == Rid.menu_activity_connect_totalstation_disconnect()) { + Device.getInstance().requestDisconnect(); + if (Device.getInstance().connectType == ConnectTypeEnum.CONNECT_TYPE_SPP + || Device.getInstance().connectType == ConnectTypeEnum.CONNECT_TYPE_BLE + || Device.getInstance().connectType == ConnectTypeEnum.CONNECT_TYPE_QXBT) { + for (int i = 0; i < mPairedDevicesArrayAdapter.getCount(); i++) { + mPairedListView.setItemChecked(i, false); + } + for (int i = 0; i < mNewDevicesArrayAdapter.getCount(); i++) { + mNewDevicesListView.setItemChecked(i, false); + } + } + } else if (itemId == Rid.menu_activity_connect_totalstation_coord_prefix()) { + showCoordPrefixDialog(); + } else if (itemId == Rid.menu_activity_connect_totalstation_comm_debug()) { + startActivity(new Intent(this, ToolCommDebugActivity.class)); + } + return super.onOptionsItemSelected(item); + } + + public void onActivityResult(int requestCode, int resultCode, Intent data) { + super.onActivityResult(requestCode, resultCode, data); + switch (requestCode) { + case REQUEST_ENABLE_BT: + if (resultCode == Activity.RESULT_OK) { + if (currentRequestCode == RC_BLUETOOTH_PERM_SCAN) { + requestBtScanPermission(); + } + } else { + Log.d("ConnectTSActivity", "BT not enabled"); + ToastUtils.showShort(Rstring.bt_not_enabled()); + } + break; + } + if (requestCode == XXPermissions.REQUEST_CODE) { + switch (currentRequestCode) { + case RC_LOCATION_PERM_CONNECT: + if (XXPermissions.isGranted(this, Permission.ACCESS_FINE_LOCATION)) { + requestBtConnectPermission(); + } else { + ToastUtils.showLong(com.bingce.device.ui.R.string.bluetooth_connection_requires_positioning_permission_please_turn_it_on_manually); + } + break; + case RC_LOCATION_PERM_SCAN: + if (XXPermissions.isGranted(this, Permission.ACCESS_FINE_LOCATION)) { + requestBtScanPermission(); + } else { + ToastUtils.showLong(com.bingce.device.ui.R.string.bluetooth_scan_requires_positioning_permission_please_turn_it_on_manually); + } + break; + case RC_BLUETOOTH_PERM_CONNECT: + if (XXPermissions.isGranted(this, Permission.BLUETOOTH_CONNECT)) { + requestBtConnectPermission(); + } else { + ToastUtils.showLong(com.bingce.device.ui.R.string.bluetooth_connection_requires_positioning_permission_please_turn_it_on_manually); + } + break; + case RC_BLUETOOTH_PERM_SCAN: + if (XXPermissions.isGranted(this, Permission.BLUETOOTH_SCAN)) { + requestBtScanPermission(); + } else { + ToastUtils.showLong(com.bingce.device.ui.R.string.bluetooth_scan_need_permission); + } + break; + } + } + } + + /** + * 连接蓝牙先请求打开定位权限 + */ + public void requestLocationPermission(int type) { + currentRequestCode = type; + if (XXPermissions.isGranted(this, Permission.ACCESS_FINE_LOCATION)) { + switch (type) { + case RC_LOCATION_PERM_SCAN: + requestBtScanPermission(); + break; + case RC_LOCATION_PERM_CONNECT: + requestBtConnectPermission(); + break; + } + } else { + new MaterialDialog.Builder(this) + .title(Rstring.location_permission()) + .content(Rstring.bluetooth_need_location_permission()) + .canceledOnTouchOutside(false) + .positiveText(Rstring.to_allow()) + .negativeText(Rstring.refuse()) + .onPositive(new MaterialDialog.SingleButtonCallback() { + @Override + public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) { + XXPermissions.with(ConnectTSActivity.this).permission(Permission.ACCESS_FINE_LOCATION, Permission.ACCESS_COARSE_LOCATION).request(new OnPermissionCallback() { + @Override + public void onGranted(List permissions, boolean all) { + if (all || permissions.contains(Permission.ACCESS_FINE_LOCATION)) { + startService(); + if (updateBluetoothList()) { + ThreadPoolUtil.executeInMain(new Runnable() { + @Override + public void run() { + switch (type) { + case RC_LOCATION_PERM_SCAN: + requestBtScanPermission(); + break; + case RC_LOCATION_PERM_CONNECT: + requestBtConnectPermission(); + break; + } + } + }, 500); + } + } + } + + @Override + public void onDenied(List permissions, boolean never) { + if (never) { + ToastUtils.showLong(com.bingce.device.ui.R.string.bluetooth_scan_requires_positioning_permission_please_turn_it_on_manually); + // 如果是被永久拒绝就跳转到应用权限系统设置页面 + XXPermissions.startPermissionActivity(ConnectTSActivity.this, permissions); + } else { + requestLocationPermission(type); + } + } + }); + } + }).onNegative(new MaterialDialog.SingleButtonCallback() { + @Override + public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) { + ToastUtils.showLong(com.bingce.device.ui.R.string.bluetooth_connection_requires_positioning_permission_please_turn_it_on_manually); + } + }).show(); + } + } + + public void requestBtScanPermission() { + currentRequestCode = RC_BLUETOOTH_PERM_SCAN; + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) { + if (XXPermissions.isGranted(this, Permission.BLUETOOTH_SCAN, Permission.BLUETOOTH_CONNECT)) { + doDiscovery(); + } else { + new MaterialDialog.Builder(this) + .title(Rstring.bluetooth_scan_permission()) + .content(Rstring.bluetooth_scan_need_permission()) + .canceledOnTouchOutside(false) + .positiveText(Rstring.to_allow()) + .negativeText(Rstring.refuse()) + .onPositive(new MaterialDialog.SingleButtonCallback() { + @Override + public void onClick(@NonNull MaterialDialog materialDialog, @NonNull DialogAction dialogAction) { + XXPermissions.with(ConnectTSActivity.this) + .permission(Permission.BLUETOOTH_SCAN, Permission.BLUETOOTH_CONNECT) + .request(new OnPermissionCallback() { + @Override + public void onGranted(List permissions, boolean all) { + if (all) { + startService(); + if (updateBluetoothList()) { + ThreadPoolUtil.executeInMain(new Runnable() { + @Override + public void run() { + doDiscovery(); + } + }, 500); + } + } else if (!permissions.contains(Permission.BLUETOOTH_SCAN)) { + requestBtScanPermission(); + } else if (!permissions.contains(Permission.BLUETOOTH_CONNECT)) { + requestBtConnectPermission(); + } + } + + @Override + public void onDenied(List permissions, boolean never) { + if (never) { + if (permissions.contains(Permission.BLUETOOTH_SCAN)) { + ToastUtils.showLong(com.bingce.device.ui.R.string.bluetooth_connection_requires_positioning_permission_please_turn_it_on_manually); + // 如果是被永久拒绝就跳转到应用权限系统设置页面 + XXPermissions.startPermissionActivity(ConnectTSActivity.this, Permission.BLUETOOTH_SCAN); + } else if (permissions.contains(Permission.BLUETOOTH_CONNECT)) { + ToastUtils.showLong(com.bingce.device.ui.R.string.bluetooth_connection_requires_positioning_permission_please_turn_it_on_manually); + // 如果是被永久拒绝就跳转到应用权限系统设置页面 + XXPermissions.startPermissionActivity(ConnectTSActivity.this, Permission.BLUETOOTH_CONNECT); + } + } else { + requestBtScanPermission(); + } + } + }); + } + }) + .onNegative(new MaterialDialog.SingleButtonCallback() { + @Override + public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) { + ToastUtils.showShort(com.bingce.device.ui.R.string.bluetooth_connect_need_permission); + } + }) + .show(); + + } + } else { + doDiscovery(); + } + } + + + public void requestBtConnectPermission() { + currentRequestCode = RC_BLUETOOTH_PERM_CONNECT; + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) { + if (XXPermissions.isGranted(this, Permission.BLUETOOTH_CONNECT)) { + connect(); + } else { + new MaterialDialog.Builder(this) + .title(Rstring.bluetooth_connect_permission()) + .content(Rstring.bluetooth_connect_need_permission()) + .canceledOnTouchOutside(false) + .positiveText(Rstring.to_allow()) + .negativeText(Rstring.refuse()) + .onPositive(new MaterialDialog.SingleButtonCallback() { + @Override + public void onClick(@NonNull MaterialDialog materialDialog, @NonNull DialogAction dialogAction) { + XXPermissions.with(ConnectTSActivity.this) + .permission(Permission.BLUETOOTH_CONNECT) + .request(new OnPermissionCallback() { + @Override + public void onGranted(List permissions, boolean all) { + startService(); + if (updateBluetoothList()) { + ThreadPoolUtil.executeInMain(new Runnable() { + @Override + public void run() { + connect(); + } + }, 500); + } + } + + @Override + public void onDenied(List permissions, boolean never) { + if (never) { + ToastUtils.showLong(com.bingce.device.ui.R.string.bluetooth_connection_requires_positioning_permission_please_turn_it_on_manually); + // 如果是被永久拒绝就跳转到应用权限系统设置页面 + XXPermissions.startPermissionActivity(ConnectTSActivity.this, Permission.BLUETOOTH_CONNECT); + } else { + requestBtConnectPermission(); + } + } + }); + } + }) + .onNegative(new MaterialDialog.SingleButtonCallback() { + @Override + public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) { + ToastUtils.showShort(com.bingce.device.ui.R.string.bluetooth_connect_need_permission); + } + }) + .show(); + } + } else { + connect(); + } + } + + public void connect() { + String checkedInfo; + if (mPairedListView.getCheckedItemPosition() >= 0 && mPairedListView.getCheckedItemPosition() < mPairedDevicesArrayAdapter.getCount()) { + checkedInfo = mPairedDevicesArrayAdapter.getItem(mPairedListView.getCheckedItemPosition()); + } else if (mNewDevicesListView.getCheckedItemPosition() >= 0 && mNewDevicesListView.getCheckedItemPosition() < mNewDevicesArrayAdapter.getCount()) { + checkedInfo = mNewDevicesArrayAdapter.getItem(mNewDevicesListView.getCheckedItemPosition()); + } else { + ToastUtils.showShort(Rstring.please_choose_device_first()); + return; + } + String[] arr = checkedInfo.split("\n", 0); + if (arr.length != 2) { + return; + } + ToastUtils.showShort(Rstring.connecting_please_wait()); + Device.getInstance().deviceBlueName = arr[0]; + Device.getInstance().deviceMacAddress = arr[1]; + Gnss.getInstance().getDevice().getBlue().setScanName(Device.getInstance().deviceBlueName); + Gnss.getInstance().getDevice().getBlue().setScanAddr(Device.getInstance().deviceMacAddress); + Gnss.getInstance().save(); + Device.getInstance().requestConnect(); + SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(ConnectTSActivity.this); + SharedPreferences.Editor editor = prefs.edit(); + editor.putString("deviceBlueName", Device.getInstance().deviceBlueName); + editor.putString("deviceMacAddress", Device.getInstance().deviceMacAddress); + editor.apply(); + } + + public void showCoordPrefixDialog() { + MaterialDialog dialog = new MaterialDialog.Builder(this).title(Rstring.coordinate_prefix()).customView(Rlayout.dialog_coord_prefix(), false).onPositive(new MaterialDialog.SingleButtonCallback() { + @Override + public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) { + TsConfig.getInstance().setPrefixX(met_coord_prefix_x.getText().toString().trim()); + TsConfig.getInstance().setPrefixY(met_coord_prefix_y.getText().toString().trim()); + TsConfig.getInstance().setPrefixZ(met_coord_prefix_z.getText().toString().trim()); + TsConfig.getInstance().save(); + SoftKeyUtils.hideSoftKey(); + } + }).positiveText(this.getString(Rstring.save())).negativeText(this.getString(Rstring.cancel())).build(); + + met_coord_prefix_x = dialog.getCustomView().findViewById(Rid.met_dialog_coord_prefix_x()); + met_coord_prefix_y = dialog.getCustomView().findViewById(Rid.met_dialog_coord_prefix_y()); + met_coord_prefix_z = dialog.getCustomView().findViewById(Rid.met_dialog_coord_prefix_z()); + + initMaterialEditTextColor(); + + met_coord_prefix_x.setText(TsConfig.getInstance().getPrefixX()); + met_coord_prefix_y.setText(TsConfig.getInstance().getPrefixY()); + met_coord_prefix_z.setText(TsConfig.getInstance().getPrefixZ()); + + dialog.show(); + } + + @Override + protected void onDestroy() { + super.onDestroy();// 确保我们没有发现,检测设备 + cancelScan(); + // 设置显示进度条 + setProgressBarIndeterminateVisibility(false); + + TsListener.getInstance().removeTsTestListener(this); + + if (publicReceiver != null) unregisterReceiver(publicReceiver); + } + + @SuppressLint("MissingPermission") + private void doDiscovery() { + if (!XXPermissions.isGranted(this, Permission.BLUETOOTH_SCAN)) { + return; + } + // 显示新设备的子标题 + layoutNewDevices.setVisibility(View.VISIBLE); + cancelScan(); + // 如果已经在请求现实了,那么就先停止 + if (Device.getInstance().connectType == ConnectTypeEnum.CONNECT_TYPE_SPP) { + // 请求从蓝牙适配器得到能够被发现的设备 + if (mBtAdapter != null) { + mBtAdapter.startDiscovery(); + } + ToastUtils.showLong(Rstring.scanning()); + } else { + BleScanner.getInstance().scan(null, null, null, false, 30000, new BleScanCallback() { + @Override + public void onScanFinished(List scanResultList) { + ToastUtils.showShort(com.bingce.device.ui.R.string.scan_complete); + } + + @Override + public void onScanStarted(boolean success) { + ToastUtils.showLong(Rstring.scanning()); + } + + @Override + public void onScanning(BleDevice bleDevice) { + if (bleDevice.getName() == null) return; + String itemString = bleDevice.getName() + "\n" + bleDevice.getMac(); +// for (int i = 0; i < mPairedDevicesArrayAdapter.getCount(); i++) { +// if (itemString.equals(mPairedDevicesArrayAdapter.getItem(i))) { +// return; +// } +// } + int count = mNewDevicesArrayAdapter.getCount(); + if (count < 1) {//列表为空时,直接添加,不需要检查是否重复 + mNewDevicesArrayAdapter.add(itemString); + } else {//列表不为空时检查是否重复 + boolean has = false; + for (int j = 0; j < count; j++) { + if (itemString.equals(mNewDevicesArrayAdapter.getItem(j))) { + has = true; + break; + } + } + if (!has) { + mNewDevicesArrayAdapter.add(itemString); + } + } + } + }); + } + } + + /** + * 取消蓝牙扫描 + */ + @SuppressLint("MissingPermission") + private void cancelScan() { + if (!XXPermissions.isGranted(this, Permission.BLUETOOTH_SCAN)) { + return; + } + if (mBtAdapter != null && mBtAdapter.isDiscovering()) { + mBtAdapter.cancelDiscovery(); + } + if (BleManager.getInstance().getScanSate() == BleScanState.STATE_SCANNING) + BleManager.getInstance().cancelScan(); + } + + View.OnClickListener listener = new View.OnClickListener() { + @Override + public void onClick(View v) { + int id = v.getId(); + if (id == Rid.activity_connect_total_station_btn_test()) { + if (Device.getInstance().isDeviceConnected()) { + TotalStation.getInstance().requestTest(); + } else { + ToastUtils.showShort(com.bingce.device.ui.R.string.no_instrument_connected); + } + } +// else if (id == Rid.activity_connect_total_station_btn_guide()) { +// EventBus.getDefault().post(new OpenShortUrlEvent("android_url_ts_communication_guide")); +// } else if (id == Rid.activity_connect_total_station_taobao()) { +// new AlertDialog.Builder(ConnectTSActivity.this) +// .setTitle(Rstring.hint()).setMessage(Rstring.buy_bluetooth_explain()) +// .setPositiveButton(Rstring.buy(), new DialogInterface.OnClickListener() { +// @Override +// public void onClick(DialogInterface dialog, int which) { +// EventBus.getDefault().post(new OpenShortUrlEvent("bluetoothTaobaoUrl")); +// } +// }) +// .setNegativeButton(Rstring.cancel(), null) +// .show(); +// } + } + }; + + class PublicReceiver extends BroadcastReceiver { + @SuppressLint("MissingPermission") + @Override + public void onReceive(Context context, Intent intent) { + String action = intent.getAction(); + // 当发现一个设备时 + if (BluetoothDevice.ACTION_FOUND.equals(action)) { + if (!XXPermissions.isGranted(ConnectTSActivity.this, Permission.BLUETOOTH_CONNECT, Permission.ACCESS_FINE_LOCATION)) { + return; + } + // 从Intent得到蓝牙设备对象 + BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE); + // 如果已经配对,则跳过,因为他已经在设备列表中了 + if (device != null && device.getName() != null /*&& device.getBondState() != BluetoothDevice.BOND_BONDED*/) { + // 否则添加到新设备列表 + int count = mNewDevicesArrayAdapter.getCount(); + String itemString = device.getName() + "\n" + device.getAddress(); + if (count < 1) {//列表为空时,直接添加,不需要检查是否重复 + mNewDevicesArrayAdapter.add(itemString); + } else {//列表不为空时检查是否重复 + boolean has = false; + for (int i = 0; i < count; i++) { + if (itemString.equals(mNewDevicesArrayAdapter.getItem(i))) { + has = true; + break; + } + } + if (!has) { + mNewDevicesArrayAdapter.add(itemString); + } + } + } + } else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) { + // 如果计数为0,则表示没有发现蓝牙 + if (mNewDevicesArrayAdapter.getCount() == 0) { + ToastUtils.showLong(Rstring.none_found()); + } + } + } + } + + private void initMaterialEditTextColor() { + if (Device.getInstance().isThemeDark) { + met_coord_prefix_x.setMetTextColor(Color.WHITE); + met_coord_prefix_y.setMetTextColor(Color.WHITE); + met_coord_prefix_z.setMetTextColor(Color.WHITE); + + met_coord_prefix_x.setPrimaryColor(Color.LTGRAY); + met_coord_prefix_y.setPrimaryColor(Color.LTGRAY); + met_coord_prefix_z.setPrimaryColor(Color.LTGRAY); + + met_coord_prefix_x.setFocusFraction(1.0f); + met_coord_prefix_y.setFocusFraction(1.0f); + met_coord_prefix_z.setFocusFraction(1.0f); + + met_coord_prefix_x.setMetHintTextColor(Color.GRAY); + met_coord_prefix_y.setMetHintTextColor(Color.GRAY); + met_coord_prefix_z.setMetHintTextColor(Color.GRAY); + + met_coord_prefix_x.setUnderlineColor(Color.GRAY); + met_coord_prefix_y.setUnderlineColor(Color.GRAY); + met_coord_prefix_z.setUnderlineColor(Color.GRAY); + } + } + + /** + * 获取热点创建状态 + **/ + public static boolean isWifiApOpen() { + WifiManager wifiManager = (WifiManager) Utils.getApp().getApplicationContext().getSystemService(Context.WIFI_SERVICE); + try { + int i = (Integer) wifiManager.getClass().getMethod("getWifiApState", new Class[0]).invoke(wifiManager, new Object[0]); + return i == WIFI_AP_STATE_ENABLED; + } catch (Exception ignored) { + } + return false; + } + + public static void start() { + Device.getInstance().deviceType = DeviceTypeEnum.DEVICE_TYPE_TS; + ActivityUtils.startActivity(ConnectTSActivity.class); + } + + public static void start(Context context) { + Device.getInstance().deviceType = DeviceTypeEnum.DEVICE_TYPE_TS; + context.startActivity(startIntent(context)); + } + + public static void start(Fragment fragment) { + Device.getInstance().deviceType = DeviceTypeEnum.DEVICE_TYPE_TS; + fragment.startActivity(startIntent(fragment.getActivity())); + } + + private static Intent startIntent(Context context) { + Intent intent500 = new Intent(context, ConnectTSActivity.class); + intent500.putExtra("customChannel", AppChannel.customChannel); + return intent500; + } + + @Override + public void onTsTestSuccess(Coordinate coordinate) { + String instrumentInfo; + if (Device.getInstance().connectType == ConnectTypeEnum.CONNECT_TYPE_HOTSPOT) { + instrumentInfo = "Wifi\n" + "IP:" + TsConfig.getInstance().getIp() + "\n" + getString(Rstring.port()) + ":" + TsConfig.getInstance().getPort() + "\n"; + } else { + instrumentInfo = getString(Rstring.instrument_name()) + ":" + Device.getInstance().deviceBlueName + "\n" + getString(Rstring.instrument_type_name()) + ":" + Device.getInstance().deviceBrand + "\n" + getString(Rstring.comm_delay()) + ":" + TsConfig.getInstance().getCommDelay().getName() + "\n"; + } + StringBuffer buffer = new StringBuffer(); + buffer.append(instrumentInfo); + if (TsConfig.getInstance().getSetupStationMethod().getMode() != SetupStationModeEnum.ON_TOTAL_STATION || !TotalStation.getInstance().isSupportCoordinate()) { + buffer.append(StringUtils.getString(totalstation.Rstring.this_ts_type_need_setup_station_in_totalstation()) + "\n"); + } + if (coordinate != null) { + buffer.append("\nX=" + Util.formatDouble2StringDotAuto(coordinate.getX()) + "\nY=" + Util.formatDouble2StringDotAuto(coordinate.getY()) + "\nZ=" + Util.formatDouble2StringDotAuto(coordinate.getZ()) + "\n"); + } + + if (TotalStation.getInstance() instanceof TopconInterface) { + buffer.append(com.bingce.device.ui.R.string.if_the_coordinates_are_reduced_by_a_factor_of_10_modify_the_decimal_point_setting_of_the_total_station_to_4_digits); + } + new MaterialDialog.Builder(ConnectTSActivity.this) + .title(Rstring.test_result()) + .content(buffer.toString()) + .negativeText(Rstring.close()) + .show(); + } + + @Override + public void onTsTestFailed(String errorMsg, String original) { + new MaterialDialog.Builder(ConnectTSActivity.this) + .title(Rstring.test_result()) + .content(errorMsg + "\n" + original) + .negativeText(Rstring.close()) + .show(); + } +} \ No newline at end of file diff --git a/app/src/main/java/com/project/survey/ui/project/ProjectListActivity.kt b/app/src/main/java/com/project/survey/ui/project/ProjectListActivity.kt index 7e735fb..5a14a2c 100644 --- a/app/src/main/java/com/project/survey/ui/project/ProjectListActivity.kt +++ b/app/src/main/java/com/project/survey/ui/project/ProjectListActivity.kt @@ -4,15 +4,19 @@ import android.view.Menu import android.view.MenuItem import androidx.activity.viewModels import com.afollestad.materialdialogs.MaterialDialog +import com.bingce.data.database.KeyValueDb +import com.bingce.data.database.ProjectDb +import com.bingce.data.surveyor.designdata.kv.KeyValueConstants +import com.bingce.data.surveyor.designdata.kv.KeyValueRecord +import com.bingce.data.surveyor.designdata.project.ProjectRecord +import com.bingce.utils.ThreadPoolUtil import com.project.survey.R import com.project.survey.constants.EventConstants import com.project.survey.constants.SPConstants import com.project.survey.databinding.ActivityProjectListBinding import com.project.survey.extend.smartDismiss -import com.project.survey.extend.toast import com.project.survey.logic.event.Message import com.project.survey.logic.viewmodel.ProjectViewModel -import com.project.survey.model.LoginBean import com.project.survey.ui.MainActivity import com.project.survey.ui.base.BaseBindingActivity import com.project.survey.ui.login.LoginActivity @@ -23,6 +27,7 @@ import com.project.survey.util.SPUtils import com.project.survey.widget.decoration.HorDividerDecoration import com.scwang.smart.refresh.layout.api.RefreshLayout import com.scwang.smart.refresh.layout.listener.OnRefreshListener +import java.util.Date class ProjectListActivity : BaseBindingActivity(), OnRefreshListener { @@ -89,6 +94,26 @@ class ProjectListActivity : BaseBindingActivity(), O adapter.getItem(position)?.let { bean -> // 进入项目,设置当前项目 SPUtils.put(SPConstants.CURRENT_PROJECT, bean) + // 存储配置--当前项目 + ThreadPoolUtil.execute { + //存储新的项目 + ProjectDb.getInstance().save( + ProjectRecord(bean.BD_XMXX_ID, bean.XMXX_NAME, null, Date().time).apply { + author = bean.XMXX_CONTACTNAME + } + ) + + var currentProjectConfig = + KeyValueDb.getInstance().findData(KeyValueConstants.KEY_CURRENT_PROJECT_ID) + if (currentProjectConfig != null) { + currentProjectConfig.value = bean.XMXX_CODE + } else { + currentProjectConfig = + KeyValueRecord(KeyValueConstants.KEY_CURRENT_PROJECT_ID, bean.XMXX_CODE) + } + KeyValueDb.getInstance().save(currentProjectConfig) + } + viewModel.msgEvent.postValue(Message(EventConstants.UPDATE_PROJECT)) MainActivity.start() ActivityNavUtil.finishActivity() diff --git a/app/src/main/res/menu/menu_activity_connect_rtk.xml b/app/src/main/res/menu/menu_activity_connect_rtk.xml new file mode 100644 index 0000000..aa3e7d3 --- /dev/null +++ b/app/src/main/res/menu/menu_activity_connect_rtk.xml @@ -0,0 +1,21 @@ + + + + + + + + + + \ No newline at end of file