diff --git a/android/app/build.gradle b/android/app/build.gradle index 66a7f0cd..47057c8e 100644 --- a/android/app/build.gradle +++ b/android/app/build.gradle @@ -148,6 +148,12 @@ dependencies { implementation 'androidx.work:work-runtime:2.7.0-alpha05' androidTestImplementation "androidx.test:core:1.4.0" implementation "org.jetbrains.kotlinx:kotlinx-coroutines-core:1.4.2" + implementation 'com.android.support:appcompat-v7:27.1.1' + testImplementation 'junit:junit:4.12' + implementation project(':blesdk_2301') + // compile "com.jstyle:1770sdk:1.0.2" + implementation 'io.reactivex.rxjava3:rxjava:3.1.3' + implementation 'io.reactivex.rxjava3:rxandroid:3.0.0' // implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-android:1.4.2' // Lepu Libraries implementation 'no.nordicsemi.android:ble:2.2.4' diff --git a/android/app/src/main/kotlin/com/cloud/diplomaticquarterapp/MainActivity.kt b/android/app/src/main/kotlin/com/cloud/diplomaticquarterapp/MainActivity.kt index b21d9107..97e166d1 100644 --- a/android/app/src/main/kotlin/com/cloud/diplomaticquarterapp/MainActivity.kt +++ b/android/app/src/main/kotlin/com/cloud/diplomaticquarterapp/MainActivity.kt @@ -9,6 +9,7 @@ import io.flutter.embedding.android.FlutterFragmentActivity import io.flutter.embedding.engine.FlutterEngine import io.flutter.plugins.GeneratedPluginRegistrant import com.cloud.diplomaticquarterapp.ble.BleBridge +import com.cloud.diplomaticquarterapp.smart_ring_2301.BleManager @Suppress("DEPRECATION") class MainActivity : FlutterFragmentActivity() { @@ -20,6 +21,7 @@ class MainActivity : FlutterFragmentActivity() { this.window.addFlags(WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED or WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON or WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD or WindowManager.LayoutParams.FLAG_ALLOW_LOCK_WHILE_SCREEN_ON) PlatformBridge(flutterEngine, this).create() OpenTokPlatformBridge(flutterEngine, this).create() + BleManager.init(this) BleBridge(flutterEngine, this).createBleBridge(BleScanManager()) { name, bluetoothDevice -> // Handle the scan result here Log.d("MainActivity", "Received scan result: $name, $bluetoothDevice") diff --git a/android/app/src/main/kotlin/com/cloud/diplomaticquarterapp/ble/BleBridge.kt b/android/app/src/main/kotlin/com/cloud/diplomaticquarterapp/ble/BleBridge.kt index b2b36e3c..7da5d779 100644 --- a/android/app/src/main/kotlin/com/cloud/diplomaticquarterapp/ble/BleBridge.kt +++ b/android/app/src/main/kotlin/com/cloud/diplomaticquarterapp/ble/BleBridge.kt @@ -1,60 +1,59 @@ package com.cloud.diplomaticquarterapp.ble + +//Ble +import BaseActivity import TmpInfo import android.annotation.SuppressLint import android.bluetooth.BluetoothDevice import android.os.Build import android.os.Handler import android.util.Log -import io.flutter.embedding.engine.FlutterEngine -import io.flutter.plugin.common.MethodCall -import io.flutter.plugin.common.MethodChannel -import io.flutter.plugin.common.EventChannel import android.util.SparseArray -import android.view.View import androidx.annotation.RequiresApi +import com.cloud.diplomaticquarterapp.MainActivity import com.cloud.diplomaticquarterapp.ble.utils.EcgData import com.cloud.diplomaticquarterapp.ble.utils.HexString import com.cloud.diplomaticquarterapp.check_me_pro.bean.BleBean import com.cloud.diplomaticquarterapp.check_me_pro.bean.UserBean -import com.cloud.diplomaticquarterapp.check_me_pro.ble.format.UserInfo -import com.cloud.diplomaticquarterapp.check_me_pro.ble.manager.BleScanManager -import com.cloud.diplomaticquarterapp.check_me_pro.ble.worker.BleDataWorker -import com.cloud.diplomaticquarterapp.utils.Constant -import com.cloud.diplomaticquarterapp.MainActivity import com.cloud.diplomaticquarterapp.check_me_pro.bean.toJson import com.cloud.diplomaticquarterapp.check_me_pro.ble.format.BpInfo import com.cloud.diplomaticquarterapp.check_me_pro.ble.format.EcgInfo import com.cloud.diplomaticquarterapp.check_me_pro.ble.format.EcgWaveInfo import com.cloud.diplomaticquarterapp.check_me_pro.ble.format.GluInfo import com.cloud.diplomaticquarterapp.check_me_pro.ble.format.OxyInfo +import com.cloud.diplomaticquarterapp.check_me_pro.ble.format.UserInfo +import com.cloud.diplomaticquarterapp.check_me_pro.ble.manager.BleScanManager +import com.cloud.diplomaticquarterapp.check_me_pro.ble.worker.BleDataWorker +import com.cloud.diplomaticquarterapp.smart_ring_2301.BleManager +import com.cloud.diplomaticquarterapp.utils.Constant import com.cloud.diplomaticquarterapp.utils.UiChannel import com.google.gson.Gson - - -//Ble import com.jeremyliao.liveeventbus.LiveEventBus +import com.jstyle.blesdk2301.Util.BleSDK +import com.jstyle.blesdk2301.callback.BleConnectionListener +import com.jstyle.blesdk2301.constant.BleConst import com.lepu.blepro.event.EventMsgConst import com.lepu.blepro.event.EventMsgConst.Ble.* import com.lepu.blepro.event.InterfaceEvent import com.lepu.blepro.ext.BleServiceHelper -import com.lepu.blepro.ext.bp2.Bp2File -import com.lepu.blepro.ext.bp2.BpFile -import com.lepu.blepro.ext.bp2.EcgFile -import com.lepu.blepro.ext.bp2.RtBpIng +import com.lepu.blepro.ext.bp2.* +import com.lepu.blepro.ext.er1.Er1EcgFile +import com.lepu.blepro.ext.er1.Er1File import com.lepu.blepro.ext.er2.DeviceInfo import com.lepu.blepro.ext.er2.Er2EcgFile import com.lepu.blepro.ext.er2.Er2File import com.lepu.blepro.ext.er2.RtData -import com.lepu.blepro.ext.bp2.* -import com.lepu.blepro.ext.er1.Er1EcgFile -import com.lepu.blepro.ext.er1.Er1File import com.lepu.blepro.ext.pc60fw.RtParam import com.lepu.blepro.ext.sp20.RtWave import com.lepu.blepro.objs.Bluetooth import com.lepu.blepro.objs.BluetoothController import com.lepu.blepro.utils.DateUtil import com.lepu.blepro.utils.Er1Decompress +import io.flutter.embedding.engine.FlutterEngine +import io.flutter.plugin.common.EventChannel +import io.flutter.plugin.common.MethodCall +import io.flutter.plugin.common.MethodChannel import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.MainScope @@ -65,10 +64,8 @@ import kotlinx.coroutines.withTimeoutOrNull import org.apache.commons.io.FileUtils import org.json.JSONObject import java.io.File -import java.text.SimpleDateFormat -import java.util.Locale -class BleBridge(private var flutterEngine: FlutterEngine, private var mainActivity: MainActivity) { +class BleBridge(private var flutterEngine: FlutterEngine, private var mainActivity: MainActivity) : BaseActivity() { private lateinit var channel: MethodChannel private lateinit var Echannel: EventChannel @@ -104,6 +101,13 @@ class BleBridge(private var flutterEngine: FlutterEngine, private var mainActivi private const val GET_ECG_WAVE_CHECK_ME_PRO = "getEcgWaveFromCheckMePro" private const val GET_GLUCOSE_DATA_CHECK_ME_PRO = "getGlucoseDataFromCheckMePro" + //FOR SMART RING + private const val SCAN_FOR_SMART_RING = "scanForSmartRing" + private const val CONNECT_DEVICE_SMART_RING = "connectDeviceSmartRing" + private const val DISCONNECT_DEVICE_SMART_RING = "disConnectDeviceSmartRing" + private const val GET_BATTERY_LEVEL_SMART_RING = "getBatteryLevelSmartRing" + + val scan = BleScanManager() val dataScope = CoroutineScope(Dispatchers.IO) val uiScope = CoroutineScope(Dispatchers.Main) @@ -235,12 +239,15 @@ class BleBridge(private var flutterEngine: FlutterEngine, private var mainActivi } + private var mHandler: Handler? = null + @SuppressLint("NewApi") fun createBleBridge(bleScanManager: BleScanManager, scanResultHandler: (String, BluetoothDevice) -> Unit) { channel = MethodChannel(flutterEngine.dartExecutor.binaryMessenger, CHANNEL) Echannel = EventChannel(flutterEngine.dartExecutor.binaryMessenger, EVENTCHANNEL) channel.setMethodCallHandler { methodCall: MethodCall, result: MethodChannel.Result -> + if (methodCall.method == SCAN_DEVICE) { scanDevice() } else if (methodCall.method == STOP_SCAN) { @@ -249,8 +256,6 @@ class BleBridge(private var flutterEngine: FlutterEngine, private var mainActivi connectDevice(methodCall.arguments as List) } else if (methodCall.method == DISCONNECT_DEVICE) { disconnectDevice(methodCall, result) - } else if (methodCall.method == STOP_SCAN_CHECK_ME) { - stopScanForCheckMePro() } else if (methodCall.method == CONNECT_DEVICE_CHECK_ME) { connectDeviceCheckMe(methodCall.arguments as List) } else if (methodCall.method == DISCONNECT_CHECK_ME) { @@ -277,8 +282,16 @@ class BleBridge(private var flutterEngine: FlutterEngine, private var mainActivi getBP2FilesList() } else if (methodCall.method == SCAN_FOR_CHECK_ME_PRO) { scanForCheckMePro(bleScanManager, scanResultHandler) - } else if (methodCall.method == READ_USER_CHECK_ME_PRO) { - + } else if (methodCall.method == STOP_SCAN_CHECK_ME) { + stopScanForCheckMePro() + } else if (methodCall.method == SCAN_FOR_SMART_RING) { + scanForSmartRing(bleScanManager) + } else if (methodCall.method == CONNECT_DEVICE_SMART_RING) { + connectDeviceSmartRing(methodCall.arguments as String); + } else if (methodCall.method == DISCONNECT_DEVICE_SMART_RING) { + disConnectDeviceSmartRing() + } else if (methodCall.method == GET_BATTERY_LEVEL_SMART_RING) { + getBatteryLevelSmartRing(); } else { result.notImplemented() } @@ -293,8 +306,6 @@ class BleBridge(private var flutterEngine: FlutterEngine, private var mainActivi } }, ) - - } private fun stopScanForCheckMePro() { @@ -1003,4 +1014,88 @@ class BleBridge(private var flutterEngine: FlutterEngine, private var mainActivi } + // SMART RING FUNCTIONS + var filterRssi: Int = -100 + + @SuppressLint("MissingPermission") + fun onScanResultSmartRing(name: String, bluetoothDevice: BluetoothDevice) { + if (!(name.contains("2301"))) return; + Log.d("SmartRingDeviceFound", "This is the Device Name: $name") + val bluetoothDeviceJson = JSONObject().apply { + put("name", bluetoothDevice.name ?: "") + put("macAddr", bluetoothDevice.address ?: "") + put("type", bluetoothDevice.type) + // Add more properties as needed + } + + println("EventDeviceFound : ${bluetoothDeviceJson.toString()}") + + val returnData = mapOf("type" to "DevicesListSmartRing", "data" to bluetoothDeviceJson.toString()) + eventSink?.success(returnData) + + } + + @RequiresApi(Build.VERSION_CODES.M) + private fun scanForSmartRing(bleScanManager: BleScanManager) { + initVar() + bleScanManager.initScan(this.mainActivity) + bleScanManager.setCallBack(object : BleScanManager.Scan { + override fun scanReturn(name: String, bluetoothDevice: BluetoothDevice) { + onScanResultSmartRing(name, bluetoothDevice) + } + }) + } + + private fun connectDeviceSmartRing(deviceAddress: String) { + BleManager.instance?.connectDevice(deviceAddress, true, object : BleConnectionListener { + override fun BleStatus(status: Int, newState: Int) { //蓝牙4.0连接状态 Bluetooth 4.0 connection status + Log.e("BleStatus", "BleStatus: $status***$newState") + } + + override fun ConnectionSucceeded() { //连接设备成功 Successfully connected the device + Log.e("BleStatus", "ConnectionSucceeded") + } + + override fun Connecting() { //设备连接中 Device is connected + Log.e("BleStatus", "Connecting") + } + + override fun ConnectionFailed() { //设备连接失败 Device connection failed + Log.e("BleStatus", "ConnectionFailed") + } + + override fun OnReconnect() { //重新连接中 Reconnecting + Log.e("BleStatus", "OnReconnect") + } + + override fun BluetoothSwitchIsTurnedOff() { //蓝牙开关被关闭 Bluetooth switch is turned off + Log.e("BleStatus", "BluetoothSwitchIsTurnedOff") + } + }) + + } + + private fun disConnectDeviceSmartRing() { + BleManager.instance?.disconnectDevice(); + } + + + private fun getBatteryLevelSmartRing() { + sendValue(BleSDK.GetDeviceBatteryLevel()); + } + + + override fun dataCallback(maps: Map?) { + super.dataCallback(maps) + val dataType = getDataType(maps) + Log.d("dataCallbackType", dataType.toString()) + + when (dataType) { + BleConst.GetDeviceBatteryLevel -> { + Log.d("BatteryLevel", maps.toString()) + } + } + } + + } \ No newline at end of file diff --git a/android/app/src/main/kotlin/com/cloud/diplomaticquarterapp/smart_ring_2301/BaseActivity.kt b/android/app/src/main/kotlin/com/cloud/diplomaticquarterapp/smart_ring_2301/BaseActivity.kt new file mode 100644 index 00000000..8aca9482 --- /dev/null +++ b/android/app/src/main/kotlin/com/cloud/diplomaticquarterapp/smart_ring_2301/BaseActivity.kt @@ -0,0 +1,105 @@ +import android.os.Bundle +import android.util.Log +import android.widget.Toast +import androidx.appcompat.app.AppCompatActivity +import com.cloud.diplomaticquarterapp.smart_ring_2301.BleManager +import com.cloud.diplomaticquarterapp.smart_ring_2301.BleService +import com.cloud.diplomaticquarterapp.smart_ring_2301.Util.BleData +import com.cloud.diplomaticquarterapp.smart_ring_2301.Util.RxBus +import com.jstyle.blesdk2301.Util.BleSDK.DataParsingWithData +import com.jstyle.blesdk2301.callback.DataListener2301 +import com.jstyle.blesdk2301.constant.DeviceKey +import io.reactivex.rxjava3.disposables.Disposable +import io.reactivex.rxjava3.schedulers.Schedulers +import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers + +import javax.annotation.Nullable + + +open class BaseActivity : AppCompatActivity(), DataListener2301 { + private var subscription: Disposable? = null + + override fun onCreate(@Nullable savedInstanceState: Bundle?) { + super.onCreate(savedInstanceState) + subscribe() + } + + protected open fun subscribe() { + subscription = RxBus.instance.toObservable(BleData::class.java).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe { bleData -> + val action = bleData.action + if (action == BleService.ACTION_DATA_AVAILABLE) { + val value = bleData.value + if (value != null) { + DataParsingWithData(value, this@BaseActivity) + } + } + } + } + + protected fun unSubscribe(disposable: Disposable?) { + if (disposable != null && !disposable.isDisposed) { + disposable.dispose() + } + } + + protected override fun onDestroy() { + super.onDestroy() + unSubscribe(subscription) + } + + protected fun Baseunsubscribe() { + unSubscribe(subscription) + } + + protected fun Gateaus(count: Int) {} + override fun dataCallback(maps: Map?) { + Log.e("info", maps.toString()) + } + + + override fun dataCallback(value: ByteArray?) { + + } + + /** + * 当蓝牙设备是连接的状态,发送指令给设备 + * When the Bluetooth device is connected, send instructions to the device + * @param value + */ + protected fun sendValue(value: ByteArray?) { + + if (value == null) return + BleManager.instance?.writeValue(value) + } + + protected fun showToast(text: String?) { + Toast.makeText(this, text, Toast.LENGTH_SHORT).show() + } + + + protected fun getEnd(maps: Map): Boolean { + return maps[DeviceKey.End] as Boolean + } + + protected fun offerData(value: ByteArray?) { + BleManager.instance?.offerValue(value) + } + + protected fun offerData() { + BleManager.instance?.writeValue() + } + + + companion object { + @JvmStatic + protected fun getDataType(maps: Map?): String? { + return if (null == maps) { + "" + } else maps[DeviceKey.DataType] as String? + } + + protected fun getData(maps: Map): Map? { + return maps[DeviceKey.Data] as Map? + } + } +} \ No newline at end of file diff --git a/android/app/src/main/kotlin/com/cloud/diplomaticquarterapp/smart_ring_2301/BleManager.kt b/android/app/src/main/kotlin/com/cloud/diplomaticquarterapp/smart_ring_2301/BleManager.kt new file mode 100644 index 00000000..bdead682 --- /dev/null +++ b/android/app/src/main/kotlin/com/cloud/diplomaticquarterapp/smart_ring_2301/BleManager.kt @@ -0,0 +1,235 @@ +package com.cloud.diplomaticquarterapp.smart_ring_2301 + +import android.annotation.SuppressLint +import android.annotation.TargetApi +import android.app.Service +import android.bluetooth.BluetoothAdapter +import android.bluetooth.BluetoothManager +import android.bluetooth.le.ScanCallback +import android.bluetooth.le.ScanResult +import android.bluetooth.le.ScanSettings +import android.content.ComponentName +import android.content.Context +import android.content.Intent +import android.content.ServiceConnection +import android.os.Build +import android.os.IBinder +import android.text.TextUtils +import com.jstyle.blesdk2301.callback.BleConnectionListener +import com.jstyle.blesdk2301.callback.OnScanResults +import com.jstyle.blesdk2301.model.Device +import java.util.Locale + +/** + * 蓝牙管理类 Bluetooth management class + */ +@SuppressLint("MissingPermission") +class BleManager private constructor(var context: Context) { + private var address: String? = null + private var bleService: BleService? = null + private val serviceConnection: ServiceConnection = object : ServiceConnection { + override fun onServiceDisconnected(name: ComponentName) { // TODO Auto-generated method stub + bleService = null + } + + override fun onServiceConnected(name: ComponentName, service: IBinder) { + bleService = (service as BleService.LocalBinder).service + if (!TextUtils.isEmpty(address)) { + bleService!!.initBluetoothDevice(address, context, NeedReconnect1, bleConnectionListener1) + } + } + } + private var serviceIntent: Intent? = null + var bluetoothAdapter: BluetoothAdapter? + val isBleEnable: Boolean + get() = bluetoothAdapter!!.enable() + + /** + * 连接蓝牙设备 + * Connect Bluetooth device + * + * @param address + */ + protected var NeedReconnect1 = true + protected var bleConnectionListener1: BleConnectionListener? = null + fun connectDevice(address: String?, NeedReconnect: Boolean, bleConnectionListener: BleConnectionListener?) { + NeedReconnect1 = NeedReconnect + bleConnectionListener1 = bleConnectionListener + if (!bluetoothAdapter!!.isEnabled || TextUtils.isEmpty(address) || isConnected) return + if (bleService == null) { + this.address = address + } else { + bleService!!.initBluetoothDevice(address, context, NeedReconnect, bleConnectionListener) + } + } + + /** + * 关闭蓝牙服务通知 + * Turn off Bluetooth service notification + */ + fun enableNotifaction() { + if (bleService == null) return + bleService!!.setCharacteristicNotification(true) + } + + /** + * 写入指令到蓝牙设备 + * Write command to Bluetooth device + */ + fun writeValue(value: ByteArray?) { + if (bleService == null || instance == null) return + bleService!!.writeValue(value) + } + + /** + * 多条指令同时添加后发送到设备 + * Multiple instructions are added at the same time and sent to the device + * + * @param data + */ + fun offerValue(data: ByteArray?) { + if (bleService == null) return + if (data != null) { + bleService!!.offerValue(data) + } + } + + /** + * 写入指令到蓝牙设备 + * Write command to Bluetooth device + */ + fun writeValue() { + if (bleService == null) return + bleService!!.nextQueue() + } + + /** + * 断开设备 Disconnect the device + */ + fun disconnectDevice() { + if (bleService == null) return + bleService!!.disconnect() + } + + val isConnected: Boolean + /** + * 查询设备是否已经连接 + * Query whether the device is connected + * + * @return + */ + get() = if (bleService == null) false else bleService!!.isConnected + + /** + * 取消扫描设备 + * Cancel scanning device + */ + @TargetApi(Build.VERSION_CODES.LOLLIPOP) + fun StopDeviceScan() { + isinScan = false + if (null != bluetoothAdapter && null != bluetoothAdapter!!.bluetoothLeScanner) { + bluetoothAdapter!!.bluetoothLeScanner.stopScan(scanCallback) + } + } + + /** + * 扫描蓝牙设备,用于开始绑定设备 + * Scan Bluetooth device to start binding device + */ + private var DevicesName: Array? = null + private var onScanResult: OnScanResults? = null + private var isinScan = false + @TargetApi(Build.VERSION_CODES.LOLLIPOP) + fun DeviceScanResults(Devicesname: Array, onScanResults: OnScanResults) { + if (!isinScan && instance!!.isBleEnable) { //如果蓝牙开关是开启的就进行扫描 + isinScan = true + DevicesName = Devicesname + onScanResult = onScanResults + //返回已配对设备 + //获得已配对的远程蓝牙设备的集合 + val devices = bluetoothAdapter!!.bondedDevices + if (devices.size > 0) { + for (bluetoothDevice in devices) { + if (Canctians(bluetoothDevice.name.lowercase(Locale.getDefault()))) { + val device = Device() + device.bluetoothDevice = bluetoothDevice + device.isIsconted = false + device.isPaired = true + device.isIsdfu = bluetoothDevice.name.lowercase(Locale.getDefault()).contains("dfu") + device.name = bluetoothDevice.name + device.mac = bluetoothDevice.address + onScanResult!!.Success(device) + } + } + } + bluetoothAdapter!!.bluetoothLeScanner.startScan(null, ScanSettings.Builder().setScanMode(ScanSettings.SCAN_MODE_LOW_LATENCY).build(), scanCallback) + } + } + + private val scanCallback: ScanCallback = object : ScanCallback() { + override fun onScanResult(callbackType: Int, result: ScanResult) { + super.onScanResult(callbackType, result) + val deviceName = result.device.name + if (isinScan && !TextUtils.isEmpty(deviceName) && Canctians(deviceName.lowercase(Locale.getDefault()).trim { it <= ' ' })) { + val device = Device() + device.bluetoothDevice = result.device + device.isIsconted = false + device.isPaired = false + device.isIsdfu = deviceName.lowercase(Locale.getDefault()).contains("dfu") + device.name = result.device.name + device.mac = result.device.address + device.riss = result.rssi + onScanResult!!.Success(device) + } + } + + override fun onBatchScanResults(results: List) { + super.onBatchScanResults(results) + } + + override fun onScanFailed(errorCode: Int) { + super.onScanFailed(errorCode) + onScanResult!!.Fail(errorCode) + } + } + + init { + if (serviceIntent == null) { + serviceIntent = Intent(context, BleService::class.java) + context.bindService(serviceIntent, serviceConnection, Service.BIND_AUTO_CREATE) + } + val bluetoothManager = context.getSystemService(Context.BLUETOOTH_SERVICE) as BluetoothManager + bluetoothAdapter = bluetoothManager.adapter + } + + private fun Canctians(name: String): Boolean { + var catian = false + if (null == DevicesName || DevicesName!!.size == 0) { + return false + } else { + for (devicesname in DevicesName!!) { + if (name.lowercase(Locale.getDefault()).contains(devicesname.lowercase(Locale.getDefault()))) { + catian = true + break + } + } + } + return catian + } + + companion object { + var instance: BleManager? = null + private set + + fun init(context: Context) { + if (instance != null) { + return + } + synchronized(BleManager::class.java) { + if (instance == null) { + instance = BleManager(context) + } + } + } + } +} \ No newline at end of file diff --git a/android/app/src/main/kotlin/com/cloud/diplomaticquarterapp/smart_ring_2301/BleService.kt b/android/app/src/main/kotlin/com/cloud/diplomaticquarterapp/smart_ring_2301/BleService.kt new file mode 100644 index 00000000..bdefbb24 --- /dev/null +++ b/android/app/src/main/kotlin/com/cloud/diplomaticquarterapp/smart_ring_2301/BleService.kt @@ -0,0 +1 @@ +package com.cloud.diplomaticquarterapp.smart_ring_2301 import android.annotation.SuppressLint import android.app.Service import android.bluetooth.BluetoothAdapter import android.bluetooth.BluetoothDevice import android.bluetooth.BluetoothGatt import android.bluetooth.BluetoothGattCallback import android.bluetooth.BluetoothGattCharacteristic import android.bluetooth.BluetoothGattDescriptor import android.bluetooth.BluetoothGattService import android.bluetooth.BluetoothManager import android.bluetooth.BluetoothProfile import android.content.Context import android.content.Intent import android.os.Binder import android.os.Build import android.os.Handler import android.os.IBinder import android.os.Looper import android.text.TextUtils import android.util.Log import com.cloud.diplomaticquarterapp.smart_ring_2301.Util.BleData import com.cloud.diplomaticquarterapp.smart_ring_2301.Util.ResolveData.byte2Hex import com.cloud.diplomaticquarterapp.smart_ring_2301.Util.ResolveData.decodeDeviceName import com.cloud.diplomaticquarterapp.smart_ring_2301.Util.RxBus.Companion.instance import com.jstyle.blesdk2301.callback.BleConnectionListener import java.util.LinkedList import java.util.Queue import java.util.UUID @SuppressLint("MissingPermission") class BleService : Service() { private var NeedReconnect = false var fastconnect = false //是否连接成功过设备 var hasp = HashMap() private val kBinder: IBinder = LocalBinder() private val gattHash = HashMap() private var bluetoothManager: BluetoothManager? = null private var mBluetoothAdapter: BluetoothAdapter? = null private var mGatt: BluetoothGatt? = null var isConnected = false private set private val handler = Handler() override fun onBind(intent: Intent): IBinder? { initAdapter() return kBinder } override fun onUnbind(intent: Intent): Boolean { return super.onUnbind(intent) } /** * 初始化BLE 如果已经连接就不用再次连 * * @param bleDevice * @return */ private var address: String? = null private var mContext: Context? = null protected var bleConnectionListener: BleConnectionListener? = null fun initBluetoothDevice(address: String?, context: Context?, needReconnect: Boolean, bleConnectionListener1: BleConnectionListener?) { if (null != bleConnectionListener1) { bleConnectionListener = bleConnectionListener1 NeedReconnect = needReconnect } //MyLog.i("开始连接"); fastconnect = false this.address = address mContext = context val device = mBluetoothAdapter!!.getRemoteDevice(address) if (isConnected) return if (null != mGatt) { refreshDeviceCache(mGatt) mGatt = null } mGatt = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { device.connectGatt(context, false, bleGattCallback, BluetoothDevice.TRANSPORT_LE) } else { device.connectGatt(context, false, bleGattCallback) } if (mGatt == null) { println(device.address + "gatt is null") } if (null != bleConnectionListener) { bleConnectionListener!!.Connecting() } // this.mContext=context; // reconnect(true); } private var scanToConnect = true private var isScaning = false @SuppressLint("MissingPermission") fun startScan(enable: Boolean) { Log.i(TAG, "startScan: $enable") if (!mBluetoothAdapter!!.isEnabled) { return } if (scanToConnect) { startScanDevice(true) } else { initBluetoothDevice(address, mContext, NeedReconnect, bleConnectionListener) } scanToConnect = !scanToConnect } @SuppressLint("MissingPermission") private fun startScanDevice(enable: Boolean) { if (enable) { if (isScaning) return handler.postDelayed({ mBluetoothAdapter!!.stopLeScan(mLeScanCallback) isScaning = false startScan(true) }, 20000) fastconnect = false mBluetoothAdapter!!.startLeScan(mLeScanCallback) } else { if (isScaning) { mBluetoothAdapter!!.stopLeScan(mLeScanCallback) handler.removeCallbacksAndMessages(null) } } isScaning = enable } private val mLeScanCallback = BluetoothAdapter.LeScanCallback { device, rssi, scanRecord -> if (device.address == address) { val name = decodeDeviceName(device, scanRecord) if (!TextUtils.isEmpty(name) && name == "DfuTarg") return@LeScanCallback if (mGatt != null) return@LeScanCallback handler.post { startScanDevice(false) mGatt = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { device.connectGatt(mContext, false, bleGattCallback, BluetoothDevice.TRANSPORT_LE) } else { device.connectGatt(mContext, false, bleGattCallback) } if (mGatt == null) { println("gatt is null ") } } } } private fun initAdapter() { if (bluetoothManager == null) { bluetoothManager = getSystemService(BLUETOOTH_SERVICE) as BluetoothManager if (bluetoothManager == null) { return } } mBluetoothAdapter = bluetoothManager!!.adapter } /** * 断开连接 */ fun disconnect() { NeedReconnect = false broadcastUpdate(ACTION_GATT_DISCONNECTED) if (mGatt != null) { mGatt = if (isConnected) { mGatt!!.disconnect() mGatt!!.close() null } else { Log.i(TAG, "close: ") mGatt!!.close() null } } isConnected = false } /** * 根据设备的Mac地址断开连接 * * @param address */ fun disconnect(address: String) { val gatts = ArrayList() for (gatt in arrayGatts) { if (gatt != null && gatt.device.address == address) { gatts.add(gatt) // gatt.disconnect(); gatt.close() // gatt = null; } } arrayGatts.removeAll(gatts) } inner class LocalBinder : Binder() { val service: BleService get() = this@BleService } private var discoverCount = 0 private val ob = Any() private val bleGattCallback: BluetoothGattCallback = object : BluetoothGattCallback() { override fun onConnectionStateChange(gatt: BluetoothGatt, status: Int, newState: Int) { var gatt: BluetoothGatt? = gatt if (status == 133 || newState == 0) { if (null != bleConnectionListener) { bleConnectionListener!!.BleStatus(status, newState) } if (mGatt != null) { mGatt!!.disconnect() mGatt!!.close() refreshDeviceCache(mGatt) mGatt = null } if (gatt != null) { gatt.disconnect() gatt.close() refreshDeviceCache(gatt) gatt = null } if (NeedReconnect) startScan(true) return } var action: String? = null Log.i(TAG, "onConnectionStateChange: status$status newstate $newState") if (newState == BluetoothProfile.STATE_CONNECTED) { try { gatt!!.discoverServices() } catch (e: Exception) { e.printStackTrace() } } else if (newState == BluetoothProfile.STATE_DISCONNECTED) { if (null != bleConnectionListener) { bleConnectionListener!!.ConnectionFailed() } isConnected = false Log.i(TAG, "onConnectionStateChange: " + ACTION_GATT_DISCONNECTED) if (mGatt != null) { mGatt!!.close() mGatt = null } queues.clear() if (!NeedReconnect) { action = ACTION_GATT_DISCONNECTED broadcastUpdate(action) } if (!NeedReconnect) { } else { if (fastconnect) { fastconnect = false Log.e(TAG, "发送异常断开") } if (status == 133) { refreshDeviceCache(gatt) } if (null != bleConnectionListener) { bleConnectionListener!!.OnReconnect() } startScan(true) } } else { Log.e("MainActivity", "onConnectionStateChange: status$status newstate $newState") if (0 == status && 0 == newState) { if (null != bleConnectionListener) { bleConnectionListener!!.BluetoothSwitchIsTurnedOff() } } else { if (null != bleConnectionListener) { bleConnectionListener!!.BleStatus(status, newState) } } } } /* * 搜索device中的services (non-Javadoc) * * @see * android.bluetooth.BluetoothGattCallback#onServicesDiscovered(android * .bluetooth.BluetoothGatt, int) */ override fun onServicesDiscovered(gatt: BluetoothGatt, status: Int) { super.onServicesDiscovered(gatt, status) // if (mGatt == null) // return; if (status == BluetoothGatt.GATT_SUCCESS) { val address = gatt.device.address val name = mBluetoothAdapter!!.getRemoteDevice(address) .name setCharacteristicNotification(true) /* if (gatt != null && Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { gatt.requestMtu(512); }else{ setCharacteristicNotification(true); }*/discoverCount = 0 } else { // mGatt = null; Log.w( "servieDiscovered", "onServicesDiscovered received: " + status ) } } override fun onMtuChanged(gatt: BluetoothGatt, mtu: Int, status: Int) { super.onMtuChanged(gatt, mtu, status) if (BluetoothGatt.GATT_SUCCESS == status) { setCharacteristicNotification(true) } else { gatt.requestMtu(153) } } /* * 读取特征�?(non-Javadoc) * * @see * android.bluetooth.BluetoothGattCallback#onCharacteristicRead(android * .bluetooth.BluetoothGatt, * android.bluetooth.BluetoothGattCharacteristic, int) */ override fun onCharacteristicRead(gatt: BluetoothGatt, characteristic: BluetoothGattCharacteristic, status: Int) { super.onCharacteristicRead(gatt, characteristic, status) if (status == BluetoothGatt.GATT_SUCCESS) { broadcastUpdate( ACTION_DATA_AVAILABLE, characteristic, gatt .device.address ) } else { } } override fun onDescriptorWrite( gatt: BluetoothGatt, descriptor: BluetoothGattDescriptor, status: Int ) { super.onDescriptorWrite(gatt, descriptor, status) if (status == BluetoothGatt.GATT_SUCCESS) { nextQueue() isConnected = true broadcastUpdate(ACTION_GATT_onDescriptorWrite) if (null != bleConnectionListener) { bleConnectionListener!!.ConnectionSucceeded() } } else { Log.i(TAG, "onDescriptorWrite: failed") } } /* * 特征值的变化 (non-Javadoc) * * @see * android.bluetooth.BluetoothGattCallback#onCharacteristicChanged(android * .bluetooth.BluetoothGatt, * android.bluetooth.BluetoothGattCharacteristic) */ override fun onCharacteristicChanged( gatt: BluetoothGatt, characteristic: BluetoothGattCharacteristic ) { super.onCharacteristicChanged(gatt, characteristic) if (mGatt == null) return Log.i(TAG, "onCharacteristicChanged: " + byte2Hex(characteristic.value)) // SDUtil.saveBTLog("log", "Receiving: " + ResolveData.byte2Hex(characteristic.getValue())); broadcastUpdate( ACTION_DATA_AVAILABLE, characteristic, gatt .device.address ) // SendData.sendBus(ACTION_DATA_AVAILABLE, characteristic.getValue()); } override fun onCharacteristicWrite( gatt: BluetoothGatt, characteristic: BluetoothGattCharacteristic, status: Int ) { super.onCharacteristicWrite(gatt, characteristic, status) if (status == BluetoothGatt.GATT_SUCCESS) { nextQueue() } else { // MyLog.i("status" + status); } } } fun refreshDeviceCache(gatt: BluetoothGatt?): Boolean { try { val localMethod = gatt!!.javaClass.getMethod( "refresh", *arrayOfNulls(0) ) if (localMethod != null) { return localMethod.invoke( gatt, *arrayOfNulls(0) ) as Boolean } } catch (localException: Exception) { Log.e("s", "An exception occured while refreshing device") } return false } /** * 广播 * * @param action */ private fun broadcastUpdate(action: String?) { val bleData = BleData() bleData.action = action instance.post(bleData) //Intent intent = new Intent(action); //sendBroadcast(intent); } /** * 发�?带蓝牙信息的到广�? * * * @param action * @param characteristic */ private fun broadcastUpdate( action: String, characteristic: BluetoothGattCharacteristic, mac: String ) { // Intent intent = new Intent(action); val data = characteristic.value val bleData = BleData() bleData.action = action bleData.value = data instance.post(bleData) } /** * 读取设备数据 * * @param * @param characteristic */ fun readValue(characteristic: BluetoothGattCharacteristic?) { if (mGatt == null) return mGatt!!.readCharacteristic(characteristic) } /** * 写入设备数据 */ fun writeValue(value: ByteArray?) { Handler(Looper.getMainLooper()).postDelayed(Runnable { if (mGatt == null || value == null) return@Runnable val service = mGatt!!.getService(SERVICE_DATA) ?: return@Runnable val characteristic = service.getCharacteristic(DATA_Characteristic) ?: return@Runnable if (value[0] == 0x47.toByte()) { NeedReconnect = false } characteristic.value = value Log.i(TAG, "writeValue: " + byte2Hex(value)) mGatt!!.writeCharacteristic(characteristic) // SDUtil.saveBTLog("log", "writeValue: " + ResolveData.byte2Hex(value)); }, 500) } fun setCharacteristicNotification(enable: Boolean) { if (mGatt == null) return val service = mGatt!!.getService(SERVICE_DATA) ?: return val characteristic = service.getCharacteristic(NOTIY_Characteristic) ?: return mGatt!!.setCharacteristicNotification(characteristic, enable) try { Thread.sleep(20) } catch (e: InterruptedException) { e.printStackTrace() } val descriptor = characteristic.getDescriptor(NOTIY) ?: //MyLog.e("setCharacteristicNotification descriptor=null,所以不能发送使能数据"); return descriptor.value = BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE if (mGatt == null) return mGatt!!.writeDescriptor(descriptor) } val supportedGattServices: List? /** * 获取services * * @return */ get() = if (mGatt == null) { //MyLog.e("getServices, gatt is null "); null } else mGatt!!.services /** * 根据设备的Mac地址从已经连接的设备中匹配对应的BluetoothGatt对象 * * @param device * @return */ private fun getBluetoothGatt(device: BluetoothDevice): BluetoothGatt? { return mGatt } /** * //读取信号 * * @param device */ fun readRssi(device: BluetoothDevice?) { mGatt!!.readRemoteRssi() } override fun onDestroy() { super.onDestroy() } var queues: Queue = LinkedList() fun offerValue(value: ByteArray) { queues.offer(value) } fun nextQueue() { val requests = queues val data = if (requests != null) requests.poll() else null writeValue(data) } companion object { private const val TAG = "BleService" private val NOTIY = UUID.fromString("00002902-0000-1000-8000-00805f9b34fb") private val SERVICE_DATA = UUID.fromString("0000fff0-0000-1000-8000-00805f9b34fb") private val DATA_Characteristic = UUID.fromString("0000fff6-0000-1000-8000-00805f9b34fb") private val NOTIY_Characteristic = UUID.fromString("0000fff7-0000-1000-8000-00805f9b34fb") const val ACTION_GATT_onDescriptorWrite = "com.jstylelife.ble.service.onDescriptorWrite" const val ACTION_GATT_CONNECTED = "com.jstylelife.ble.service.ACTION_GATT_CONNECTED" const val ACTION_GATT_DISCONNECTED = "com.jstylelife.ble.service.ACTION_GATT_DISCONNECTED" const val ACTION_DATA_AVAILABLE = "com.jstylelife.ble.service.ACTION_DATA_AVAILABLE" private val arrayGatts = ArrayList() // 存放BluetoothGatt的集�? var colorCharacteristic: BluetoothGattCharacteristic? = null } } \ No newline at end of file diff --git a/android/app/src/main/kotlin/com/cloud/diplomaticquarterapp/smart_ring_2301/Util/BleData.kt b/android/app/src/main/kotlin/com/cloud/diplomaticquarterapp/smart_ring_2301/Util/BleData.kt new file mode 100644 index 00000000..0d52c3db --- /dev/null +++ b/android/app/src/main/kotlin/com/cloud/diplomaticquarterapp/smart_ring_2301/Util/BleData.kt @@ -0,0 +1,11 @@ +package com.cloud.diplomaticquarterapp.smart_ring_2301.Util + +/** + * Created by Administrator on 2017/4/11. + */ +class BleData { + + var value: ByteArray? = null + var action: String? = null + var data: String? = null +} \ No newline at end of file diff --git a/android/app/src/main/kotlin/com/cloud/diplomaticquarterapp/smart_ring_2301/Util/CustomCountDownTimer.kt b/android/app/src/main/kotlin/com/cloud/diplomaticquarterapp/smart_ring_2301/Util/CustomCountDownTimer.kt new file mode 100644 index 00000000..88574367 --- /dev/null +++ b/android/app/src/main/kotlin/com/cloud/diplomaticquarterapp/smart_ring_2301/Util/CustomCountDownTimer.kt @@ -0,0 +1,137 @@ +package com.cloud.diplomaticquarterapp.smart_ring_2301.Util + +import android.os.Handler +import android.os.Looper +import java.util.concurrent.Executors +import java.util.concurrent.ScheduledExecutorService +import java.util.concurrent.TimeUnit + +/** + * 计时器 + */ +class CustomCountDownTimer( +//Millis since epoch when alarm should stop. + private var millisInFuture: Long, countDownInterval: Long, + tickListener: TimerTickListener +) { + //thread on which the callbacks will be called + private val mainThreadHandler = Handler(Looper.getMainLooper()) + + //listener interface which is to be implemented by the users of the count down timer + interface TimerTickListener { + /** + * Callback on each tick + * + * @param millisLeft time left in millisec for the timer to shutdown + */ + fun onTick(millisLeft: Long) + + /** + * Callback to be invokded when timer's time finishes + */ + fun onFinish() + + /** + * Callback to be invokded when timer is canceled + */ + fun onCancel() + } + + /** + * Inner class which delegates the events to callbacks provided in the TimerTickListener + */ + private inner class TimerRunnable : Runnable { + override fun run() { + if (isCancelled) { + scheduler.shutdown() + mainThreadHandler.post { tickListener.onCancel() } + } else if (isPaused) { + } else { + stopTimeInFuture = stopTimeInFuture - countdownInterval + mainThreadHandler.post(object : Runnable { + val millisLeft = stopTimeInFuture + override fun run() { + if (millisLeft <= 0) { + tickListener.onFinish() + scheduler.shutdown() + } else { + tickListener.onTick(millisLeft) + } + } + }) + } + } + } + + //The interval in millis that the user receives callbacks + private val countdownInterval: Long + + //the time at which timer is to stop + private var stopTimeInFuture: Long + + //boolean representing if the timer was cancelled + var isCancelled = false + + //boolean representing if the timer was paused + private var isPaused = false + + //listener which listens to the timer events + private val tickListener: TimerTickListener + + //scheduler which provides the thread to create timer + private val scheduler: ScheduledExecutorService + + /** + * Constructor + * + * @param millisInFuture time in millisec for which timer is to run + * @param countDownInterval interval frequency in millisec at which the callback will be invoked + * @param tickListener implementation of TimerTickListener which provides callbacks code + */ + init { + stopTimeInFuture = millisInFuture + countdownInterval = countDownInterval + this.tickListener = tickListener + scheduler = Executors.newSingleThreadScheduledExecutor() + } + + /** + * Start the countdown. + */ + @Synchronized + fun start() { + isCancelled = false + isPaused = false + scheduler.scheduleWithFixedDelay( + TimerRunnable(), countdownInterval, countdownInterval, + TimeUnit.MILLISECONDS + ) + } + + /** + * Cancels the countdown timer + */ + @Synchronized + fun cancel() { + isCancelled = true + } + + @Synchronized + fun pause() { + isPaused = true + } + + @Synchronized + fun resume() { + isPaused = false + } + + fun extendTime(delta: Long) { + stopTimeInFuture = stopTimeInFuture + delta + millisInFuture = millisInFuture + delta + } + + companion object { + const val TAG = "CustomCountDownTimer" + } +} \ No newline at end of file diff --git a/android/app/src/main/kotlin/com/cloud/diplomaticquarterapp/smart_ring_2301/Util/DateUtil.kt b/android/app/src/main/kotlin/com/cloud/diplomaticquarterapp/smart_ring_2301/Util/DateUtil.kt new file mode 100644 index 00000000..866e1747 --- /dev/null +++ b/android/app/src/main/kotlin/com/cloud/diplomaticquarterapp/smart_ring_2301/Util/DateUtil.kt @@ -0,0 +1,504 @@ +package com.cloud.diplomaticquarterapp.smart_ring_2301.Util + +import android.content.Context +import java.text.NumberFormat +import java.text.ParseException +import java.text.SimpleDateFormat +import java.util.Calendar +import java.util.Date + +/** + * Created by Administrator on 2017/3/24. + */ +object DateUtil { + const val oneDayMillis = 24 * 60 * 60 * 1000L + private const val oneMinMillis = 60 * 1000L + const val Default_FormatString = "yy.MM.dd" + const val SHOW_FormatString = "MM-dd,yyyy" + val format = SimpleDateFormat("yy.MM.dd HH:mm:ss") + var defaultFormat = SimpleDateFormat(Default_FormatString) + const val DATA_MONTH_FormatString = "yy.MM" + const val DATA_Year_FormatString = "yyyy.M" //数据年日期 + const val last_month = -1 + const val this_month = 0 + const val next_month = 1 + const val nextWeek = 326 + const val lastWeek = 396 + + /** + * 明天的日期 + */ + fun getTomorrowDateString(today: String?): String { + val c = Calendar.getInstance() + c.timeInMillis = getDateLong(today) + oneDayMillis + return getDefaultFormatTime(c.time) + } + + fun getDateString(today: String?, days: Int): String { + val c = Calendar.getInstance() + c.timeInMillis = getDateLong(today) - oneDayMillis * days + return getDefaultFormatTime(c.time) + } + + /** + * 昨天的日期 + */ + @Synchronized + fun getYesterdayDateString(today: String?): String { + val c = Calendar.getInstance() + c.timeInMillis = getDateLong(today) - oneDayMillis + return getDefaultFormatTime(c.time) + } + + /** + * 获取指定格式的日期字符串 + * + * @param time + * @param formatString + * @return + */ + @Synchronized + fun getFormatTimeString(time: Long, formatString: String?): String { + val format = SimpleDateFormat(formatString) + return format.format(Date(time)) + } + + @Synchronized + fun getFormatTimeString(time: Long): String { + return format.format(Date(time)) + } + + @Synchronized + fun getEcgFormatTimeString(time: Long): String { + val simpleDateFormat = SimpleDateFormat("yyyy.MM.dd HH:mm:ss") + return simpleDateFormat.format(Date(time)) + } + + @Synchronized + fun getEcgFormatTodayString(time: Long): String { + val simpleDateFormat = SimpleDateFormat("yyyy.MM.dd") + return simpleDateFormat.format(Date(time)) + } + + /** + * 获取默认格式日期字符串 + * + * @return + */ + @Synchronized + fun getDefaultFormatTime(date: Date): String { + return getFormatTimeString(date.time, Default_FormatString) + } + + /**字符串代表日期的毫秒数 + * @param date + * @return + */ + @Synchronized + fun getDateLong(date: String?): Long { + var time: Long = 0 + try { + val dates = defaultFormat.parse(date) + time = dates.time + } catch (e: Exception) { + // TODO: handle exception + } + return time + } + + @Synchronized + fun getGpsDateLong(date: String?): Long { + var time: Long = 0 + try { + val dates = format.parse(date) + time = dates.time + } catch (e: Exception) { + // TODO: handle exception + } + return time + } + + /**字符串转date + * @param dateString + * @return + */ + fun String2Date(dateString: String?, formatString: String?): Date? { + val format = SimpleDateFormat(formatString) + var date: Date? = null + try { + date = format.parse(dateString) + } catch (e: ParseException) { + e.printStackTrace() + } + return date + } + + fun getMonthString(thisMonth: String?, monthType: Int): String { + val calendar = Calendar.getInstance() + if (monthType != this_month) calendar.time = String2Date(thisMonth, DATA_MONTH_FormatString) + calendar.add(Calendar.MONTH, monthType) + return getFormatTimeString(calendar.timeInMillis, DATA_MONTH_FormatString) + } + + fun getTodayWeek(time: Long): Array { + val format = SimpleDateFormat(Default_FormatString) + val week = arrayOfNulls(7) + val calendar = Calendar.getInstance() + if (time != 0L) { + calendar.timeInMillis = time + } + setToFirstDay(calendar) + for (i in 0..6) { + week[i] = format.format(calendar.time) + calendar.add(Calendar.DATE, 1) + } + return week + } + + private fun setToFirstDay(calendar: Calendar) { + while (calendar[Calendar.DAY_OF_WEEK] != Calendar.MONDAY) { + calendar.add(Calendar.DATE, -1) + } + } + + fun getWeekString(time: String?, type: Int): Array { + val format = SimpleDateFormat(Default_FormatString) + var date: Date? = null + try { + date = format.parse(time) + } catch (e: Exception) { + // TODO: handle exception + } + val nowL = if (type == lastWeek) date!!.time - oneDayMillis else date!!.time + oneDayMillis + return getTodayWeek(nowL) + } + + /**时间段在一天中的时间节点(一分钟一点) + * @param time + * @param defaultTime + * @return + */ + fun get1MIndex(time: String?, defaultTime: String?): Int { + val format = SimpleDateFormat("yy.MM.dd HH:mm:ss") + var count = 0 + try { + val date = format.parse(time) + val dateBase = format.parse(defaultTime) + val min = date.time - dateBase.time + count = (min / oneMinMillis).toInt() + } catch (e: Exception) { + // TODO: handle exception + } + return count + } + + fun get1SIndex(time: String?, defaultTime: String?): Int { + val format = SimpleDateFormat("yy.MM.dd HH:mm:ss") + var count = 0 + try { + val date = format.parse(time) + val dateBase = format.parse(defaultTime) + val min = date.time - dateBase.time + count = (min / 1000L).toInt() + } catch (e: Exception) { + // TODO: handle exception + } + return count + } + + fun get5MIndex(time: String?, defaultTime: String?): Int { + val format = SimpleDateFormat("yy.MM.dd HH:mm:ss") + var count = 0 + try { + val date = format.parse(time) + val dateBase = format.parse(defaultTime) + val min = date.time - dateBase.time + count = (min / (oneMinMillis * 5)).toInt() + } catch (e: Exception) { + // TODO: handle exception + } + return count + } + + fun getMIndex(time: String?, defaultTime: String?, countMIN: Int): Int { + val format = SimpleDateFormat("yy.MM.dd HH:mm:ss") + var count = 0 + try { + val date = format.parse(time) + val dateBase = format.parse(defaultTime) + val min = date.time - dateBase.time + count = (min / (oneMinMillis * countMIN)).toInt() + } catch (e: Exception) { + // TODO: handle exception + } + return count + } + + @Synchronized + fun getHistoryTime(time: Long): String { + val defaultTime = getDateLong("00.01.01") + return getFormatTimeString(time * 1000 * 5 + defaultTime) + } + + private const val TAG = "DateUtil" + @Synchronized + fun getDefaultLongMi(defaultTime: String?): Long { + var date = Date() + // SimpleDateFormat format = new SimpleDateFormat("yy.MM.dd HH:mm:ss"); + // Log.i(TAG, "getDefaultLongMi: "+defaultTime); + try { + date = format.parse(defaultTime) + } catch (e: Exception) { + // Log.i(TAG, "getDefaultLongMi: "+e.getMessage()); + } + return date.time + } + + fun getSleepTime(minute: Int): String { + val hour = minute / 60 + val min = minute % 60 + return String.format("%1$02dh%2$02dmin", hour, min) + } + + fun getActivityShowTime(minute: Int): String { + val hour = minute / 60 + val min = minute % 60 + return String.format("%1$02d:%2$02d", hour, min) + } + + fun getSportTime(seconds: Int): String { + var hour = 0 + var min = seconds / 60 + var second = seconds % 60 + if (min >= 60) { + hour = min / 60 + min = min % 60 + second = seconds - hour * 3600 - min * 60 + } + return String.format("%1$02d:%2$02d:%3$02d", hour, min, second) + } + + fun getExerciseListTotalTime(seconds: Int): String { + var hour = 0 + var min = seconds / 60 + // int second=seconds%60; + if (min >= 60) { + hour = min / 60 + min = min % 60 + //second = seconds - hour * 3600 - min * 60; + } + return String.format("%1$02dh%2$02dmin", hour, min) + } + + fun getSportAxieTime(seconds: Int): String { + var hour = 0 + var min = seconds / 60 + var second = seconds % 60 + if (min >= 60) { + hour = min / 60 + min = min % 60 + second = seconds - hour * 3600 - min * 60 + } + return if (hour == 0) String.format("%1$02d:%2$02d", min, second) else String.format("%1$02d:%2$02d:%3$02d", hour, min, second) + } + + fun getPaceTime(seconds: Int): String { + val min = seconds / 60 + val second = seconds % 60 + // if(min>60){ +// hour=min/60; +// min=min%60; +// second = seconds - hour * 3600 - min * 60; +// } + return String.format("%1$02d'%2$02d\"", min, second) + } + + fun getActivityTime(seconds: Int): String { + var hour = 0 + var min = seconds / 60 + var second = seconds % 60 + if (min > 60) { + hour = min / 60 + min = min % 60 + second = seconds - hour * 3600 - min * 60 + } + return if (hour == 0) String.format("%1$02d:%2$02d", min, second) else String.format("%1$02d:%2$02d:%3$02d", hour, min, second) + } + + fun getPointSleepTime(minute: Float): String { + val nf = NumberFormat.getInstance() + nf.minimumFractionDigits = 2 + return nf.format((minute / 60f).toDouble()) + "h" + } + + fun getSleepTimeFloat(minute: Int): Float { + val hour = minute / 60 + val min = minute % 60 + return hour + min / 60f + } + + /**时间点换成时间段 + * @param count + * @return + */ + fun getCountTime(count: Int, defaultTime: String?): String { + val format = SimpleDateFormat("yy.MM.dd HH:mm:ss") + // String base = "00:00:00"; + var time: Long = 0 + try { + time = format.parse(defaultTime).time + count * oneMinMillis + } catch (e: Exception) { + // TODO: handle exception + } + return format.format(Date(time)) + } + + fun getSleepCountTime(count: Int, defaultTime: String?): String { + val format = SimpleDateFormat("yy.MM.dd HH:mm:ss") + // String base = "00:00:00"; + var time: Long = 0 + try { + time = format.parse(defaultTime).time + 5 * count * oneMinMillis + } catch (e: Exception) { + // TODO: handle exception + } + return format.format(Date(time)) + } + + val thisMonth: Array + get() { + val format = SimpleDateFormat("yy.MM.dd") + // String[] month = new String[3]; + val cal_1 = Calendar.getInstance() // 获取当前日期 + val max = cal_1.getActualMaximum(Calendar.DAY_OF_MONTH) + val month = arrayOfNulls(max) + for (i in 1 until max + 1) { + cal_1[Calendar.DAY_OF_MONTH] = i + month[i - 1] = format.format(cal_1.time) + } + return month + } + + fun getNextMonth(date: String?): Array { + val format = SimpleDateFormat("yy.MM.dd") + var dates: Date? = Date() + try { + dates = format.parse(date) + } catch (e: Exception) { + // TODO: handle exception + } + val cal_1 = Calendar.getInstance() // 获取当前日期 + cal_1.time = dates + var months = cal_1[Calendar.MONTH] + var year = cal_1[Calendar.YEAR] + if (months == Calendar.DECEMBER) { + year++ + months = Calendar.JANUARY + } else { + months++ + } + cal_1[Calendar.YEAR] = year + cal_1[Calendar.MONTH] = months + val max = cal_1.getActualMaximum(Calendar.DAY_OF_MONTH) + val month = arrayOfNulls(max) + for (i in 1 until max + 1) { + cal_1[Calendar.DAY_OF_MONTH] = i + month[i - 1] = format.format(cal_1.time) + } + +// cal_1.set(Calendar.DAY_OF_MONTH, +// cal_1.getActualMaximum(Calendar.DAY_OF_MONTH));// 设置为1号,当前日期既为本月第一天 +// month[1] = format.format(cal_1.getTime()); +// month[2]=cal_1.getActualMaximum(Calendar.DAY_OF_MONTH)+""; + return month + } + + fun getMonth(year: Int, month: Int): Array { + val format = SimpleDateFormat("yy.MM.dd") + val cal_1 = Calendar.getInstance() // 获取当前日期 + cal_1[Calendar.YEAR] = year + cal_1[Calendar.MONTH] = month + val max = cal_1.getActualMaximum(Calendar.DAY_OF_MONTH) + val months = arrayOfNulls(max) + for (i in 1 until max + 1) { + cal_1[Calendar.DAY_OF_MONTH] = i + months[i - 1] = format.format(cal_1.time) + } + return months + } + + fun getLastMonth(date: String?): Array { + val format = SimpleDateFormat("yy.MM.dd") + var dates: Date? = Date() + try { + dates = format.parse(date) + } catch (e: Exception) { + // TODO: handle exception + } + val cal_1 = Calendar.getInstance() // 获取当前日期 + cal_1.time = dates + var months = cal_1[Calendar.MONTH] + var year = cal_1[Calendar.YEAR] + if (months == Calendar.JANUARY) { + year-- + months = Calendar.DECEMBER + } else { + months-- + } + cal_1[Calendar.YEAR] = year + cal_1[Calendar.MONTH] = months + val max = cal_1.getActualMaximum(Calendar.DAY_OF_MONTH) + val month = arrayOfNulls(max) + for (i in 1 until max + 1) { + cal_1[Calendar.DAY_OF_MONTH] = i + month[i - 1] = format.format(cal_1.time) + } + // 设置为1号,当前日期既为本月第一天 + + +// cal_1.set(Calendar.DAY_OF_MONTH, +// cal_1.getActualMaximum(Calendar.DAY_OF_MONTH));// 设置为1号,当前日期既为本月第一天 +// month[1] = format.format(cal_1.getTime()); + return month + } + + fun beforeData(lastTime: String?, bleTime: String?): Boolean { + var isBefore = false + try { + val lastDate = format.parse(lastTime) + val bleDate = format.parse(bleTime) + isBefore = lastDate.before(bleDate) + } catch (e: ParseException) { + e.printStackTrace() + } + return isBefore + } + + fun getCountTime(count: Int): String { + val format = SimpleDateFormat("HH:mm") + val base = "12:00" + var time: Long = 0 + try { + time = format.parse(base).time + count * 5 * 60 * 1000L + } catch (e: Exception) { + // TODO: handle exception + } + return format.format(Date(time)) + } + + fun getShowDate(context: Context, monthString: String?): String { + val locale = context.resources.configuration.locale + val language = locale.language + val time = getDateLong(monthString) + var format = "" + // if (language.equals("zh")) { + format = "yyyy-MM" + // } else { +// format = "MM-yyyy"; +// } + return getFormatTimeString(time, format) + } + + private val timestamp: String + private get() = (System.currentTimeMillis() / 1000).toString() + "" +} \ No newline at end of file diff --git a/android/app/src/main/kotlin/com/cloud/diplomaticquarterapp/smart_ring_2301/Util/EcgGraphicView.kt b/android/app/src/main/kotlin/com/cloud/diplomaticquarterapp/smart_ring_2301/Util/EcgGraphicView.kt new file mode 100644 index 00000000..8844f931 --- /dev/null +++ b/android/app/src/main/kotlin/com/cloud/diplomaticquarterapp/smart_ring_2301/Util/EcgGraphicView.kt @@ -0,0 +1,203 @@ +package com.cloud.diplomaticquarterapp.smart_ring_2301.Util + +import android.app.Activity +import android.content.Context +import android.graphics.Canvas +import android.graphics.Color +import android.graphics.Paint +import android.graphics.Path +import android.graphics.PorterDuff +import android.util.AttributeSet +import android.util.DisplayMetrics +import android.util.Log +import android.view.SurfaceHolder +import android.view.SurfaceView + +/** + * 自定义心电图 + * + * @author manhongjie + */ +// public class EcgGraphicView extends View { +class EcgGraphicView(context: Context, attrs: AttributeSet?) : SurfaceView(context, attrs), SurfaceHolder.Callback, Runnable { + private val mSurfaceHolder: SurfaceHolder + private val mPaint: Paint + private val blackPaint: Paint? = null + private val wangge_Paint: Paint? = null + private val pixPaint: Paint? = null + private var mPath = Path() + + // 屏幕的长�? + private var SCREEN_WIDTH = 480f + + // + private val POINT_LEN = 3000 + private val rulerStartX = 0 + + // public float[] x = new float[POINT_LEN]; + // public float[] y = new float[POINT_LEN]; + // 数组中有3000个点 + var x = FloatArray(POINT_LEN) + var y = FloatArray(POINT_LEN) + var scale = 0f + var x0 = 240f + var y0 = 192f + private val context: Context + var distanceY = 0f + private var isDrawing = false + private var mCanvas: Canvas? = null + + // @Override + // public void onDraw(Canvas canvas) { + // + // float width = SCREEN_WIDTH; + // scale = 1; + // + // // String ruleStr = new String(scale * 10 + "mm/100mv"); + // // 移动后的坐标 + // makeFollowPathOne(); + // + // // rulerStartX = SCREEN_WIDTH - 60; + // // 每列的间隔是32 + // // int colomn = (int) (width / 32); + // + // // 画网格线行和�? + // + // // for (int i = 0; i <= 13; i++) { + // // canvas.drawLine(0, i * 32, width, i * 32, wangge_Paint); + // // } + // // for (int i = 0; i <= colomn; i++) { + // // canvas.drawLine(i * 32, 0, i * 32, 12 * 32, wangge_Paint); + // // } + // + // // 画标�? + // + // // canvas.drawLine(rulerStartX + 0, 192, rulerStartX + 8, 192, + // // pixPaint); + // // canvas.drawLine(rulerStartX + 24, 192, rulerStartX + 32, 192, + // // pixPaint); + // // canvas.drawLine(rulerStartX + 8, 128, rulerStartX + 24, 128, + // // pixPaint); + // // canvas.drawLine(rulerStartX + 8, 128, rulerStartX + 8, 192, + // // pixPaint); + // // canvas.drawLine(rulerStartX + 24, 128, rulerStartX + 24, 192, + // // pixPaint); + // + // // 文本�?25mm/s 10.0mm/100mv + // // canvas.drawText(ruleStr, rulerStartX - 120, 40, pixPaint); + // // canvas.drawText("25mm/s", rulerStartX - 200, 40, pixPaint); + // + // canvas.drawPath(mPath, mPaint); + // } + override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) { + // TODO Auto-generated method stub + if (MeasureSpec.getMode(widthMeasureSpec) == MeasureSpec.EXACTLY) { + SCREEN_WIDTH = MeasureSpec.getSize(widthMeasureSpec).toFloat() + } + super.onMeasure(widthMeasureSpec, heightMeasureSpec) + } + + // + fun makeFollowPathOne(canvas: Canvas) { + val height = height.toFloat() + val size = ecgValues.size + if (size == 0) return + mPath.reset() + val width = SCREEN_WIDTH / maxSize + val heightI = height / 16000 + mPath.moveTo(0f, (8000 - ecgValues[0]) * heightI) + for (i in 1 until size - 1) { + canvas.drawPoint(i * width, (8000 - ecgValues[i]) * heightI, mPaint) + // mPath.lineTo(i * width, (8000 - ecgValues.get(i)) * heightI); + } + } + + var ecgValues: MutableList = ArrayList() + var maxSize = 1516f + fun setValue(value: Int) { + if (ecgValues.size > maxSize) ecgValues.removeAt(0) + ecgValues.add(value) + } + + fun clearData() { + ecgValues.clear() + } + + fun setYDistance(distance: Float) { + distanceY = distance + } + + override fun surfaceCreated(holder: SurfaceHolder) { + isDrawing = true + Thread(this).start() + } + + override fun surfaceChanged(holder: SurfaceHolder, format: Int, width: Int, height: Int) {} + override fun surfaceDestroyed(holder: SurfaceHolder) { + isDrawing = false + } + + override fun run() { + while (isDrawing) { + drawing() + } + } + + init { + // TODO Auto-generated constructor stub + // 分辨率矩�? + val dm = DisplayMetrics() + // 取得窗口属�?? + if (context is Activity) { + context.windowManager.defaultDisplay.getMetrics(dm) + SCREEN_WIDTH = dm.widthPixels.toFloat() + Log.d("EcgGraphicView", "width: $SCREEN_WIDTH") + } + mPath = Path() + + // 画心电图的画�? + mPaint = Paint(Paint.ANTI_ALIAS_FLAG) + mPaint.style = Paint.Style.STROKE + mPaint.strokeWidth = ScreenUtils.Companion.dip2px(context, 1f).toFloat() + mPaint.textSize = 2f + mPaint.color = Color.WHITE + this.context = context + // blackPaint = new Paint(Paint.ANTI_ALIAS_FLAG); + // blackPaint.setStyle(Paint.Style.STROKE); + // blackPaint.setStrokeWidth(2); + // blackPaint.setTextSize(2); + // blackPaint.setColor(Color.RED); + // 网格线画�? + // wangge_Paint = new Paint(Paint.ANTI_ALIAS_FLAG); + // wangge_Paint.setStyle(Paint.Style.STROKE); + // wangge_Paint.setStrokeWidth(1.0f); + // wangge_Paint.setTextSize(0.5f); + // wangge_Paint.setColor(Color.parseColor("#000000")); + + // pixPaint = new Paint(Paint.ANTI_ALIAS_FLAG); + // pixPaint.setStyle(Paint.Style.FILL); + // pixPaint.setStrokeWidth(2.0f); + // pixPaint.setTextSize(20.0f); + // pixPaint.setColor(Color.RED); + mSurfaceHolder = holder + mSurfaceHolder.addCallback(this) + } + + private fun drawing() { + try { + mCanvas = mSurfaceHolder.lockCanvas() + if (mCanvas == null) return + mCanvas!!.drawColor(Color.TRANSPARENT, PorterDuff.Mode.CLEAR) + makeFollowPathOne(mCanvas!!) + // mCanvas.drawPath(mPath, mPaint); + } finally { + if (mCanvas != null) { + mSurfaceHolder.unlockCanvasAndPost(mCanvas) + } + } + } + + companion object { + private const val TAG = "EcgGraphicView" + } +} \ No newline at end of file diff --git a/android/app/src/main/kotlin/com/cloud/diplomaticquarterapp/smart_ring_2301/Util/ResolveData.kt b/android/app/src/main/kotlin/com/cloud/diplomaticquarterapp/smart_ring_2301/Util/ResolveData.kt new file mode 100644 index 00000000..cb1f42e2 --- /dev/null +++ b/android/app/src/main/kotlin/com/cloud/diplomaticquarterapp/smart_ring_2301/Util/ResolveData.kt @@ -0,0 +1,248 @@ +package com.cloud.diplomaticquarterapp.smart_ring_2301.Util + +import android.annotation.SuppressLint +import android.bluetooth.BluetoothDevice +import android.content.ContentResolver +import android.content.ContentUris +import android.content.Context +import android.database.Cursor +import android.net.Uri +import android.os.Build +import android.os.Environment +import android.provider.DocumentsContract +import android.provider.MediaStore +import android.text.TextUtils +import android.util.Log +import java.io.UnsupportedEncodingException + +/** + * Created by Administrator on 2017/4/6. + */ +object ResolveData { + private const val TAG = "ResolveData" + private const val SHORTENED_LOCAL_NAME = 0x08 + private const val COMPLETE_LOCAL_NAME = 0x09 + private const val oneMinMillis = 60 * 1000L + var startString = " 12:00:00" + fun getBcd(value: String): Int { + return value.toInt(16) + } + + fun decodeDeviceName(data: ByteArray): String? { + var name: String? = null + var fieldLength: Int + var fieldName: Int + val packetLength = data.size + var index = 0 + while (index < packetLength) { + fieldLength = data[index].toInt() + if (fieldLength <= 0) break + fieldName = data[++index].toInt() + if (fieldName == COMPLETE_LOCAL_NAME + || fieldName == SHORTENED_LOCAL_NAME + ) { + name = decodeLocalName(data, index + 1, fieldLength - 1) + break + } + index += fieldLength - 1 + index++ + } + return name + } + + @SuppressLint("MissingPermission") + @JvmStatic + fun decodeDeviceName(bluetoothDevice: BluetoothDevice, data: ByteArray): String? { + var name = bluetoothDevice.name + if (!TextUtils.isEmpty(name)) return name + var fieldLength: Int + var fieldName: Int + val packetLength = data.size + var index = 0 + while (index < packetLength) { + fieldLength = data[index].toInt() + if (fieldLength <= 0) break + fieldName = data[++index].toInt() + if (fieldName == COMPLETE_LOCAL_NAME + || fieldName == SHORTENED_LOCAL_NAME + ) { + name = decodeLocalName(data, index + 1, fieldLength - 1) + break + } + index += fieldLength - 1 + index++ + } + return name + } + + /** + * Decodes the local name + */ + fun decodeLocalName( + data: ByteArray?, start: Int, + length: Int + ): String? { + return try { + kotlin.String() + } catch (e: UnsupportedEncodingException) { + Log.e( + "scan", "Unable to convert the complete local name to UTF-8", + e + ) + null + } catch (e: IndexOutOfBoundsException) { + Log.e("scan", "Error when reading complete local name", e) + null + } + } + + /** + * 转十六进制字符串 + * + * @param data + * @return + */ + @JvmStatic + fun byte2Hex(data: ByteArray?): String { + if (data != null && data.size > 0) { + val sb = StringBuilder(data.size) + for (tmp in data) { + sb.append(String.format("%02X ", tmp)) + } + return sb.toString() + } + return "no data" + } + + fun getRealFilePath(context: Context, uri: Uri?): String? { + if (null == uri) return null + val scheme = uri.scheme + var data: String? = null + if (scheme == null) data = uri.path else if (ContentResolver.SCHEME_FILE == scheme) { + data = uri.path + } else if (ContentResolver.SCHEME_CONTENT == scheme) { + val cursor = context.contentResolver.query(uri, arrayOf(MediaStore.Images.ImageColumns.DATA), null, null, null) + if (null != cursor) { + if (cursor.moveToFirst()) { + val index = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA) + if (index > -1) { + data = cursor.getString(index) + } + } + cursor.close() + } + } + return data + } + + /** + * 专为Android4.4设计的从Uri获取文件绝对路径 + */ + fun getPath(context: Context, uri: Uri): String? { + + + // DocumentProvider + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT && DocumentsContract.isDocumentUri(context, uri)) { + // ExternalStorageProvider + if (isExternalStorageDocument(uri)) { + val docId = DocumentsContract.getDocumentId(uri) + val split = docId.split(":".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray() + val type = split[0] + if ("primary".equals(type, ignoreCase = true)) { + return Environment.getExternalStorageDirectory().toString() + "/" + split[1] + } + + // TODO handle non-primary volumes + } else if (isDownloadsDocument(uri)) { + val id = DocumentsContract.getDocumentId(uri) + val contentUri = ContentUris.withAppendedId( + Uri.parse("content://downloads/public_downloads"), java.lang.Long.valueOf(id) + ) + return getDataColumn(context, contentUri, null, null) + } else if (isMediaDocument(uri)) { + val docId = DocumentsContract.getDocumentId(uri) + val split = docId.split(":".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray() + val type = split[0] + var contentUri: Uri? = null + if ("image" == type) { + contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI + } else if ("video" == type) { + contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI + } else if ("audio" == type) { + contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI + } + val selection = "_id=?" + val selectionArgs = arrayOf(split[1]) + return getDataColumn(context, contentUri, selection, selectionArgs) + } + } else if ("content".equals(uri.scheme, ignoreCase = true)) { + return getDataColumn(context, uri, null, null) + } else if ("file".equals(uri.scheme, ignoreCase = true)) { + return uri.path + } + return null + } + + /** + * Get the value of the data column for this Uri. This is useful for + * MediaStore Uris, and other file-based ContentProviders. + * + * @param context + * The context. + * @param uri + * The Uri to query. + * @param selection + * (Optional) Filter used in the query. + * @param selectionArgs + * (Optional) Selection arguments used in the query. + * @return The value of the _data column, which is typically a file path. + */ + fun getDataColumn( + context: Context, uri: Uri?, selection: String?, + selectionArgs: Array? + ): String? { + var cursor: Cursor? = null + val column = "_data" + val projection = arrayOf(column) + try { + cursor = context.contentResolver.query( + uri!!, projection, selection, selectionArgs, + null + ) + if (cursor != null && cursor.moveToFirst()) { + val column_index = cursor.getColumnIndexOrThrow(column) + return cursor.getString(column_index) + } + } finally { + cursor?.close() + } + return null + } + + /** + * @param uri + * The Uri to check. + * @return Whether the Uri authority is ExternalStorageProvider. + */ + fun isExternalStorageDocument(uri: Uri): Boolean { + return "com.android.externalstorage.documents" == uri.authority + } + + /** + * @param uri + * The Uri to check. + * @return Whether the Uri authority is DownloadsProvider. + */ + fun isDownloadsDocument(uri: Uri): Boolean { + return "com.android.providers.downloads.documents" == uri.authority + } + + /** + * @param uri + * The Uri to check. + * @return Whether the Uri authority is MediaProvider. + */ + fun isMediaDocument(uri: Uri): Boolean { + return "com.android.providers.media.documents" == uri.authority + } +} \ No newline at end of file diff --git a/android/app/src/main/kotlin/com/cloud/diplomaticquarterapp/smart_ring_2301/Util/RxBus.kt b/android/app/src/main/kotlin/com/cloud/diplomaticquarterapp/smart_ring_2301/Util/RxBus.kt new file mode 100644 index 00000000..c9f4cb11 --- /dev/null +++ b/android/app/src/main/kotlin/com/cloud/diplomaticquarterapp/smart_ring_2301/Util/RxBus.kt @@ -0,0 +1,34 @@ +package com.cloud.diplomaticquarterapp.smart_ring_2301.Util + +import io.reactivex.rxjava3.core.Observable +import io.reactivex.rxjava3.processors.FlowableProcessor +import io.reactivex.rxjava3.processors.PublishProcessor +import io.reactivex.rxjava3.subjects.PublishSubject +import io.reactivex.rxjava3.subjects.Subject + + +/** + * Created by zhuge on 2017/1/19 0019. + */ +class RxBus private constructor() { + private val bus: Subject + private val mBus: FlowableProcessor + + init { + mBus = PublishProcessor.create().toSerialized() + bus = PublishSubject.create().toSerialized() + } + + fun post(`object`: Any) { + bus.onNext(`object`) + } + + fun toObservable(eventType: Class): Observable { + return bus.ofType(eventType) + } + + + companion object { + val instance = RxBus() + } +} \ No newline at end of file diff --git a/android/app/src/main/kotlin/com/cloud/diplomaticquarterapp/smart_ring_2301/Util/SchedulersTransformer.kt b/android/app/src/main/kotlin/com/cloud/diplomaticquarterapp/smart_ring_2301/Util/SchedulersTransformer.kt new file mode 100644 index 00000000..c78844af --- /dev/null +++ b/android/app/src/main/kotlin/com/cloud/diplomaticquarterapp/smart_ring_2301/Util/SchedulersTransformer.kt @@ -0,0 +1,17 @@ +package com.cloud.diplomaticquarterapp.smart_ring_2301.Util + +import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers +import io.reactivex.rxjava3.core.ObservableTransformer +import io.reactivex.rxjava3.schedulers.Schedulers + + +/** + * Created by Administrator on 2017/4/26. + */ +object SchedulersTransformer { + private const val TAG = "SchedulersTransformer" + fun io2MainObservable(): ObservableTransformer { + return ObservableTransformer { upstream -> upstream.subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()) } + } + +} \ No newline at end of file diff --git a/android/app/src/main/kotlin/com/cloud/diplomaticquarterapp/smart_ring_2301/Util/ScreenUtils.kt b/android/app/src/main/kotlin/com/cloud/diplomaticquarterapp/smart_ring_2301/Util/ScreenUtils.kt new file mode 100644 index 00000000..4d6d8dcf --- /dev/null +++ b/android/app/src/main/kotlin/com/cloud/diplomaticquarterapp/smart_ring_2301/Util/ScreenUtils.kt @@ -0,0 +1,120 @@ +package com.cloud.diplomaticquarterapp.smart_ring_2301.Util + +import android.app.Activity +import android.content.Context +import android.graphics.Bitmap +import android.graphics.Paint +import android.util.DisplayMetrics +import android.view.WindowManager + +/** + * 获得屏幕相关的辅助类 + * + * + * + */ +class ScreenUtils private constructor() { + init { + /* cannot be instantiated */ + throw UnsupportedOperationException("cannot be instantiated") + } + + companion object { + /** + * 获得屏幕高度 + * + * @param context + * @return + */ + fun getScreenWidth(context: Context): Int { + val wm = context + .getSystemService(Context.WINDOW_SERVICE) as WindowManager + val outMetrics = DisplayMetrics() + wm.defaultDisplay.getMetrics(outMetrics) + return outMetrics.widthPixels + } + + /** + * 获得屏幕宽度 + * + * @param context + * @return + */ + fun getScreenHeight(context: Context): Int { + val wm = context + .getSystemService(Context.WINDOW_SERVICE) as WindowManager + val outMetrics = DisplayMetrics() + wm.defaultDisplay.getMetrics(outMetrics) + return outMetrics.heightPixels + } + + /** + * 获得状态栏的高度 + * + * @param context + * @return + */ + fun getStatusHeight(context: Context): Int { + var statusHeight = -1 + try { + val clazz = Class.forName("com.android.internal.R\$dimen") + val `object` = clazz.newInstance() + val height = clazz.getField("status_bar_height")[`object`].toString().toInt() + statusHeight = context.resources.getDimensionPixelSize(height) + } catch (e: Exception) { + e.printStackTrace() + } + return statusHeight + } + + /** + * 获取当前屏幕截图,包含状态栏 + * + * @param activity + * @return + */ + fun snapShotWithStatusBar(activity: Activity): Bitmap? { + val view = activity.window.decorView + view.isDrawingCacheEnabled = true + view.buildDrawingCache() + val bmp = view.drawingCache + val width = getScreenWidth(activity) + val height = getScreenHeight(activity) + var bp: Bitmap? = null + bp = Bitmap.createBitmap(bmp, 0, 0, width, height) + view.destroyDrawingCache() + return bp + } + /** + * 获取当前屏幕截图,不包含状态栏 + * + * @param activity + * @return + */ + /** + * 根据手机的分辨率从 dp 的单位 转成为 px(像素) + */ + fun dip2px(context: Context, dpValue: Float): Int { + val scale = context.resources.displayMetrics.density + return (dpValue * scale + 0.5f).toInt() + } + + /** + * 根据手机的分辨率从 px(像素) 的单位 转成为 dp + */ + fun px2dip(context: Context, pxValue: Float): Int { + val scale = context.resources.displayMetrics.density + return (pxValue / scale + 0.5f).toInt() + } + + fun sp2px(context: Context, spValue: Float): Int { + val scale = context.resources.displayMetrics.density + return (scale * spValue).toInt() + } + + fun getFontHeight(paint: Paint): Float { + val fm = paint.fontMetrics + return fm.descent - fm.ascent + } + } +} \ No newline at end of file diff --git a/android/app/src/main/kotlin/com/cloud/diplomaticquarterapp/smart_ring_2301/Util/SharedPreferenceUtils.kt b/android/app/src/main/kotlin/com/cloud/diplomaticquarterapp/smart_ring_2301/Util/SharedPreferenceUtils.kt new file mode 100644 index 00000000..6016173c --- /dev/null +++ b/android/app/src/main/kotlin/com/cloud/diplomaticquarterapp/smart_ring_2301/Util/SharedPreferenceUtils.kt @@ -0,0 +1,93 @@ +package com.cloud.diplomaticquarterapp.smart_ring_2301.Util + +import android.app.Activity +import android.content.Context +import android.content.SharedPreferences + +object SharedPreferenceUtils { + const val KEY_REMIND_PSD = "REMIND_PSD" + const val KEY_account_type = "KEY_account_type" + const val KEY_countryCode = "KEY_countryCode" + const val KEY_TimeZone = "KEY_TimeZone" + const val KEY_DFU_ADDRESS = "KEY_DFU_ADDRESS" + const val KEY_Exercise_Mode = "KEY_Exercise_Mode" + const val KEY_Enable_ActivityClock = "KEY_Enable_ActivityClock" + const val KEY_UNIT_WEIGHT = "KEY_UNIT_WEIGHT" + const val KEY_UNIT_HEIGHT = "KEY_UNIT_HEIGHT" + const val KEY_RES_FILEPATH = "KEY_RES_FILEPATH" + const val KEY_Is_First = "KEY_Is_First" + const val KEY_From_Login = "KEY_From_Login" + const val KEY_PHONE = "PHONE" + const val KEY_UID = "uid" + const val KEY_PSD = "PSD" + const val KEY_ADDRESS = "ADDRESS" + const val KEY_Language = "Language" + const val KEY_LOGIN = "lOGIN" + const val KEY_NICKNAME = "nickname" + private const val spName = "jstyle_sleep" + const val KEY_AUTH_USERID = "KEY_AUTH_USERID" + const val KEY_highHeart = "highHeart" + const val KEY_highBrEATH = "highBrEATH" + const val KEY_lowHeart = "lowHeart" + const val KEY_lowBreath = "lowBreath" + const val KEY_deviceName = "deviceName" + const val KEY_PLAN_ON = "PLAN_ON" + const val KEY_PLAN_first = "PLAN_first" + const val KEY_Sleep_goal = "KEY_Sleep_goal" + const val KEY_Step_goal = "KEY_Step_goal" + const val KEY_deviceType = "KEY_deviceType" + var sharedPreferences: SharedPreferences? = null + private set + const val DefaultCountryCode = "0086-" + fun init(context: Context) { + sharedPreferences = context.getSharedPreferences(spName, Activity.MODE_PRIVATE) + } + + fun setSpBoolean(name: String?, bool: Boolean) { + sharedPreferences!!.edit().putBoolean(name, bool).commit() + } + + fun getSpBoolean(name: String?): Boolean { + return sharedPreferences!!.getBoolean(name, false) + } + + fun getBoolean(name: String?, defaultValue: Boolean): Boolean { + return sharedPreferences!!.getBoolean(name, defaultValue) + } + + fun setSpString(name: String?, value: String?) { + sharedPreferences!!.edit().putString(name, value).commit() + } + + fun getSpString(name: String?): String? { + return getString(name, null) + } + + fun getString(name: String?, defaultValue: String?): String? { + return sharedPreferences!!.getString(name, defaultValue) + } + + fun setSpInteger(name: String?, value: Int) { + sharedPreferences!!.edit().putInt(name, value).commit() + } + + fun getInteger(name: String?, defaultValue: Int): Int { + return sharedPreferences!!.getInt(name, defaultValue) + } + + fun getSpInteger(name: String?): Int { + return getInteger(name, -1) + } + + fun setSpFloat(name: String?, value: Float) { + sharedPreferences!!.edit().putFloat(name, value).commit() + } + + fun getSpFloat(name: String?): Float { + return getFloat(name, 0.0f) + } + + fun getFloat(name: String?, defaultValue: Float): Float { + return sharedPreferences!!.getFloat(name, defaultValue) + } +} \ No newline at end of file diff --git a/android/blesdk_2301/build.gradle b/android/blesdk_2301/build.gradle index 1177acf0..0c6cd1c7 100644 --- a/android/blesdk_2301/build.gradle +++ b/android/blesdk_2301/build.gradle @@ -1,4 +1,5 @@ apply plugin: 'com.android.library' +apply plugin: 'org.jetbrains.kotlin.android' android { @@ -44,6 +45,7 @@ android { dependencies { implementation fileTree(dir: 'libs', include: ['*.jar']) + implementation 'androidx.core:core-ktx:+' testImplementation 'junit:junit:4.12' diff --git a/android/blesdk_2301/src/main/java/com/jstyle/blesdk2301/Util/BleSDK.java b/android/blesdk_2301/src/main/java/com/jstyle/blesdk2301/Util/BleSDK.java deleted file mode 100644 index 3ab7053e..00000000 --- a/android/blesdk_2301/src/main/java/com/jstyle/blesdk2301/Util/BleSDK.java +++ /dev/null @@ -1,1006 +0,0 @@ -package com.jstyle.blesdk2301.Util; - -import android.text.TextUtils; - -import com.jstyle.blesdk2301.callback.DataListener2301; -import com.jstyle.blesdk2301.constant.BleConst; -import com.jstyle.blesdk2301.constant.DeviceConst; - -import com.jstyle.blesdk2301.constant.DeviceKey; -import com.jstyle.blesdk2301.model.AutoMode; -import com.jstyle.blesdk2301.model.AutoTestMode; -import com.jstyle.blesdk2301.model.MyAutomaticHRMonitoring; -import com.jstyle.blesdk2301.model.MyPersonalInfo; -import com.jstyle.blesdk2301.model.MyDeviceTime; -import com.jstyle.blesdk2301.other.ResolveUtil; - -import java.io.UnsupportedEncodingException; -import java.text.SimpleDateFormat; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Date; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - - -/** - * Created by Administrator on 2018/4/9. - */ - -public class BleSDK { - public static final int DATA_READ_START = 0; - public static final int DATA_READ_CONTINUE = 2; - public static final int DATA_DELETE = 99; - public static final byte DistanceMode_MILE = (byte) 0x81; - public static final byte DistanceMode_KM = (byte) 0x80; - public static final byte TimeMode_12h = (byte) 0x81; - public static final byte TimeMode_24h = (byte) 0x80; - public static final byte WristOn_Enable = (byte) 0x81; - public static final byte WristOn_DisEnable = (byte) 0x80; - public static final byte TempUnit_C = (byte) 0x80; - public static final byte TempUnit_F = (byte) 0x81; - - public static final String TAG = "BleSDK"; - public static boolean isruning = false; - - private static byte[] getByteArray(float f) { - int intbits = Float.floatToIntBits(f);//将float里面的二进制串解释为int整数 - return getByteArrays(intbits); - } - - public static byte[] getByteArrays(int i) { - byte[] b = new byte[4]; - b[3] = (byte) ((i & 0xff000000) >> 24); - b[2] = (byte) ((i & 0x00ff0000) >> 16); - b[1] = (byte) ((i & 0x0000ff00) >> 8); - b[0] = (byte) (i & 0x000000ff); - return b; - } - - - public static void DataParsingWithData(byte[] value, final DataListener2301 dataListener) { - Map map = new HashMap<>(); - switch (value[0]) { - - case DeviceConst.CMD_Set_UseInfo: - dataListener.dataCallback(ResolveUtil.setMethodSuccessful(BleConst.SetPersonalInfo)); - break; - case DeviceConst.CMD_Set_Auto: - dataListener.dataCallback(ResolveUtil.setMethodSuccessful(BleConst.SetAutomatic)); - break; - case DeviceConst.CMD_Set_DeviceID: - dataListener.dataCallback(ResolveUtil.setMacSuccessful()); - break; - case DeviceConst.CMD_SET_TIME: - dataListener.dataCallback(ResolveUtil.setTimeSuccessful(value)); - break; - - case DeviceConst.CMD_GET_TIME: - dataListener.dataCallback(ResolveUtil.getDeviceTime(value)); - break; - case DeviceConst.CMD_GET_USERINFO: - dataListener.dataCallback(ResolveUtil.getUserInfo(value)); - break; - case DeviceConst.CMD_Enable_Activity: - dataListener.dataCallback(ResolveUtil.getActivityData(value)); - break; - case DeviceConst.CMD_Get_BatteryLevel: - dataListener.dataCallback(ResolveUtil.getDeviceBattery(value)); - break; - case DeviceConst.CMD_Get_Address: - dataListener.dataCallback(ResolveUtil.getDeviceAddress(value)); - break; - case DeviceConst.CMD_Get_Version: - dataListener.dataCallback(ResolveUtil.getDeviceVersion(value)); - break; - case DeviceConst.CMD_Get_Auto: - dataListener.dataCallback(ResolveUtil.getAutoHeart(value)); - break; - case DeviceConst.CMD_Reset: - dataListener.dataCallback(ResolveUtil.Reset()); - break; - case DeviceConst.CMD_Mcu_Reset: - dataListener.dataCallback(ResolveUtil.MCUReset()); - break; - case DeviceConst.CMD_Get_TotalData: - if (GetTotalActivityDataWithMode) { - dataListener.dataCallback(ResolveUtil.setMethodSuccessful(BleConst.Delete_GetTotalActivityData)); - } else { - dataListener.dataCallback(ResolveUtil.getTotalStepData(value)); - } - break; - case DeviceConst.CMD_Get_DetailData: - if (GetDetailActivityDataWithMode) { - dataListener.dataCallback(ResolveUtil.setMethodSuccessful(BleConst.deleteGetDetailActivityDataWithMode)); - } else { - dataListener.dataCallback(ResolveUtil.getDetailData(value)); - } - break; - case DeviceConst.CMD_Get_SleepData: - if (Delete_GetDetailSleepData) { - dataListener.dataCallback(ResolveUtil.setMethodSuccessful(BleConst.Delete_GetDetailSleepData)); - } else { - dataListener.dataCallback(ResolveUtil.getSleepData(value)); - } - break; - case DeviceConst.CMD_Get_HeartData: - if (GetDynamicHRWithMode) { - dataListener.dataCallback(ResolveUtil.setMethodSuccessful(BleConst.Delete_GetDynamicHR)); - } else { - dataListener.dataCallback(ResolveUtil.getHeartData(value)); - } - - break; - case DeviceConst.CMD_Get_OnceHeartData: - if (GetStaticHRWithMode) { - dataListener.dataCallback(ResolveUtil.setMethodSuccessful(BleConst.Delete_GetStaticHR)); - } else { - dataListener.dataCallback(ResolveUtil.getOnceHeartData(value)); - } - - break; - case DeviceConst.CMD_Get_HrvTestData: - if (readhrv) { - dataListener.dataCallback(ResolveUtil.getHrvTestData(value)); - } else { - dataListener.dataCallback(ResolveUtil.DeleteHrv()); - } - break; - case DeviceConst.ReadTempHisrory: - if (GetTemperature_historyDataWithMode) { - dataListener.dataCallback(ResolveUtil.setMethodSuccessful(BleConst.deleteGetTemperature_historyDataWithMode)); - } else { - dataListener.dataCallback(ResolveUtil.getTempData(value)); - } - break; - case DeviceConst.Oxygen_data: - if (Obtain_The_data_of_manual_blood_oxygen_test) { - dataListener.dataCallback(ResolveUtil.setMethodSuccessful(BleConst.Delete_Obtain_The_data_of_manual_blood_oxygen_test)); - } else { - dataListener.dataCallback(ResolveUtil.GetAutomaticSpo2Monitoring(value)); - } - break; - case DeviceConst.CMD_HeartPackageFromDevice: - dataListener.dataCallback(ResolveUtil.getActivityExerciseData(value)); - break; - case DeviceConst.CMD_Set_Name: - dataListener.dataCallback(ResolveUtil.setMethodSuccessful(BleConst.CMD_Set_Name)); - break; - case DeviceConst.CMD_Get_Name: - dataListener.dataCallback(ResolveUtil.getDeviceName(value)); - break; - case DeviceConst.CMD_Get_SPORTData: - if (GetActivityModeDataWithMode) { - dataListener.dataCallback(ResolveUtil.setMethodSuccessful(BleConst.Delete_ActivityModeData)); - } else { - dataListener.dataCallback(ResolveUtil.getExerciseData(value)); - } - break; - case DeviceConst.MeasurementWithType: - if (StartDeviceMeasurementWithType) { - Map vv = new HashMap<>(); - switch (value[1]) { - case 1://hrv - vv.put(DeviceKey.DataType, BleConst.MeasurementHrvCallback); - vv.put(DeviceKey.End, true); - Map lm = new HashMap<>(); - lm.put(DeviceKey.Type, ResolveUtil.getValue(value[1], 0) + ""); - lm.put(DeviceKey.HeartRate, ResolveUtil.getValue(value[2], 0) + ""); - lm.put(DeviceKey.Blood_oxygen, ResolveUtil.getValue(value[3], 0) + ""); - lm.put(DeviceKey.HRV, ResolveUtil.getValue(value[4], 0) + ""); - lm.put(DeviceKey.Stress, ResolveUtil.getValue(value[5], 0) + ""); - lm.put(DeviceKey.HighPressure, ResolveUtil.getValue(value[6], 0) + ""); - lm.put(DeviceKey.LowPressure, ResolveUtil.getValue(value[7], 0) + ""); - vv.put(DeviceKey.Data, lm); - dataListener.dataCallback(vv); - break; - case 2://heart - vv.put(DeviceKey.DataType, BleConst.MeasurementHeartCallback); - vv.put(DeviceKey.End, true); - Map lmB = new HashMap<>(); - lmB.put(DeviceKey.Type, ResolveUtil.getValue(value[1], 0) + ""); - lmB.put(DeviceKey.HeartRate, ResolveUtil.getValue(value[2], 0) + ""); - lmB.put(DeviceKey.Blood_oxygen, ResolveUtil.getValue(value[3], 0) + ""); - lmB.put(DeviceKey.HRV, ResolveUtil.getValue(value[4], 0) + ""); - lmB.put(DeviceKey.Stress, ResolveUtil.getValue(value[5], 0) + ""); - lmB.put(DeviceKey.HighPressure, ResolveUtil.getValue(value[6], 0) + ""); - lmB.put(DeviceKey.LowPressure, ResolveUtil.getValue(value[7], 0) + ""); - vv.put(DeviceKey.Data, lmB); - dataListener.dataCallback(vv); - break; - case 3://0xy - vv.put(DeviceKey.DataType, BleConst.MeasurementOxygenCallback); - vv.put(DeviceKey.End, true); - Map lmC = new HashMap<>(); - lmC.put(DeviceKey.Type, ResolveUtil.getValue(value[1], 0) + ""); - lmC.put(DeviceKey.HeartRate, ResolveUtil.getValue(value[2], 0) + ""); - lmC.put(DeviceKey.Blood_oxygen, ResolveUtil.getValue(value[3], 0) + ""); - lmC.put(DeviceKey.HRV, ResolveUtil.getValue(value[4], 0) + ""); - lmC.put(DeviceKey.Stress, ResolveUtil.getValue(value[5], 0) + ""); - lmC.put(DeviceKey.HighPressure, ResolveUtil.getValue(value[6], 0) + ""); - lmC.put(DeviceKey.LowPressure, ResolveUtil.getValue(value[7], 0) + ""); - vv.put(DeviceKey.Data, lmC); - dataListener.dataCallback(vv); - break; - } - } else { - Map vv = new HashMap<>(); - switch (value[1]) { - case 1://hrv - vv.put(DeviceKey.DataType, BleConst.StopMeasurementHrvCallback); - vv.put(DeviceKey.End, true); - vv.put(DeviceKey.Data, new HashMap<>()); - dataListener.dataCallback(vv); - break; - case 2://heart - vv.put(DeviceKey.DataType, BleConst.StopMeasurementHeartCallback); - vv.put(DeviceKey.End, true); - vv.put(DeviceKey.Data, new HashMap<>()); - dataListener.dataCallback(vv); - break; - case 3://0xy - vv.put(DeviceKey.DataType, BleConst.StopMeasurementOxygenCallback); - vv.put(DeviceKey.End, true); - vv.put(DeviceKey.Data, new HashMap<>()); - dataListener.dataCallback(vv); - break; - } - } - break; - case DeviceConst.CMD_Get_Bloodsugar: - if (startBloodsugar) {//只有开始测量才返回状态 - Map vv = new HashMap<>(); - vv.put(DeviceKey.DataType, BleConst.Blood_glucose_status); - vv.put(DeviceKey.End, true); - Map lm = new HashMap<>(); - lm.put(DeviceKey.Type, ResolveUtil.getValue(value[1], 0) + ""); - vv.put(DeviceKey.Data, lm); - dataListener.dataCallback(vv); - } - break; - case DeviceConst.Bloodsugar_data: - Map vv = new HashMap<>(); - vv.put(DeviceKey.DataType, BleConst.Blood_glucose_data); - vv.put(DeviceKey.End, false); - Map lm = new HashMap<>(); - lm.put(DeviceKey.Time, getFormatTimeString(System.currentTimeMillis(), "yyyy.MM.dd HH:mm:ss")); - List simplePpg = new ArrayList<>(); - if (value.length == 153) {//新血糖解析 - byte[] valueer = new byte[value.length - 3]; - System.arraycopy(value, 3, valueer, 0, valueer.length); - for (int i = 0; i < valueer.length / 3; i++) { - int valuedata = ResolveUtil.getValue(valueer[3 * i], 2) - + ResolveUtil.getValue(valueer[3 * i + 1], 1) - + ResolveUtil.getValue(valueer[3 * i + 2], 0); - simplePpg.add(valuedata); - } - lm.put(DeviceKey.PPG, Arrays.toString(simplePpg.toArray())); - } - vv.put(DeviceKey.Data, lm); - dataListener.dataCallback(vv); - break; - - case DeviceConst.CMD_Start_EXERCISE: - if(FindActivityMode){ - Map mapEXERCISE = new HashMap<>(); - mapEXERCISE.put(DeviceKey.DataType, BleConst.FindActivityMode); - mapEXERCISE.put(DeviceKey.End, true); - Map mapsx = new HashMap<>(); - mapsx.put(DeviceKey.Type, ResolveUtil.getValue(value[1], 0) + ""); - mapsx.put(DeviceKey.Status, ResolveUtil.getValue(value[2], 0) + ""); - mapEXERCISE.put(DeviceKey.Data, mapsx); - dataListener.dataCallback(mapEXERCISE); - }else{ - Map mapEXERCISE = new HashMap<>(); - mapEXERCISE.put(DeviceKey.DataType, BleConst.EnterActivityMode); - mapEXERCISE.put(DeviceKey.End, true); - Map mapsx = new HashMap<>(); - mapsx.put(DeviceKey.enterActivityModeSuccess, ResolveUtil.getValue(value[1], 0) + ""); - mapEXERCISE.put(DeviceKey.Data, mapsx); - dataListener.dataCallback(mapEXERCISE); - } - break; - - - } - // return map; - } - - protected static boolean Delete_GetDetailSleepData = false; - - public static byte[] GetDetailSleepDataWithMode(byte mode, String dateOfLastData) { - Delete_GetDetailSleepData = ((byte) 0x99 == mode); - byte[] value = new byte[16]; - value[0] = DeviceConst.CMD_Get_SleepData; - value[1] = mode; - insertDateValue(value, dateOfLastData); - crcValue(value); - return value; - } - - - /** - * 开始实时计步 - * - * @return - */ - public static byte[] RealTimeStep(boolean enable, boolean tempEnable) { - byte[] value = new byte[16]; - value[0] = DeviceConst.CMD_Enable_Activity; - value[1] = (byte) (enable ? 1 : 0); - value[2] = (byte) (tempEnable ? 1 : 0); - crcValue(value); - return value; - } - - - /** - * 设置个人信息 - * - * @param - * @return - */ - public static byte[] SetPersonalInfo(MyPersonalInfo info) { - byte[] value = new byte[16]; - int male = info.getSex(); - int age = info.getAge(); - int height = info.getHeight(); - int weight = info.getWeight(); - int stepLength = info.getStepLength(); - value[0] = DeviceConst.CMD_Set_UseInfo; - value[1] = (byte) male; - value[2] = (byte) age; - value[3] = (byte) height; - value[4] = (byte) weight; - value[5] = (byte) stepLength; - crcValue(value); - - return value; - } - - - /** - * 获取个人信息 - * - * @return - */ - public static byte[] GetPersonalInfo() { - byte[] value = new byte[16]; - value[0] = DeviceConst.CMD_GET_USERINFO; - crcValue(value); - return value; - } - - - /** - * 设置设备时间 - * - * @param - * @return - */ - public static byte[] SetDeviceTime(MyDeviceTime time) { - byte[] value = new byte[16]; - String timeZone = ResolveUtil.getCurrentTimeZone(); - String zone = timeZone.substring(3); - byte zoneValue = 0; - if (zone.contains("-")) { - zone = zone.replace("-", ""); - zoneValue = Byte.valueOf(String.valueOf(zone)); - } else { - zoneValue = (byte) (Byte.valueOf(zone) + 0x80); - } - int year = time.getYear(); - int month = time.getMonth(); - int day = time.getDay(); - int hour = time.getHour(); - int min = time.getMinute(); - int second = time.getSecond(); - value[0] = DeviceConst.CMD_SET_TIME; - value[1] = ResolveUtil.getTimeValue(year); - value[2] = ResolveUtil.getTimeValue(month); - value[3] = ResolveUtil.getTimeValue(day); - value[4] = ResolveUtil.getTimeValue(hour); - value[5] = ResolveUtil.getTimeValue(min); - value[6] = ResolveUtil.getTimeValue(second); - value[8] = zoneValue; - crcValue(value); - - return value; - } - - - /** - * 获取设备时间 - * - * @return - */ - public static byte[] GetDeviceTime() { - byte[] value = new byte[16]; - value[0] = DeviceConst.CMD_GET_TIME; - crcValue(value); - return value; - } - - - /** - * 99: 删除步数详细数据 , - * 0:读最近的步数详细数据。 - * 1:读指定位置的步数详细数据。 - * 2:继续上次读的位置下一段数据 - * - * @param - * @return * dateOfLastData "yyyy-MM-dd HH:mm:ss or yyyy.MM.dd HH:mm:ss" - */ - private static boolean GetDetailActivityDataWithMode = false; - - public static byte[] GetDetailActivityDataWithMode(byte mode, String dateOfLastData) { - GetDetailActivityDataWithMode = ((byte) 0x99 == mode); - byte[] value = new byte[16]; - value[0] = DeviceConst.CMD_Get_DetailData; - value[1] = (byte) mode; - insertDateValue(value, dateOfLastData); - crcValue(value); - return value; - } - - /** - * 99: 删除温度数据 , - * 0:读最近的温度详细数据。 - * 1:读指定位置的步数详细数据。 - * 2:继续上次读的位置下一段数据 - * - * @param - * @return - */ - protected static boolean GetTemperature_historyDataWithMode; - - public static byte[] GetTemperature_historyData(byte mode, String dateOfLastData) { - GetTemperature_historyDataWithMode = ((byte) 0x99 == mode); - byte[] value = new byte[16]; - value[0] = DeviceConst.ReadTempHisrory; - value[1] = mode; - insertDateValue(value, dateOfLastData); - crcValue(value); - return value; - } - - public static boolean StartDeviceMeasurementWithType = false; - - public static byte[] SetDeviceMeasurementWithType(AutoTestMode dataType, long second, boolean open) { - StartDeviceMeasurementWithType = open; - byte[] value = new byte[16]; - value[0] = DeviceConst.MeasurementWithType; - switch (dataType) { - case AutoHeartRate: - value[1] = (byte) 0x02; - break; - case AutoSpo2: - value[1] = (byte) 0x03; - break; - - } - value[2] = open ? (byte) 0x01 : (byte) 0x00; - value[3] = (byte) ((second) & 0xff); - value[4] = (byte) ((second >> 8) & 0xff); - crcValue(value); - return value; - } - - public static byte[] SetAutomaticHRMonitoring(MyAutomaticHRMonitoring autoHeart, AutoMode type) { - byte[] value = new byte[16]; - int time = autoHeart.getTime(); - value[0] = DeviceConst.CMD_Set_Auto; - value[1] = (byte) autoHeart.getOpen(); - value[2] = ResolveUtil.getTimeValue(autoHeart.getStartHour()); - value[3] = ResolveUtil.getTimeValue(autoHeart.getStartMinute()); - value[4] = ResolveUtil.getTimeValue(autoHeart.getEndHour()); - value[5] = ResolveUtil.getTimeValue(autoHeart.getEndMinute()); - value[6] = (byte) autoHeart.getWeek(); - value[7] = (byte) (time & 0xff); - value[8] = (byte) ((time >> 8) & 0xff); - if (null == type) { - value[9] = (byte) 0x01; - } else { - switch (type) { - case AutoHeartRate: - value[9] = (byte) 0x01; - break; - case AutoSpo2: - value[9] = (byte) 0x02; - break; - case AutoTemp: - value[9] = (byte) 0x03; - break; - case AutoHrv: - value[9] = (byte) 0x04; - break; - } - } - crcValue(value); - return value; - } - - - public static byte[] GetAutomatic(AutoMode type) { - byte[] value = new byte[16]; - value[0] = DeviceConst.CMD_Get_Auto; - if (null == type) { - value[1] = (byte) 0x01; - } else { - switch (type) { - case AutoHeartRate: - value[1] = (byte) 0x01; - break; - case AutoSpo2: - value[1] = (byte) 0x02; - break; - case AutoTemp: - value[1] = (byte) 0x03; - break; - case AutoHrv: - value[1] = (byte) 0x04; - break; - } - } - crcValue(value); - return value; - } - - - /** - * 获取某天总数据 - * 0 - * - * @param mode 0:表⽰是从最新的位置开始读取(最多50组数据) 2:表⽰接着读取(当数据总数⼤于50的时候) 0x99:表⽰删除所有运 - * 动数据 - * @return - */ - protected static boolean GetTotalActivityDataWithMode; - - public static byte[] GetTotalActivityDataWithMode(byte mode, String dateOfLastData) { - GetTotalActivityDataWithMode = (byte) 0x99 == mode; - byte[] value = new byte[16]; - value[0] = DeviceConst.CMD_Get_TotalData; - value[1] = mode; - insertDateValueNoH(value, dateOfLastData); - crcValue(value); - return value; - } - - - /** - * 获取设备版本号 - * - * @return - */ - public static byte[] GetDeviceVersion() { - byte[] value = new byte[16]; - value[0] = DeviceConst.CMD_Get_Version; - crcValue(value); - return value; - } - - - /** - * 恢复出厂设置 - * - * @return - */ - public static byte[] Reset() { - byte[] value = new byte[16]; - value[0] = DeviceConst.CMD_Reset; - crcValue(value); - return value; - } - - - /** - * 获取设备mac地址 - * - * @return - */ - public static byte[] GetDeviceMacAddress() { - byte[] value = new byte[16]; - value[0] = DeviceConst.CMD_Get_Address; - crcValue(value); - return value; - } - - - /** - * 获取设备电量 - * - * @return - */ - public static byte[] GetDeviceBatteryLevel() { - byte[] value = new byte[16]; - value[0] = DeviceConst.CMD_Get_BatteryLevel; - crcValue(value); - return value; - } - - - /** - * 重启设备 - * - * @return - */ - public static byte[] MCUReset() { - byte[] value = new byte[16]; - value[0] = DeviceConst.CMD_Mcu_Reset; - crcValue(value); - return value; - } - - - private static boolean readhrv = false; - - public static byte[] GetHRVDataWithMode(byte mode, String dateOfLastData) { - readhrv = (byte) 0x99 != mode; - byte[] value = new byte[16]; - value[0] = DeviceConst.CMD_Get_HrvTestData; - value[1] = mode; - insertDateValue(value, dateOfLastData); - crcValue(value); - return value; - } - - - protected static boolean GetStaticHRWithMode; - - public static byte[] GetStaticHRWithMode(byte mode, String dateOfLastData) { - GetStaticHRWithMode = ((byte) 0x99 == mode); - byte[] value = new byte[16]; - value[0] = DeviceConst.CMD_Get_OnceHeartData; - value[1] = mode; - insertDateValue(value, dateOfLastData); - crcValue(value); - return value; - } - - - protected static boolean GetDynamicHRWithMode; - - public static byte[] GetDynamicHRWithMode(byte Number, String dateOfLastData) { - GetDynamicHRWithMode = (byte) 0x99 == Number; - byte[] value = new byte[16]; - value[0] = DeviceConst.CMD_Get_HeartData; - value[1] = (byte) Number; - insertDateValue(value, dateOfLastData); - crcValue(value); - return value; - } - - - public static byte[] SetDeviceID(String deviceId) { - byte[] value = new byte[16]; - value[0] = DeviceConst.CMD_Set_DeviceID; - for (int i = 0; i < 6; i++) { - value[i + 1] = (byte) deviceId.charAt(i); - } - crcValue(value); - return value; - } - - - public static byte[] intTobyte(int num) { - return new byte[]{(byte) ((num >> 8) & 0xff), (byte) (num & 0xff)}; - } - - public static int byteArrayToInt(byte[] arr) { - short targets = (short) ((arr[1] & 0xff) | ((arr[0] << 8) & 0xff00)); - - return targets; - } - - - public static byte[] getInfoValue(String info, int maxLength) { - byte[] nameBytes = null; - try { - nameBytes = info.getBytes("UTF-8"); - if (nameBytes.length >= maxLength) {//两条命令总共32个字节,内容只占24个字节(32-2*(1cmd+1消息类型+1长度+1校验)) - byte[] real = new byte[maxLength]; - char[] chars = info.toCharArray(); - int length = 0; - for (int i = 0; i < chars.length; i++) { - String s = String.valueOf(chars[i]); - byte[] nameB = s.getBytes("UTF-8"); - ; - if (length + nameB.length == maxLength) { - System.arraycopy(nameBytes, 0, real, 0, real.length); - return real; - } else if (length + nameB.length > maxLength) {//大于24会导致有个字节发不到下位机导致乱码 - System.arraycopy(nameBytes, 0, real, 0, length); - return real; - } - length += nameB.length; - } - } - } catch (UnsupportedEncodingException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - - return nameBytes; - } - - public static void crcValue(byte[] value) { - byte crc = 0; - for (int i = 0; i < value.length - 1; i++) { - crc += value[i]; - } - value[value.length - 1] = (byte) (crc & 0xff); - } - - - public static void insertDateValue(byte[] value, String time) { - if (!TextUtils.isEmpty(time) && time.length() > 8) { - String[] timeArray = time.split(" "); - String INDEX; - if (time.contains("-")) { - INDEX = "-"; - } else { - INDEX = "\\."; - } - int year = Integer.parseInt(timeArray[0].split(INDEX)[0]); - int month = Integer.parseInt(timeArray[0].split(INDEX)[1]); - int day = Integer.parseInt(timeArray[0].split(INDEX)[2]); - int hour = Integer.parseInt(timeArray[1].split(":")[0]); - int min = Integer.parseInt(timeArray[1].split(":")[1]); - int second = Integer.parseInt(timeArray[1].split(":")[2]); - value[4] = ResolveUtil.getTimeValue(year); - value[5] = ResolveUtil.getTimeValue(month); - value[6] = ResolveUtil.getTimeValue(day); - value[7] = ResolveUtil.getTimeValue(hour); - value[8] = ResolveUtil.getTimeValue(min); - value[9] = ResolveUtil.getTimeValue(second); - } - - } - - - public static void insertDateValueNoH(byte[] value, String time) { - if (!TextUtils.isEmpty(time) && time.contains("-")) { - String[] timeArray = time.split(" "); - String INDEX; - if (time.contains("-")) { - INDEX = "-"; - } else { - INDEX = "\\."; - } - int year = Integer.parseInt(timeArray[0].split(INDEX)[0]); - int month = Integer.parseInt(timeArray[0].split(INDEX)[1]); - int day = Integer.parseInt(timeArray[0].split(INDEX)[2]); - value[4] = ResolveUtil.getTimeValue(year); - value[5] = ResolveUtil.getTimeValue(month); - value[6] = ResolveUtil.getTimeValue(day); - } - - - } - - - /** - * 转十六进制字符串 - * - * @param data - * @return - */ - public static String byte2Hex(byte[] data) { - if (data != null && data.length > 0) { - StringBuilder sb = new StringBuilder(data.length); - for (byte tmp : data) { - sb.append(String.format("%02X ", tmp)); - } - return sb.toString(); - } - return "no data"; - } - - - /** - * OObtain automated test oximetry data - * 获得自动测试血氧数据 - */ - protected static boolean Obtain_The_data_of_manual_blood_oxygen_test; - - public static byte[] Oxygen_data(byte Number) { - Obtain_The_data_of_manual_blood_oxygen_test = ((byte) 0x99 == Number); - byte[] value = new byte[16]; - value[0] = DeviceConst.Oxygen_data; - value[1] = (byte) Number; - crcValue(value); - return value; - } - - public static byte[] EnterActivityMode(int time, int activityMode, int WorkMode) { - FindActivityMode=false; - byte[] value = new byte[16]; - value[0] = DeviceConst.CMD_Start_EXERCISE; - value[1] = (byte) WorkMode; - value[2] = (byte) activityMode; - value[4] = (byte) time; - crcValue(value); - return value; - } - - private static boolean FindActivityMode=false; - public static byte[] FindActivityMode() { - FindActivityMode=true; - byte[] value = new byte[16]; - value[0] = DeviceConst.CMD_Start_EXERCISE; - value[1] = (byte) 0x05; - crcValue(value); - return value; - } - - /** - * @param status 级别 0,1,2 - * @param time 分钟 - * @param WorkMode START=1;PAUSE=2;CONTUINE=3;FINISH=4; - * @return - */ - public static byte[] setExerciseModeByBreath(int status, int time, int WorkMode) { - FindActivityMode=false; - byte[] value = new byte[16]; - value[0] = DeviceConst.CMD_Start_EXERCISE; - value[1] = (byte) WorkMode; - value[2] = (byte) 0x06; - value[3] = (byte) status; - value[4] = (byte) time; - crcValue(value); - return value; - } - - public static byte[] sendHeartPackage(float distance, int space, int rssi) { - byte[] value = new byte[16]; - byte[] distanceValue = getByteArray(distance); - int min = space / 60; - int second = space % 60; - value[0] = DeviceConst.CMD_heart_package; - System.arraycopy(distanceValue, 0, value, 1, distanceValue.length); - value[5] = (byte) min; - value[6] = (byte) second; - value[7] = (byte) rssi; - crcValue(value); - return value; - } - - /** - * 设置设备名字 - * - * @param - * @return - */ - public static byte[] SetDeviceName(String strDeviceName) { - byte[] value = new byte[16]; - value[0] = DeviceConst.CMD_Set_Name; - int length = strDeviceName.length() > 14 ? 14 : strDeviceName.length(); - for (int i = 0; i < length; i++) { - value[i + 1] = (byte) strDeviceName.charAt(i); - } - crcValue(value); - return value; - } - - - /** - * 获取设备名字 - * - * @return - */ - public static byte[] GetDeviceName() { - byte[] value = new byte[16]; - value[0] = DeviceConst.CMD_Get_Name; - crcValue(value); - return value; - } - - - /** - * 获取多模式运动数据 - * - * @param mode 0:表⽰是从最新的位置开始读取(最多50组数据) 2:表⽰接着读取(当数据总数⼤于50的时候) 0x99:表⽰删除所有 - * GPS数据 - * @return - */ - protected static boolean GetActivityModeDataWithMode; - - public static byte[] GetActivityModeDataWithMode(byte mode) { - GetActivityModeDataWithMode = ((byte) 0x99 == mode); - byte[] value = new byte[16]; - value[0] = DeviceConst.CMD_Get_SPORTData; - value[1] = mode; - crcValue(value); - return value; - } - - - /** - * 开始血氧测量 - * Start blood oxygen measurement - */ - public static boolean startBloodsugar = false; - - public static byte[] startBloodsugar() { - startBloodsugar = true; - byte[] value = new byte[16]; - value[0] = DeviceConst.CMD_Get_Bloodsugar; - value[1] = (byte) 0x01; - crcValue(value); - return value; - } - - /** - * 停止血氧测量 - * Stop blood oxygen measurement - */ - public static byte[] BloodsugarStop() { - startBloodsugar = false; - byte[] value = new byte[16]; - value[0] = DeviceConst.CMD_Get_Bloodsugar; - value[1] = (byte) 0x05; - crcValue(value); - return value; - } - - /** - * 血氧测量停止信号采集 - * Blood oxygen measurement stop signal acquisition - */ - public static byte[] BloodsugarStopSiss() { - startBloodsugar = false; - byte[] value = new byte[16]; - value[0] = DeviceConst.CMD_Get_Bloodsugar; - value[1] = (byte) 0x03; - crcValue(value); - return value; - } - - - /** - * 血氧测量进度更新 - * Blood oxygen measurement progress update - */ - public static byte[] BloodsugarProgress(int Progress) { - startBloodsugar = false; - byte[] value = new byte[16]; - value[0] = DeviceConst.CMD_Get_Bloodsugar; - value[1] = (byte) 0x04; - value[2] = (byte) Progress;//0-100 - crcValue(value); - return value; - } - - /** - * 血氧测量结果 - * Send blood glucose results to the device - * status 1低 2中 3高 0测试失败 - * Status 1 low 2 3 high 0 test failed - */ - public static byte[] SendBloodGlucoseResultsToTheDevice(int status) { - startBloodsugar = false; - byte[] value = new byte[16]; - value[0] = DeviceConst.CMD_Get_Bloodsugar; - value[1] = (byte) 0x02; - value[2] = (byte) status; - crcValue(value); - return value; - } - - - /** - * 获取指定格式的日期字符串 - */ - public static synchronized String getFormatTimeString(long time, String formatString) { - SimpleDateFormat format = new SimpleDateFormat(formatString); - String data = ""; - try { - data = format.format(new Date(time)); - } catch (Exception E) { - E.printStackTrace(); - } - return data; - } -} diff --git a/android/blesdk_2301/src/main/java/com/jstyle/blesdk2301/Util/BleSDK.kt b/android/blesdk_2301/src/main/java/com/jstyle/blesdk2301/Util/BleSDK.kt new file mode 100644 index 00000000..992416a8 --- /dev/null +++ b/android/blesdk_2301/src/main/java/com/jstyle/blesdk2301/Util/BleSDK.kt @@ -0,0 +1,886 @@ +package com.jstyle.blesdk2301.Util + +import android.text.TextUtils +import com.jstyle.blesdk2301.callback.DataListener2301 +import com.jstyle.blesdk2301.constant.BleConst +import com.jstyle.blesdk2301.constant.DeviceConst +import com.jstyle.blesdk2301.constant.DeviceKey +import com.jstyle.blesdk2301.model.AutoMode +import com.jstyle.blesdk2301.model.AutoTestMode +import com.jstyle.blesdk2301.model.MyAutomaticHRMonitoring +import com.jstyle.blesdk2301.model.MyDeviceTime +import com.jstyle.blesdk2301.model.MyPersonalInfo +import com.jstyle.blesdk2301.other.ResolveUtil +import java.io.UnsupportedEncodingException +import java.text.SimpleDateFormat +import java.util.Arrays +import java.util.Date +import kotlin.experimental.and + +/** + * Created by Administrator on 2018/4/9. + */ +object BleSDK { + const val DATA_READ_START = 0 + const val DATA_READ_CONTINUE = 2 + const val DATA_DELETE = 99 + const val DistanceMode_MILE = 0x81.toByte() + const val DistanceMode_KM = 0x80.toByte() + const val TimeMode_12h = 0x81.toByte() + const val TimeMode_24h = 0x80.toByte() + const val WristOn_Enable = 0x81.toByte() + const val WristOn_DisEnable = 0x80.toByte() + const val TempUnit_C = 0x80.toByte() + const val TempUnit_F = 0x81.toByte() + const val TAG = "BleSDK" + var isruning = false + private fun getByteArray(f: Float): ByteArray { + val intbits = java.lang.Float.floatToIntBits(f) //将float里面的二进制串解释为int整数 + return getByteArrays(intbits) + } + + fun getByteArrays(i: Int): ByteArray { + val b = ByteArray(4) + b[3] = (i and -0x1000000 shr 24).toByte() + b[2] = (i and 0x00ff0000 shr 16).toByte() + b[1] = (i and 0x0000ff00 shr 8).toByte() + b[0] = (i and 0x000000ff).toByte() + return b + } + + fun DataParsingWithData(value: ByteArray, dataListener: DataListener2301) { + val map: Map = HashMap() + when (value[0]) { + DeviceConst.CMD_Set_UseInfo -> dataListener.dataCallback(ResolveUtil.setMethodSuccessful(BleConst.SetPersonalInfo)) + DeviceConst.CMD_Set_Auto -> dataListener.dataCallback(ResolveUtil.setMethodSuccessful(BleConst.SetAutomatic)) + DeviceConst.CMD_Set_DeviceID -> dataListener.dataCallback(ResolveUtil.setMacSuccessful()) + DeviceConst.CMD_SET_TIME -> dataListener.dataCallback(ResolveUtil.setTimeSuccessful(value)) + DeviceConst.CMD_GET_TIME -> dataListener.dataCallback(ResolveUtil.getDeviceTime(value)) + DeviceConst.CMD_GET_USERINFO -> dataListener.dataCallback(ResolveUtil.getUserInfo(value)) + DeviceConst.CMD_Enable_Activity -> dataListener.dataCallback(ResolveUtil.getActivityData(value)) + DeviceConst.CMD_Get_BatteryLevel -> dataListener.dataCallback(ResolveUtil.getDeviceBattery(value)) + DeviceConst.CMD_Get_Address -> dataListener.dataCallback(ResolveUtil.getDeviceAddress(value)) + DeviceConst.CMD_Get_Version -> dataListener.dataCallback(ResolveUtil.getDeviceVersion(value)) + DeviceConst.CMD_Get_Auto -> dataListener.dataCallback(ResolveUtil.getAutoHeart(value)) + DeviceConst.CMD_Reset -> dataListener.dataCallback(ResolveUtil.Reset()) + DeviceConst.CMD_Mcu_Reset -> dataListener.dataCallback(ResolveUtil.MCUReset()) + DeviceConst.CMD_Get_TotalData -> if (GetTotalActivityDataWithMode) { + dataListener.dataCallback(ResolveUtil.setMethodSuccessful(BleConst.Delete_GetTotalActivityData)) + } else { + dataListener.dataCallback(ResolveUtil.getTotalStepData(value)) + } + + DeviceConst.CMD_Get_DetailData -> if (GetDetailActivityDataWithMode) { + dataListener.dataCallback(ResolveUtil.setMethodSuccessful(BleConst.deleteGetDetailActivityDataWithMode)) + } else { + dataListener.dataCallback(ResolveUtil.getDetailData(value)) + } + + DeviceConst.CMD_Get_SleepData -> if (Delete_GetDetailSleepData) { + dataListener.dataCallback(ResolveUtil.setMethodSuccessful(BleConst.Delete_GetDetailSleepData)) + } else { + dataListener.dataCallback(ResolveUtil.getSleepData(value)) + } + + DeviceConst.CMD_Get_HeartData -> if (GetDynamicHRWithMode) { + dataListener.dataCallback(ResolveUtil.setMethodSuccessful(BleConst.Delete_GetDynamicHR)) + } else { + dataListener.dataCallback(ResolveUtil.getHeartData(value)) + } + + DeviceConst.CMD_Get_OnceHeartData -> if (GetStaticHRWithMode) { + dataListener.dataCallback(ResolveUtil.setMethodSuccessful(BleConst.Delete_GetStaticHR)) + } else { + dataListener.dataCallback(ResolveUtil.getOnceHeartData(value)) + } + + DeviceConst.CMD_Get_HrvTestData -> if (readhrv) { + dataListener.dataCallback(ResolveUtil.getHrvTestData(value)) + } else { + dataListener.dataCallback(ResolveUtil.DeleteHrv()) + } + + DeviceConst.ReadTempHisrory -> if (GetTemperature_historyDataWithMode) { + dataListener.dataCallback(ResolveUtil.setMethodSuccessful(BleConst.deleteGetTemperature_historyDataWithMode)) + } else { + dataListener.dataCallback(ResolveUtil.getTempData(value)) + } + + DeviceConst.Oxygen_data -> if (Obtain_The_data_of_manual_blood_oxygen_test) { + dataListener.dataCallback(ResolveUtil.setMethodSuccessful(BleConst.Delete_Obtain_The_data_of_manual_blood_oxygen_test)) + } else { + dataListener.dataCallback(ResolveUtil.GetAutomaticSpo2Monitoring(value)) + } + + DeviceConst.CMD_HeartPackageFromDevice -> dataListener.dataCallback(ResolveUtil.getActivityExerciseData(value)) + DeviceConst.CMD_Set_Name -> dataListener.dataCallback(ResolveUtil.setMethodSuccessful(BleConst.CMD_Set_Name)) + DeviceConst.CMD_Get_Name -> dataListener.dataCallback(ResolveUtil.getDeviceName(value)) + DeviceConst.CMD_Get_SPORTData -> if (GetActivityModeDataWithMode) { + dataListener.dataCallback(ResolveUtil.setMethodSuccessful(BleConst.Delete_ActivityModeData)) + } else { + dataListener.dataCallback(ResolveUtil.getExerciseData(value)) + } + + DeviceConst.MeasurementWithType -> if (StartDeviceMeasurementWithType) { + val vv: MutableMap = HashMap() + when (value[1]) { + 1.toByte() -> { + vv[DeviceKey.DataType] = BleConst.MeasurementHrvCallback + vv[DeviceKey.End] = true + val lm: MutableMap = HashMap() + lm[DeviceKey.Type] = ResolveUtil.getValue(value[1], 0).toString() + "" + lm[DeviceKey.HeartRate] = ResolveUtil.getValue(value[2], 0).toString() + "" + lm[DeviceKey.Blood_oxygen] = ResolveUtil.getValue(value[3], 0).toString() + "" + lm[DeviceKey.HRV] = ResolveUtil.getValue(value[4], 0).toString() + "" + lm[DeviceKey.Stress] = ResolveUtil.getValue(value[5], 0).toString() + "" + lm[DeviceKey.HighPressure] = ResolveUtil.getValue(value[6], 0).toString() + "" + lm[DeviceKey.LowPressure] = ResolveUtil.getValue(value[7], 0).toString() + "" + vv[DeviceKey.Data] = lm + dataListener.dataCallback(vv) + } + + 2.toByte() -> { + vv[DeviceKey.DataType] = BleConst.MeasurementHeartCallback + vv[DeviceKey.End] = true + val lmB: MutableMap = HashMap() + lmB[DeviceKey.Type] = ResolveUtil.getValue(value[1], 0).toString() + "" + lmB[DeviceKey.HeartRate] = ResolveUtil.getValue(value[2], 0).toString() + "" + lmB[DeviceKey.Blood_oxygen] = ResolveUtil.getValue(value[3], 0).toString() + "" + lmB[DeviceKey.HRV] = ResolveUtil.getValue(value[4], 0).toString() + "" + lmB[DeviceKey.Stress] = ResolveUtil.getValue(value[5], 0).toString() + "" + lmB[DeviceKey.HighPressure] = ResolveUtil.getValue(value[6], 0).toString() + "" + lmB[DeviceKey.LowPressure] = ResolveUtil.getValue(value[7], 0).toString() + "" + vv[DeviceKey.Data] = lmB + dataListener.dataCallback(vv) + } + + 3.toByte() -> { + vv[DeviceKey.DataType] = BleConst.MeasurementOxygenCallback + vv[DeviceKey.End] = true + val lmC: MutableMap = HashMap() + lmC[DeviceKey.Type] = ResolveUtil.getValue(value[1], 0).toString() + "" + lmC[DeviceKey.HeartRate] = ResolveUtil.getValue(value[2], 0).toString() + "" + lmC[DeviceKey.Blood_oxygen] = ResolveUtil.getValue(value[3], 0).toString() + "" + lmC[DeviceKey.HRV] = ResolveUtil.getValue(value[4], 0).toString() + "" + lmC[DeviceKey.Stress] = ResolveUtil.getValue(value[5], 0).toString() + "" + lmC[DeviceKey.HighPressure] = ResolveUtil.getValue(value[6], 0).toString() + "" + lmC[DeviceKey.LowPressure] = ResolveUtil.getValue(value[7], 0).toString() + "" + vv[DeviceKey.Data] = lmC + dataListener.dataCallback(vv) + } + } + } else { + val vv: MutableMap = HashMap() + when (value[1]) { + 1.toByte() -> { + vv[DeviceKey.DataType] = BleConst.StopMeasurementHrvCallback + vv[DeviceKey.End] = true + vv[DeviceKey.Data] = HashMap() + dataListener.dataCallback(vv) + } + + 2.toByte() -> { + vv[DeviceKey.DataType] = BleConst.StopMeasurementHeartCallback + vv[DeviceKey.End] = true + vv[DeviceKey.Data] = HashMap() + dataListener.dataCallback(vv) + } + + 3.toByte() -> { + vv[DeviceKey.DataType] = BleConst.StopMeasurementOxygenCallback + vv[DeviceKey.End] = true + vv[DeviceKey.Data] = HashMap() + dataListener.dataCallback(vv) + } + } + } + + DeviceConst.CMD_Get_Bloodsugar -> if (startBloodsugar) { //只有开始测量才返回状态 + val vv: MutableMap = HashMap() + vv[DeviceKey.DataType] = BleConst.Blood_glucose_status + vv[DeviceKey.End] = true + val lm: MutableMap = HashMap() + lm[DeviceKey.Type] = ResolveUtil.getValue(value[1], 0).toString() + "" + vv[DeviceKey.Data] = lm + dataListener.dataCallback(vv) + } + + DeviceConst.Bloodsugar_data -> { + val vv: MutableMap = HashMap() + vv[DeviceKey.DataType] = BleConst.Blood_glucose_data + vv[DeviceKey.End] = false + val lm: MutableMap = HashMap() + lm[DeviceKey.Time] = getFormatTimeString(System.currentTimeMillis(), "yyyy.MM.dd HH:mm:ss") + val simplePpg: MutableList = ArrayList() + if (value.size == 153) { //新血糖解析 + val valueer = ByteArray(value.size - 3) + System.arraycopy(value, 3, valueer, 0, valueer.size) + var i = 0 + while (i < valueer.size / 3) { + val valuedata = (ResolveUtil.getValue(valueer[3 * i], 2) + + ResolveUtil.getValue(valueer[3 * i + 1], 1) + + ResolveUtil.getValue(valueer[3 * i + 2], 0)) + simplePpg.add(valuedata) + i++ + } + lm[DeviceKey.PPG] = Arrays.toString(simplePpg.toTypedArray()) + } + vv[DeviceKey.Data] = lm + dataListener.dataCallback(vv) + } + + DeviceConst.CMD_Start_EXERCISE -> if (FindActivityMode) { + val mapEXERCISE: MutableMap = HashMap() + mapEXERCISE[DeviceKey.DataType] = BleConst.FindActivityMode + mapEXERCISE[DeviceKey.End] = true + val mapsx: MutableMap = HashMap() + mapsx[DeviceKey.Type] = ResolveUtil.getValue(value[1], 0).toString() + "" + mapsx[DeviceKey.Status] = ResolveUtil.getValue(value[2], 0).toString() + "" + mapEXERCISE[DeviceKey.Data] = mapsx + dataListener.dataCallback(mapEXERCISE) + } else { + val mapEXERCISE: MutableMap = HashMap() + mapEXERCISE[DeviceKey.DataType] = BleConst.EnterActivityMode + mapEXERCISE[DeviceKey.End] = true + val mapsx: MutableMap = HashMap() + mapsx[DeviceKey.enterActivityModeSuccess] = ResolveUtil.getValue(value[1], 0).toString() + "" + mapEXERCISE[DeviceKey.Data] = mapsx + dataListener.dataCallback(mapEXERCISE) + } + } + // return map; + } + + internal var Delete_GetDetailSleepData = false + fun GetDetailSleepDataWithMode(mode: Byte, dateOfLastData: String): ByteArray { + Delete_GetDetailSleepData = 0x99.toByte() == mode + val value = ByteArray(16) + value[0] = DeviceConst.CMD_Get_SleepData + value[1] = mode + insertDateValue(value, dateOfLastData) + crcValue(value) + return value + } + + /** + * 开始实时计步 + * + * @return + */ + fun RealTimeStep(enable: Boolean, tempEnable: Boolean): ByteArray { + val value = ByteArray(16) + value[0] = DeviceConst.CMD_Enable_Activity + value[1] = (if (enable) 1 else 0).toByte() + value[2] = (if (tempEnable) 1 else 0).toByte() + crcValue(value) + return value + } + + /** + * 设置个人信息 + * + * @param + * @return + */ + fun SetPersonalInfo(info: MyPersonalInfo): ByteArray { + val value = ByteArray(16) + val male = info.sex + val age = info.age + val height = info.height + val weight = info.weight + val stepLength = info.stepLength + value[0] = DeviceConst.CMD_Set_UseInfo + value[1] = male.toByte() + value[2] = age.toByte() + value[3] = height.toByte() + value[4] = weight.toByte() + value[5] = stepLength.toByte() + crcValue(value) + return value + } + + /** + * 获取个人信息 + * + * @return + */ + fun GetPersonalInfo(): ByteArray { + val value = ByteArray(16) + value[0] = DeviceConst.CMD_GET_USERINFO + crcValue(value) + return value + } + + /** + * 设置设备时间 + * + * @param + * @return + */ + fun SetDeviceTime(time: MyDeviceTime): ByteArray { + val value = ByteArray(16) + val timeZone = ResolveUtil.getCurrentTimeZone() + var zone = timeZone.substring(3) + var zoneValue: Byte = 0 + if (zone.contains("-")) { + zone = zone.replace("-", "") + zoneValue = java.lang.Byte.valueOf(zone) + } else { + zoneValue = (java.lang.Byte.valueOf(zone) + 0x80).toByte() + } + val year = time.year + val month = time.month + val day = time.day + val hour = time.hour + val min = time.minute + val second = time.second + value[0] = DeviceConst.CMD_SET_TIME + value[1] = ResolveUtil.getTimeValue(year) + value[2] = ResolveUtil.getTimeValue(month) + value[3] = ResolveUtil.getTimeValue(day) + value[4] = ResolveUtil.getTimeValue(hour) + value[5] = ResolveUtil.getTimeValue(min) + value[6] = ResolveUtil.getTimeValue(second) + value[8] = zoneValue + crcValue(value) + return value + } + + /** + * 获取设备时间 + * + * @return + */ + fun GetDeviceTime(): ByteArray { + val value = ByteArray(16) + value[0] = DeviceConst.CMD_GET_TIME + crcValue(value) + return value + } + + /** + * 99: 删除步数详细数据 , + * 0:读最近的步数详细数据。 + * 1:读指定位置的步数详细数据。 + * 2:继续上次读的位置下一段数据 + * + * @param + * @return * dateOfLastData "yyyy-MM-dd HH:mm:ss or yyyy.MM.dd HH:mm:ss" + */ + private var GetDetailActivityDataWithMode = false + fun GetDetailActivityDataWithMode(mode: Byte, dateOfLastData: String): ByteArray { + GetDetailActivityDataWithMode = 0x99.toByte() == mode + val value = ByteArray(16) + value[0] = DeviceConst.CMD_Get_DetailData + value[1] = mode + insertDateValue(value, dateOfLastData) + crcValue(value) + return value + } + + /** + * 99: 删除温度数据 , + * 0:读最近的温度详细数据。 + * 1:读指定位置的步数详细数据。 + * 2:继续上次读的位置下一段数据 + * + * @param + * @return + */ + internal var GetTemperature_historyDataWithMode = false + fun GetTemperature_historyData(mode: Byte, dateOfLastData: String): ByteArray { + GetTemperature_historyDataWithMode = 0x99.toByte() == mode + val value = ByteArray(16) + value[0] = DeviceConst.ReadTempHisrory + value[1] = mode + insertDateValue(value, dateOfLastData) + crcValue(value) + return value + } + + var StartDeviceMeasurementWithType = false + fun SetDeviceMeasurementWithType(dataType: AutoTestMode?, second: Long, open: Boolean): ByteArray { + StartDeviceMeasurementWithType = open + val value = ByteArray(16) + value[0] = DeviceConst.MeasurementWithType + when (dataType) { + AutoTestMode.AutoHeartRate -> value[1] = 0x02.toByte() + AutoTestMode.AutoSpo2 -> value[1] = 0x03.toByte() + else -> {} + } + value[2] = if (open) 0x01.toByte() else 0x00.toByte() + value[3] = (second and 0xffL).toByte() + value[4] = (second shr 8 and 0xffL).toByte() + crcValue(value) + return value + } + + fun SetAutomaticHRMonitoring(autoHeart: MyAutomaticHRMonitoring, type: AutoMode?): ByteArray { + val value = ByteArray(16) + val time = autoHeart.time + value[0] = DeviceConst.CMD_Set_Auto + value[1] = autoHeart.open.toByte() + value[2] = ResolveUtil.getTimeValue(autoHeart.startHour) + value[3] = ResolveUtil.getTimeValue(autoHeart.startMinute) + value[4] = ResolveUtil.getTimeValue(autoHeart.endHour) + value[5] = ResolveUtil.getTimeValue(autoHeart.endMinute) + value[6] = autoHeart.week.toByte() + value[7] = (time and 0xff).toByte() + value[8] = (time shr 8 and 0xff).toByte() + if (null == type) { + value[9] = 0x01.toByte() + } else { + when (type) { + AutoMode.AutoHeartRate -> value[9] = 0x01.toByte() + AutoMode.AutoSpo2 -> value[9] = 0x02.toByte() + AutoMode.AutoTemp -> value[9] = 0x03.toByte() + AutoMode.AutoHrv -> value[9] = 0x04.toByte() + } + } + crcValue(value) + return value + } + + fun GetAutomatic(type: AutoMode?): ByteArray { + val value = ByteArray(16) + value[0] = DeviceConst.CMD_Get_Auto + if (null == type) { + value[1] = 0x01.toByte() + } else { + when (type) { + AutoMode.AutoHeartRate -> value[1] = 0x01.toByte() + AutoMode.AutoSpo2 -> value[1] = 0x02.toByte() + AutoMode.AutoTemp -> value[1] = 0x03.toByte() + AutoMode.AutoHrv -> value[1] = 0x04.toByte() + } + } + crcValue(value) + return value + } + + /** + * 获取某天总数据 + * 0 + * + * @param mode 0:表⽰是从最新的位置开始读取(最多50组数据) 2:表⽰接着读取(当数据总数⼤于50的时候) 0x99:表⽰删除所有运 + * 动数据 + * @return + */ + internal var GetTotalActivityDataWithMode = false + fun GetTotalActivityDataWithMode(mode: Byte, dateOfLastData: String): ByteArray { + GetTotalActivityDataWithMode = 0x99.toByte() == mode + val value = ByteArray(16) + value[0] = DeviceConst.CMD_Get_TotalData + value[1] = mode + insertDateValueNoH(value, dateOfLastData) + crcValue(value) + return value + } + + /** + * 获取设备版本号 + * + * @return + */ + fun GetDeviceVersion(): ByteArray { + val value = ByteArray(16) + value[0] = DeviceConst.CMD_Get_Version + crcValue(value) + return value + } + + /** + * 恢复出厂设置 + * + * @return + */ + fun Reset(): ByteArray { + val value = ByteArray(16) + value[0] = DeviceConst.CMD_Reset + crcValue(value) + return value + } + + /** + * 获取设备mac地址 + * + * @return + */ + fun GetDeviceMacAddress(): ByteArray { + val value = ByteArray(16) + value[0] = DeviceConst.CMD_Get_Address + crcValue(value) + return value + } + + /** + * 获取设备电量 + * + * @return + */ + fun GetDeviceBatteryLevel(): ByteArray { + val value = ByteArray(16) + value[0] = DeviceConst.CMD_Get_BatteryLevel + crcValue(value) + return value + } + + /** + * 重启设备 + * + * @return + */ + fun MCUReset(): ByteArray { + val value = ByteArray(16) + value[0] = DeviceConst.CMD_Mcu_Reset + crcValue(value) + return value + } + + private var readhrv = false + fun GetHRVDataWithMode(mode: Byte, dateOfLastData: String): ByteArray { + readhrv = 0x99.toByte() != mode + val value = ByteArray(16) + value[0] = DeviceConst.CMD_Get_HrvTestData + value[1] = mode + insertDateValue(value, dateOfLastData) + crcValue(value) + return value + } + + internal var GetStaticHRWithMode = false + fun GetStaticHRWithMode(mode: Byte, dateOfLastData: String): ByteArray { + GetStaticHRWithMode = 0x99.toByte() == mode + val value = ByteArray(16) + value[0] = DeviceConst.CMD_Get_OnceHeartData + value[1] = mode + insertDateValue(value, dateOfLastData) + crcValue(value) + return value + } + + internal var GetDynamicHRWithMode = false + fun GetDynamicHRWithMode(Number: Byte, dateOfLastData: String): ByteArray { + GetDynamicHRWithMode = 0x99.toByte() == Number + val value = ByteArray(16) + value[0] = DeviceConst.CMD_Get_HeartData + value[1] = Number + insertDateValue(value, dateOfLastData) + crcValue(value) + return value + } + + fun SetDeviceID(deviceId: String): ByteArray { + val value = ByteArray(16) + value[0] = DeviceConst.CMD_Set_DeviceID + for (i in 0..5) { + value[i + 1] = deviceId[i].code.toByte() + } + crcValue(value) + return value + } + + fun intTobyte(num: Int): ByteArray { + return byteArrayOf((num shr 8 and 0xff).toByte(), (num and 0xff).toByte()) + } + + @JvmStatic + fun byteArrayToInt(arr: ByteArray): Int { + val targets = (arr[1].toInt() and 0xff or (arr[0].toInt() shl 8 and 0xff00)).toShort() + return targets.toInt() + } + + fun getInfoValue(info: String, maxLength: Int): ByteArray? { + var nameBytes: ByteArray? = null + try { + nameBytes = info.toByteArray(charset("UTF-8")) + if (nameBytes.size >= maxLength) { //两条命令总共32个字节,内容只占24个字节(32-2*(1cmd+1消息类型+1长度+1校验)) + val real = ByteArray(maxLength) + val chars = info.toCharArray() + var length = 0 + for (i in chars.indices) { + val s = chars[i].toString() + val nameB = s.toByteArray(charset("UTF-8")) + if (length + nameB.size == maxLength) { + System.arraycopy(nameBytes, 0, real, 0, real.size) + return real + } else if (length + nameB.size > maxLength) { //大于24会导致有个字节发不到下位机导致乱码 + System.arraycopy(nameBytes, 0, real, 0, length) + return real + } + length += nameB.size + } + } + } catch (e: UnsupportedEncodingException) { + // TODO Auto-generated catch block + e.printStackTrace() + } + return nameBytes + } + + fun crcValue(value: ByteArray) { + var crc: Byte = 0 + for (i in 0 until value.size - 1) { + crc = (crc + value[i]).toByte() + } + value[value.size - 1] = (crc and 0xff.toByte()) + } + + + fun insertDateValue(value: ByteArray, time: String) { + if (!TextUtils.isEmpty(time) && time.length > 8) { + val timeArray = time.split(" ".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray() + val INDEX: String + INDEX = if (time.contains("-")) { + "-" + } else { + "\\." + } + val year = timeArray[0].split(INDEX.toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray()[0].toInt() + val month = timeArray[0].split(INDEX.toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray()[1].toInt() + val day = timeArray[0].split(INDEX.toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray()[2].toInt() + val hour = timeArray[1].split(":".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray()[0].toInt() + val min = timeArray[1].split(":".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray()[1].toInt() + val second = timeArray[1].split(":".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray()[2].toInt() + value[4] = ResolveUtil.getTimeValue(year) + value[5] = ResolveUtil.getTimeValue(month) + value[6] = ResolveUtil.getTimeValue(day) + value[7] = ResolveUtil.getTimeValue(hour) + value[8] = ResolveUtil.getTimeValue(min) + value[9] = ResolveUtil.getTimeValue(second) + } + } + + fun insertDateValueNoH(value: ByteArray, time: String) { + if (!TextUtils.isEmpty(time) && time.contains("-")) { + val timeArray = time.split(" ".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray() + val INDEX: String + INDEX = if (time.contains("-")) { + "-" + } else { + "\\." + } + val year = timeArray[0].split(INDEX.toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray()[0].toInt() + val month = timeArray[0].split(INDEX.toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray()[1].toInt() + val day = timeArray[0].split(INDEX.toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray()[2].toInt() + value[4] = ResolveUtil.getTimeValue(year) + value[5] = ResolveUtil.getTimeValue(month) + value[6] = ResolveUtil.getTimeValue(day) + } + } + + /** + * 转十六进制字符串 + * + * @param data + * @return + */ + fun byte2Hex(data: ByteArray?): String { + if (data != null && data.size > 0) { + val sb = StringBuilder(data.size) + for (tmp in data) { + sb.append(String.format("%02X ", tmp)) + } + return sb.toString() + } + return "no data" + } + + /** + * OObtain automated test oximetry data + * 获得自动测试血氧数据 + */ + internal var Obtain_The_data_of_manual_blood_oxygen_test = false + fun Oxygen_data(Number: Byte): ByteArray { + Obtain_The_data_of_manual_blood_oxygen_test = 0x99.toByte() == Number + val value = ByteArray(16) + value[0] = DeviceConst.Oxygen_data + value[1] = Number + crcValue(value) + return value + } + + fun EnterActivityMode(time: Int, activityMode: Int, WorkMode: Int): ByteArray { + FindActivityMode = false + val value = ByteArray(16) + value[0] = DeviceConst.CMD_Start_EXERCISE + value[1] = WorkMode.toByte() + value[2] = activityMode.toByte() + value[4] = time.toByte() + crcValue(value) + return value + } + + private var FindActivityMode = false + fun FindActivityMode(): ByteArray { + FindActivityMode = true + val value = ByteArray(16) + value[0] = DeviceConst.CMD_Start_EXERCISE + value[1] = 0x05.toByte() + crcValue(value) + return value + } + + /** + * @param status 级别 0,1,2 + * @param time 分钟 + * @param WorkMode START=1;PAUSE=2;CONTUINE=3;FINISH=4; + * @return + */ + fun setExerciseModeByBreath(status: Int, time: Int, WorkMode: Int): ByteArray { + FindActivityMode = false + val value = ByteArray(16) + value[0] = DeviceConst.CMD_Start_EXERCISE + value[1] = WorkMode.toByte() + value[2] = 0x06.toByte() + value[3] = status.toByte() + value[4] = time.toByte() + crcValue(value) + return value + } + + fun sendHeartPackage(distance: Float, space: Int, rssi: Int): ByteArray { + val value = ByteArray(16) + val distanceValue = getByteArray(distance) + val min = space / 60 + val second = space % 60 + value[0] = DeviceConst.CMD_heart_package + System.arraycopy(distanceValue, 0, value, 1, distanceValue.size) + value[5] = min.toByte() + value[6] = second.toByte() + value[7] = rssi.toByte() + crcValue(value) + return value + } + + /** + * 设置设备名字 + * + * @param + * @return + */ + fun SetDeviceName(strDeviceName: String): ByteArray { + val value = ByteArray(16) + value[0] = DeviceConst.CMD_Set_Name + val length = if (strDeviceName.length > 14) 14 else strDeviceName.length + for (i in 0 until length) { + value[i + 1] = strDeviceName[i].code.toByte() + } + crcValue(value) + return value + } + + /** + * 获取设备名字 + * + * @return + */ + fun GetDeviceName(): ByteArray { + val value = ByteArray(16) + value[0] = DeviceConst.CMD_Get_Name + crcValue(value) + return value + } + + /** + * 获取多模式运动数据 + * + * @param mode 0:表⽰是从最新的位置开始读取(最多50组数据) 2:表⽰接着读取(当数据总数⼤于50的时候) 0x99:表⽰删除所有 + * GPS数据 + * @return + */ + internal var GetActivityModeDataWithMode = false + fun GetActivityModeDataWithMode(mode: Byte): ByteArray { + GetActivityModeDataWithMode = 0x99.toByte() == mode + val value = ByteArray(16) + value[0] = DeviceConst.CMD_Get_SPORTData + value[1] = mode + crcValue(value) + return value + } + + /** + * 开始血氧测量 + * Start blood oxygen measurement + */ + var startBloodsugar = false + fun startBloodsugar(): ByteArray { + startBloodsugar = true + val value = ByteArray(16) + value[0] = DeviceConst.CMD_Get_Bloodsugar + value[1] = 0x01.toByte() + crcValue(value) + return value + } + + /** + * 停止血氧测量 + * Stop blood oxygen measurement + */ + fun BloodsugarStop(): ByteArray { + startBloodsugar = false + val value = ByteArray(16) + value[0] = DeviceConst.CMD_Get_Bloodsugar + value[1] = 0x05.toByte() + crcValue(value) + return value + } + + /** + * 血氧测量停止信号采集 + * Blood oxygen measurement stop signal acquisition + */ + fun BloodsugarStopSiss(): ByteArray { + startBloodsugar = false + val value = ByteArray(16) + value[0] = DeviceConst.CMD_Get_Bloodsugar + value[1] = 0x03.toByte() + crcValue(value) + return value + } + + /** + * 血氧测量进度更新 + * Blood oxygen measurement progress update + */ + fun BloodsugarProgress(Progress: Int): ByteArray { + startBloodsugar = false + val value = ByteArray(16) + value[0] = DeviceConst.CMD_Get_Bloodsugar + value[1] = 0x04.toByte() + value[2] = Progress.toByte() //0-100 + crcValue(value) + return value + } + + /** + * 血氧测量结果 + * Send blood glucose results to the device + * status 1低 2中 3高 0测试失败 + * Status 1 low 2 3 high 0 test failed + */ + fun SendBloodGlucoseResultsToTheDevice(status: Int): ByteArray { + startBloodsugar = false + val value = ByteArray(16) + value[0] = DeviceConst.CMD_Get_Bloodsugar + value[1] = 0x02.toByte() + value[2] = status.toByte() + crcValue(value) + return value + } + + /** + * 获取指定格式的日期字符串 + */ + @Synchronized + fun getFormatTimeString(time: Long, formatString: String?): String { + val format = SimpleDateFormat(formatString) + var data = "" + try { + data = format.format(Date(time)) + } catch (E: Exception) { + E.printStackTrace() + } + return data + } +} \ No newline at end of file diff --git a/android/blesdk_2301/src/main/java/com/jstyle/blesdk2301/Util/PDFCreate.java b/android/blesdk_2301/src/main/java/com/jstyle/blesdk2301/Util/PDFCreate.java deleted file mode 100644 index 72307c52..00000000 --- a/android/blesdk_2301/src/main/java/com/jstyle/blesdk2301/Util/PDFCreate.java +++ /dev/null @@ -1,244 +0,0 @@ -package com.jstyle.blesdk2301.Util; - -import android.annotation.SuppressLint; -import android.content.Context; -import android.graphics.Canvas; -import android.graphics.Color; -import android.graphics.Paint; -import android.graphics.Path; -import android.graphics.Rect; -import android.graphics.pdf.PdfDocument; -import android.text.TextUtils; - -import com.jstyle.blesdk2301.model.UserInfo; - -import java.io.File; -import java.io.FileNotFoundException; -import java.io.FileOutputStream; -import java.io.IOException; -import java.util.List; - -public class PDFCreate { - private static final String TAG = "PDFCreate"; - final static int maxXSize = 5120; - static float length = 20; - static float totalWidth = 1070; - static int startX = 35; - static float endX = startX + 1000; - static float startY ; - private static float endY; - private static float height ; - private static float width ; - private static int strokeWidthTime; - private static int strokeWidthLine; - private static float totalHeight; - - public static void createPdf(String path, Context context, List data, UserInfo userInfo) { - int size = data.size(); - float col = size % maxXSize == 0 ? size / maxXSize : size / maxXSize + 1;//一次画5120个点,分多少次画 - length=dip2px(context,10); - height=length; - width=length; - startX=dip2px(context,20); - endX=startX+50*length; - totalWidth=endX+startX; - totalHeight = col * height * 5 + dip2px(context,130);//一次需要5个高度 - PdfDocument pdfDocument = new PdfDocument(); - - PdfDocument.PageInfo pageInfo = new PdfDocument.PageInfo.Builder((int) totalWidth, (int) totalHeight, 1) - // .setContentRect(new Rect(0,0,(int)totalWidth,(int)totalHeight)) - .create(); - - PdfDocument.Page page = pdfDocument.startPage(pageInfo); - Canvas canvas = page.getCanvas(); - Paint paint = new Paint(); - strokeWidthTime = dip2px(context, 1.5f); - strokeWidthLine = dip2px(context, 0.5f); - drawReportInfo(context, canvas, paint,userInfo); - Path pathCanvas = new Path(); - endY = startY + col * height * 5; - paint.setTextSize(dip2px(context, 15)); - drawAxes(pathCanvas, canvas, paint, col); - drawTimeLine(pathCanvas, canvas, paint); - drawDataLine(context,pathCanvas, canvas, paint, col, data); - pdfDocument.finishPage(page); - File file = new File(path); - FileOutputStream outputStream = null; - try { - outputStream = new FileOutputStream(file); - } catch (FileNotFoundException e) { - e.printStackTrace(); - } - try { - pdfDocument.writeTo(outputStream); - } catch (IOException e) { - e.printStackTrace(); - } - - } - - /**用户信息 - * @param context - * @param canvas - * @param paint - * @param - */ - private static void drawReportInfo(Context context, Canvas canvas, Paint paint,UserInfo userInfo) { - paint.setTextSize(dip2px(context,15)); - paint.setColor(Color.BLACK); - paint.setStyle(Paint.Style.FILL); - if(null!=userInfo){ - if(!TextUtils.isEmpty(userInfo.getEcgTitle())){ - String title=userInfo.getEcgTitle(); - Rect rect = new Rect(); - paint.getTextBounds(title, 0, title.length(), rect); - int heightTitle = rect.height(); - float startTextY=heightTitle+dip2px(context,8); - float marginTop=dip2px(context,4); - float marginRight=dip2px(context,8); - //标题 - canvas.drawText(title, totalWidth / 2 - 150, startTextY, paint); - //提醒 - paint.setTextSize(dip2px(context, 12)); - int widthTips = rect.width(); - int heightTips = rect.height(); - if(!TextUtils.isEmpty(userInfo.getEcgReportTips())) { - - String tips = userInfo.getEcgReportTips(); - float tipsTextY = startTextY + heightTitle + marginTop; - paint.getTextBounds(tips, 0, tips.length(), rect); - canvas.drawText(tips, totalWidth - widthTips - marginRight, tipsTextY, paint); - } - - float tipsTextY=startTextY+heightTitle+marginTop; - - - String name = userInfo.getName(); - String genderString = userInfo.getGender(); - String age = userInfo.getAge(); - - - String userWeight = userInfo.getWeight(); - String userHeight = userInfo.getHeight(); - //个人信息 - float infoTextY=tipsTextY+heightTips+marginTop; - @SuppressLint("StringFormatMatches") - String info=name+" "+genderString+" "+age+" "+ userHeight+" "+userWeight; - paint.getTextBounds(info, 0, info.length(), rect); - int heightInfo = rect.height(); - int widthInfo = rect.width(); - canvas.drawText(info, totalWidth / 2 - (widthInfo >> 1), infoTextY, paint); - //时间 - float dateTextY=infoTextY+heightInfo+marginTop; - String dateString=userInfo.getDate(); - paint.getTextBounds(dateString, 0, dateString.length(), rect); - int widthDate=rect.width(); - int heightDate=rect.height(); - canvas.drawText(dateString, totalWidth - widthDate-marginRight, dateTextY, paint); - startY=dateTextY+heightDate+marginTop; - } - - - - - } - - } - - /** - * 画网格 - * - * @param pathCanvas - * @param canvas - * @param paint - * @param col - */ - private static void drawAxes(Path pathCanvas, Canvas canvas, Paint paint, float col) { - //画网格竖线 - int colorLine = Color.rgb(243, 119, 99); - paint.setColor(colorLine); - paint.setStyle(Paint.Style.STROKE); - paint.setStrokeWidth(strokeWidthLine); - paint.setAlpha(200); - for (int i = 0; i <51; i++) { - pathCanvas.moveTo(i * width + startX, startY); - pathCanvas.lineTo(i * width + startX, endY); - } - //画网格横线 - for (int i = 0; i <= col * 5; i++) { - pathCanvas.moveTo(startX - (strokeWidthTime >> 1), i * height + startY); - pathCanvas.lineTo(endX + (strokeWidthTime >> 1), i * height + startY); - } - canvas.drawPath(pathCanvas, paint); - pathCanvas.reset(); - } - - /** - * 加粗时间线 - * - * @param pathCanvas - * @param canvas - * @param paint - */ - private static void drawTimeLine(Path pathCanvas, Canvas canvas, Paint paint) { - paint.setColor(Color.BLACK); - paint.setStrokeWidth(strokeWidthTime); - paint.setStyle(Paint.Style.FILL); - Rect rect=new Rect(); - for (int i = 0; i < 11; i++) { - pathCanvas.moveTo(i * 5 * width + startX, startY); - pathCanvas.lineTo(i * 5 * width + startX, endY + 20); - String time=i+"s"; - paint.getTextBounds(time, 0, time.length(), rect); - int widthTime=rect.width(); - canvas.drawText(time, i * 5 * width + startX - (widthTime >> 1), endY + 50, paint); - } - int colorS = Color.rgb(255, 119, 99); - paint.setColor(colorS); - paint.setAlpha(255); - paint.setStyle(Paint.Style.STROKE); - canvas.drawPath(pathCanvas, paint); - pathCanvas.reset(); - } - - /** - * 画数据 - * - * @param pathCanvas - * @param canvas - * @param paint - * @param col - * @param data - */ - private static void drawDataLine(Context context,Path pathCanvas, Canvas canvas, Paint paint, float col, List data) { - int size = data.size(); - paint.setStrokeWidth(strokeWidthLine); - paint.setColor(Color.BLACK); - out: - for (int i = 0; i < col; i++) { - int startPoint = i * maxXSize; - in: for (int j = 0; j = size) break out; - Integer y = data.get(startPoint + j); - if (j == 0) pathCanvas.moveTo(startX, i * height * 5 + getCanvasY(y,context)); - pathCanvas.lineTo(startX + x * (endX - startX) / maxXSize, i * height * 5 + getCanvasY(y,context)); - } - } - - canvas.drawPath(pathCanvas, paint); - } - - private static float getCanvasY(double value,Context context) { - double height = 5 * 10 / 16000f; - return dip2px (context,(float) (height * (8000 - value))) + startY; - } - - /** - * 根据手机的分辨率从 dp 的单位 转成为 px(像素) - */ - public static int dip2px(Context context, float dpValue) { - final float scale = context.getResources().getDisplayMetrics().density; - return (int) (dpValue * scale + 0.5f); - } -} diff --git a/android/blesdk_2301/src/main/java/com/jstyle/blesdk2301/Util/PDFCreate.kt b/android/blesdk_2301/src/main/java/com/jstyle/blesdk2301/Util/PDFCreate.kt new file mode 100644 index 00000000..bd9e147f --- /dev/null +++ b/android/blesdk_2301/src/main/java/com/jstyle/blesdk2301/Util/PDFCreate.kt @@ -0,0 +1,230 @@ +package com.jstyle.blesdk2301.Util + +import android.annotation.SuppressLint +import android.content.Context +import android.graphics.Canvas +import android.graphics.Color +import android.graphics.Paint +import android.graphics.Path +import android.graphics.Rect +import android.graphics.pdf.PdfDocument +import android.os.Build +import android.text.TextUtils +import com.jstyle.blesdk2301.model.UserInfo +import java.io.File +import java.io.FileNotFoundException +import java.io.FileOutputStream +import java.io.IOException + +object PDFCreate { + private const val TAG = "PDFCreate" + const val maxXSize = 5120 + var length = 20f + var totalWidth = 1070f + var startX = 35 + var endX = (startX + 1000).toFloat() + var startY = 0f + private var endY = 0f + private var height = 0f + private var width = 0f + private var strokeWidthTime = 0 + private var strokeWidthLine = 0 + private var totalHeight = 0f + fun createPdf(path: String?, context: Context, data: List, userInfo: UserInfo?) { + val size = data.size + val col = (if (size % maxXSize == 0) size / maxXSize else size / maxXSize + 1).toFloat() //一次画5120个点,分多少次画 + length = dip2px(context, 10f).toFloat() + height = length + width = length + startX = dip2px(context, 20f) + endX = startX + 50 * length + totalWidth = endX + startX + totalHeight = col * height * 5 + dip2px(context, 130f) //一次需要5个高度 + val pdfDocument = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) { + PdfDocument() + } else { + TODO("VERSION.SDK_INT < KITKAT") + } + val pageInfo = PdfDocument.PageInfo.Builder(totalWidth.toInt(), totalHeight.toInt(), 1) // .setContentRect(new Rect(0,0,(int)totalWidth,(int)totalHeight)) + .create() + val page = pdfDocument.startPage(pageInfo) + val canvas = page.canvas + val paint = Paint() + strokeWidthTime = dip2px(context, 1.5f) + strokeWidthLine = dip2px(context, 0.5f) + drawReportInfo(context, canvas, paint, userInfo) + val pathCanvas = Path() + endY = startY + col * height * 5 + paint.textSize = dip2px(context, 15f).toFloat() + drawAxes(pathCanvas, canvas, paint, col) + drawTimeLine(pathCanvas, canvas, paint) + drawDataLine(context, pathCanvas, canvas, paint, col, data) + pdfDocument.finishPage(page) + val file = File(path) + var outputStream: FileOutputStream? = null + try { + outputStream = FileOutputStream(file) + } catch (e: FileNotFoundException) { + e.printStackTrace() + } + try { + pdfDocument.writeTo(outputStream) + } catch (e: IOException) { + e.printStackTrace() + } + } + + /**用户信息 + * @param context + * @param canvas + * @param paint + * @param + */ + private fun drawReportInfo(context: Context, canvas: Canvas, paint: Paint, userInfo: UserInfo?) { + paint.textSize = dip2px(context, 15f).toFloat() + paint.color = Color.BLACK + paint.style = Paint.Style.FILL + if (null != userInfo) { + if (!TextUtils.isEmpty(userInfo.ecgTitle)) { + val title = userInfo.ecgTitle + val rect = Rect() + paint.getTextBounds(title, 0, title.length, rect) + val heightTitle = rect.height() + val startTextY = (heightTitle + dip2px(context, 8f)).toFloat() + val marginTop = dip2px(context, 4f).toFloat() + val marginRight = dip2px(context, 8f).toFloat() + //标题 + canvas.drawText(title, totalWidth / 2 - 150, startTextY, paint) + //提醒 + paint.textSize = dip2px(context, 12f).toFloat() + val widthTips = rect.width() + val heightTips = rect.height() + if (!TextUtils.isEmpty(userInfo.ecgReportTips)) { + val tips = userInfo.ecgReportTips + val tipsTextY = startTextY + heightTitle + marginTop + paint.getTextBounds(tips, 0, tips.length, rect) + canvas.drawText(tips, totalWidth - widthTips - marginRight, tipsTextY, paint) + } + val tipsTextY = startTextY + heightTitle + marginTop + val name = userInfo.name + val genderString = userInfo.gender + val age = userInfo.age + val userWeight = userInfo.weight + val userHeight = userInfo.height + //个人信息 + val infoTextY = tipsTextY + heightTips + marginTop + @SuppressLint("StringFormatMatches") val info = "$name $genderString $age $userHeight $userWeight" + paint.getTextBounds(info, 0, info.length, rect) + val heightInfo = rect.height() + val widthInfo = rect.width() + canvas.drawText(info, totalWidth / 2 - (widthInfo shr 1), infoTextY, paint) + //时间 + val dateTextY = infoTextY + heightInfo + marginTop + val dateString = userInfo.date + paint.getTextBounds(dateString, 0, dateString.length, rect) + val widthDate = rect.width() + val heightDate = rect.height() + canvas.drawText(dateString, totalWidth - widthDate - marginRight, dateTextY, paint) + startY = dateTextY + heightDate + marginTop + } + } + } + + /** + * 画网格 + * + * @param pathCanvas + * @param canvas + * @param paint + * @param col + */ + private fun drawAxes(pathCanvas: Path, canvas: Canvas, paint: Paint, col: Float) { + //画网格竖线 + val colorLine = Color.rgb(243, 119, 99) + paint.color = colorLine + paint.style = Paint.Style.STROKE + paint.strokeWidth = strokeWidthLine.toFloat() + paint.alpha = 200 + for (i in 0..50) { + pathCanvas.moveTo(i * width + startX, startY) + pathCanvas.lineTo(i * width + startX, endY) + } + //画网格横线 + var i = 0 + while (i <= col * 5) { + pathCanvas.moveTo((startX - (strokeWidthTime shr 1)).toFloat(), i * height + startY) + pathCanvas.lineTo(endX + (strokeWidthTime shr 1), i * height + startY) + i++ + } + canvas.drawPath(pathCanvas, paint) + pathCanvas.reset() + } + + /** + * 加粗时间线 + * + * @param pathCanvas + * @param canvas + * @param paint + */ + private fun drawTimeLine(pathCanvas: Path, canvas: Canvas, paint: Paint) { + paint.color = Color.BLACK + paint.strokeWidth = strokeWidthTime.toFloat() + paint.style = Paint.Style.FILL + val rect = Rect() + for (i in 0..10) { + pathCanvas.moveTo(i * 5 * width + startX, startY) + pathCanvas.lineTo(i * 5 * width + startX, endY + 20) + val time = i.toString() + "s" + paint.getTextBounds(time, 0, time.length, rect) + val widthTime = rect.width() + canvas.drawText(time, i * 5 * width + startX - (widthTime shr 1), endY + 50, paint) + } + val colorS = Color.rgb(255, 119, 99) + paint.color = colorS + paint.alpha = 255 + paint.style = Paint.Style.STROKE + canvas.drawPath(pathCanvas, paint) + pathCanvas.reset() + } + + /** + * 画数据 + * + * @param pathCanvas + * @param canvas + * @param paint + * @param col + * @param data + */ + private fun drawDataLine(context: Context, pathCanvas: Path, canvas: Canvas, paint: Paint, col: Float, data: List) { + val size = data.size + paint.strokeWidth = strokeWidthLine.toFloat() + paint.color = Color.BLACK + var i = 0 + out@ while (i < col) { + val startPoint = i * maxXSize + `in`@ for (j in 0 until maxXSize) { + if (startPoint + j >= size) break@out + val y = data[startPoint + j] + if (j == 0) pathCanvas.moveTo(startX.toFloat(), i * height * 5 + getCanvasY(y.toDouble(), context)) + pathCanvas.lineTo(startX + j * (endX - startX) / maxXSize, i * height * 5 + getCanvasY(y.toDouble(), context)) + } + i++ + } + canvas.drawPath(pathCanvas, paint) + } + + private fun getCanvasY(value: Double, context: Context): Float { + val height = (5 * 10 / 16000f).toDouble() + return dip2px(context, (height * (8000 - value)).toFloat()) + startY + } + + /** + * 根据手机的分辨率从 dp 的单位 转成为 px(像素) + */ + fun dip2px(context: Context, dpValue: Float): Int { + val scale = context.resources.displayMetrics.density + return (dpValue * scale + 0.5f).toInt() + } +} \ No newline at end of file diff --git a/android/blesdk_2301/src/main/java/com/jstyle/blesdk2301/callback/BleConnectionListener.java b/android/blesdk_2301/src/main/java/com/jstyle/blesdk2301/callback/BleConnectionListener.java deleted file mode 100644 index ee6db91d..00000000 --- a/android/blesdk_2301/src/main/java/com/jstyle/blesdk2301/callback/BleConnectionListener.java +++ /dev/null @@ -1,10 +0,0 @@ -package com.jstyle.blesdk2301.callback; - -public interface BleConnectionListener { - void BleStatus(int status,int newState);//蓝牙4.0连接状态 Bluetooth 4.0 connection status - void ConnectionSucceeded();//连接设备成功 Successfully connected the device - void Connecting();//设备连接中 Device is connected - void ConnectionFailed();//设备连接失败 Device connection failed - void OnReconnect();//重新连接中 Reconnecting - void BluetoothSwitchIsTurnedOff();//蓝牙开关被关闭 Bluetooth switch is turned off -} diff --git a/android/blesdk_2301/src/main/java/com/jstyle/blesdk2301/callback/BleConnectionListener.kt b/android/blesdk_2301/src/main/java/com/jstyle/blesdk2301/callback/BleConnectionListener.kt new file mode 100644 index 00000000..3038490e --- /dev/null +++ b/android/blesdk_2301/src/main/java/com/jstyle/blesdk2301/callback/BleConnectionListener.kt @@ -0,0 +1,10 @@ +package com.jstyle.blesdk2301.callback + +interface BleConnectionListener { + fun BleStatus(status: Int, newState: Int) //蓝牙4.0连接状态 Bluetooth 4.0 connection status + fun ConnectionSucceeded() //连接设备成功 Successfully connected the device + fun Connecting() //设备连接中 Device is connected + fun ConnectionFailed() //设备连接失败 Device connection failed + fun OnReconnect() //重新连接中 Reconnecting + fun BluetoothSwitchIsTurnedOff() //蓝牙开关被关闭 Bluetooth switch is turned off +} \ No newline at end of file diff --git a/android/blesdk_2301/src/main/java/com/jstyle/blesdk2301/callback/DataListener2301.java b/android/blesdk_2301/src/main/java/com/jstyle/blesdk2301/callback/DataListener2301.java deleted file mode 100644 index bb8a8920..00000000 --- a/android/blesdk_2301/src/main/java/com/jstyle/blesdk2301/callback/DataListener2301.java +++ /dev/null @@ -1,13 +0,0 @@ -package com.jstyle.blesdk2301.callback; - -import java.util.Map; - -/** - * Created by Administrator on 2018/4/10. - */ - -public interface DataListener2301 { - void dataCallback(Map maps); - void dataCallback(byte[] value); - -} diff --git a/android/blesdk_2301/src/main/java/com/jstyle/blesdk2301/callback/DataListener2301.kt b/android/blesdk_2301/src/main/java/com/jstyle/blesdk2301/callback/DataListener2301.kt new file mode 100644 index 00000000..6e410b23 --- /dev/null +++ b/android/blesdk_2301/src/main/java/com/jstyle/blesdk2301/callback/DataListener2301.kt @@ -0,0 +1,9 @@ +package com.jstyle.blesdk2301.callback + +/** + * Created by Administrator on 2018/4/10. + */ +interface DataListener2301 { + fun dataCallback(maps: Map?) + fun dataCallback(value: ByteArray?) +} \ No newline at end of file diff --git a/android/blesdk_2301/src/main/java/com/jstyle/blesdk2301/callback/OnScanResults.java b/android/blesdk_2301/src/main/java/com/jstyle/blesdk2301/callback/OnScanResults.java deleted file mode 100644 index 98a00c64..00000000 --- a/android/blesdk_2301/src/main/java/com/jstyle/blesdk2301/callback/OnScanResults.java +++ /dev/null @@ -1,9 +0,0 @@ -package com.jstyle.blesdk2301.callback; - - -import com.jstyle.blesdk2301.model.Device; - -public interface OnScanResults { - void Success(Device date); - void Fail(int code); -} diff --git a/android/blesdk_2301/src/main/java/com/jstyle/blesdk2301/callback/OnScanResults.kt b/android/blesdk_2301/src/main/java/com/jstyle/blesdk2301/callback/OnScanResults.kt new file mode 100644 index 00000000..9c0feee3 --- /dev/null +++ b/android/blesdk_2301/src/main/java/com/jstyle/blesdk2301/callback/OnScanResults.kt @@ -0,0 +1,8 @@ +package com.jstyle.blesdk2301.callback + +import com.jstyle.blesdk2301.model.Device + +interface OnScanResults { + fun Success(date: Device?) + fun Fail(code: Int) +} \ No newline at end of file diff --git a/android/blesdk_2301/src/main/java/com/jstyle/blesdk2301/cmdenum/YhDeviceData.java b/android/blesdk_2301/src/main/java/com/jstyle/blesdk2301/cmdenum/YhDeviceData.java deleted file mode 100644 index 47e53161..00000000 --- a/android/blesdk_2301/src/main/java/com/jstyle/blesdk2301/cmdenum/YhDeviceData.java +++ /dev/null @@ -1,42 +0,0 @@ -package com.jstyle.blesdk2301.cmdenum; - -import java.io.Serializable; - -public class YhDeviceData implements Serializable { - int dataType;// is index - String data="";//data object - boolean dataEnd=false; //Is it over? - - public boolean isDataEnd() { - return dataEnd; - } - - public void setDataEnd(boolean dataEnd) { - this.dataEnd = dataEnd; - } - - public int getDataType() { - return dataType; - } - - public void setDataType(int dataType) { - this.dataType = dataType; - } - - public String getData() { - return data==null?"":data; - } - - public void setData(String data) { - this.data = data; - } - - @Override - public String toString() { - return "YhDeviceData{" + - "dataType=" + dataType + - ", data=" + data + - ", dataEnd=" + dataEnd + - '}'; - } -} diff --git a/android/blesdk_2301/src/main/java/com/jstyle/blesdk2301/cmdenum/YhDeviceData.kt b/android/blesdk_2301/src/main/java/com/jstyle/blesdk2301/cmdenum/YhDeviceData.kt new file mode 100644 index 00000000..8ab6c74a --- /dev/null +++ b/android/blesdk_2301/src/main/java/com/jstyle/blesdk2301/cmdenum/YhDeviceData.kt @@ -0,0 +1,24 @@ +package com.jstyle.blesdk2301.cmdenum + +import java.io.Serializable + +class YhDeviceData : Serializable { + var dataType = 0 // is index + var data: String? = "" //data object + var isDataEnd = false //Is it over? + fun srgetDeviceData(): String { + return if (data == null) "" else data!! + } + + fun srsetData(data: String?) { + this.data = data + } + + override fun toString(): String { + return "YhDeviceData{" + + "dataType=" + dataType + + ", data=" + data + + ", dataEnd=" + isDataEnd + + '}' + } +} \ No newline at end of file diff --git a/android/blesdk_2301/src/main/java/com/jstyle/blesdk2301/constant/BleConst.java b/android/blesdk_2301/src/main/java/com/jstyle/blesdk2301/constant/BleConst.java deleted file mode 100644 index 567e0fa5..00000000 --- a/android/blesdk_2301/src/main/java/com/jstyle/blesdk2301/constant/BleConst.java +++ /dev/null @@ -1,135 +0,0 @@ -package com.jstyle.blesdk2301.constant; - -/** - * Created by Administrator on 2020/4/9. - */ - -public class BleConst { - public static final String GetDeviceTime="0"; - public static final String SetDeviceTime="1"; - public static final String GetPersonalInfo="2"; - public static final String SetPersonalInfo="3"; - public static final String GetDeviceInfo="4"; - public static final String SetDeviceInfo="5";//设置手环基本参数 - public static final String CMD_Set_Mac="6"; - public static final String GetStepGoal="7"; - public static final String SetStepGoal="8"; - public static final String GetDeviceBatteryLevel="9"; - public static final String GetDeviceMacAddress="10"; - public static final String GetDeviceVersion="11"; - public static final String CMD_Reset="12"; - public static final String CMD_MCUReset="13"; - public static final String SetMotorVibrationWithTimes ="14"; - public static final String GetDeviceName="15"; - public static final String GetAutomatic="16"; - public static final String SetAutomatic="17"; - public static final String GetAlarmClock="18"; - public static final String SetAlarmClockWithAllClock="19"; - public static final String Notify="20"; - public static final String GetSedentaryReminder="21"; - public static final String SetSedentaryReminder="22"; - public static final String RealTimeStep="23"; - public static final String GetTotalActivityData="24"; - public static final String GetDetailActivityData="25"; - public static final String GetDetailSleepData="26"; - public static final String GetDynamicHR="27"; - public static final String GetStaticHR="28"; - public static final String GetActivityModeData="29"; - public static final String EnterActivityMode="30"; - public static final String DeviceSendDataToAPP="31"; - public static final String BackHomeView="35"; - public static final String GetTempHistoryData="36"; - public static final String ECGDATA="37"; - public static final String EcgppGstatus="38"; - public static final String EcgppG="39"; - public static final String GPSControlCommand="40"; - public static final String Gps="41";//手环发送给app - public static final String GetHRVData="42"; - public static final String CMD_Set_TemperatureCorrection="43"; - public static final String Weather="44"; - public static final String Braceletdial="45"; - public static final String Braceletdialok="46"; - public static final String SportMode="47"; - public static final String GetSportMode="48"; - public static final String CMD_Set_WorkOutReminder="49"; - public static final String CMD_Get_WorkOutReminder="50"; - public static final String ReadSerialNumber="51"; - public static final String ECG="53"; - public static final String Clear_Bracelet_data="54"; - public static final String Blood_oxygen="55"; - public static final String SocialdistanceGetting="56"; - public static final String SocialdistanceSetting="57"; - public static final String Sos="58"; - public static final String Temperature_history="59"; - public static final String SetDialinterface="60"; - public static final String HeartBeatpacket="61"; - public static final String GetAxillaryTemperatureDataWithMode="62"; - public static final String GetMAC="63"; - public static final String Getppg="64"; - public static final String CloseECGPPG="65"; - public static final String GetEcgPpgStatus="66"; - public static final String ECGdata="67"; - public static final String GetAutomaticSpo2Monitoring="68"; - public static final String SetSpo2="69"; - public static final String GEtSpo2="70"; - public static final String DeleteECGdata="71"; - public static final String DeleteHrv="72"; - public static final String MeasurementHrvCallback="73"; - public static final String MeasurementHeartCallback="74"; - public static final String MeasurementOxygenCallback="75"; - public static final String StopMeasurementHrvCallback="76"; - public static final String StopMeasurementHeartCallback="77"; - public static final String StopMeasurementOxygenCallback="78"; - public static final String ExitQRcode="79"; - public static final String EnterQRcode="80"; - public static final String QRcodebandBack="81"; - public static final String SportData="82"; - public static final String Delete_Obtain_The_data_of_manual_blood_oxygen_test="83"; - public static final String Delete_Blood_oxygen="84"; - public static final String Delete_GetTotalActivityData="85"; - public static final String Delete_AlarmClock="87"; - public static final String Delete_ActivityModeData="88"; - public static final String Delete_GetStaticHR="89"; - public static final String Delete_GetDynamicHR="90"; - public static final String deleteGetTemperature_historyDataWithMode="91"; - public static final String deleteGetAxillaryTemperatureDataWithMode="92"; - public static final String deleteGetDetailActivityDataWithMode="93"; - public static final String Delete_GetDetailSleepData="94"; - public static final String Enter_photo_mode="95"; - public static final String openRRInterval="96"; - public static final String closeRRInterval="97"; - public static final String realtimeRRIntervalData="98"; - public static final String realtimePPGData="99"; - public static final String realtimePPIData="100"; - - public static final String ppgWithMode="101"; - public static final String ppgStartSucessed="102"; - public static final String ppgStartFailed="103"; - public static final String ppgStop="104"; - public static final String ppgQuit="105"; - public static final String ppgMeasurementProgress="106"; - public static final String ppgResult="107"; - public static final String SetBloodpressure_calibration="108"; - public static final String GetBloodpressure_calibration="109"; - public static final String SetWomenHealth="110"; - public static final String GetWomenHealth="111"; - - public static final String SetPregnancyCycle="112"; - public static final String GetPregnancyCycle="113"; - public static final String Getpeisu="114"; - public static final String GetpeisuER="115"; - public static final String CMD_Set_Name="116"; - public static final String CMD_Get_Name="117"; - public static final String Blood_glucose_status="118"; - public static final String Blood_glucose_data="119"; - public static final String FindActivityMode="120"; - - - - public static final String FindMobilePhoneMode="FindMobilePhoneMode"; - public static final String RejectTelMode ="RejectTelMode"; - public static final String TelMode ="TelMode"; - public static final String ECGResult="ECGResult"; - public static final String ENTERECG="ENTERECG"; - -} diff --git a/android/blesdk_2301/src/main/java/com/jstyle/blesdk2301/constant/BleConst.kt b/android/blesdk_2301/src/main/java/com/jstyle/blesdk2301/constant/BleConst.kt new file mode 100644 index 00000000..d8a5b241 --- /dev/null +++ b/android/blesdk_2301/src/main/java/com/jstyle/blesdk2301/constant/BleConst.kt @@ -0,0 +1,128 @@ +package com.jstyle.blesdk2301.constant + +/** + * Created by Administrator on 2020/4/9. + */ +object BleConst { + const val GetDeviceTime = "0" + const val SetDeviceTime = "1" + const val GetPersonalInfo = "2" + const val SetPersonalInfo = "3" + const val GetDeviceInfo = "4" + const val SetDeviceInfo = "5" //设置手环基本参数 + const val CMD_Set_Mac = "6" + const val GetStepGoal = "7" + const val SetStepGoal = "8" + const val GetDeviceBatteryLevel = "9" + const val GetDeviceMacAddress = "10" + const val GetDeviceVersion = "11" + const val CMD_Reset = "12" + const val CMD_MCUReset = "13" + const val SetMotorVibrationWithTimes = "14" + const val GetDeviceName = "15" + const val GetAutomatic = "16" + const val SetAutomatic = "17" + const val GetAlarmClock = "18" + const val SetAlarmClockWithAllClock = "19" + const val Notify = "20" + const val GetSedentaryReminder = "21" + const val SetSedentaryReminder = "22" + const val RealTimeStep = "23" + const val GetTotalActivityData = "24" + const val GetDetailActivityData = "25" + const val GetDetailSleepData = "26" + const val GetDynamicHR = "27" + const val GetStaticHR = "28" + const val GetActivityModeData = "29" + const val EnterActivityMode = "30" + const val DeviceSendDataToAPP = "31" + const val BackHomeView = "35" + const val GetTempHistoryData = "36" + const val ECGDATA = "37" + const val EcgppGstatus = "38" + const val EcgppG = "39" + const val GPSControlCommand = "40" + const val Gps = "41" //手环发送给app + const val GetHRVData = "42" + const val CMD_Set_TemperatureCorrection = "43" + const val Weather = "44" + const val Braceletdial = "45" + const val Braceletdialok = "46" + const val SportMode = "47" + const val GetSportMode = "48" + const val CMD_Set_WorkOutReminder = "49" + const val CMD_Get_WorkOutReminder = "50" + const val ReadSerialNumber = "51" + const val ECG = "53" + const val Clear_Bracelet_data = "54" + const val Blood_oxygen = "55" + const val SocialdistanceGetting = "56" + const val SocialdistanceSetting = "57" + const val Sos = "58" + const val Temperature_history = "59" + const val SetDialinterface = "60" + const val HeartBeatpacket = "61" + const val GetAxillaryTemperatureDataWithMode = "62" + const val GetMAC = "63" + const val Getppg = "64" + const val CloseECGPPG = "65" + const val GetEcgPpgStatus = "66" + const val ECGdata = "67" + const val GetAutomaticSpo2Monitoring = "68" + const val SetSpo2 = "69" + const val GEtSpo2 = "70" + const val DeleteECGdata = "71" + const val DeleteHrv = "72" + const val MeasurementHrvCallback = "73" + const val MeasurementHeartCallback = "74" + const val MeasurementOxygenCallback = "75" + const val StopMeasurementHrvCallback = "76" + const val StopMeasurementHeartCallback = "77" + const val StopMeasurementOxygenCallback = "78" + const val ExitQRcode = "79" + const val EnterQRcode = "80" + const val QRcodebandBack = "81" + const val SportData = "82" + const val Delete_Obtain_The_data_of_manual_blood_oxygen_test = "83" + const val Delete_Blood_oxygen = "84" + const val Delete_GetTotalActivityData = "85" + const val Delete_AlarmClock = "87" + const val Delete_ActivityModeData = "88" + const val Delete_GetStaticHR = "89" + const val Delete_GetDynamicHR = "90" + const val deleteGetTemperature_historyDataWithMode = "91" + const val deleteGetAxillaryTemperatureDataWithMode = "92" + const val deleteGetDetailActivityDataWithMode = "93" + const val Delete_GetDetailSleepData = "94" + const val Enter_photo_mode = "95" + const val openRRInterval = "96" + const val closeRRInterval = "97" + const val realtimeRRIntervalData = "98" + const val realtimePPGData = "99" + const val realtimePPIData = "100" + const val ppgWithMode = "101" + const val ppgStartSucessed = "102" + const val ppgStartFailed = "103" + const val ppgStop = "104" + const val ppgQuit = "105" + const val ppgMeasurementProgress = "106" + const val ppgResult = "107" + const val SetBloodpressure_calibration = "108" + const val GetBloodpressure_calibration = "109" + const val SetWomenHealth = "110" + const val GetWomenHealth = "111" + const val SetPregnancyCycle = "112" + const val GetPregnancyCycle = "113" + const val Getpeisu = "114" + const val GetpeisuER = "115" + const val CMD_Set_Name = "116" + const val CMD_Get_Name = "117" + const val Blood_glucose_status = "118" + const val Blood_glucose_data = "119" + const val FindActivityMode = "120" + const val FindMobilePhoneMode = "FindMobilePhoneMode" + const val RejectTelMode = "RejectTelMode" + const val TelMode = "TelMode" + const val ECGResult = "ECGResult" + const val ENTERECG = "ENTERECG" +} \ No newline at end of file diff --git a/android/blesdk_2301/src/main/java/com/jstyle/blesdk2301/constant/DeviceConst.java b/android/blesdk_2301/src/main/java/com/jstyle/blesdk2301/constant/DeviceConst.java deleted file mode 100644 index 0f09b9be..00000000 --- a/android/blesdk_2301/src/main/java/com/jstyle/blesdk2301/constant/DeviceConst.java +++ /dev/null @@ -1,41 +0,0 @@ -package com.jstyle.blesdk2301.constant; - -/** - * Created by Administrator on 2018/1/17. - */ - -public class DeviceConst { - public static final byte CMD_SET_TIME = (byte)0x01; - public static final byte CMD_GET_TIME = (byte)0x41; - public static final byte CMD_Set_UseInfo = (byte)0x02; - public static final byte CMD_GET_USERINFO = (byte) 0x42; - public static final byte CMD_Set_DeviceID = (byte)0x05; - public static final byte CMD_Enable_Activity = (byte)0x09;// - public static final byte CMD_Get_BatteryLevel = (byte)0x13;// - public static final byte CMD_Get_Address = (byte)0x22; - public static final byte CMD_Get_Version = (byte)0x27; - public static final byte CMD_Reset = (byte)0x12; - public static final byte CMD_Mcu_Reset = (byte)0x2e; - public static final byte CMD_Set_Auto = (byte)0x2a; - public static final byte CMD_Get_Auto = (byte)0x2b; - public static final byte CMD_Get_TotalData = (byte)0x51;// - public static final byte CMD_Get_DetailData = (byte)0x52; - public static final byte CMD_Get_SleepData = (byte)0x53; - public static final byte CMD_Get_HeartData = (byte)0x54; - public static final byte CMD_Get_OnceHeartData = (byte)0x55; - public static final byte CMD_Get_HrvTestData = (byte)0x56;// - public static final byte ReadTempHisrory= (byte)0x62; - public static final byte MeasurementWithType= (byte)0x28; - public static final byte Oxygen_data= (byte)0x66; - - public static final byte CMD_Start_EXERCISE = (byte)0x19; - public static final byte CMD_heart_package= (byte)0x17; - public static final byte CMD_HeartPackageFromDevice = (byte)0x18;// - public static final byte CMD_Set_Name = (byte)0x3d; - public static final byte CMD_Get_Name = (byte)0x3e; - - public static final byte CMD_Get_SPORTData = (byte)0x5C; - - public static final byte CMD_Get_Bloodsugar = (byte)0x78; - public static final byte Bloodsugar_data=(byte)0x3a;//血糖数据 -} diff --git a/android/blesdk_2301/src/main/java/com/jstyle/blesdk2301/constant/DeviceConst.kt b/android/blesdk_2301/src/main/java/com/jstyle/blesdk2301/constant/DeviceConst.kt new file mode 100644 index 00000000..ed9d8add --- /dev/null +++ b/android/blesdk_2301/src/main/java/com/jstyle/blesdk2301/constant/DeviceConst.kt @@ -0,0 +1,37 @@ +package com.jstyle.blesdk2301.constant + +/** + * Created by Administrator on 2018/1/17. + */ +object DeviceConst { + const val CMD_SET_TIME = 0x01.toByte() + const val CMD_GET_TIME = 0x41.toByte() + const val CMD_Set_UseInfo = 0x02.toByte() + const val CMD_GET_USERINFO = 0x42.toByte() + const val CMD_Set_DeviceID = 0x05.toByte() + const val CMD_Enable_Activity = 0x09.toByte() // + const val CMD_Get_BatteryLevel = 0x13.toByte() // + const val CMD_Get_Address = 0x22.toByte() + const val CMD_Get_Version = 0x27.toByte() + const val CMD_Reset = 0x12.toByte() + const val CMD_Mcu_Reset = 0x2e.toByte() + const val CMD_Set_Auto = 0x2a.toByte() + const val CMD_Get_Auto = 0x2b.toByte() + const val CMD_Get_TotalData = 0x51.toByte() // + const val CMD_Get_DetailData = 0x52.toByte() + const val CMD_Get_SleepData = 0x53.toByte() + const val CMD_Get_HeartData = 0x54.toByte() + const val CMD_Get_OnceHeartData = 0x55.toByte() + const val CMD_Get_HrvTestData = 0x56.toByte() // + const val ReadTempHisrory = 0x62.toByte() + const val MeasurementWithType = 0x28.toByte() + const val Oxygen_data = 0x66.toByte() + const val CMD_Start_EXERCISE = 0x19.toByte() + const val CMD_heart_package = 0x17.toByte() + const val CMD_HeartPackageFromDevice = 0x18.toByte() // + const val CMD_Set_Name = 0x3d.toByte() + const val CMD_Get_Name = 0x3e.toByte() + const val CMD_Get_SPORTData = 0x5C.toByte() + const val CMD_Get_Bloodsugar = 0x78.toByte() + const val Bloodsugar_data = 0x3a.toByte() //血糖数据 +} \ No newline at end of file diff --git a/android/blesdk_2301/src/main/java/com/jstyle/blesdk2301/constant/DeviceKey.java b/android/blesdk_2301/src/main/java/com/jstyle/blesdk2301/constant/DeviceKey.java deleted file mode 100644 index 3bcdbcf1..00000000 --- a/android/blesdk_2301/src/main/java/com/jstyle/blesdk2301/constant/DeviceKey.java +++ /dev/null @@ -1,413 +0,0 @@ -package com.jstyle.blesdk2301.constant; - -/** - * Created by Administrator on 2018/4/10. - */ - -public class DeviceKey { - public static final String heartValue = "heartValue"; - public static final String hrvValue = "hrvValue"; - public static final String Quality = "Quality"; - - public static final String HangUp = "HangUp"; - public static final String Telephone = "Telephone"; - public static final String Photograph = "Photograph"; - public static final String CanclePhotograph = "CanclePhotograph"; - public static final String type = "type"; - public static final String Play = "Play"; - public static final String Suspend = "Suspend"; - public static final String LastSong = "LastSong"; - public static final String NextSong = "NextSong"; - public static final String VolumeReduction = "VolumeReduction"; - public static final String VolumeUp = "VolumeUp"; - public static final String FindYourPhone = "FindYourPhone"; - public static final String Cancle_FindPhone = "Cancle_FindPhone"; - public static final String SOS = "SOS"; - public static final String DataType = "dataType"; - public static final String enterActivityModeSuccess = "enterActivityModeSuccess"; - public static final String Type = "Type"; - public static final String Status = "Status"; - public static final String RRIntervalData = "RRIntervalData"; - public static final String Manual = "Manual"; - public static final String automatic = "automatic"; - public static final String Data = "dicData"; - public static final String End = "dataEnd"; - public static final String index = "index"; - public static final String scanInterval = "scanInterval"; - public static final String scanTime = "scanTime"; - public static final String signalStrength = "signalStrength"; - public static final String arrayX = "arrayX"; - public static final String arrayY = "arrayY"; - public static final String arrayZ = "arrayZ"; - public static final String arrayPpgRawData = "arrayPpgRawData"; - public static final String KGpsResCheck0 = "KGpsResCheck0"; // 设备时间 GET_DEVICE_Time - public static final String KGpsResCheck1 = "KGpsResCheck1"; // 设备时间 - public static final String Band = "Band"; - public static final String KFinishFlag = "finish"; - public static final String DeviceTime = "strDeviceTime"; // 设备时间 GET_DEVICE_Time - public static final String GPSTime = "gpsExpirationTime"; // 设备时间 GET_DEVICE_Time - public static final String TimeZone = "TimeZone"; // 设备时间 GET_DEVICE_Time - - - public static final String KHrvBloodHighPressure = "KHrvBloodHighPressure"; - public static final String KHrvBloodLowPressure = "KHrvBloodLowPressure"; - /* - * GET_PERSONAL_INFO - * sex 性别 - * Age 年龄 - * Height 身高 - * Weight 体重 - * stepLength 步长 - * deviceId 设备ID - */ - public static final String Gender = "MyGender"; - public static final String Age = "MyAge"; - public static final String Height = "MyHeight"; - public static final String Weight = "MyWeight"; - public static final String Stride = "MyStride"; - public static final String KUserDeviceId = "deviceId"; - - - /* - * GET_DEVICE_INFO - * distanceUnit 距离单位 - * hourState 12小时24小时显示 - * handleEnable 抬手检查使能标志 - * handleSign 抬手检测左右手标志 - * screenState 横竖屏显示 - * anceEnable ANCS使能开关 - */ - public static final String DistanceUnit = "distancUnit"; - public static final String TimeUnit = "timeUnit"; - public static final String TempUnit = "temperatureUnit"; - public static final String WristOn = "wristOn"; - public static final String TemperatureUnit = "TemperatureUnit"; - public static final String NightMode = "NightMode"; - public static final String LeftOrRight = "handleSign"; - //public static final String ScreenShow = "screenState"; - public static final String Dialinterface = "dialinterface"; - public static final String SocialDistancedwitch = "SocialDistancedwitch"; - public static final String ChineseOrEnglish= "ChineseOrEnglish"; - public static final String Lauage= "Lauage"; - public static final String ScreenBrightness = "dcreenBrightness"; - public static final String KBaseHeart = "baseHeartRate"; - public static final String isHorizontalScreen = "isHorizontalScreen"; - - public static final String Year = "Year"; - public static final String Month = "Month"; - public static final String Day = "Day"; - public static final String MenstrualPeriod_Lenth = "MenstrualPeriod_Lenth"; - public static final String MenstrualPeriod_Period = "MenstrualPeriod_Period"; - - /* - * SET_STEP_MODEL - *totalSteps 总步数 - *calories 卡路里 - *distance 距离 - *time 时间 - *heartValue 心率值 - */ - - public static final String Step = "step"; - public static final String Calories = "calories"; - public static final String Distance = "distance"; - public static final String ExerciseMinutes = "exerciseMinutes"; - public static final String HeartRate = "heartRate"; - public static final String ActiveMinutes = "ExerciseTime"; - public static final String TempData = "TempData"; - public static final String StepGoal = "stepGoal"; // 目标步数值 GET_GOAL - public static final String BatteryLevel = "batteryLevel"; // 电量级别 READ_DEVICE_BATTERY - public static final String Chargingstate = "Chargingstate"; // 充电状态 - public static final String Voltage_value = "VoltageValue"; // 电压值 - public static final String MacAddress = "macAddress"; // MAC地址 READ_MAC_ADDRESS - public static final String DeviceVersion = "deviceVersion"; // 版本号 READ_VERSION - public static final String DeviceName = "deviceName"; // 设备名称 GET_DEVICE_NAME - public static final String TemperatureCorrectionValue = "TemperatureCorrectionValue"; // 设备名称 GET_DEVICE_NAME - - /* - * GET_AUTOMIC_HEART - *workModel 工作模式 - *heartStartHour 开始运动时间的小时 - *heartStartMinter 开始运动时间的分钟 - *heartEndHour 结束运动时间的小时 - *heartEndMinter 结束运动时间的分钟 - *heartWeek 星期使能 - *workTime 工作模式时间 - */ - public static final String WorkMode = "workModel"; - public static final String StartTime = "heartStartHour"; - public static final String KHeartStartMinter = "heartStartMinter"; - public static final String EndTime = "heartEndHour"; - public static final String KHeartEndMinter = "heartEndMinter"; - public static final String Weeks = "weekValue"; - public static final String IntervalTime = "intervalTime"; - public static final String Time = "Time"; - public static final String PPG = "PPG"; - - - /* - * READ_SPORT_PERIOD - *StartTimeHour 开始运动时间的小时 - *StartTimeMin 开始运动时间的分钟 - *EndTimeHour 结束运动时间的小时 - *EndTimeMin 结束运动时间的分钟 - *Week 星期使能 - *KSportNotifierTime 运动提醒周期 - */ - public static final String StartTimeHour = "sportStartHour"; - public static final String StartTimeMin = "sportStartMinter"; - public static final String EndTimeHour = "sportEndHour"; - public static final String EndTimeMin = "sportEndMinter"; - - public static final String LeastSteps = "leastSteps"; - - /* - * GET_STEP_DATA - *historyDate 日期:年月日 - *historySteps 步数 - *historyTime 运动时间 - *historyDistance 距离 - *Calories 卡路里 - *historyGoal 目标 - */ - public static final String Date = "date"; - public static final String Size = "size"; - public static final String Goal = "goal"; - - - - /* - * GET_STEP_DETAIL - *Date 日期:年月日时分秒 - *ArraySteps 步数 - *Calories 卡路里 - *Distance 距离 - *KDetailMinterStep 10分钟内每一分钟的步数 - */ - - public static final String ArraySteps = "arraySteps"; - - public static final String KDetailMinterStep = "detailMinterStep"; - public static final String temperature = "temperature"; - public static final String axillaryTemperature = "axillaryTemperature"; - - /* - * GET_SLEEP_DETAIL - *Date 日期:年月日时分秒 - *KSleepLength 睡眠数据的长度 - *ArraySleep 5分钟的睡眠质量 (总共24个数据,每一个数据代表五分钟) - */ - - public static final String KSleepLength = "sleepLength"; - public static final String ArraySleep = "arraySleepQuality"; - public static final String sleepUnitLength = "sleepUnitLength";//是不是一分钟的睡眠数据 1为1分钟数据 0为5分钟数据 - - /* - * GET_HEART_DATA - *Date 日期:年月日时分秒 - *ArrayDynamicHR 10秒一个心率值,总共12个心率值 - */ - - public static final String ArrayDynamicHR = "arrayDynamicHR"; - public static final String Blood_oxygen = "Blood_oxygen"; - - - - /* - * GET_ONCE_HEARTDATA - *Date 日期:年月日时分秒 - *StaticHR 心率值 - */ - - public static final String StaticHR = "onceHeartValue"; - - /* - * GET_HRV_DATA - *Date 日期:年月日时分秒 - *HRV HRV值 - *VascularAging 血管老化度值 - *HeartRate 心率值 - *Stress 疲劳度 - */ - - public static final String HRV = "hrv"; - public static final String VascularAging = "vascularAging"; - public static final String Fatiguedegree = "fatigueDegree"; - - public static final String Stress = "stress"; - public static final String HighPressure = "highPressure"; - public static final String LowPressure = "lowPressure"; - public static final String highBP = "highBP"; - public static final String lowBP = "lowBP"; - - /* - *GET_ALARM - *KAlarmId 0到4闹钟编号 - *ClockType 闹钟类型 - *ClockTime 闹钟时间的小时 - *KAlarmMinter 闹钟时间的分钟 - *Week 星期使能 - *KAlarmLength 长度 - *KAlarmContent 文本的内容 - */ - public static final String KAlarmId = "alarmId"; - public static final String OpenOrClose = "clockOpenOrClose"; - public static final String ClockType = "clockType"; - public static final String ClockTime = "alarmHour"; - public static final String KAlarmMinter = "alarmMinter"; - public static final String Week = "weekValue"; - public static final String KAlarmLength = "alarmLength"; - public static final String KAlarmContent = "dicClock"; - - - /***********************GET_HRV_TESTDATA***************************************************/ - /* - *KBloodTestLength 数据长度 - *KBloodTestProgress 进度 - *KBloodTestValue 本次PPG获得的值 - *KBolldTestCurve 本次波型的高度 - */ - public static final String KBloodTestLength = "bloodTestLength"; - public static final String KBloodTestProgress = "bloodTestProgress"; - public static final String KBloodTestValue = "bloodTestValue"; - public static final String KBloodTestCurve = "bloodTestCurve"; - - /* - *KBloodResultPercent 反弹的百分比 - *KBloodResultRebound 平均反弹高度 - *KBloodResultMax 最大高度 - *KBloodResultRank 结果级别(1到6) - */ - public static final String KBloodResultPercent = "bloodPercent"; - public static final String KBloodResultRebound = "bloodRebound"; - public static final String KBloodResultMax = "bloodResultMax"; - public static final String KBloodResultRank = "bloodResultRank"; - - - /* - *KHrvTestProgress 进度 - *KHrvTestWidth 本次心跳的宽度 - *KHrvTestValue 心率值 - */ - public static final String KHrvTestProgress = "hrvTestProgress"; - public static final String KHrvTestWidth = "hrvTestWidth"; - public static final String KHrvTestValue = "hrvTestValue"; - - /* - *KHrvResultState SDNN结果 如果是0,说明检测失败 - *KHrvResultAvg SDNN平均值 - *KHrvResultTotal 总SDNN结果 - *KHrvResultCount 有效数据个数 - *KHrvResultTired 疲劳指数据 - *KHrvResultValue 心率值 - */ - public static final String KHrvResultState = "hrvResultState"; - public static final String KHrvResultAvg = "hrvResultAvg"; - public static final String KHrvResultTotal = "hrvResultTotal"; - public static final String KHrvResultCount = "hrvResultCount"; - public static final String KHrvResultTired = "hrvResultTired"; - public static final String KHrvResultValue = "hrvResultValue"; - - - /* - *KDisturbState 1:开始运动 0:停止运动 - *KSlipHand 1: 带在手上 0;脱手。 - *KPPGData PPG的波型值 - */ - public static final String KDisturbState = "disturbState"; - public static final String KSlipHand = "slipHand"; - public static final String KPPGData = "ppgData"; - public static final String KPPIData = "ppiData"; - - public static final String ppgResult = "ppgResult"; - - public static final String ppgStartSucessed="ppgStartSucessed"; - public static final String ppgStartFailed="ppgStartFailed"; - public static final String ppgStop="ppgStop"; - public static final String ppgQuit="ppgQuit"; - public static final String ppgMeasurementProgress="ppgMeasurementProgress"; - - - - - - /* - *@param Date 时间:年月日时分秒 - *@param Latitude 纬度数据 - *@param Longitude 经度数据 - */ - - - public static final String Latitude = "locationLatitude"; - public static final String Longitude = "locationLongitude"; - - public static final String KActivityLocationTime = "ActivityLocationTIme"; - public static final String KActivityLocationLatitude = "ActivityLocationLatitude"; - public static final String KActivityLocationLongitude = "ActivityLocationLongitude"; - public static final String KActivityLocationCount = "KActivityLocationCount"; -/* - * GET_SPORTMODEL_DATA - *@param Date 时间:年月日时分秒 - *@param ActivityMode 运动类型 - 0=Run, - 1=Cycling, - 2=Swimming, - 3=Badminton, - 4=Football, - 5=Tennis, - 6=Yoga, - 7=Medication, - 8=Dance - - *@param HeartRate 心率 - *@param ActiveMinutes 运动时间 - *@param Step 运动步数 - *@param Pace 运动速度 - *@param Calories 卡路里 - *@param Distance 距离 - */ - - - public static final String ActivityMode = "sportModel"; - public static final String Pace = "sportModelSpeed"; - - public static final String KDataID = "KDataID"; - public static final String KPhoneDataLength = "KPhoneDataLength"; - public static final String KClockLast = "KClockLast"; - - - public static final String TakePhotoMode = "TakePhotoMode"; - public static final String KFunction_tel = "TelMode"; - public static final String KFunction_reject_tel = "RejectTelMode"; - - public static final String FindMobilePhoneMode = "FindMobilePhoneMode"; - public static final String KEnable_exercise = "KEnable_exercise"; - public static final String ECGQualityValue = "ECGQualityValue"; - - public static final String ECGResultValue = "ECGResultVALUE"; - public static final String ECGHrvValue = "ECGHrvValue"; - public static final String ECGAvBlockValue = "ECGAvBlockValue"; - public static final String ECGHrValue = "ECGHrValue"; - public static final String PPGHrValue = "PPGHrValue"; - public static final String ECGStreesValue = "ECGStreesValue"; - public static final String ECGhighBpValue = "ECGhighBpValue"; - public static final String ECGLowBpValue = "ECGLowBpValue"; - public static final String ECGMoodValue = "ECGMoodValue"; - public static final String ECGBreathValue = "ECGBreathValue"; - public static final String KEcgDataString = "KEcgDataString"; // ecg - public static final String ECGValue = "ECGValue"; - public static final String PPGValue = "PPGValue"; - public static final String EcgStatus = "EcgStatus"; - public static final String EcgSBP = "PPGSBP"; - public static final String EcgDBP = "PPGDBP"; - public static final String EcgHR = "PPGHR"; - public static final String WaveformDownTime = "WaveformDownTime"; - public static final String WaveformRiseTime = "WaveformRiseTime"; - - public static final String EcgGender = "Gender"; - public static final String EcgAge = "Age"; - public static final String EcgHeight = "Height"; - public static final String EcgWeight = "Weight"; - - -} diff --git a/android/blesdk_2301/src/main/java/com/jstyle/blesdk2301/constant/DeviceKey.kt b/android/blesdk_2301/src/main/java/com/jstyle/blesdk2301/constant/DeviceKey.kt new file mode 100644 index 00000000..62659f4a --- /dev/null +++ b/android/blesdk_2301/src/main/java/com/jstyle/blesdk2301/constant/DeviceKey.kt @@ -0,0 +1,373 @@ +package com.jstyle.blesdk2301.constant + +/** + * Created by Administrator on 2018/4/10. + */ +object DeviceKey { + const val heartValue = "heartValue" + const val hrvValue = "hrvValue" + const val Quality = "Quality" + const val HangUp = "HangUp" + const val Telephone = "Telephone" + const val Photograph = "Photograph" + const val CanclePhotograph = "CanclePhotograph" + const val type = "type" + const val Play = "Play" + const val Suspend = "Suspend" + const val LastSong = "LastSong" + const val NextSong = "NextSong" + const val VolumeReduction = "VolumeReduction" + const val VolumeUp = "VolumeUp" + const val FindYourPhone = "FindYourPhone" + const val Cancle_FindPhone = "Cancle_FindPhone" + const val SOS = "SOS" + const val DataType = "dataType" + const val enterActivityModeSuccess = "enterActivityModeSuccess" + const val Type = "Type" + const val Status = "Status" + const val RRIntervalData = "RRIntervalData" + const val Manual = "Manual" + const val automatic = "automatic" + const val Data = "dicData" + const val End = "dataEnd" + const val index = "index" + const val scanInterval = "scanInterval" + const val scanTime = "scanTime" + const val signalStrength = "signalStrength" + const val arrayX = "arrayX" + const val arrayY = "arrayY" + const val arrayZ = "arrayZ" + const val arrayPpgRawData = "arrayPpgRawData" + const val KGpsResCheck0 = "KGpsResCheck0" // 设备时间 GET_DEVICE_Time + const val KGpsResCheck1 = "KGpsResCheck1" // 设备时间 + const val Band = "Band" + const val KFinishFlag = "finish" + const val DeviceTime = "strDeviceTime" // 设备时间 GET_DEVICE_Time + const val GPSTime = "gpsExpirationTime" // 设备时间 GET_DEVICE_Time + const val TimeZone = "TimeZone" // 设备时间 GET_DEVICE_Time + const val KHrvBloodHighPressure = "KHrvBloodHighPressure" + const val KHrvBloodLowPressure = "KHrvBloodLowPressure" + + /* + * GET_PERSONAL_INFO + * sex 性别 + * Age 年龄 + * Height 身高 + * Weight 体重 + * stepLength 步长 + * deviceId 设备ID + */ + const val Gender = "MyGender" + const val Age = "MyAge" + const val Height = "MyHeight" + const val Weight = "MyWeight" + const val Stride = "MyStride" + const val KUserDeviceId = "deviceId" + + /* + * GET_DEVICE_INFO + * distanceUnit 距离单位 + * hourState 12小时24小时显示 + * handleEnable 抬手检查使能标志 + * handleSign 抬手检测左右手标志 + * screenState 横竖屏显示 + * anceEnable ANCS使能开关 + */ + const val DistanceUnit = "distancUnit" + const val TimeUnit = "timeUnit" + const val TempUnit = "temperatureUnit" + const val WristOn = "wristOn" + const val TemperatureUnit = "TemperatureUnit" + const val NightMode = "NightMode" + const val LeftOrRight = "handleSign" + + //public static final String ScreenShow = "screenState"; + const val Dialinterface = "dialinterface" + const val SocialDistancedwitch = "SocialDistancedwitch" + const val ChineseOrEnglish = "ChineseOrEnglish" + const val Lauage = "Lauage" + const val ScreenBrightness = "dcreenBrightness" + const val KBaseHeart = "baseHeartRate" + const val isHorizontalScreen = "isHorizontalScreen" + const val Year = "Year" + const val Month = "Month" + const val Day = "Day" + const val MenstrualPeriod_Lenth = "MenstrualPeriod_Lenth" + const val MenstrualPeriod_Period = "MenstrualPeriod_Period" + + /* + * SET_STEP_MODEL + *totalSteps 总步数 + *calories 卡路里 + *distance 距离 + *time 时间 + *heartValue 心率值 + */ + const val Step = "step" + const val Calories = "calories" + const val Distance = "distance" + const val ExerciseMinutes = "exerciseMinutes" + const val HeartRate = "heartRate" + const val ActiveMinutes = "ExerciseTime" + const val TempData = "TempData" + const val StepGoal = "stepGoal" // 目标步数值 GET_GOAL + const val BatteryLevel = "batteryLevel" // 电量级别 READ_DEVICE_BATTERY + const val Chargingstate = "Chargingstate" // 充电状态 + const val Voltage_value = "VoltageValue" // 电压值 + const val MacAddress = "macAddress" // MAC地址 READ_MAC_ADDRESS + const val DeviceVersion = "deviceVersion" // 版本号 READ_VERSION + const val DeviceName = "deviceName" // 设备名称 GET_DEVICE_NAME + const val TemperatureCorrectionValue = "TemperatureCorrectionValue" // 设备名称 GET_DEVICE_NAME + + /* + * GET_AUTOMIC_HEART + *workModel 工作模式 + *heartStartHour 开始运动时间的小时 + *heartStartMinter 开始运动时间的分钟 + *heartEndHour 结束运动时间的小时 + *heartEndMinter 结束运动时间的分钟 + *heartWeek 星期使能 + *workTime 工作模式时间 + */ + const val WorkMode = "workModel" + const val StartTime = "heartStartHour" + const val KHeartStartMinter = "heartStartMinter" + const val EndTime = "heartEndHour" + const val KHeartEndMinter = "heartEndMinter" + const val Weeks = "weekValue" + const val IntervalTime = "intervalTime" + const val Time = "Time" + const val PPG = "PPG" + + /* + * READ_SPORT_PERIOD + *StartTimeHour 开始运动时间的小时 + *StartTimeMin 开始运动时间的分钟 + *EndTimeHour 结束运动时间的小时 + *EndTimeMin 结束运动时间的分钟 + *Week 星期使能 + *KSportNotifierTime 运动提醒周期 + */ + const val StartTimeHour = "sportStartHour" + const val StartTimeMin = "sportStartMinter" + const val EndTimeHour = "sportEndHour" + const val EndTimeMin = "sportEndMinter" + const val LeastSteps = "leastSteps" + + /* + * GET_STEP_DATA + *historyDate 日期:年月日 + *historySteps 步数 + *historyTime 运动时间 + *historyDistance 距离 + *Calories 卡路里 + *historyGoal 目标 + */ + const val Date = "date" + const val Size = "size" + const val Goal = "goal" + + /* + * GET_STEP_DETAIL + *Date 日期:年月日时分秒 + *ArraySteps 步数 + *Calories 卡路里 + *Distance 距离 + *KDetailMinterStep 10分钟内每一分钟的步数 + */ + const val ArraySteps = "arraySteps" + const val KDetailMinterStep = "detailMinterStep" + const val temperature = "temperature" + const val axillaryTemperature = "axillaryTemperature" + + /* + * GET_SLEEP_DETAIL + *Date 日期:年月日时分秒 + *KSleepLength 睡眠数据的长度 + *ArraySleep 5分钟的睡眠质量 (总共24个数据,每一个数据代表五分钟) + */ + const val KSleepLength = "sleepLength" + const val ArraySleep = "arraySleepQuality" + const val sleepUnitLength = "sleepUnitLength" //是不是一分钟的睡眠数据 1为1分钟数据 0为5分钟数据 + + /* + * GET_HEART_DATA + *Date 日期:年月日时分秒 + *ArrayDynamicHR 10秒一个心率值,总共12个心率值 + */ + const val ArrayDynamicHR = "arrayDynamicHR" + const val Blood_oxygen = "Blood_oxygen" + + /* + * GET_ONCE_HEARTDATA + *Date 日期:年月日时分秒 + *StaticHR 心率值 + */ + const val StaticHR = "onceHeartValue" + + /* + * GET_HRV_DATA + *Date 日期:年月日时分秒 + *HRV HRV值 + *VascularAging 血管老化度值 + *HeartRate 心率值 + *Stress 疲劳度 + */ + const val HRV = "hrv" + const val VascularAging = "vascularAging" + const val Fatiguedegree = "fatigueDegree" + const val Stress = "stress" + const val HighPressure = "highPressure" + const val LowPressure = "lowPressure" + const val highBP = "highBP" + const val lowBP = "lowBP" + + /* + *GET_ALARM + *KAlarmId 0到4闹钟编号 + *ClockType 闹钟类型 + *ClockTime 闹钟时间的小时 + *KAlarmMinter 闹钟时间的分钟 + *Week 星期使能 + *KAlarmLength 长度 + *KAlarmContent 文本的内容 + */ + const val KAlarmId = "alarmId" + const val OpenOrClose = "clockOpenOrClose" + const val ClockType = "clockType" + const val ClockTime = "alarmHour" + const val KAlarmMinter = "alarmMinter" + const val Week = "weekValue" + const val KAlarmLength = "alarmLength" + const val KAlarmContent = "dicClock" + + /***********************GET_HRV_TESTDATA */ /* + *KBloodTestLength 数据长度 + *KBloodTestProgress 进度 + *KBloodTestValue 本次PPG获得的值 + *KBolldTestCurve 本次波型的高度 + */ + const val KBloodTestLength = "bloodTestLength" + const val KBloodTestProgress = "bloodTestProgress" + const val KBloodTestValue = "bloodTestValue" + const val KBloodTestCurve = "bloodTestCurve" + + /* + *KBloodResultPercent 反弹的百分比 + *KBloodResultRebound 平均反弹高度 + *KBloodResultMax 最大高度 + *KBloodResultRank 结果级别(1到6) + */ + const val KBloodResultPercent = "bloodPercent" + const val KBloodResultRebound = "bloodRebound" + const val KBloodResultMax = "bloodResultMax" + const val KBloodResultRank = "bloodResultRank" + + /* + *KHrvTestProgress 进度 + *KHrvTestWidth 本次心跳的宽度 + *KHrvTestValue 心率值 + */ + const val KHrvTestProgress = "hrvTestProgress" + const val KHrvTestWidth = "hrvTestWidth" + const val KHrvTestValue = "hrvTestValue" + + /* + *KHrvResultState SDNN结果 如果是0,说明检测失败 + *KHrvResultAvg SDNN平均值 + *KHrvResultTotal 总SDNN结果 + *KHrvResultCount 有效数据个数 + *KHrvResultTired 疲劳指数据 + *KHrvResultValue 心率值 + */ + const val KHrvResultState = "hrvResultState" + const val KHrvResultAvg = "hrvResultAvg" + const val KHrvResultTotal = "hrvResultTotal" + const val KHrvResultCount = "hrvResultCount" + const val KHrvResultTired = "hrvResultTired" + const val KHrvResultValue = "hrvResultValue" + + /* + *KDisturbState 1:开始运动 0:停止运动 + *KSlipHand 1: 带在手上 0;脱手。 + *KPPGData PPG的波型值 + */ + const val KDisturbState = "disturbState" + const val KSlipHand = "slipHand" + const val KPPGData = "ppgData" + const val KPPIData = "ppiData" + const val ppgResult = "ppgResult" + const val ppgStartSucessed = "ppgStartSucessed" + const val ppgStartFailed = "ppgStartFailed" + const val ppgStop = "ppgStop" + const val ppgQuit = "ppgQuit" + const val ppgMeasurementProgress = "ppgMeasurementProgress" + + /* + *@param Date 时间:年月日时分秒 + *@param Latitude 纬度数据 + *@param Longitude 经度数据 + */ + const val Latitude = "locationLatitude" + const val Longitude = "locationLongitude" + const val KActivityLocationTime = "ActivityLocationTIme" + const val KActivityLocationLatitude = "ActivityLocationLatitude" + const val KActivityLocationLongitude = "ActivityLocationLongitude" + const val KActivityLocationCount = "KActivityLocationCount" + + /* + * GET_SPORTMODEL_DATA + *@param Date 时间:年月日时分秒 + *@param ActivityMode 运动类型 + 0=Run, + 1=Cycling, + 2=Swimming, + 3=Badminton, + 4=Football, + 5=Tennis, + 6=Yoga, + 7=Medication, + 8=Dance + + *@param HeartRate 心率 + *@param ActiveMinutes 运动时间 + *@param Step 运动步数 + *@param Pace 运动速度 + *@param Calories 卡路里 + *@param Distance 距离 + */ + const val ActivityMode = "sportModel" + const val Pace = "sportModelSpeed" + const val KDataID = "KDataID" + const val KPhoneDataLength = "KPhoneDataLength" + const val KClockLast = "KClockLast" + const val TakePhotoMode = "TakePhotoMode" + const val KFunction_tel = "TelMode" + const val KFunction_reject_tel = "RejectTelMode" + const val FindMobilePhoneMode = "FindMobilePhoneMode" + const val KEnable_exercise = "KEnable_exercise" + const val ECGQualityValue = "ECGQualityValue" + const val ECGResultValue = "ECGResultVALUE" + const val ECGHrvValue = "ECGHrvValue" + const val ECGAvBlockValue = "ECGAvBlockValue" + const val ECGHrValue = "ECGHrValue" + const val PPGHrValue = "PPGHrValue" + const val ECGStreesValue = "ECGStreesValue" + const val ECGhighBpValue = "ECGhighBpValue" + const val ECGLowBpValue = "ECGLowBpValue" + const val ECGMoodValue = "ECGMoodValue" + const val ECGBreathValue = "ECGBreathValue" + const val KEcgDataString = "KEcgDataString" // ecg + const val ECGValue = "ECGValue" + const val PPGValue = "PPGValue" + const val EcgStatus = "EcgStatus" + const val EcgSBP = "PPGSBP" + const val EcgDBP = "PPGDBP" + const val EcgHR = "PPGHR" + const val WaveformDownTime = "WaveformDownTime" + const val WaveformRiseTime = "WaveformRiseTime" + const val EcgGender = "Gender" + const val EcgAge = "Age" + const val EcgHeight = "Height" + const val EcgWeight = "Weight" +} \ No newline at end of file diff --git a/android/blesdk_2301/src/main/java/com/jstyle/blesdk2301/model/AutoMode.java b/android/blesdk_2301/src/main/java/com/jstyle/blesdk2301/model/AutoMode.java deleted file mode 100644 index 63ab1b1a..00000000 --- a/android/blesdk_2301/src/main/java/com/jstyle/blesdk2301/model/AutoMode.java +++ /dev/null @@ -1,5 +0,0 @@ -package com.jstyle.blesdk2301.model; - -public enum AutoMode { - AutoHeartRate, AutoSpo2,AutoTemp,AutoHrv -} diff --git a/android/blesdk_2301/src/main/java/com/jstyle/blesdk2301/model/AutoMode.kt b/android/blesdk_2301/src/main/java/com/jstyle/blesdk2301/model/AutoMode.kt new file mode 100644 index 00000000..103c1a8b --- /dev/null +++ b/android/blesdk_2301/src/main/java/com/jstyle/blesdk2301/model/AutoMode.kt @@ -0,0 +1,5 @@ +package com.jstyle.blesdk2301.model + +enum class AutoMode { + AutoHeartRate, AutoSpo2, AutoTemp, AutoHrv +} \ No newline at end of file diff --git a/android/blesdk_2301/src/main/java/com/jstyle/blesdk2301/model/AutoTestMode.java b/android/blesdk_2301/src/main/java/com/jstyle/blesdk2301/model/AutoTestMode.java deleted file mode 100644 index a5dfae77..00000000 --- a/android/blesdk_2301/src/main/java/com/jstyle/blesdk2301/model/AutoTestMode.java +++ /dev/null @@ -1,5 +0,0 @@ -package com.jstyle.blesdk2301.model; - -public enum AutoTestMode { - AutoHeartRate, AutoSpo2, -} diff --git a/android/blesdk_2301/src/main/java/com/jstyle/blesdk2301/model/AutoTestMode.kt b/android/blesdk_2301/src/main/java/com/jstyle/blesdk2301/model/AutoTestMode.kt new file mode 100644 index 00000000..8a3c44e1 --- /dev/null +++ b/android/blesdk_2301/src/main/java/com/jstyle/blesdk2301/model/AutoTestMode.kt @@ -0,0 +1,5 @@ +package com.jstyle.blesdk2301.model + +enum class AutoTestMode { + AutoHeartRate, AutoSpo2 +} \ No newline at end of file diff --git a/android/blesdk_2301/src/main/java/com/jstyle/blesdk2301/model/Clock.java b/android/blesdk_2301/src/main/java/com/jstyle/blesdk2301/model/Clock.java deleted file mode 100644 index cc98963b..00000000 --- a/android/blesdk_2301/src/main/java/com/jstyle/blesdk2301/model/Clock.java +++ /dev/null @@ -1,87 +0,0 @@ -package com.jstyle.blesdk2301.model; - -import java.io.Serializable; - -/** - * Created by Administrator on 2018/1/16. - */ - -public class Clock extends SendData implements Serializable { - - int number; - int type; - int hour; - int minute; - byte week; - String content; - boolean enable; - - public boolean isEnable() { - return enable; - } - - public void setEnable(boolean enable) { - this.enable = enable; - } - - public String getContent() { - return content; - } - - public void setContent(String content) { - this.content = content; - } - - public int getNumber() { - return number; - } - - public void setNumber(int number) { - this.number = number; - } - - public int getType() { - return type; - } - - public void setType(int type) { - this.type = type; - } - - public int getHour() { - return hour; - } - - public void setHour(int hour) { - this.hour = hour; - } - - public int getMinute() { - return minute; - } - - public void setMinute(int minute) { - this.minute = minute; - } - - public int getWeek() { - return week; - } - - public void setWeek(byte week) { - this.week = week; - } - - @Override - public String toString() { - return "Clock{" + - "number=" + number + - ", type=" + type + - ", hour=" + hour + - ", minute=" + minute + - ", week=" + week + - ", content='" + content + '\'' + - ", enable=" + enable + - '}'; - } -} diff --git a/android/blesdk_2301/src/main/java/com/jstyle/blesdk2301/model/Clock.kt b/android/blesdk_2301/src/main/java/com/jstyle/blesdk2301/model/Clock.kt new file mode 100644 index 00000000..06d89337 --- /dev/null +++ b/android/blesdk_2301/src/main/java/com/jstyle/blesdk2301/model/Clock.kt @@ -0,0 +1,35 @@ +package com.jstyle.blesdk2301.model + +import java.io.Serializable + +/** + * Created by Administrator on 2018/1/16. + */ +class Clock : SendData(), Serializable { + var number = 0 + var type = 0 + var hour = 0 + var minute = 0 + var week: Byte = 0 + var content: String? = null + var isEnable = false + fun srgetWeek(): Int { + return week.toInt() + } + + fun srsetWeek(week: Byte) { + this.week = week + } + + override fun toString(): String { + return "Clock{" + + "number=" + number + + ", type=" + type + + ", hour=" + hour + + ", minute=" + minute + + ", week=" + week + + ", content='" + content + '\'' + + ", enable=" + isEnable + + '}' + } +} \ No newline at end of file diff --git a/android/blesdk_2301/src/main/java/com/jstyle/blesdk2301/model/Device.java b/android/blesdk_2301/src/main/java/com/jstyle/blesdk2301/model/Device.java deleted file mode 100644 index 451a61d2..00000000 --- a/android/blesdk_2301/src/main/java/com/jstyle/blesdk2301/model/Device.java +++ /dev/null @@ -1,103 +0,0 @@ -package com.jstyle.blesdk2301.model; - -import android.bluetooth.BluetoothDevice; - -import java.io.Serializable; -import java.util.concurrent.ScheduledThreadPoolExecutor; - - -public class Device implements Serializable{ - String name;//设备名字 - String mac;//设备的mac - int productID;//产品id,预留 - BluetoothDevice getBluetoothDevice;//蓝牙 - boolean isconted=false;//蓝牙是否连接 - boolean IsPaired=false;//是否是配对设备 - boolean isdfu=false;//是否直接升级 - int riss=100; - - public int getRiss() { - return riss; - } - - public void setRiss(int riss) { - this.riss = riss; - } - - ScheduledThreadPoolExecutor time=null;//每一个设备轮询器 - - public boolean isIsdfu() { - return isdfu; - } - - public void setIsdfu(boolean isdfu) { - this.isdfu = isdfu; - } - - public ScheduledThreadPoolExecutor getTime() { - return time; - } - - public void setTime(ScheduledThreadPoolExecutor time) { - this.time = time; - } - public boolean isPaired() { - return IsPaired; - } - - public void setPaired(boolean paired) { - IsPaired = paired; - } - - public boolean isIsconted() { - return isconted; - } - - public void setIsconted(boolean isconted) { - this.isconted = isconted; - } - - public String getName() { - return name==null?"":this.name; - } - - public void setName(String name) { - this.name = name; - } - - public String getMac() { - return mac==null?"":this.mac; - } - - public void setMac(String mac) { - this.mac = mac; - } - - public int getProductID() { - return productID; - } - - public void setProductID(int productID) { - this.productID = productID; - } - - public BluetoothDevice getBluetoothDevice() { - return getBluetoothDevice; - } - - public void setBluetoothDevice(BluetoothDevice bluetoothDevice) { - this.getBluetoothDevice = bluetoothDevice; - } - - - @Override - public String toString() { - return "Device{" + - "name='" + name + '\'' + - ", mac='" + mac + '\'' + - ", productID=" + productID + - ", getBluetoothDevice=" + getBluetoothDevice + - ", isconted=" + isconted + - '}'; - } -} diff --git a/android/blesdk_2301/src/main/java/com/jstyle/blesdk2301/model/Device.kt b/android/blesdk_2301/src/main/java/com/jstyle/blesdk2301/model/Device.kt new file mode 100644 index 00000000..c5be38cc --- /dev/null +++ b/android/blesdk_2301/src/main/java/com/jstyle/blesdk2301/model/Device.kt @@ -0,0 +1,50 @@ +package com.jstyle.blesdk2301.model + +import android.bluetooth.BluetoothDevice +import java.io.Serializable +import java.util.concurrent.ScheduledThreadPoolExecutor + +class Device : Serializable { + var name: String? = null //设备名字 + var mac: String? = null //设备的mac + var productID = 0 //产品id,预留 + var bluetoothDevice: BluetoothDevice? = null //蓝牙 + var isIsconted = false //蓝牙是否连接 + var isPaired = false //是否是配对设备 + var isIsdfu = false //是否直接升级 + var riss = 100 + var time: ScheduledThreadPoolExecutor? = null //每一个设备轮询器 + fun srsetIsdfu(isdfu: Boolean) { + isIsdfu = isdfu + } + + fun srsetIsconted(isconted: Boolean) { + isIsconted = isconted + } + + fun srgetName(): String { + return if (name == null) "" else name!! + } + + fun srsetName(name: String?) { + this.name = name + } + + fun srgetMac(): String { + return if (mac == null) "" else mac!! + } + + fun srsetMac(mac: String?) { + this.mac = mac + } + + override fun toString(): String { + return "Device{" + + "name='" + name + '\'' + + ", mac='" + mac + '\'' + + ", productID=" + productID + + ", getBluetoothDevice=" + bluetoothDevice + + ", isconted=" + isIsconted + + '}' + } +} \ No newline at end of file diff --git a/android/blesdk_2301/src/main/java/com/jstyle/blesdk2301/model/DeviceBean.java b/android/blesdk_2301/src/main/java/com/jstyle/blesdk2301/model/DeviceBean.java deleted file mode 100644 index a761263e..00000000 --- a/android/blesdk_2301/src/main/java/com/jstyle/blesdk2301/model/DeviceBean.java +++ /dev/null @@ -1,29 +0,0 @@ -package com.jstyle.blesdk2301.model; - -import java.util.List; -import java.util.Map; - -/** - * Created by Administrator on 2018/4/28. - */ - -public class DeviceBean { - List>dataList; - boolean finish; - - public List> getDataList() { - return dataList; - } - - public void setDataList(List> dataList) { - this.dataList = dataList; - } - - public boolean isFinish() { - return finish; - } - - public void setFinish(boolean finish) { - this.finish = finish; - } -} diff --git a/android/blesdk_2301/src/main/java/com/jstyle/blesdk2301/model/DeviceBean.kt b/android/blesdk_2301/src/main/java/com/jstyle/blesdk2301/model/DeviceBean.kt new file mode 100644 index 00000000..af1c3894 --- /dev/null +++ b/android/blesdk_2301/src/main/java/com/jstyle/blesdk2301/model/DeviceBean.kt @@ -0,0 +1,9 @@ +package com.jstyle.blesdk2301.model + +/** + * Created by Administrator on 2018/4/28. + */ +class DeviceBean { + var dataList: List>? = null + var isFinish = false +} \ No newline at end of file diff --git a/android/blesdk_2301/src/main/java/com/jstyle/blesdk2301/model/DeviceName.java b/android/blesdk_2301/src/main/java/com/jstyle/blesdk2301/model/DeviceName.java deleted file mode 100644 index 708cfeb5..00000000 --- a/android/blesdk_2301/src/main/java/com/jstyle/blesdk2301/model/DeviceName.java +++ /dev/null @@ -1,17 +0,0 @@ -package com.jstyle.blesdk2301.model; - -/** - * Created by Administrator on 2018/4/9. - */ - -public class DeviceName extends SendData{ - String name; - - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } -} diff --git a/android/blesdk_2301/src/main/java/com/jstyle/blesdk2301/model/DeviceName.kt b/android/blesdk_2301/src/main/java/com/jstyle/blesdk2301/model/DeviceName.kt new file mode 100644 index 00000000..187a17a6 --- /dev/null +++ b/android/blesdk_2301/src/main/java/com/jstyle/blesdk2301/model/DeviceName.kt @@ -0,0 +1,8 @@ +package com.jstyle.blesdk2301.model + +/** + * Created by Administrator on 2018/4/9. + */ +class DeviceName : SendData() { + var name: String? = null +} \ No newline at end of file diff --git a/android/blesdk_2301/src/main/java/com/jstyle/blesdk2301/model/ExerciseMode.java b/android/blesdk_2301/src/main/java/com/jstyle/blesdk2301/model/ExerciseMode.java deleted file mode 100644 index d91859a7..00000000 --- a/android/blesdk_2301/src/main/java/com/jstyle/blesdk2301/model/ExerciseMode.java +++ /dev/null @@ -1,56 +0,0 @@ -package com.jstyle.blesdk2301.model; - -/** - * Created by Administrator on 2018/8/2. - */ - -public class ExerciseMode extends SendData { - public static final int Status_START=1; - public static final int Status_PAUSE=2; - public static final int Status_CONTUINE=3; - public static final int Status_FINISH=4; - - public static final int Mode_RUN=0; - public static final int Mode_CYCLING=1; - public static final int Mode_BADMINTON=2; - public static final int Mode_FOOTBALL=3; - public static final int Mode_TENNIS=4; - public static final int Mode_YOGA=5; - public static final int Mode_BREATH=6; - public static final int Mode_DANCE=7; - public static final int Mode_BASKETBALL=8; - public static final int Mode_Walk=9; - public static final int Mode_workout=10; - public static final int Mode_Cricket=11; - public static final int Mode_Hiking=12; - public static final int Mode_Aerobics=13; - public static final int Mode_PingPong=14; - public static final int Mode_RopeJump=15; - public static final int Mode_Situps=16; - public static final int Volleyball=17; - - - public static int[]modes=new int[]{Mode_RUN,Mode_CYCLING,Mode_BADMINTON,Mode_FOOTBALL, - Mode_TENNIS,Mode_YOGA,Mode_BREATH,Mode_DANCE,Mode_BASKETBALL,Mode_Walk,Mode_workout - ,Mode_Cricket,Mode_Hiking,Mode_Aerobics,Mode_PingPong, Mode_RopeJump,Mode_Situps,Volleyball}; - int exerciseMode; - int enableStatus; - public int getExerciseMode(int position){ - return modes[position]; - } - public int getExerciseMode() { - return exerciseMode; - } - - public void setExerciseMode(int exerciseMode) { - this.exerciseMode = exerciseMode; - } - - public int getEnableStatus() { - return enableStatus; - } - - public void setEnableStatus(int enableStatus) { - this.enableStatus = enableStatus; - } -} diff --git a/android/blesdk_2301/src/main/java/com/jstyle/blesdk2301/model/ExerciseMode.kt b/android/blesdk_2301/src/main/java/com/jstyle/blesdk2301/model/ExerciseMode.kt new file mode 100644 index 00000000..5017fa2d --- /dev/null +++ b/android/blesdk_2301/src/main/java/com/jstyle/blesdk2301/model/ExerciseMode.kt @@ -0,0 +1,41 @@ +package com.jstyle.blesdk2301.model + +/** + * Created by Administrator on 2018/8/2. + */ +class ExerciseMode : SendData() { + var exerciseMode = 0 + var enableStatus = 0 + fun getExerciseMode(position: Int): Int { + return modes[position] + } + + companion object { + const val Status_START = 1 + const val Status_PAUSE = 2 + const val Status_CONTUINE = 3 + const val Status_FINISH = 4 + const val Mode_RUN = 0 + const val Mode_CYCLING = 1 + const val Mode_BADMINTON = 2 + const val Mode_FOOTBALL = 3 + const val Mode_TENNIS = 4 + const val Mode_YOGA = 5 + const val Mode_BREATH = 6 + const val Mode_DANCE = 7 + const val Mode_BASKETBALL = 8 + const val Mode_Walk = 9 + const val Mode_workout = 10 + const val Mode_Cricket = 11 + const val Mode_Hiking = 12 + const val Mode_Aerobics = 13 + const val Mode_PingPong = 14 + const val Mode_RopeJump = 15 + const val Mode_Situps = 16 + const val Volleyball = 17 + var modes = intArrayOf( + Mode_RUN, Mode_CYCLING, Mode_BADMINTON, Mode_FOOTBALL, + Mode_TENNIS, Mode_YOGA, Mode_BREATH, Mode_DANCE, Mode_BASKETBALL, Mode_Walk, Mode_workout, Mode_Cricket, Mode_Hiking, Mode_Aerobics, Mode_PingPong, Mode_RopeJump, Mode_Situps, Volleyball + ) + } +} \ No newline at end of file diff --git a/android/blesdk_2301/src/main/java/com/jstyle/blesdk2301/model/ExtendedBluetoothDevice.java b/android/blesdk_2301/src/main/java/com/jstyle/blesdk2301/model/ExtendedBluetoothDevice.kt similarity index 64% rename from android/blesdk_2301/src/main/java/com/jstyle/blesdk2301/model/ExtendedBluetoothDevice.java rename to android/blesdk_2301/src/main/java/com/jstyle/blesdk2301/model/ExtendedBluetoothDevice.kt index b27b5a2e..382a47ec 100644 --- a/android/blesdk_2301/src/main/java/com/jstyle/blesdk2301/model/ExtendedBluetoothDevice.java +++ b/android/blesdk_2301/src/main/java/com/jstyle/blesdk2301/model/ExtendedBluetoothDevice.kt @@ -1,50 +1,53 @@ -/* - * Copyright (c) 2015, Nordic Semiconductor - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. - * - * 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this - * software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT - * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT - * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON - * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE - * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ -package com.jstyle.blesdk2301.model; - -import android.bluetooth.BluetoothDevice; - - -public class ExtendedBluetoothDevice { - /* package */public static final int NO_RSSI = -1000; - public final BluetoothDevice device; - /** The name is not parsed by some Android devices, f.e. Sony Xperia Z1 with Android 4.3 (C6903). It needs to be parsed manually. */ - public String name; - public int rssi; - - - public ExtendedBluetoothDevice(BluetoothDevice device, String name, int rssi) { - this.device = device; - this.name = name; - this.rssi=rssi; - } - - public ExtendedBluetoothDevice(final BluetoothDevice device) { - this.device = device; - this.name = device.getName(); - this.rssi = NO_RSSI; - } - - public boolean matches(final BluetoothDevice mdevice) { - return device.getAddress().equals(mdevice.getAddress()); - } -} +/* + * Copyright (c) 2015, Nordic Semiconductor + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this + * software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON + * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE + * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ +package com.jstyle.blesdk2301.model + +import android.bluetooth.BluetoothDevice + +class ExtendedBluetoothDevice { + val device: BluetoothDevice + + /** The name is not parsed by some Android devices, f.e. Sony Xperia Z1 with Android 4.3 (C6903). It needs to be parsed manually. */ + var name: String + var rssi: Int + + constructor(device: BluetoothDevice, name: String, rssi: Int) { + this.device = device + this.name = name + this.rssi = rssi + } + + constructor(device: BluetoothDevice) { + this.device = device + name = device.name + rssi = NO_RSSI + } + + fun matches(mdevice: BluetoothDevice): Boolean { + return device.address == mdevice.address + } + + companion object { + /* package */ + const val NO_RSSI = -1000 + } +} \ No newline at end of file diff --git a/android/blesdk_2301/src/main/java/com/jstyle/blesdk2301/model/GetData.java b/android/blesdk_2301/src/main/java/com/jstyle/blesdk2301/model/GetData.java deleted file mode 100644 index e970b018..00000000 --- a/android/blesdk_2301/src/main/java/com/jstyle/blesdk2301/model/GetData.java +++ /dev/null @@ -1,22 +0,0 @@ -package com.jstyle.blesdk2301.model; - -/** - * Created by Administrator on 2018/4/9. - */ - -public class GetData extends SendData{ - public final static byte DataNum_Delete= (byte) 0x99; - public final static int DataNum_Last=0; - /** - * 99删除数据,0获取数据 - */ - int dataNum=DataNum_Last; - - public int getDataNum() { - return dataNum; - } - - public void setDataNum(int dataNum) { - this.dataNum = dataNum; - } -} diff --git a/android/blesdk_2301/src/main/java/com/jstyle/blesdk2301/model/GetData.kt b/android/blesdk_2301/src/main/java/com/jstyle/blesdk2301/model/GetData.kt new file mode 100644 index 00000000..26fefd9a --- /dev/null +++ b/android/blesdk_2301/src/main/java/com/jstyle/blesdk2301/model/GetData.kt @@ -0,0 +1,16 @@ +package com.jstyle.blesdk2301.model + +/** + * Created by Administrator on 2018/4/9. + */ +class GetData : SendData() { + /** + * 99删除数据,0获取数据 + */ + var dataNum = DataNum_Last + + companion object { + const val DataNum_Delete = 0x99.toByte() + const val DataNum_Last = 0 + } +} \ No newline at end of file diff --git a/android/blesdk_2301/src/main/java/com/jstyle/blesdk2301/model/MyAutomaticHRMonitoring.java b/android/blesdk_2301/src/main/java/com/jstyle/blesdk2301/model/MyAutomaticHRMonitoring.java deleted file mode 100644 index e2f5d95c..00000000 --- a/android/blesdk_2301/src/main/java/com/jstyle/blesdk2301/model/MyAutomaticHRMonitoring.java +++ /dev/null @@ -1,85 +0,0 @@ -package com.jstyle.blesdk2301.model; - -/** - * Created by Administrator on 2018/1/16. - */ - -public class MyAutomaticHRMonitoring extends SendData{ - int open;//1 开启整个时间段都测量 2时间段内间隔测量 0关闭 - // 1. Enable measurement throughout the entire time period 2. Measure intervals within the time period 0. Close - int startHour;//开始小时 Starting hours - int startMinute;//开始分钟 Start minute - int endHour;//结束小时 End Hour - int endMinute;//结束分钟 End minute - int week;//星期一到星期日 开启选择 Monday to Sunday open selection - int time;//多少时间测试一次,单位是分钟。 How many times does it take to test, in minutes. - - public int getTime() { - return time; - } - - public void setTime(int time) { - this.time = time; - } - - public int getOpen() { - return open; - } - - public void setOpen(int open) { - this.open = open; - } - - public int getStartHour() { - return startHour; - } - - public void setStartHour(int startHour) { - this.startHour = startHour; - } - - public int getStartMinute() { - return startMinute; - } - - public void setStartMinute(int startMinute) { - this.startMinute = startMinute; - } - - public int getEndHour() { - return endHour; - } - - public void setEndHour(int endHour) { - this.endHour = endHour; - } - - public int getEndMinute() { - return endMinute; - } - - public void setEndMinute(int endMinute) { - this.endMinute = endMinute; - } - - public int getWeek() { - return week; - } - - public void setWeek(int week) { - this.week = week; - } - - @Override - public String toString() { - return "MyAutomaticHRMonitoring{" + - "open=" + open + - ", startHour=" + startHour + - ", startMinute=" + startMinute + - ", endHour=" + endHour + - ", endMinute=" + endMinute + - ", week=" + week + - ", time=" + time + - '}'; - } -} diff --git a/android/blesdk_2301/src/main/java/com/jstyle/blesdk2301/model/MyAutomaticHRMonitoring.kt b/android/blesdk_2301/src/main/java/com/jstyle/blesdk2301/model/MyAutomaticHRMonitoring.kt new file mode 100644 index 00000000..3d0f9c4a --- /dev/null +++ b/android/blesdk_2301/src/main/java/com/jstyle/blesdk2301/model/MyAutomaticHRMonitoring.kt @@ -0,0 +1,27 @@ +package com.jstyle.blesdk2301.model + +/** + * Created by Administrator on 2018/1/16. + */ +class MyAutomaticHRMonitoring : SendData() { + var open = 0 //1 开启整个时间段都测量 2时间段内间隔测量 0关闭 + + // 1. Enable measurement throughout the entire time period 2. Measure intervals within the time period 0. Close + var startHour = 0 //开始小时 Starting hours + var startMinute = 0 //开始分钟 Start minute + var endHour = 0 //结束小时 End Hour + var endMinute = 0 //结束分钟 End minute + var week = 0 //星期一到星期日 开启选择 Monday to Sunday open selection + var time = 0 //多少时间测试一次,单位是分钟。 How many times does it take to test, in minutes. + override fun toString(): String { + return "MyAutomaticHRMonitoring{" + + "open=" + open + + ", startHour=" + startHour + + ", startMinute=" + startMinute + + ", endHour=" + endHour + + ", endMinute=" + endMinute + + ", week=" + week + + ", time=" + time + + '}' + } +} \ No newline at end of file diff --git a/android/blesdk_2301/src/main/java/com/jstyle/blesdk2301/model/MyDeviceInfo.java b/android/blesdk_2301/src/main/java/com/jstyle/blesdk2301/model/MyDeviceInfo.java deleted file mode 100644 index 2de5df25..00000000 --- a/android/blesdk_2301/src/main/java/com/jstyle/blesdk2301/model/MyDeviceInfo.java +++ /dev/null @@ -1,117 +0,0 @@ -package com.jstyle.blesdk2301.model; - -/** - * Created by Administrator on 2018/4/9. - */ - -public class MyDeviceInfo extends SendData{ - - boolean DistanceUnit;//1 mile(true),0km(false) - boolean is12Hour;//1(12小时)(true),0(24小时制)(false) - boolean Bright_screen;//1 turn on the bright screen, 0 turn off the bright screen - boolean Fahrenheit_or_centigrade;//Fahrenheit or centigrade - boolean isHorizontalScreen;//1 Horizontal screen, 0 Vertical screen - boolean Night_mode;//夜间模式 - boolean Temperature_unit;//夜间模式 - boolean Social_distance_switch;//社交距离开关 Social distance switch - int LauageNumber=-1;//中英文切换 Chinese_English_switch - int baseheart=60;//Basic heart rate - int ScreenBrightness=-1;//Screen brightness 屏幕亮度0-5 - int Dialinterface=-1;//表盘更换 Dial replacement 0-10 - - public boolean isTemperature_unit() { - return Temperature_unit; - } - - public void setTemperature_unit(boolean temperature_unit) { - Temperature_unit = temperature_unit; - } - - public int getLauageNumber() { - return LauageNumber; - } - - public void setLauageNumber(int lauageNumber) { - LauageNumber = lauageNumber; - } - - public boolean isSocial_distance_switch() { - return Social_distance_switch; - } - - public void setSocial_distance_switch(boolean social_distance_switch) { - Social_distance_switch = social_distance_switch; - } - - public boolean isNight_mode() { - return Night_mode; - } - - public void setNight_mode(boolean night_mode) { - Night_mode = night_mode; - } - - public boolean isDistanceUnit() { - return DistanceUnit; - } - - public void setDistanceUnit(boolean distanceUnit) { - DistanceUnit = distanceUnit; - } - - public boolean isIs12Hour() { - return is12Hour; - } - - public void setIs12Hour(boolean is12Hour) { - this.is12Hour = is12Hour; - } - - public boolean isBright_screen() { - return Bright_screen; - } - - public void setBright_screen(boolean bright_screen) { - Bright_screen = bright_screen; - } - - public boolean isFahrenheit_or_centigrade() { - return Fahrenheit_or_centigrade; - } - - public void setFahrenheit_or_centigrade(boolean fahrenheit_or_centigrade) { - Fahrenheit_or_centigrade = fahrenheit_or_centigrade; - } - - public boolean isHorizontalScreen() { - return isHorizontalScreen; - } - - public void setHorizontalScreen(boolean horizontalScreen) { - isHorizontalScreen = horizontalScreen; - } - - public int getBaseheart() { - return baseheart; - } - - public void setBaseheart(int baseheart) { - this.baseheart = baseheart; - } - - public int getScreenBrightness() { - return ScreenBrightness; - } - - public void setScreenBrightness(int screenBrightness) { - ScreenBrightness = screenBrightness; - } - - public int getDialinterface() { - return Dialinterface; - } - - public void setDialinterface(int dialinterface) { - Dialinterface = dialinterface; - } -} diff --git a/android/blesdk_2301/src/main/java/com/jstyle/blesdk2301/model/MyDeviceInfo.kt b/android/blesdk_2301/src/main/java/com/jstyle/blesdk2301/model/MyDeviceInfo.kt new file mode 100644 index 00000000..ea558eab --- /dev/null +++ b/android/blesdk_2301/src/main/java/com/jstyle/blesdk2301/model/MyDeviceInfo.kt @@ -0,0 +1,22 @@ +package com.jstyle.blesdk2301.model + +/** + * Created by Administrator on 2018/4/9. + */ +class MyDeviceInfo : SendData() { + var isDistanceUnit = false //1 mile(true),0km(false) + var isIs12Hour = false //1(12小时)(true),0(24小时制)(false) + var isBright_screen = false //1 turn on the bright screen, 0 turn off the bright screen + var isFahrenheit_or_centigrade = false //Fahrenheit or centigrade + var isHorizontalScreen = false //1 Horizontal screen, 0 Vertical screen + var isNight_mode = false //夜间模式 + var isTemperature_unit = false //夜间模式 + var isSocial_distance_switch = false //社交距离开关 Social distance switch + var lauageNumber = -1 //中英文切换 Chinese_English_switch + var baseheart = 60 //Basic heart rate + var screenBrightness = -1 //Screen brightness 屏幕亮度0-5 + var dialinterface = -1 //表盘更换 Dial replacement 0-10 + fun srsetIs12Hour(is12Hour: Boolean) { + isIs12Hour = is12Hour + } +} \ No newline at end of file diff --git a/android/blesdk_2301/src/main/java/com/jstyle/blesdk2301/model/MyDeviceTime.java b/android/blesdk_2301/src/main/java/com/jstyle/blesdk2301/model/MyDeviceTime.java deleted file mode 100644 index 0adc63f1..00000000 --- a/android/blesdk_2301/src/main/java/com/jstyle/blesdk2301/model/MyDeviceTime.java +++ /dev/null @@ -1,86 +0,0 @@ -package com.jstyle.blesdk2301.model; - -import java.util.Calendar; - -/** - * Created by Administrator on 2018/1/16. - */ - -public class MyDeviceTime extends SendData{ - int year; - int month; - int day; - int hour; - int minute; - int second; - - public MyDeviceTime() { - Calendar calendar=Calendar.getInstance(); - this.year=calendar.get(Calendar.YEAR); - this.month=calendar.get(Calendar.MONTH)+1; - this.day=calendar.get(Calendar.DAY_OF_MONTH); - this.hour=calendar.get(Calendar.HOUR_OF_DAY); - this.minute=calendar.get(Calendar.MINUTE); - this.second=calendar.get(Calendar.SECOND); - } - - public int getYear() { - return year; - } - - public void setYear(int year) { - this.year = year; - } - - public int getMonth() { - return month; - } - - public void setMonth(int month) { - this.month = month; - } - - public int getDay() { - return day; - } - - public void setDay(int day) { - this.day = day; - } - - public int getHour() { - return hour; - } - - public void setHour(int hour) { - this.hour = hour; - } - - public int getMinute() { - return minute; - } - - public void setMinute(int minute) { - this.minute = minute; - } - - public int getSecond() { - return second; - } - - public void setSecond(int second) { - this.second = second; - } - - @Override - public String toString() { - return "MyDeviceTime{" + - "year=" + year + - ", month=" + month + - ", day=" + day + - ", hour=" + hour + - ", minute=" + minute + - ", second=" + second + - '}'; - } -} diff --git a/android/blesdk_2301/src/main/java/com/jstyle/blesdk2301/model/MyDeviceTime.kt b/android/blesdk_2301/src/main/java/com/jstyle/blesdk2301/model/MyDeviceTime.kt new file mode 100644 index 00000000..8024f624 --- /dev/null +++ b/android/blesdk_2301/src/main/java/com/jstyle/blesdk2301/model/MyDeviceTime.kt @@ -0,0 +1,36 @@ +package com.jstyle.blesdk2301.model + +import java.util.Calendar + +/** + * Created by Administrator on 2018/1/16. + */ +class MyDeviceTime : SendData() { + var year: Int + var month: Int + var day: Int + var hour: Int + var minute: Int + var second: Int + + init { + val calendar = Calendar.getInstance() + year = calendar[Calendar.YEAR] + month = calendar[Calendar.MONTH] + 1 + day = calendar[Calendar.DAY_OF_MONTH] + hour = calendar[Calendar.HOUR_OF_DAY] + minute = calendar[Calendar.MINUTE] + second = calendar[Calendar.SECOND] + } + + override fun toString(): String { + return "MyDeviceTime{" + + "year=" + year + + ", month=" + month + + ", day=" + day + + ", hour=" + hour + + ", minute=" + minute + + ", second=" + second + + '}' + } +} \ No newline at end of file diff --git a/android/blesdk_2301/src/main/java/com/jstyle/blesdk2301/model/MyPersonalInfo.java b/android/blesdk_2301/src/main/java/com/jstyle/blesdk2301/model/MyPersonalInfo.java deleted file mode 100644 index ffabc810..00000000 --- a/android/blesdk_2301/src/main/java/com/jstyle/blesdk2301/model/MyPersonalInfo.java +++ /dev/null @@ -1,66 +0,0 @@ -package com.jstyle.blesdk2301.model; - -/** - * Created by Administrator on 2018/1/16. - */ - -public class MyPersonalInfo extends SendData{ - int sex;//1 male,0female - int age; - int height; - int weight; - int stepLength=70; - - - - public int getSex() { - return sex; - } - - public void setSex(int sex) { - this.sex = sex; - } - - public int getAge() { - return age; - } - - public void setAge(int age) { - this.age = age; - } - - public int getHeight() { - return height; - } - - public void setHeight(int height) { - this.height = height; - } - - public int getWeight() { - return weight; - } - - public void setWeight(int weight) { - this.weight = weight; - } - - public int getStepLength() { - return stepLength; - } - - public void setStepLength(int stepLength) { - this.stepLength = stepLength; - } - - @Override - public String toString() { - return "MyPersonalInfo{" + - "sex=" + sex + - ", age=" + age + - ", height=" + height + - ", weight=" + weight + - ", stepLength=" + stepLength + - '}'; - } -} diff --git a/android/blesdk_2301/src/main/java/com/jstyle/blesdk2301/model/MyPersonalInfo.kt b/android/blesdk_2301/src/main/java/com/jstyle/blesdk2301/model/MyPersonalInfo.kt new file mode 100644 index 00000000..4ea4ba2f --- /dev/null +++ b/android/blesdk_2301/src/main/java/com/jstyle/blesdk2301/model/MyPersonalInfo.kt @@ -0,0 +1,21 @@ +package com.jstyle.blesdk2301.model + +/** + * Created by Administrator on 2018/1/16. + */ +class MyPersonalInfo : SendData() { + var sex = 0 //1 male,0female + var age = 0 + var height = 0 + var weight = 0 + var stepLength = 70 + override fun toString(): String { + return "MyPersonalInfo{" + + "sex=" + sex + + ", age=" + age + + ", height=" + height + + ", weight=" + weight + + ", stepLength=" + stepLength + + '}' + } +} \ No newline at end of file diff --git a/android/blesdk_2301/src/main/java/com/jstyle/blesdk2301/model/MySedentaryReminder.java b/android/blesdk_2301/src/main/java/com/jstyle/blesdk2301/model/MySedentaryReminder.java deleted file mode 100644 index f2259639..00000000 --- a/android/blesdk_2301/src/main/java/com/jstyle/blesdk2301/model/MySedentaryReminder.java +++ /dev/null @@ -1,94 +0,0 @@ -package com.jstyle.blesdk2301.model; - -/** - * Created by Administrator on 2018/1/16. - */ - -public class MySedentaryReminder extends SendData{ - int startHour; - int startMinute; - int endHour; - int endMinute; - int week; - int intervalTime; - int leastStep; - boolean enable; - - public boolean isEnable() { - return enable; - } - - public void setEnable(boolean enable) { - this.enable = enable; - } - - public int getStartHour() { - return startHour; - } - - public void setStartHour(int startHour) { - this.startHour = startHour; - } - - public int getStartMinute() { - return startMinute; - } - - public void setStartMinute(int startMinute) { - this.startMinute = startMinute; - } - - public int getEndHour() { - return endHour; - } - - public void setEndHour(int endHour) { - this.endHour = endHour; - } - - public int getEndMinute() { - return endMinute; - } - - public void setEndMinute(int endMinute) { - this.endMinute = endMinute; - } - - public int getWeek() { - return week; - } - - public void setWeek(int week) { - this.week = week; - } - - public int getIntervalTime() { - return intervalTime; - } - - public void setIntervalTime(int intervalTime) { - this.intervalTime = intervalTime; - } - - public int getLeastStep() { - return leastStep; - } - - public void setLeastStep(int leastStep) { - this.leastStep = leastStep; - } - - @Override - public String toString() { - return "MySedentaryReminder{" + - "startHour=" + startHour + - ", startMinute=" + startMinute + - ", endHour=" + endHour + - ", endMinute=" + endMinute + - ", week=" + week + - ", intervalTime=" + intervalTime + - ", leastStep=" + leastStep + - ", enable=" + enable + - '}'; - } -} diff --git a/android/blesdk_2301/src/main/java/com/jstyle/blesdk2301/model/MySedentaryReminder.kt b/android/blesdk_2301/src/main/java/com/jstyle/blesdk2301/model/MySedentaryReminder.kt new file mode 100644 index 00000000..0024735f --- /dev/null +++ b/android/blesdk_2301/src/main/java/com/jstyle/blesdk2301/model/MySedentaryReminder.kt @@ -0,0 +1,27 @@ +package com.jstyle.blesdk2301.model + +/** + * Created by Administrator on 2018/1/16. + */ +class MySedentaryReminder : SendData() { + var startHour = 0 + var startMinute = 0 + var endHour = 0 + var endMinute = 0 + var week = 0 + var intervalTime = 0 + var leastStep = 0 + var isEnable = false + override fun toString(): String { + return "MySedentaryReminder{" + + "startHour=" + startHour + + ", startMinute=" + startMinute + + ", endHour=" + endHour + + ", endMinute=" + endMinute + + ", week=" + week + + ", intervalTime=" + intervalTime + + ", leastStep=" + leastStep + + ", enable=" + isEnable + + '}' + } +} \ No newline at end of file diff --git a/android/blesdk_2301/src/main/java/com/jstyle/blesdk2301/model/Notifier.java b/android/blesdk_2301/src/main/java/com/jstyle/blesdk2301/model/Notifier.java deleted file mode 100644 index f89f0096..00000000 --- a/android/blesdk_2301/src/main/java/com/jstyle/blesdk2301/model/Notifier.java +++ /dev/null @@ -1,58 +0,0 @@ -package com.jstyle.blesdk2301.model; - -/** - * Created by Administrator on 2018/1/16. - */ - -public class Notifier extends SendData{ - public static final int Data_Tel=0; - public static final int Data_Sms=1; - public static final int Data_WeChat=2; - public static final int Data_Facebook=3; - public static final int Data_Instagram=4; - public static final int Data_Skype=5; - public static final int Data_Telegram=6; - public static final int Data_Twitter=7; - public static final int Data_Vkclient=8; - public static final int Data_WhatApp=9; - public static final int Data_QQ=10; - public static final int Data_IN=11; - public static final int Data_Stop_Tel=0xff; - - int type; - String info=""; - String title=""; - - public String getTitle() { - return title; - } - - public void setTitle(String title) { - this.title = title; - } - - public int getType() { - return type; - } - - public void setType(int type) { - this.type = type; - } - - public String getInfo() { - return info; - } - - public void setInfo(String info) { - this.info = info; - } - - @Override - public String toString() { - return "Notifier{" + - "type=" + type + - ", info='" + info + '\'' + - ", title='" + title + '\'' + - '}'; - } -} diff --git a/android/blesdk_2301/src/main/java/com/jstyle/blesdk2301/model/Notifier.kt b/android/blesdk_2301/src/main/java/com/jstyle/blesdk2301/model/Notifier.kt new file mode 100644 index 00000000..02d86037 --- /dev/null +++ b/android/blesdk_2301/src/main/java/com/jstyle/blesdk2301/model/Notifier.kt @@ -0,0 +1,33 @@ +package com.jstyle.blesdk2301.model + +/** + * Created by Administrator on 2018/1/16. + */ +class Notifier : SendData() { + var type = 0 + var info = "" + var title = "" + override fun toString(): String { + return "Notifier{" + + "type=" + type + + ", info='" + info + '\'' + + ", title='" + title + '\'' + + '}' + } + + companion object { + const val Data_Tel = 0 + const val Data_Sms = 1 + const val Data_WeChat = 2 + const val Data_Facebook = 3 + const val Data_Instagram = 4 + const val Data_Skype = 5 + const val Data_Telegram = 6 + const val Data_Twitter = 7 + const val Data_Vkclient = 8 + const val Data_WhatApp = 9 + const val Data_QQ = 10 + const val Data_IN = 11 + const val Data_Stop_Tel = 0xff + } +} \ No newline at end of file diff --git a/android/blesdk_2301/src/main/java/com/jstyle/blesdk2301/model/PregnancyCycle.java b/android/blesdk_2301/src/main/java/com/jstyle/blesdk2301/model/PregnancyCycle.java deleted file mode 100644 index 6b17ae2a..00000000 --- a/android/blesdk_2301/src/main/java/com/jstyle/blesdk2301/model/PregnancyCycle.java +++ /dev/null @@ -1,86 +0,0 @@ -package com.jstyle.blesdk2301.model; - - - -/** - * 怀孕周期 - * 算法 开始到生产 280天 每7天算一周 - */ - -public class PregnancyCycle { - String address=""; - String userId=""; - String MenstrualPeriod_StartTime="1990-01-01";//经期开始时间 yyyy-MM-dd - String DueDateTime="";//预产期 - long MenstrualPeriod_Period=30;//经期周期,默认30天 21-35 - - - public PregnancyCycle() { - } - - - public PregnancyCycle(String address, String userId, - String MenstrualPeriod_StartTime, String DueDateTime, - long MenstrualPeriod_Period) { - this.address = address; - this.userId = userId; - this.MenstrualPeriod_StartTime = MenstrualPeriod_StartTime; - this.DueDateTime = DueDateTime; - this.MenstrualPeriod_Period = MenstrualPeriod_Period; - } - - - public String getUserId() { - return userId; - } - - public void setUserId(String userId) { - this.userId = userId; - } - - public String getMenstrualPeriod_StartTime() { - return MenstrualPeriod_StartTime; - } - - public void setMenstrualPeriod_StartTime(String menstrualPeriod_StartTime) { - MenstrualPeriod_StartTime = menstrualPeriod_StartTime; - } - - public String getDueDateTime() { - return DueDateTime; - } - - public void setDueDateTime(String dueDateTime) { - DueDateTime = dueDateTime; - } - - public long getMenstrualPeriod_Period() { - return MenstrualPeriod_Period; - } - - public void setMenstrualPeriod_Period(long menstrualPeriod_Period) { - MenstrualPeriod_Period = menstrualPeriod_Period; - } - - public String getAddress() { - return address; - } - - public void setAddress(String address) { - this.address = address; - } - - @Override - public String toString() { - return "PregnancyCycle{" + - "address='" + address + '\'' + - ", userId='" + userId + '\'' + - ", MenstrualPeriod_StartTime='" + MenstrualPeriod_StartTime + '\'' + - ", DueDateTime='" + DueDateTime + '\'' + - ", MenstrualPeriod_Period=" + MenstrualPeriod_Period + - '}'; - } -} - - - diff --git a/android/blesdk_2301/src/main/java/com/jstyle/blesdk2301/model/PregnancyCycle.kt b/android/blesdk_2301/src/main/java/com/jstyle/blesdk2301/model/PregnancyCycle.kt new file mode 100644 index 00000000..e2b3e016 --- /dev/null +++ b/android/blesdk_2301/src/main/java/com/jstyle/blesdk2301/model/PregnancyCycle.kt @@ -0,0 +1,36 @@ +package com.jstyle.blesdk2301.model + +/** + * 怀孕周期 + * 算法 开始到生产 280天 每7天算一周 + */ +class PregnancyCycle { + var address = "" + var userId = "" + var menstrualPeriod_StartTime = "1990-01-01" //经期开始时间 yyyy-MM-dd + var dueDateTime = "" //预产期 + var menstrualPeriod_Period: Long = 30 //经期周期,默认30天 21-35 + + constructor() + constructor( + address: String, userId: String, + MenstrualPeriod_StartTime: String, DueDateTime: String, + MenstrualPeriod_Period: Long + ) { + this.address = address + this.userId = userId + menstrualPeriod_StartTime = MenstrualPeriod_StartTime + dueDateTime = DueDateTime + menstrualPeriod_Period = MenstrualPeriod_Period + } + + override fun toString(): String { + return "PregnancyCycle{" + + "address='" + address + '\'' + + ", userId='" + userId + '\'' + + ", MenstrualPeriod_StartTime='" + menstrualPeriod_StartTime + '\'' + + ", DueDateTime='" + dueDateTime + '\'' + + ", MenstrualPeriod_Period=" + menstrualPeriod_Period + + '}' + } +} \ No newline at end of file diff --git a/android/blesdk_2301/src/main/java/com/jstyle/blesdk2301/model/SendData.java b/android/blesdk_2301/src/main/java/com/jstyle/blesdk2301/model/SendData.java deleted file mode 100644 index 12414ad3..00000000 --- a/android/blesdk_2301/src/main/java/com/jstyle/blesdk2301/model/SendData.java +++ /dev/null @@ -1,8 +0,0 @@ -package com.jstyle.blesdk2301.model; - -/** - * Created by Administrator on 2018/4/8. - */ - -public class SendData { -} diff --git a/android/blesdk_2301/src/main/java/com/jstyle/blesdk2301/model/SendData.kt b/android/blesdk_2301/src/main/java/com/jstyle/blesdk2301/model/SendData.kt new file mode 100644 index 00000000..ada386ee --- /dev/null +++ b/android/blesdk_2301/src/main/java/com/jstyle/blesdk2301/model/SendData.kt @@ -0,0 +1,6 @@ +package com.jstyle.blesdk2301.model + +/** + * Created by Administrator on 2018/4/8. + */ +open class SendData \ No newline at end of file diff --git a/android/blesdk_2301/src/main/java/com/jstyle/blesdk2301/model/SportPeriod.java b/android/blesdk_2301/src/main/java/com/jstyle/blesdk2301/model/SportPeriod.java deleted file mode 100644 index 4ba7cb24..00000000 --- a/android/blesdk_2301/src/main/java/com/jstyle/blesdk2301/model/SportPeriod.java +++ /dev/null @@ -1,89 +0,0 @@ -package com.jstyle.blesdk2301.model; - -/** - * Created by Administrator on 2018/1/16. - */ - -public class SportPeriod extends SendData { - int startHour; - int startMinute; - int endHour; - int endMinute; - int week; - int days; - int intervalTime; - int leastStep; - boolean enable; - - public boolean isEnable() { - return enable; - } - - public void setEnable(boolean enable) { - this.enable = enable; - } - - public int getStartHour() { - return startHour; - } - - public void setStartHour(int startHour) { - this.startHour = startHour; - } - - public int getStartMinute() { - return startMinute; - } - - public void setStartMinute(int startMinute) { - this.startMinute = startMinute; - } - - public int getEndHour() { - return endHour; - } - - public void setEndHour(int endHour) { - this.endHour = endHour; - } - - public int getEndMinute() { - return endMinute; - } - - public void setEndMinute(int endMinute) { - this.endMinute = endMinute; - } - - public int getWeek() { - return week; - } - - public void setWeek(int week) { - this.week = week; - } - - public int getIntervalTime() { - return intervalTime; - } - - public void setIntervalTime(int intervalTime) { - this.intervalTime = intervalTime; - } - - public int getLeastStep() { - return leastStep; - } - - public void setLeastStep(int leastStep) { - this.leastStep = leastStep; - } - - public int getDays() { - return days; - } - - public void setDays(int days) { - this.days = days; - } -} diff --git a/android/blesdk_2301/src/main/java/com/jstyle/blesdk2301/model/SportPeriod.kt b/android/blesdk_2301/src/main/java/com/jstyle/blesdk2301/model/SportPeriod.kt new file mode 100644 index 00000000..ae258081 --- /dev/null +++ b/android/blesdk_2301/src/main/java/com/jstyle/blesdk2301/model/SportPeriod.kt @@ -0,0 +1,16 @@ +package com.jstyle.blesdk2301.model + +/** + * Created by Administrator on 2018/1/16. + */ +class SportPeriod : SendData() { + var startHour = 0 + var startMinute = 0 + var endHour = 0 + var endMinute = 0 + var week = 0 + var days = 0 + var intervalTime = 0 + var leastStep = 0 + var isEnable = false +} \ No newline at end of file diff --git a/android/blesdk_2301/src/main/java/com/jstyle/blesdk2301/model/StepModel.java b/android/blesdk_2301/src/main/java/com/jstyle/blesdk2301/model/StepModel.java deleted file mode 100644 index f40b862d..00000000 --- a/android/blesdk_2301/src/main/java/com/jstyle/blesdk2301/model/StepModel.java +++ /dev/null @@ -1,25 +0,0 @@ -package com.jstyle.blesdk2301.model; - -/** - * Created by Administrator on 2018/4/9. - */ - -public class StepModel extends SendData{ - boolean stepState;//true开启实时计步,false停止实时计步 - - public boolean isStepState() { - return stepState; - } - - public void setStepState(boolean stepState) { - this.stepState = stepState; - } - - - @Override - public String toString() { - return "StepModel{" + - "stepState=" + stepState + - '}'; - } -} diff --git a/android/blesdk_2301/src/main/java/com/jstyle/blesdk2301/model/StepModel.kt b/android/blesdk_2301/src/main/java/com/jstyle/blesdk2301/model/StepModel.kt new file mode 100644 index 00000000..505fee5d --- /dev/null +++ b/android/blesdk_2301/src/main/java/com/jstyle/blesdk2301/model/StepModel.kt @@ -0,0 +1,13 @@ +package com.jstyle.blesdk2301.model + +/** + * Created by Administrator on 2018/4/9. + */ +class StepModel : SendData() { + var isStepState = false //true开启实时计步,false停止实时计步 + override fun toString(): String { + return "StepModel{" + + "stepState=" + isStepState + + '}' + } +} \ No newline at end of file diff --git a/android/blesdk_2301/src/main/java/com/jstyle/blesdk2301/model/UserInfo.java b/android/blesdk_2301/src/main/java/com/jstyle/blesdk2301/model/UserInfo.java deleted file mode 100644 index b2049d4b..00000000 --- a/android/blesdk_2301/src/main/java/com/jstyle/blesdk2301/model/UserInfo.java +++ /dev/null @@ -1,107 +0,0 @@ -package com.jstyle.blesdk2301.model; - - -/** - * Created by Administrator on 2022/2/18. - */ -public class UserInfo { - - String phone=""; - String name=""; - String gender;//0男,1女 - String age="";//18 - String height="";//175 - String weight="";//75 - String ecgTitle=""; - String ecgReportTips=""; - String date=""; - - public String getDate() { - return date; - } - - public void setDate(String date) { - this.date = date; - } - - - - public String getPhone() { - return phone; - } - - public void setPhone(String phone) { - this.phone = phone; - } - - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - - public String getGender() { - return gender; - } - - public void setGender(String gender) { - this.gender = gender; - } - - public String getAge() { - return age; - } - - public void setAge(String age) { - this.age = age; - } - - public String getHeight() { - return height; - } - - public void setHeight(String height) { - this.height = height; - } - - public String getWeight() { - return weight; - } - - public void setWeight(String weight) { - this.weight = weight; - } - - public String getEcgTitle() { - return ecgTitle; - } - - public void setEcgTitle(String ecgTitle) { - this.ecgTitle = ecgTitle; - } - - public String getEcgReportTips() { - return ecgReportTips; - } - - public void setEcgReportTips(String ecgReportTips) { - this.ecgReportTips = ecgReportTips; - } - - @Override - public String toString() { - return "UserInfo{" + - "phone='" + phone + '\'' + - ", name='" + name + '\'' + - ", gender='" + gender + '\'' + - ", age='" + age + '\'' + - ", height='" + height + '\'' + - ", weight='" + weight + '\'' + - ", ecgTitle='" + ecgTitle + '\'' + - ", ecgReportTips='" + ecgReportTips + '\'' + - ", date='" + date + '\'' + - '}'; - } -} diff --git a/android/blesdk_2301/src/main/java/com/jstyle/blesdk2301/model/UserInfo.kt b/android/blesdk_2301/src/main/java/com/jstyle/blesdk2301/model/UserInfo.kt new file mode 100644 index 00000000..bba146d6 --- /dev/null +++ b/android/blesdk_2301/src/main/java/com/jstyle/blesdk2301/model/UserInfo.kt @@ -0,0 +1,29 @@ +package com.jstyle.blesdk2301.model + +/** + * Created by Administrator on 2022/2/18. + */ +class UserInfo { + var phone = "" + var name = "" + var gender: String? = null //0男,1女 + var age = "" //18 + var height = "" //175 + var weight = "" //75 + var ecgTitle = "" + var ecgReportTips = "" + var date = "" + override fun toString(): String { + return "UserInfo{" + + "phone='" + phone + '\'' + + ", name='" + name + '\'' + + ", gender='" + gender + '\'' + + ", age='" + age + '\'' + + ", height='" + height + '\'' + + ", weight='" + weight + '\'' + + ", ecgTitle='" + ecgTitle + '\'' + + ", ecgReportTips='" + ecgReportTips + '\'' + + ", date='" + date + '\'' + + '}' + } +} \ No newline at end of file diff --git a/android/blesdk_2301/src/main/java/com/jstyle/blesdk2301/model/WeatherData.java b/android/blesdk_2301/src/main/java/com/jstyle/blesdk2301/model/WeatherData.java deleted file mode 100644 index 4bfa8621..00000000 --- a/android/blesdk_2301/src/main/java/com/jstyle/blesdk2301/model/WeatherData.java +++ /dev/null @@ -1,49 +0,0 @@ -package com.jstyle.blesdk2301.model; - -public class WeatherData { - int tempNow; - int tempHigh; - int tempLow; - String cityName=""; - int weatherId; - - public int getTempNow() { - return tempNow; - } - - public void setTempNow(int tempNow) { - this.tempNow = tempNow; - } - - public int getTempHigh() { - return tempHigh; - } - - public void setTempHigh(int tempHigh) { - this.tempHigh = tempHigh; - } - - public int getTempLow() { - return tempLow; - } - - public void setTempLow(int tempLow) { - this.tempLow = tempLow; - } - - public String getCityName() { - return cityName; - } - - public void setCityName(String cityName) { - this.cityName = cityName; - } - - public int getWeatherId() { - return weatherId; - } - - public void setWeatherId(int weatherId) { - this.weatherId = weatherId; - } -} diff --git a/android/blesdk_2301/src/main/java/com/jstyle/blesdk2301/model/WeatherData.kt b/android/blesdk_2301/src/main/java/com/jstyle/blesdk2301/model/WeatherData.kt new file mode 100644 index 00000000..5d24c23d --- /dev/null +++ b/android/blesdk_2301/src/main/java/com/jstyle/blesdk2301/model/WeatherData.kt @@ -0,0 +1,9 @@ +package com.jstyle.blesdk2301.model + +class WeatherData { + var tempNow = 0 + var tempHigh = 0 + var tempLow = 0 + var cityName = "" + var weatherId = 0 +} \ No newline at end of file diff --git a/android/blesdk_2301/src/main/java/com/jstyle/blesdk2301/model/WomenHealth.java b/android/blesdk_2301/src/main/java/com/jstyle/blesdk2301/model/WomenHealth.java deleted file mode 100644 index c5a3a274..00000000 --- a/android/blesdk_2301/src/main/java/com/jstyle/blesdk2301/model/WomenHealth.java +++ /dev/null @@ -1,264 +0,0 @@ -package com.jstyle.blesdk2301.model; - -/** - * 女性健康 - */ -public class WomenHealth { - String userId=""; - String address=""; - String MenstrualPeriod_StartTime="1990-01-01";//经期开始时间 yyyy-MM-dd - long MenstrualPeriod_Lenth=7;//经期长度,默认7天,2-8 - long MenstrualPeriod_Period=30;//经期周期,默认30天 21-35 - long FlowRate=-1;//流量 -1没有数据 0-4等级 - long Dysmenorrhea=-1;//痛经 -1没有数据 0-4等级 - boolean Love=false;//爱爱 - long mood=-1;//心情 -1没有数据 0-4等级 - boolean start=false;//是否是第一个日期 - boolean yuejinqi=false;//是否是月经期 经期七天 - boolean yuceyuejinqi=false;//预测月经期 经期前3天 - - boolean yiyunqi=false;//是否是易孕期 经期七天后10天的日期 - boolean yuceyiyunqi=false;//预测易孕期 易孕期前3天 - boolean pailuanqi=false;//是否是排卵期 开始15后的一天 - - boolean up=false;//上升期还是下降器 - - - boolean edidt=false;//是否被编辑过 - int day=0;//每次循环的第几天 - - int[] Menstrual_symptoms = new int[32];//经期症状 - - - - public WomenHealth() { - } - - public WomenHealth(String userId, String address, - String MenstrualPeriod_StartTime, long MenstrualPeriod_Lenth, - long MenstrualPeriod_Period, long FlowRate, long Dysmenorrhea, - boolean Love, long mood, boolean start, boolean yuejinqi, - boolean yuceyuejinqi, boolean yiyunqi, boolean yuceyiyunqi, - boolean pailuanqi, boolean up, boolean edidt, int day, - int[] Menstrual_symptoms) { - this.userId = userId; - this.address = address; - this.MenstrualPeriod_StartTime = MenstrualPeriod_StartTime; - this.MenstrualPeriod_Lenth = MenstrualPeriod_Lenth; - this.MenstrualPeriod_Period = MenstrualPeriod_Period; - this.FlowRate = FlowRate; - this.Dysmenorrhea = Dysmenorrhea; - this.Love = Love; - this.mood = mood; - this.start = start; - this.yuejinqi = yuejinqi; - this.yuceyuejinqi = yuceyuejinqi; - this.yiyunqi = yiyunqi; - this.yuceyiyunqi = yuceyiyunqi; - this.pailuanqi = pailuanqi; - this.up = up; - this.edidt = edidt; - this.day = day; - this.Menstrual_symptoms = Menstrual_symptoms; - } - - - - public String getAddress() { - return address; - } - - public void setAddress(String address) { - this.address = address; - } - - public boolean isUp() { - return up; - } - - public void setUp(boolean up) { - this.up = up; - } - - public boolean isYuceyuejinqi() { - return yuceyuejinqi; - } - - public void setYuceyuejinqi(boolean yuceyuejinqi) { - this.yuceyuejinqi = yuceyuejinqi; - } - - public boolean isYuceyiyunqi() { - return yuceyiyunqi; - } - - public void setYuceyiyunqi(boolean yuceyiyunqi) { - this.yuceyiyunqi = yuceyiyunqi; - } - - public int getDay() { - return day; - } - - public void setDay(int day) { - this.day = day; - } - - public boolean isStart() { - return start; - } - - public boolean isYuejinqi() { - return yuejinqi; - } - - public void setYuejinqi(boolean yuejinqi) { - this.yuejinqi = yuejinqi; - } - - public boolean isEdidt() { - return edidt; - } - - public void setEdidt(boolean edidt) { - this.edidt = edidt; - } - - public boolean isYiyunqi() { - return yiyunqi; - } - - public void setYiyunqi(boolean yiyunqi) { - this.yiyunqi = yiyunqi; - } - - public boolean isPailuanqi() { - return pailuanqi; - } - - public void setPailuanqi(boolean pailuanqi) { - this.pailuanqi = pailuanqi; - } - - public void setStart(boolean start) { - this.start = start; - } - - public String getUserId() { - return userId; - } - - public void setUserId(String userId) { - this.userId = userId; - } - - public String getMenstrualPeriod_StartTime() { - return MenstrualPeriod_StartTime; - } - - public void setMenstrualPeriod_StartTime(String menstrualPeriod_StartTime) { - MenstrualPeriod_StartTime = menstrualPeriod_StartTime; - } - - public long getMenstrualPeriod_Lenth() { - return MenstrualPeriod_Lenth; - } - - public void setMenstrualPeriod_Lenth(long menstrualPeriod_Lenth) { - MenstrualPeriod_Lenth = menstrualPeriod_Lenth; - } - - public long getMenstrualPeriod_Period() { - return MenstrualPeriod_Period; - } - - public void setMenstrualPeriod_Period(long menstrualPeriod_Period) { - MenstrualPeriod_Period = menstrualPeriod_Period; - } - - public long getFlowRate() { - return FlowRate; - } - - public void setFlowRate(long flowRate) { - FlowRate = flowRate; - } - - public long getDysmenorrhea() { - return Dysmenorrhea; - } - - public void setDysmenorrhea(long dysmenorrhea) { - Dysmenorrhea = dysmenorrhea; - } - - public boolean isLove() { - return Love; - } - - public void setLove(boolean love) { - Love = love; - } - - public long getMood() { - return mood; - } - - public void setMood(long mood) { - this.mood = mood; - } - - public int[] getMenstrual_symptoms() { - return Menstrual_symptoms; - } - - public void setMenstrual_symptoms(int[] menstrual_symptoms) { - Menstrual_symptoms = menstrual_symptoms; - } - - - public boolean getLove() { - return this.Love; - } - - public boolean getStart() { - return this.start; - } - - public boolean getYuejinqi() { - return this.yuejinqi; - } - - public boolean getYiyunqi() { - return this.yiyunqi; - } - - public boolean getPailuanqi() { - return this.pailuanqi; - } - - public boolean getEdidt() { - return this.edidt; - } - - - public boolean getYuceyuejinqi() { - return this.yuceyuejinqi; - } - - public boolean getYuceyiyunqi() { - return this.yuceyiyunqi; - } - - - - public boolean getUp() { - return this.up; - } - - - -} - - - diff --git a/android/blesdk_2301/src/main/java/com/jstyle/blesdk2301/model/WomenHealth.kt b/android/blesdk_2301/src/main/java/com/jstyle/blesdk2301/model/WomenHealth.kt new file mode 100644 index 00000000..f6ff4aae --- /dev/null +++ b/android/blesdk_2301/src/main/java/com/jstyle/blesdk2301/model/WomenHealth.kt @@ -0,0 +1,93 @@ +package com.jstyle.blesdk2301.model + +/** + * 女性健康 + */ +class WomenHealth { + var userId = "" + var address = "" + var menstrualPeriod_StartTime = "1990-01-01" //经期开始时间 yyyy-MM-dd + var menstrualPeriod_Lenth: Long = 7 //经期长度,默认7天,2-8 + var menstrualPeriod_Period: Long = 30 //经期周期,默认30天 21-35 + var flowRate: Long = -1 //流量 -1没有数据 0-4等级 + var dysmenorrhea: Long = -1 //痛经 -1没有数据 0-4等级 + var isLove = false //爱爱 + var mood: Long = -1 //心情 -1没有数据 0-4等级 + var isStart = false //是否是第一个日期 + var isYuejinqi = false //是否是月经期 经期七天 + var isYuceyuejinqi = false //预测月经期 经期前3天 + var isYiyunqi = false //是否是易孕期 经期七天后10天的日期 + var isYuceyiyunqi = false //预测易孕期 易孕期前3天 + var isPailuanqi = false //是否是排卵期 开始15后的一天 + var isUp = false //上升期还是下降器 + var isEdidt = false //是否被编辑过 + var day = 0 //每次循环的第几天 + var menstrual_symptoms = IntArray(32) //经期症状 + + constructor() + constructor( + userId: String, address: String, + MenstrualPeriod_StartTime: String, MenstrualPeriod_Lenth: Long, + MenstrualPeriod_Period: Long, FlowRate: Long, Dysmenorrhea: Long, + Love: Boolean, mood: Long, start: Boolean, yuejinqi: Boolean, + yuceyuejinqi: Boolean, yiyunqi: Boolean, yuceyiyunqi: Boolean, + pailuanqi: Boolean, up: Boolean, edidt: Boolean, day: Int, + Menstrual_symptoms: IntArray + ) { + this.userId = userId + this.address = address + menstrualPeriod_StartTime = MenstrualPeriod_StartTime + menstrualPeriod_Lenth = MenstrualPeriod_Lenth + menstrualPeriod_Period = MenstrualPeriod_Period + flowRate = FlowRate + dysmenorrhea = Dysmenorrhea + isLove = Love + this.mood = mood + isStart = start + isYuejinqi = yuejinqi + isYuceyuejinqi = yuceyuejinqi + isYiyunqi = yiyunqi + isYuceyiyunqi = yuceyiyunqi + isPailuanqi = pailuanqi + isUp = up + isEdidt = edidt + this.day = day + menstrual_symptoms = Menstrual_symptoms + } + + fun getLove(): Boolean { + return isLove + } + + fun getStart(): Boolean { + return isStart + } + + fun getYuejinqi(): Boolean { + return isYuejinqi + } + + fun getYiyunqi(): Boolean { + return isYiyunqi + } + + fun getPailuanqi(): Boolean { + return isPailuanqi + } + + fun getEdidt(): Boolean { + return isEdidt + } + + fun getYuceyuejinqi(): Boolean { + return isYuceyuejinqi + } + + fun getYuceyiyunqi(): Boolean { + return isYuceyiyunqi + } + + fun getUp(): Boolean { + return isUp + } +} \ No newline at end of file diff --git a/android/build.gradle b/android/build.gradle index 4ee80e4c..daaa7606 100644 --- a/android/build.gradle +++ b/android/build.gradle @@ -12,7 +12,7 @@ buildscript { dependencies { classpath 'com.android.tools.build:gradle:7.1.3' - classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version" + classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:2.0.0" classpath 'com.google.gms:google-services:4.3.8' // classpath 'com.google.firebase:firebase-crashlytics-gradle:2.8.1' classpath 'com.huawei.agconnect:agcp:1.5.2.300' diff --git a/lib/main.dart b/lib/main.dart index 32286f07..8481c300 100644 --- a/lib/main.dart +++ b/lib/main.dart @@ -17,6 +17,7 @@ import 'package:firebase_core/firebase_core.dart'; import 'package:flutter/material.dart'; import 'package:flutter_localizations/flutter_localizations.dart'; import 'package:in_app_update/in_app_update.dart'; +import 'package:logger/logger.dart'; import 'package:provider/provider.dart'; import 'config/size_config.dart'; @@ -25,6 +26,8 @@ import 'core/viewModels/project_view_model.dart'; import 'locator.dart'; import 'pages/pharmacies/compare-list.dart'; +Logger logger = Logger(); + void main() async { WidgetsFlutterBinding.ensureInitialized(); await Firebase.initializeApp(); diff --git a/lib/pages/medical/my_trackers/ble_device_type_screens/ble_devices_screen.dart b/lib/pages/medical/my_trackers/ble_device_type_screens/ble_devices_screen.dart index 046dbc10..7f801a77 100644 --- a/lib/pages/medical/my_trackers/ble_device_type_screens/ble_devices_screen.dart +++ b/lib/pages/medical/my_trackers/ble_device_type_screens/ble_devices_screen.dart @@ -41,7 +41,7 @@ class _BleDevicesScreenState extends State { myTrackersVm.startSearchingForCheckMePro(); } if (myTrackersVm.currentSelectedTrackerType == TrackerTypeEnum.SmartRing) { - myTrackersVm.startFlutterScan(); + myTrackersVm.startSearchingForSmartRing(); } else { myTrackersVm.startSearchingForTracker(); myTrackersVm.startTimerForNativeScan(); @@ -121,9 +121,9 @@ class _BleDevicesScreenState extends State { case TrackerTypeEnum.SmartRing: if (myTrackersVm.isDeviceFromAndesFit(device.name)) { - Navigator.pushReplacement(context, FadePage(page: SmartRingAllInOneConnectScreen(deviceModel: device.andesfitBluetoothDevice))); return; } + Navigator.pushReplacement(context, FadePage(page: SmartRingAllInOneConnectScreen(deviceModel: device))); break; case TrackerTypeEnum.AllInOneTracker: diff --git a/lib/pages/medical/my_trackers/ble_device_type_screens/smart_ring_connect_screen.dart b/lib/pages/medical/my_trackers/ble_device_type_screens/smart_ring_connect_screen.dart index 02c26dc2..42f46b2b 100644 --- a/lib/pages/medical/my_trackers/ble_device_type_screens/smart_ring_connect_screen.dart +++ b/lib/pages/medical/my_trackers/ble_device_type_screens/smart_ring_connect_screen.dart @@ -1,18 +1,13 @@ -import 'dart:developer'; - -import 'package:diplomaticquarterapp/pages/medical/my_trackers/ble_device_type_screens/checkme_all_in_one_info_screen.dart'; import 'package:diplomaticquarterapp/pages/medical/my_trackers/ble_models/ble_devices_model.dart'; import 'package:diplomaticquarterapp/pages/medical/my_trackers/my_trackers_view_model/my_trackers_view_model.dart'; -import 'package:diplomaticquarterapp/widgets/transitions/fade_page.dart'; import 'package:diplomaticquarterapp/widgets/buttons/defaultButton.dart'; import 'package:diplomaticquarterapp/widgets/data_display/medical/medical_profile_item.dart'; import 'package:diplomaticquarterapp/widgets/others/app_scaffold_widget.dart'; import 'package:flutter/material.dart'; -import 'package:flutter_blue_plus/flutter_blue_plus.dart'; import 'package:provider/provider.dart'; class SmartRingAllInOneConnectScreen extends StatefulWidget { - final BluetoothDevice deviceModel; + final BleDeviceModel deviceModel; const SmartRingAllInOneConnectScreen({this.deviceModel}); @@ -26,15 +21,13 @@ class _SmartRingAllInOneConnectScreenState extends State(); - myTrackersVm.connectSmartRingDevice(widget.deviceModel); + myTrackersVm.connectDevice(widget.deviceModel); super.initState(); } @override void dispose() { - myTrackersVm.selectedAndesFitScanResult = null; - myTrackersVm.isAndesfitDeviceConnected = null; - myTrackersVm.disConnectAndesfitDevice(widget.deviceModel); + myTrackersVm.disConnectDevice(); super.dispose(); } @@ -74,19 +67,13 @@ class _SmartRingAllInOneConnectScreenState extends State onTrackerTypePressed(myTrackersViewModel.checkMeProTrackers[index], myTrackersViewModel), + onTap: () => onTrackerTypePressed(myTrackersViewModel.smartRingTrackers[index], myTrackersViewModel), child: MedicalProfileItem( - title: getTrackerNameByEnum(myTrackersViewModel.checkMeProTrackers[index]), + title: getTrackerNameByEnum(myTrackersViewModel.smartRingTrackers[index]), imagePath: 'tracker.svg', subTitle: "", isEnable: true, diff --git a/lib/pages/medical/my_trackers/ble_helpers/ble_connect_helper.dart b/lib/pages/medical/my_trackers/ble_helpers/ble_connect_helper.dart index 1ce1ddf6..b0a7ad87 100644 --- a/lib/pages/medical/my_trackers/ble_helpers/ble_connect_helper.dart +++ b/lib/pages/medical/my_trackers/ble_helpers/ble_connect_helper.dart @@ -218,4 +218,63 @@ class BleChannel { return "Error: $e"; } } + + // SMART RING SERVICES + + static Future scanSmartRingNative() async { + try { + String result; + print("----------Flutter scanForSmartRing -------"); + + result = await platform.invokeMethod('scanForSmartRing'); + + print("----------Flutter scanForSmartRing Result -------"); + print(result); + return result; + } catch (e) { + return "Error: $e"; + } + } + + static Future connectDeviceSmartRing(String deviceAddress) async { + try { + String result; + print("----------Flutter init connectDeviceSmartRing -------"); + + result = await platform.invokeMethod('connectDeviceSmartRing', deviceAddress); + + print("----------Flutter Result connectDeviceSmartRing -------"); + print(result); + return result; + } catch (e) { + return "Error: $e"; + } + } + + static Future disConnectDeviceSmartRing() async { + try { + String result; + print("----------Flutter init disConnectDeviceSmartRing -------"); + + result = await platform.invokeMethod('disConnectDeviceSmartRing'); + + print("----------Flutter Result disConnectDeviceSmartRing -------"); + print(result); + return result; + } catch (e) { + return "Error: $e"; + } + } + + static Future getBatteryLevelSmartRing() async { + try { + print("----------Flutter getBatteryLevelSmartRing -------"); + final String result = await platform.invokeMethod('getBatteryLevelSmartRing'); + print("----------Flutter getBatteryLevelSmartRing result -------"); + print(result); + return result; + } catch (e) { + return "Error: $e"; + } + } } diff --git a/lib/pages/medical/my_trackers/my_trackers_view_model/my_trackers_view_model.dart b/lib/pages/medical/my_trackers/my_trackers_view_model/my_trackers_view_model.dart index ce4d2c5b..ae4e4f79 100644 --- a/lib/pages/medical/my_trackers/my_trackers_view_model/my_trackers_view_model.dart +++ b/lib/pages/medical/my_trackers/my_trackers_view_model/my_trackers_view_model.dart @@ -3,6 +3,7 @@ import 'dart:convert'; import 'dart:developer'; import 'dart:io'; import 'package:diplomaticquarterapp/config/size_config.dart'; +import 'package:diplomaticquarterapp/main.dart'; import 'package:diplomaticquarterapp/pages/medical/my_trackers/ble_device_type_screens/checkme_all_in_one_info_screen.dart'; import 'package:diplomaticquarterapp/pages/medical/my_trackers/ble_models/andesfit_devices/weight_data_model.dart'; import 'package:diplomaticquarterapp/pages/medical/my_trackers/ble_models/ble_devices_model.dart'; @@ -52,6 +53,9 @@ String kOxiCheckMePro = "OxiCheckMePro"; String kGlucoseCheckMePro = "GlucoseCheckMePro"; String kBPCheckMePro = "BPCheckMePro"; +String kDevicesListSmartRing = "DevicesListSmartRing"; +String kBatteryLevelSmartRing = "BatteryLevelSmartRing"; + class MyTrackersViewModel extends ChangeNotifier { EventChannel eventChannel = EventChannel('BLE-Platform-Bridge-Event'); @@ -132,6 +136,12 @@ class MyTrackersViewModel extends ChangeNotifier { TrackerTypeEnum.BloodSugarTracker, TrackerTypeEnum.ECGTracker, ]; + List smartRingTrackers = [ + TrackerTypeEnum.Temperature, + TrackerTypeEnum.OxymeterTracker, + TrackerTypeEnum.BloodSugarTracker, + TrackerTypeEnum.ECGTracker, + ]; List andesFitDevices = [ "BPM", @@ -140,7 +150,6 @@ class MyTrackersViewModel extends ChangeNotifier { "TEMP", "Samico GL", "BLE-MSA", - "2301A", ]; StreamSubscription bleDevicesStream; @@ -423,6 +432,8 @@ class MyTrackersViewModel extends ChangeNotifier { Future connectDevice(BleDeviceModel device) async { if (currentSelectedTrackerType == TrackerTypeEnum.AllInOneTracker) { await BleChannel.connectDeviceCheckMe([device.name, device.model.toString(), currentSelectedTrackerType.name]); + } else if (currentSelectedTrackerType == TrackerTypeEnum.SmartRing) { + await BleChannel.connectDeviceSmartRing("CA:59:D9:7E:3E:D6"); //TODO: NEED TO VERIFY IF IT KEEPS CHANGING OR NO } else { await BleChannel.connectDevice([device.name, device.model.toString(), currentSelectedTrackerType.name]); } @@ -430,6 +441,10 @@ class MyTrackersViewModel extends ChangeNotifier { Future disConnectDevice() async { isDeviceSelected = false; + if (currentSelectedTrackerType == TrackerTypeEnum.SmartRing) { + await BleChannel.disConnectDeviceSmartRing(); + return; + } await BleChannel.disconnect(); } @@ -452,7 +467,6 @@ class MyTrackersViewModel extends ChangeNotifier { FlutterBluePlus.stopScan(); return; } - log("blueToothDevicesLength : ${blueToothDevices.length}"); blueToothDevices.forEach((element) async { if (element.device.localName.isNotEmpty) { @@ -1092,42 +1106,6 @@ class MyTrackersViewModel extends ChangeNotifier { bool isDeviceSelected = false; - Future connectSmartRingDevice(BluetoothDevice device) async { - device.connectionState.listen((BluetoothConnectionState state) async { - if (state == BluetoothConnectionState.disconnected) { - isAndesfitDeviceConnected = false; - notifyListeners(); - } - if (state == BluetoothConnectionState.connected) { - isAndesfitDeviceConnected = true; - notifyListeners(); - bleDevicesStream.cancel(); - List services = await device.discoverServices(); - services.forEach((service) { - if (service.serviceUuid.toString().toLowerCase() == BLEUtils.TEMPERATURE_SERVICE) { - print(service.serviceUuid); - service.characteristics.forEach((characteristic) async { - if (characteristic.characteristicUuid.toString().toLowerCase() == BLEUtils.TEMPERATURE_CHARACTERISTIC) { - print(characteristic.characteristicUuid); - characteristic.onValueReceived.listen((event) { - print("onValueReceived Stream"); - print(event); - updateCurrentTempInCelsius(convertIntListToHexTemp(event)); - String currentTempInFahrenheit = ((num.parse(currentTempInCelsius) * 1.8) + 32).toStringAsFixed(1); - String tempCurrentTempInCelsius = currentTempInCelsius + "\u2103" + " / " + currentTempInFahrenheit + "\u2109"; - updateCurrentTempInCelsius(tempCurrentTempInCelsius); - }); - await characteristic.setNotifyValue(true); - } - }); - return true; - } - }); - } - }); - await device.connect(timeout: Duration(seconds: 35)); - } - Future connectAndesfitAllInOneDevice(BluetoothDevice device) async { log("deviceToConnect: ${device.toString()}"); } @@ -1378,4 +1356,72 @@ class MyTrackersViewModel extends ChangeNotifier { checkMeGlucose = List.generate(returnData.length, (index) => CheckMeGlucoseModel.fromJson(returnData[index])); notifyListeners(); } + + // SMART RING + + Future scanForSmartRing() async { + await BleChannel.scanSmartRingNative(); + } + + Future startSearchingForSmartRing() async { + log("selectedTracker in startSearchingForSmartRing: ${currentSelectedTrackerType.name}"); + await checkBLEPermissions(); + eventChannel.receiveBroadcastStream().listen((event) { + print('Received event---: $event'); + print(event['type']); + if (event['type'] == kDevicesListSmartRing) { + if (Platform.isAndroid) { + List list = [json.decode(event['data'])]; + parsesDevicesList(list); + } else {} + } + + if (event['type'] == kBatteryLevelSmartRing) { + updateCheckMeTemperatureInfoModel(json.decode(event['data'])); + } + }); + + await scanForSmartRing(); + } + + Future connectSmartRingDevice(BluetoothDevice device) async { + device.connectionState.listen((BluetoothConnectionState state) async { + if (state == BluetoothConnectionState.disconnected) { + isAndesfitDeviceConnected = false; + notifyListeners(); + } + if (state == BluetoothConnectionState.connected) { + isAndesfitDeviceConnected = true; + notifyListeners(); + bleDevicesStream.cancel(); + List services = await device.discoverServices(); + services.forEach((service) { + if (service.serviceUuid.toString().toLowerCase() == BLEUtils.TEMPERATURE_SERVICE) { + print(service.serviceUuid); + service.characteristics.forEach((characteristic) async { + if (characteristic.characteristicUuid.toString().toLowerCase() == BLEUtils.TEMPERATURE_CHARACTERISTIC) { + print(characteristic.characteristicUuid); + characteristic.onValueReceived.listen((event) { + print("onValueReceived Stream"); + print(event); + updateCurrentTempInCelsius(convertIntListToHexTemp(event)); + String currentTempInFahrenheit = ((num.parse(currentTempInCelsius) * 1.8) + 32).toStringAsFixed(1); + String tempCurrentTempInCelsius = currentTempInCelsius + "\u2103" + " / " + currentTempInFahrenheit + "\u2109"; + updateCurrentTempInCelsius(tempCurrentTempInCelsius); + }); + await characteristic.setNotifyValue(true); + } + }); + return true; + } + }); + } + }); + await device.connect(timeout: Duration(seconds: 35)); + } + + Future getBatteryLevelSmartRing() async { + String data = await BleChannel.getBatteryLevelSmartRing(); + logger.i(jsonEncode(data.toString())); + } } diff --git a/pubspec.yaml b/pubspec.yaml index 3e0bfa67..29204538 100644 --- a/pubspec.yaml +++ b/pubspec.yaml @@ -218,6 +218,10 @@ dependencies: # flutter_callkit_incoming: ^1.0.3+3 # firebase_core: 1.12.0 + + logger: ^2.3.0 + + # flutter_amazonpaymentservices: 0.0.6 # crypto: