Comparar commits

...

Autor SHA1 Mensaje Fecha
  liup 519a2f4129 修改校准 hace 5 meses
  liup e95d0f47e6 页面修改 hace 6 meses
  liup 31da1c43be 小炒机工序执行修改 hace 6 meses
  pry 12b561520e 桌面小炒合并 hace 7 meses
  fyf b73f66f44b 4213 hace 11 meses
  fyf 84ba4f8df4 23 hace 11 meses
  fyf 236835bbe0 444 hace 11 meses
  fyf d573c04a99 4 hace 11 meses
  fyf 0edeb850cf 555 hace 11 meses
  fyf 49aaf4a3e4 777 hace 11 meses
  fyf f6abb344d5 333 hace 11 meses
  fyf 43496bd30a 333 hace 11 meses
  fyf b2da602fae 1111 hace 11 meses
  fyf 28ea495971 gengx hace 11 meses
  fyf 5a602905c6 gengx hace 11 meses
  fyf 66a2b7e18d 5555 hace 11 meses
  fyf f0be378dbc 555 hace 11 meses
  fyf 412b3bb858 222 hace 11 meses
  fyf 38bc6569ec 1111 hace 11 meses
  fyf b8505b53e9 更新最小版本 hace 11 meses
  fyf ef37bfc0f1 提交 hace 11 meses
  fyf eca41a8306 3333 hace 11 meses
  fyf 03f3add637 更44 hace 1 año
  fyf 6b54a5b1b5 hace 1 año
  fyf 9f314b7ddb 温度控制 hace 1 año
  fyf 5e1c88b6cf 32323 hace 1 año
  fyf daa03c635d 888333 hace 1 año
  fyf 762569df05 122121212 hace 1 año
  fyf 7465adaec4 122121212 hace 1 año
Se han modificado 100 ficheros con 11559 adiciones y 308 borrados
Dividir vista
  1. +10
    -0
      .idea/deploymentTargetDropDown.xml
  2. +18
    -0
      .idea/deploymentTargetSelector.xml
  3. +2
    -3
      .idea/gradle.xml
  4. +10
    -0
      .idea/migrations.xml
  5. +1
    -2
      .idea/misc.xml
  6. +32
    -0
      app/build.gradle
  7. +104
    -23
      app/src/main/AndroidManifest.xml
  8. +22
    -0
      app/src/main/assets/error_code.json
  9. +535
    -0
      app/src/main/java/com/bonait/bnframework/HBL/API/APIHelper.java
  10. +21
    -0
      app/src/main/java/com/bonait/bnframework/HBL/API/APIResult.java
  11. +21
    -0
      app/src/main/java/com/bonait/bnframework/HBL/API/APIResultT.java
  12. +57
    -0
      app/src/main/java/com/bonait/bnframework/HBL/API/Utils.java
  13. +44
    -0
      app/src/main/java/com/bonait/bnframework/HBL/Communication/CommBase.java
  14. +86
    -0
      app/src/main/java/com/bonait/bnframework/HBL/Communication/Modbus/ExceptionServer.java
  15. +15
    -0
      app/src/main/java/com/bonait/bnframework/HBL/Communication/Modbus/IExceptionHandling.java
  16. +10
    -0
      app/src/main/java/com/bonait/bnframework/HBL/Communication/Modbus/IModbusMaster.java
  17. +24
    -0
      app/src/main/java/com/bonait/bnframework/HBL/Communication/Modbus/IRead.java
  18. +23
    -0
      app/src/main/java/com/bonait/bnframework/HBL/Communication/Modbus/IWrite.java
  19. +727
    -0
      app/src/main/java/com/bonait/bnframework/HBL/Communication/Modbus/ModbusMaster.java
  20. +157
    -0
      app/src/main/java/com/bonait/bnframework/HBL/Communication/Siemens/CommHelper.java
  21. +360
    -0
      app/src/main/java/com/bonait/bnframework/HBL/Communication/Siemens/SiemensHelper.java
  22. +213
    -0
      app/src/main/java/com/bonait/bnframework/HBL/CustomView/ShadowContainer.java
  23. +81
    -0
      app/src/main/java/com/bonait/bnframework/HBL/DataUtil/ByteLib.java
  24. +51
    -0
      app/src/main/java/com/bonait/bnframework/HBL/DataUtil/ByteTransDataFormat.java
  25. +107
    -0
      app/src/main/java/com/bonait/bnframework/HBL/DataUtil/Convert.java
  26. +266
    -0
      app/src/main/java/com/bonait/bnframework/HBL/DataUtil/DataConvertLib.java
  27. +16
    -0
      app/src/main/java/com/bonait/bnframework/HBL/DataUtil/DataType.java
  28. +46
    -0
      app/src/main/java/com/bonait/bnframework/HBL/DataUtil/ErrorCodeManager.java
  29. +64
    -0
      app/src/main/java/com/bonait/bnframework/HBL/DataUtil/ErrorCodeUtil.java
  30. +31
    -0
      app/src/main/java/com/bonait/bnframework/HBL/DataUtil/FloatLib.java
  31. +51
    -0
      app/src/main/java/com/bonait/bnframework/HBL/DataUtil/IntLib.java
  32. +37
    -0
      app/src/main/java/com/bonait/bnframework/HBL/DataUtil/NotifyPropVar.java
  33. +51
    -0
      app/src/main/java/com/bonait/bnframework/HBL/DataUtil/ShortLib.java
  34. +8
    -0
      app/src/main/java/com/bonait/bnframework/HBL/Dialog/AlertDialogButton.java
  35. +15
    -0
      app/src/main/java/com/bonait/bnframework/HBL/Dialog/DialogActivity.java
  36. +309
    -0
      app/src/main/java/com/bonait/bnframework/HBL/Dialog/DialogManager.java
  37. +7
    -0
      app/src/main/java/com/bonait/bnframework/HBL/Dialog/DialogType.java
  38. +35
    -0
      app/src/main/java/com/bonait/bnframework/HBL/Dialog/DialogView.java
  39. +6
    -0
      app/src/main/java/com/bonait/bnframework/HBL/Dialog/IDialogAction.java
  40. +8
    -0
      app/src/main/java/com/bonait/bnframework/HBL/Enum/DataFormat.java
  41. +40
    -0
      app/src/main/java/com/bonait/bnframework/HBL/Executor.java
  42. +5
    -0
      app/src/main/java/com/bonait/bnframework/HBL/Interface/IRun.java
  43. +3
    -1
      app/src/main/java/com/bonait/bnframework/HBL/Interface/IRunT.java
  44. +5
    -0
      app/src/main/java/com/bonait/bnframework/HBL/Interface/IRunT2.java
  45. +7
    -0
      app/src/main/java/com/bonait/bnframework/HBL/Logs/IMessageLogNotify.java
  46. +70
    -0
      app/src/main/java/com/bonait/bnframework/HBL/Logs/MessageLog.java
  47. +230
    -0
      app/src/main/java/com/bonait/bnframework/HBL/NetworkUtils.java
  48. +60
    -0
      app/src/main/java/com/bonait/bnframework/HBL/NotifyEvent.java
  49. +39
    -0
      app/src/main/java/com/bonait/bnframework/HBL/Result/IResult.java
  50. +78
    -0
      app/src/main/java/com/bonait/bnframework/HBL/Result/OperateResult.java
  51. +88
    -0
      app/src/main/java/com/bonait/bnframework/HBL/Result/OperateResultT.java
  52. +38
    -0
      app/src/main/java/com/bonait/bnframework/HBL/Result/ResultCode.java
  53. +5
    -0
      app/src/main/java/com/bonait/bnframework/HBL/Thread/IThread.java
  54. +7
    -0
      app/src/main/java/com/bonait/bnframework/HBL/Thread/IThreadComplete.java
  55. +137
    -0
      app/src/main/java/com/bonait/bnframework/HBL/Thread/ThreadManager.java
  56. +8
    -0
      app/src/main/java/com/bonait/bnframework/HBL/Thread/ThreadModel.java
  57. +4
    -2
      app/src/main/java/com/bonait/bnframework/HBL/Trig/RTrig.java
  58. +2
    -54
      app/src/main/java/com/bonait/bnframework/MainApplication.java
  59. +1
    -1
      app/src/main/java/com/bonait/bnframework/Model/AppLoginPo.java
  60. +34
    -0
      app/src/main/java/com/bonait/bnframework/Model/ErrorCodeBean.java
  61. +1
    -1
      app/src/main/java/com/bonait/bnframework/Model/UpdateAppPo.java
  62. +1
    -1
      app/src/main/java/com/bonait/bnframework/Model/UserInfo.java
  63. +148
    -0
      app/src/main/java/com/bonait/bnframework/Service/AnalogConvert.java
  64. +52
    -0
      app/src/main/java/com/bonait/bnframework/Service/ControlAdress.java
  65. +24
    -0
      app/src/main/java/com/bonait/bnframework/Service/Func.java
  66. +530
    -0
      app/src/main/java/com/bonait/bnframework/Service/ModbusHelper.java
  67. +16
    -0
      app/src/main/java/com/bonait/bnframework/Service/OperationModel.java
  68. +23
    -0
      app/src/main/java/com/bonait/bnframework/Service/PLCModel.java
  69. +42
    -74
      app/src/main/java/com/bonait/bnframework/ViewModel/ActivityViewModel/BottomNavigation2Activity.java
  70. +634
    -0
      app/src/main/java/com/bonait/bnframework/ViewModel/ActivityViewModel/BottomNavigationNewActivity.java
  71. +167
    -0
      app/src/main/java/com/bonait/bnframework/ViewModel/ActivityViewModel/BunkerSetupActivity.java
  72. +411
    -0
      app/src/main/java/com/bonait/bnframework/ViewModel/ActivityViewModel/CookingActivity.java
  73. +417
    -0
      app/src/main/java/com/bonait/bnframework/ViewModel/ActivityViewModel/CookingNewActivity.java
  74. +609
    -0
      app/src/main/java/com/bonait/bnframework/ViewModel/ActivityViewModel/CookingSimulatedActivity.java
  75. +12
    -19
      app/src/main/java/com/bonait/bnframework/ViewModel/ActivityViewModel/CpActivity.java
  76. +6
    -6
      app/src/main/java/com/bonait/bnframework/ViewModel/ActivityViewModel/CpxzActivity.java
  77. +1370
    -0
      app/src/main/java/com/bonait/bnframework/ViewModel/ActivityViewModel/DishTestActivity.java
  78. +28
    -26
      app/src/main/java/com/bonait/bnframework/ViewModel/ActivityViewModel/DiyActivity.java
  79. +681
    -0
      app/src/main/java/com/bonait/bnframework/ViewModel/ActivityViewModel/DiyMemoryActivity.java
  80. +777
    -0
      app/src/main/java/com/bonait/bnframework/ViewModel/ActivityViewModel/DiyUpdate1Activity.java
  81. +28
    -16
      app/src/main/java/com/bonait/bnframework/ViewModel/ActivityViewModel/DiyUpdateActivity.java
  82. +1
    -1
      app/src/main/java/com/bonait/bnframework/ViewModel/ActivityViewModel/FileActivity.java
  83. +3
    -10
      app/src/main/java/com/bonait/bnframework/ViewModel/ActivityViewModel/ImageChooseActivity.java
  84. +57
    -26
      app/src/main/java/com/bonait/bnframework/ViewModel/ActivityViewModel/LoginActivity.java
  85. +1
    -1
      app/src/main/java/com/bonait/bnframework/ViewModel/ActivityViewModel/NoticeActivity.java
  86. +53
    -8
      app/src/main/java/com/bonait/bnframework/ViewModel/ActivityViewModel/SzActivity.java
  87. +338
    -0
      app/src/main/java/com/bonait/bnframework/ViewModel/ActivityViewModel/UserActivity.java
  88. +43
    -5
      app/src/main/java/com/bonait/bnframework/ViewModel/ActivityViewModel/WelcomeActivity.java
  89. +40
    -7
      app/src/main/java/com/bonait/bnframework/ViewModel/ActivityViewModel/WhActivity.java
  90. +1
    -1
      app/src/main/java/com/bonait/bnframework/ViewModel/Adapter/FragmentAdapter.java
  91. +4
    -2
      app/src/main/java/com/bonait/bnframework/ViewModel/Adapter/gongxubuzhou_adapter.java
  92. +67
    -0
      app/src/main/java/com/bonait/bnframework/ViewModel/Adapter/gongxubuzhou_adapter1.java
  93. +56
    -0
      app/src/main/java/com/bonait/bnframework/ViewModel/Adapter/gongxubuzhou_adapter2.java
  94. +248
    -0
      app/src/main/java/com/bonait/bnframework/ViewModel/Adapter/good_adapter.java
  95. +2
    -6
      app/src/main/java/com/bonait/bnframework/ViewModel/Adapter/image_sp_adapter.java
  96. +7
    -8
      app/src/main/java/com/bonait/bnframework/ViewModel/Adapter/lc_adapter.java
  97. +1
    -1
      app/src/main/java/com/bonait/bnframework/ViewModel/Adapter/monitor_adapter.java
  98. +1
    -2
      app/src/main/java/com/bonait/bnframework/ViewModel/Adapter/process_adapter.java
  99. +1
    -1
      app/src/main/java/com/bonait/bnframework/ViewModel/Adapter/processchid_adapter.java
  100. +116
    -0
      app/src/main/java/com/bonait/bnframework/ViewModel/Adapter/silos_calibrate_adapter.java

+ 10
- 0
.idea/deploymentTargetDropDown.xml Ver fichero

@@ -0,0 +1,10 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="deploymentTargetDropDown">
<value>
<entry key="app">
<State />
</entry>
</value>
</component>
</project>

+ 18
- 0
.idea/deploymentTargetSelector.xml Ver fichero

@@ -0,0 +1,18 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="deploymentTargetSelector">
<selectionStates>
<SelectionState runConfigName="app">
<option name="selectionMode" value="DROPDOWN" />
<DropdownSelection timestamp="2024-05-22T08:50:34.498213700Z">
<Target type="DEFAULT_BOOT">
<handle>
<DeviceId pluginId="Default" identifier="serial=10.24.61.120:5555;connection=fa0f3ba7" />
</handle>
</Target>
</DropdownSelection>
<DialogSelection />
</SelectionState>
</selectionStates>
</component>
</project>

+ 2
- 3
.idea/gradle.xml Ver fichero

@@ -4,16 +4,15 @@
<component name="GradleSettings">
<option name="linkedExternalProjectsSettings">
<GradleProjectSettings>
<option name="testRunner" value="GRADLE" />
<option name="distributionType" value="DEFAULT_WRAPPED" />
<option name="externalProjectPath" value="$PROJECT_DIR$" />
<option name="gradleJvm" value="JDK" />
<option name="gradleJvm" value="corretto-11" />
<option name="modules">
<set>
<option value="$PROJECT_DIR$" />
<option value="$PROJECT_DIR$/app" />
</set>
</option>
<option name="resolveExternalAnnotations" value="false" />
</GradleProjectSettings>
</option>
</component>

+ 10
- 0
.idea/migrations.xml Ver fichero

@@ -0,0 +1,10 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ProjectMigrations">
<option name="MigrateToGradleLocalJavaHome">
<set>
<option value="$PROJECT_DIR$" />
</set>
</option>
</component>
</project>

+ 1
- 2
.idea/misc.xml Ver fichero

@@ -1,5 +1,4 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ExternalStorageConfigurationManager" enabled="true" />
<component name="ProjectRootManager" version="2" languageLevel="JDK_11" default="true" project-jdk-name="JDK" project-jdk-type="JavaSDK" />
<component name="ProjectRootManager" version="2" languageLevel="JDK_11" default="true" project-jdk-name="corretto-11" project-jdk-type="JavaSDK" />
</project>

+ 32
- 0
app/build.gradle Ver fichero

@@ -11,6 +11,7 @@ android {
targetSdk rootProject.ext.targetSdkVersion
versionCode rootProject.ext.versionCode
versionName rootProject.ext.versionName
manifestPlaceholders = [UMENG_CHANNEL_VALUE : "default"]
testInstrumentationRunner 'androidx.test.runner.AndroidJUnitRunner'
multiDexEnabled true
}
@@ -34,6 +35,7 @@ android {
}

compileOptions {
coreLibraryDesugaringEnabled true
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
@@ -42,14 +44,21 @@ android {
sourceSets {
main {
res.srcDirs = [
'src/main/res/layout/dialog',
'src/main/res/layout/datatab',
'src/main/res/layout/item',
'src/main/res/layout',
'src/main/res'
]
assets {
srcDirs 'src\\main\\assets'
}

}
}
buildFeatures {
viewBinding = true
}
}

dependencies {
@@ -149,7 +158,30 @@ dependencies {

//阿里云IOT
implementation ('com.aliyun.alink.linksdk:lp-iot-linkkit:1.7.3.2')

implementation 'com.github.SheHuan:NiceImageView:1.0.5'

coreLibraryDesugaring 'com.android.tools:desugar_jdk_libs:1.1.6'
implementation 'com.github.xingshuangs:iot-communication:1.5.0'

//MQTT
// implementation files('libs\\org.eclipse.paho.android.service-1.1.1.jar')
// implementation files('libs\\org.eclipse.paho.client.mqttv3-1.2.5.jar')

//日志工具 可定位代码行数
api 'com.apkfuns.logutils:library:1.7.5'


api 'com.squareup.okhttp3:okhttp:3.12.0'

api 'org.greenrobot:eventbus:3.1.1'

api 'com.github.bumptech.glide:glide:4.16.0'
annotationProcessor 'com.github.bumptech.glide:compiler:4.16.0'
api "com.github.bumptech.glide:okhttp3-integration:4.16.0"
api 'pl.droidsonroids.gif:android-gif-drawable:1.2.19'

implementation "com.github.bumptech.glide:okhttp3-integration:4.16.0"
implementation 'com.squareup.retrofit2:converter-gson:2.5.0'
implementation 'com.squareup.okhttp3:logging-interceptor:3.10.0'
}

+ 104
- 23
app/src/main/AndroidManifest.xml Ver fichero

@@ -34,67 +34,139 @@
tools:node="merge"
tools:replace="android:icon">
<activity
android:name=".modules.home.fragment.from.fragment.SystemCsPLCFragment"
android:name=".ViewModel.ActivityViewModel.DiyUpdate1Activity"
android:screenOrientation="portrait"
android:exported="false" />
<activity
android:name=".ViewModel.ActivityViewModel.CookingSimulatedActivity"
android:screenOrientation="portrait"
android:exported="false" />
<activity
android:name=".ViewModel.ActivityViewModel.DishTestActivity"
android:screenOrientation="portrait"
android:exported="false" />
<activity
android:name=".ViewModel.ActivityViewModel.BunkerSetupActivity"
android:screenOrientation="portrait"
android:exported="false" />
<activity
android:name=".ViewModel.ActivityViewModel.CookingActivity"
android:screenOrientation="portrait"
android:exported="false"
tools:ignore="Instantiatable" />
<activity
android:name=".ViewModel.FragmentViewModel.Home4Fragment"
android:screenOrientation="portrait"
android:exported="false"
tools:ignore="Instantiatable" />
<!--android:windowSoftInputMode="adjustPan" 键盘不会影响布局-->
<!--android:configChanges="keyboardHidden|orientation|screenSize|screenLayout|smallestScreenSize|uiMode|layoutDirection|keyboard"-->
<activity
android:name=".modules.home.fragment.from.FileActivity"
android:name=".ViewModel.ActivityViewModel.BottomNavigationNewActivity"
android:launchMode="singleTask"
android:windowSoftInputMode="adjustPan"
android:screenOrientation="portrait"
android:exported="false" />
<activity
android:name=".modules.home.fragment.from.ImageChooseActivity"
android:name=".ViewModel.ActivityViewModel.UserActivity"
android:screenOrientation="portrait"
android:exported="false" />
<activity
android:name=".modules.home.fragment.from.DiyUpdateActivity"
android:name=".ViewModel.ActivityViewModel.DiyMemoryActivity"
android:screenOrientation="portrait"
android:exported="false" />
<activity
android:name=".modules.home.fragment.mode.fragment_gx"
android:name=".ViewModel.FragmentViewModel.SystemCsPLCFragment"
android:screenOrientation="portrait"
android:exported="false"
tools:ignore="Instantiatable" />
<activity
android:name=".modules.home.fragment.from.fragment.SystemCsFltlFragment"
android:name=".ViewModel.ActivityViewModel.FileActivity"
android:screenOrientation="portrait"
android:exported="false" />
<activity
android:name=".ViewModel.ActivityViewModel.ImageChooseActivity"
android:screenOrientation="portrait"
android:exported="false" />
<activity
android:name=".ViewModel.ActivityViewModel.DiyUpdateActivity"
android:screenOrientation="portrait"
android:exported="false" />
<activity
android:name=".ViewModel.CustomView.fragment_gx"
android:screenOrientation="portrait"
android:exported="false"
tools:ignore="Instantiatable" />
<activity
android:name=".ViewModel.FragmentViewModel.SystemCsFltlFragment"
android:screenOrientation="portrait"
android:exported="false"
tools:ignore="Instantiatable" />
<activity
android:name=".modules.home.fragment.from.fragment.SystemCsMonitorFragment"
android:name=".ViewModel.FragmentViewModel.SystemCsMonitorFragment"
android:screenOrientation="portrait"
android:exported="false"
tools:ignore="Instantiatable" />
<activity
android:name=".modules.home.fragment.from.fragment.SystemCsControlFragment"
android:name=".ViewModel.FragmentViewModel.SystemCsControlFragment"
android:screenOrientation="portrait"
android:exported="false"
tools:ignore="Instantiatable" />
<activity
android:name=".modules.home.fragment.from.fragment.SystemSeasoningsetFragment"
android:name=".ViewModel.FragmentViewModel.SystemSeasoningsetFragment"
android:screenOrientation="portrait"
android:windowSoftInputMode="adjustPan"
android:exported="false"
tools:ignore="Instantiatable" />
<activity
android:name=".modules.home.fragment.from.fragment.SystemSystemsetFragment"
android:name=".ViewModel.FragmentViewModel.SystemSystemsetFragment"
android:screenOrientation="portrait"
android:exported="false"
tools:ignore="Instantiatable" />
<activity
android:name=".modules.home.fragment.from.fragment.SystemDeviceinFragment"
android:name=".ViewModel.FragmentViewModel.SystemDeviceinFragment"
android:screenOrientation="portrait"
android:exported="false"
tools:ignore="Instantiatable" />
<activity
android:name=".modules.home.fragment.from.fragment.systeminternetfragment"
android:name=".ViewModel.FragmentViewModel.systeminternetfragment"
android:screenOrientation="portrait"
android:exported="false"
tools:ignore="Instantiatable" />
<activity
android:name=".modules.home.fragment.from.CpxzActivity"
android:name=".ViewModel.ActivityViewModel.CpxzActivity"
android:screenOrientation="portrait"
android:exported="false" />
<activity
android:name=".ViewModel.ActivityViewModel.SzActivity"
android:windowSoftInputMode="adjustPan"
android:screenOrientation="portrait"
android:exported="false" />
<activity
android:name=".modules.home.fragment.from.SzActivity"
android:name=".ui.activity.SetSeasoningActivity"
android:windowSoftInputMode="adjustPan"
android:screenOrientation="portrait"
android:exported="false" />
<activity
android:name=".modules.home.fragment.from.WhActivity"
android:name=".ui.activity.EditClassifyActivity"
android:windowSoftInputMode="adjustPan"
android:screenOrientation="portrait"
android:exported="false" />
<activity
android:name=".modules.home.fragment.from.CpActivity"
android:name=".ViewModel.ActivityViewModel.WhActivity"
android:screenOrientation="portrait"
android:exported="false" />
<activity
android:name=".modules.home.fragment.from.DiyActivity"
android:name=".ViewModel.ActivityViewModel.CpActivity"
android:screenOrientation="portrait"
android:exported="false" />
<activity
android:name=".modules.mine.fragment.from.NoticeActivity"
android:name=".ViewModel.ActivityViewModel.DiyActivity"
android:screenOrientation="portrait"
android:exported="false" />
<activity
android:name=".ViewModel.ActivityViewModel.NoticeActivity"
android:screenOrientation="portrait"
android:exported="false" />

<provider
@@ -108,8 +180,9 @@
</provider>

<activity
android:name=".modules.welcome.activity.WelcomeActivity"
android:name=".ViewModel.ActivityViewModel.WelcomeActivity"
android:exported="true"
android:screenOrientation="portrait"
android:theme="@style/AppTheme.Launcher">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
@@ -117,10 +190,11 @@
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".modules.welcome.activity.LoginActivity">
<activity android:name=".ViewModel.ActivityViewModel.LoginActivity"
android:launchMode="singleTask">

<!-- <intent-filter> -->
<!-- <action android:name="com.bonait.bnframework.modules.welcome.activity.LoginActivity.ACTION_START" /> -->
<!-- <action android:name="com.bonait.bnframework.ViewModel.ActivityViewModel.LoginActivity.ACTION_START" /> -->


<!-- <category android:name="android.intent.category.DEFAULT" /> -->
@@ -136,8 +210,9 @@
</intent-filter>
-->
</activity>
<activity android:name=".modules.home.activity.BottomNavigation2Activity" />
<activity android:name=".modules.home.activity.BottomNavigationActivity" /> <!-- <service android:name="org.eclipse.paho.android.service.MqttService" /> -->
<activity android:name=".ViewModel.ActivityViewModel.BottomNavigation2Activity"
android:screenOrientation="portrait"/>

<receiver
android:name=".common.base.BootReceiver"
android:exported="true">
@@ -147,6 +222,12 @@
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</receiver>
<meta-data
android:name="design_width_in_dp"
android:value="800" />
<meta-data
android:name="design_height_in_dp"
android:value="1208" />
</application>

</manifest>

+ 22
- 0
app/src/main/assets/error_code.json Ver fichero

@@ -0,0 +1,22 @@
[
{
"code": 0,
"description": "正常",
"name": "设备"
},
{
"code": 1,
"description": "机芯散热器温度超过 78℃",
"name": "IGBT过热"
},
{
"code": 2,
"description": "电源电压过高大于 450V",
"name": "直流母线过压"
},
{
"code": 3,
"description": "直流母线欠压",
"name": "电源电压过低低于300V"
}
]

+ 535
- 0
app/src/main/java/com/bonait/bnframework/HBL/API/APIHelper.java Ver fichero

@@ -0,0 +1,535 @@
package com.bonait.bnframework.HBL.API;

import com.bonait.bnframework.HBL.Interface.IRunT;
import com.bonait.bnframework.HBL.Logs.MessageLog;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.lang.reflect.Field;
import java.lang.reflect.Type;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicReference;

public class APIHelper {

private static String key="64059261-1599-472c-b418-3c18b4e3883e";

/**
* 获取加密后的签名
* @param t
* @return
*/
public static String GetSign(Object t,String key){
AtomicReference<String> retstr = new AtomicReference<>("");
List<Field> fields = Arrays.asList(t.getClass().getFields());
Collections.sort(fields, Comparator.comparing(Field::getName));
fields.forEach(item->{
if( item.getName().toUpperCase()!="sign".toUpperCase()){
try {
if(item.get(t)!=null&&!item.get(t).toString().isEmpty()){
Type type = item.getGenericType();
String typeName = type.toString();
switch(typeName){
case "class java.util.Date":
case "class java.lang.String":
case "byte":
case "int":
case "float":
case "double":
case "long":
case "short":
case "boolean":
retstr.set(retstr.get() + item.getName() + "=" + item.get(t) + "&");
break;
default:
// String a= new GsonBuilder().serializeNulls().create().toJson(item.get(t));//保留为空的属性
String a= new Gson().toJson(item.get(t));
retstr.set(retstr.get() + item.getName() + "=" + a + "&");
break;
}
}
} catch (Exception e) {
}
}
});
String tempSign="&key="+key;
if(retstr.get().length()>0){
tempSign=retstr.get().substring(0, retstr.get().length()-1)+"&key="+key;
}
// String tempSign=retstr.get().substring(0, retstr.get().length()-1)+"&key="+key;
StringBuilder sb = new StringBuilder();
try{
MessageDigest md = MessageDigest.getInstance("MD5");
byte[] digest = md.digest(tempSign.toUpperCase().getBytes());
for (byte b : digest) {
sb.append(Integer.toHexString((b & 0xFF) | 0x100).substring(1,3));
}
}catch (Exception e){

}
return sb.toString().toUpperCase();
}

public static String Post(String url, Map<String, String> parameters, Map<String, String> headers) throws IOException {
HttpURLConnection connection = null;
InputStream inputStream = null;
BufferedReader reader = null;
StringBuffer buffer = new StringBuffer();
try {
URL requestUrl = new URL(url);
connection = (HttpURLConnection) requestUrl.openConnection();
connection.setRequestMethod("POST");
connection.setConnectTimeout(5000);
connection.setReadTimeout(5000);
connection.setDoOutput(true);
connection.setDoInput(true);
// 设置header
if (headers != null) {
for (Map.Entry<String, String> entry : headers.entrySet()) {
connection.setRequestProperty(entry.getKey(), entry.getValue());
}
}
// 设置参数
if (parameters != null) {
StringBuilder stringBuilder = new StringBuilder();
for (Map.Entry<String, String> entry : parameters.entrySet()) {
stringBuilder.append(entry.getKey()).append("=").append(URLEncoder.encode(entry.getValue(), "UTF-8")).append("&");
}
String params = stringBuilder.toString();
byte[] postData = params.getBytes("UTF-8");
connection.setRequestProperty("Content-Length", Integer.toString(postData.length));
try (DataOutputStream outputStream = new DataOutputStream(connection.getOutputStream())) {
outputStream.write(postData);
}
}
// 获取响应结果
int statusCode = connection.getResponseCode();
if (statusCode == HttpURLConnection.HTTP_OK) {
inputStream = connection.getInputStream();
reader = new BufferedReader(new InputStreamReader(inputStream, StandardCharsets.UTF_8));
String line;
while ((line = reader.readLine()) != null) {
buffer.append(line);
}
} else {
throw new IOException("服务器返回错误,状态码:" + statusCode);
}
}catch (Exception e){
MessageLog.ShowError("POST 请求异常:"+e.toString());
}finally {
// 关闭连接和流
if (reader != null) {
reader.close();
}
if (inputStream != null) {
inputStream.close();
}
if (connection != null) {
connection.disconnect();
}
}
return buffer.toString();
}
public static String Post(String url, String body, Map<String, String> headers) throws IOException {
HttpURLConnection connection = null;
InputStream inputStream = null;
BufferedReader reader = null;
StringBuffer buffer = new StringBuffer();
try {
URL requestUrl = new URL(url);
connection = (HttpURLConnection) requestUrl.openConnection();
connection.setRequestMethod("POST");
connection.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 5.2; Trident/4.0; .NET CLR 1.1.4322; .NET CLR 2.0.50727; .NET CLR 3.0.04506.30; .NET CLR 3.0.4506.2152; .NET CLR 3.5.30729)");// "Fiddler"
connection.setRequestProperty("Content-Type", "application/json");
connection.setRequestProperty("Charset", "UTF-8");
connection.setConnectTimeout(5000);
connection.setReadTimeout(5000);
connection.setDoOutput(true);
connection.setDoInput(true);
// 设置header
if (headers != null) {
for (Map.Entry<String, String> entry : headers.entrySet()) {
connection.setRequestProperty(entry.getKey(), entry.getValue());
}
}
// 设置参数
if (!body .isEmpty()) {
connection.setRequestProperty("Content-Length", Integer.toString(body.getBytes().length));
try (DataOutputStream outputStream = new DataOutputStream(connection.getOutputStream())) {
outputStream.write(body.getBytes());
}
}
// 获取响应结果
int statusCode = connection.getResponseCode();
if (statusCode == HttpURLConnection.HTTP_OK) {
inputStream = connection.getInputStream();
reader = new BufferedReader(new InputStreamReader(inputStream, StandardCharsets.UTF_8));
String line;
while ((line = reader.readLine()) != null) {
buffer.append(line);
}
} else {
throw new IOException("服务器返回错误,状态码:" + statusCode);
}
}catch (Exception e){
MessageLog.ShowError("POST 请求异常:"+e.toString());
}finally {
// 关闭连接和流
if (reader != null) {
reader.close();
}
if (inputStream != null) {
inputStream.close();
}
if (connection != null) {
connection.disconnect();
}
}
return buffer.toString();
}
public static String Post(String url, Object body, Map<String, String> headers) throws IOException {
HttpURLConnection connection = null;
InputStream inputStream = null;
BufferedReader reader = null;
StringBuffer buffer = new StringBuffer();
try {
URL requestUrl = new URL(url);
connection = (HttpURLConnection) requestUrl.openConnection();
connection.setRequestMethod("POST");
connection.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 5.2; Trident/4.0; .NET CLR 1.1.4322; .NET CLR 2.0.50727; .NET CLR 3.0.04506.30; .NET CLR 3.0.4506.2152; .NET CLR 3.5.30729)");// "Fiddler"
connection.setRequestProperty("Content-Type", "application/json");
connection.setRequestProperty("Charset", "UTF-8");
connection.setConnectTimeout(5000);
connection.setReadTimeout(5000);
connection.setDoOutput(true);
connection.setDoInput(true);
// 设置header
if (headers != null) {
for (Map.Entry<String, String> entry : headers.entrySet()) {
connection.setRequestProperty(entry.getKey(), entry.getValue());
}
}
// 设置参数
if (body !=null) {
byte[] bytes = new Gson().toJson(body).getBytes();
connection.setRequestProperty("Content-Length", Integer.toString(bytes.length));
try (DataOutputStream outputStream = new DataOutputStream(connection.getOutputStream())) {
outputStream.write(bytes);
}
}
// 获取响应结果
int statusCode = connection.getResponseCode();
if (statusCode == HttpURLConnection.HTTP_OK) {
inputStream = connection.getInputStream();
reader = new BufferedReader(new InputStreamReader(inputStream, StandardCharsets.UTF_8));
String line;
while ((line = reader.readLine()) != null) {
buffer.append(line);
}
} else {
throw new IOException("服务器返回错误,状态码:" + statusCode);
}
}catch (Exception e){
MessageLog.ShowError("POST 请求异常:"+e.toString());
}finally {
// 关闭连接和流
if (reader != null) {
reader.close();
}
if (inputStream != null) {
inputStream.close();
}
if (connection != null) {
connection.disconnect();
}
}
return buffer.toString();
}
public static void Post(String url, Object body, IRunT<APIResult> callback) {
new Thread(()->{
HttpURLConnection connection = null;
InputStream inputStream = null;
BufferedReader reader = null;
StringBuffer buffer = new StringBuffer();
try {
URL requestUrl = new URL(url);
connection = (HttpURLConnection) requestUrl.openConnection();
connection.setRequestMethod("POST");
connection.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 5.2; Trident/4.0; .NET CLR 1.1.4322; .NET CLR 2.0.50727; .NET CLR 3.0.04506.30; .NET CLR 3.0.4506.2152; .NET CLR 3.5.30729)");// "Fiddler"
connection.setRequestProperty("Content-Type", "application/json");
connection.setRequestProperty("Charset", "UTF-8");
connection.setConnectTimeout(5000);
connection.setReadTimeout(5000);
connection.setDoOutput(true);
connection.setDoInput(true);

if(body!=null){
//获取签名信息
String sign = GetSign(body,key);

//设置请求头
connection.setRequestProperty("key", key);
connection.setRequestProperty("sign", sign);


//设置请求 body
byte[] bytes = new Gson().toJson(body).getBytes();
connection.setRequestProperty("Content-Length", Integer.toString(bytes.length));
try (DataOutputStream outputStream = new DataOutputStream(connection.getOutputStream())) {
outputStream.write(bytes);
}
}

// 获取响应结果
int statusCode = connection.getResponseCode();
if (statusCode == HttpURLConnection.HTTP_OK) {
inputStream = connection.getInputStream();
reader = new BufferedReader(new InputStreamReader(inputStream, StandardCharsets.UTF_8));
String line;
while ((line = reader.readLine()) != null) {
buffer.append(line);
}
} else {
throw new IOException("服务器返回错误,状态码:" + statusCode);
}
}catch (Exception e){
MessageLog.ShowError("POST 请求异常:"+e.toString());
return;
}finally {
try{
// 关闭连接和流
if (reader != null) reader.close();

if (inputStream != null) inputStream.close();

if (connection != null) connection.disconnect();

}catch(Exception e){
MessageLog.ShowError("POST 请求异常:"+e.toString());
return;
}
}

try{
APIResult res = new GsonBuilder().serializeNulls().create().fromJson(buffer.toString(), APIResult.class);
if(res!=null)if(callback!=null) callback.Run(res);
}catch(Exception e){

}
}).start();

}
public static void Post(String url, Object body,String signkey, IRunT<APIResult> callback) {
new Thread(()->{
HttpURLConnection connection = null;
InputStream inputStream = null;
BufferedReader reader = null;
StringBuffer buffer = new StringBuffer();
try {
URL requestUrl = new URL(url);
connection = (HttpURLConnection) requestUrl.openConnection();
connection.setRequestMethod("POST");
connection.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 5.2; Trident/4.0; .NET CLR 1.1.4322; .NET CLR 2.0.50727; .NET CLR 3.0.04506.30; .NET CLR 3.0.4506.2152; .NET CLR 3.5.30729)");// "Fiddler"
connection.setRequestProperty("Content-Type", "application/json");
connection.setRequestProperty("Charset", "UTF-8");
connection.setConnectTimeout(5000);
connection.setReadTimeout(5000);
connection.setDoOutput(true);
connection.setDoInput(true);

if(body!=null){
//获取签名信息
String sign = GetSign(body,signkey);

MessageLog.ShowInfo("签名信息:"+sign);

//设置请求头
connection.setRequestProperty("key", signkey);
// connection.setRequestProperty("sign", sign);


//设置请求 body
byte[] bytes = new Gson().toJson(body).getBytes();
connection.setRequestProperty("Content-Length", Integer.toString(bytes.length));
try (DataOutputStream outputStream = new DataOutputStream(connection.getOutputStream())) {
outputStream.write(bytes);
}
}

// 获取响应结果
int statusCode = connection.getResponseCode();
if (statusCode == HttpURLConnection.HTTP_OK) {
inputStream = connection.getInputStream();
reader = new BufferedReader(new InputStreamReader(inputStream, StandardCharsets.UTF_8));
String line;
while ((line = reader.readLine()) != null) {
buffer.append(line);
}
} else {
throw new IOException("服务器返回错误,状态码:" + statusCode);
}
}catch (Exception e){
MessageLog.ShowError("POST 请求异常:"+e.toString());
return;
}finally {
try{
// 关闭连接和流
if (reader != null) reader.close();

if (inputStream != null) inputStream.close();

if (connection != null) connection.disconnect();

}catch(Exception e){
MessageLog.ShowError("POST 请求异常:"+e.toString());
return;
}
}

try{
APIResult res = new GsonBuilder().serializeNulls().create().fromJson(buffer.toString(), APIResult.class);
if(res!=null)if(callback!=null) callback.Run(res);
}catch(Exception e){
MessageLog.ShowError("POST 请求异常:"+e.toString());
}
}).start();

}

public static <T> void PostT(String url, Object body,String signkey ,IRunT<APIResultT<T>> callback) {
new Thread(()->{
HttpURLConnection connection = null;
InputStream inputStream = null;
BufferedReader reader = null;
StringBuffer buffer = new StringBuffer();
try {
URL requestUrl = new URL(url);
connection = (HttpURLConnection) requestUrl.openConnection();
connection.setRequestMethod("POST");
connection.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 5.2; Trident/4.0; .NET CLR 1.1.4322; .NET CLR 2.0.50727; .NET CLR 3.0.04506.30; .NET CLR 3.0.4506.2152; .NET CLR 3.5.30729)");// "Fiddler"
connection.setRequestProperty("Content-Type", "application/json");
connection.setRequestProperty("Charset", "UTF-8");
connection.setConnectTimeout(5000);
connection.setReadTimeout(5000);
connection.setDoOutput(true);
connection.setDoInput(true);

if(body!=null){
//获取签名信息
String sign = GetSign(body,signkey);

//设置请求头
connection.setRequestProperty("key", signkey);
connection.setRequestProperty("sign", sign);


//设置请求 body
byte[] bytes = new Gson().toJson(body).getBytes();
connection.setRequestProperty("Content-Length", Integer.toString(bytes.length));
try (DataOutputStream outputStream = new DataOutputStream(connection.getOutputStream())) {
outputStream.write(bytes);
}
}

// 获取响应结果
int statusCode = connection.getResponseCode();
if (statusCode == HttpURLConnection.HTTP_OK) {
inputStream = connection.getInputStream();
reader = new BufferedReader(new InputStreamReader(inputStream, StandardCharsets.UTF_8));
String line;
while ((line = reader.readLine()) != null) {
buffer.append(line);
}
} else {
throw new IOException("服务器返回错误,状态码:" + statusCode);
}
}catch (Exception e){
MessageLog.ShowError("POST 请求异常:"+e.toString());
return;
}finally {
try{
// 关闭连接和流
if (reader != null) reader.close();
if (inputStream != null) inputStream.close();
if (connection != null) connection.disconnect();
}catch(Exception e){
MessageLog.ShowError("POST 请求异常:"+e.toString());
return;
}
}
try{

APIResultT<T> res = new GsonBuilder().serializeNulls().create().fromJson(buffer.toString(), APIResultT.class);
if(res!=null)if(callback!=null) callback.Run(res);
}catch(Exception e){
MessageLog.ShowError("POST请求返回值解析异常,"+e.toString());
}
}).start();

}
public static void get(String urlAdd,Map<String,String> params,IRunT<String> callback) {
new Thread(()->{
try {
String ResponseAdd = BuildUrlWithParams(urlAdd,params);//请求地址和参数
URL url = new URL(ResponseAdd);
HttpURLConnection Connection = (HttpURLConnection) url.openConnection();
Connection.setRequestMethod("GET");
Connection.setConnectTimeout(3000);
Connection.setReadTimeout(3000);
int responseCode = Connection.getResponseCode();
if (responseCode == Connection.HTTP_OK) {
InputStream inputStream = Connection.getInputStream();
ByteArrayOutputStream arrayOutputStream = new ByteArrayOutputStream();
byte[] bytes = new byte[1024];
int length = 0;
while ((length = inputStream.read(bytes)) != -1) {
arrayOutputStream.write(bytes, 0, length);
arrayOutputStream.flush();//强制释放缓冲区
}
String s = arrayOutputStream.toString();
if(callback!=null)callback.Run(s);
} else {
MessageLog.ShowError("get 请求失败");
}
} catch (Exception e) {
MessageLog.ShowError(e);
}
}).start();
}

/**
* 请求参数拼接
* @param Url 请求地址
* @param params 请求参数
* @return
*/
public static String BuildUrlWithParams(String Url,Map<String,String> params){
StringBuilder sb = new StringBuilder(Url);
if(params!=null&&!params.isEmpty()){
sb.append("?");

params.forEach((key,value)->{
sb.append(key).append("=").append(value).append("&");
});

sb.deleteCharAt(sb.length()-1);
}
return sb.toString();
}

}

+ 21
- 0
app/src/main/java/com/bonait/bnframework/HBL/API/APIResult.java Ver fichero

@@ -0,0 +1,21 @@
package com.bonait.bnframework.HBL.API;

import com.google.gson.GsonBuilder;

public class APIResult {
public int statusCode ;

public Object data ;

public String succeeded ;

public String errors ;

public String extras ;

public int timestamp ;

public String toString(){
return new GsonBuilder().serializeNulls().create().toJson(this);//保留为空的属性
}
}

+ 21
- 0
app/src/main/java/com/bonait/bnframework/HBL/API/APIResultT.java Ver fichero

@@ -0,0 +1,21 @@
package com.bonait.bnframework.HBL.API;

import com.google.gson.GsonBuilder;

public class APIResultT<T> {
public int statusCode ;

public T data ;

public String succeeded ;

public String errors ;

public String extras ;

public int timestamp ;

public String toString(){
return new GsonBuilder().serializeNulls().create().toJson(this);//保留为空的属性
}
}

+ 57
- 0
app/src/main/java/com/bonait/bnframework/HBL/API/Utils.java Ver fichero

@@ -0,0 +1,57 @@
package com.bonait.bnframework.HBL.API;

import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.security.cert.X509Certificate;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;

public class Utils {

/**
* 禁用SSL验证
*/
public static void disableSSLCertChecking() {
try {
TrustManager[] trustAllCerts = new TrustManager[]{
new X509TrustManager() {
public X509Certificate[] getAcceptedIssuers() {
return new X509Certificate[0];
}

@Override
public void checkClientTrusted(X509Certificate[] certs, String authType) {
}

@Override
public void checkServerTrusted(X509Certificate[] certs, String authType) {
}
}
};

SSLContext sc = SSLContext.getInstance("SSL");
sc.init(null, trustAllCerts, new SecureRandom());
HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());

// Create all-trusting host name verifier
HostnameVerifier allHostsValid = new HostnameVerifier() {
public boolean verify(String hostname, SSLSession session) {
return true;
}
};

// Install the all-trusting host verifier
HttpsURLConnection.setDefaultHostnameVerifier(allHostsValid);
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (KeyManagementException e) {
e.printStackTrace();
}
}
}

+ 44
- 0
app/src/main/java/com/bonait/bnframework/HBL/Communication/CommBase.java Ver fichero

@@ -0,0 +1,44 @@
package com.bonait.bnframework.HBL.Communication;

import java.io.IOException;
import java.io.InputStreamReader;
import java.io.LineNumberReader;

public class CommBase {
/**
* Ping PLC地址是否通畅
* @param address
* @param pingTimes ping的次数
* @param timeOut 超时时间 10
* @return
*/
public boolean NetPing(String address, int pingTimes, int timeOut) {
Process process = null;
try {
process = Runtime.getRuntime().exec( "ping " + "-c " + pingTimes + " -w " + timeOut+ " "+address);
InputStreamReader r = new InputStreamReader(process.getInputStream());
LineNumberReader returnData = new LineNumberReader(r);
String returnMsg="";
String line = "";
while ((line = returnData.readLine()) != null) {
System.out.println(line);
returnMsg += line;
}

if(returnMsg.indexOf("100% packet loss")!=-1){
System.out.println("与 " +address +" 连接不畅通.");
//ToastUtils.info("与 " +address +" 连接不畅通.");
return false;
} else{
System.out.println("与 " +address +" 连接畅通.");
//ToastUtils.info("与 " +address +" 连接不畅通.");
return true;
}
} catch (IOException e) {
// e.printStackTrace();
}
return false;

}

}

+ 86
- 0
app/src/main/java/com/bonait/bnframework/HBL/Communication/Modbus/ExceptionServer.java Ver fichero

@@ -0,0 +1,86 @@
package com.bonait.bnframework.HBL.Communication.Modbus;

import com.bonait.bnframework.HBL.Logs.MessageLog;
import com.licheedev.modbus4android.ModbusRespException;
import com.serotonin.modbus4j.exception.ModbusInitException;
import com.serotonin.modbus4j.exception.ModbusTransportException;

import java.util.concurrent.ExecutionException;

public class ExceptionServer {

public ExceptionServer(String Address, int length,IExceptionHandling excpet)
{
try {
int add = GetAddress(Address);
MessageLog.ShowInfo( "ExceptionServer add="+add);
if (add < 0) {
MessageLog.ShowError("地址解析失败=" + Address);
return;
}
if (excpet!=null) excpet.onSuccess(add);
} catch (InterruptedException e) {
if (excpet!=null) excpet.onFailure(e.toString());
} catch (ExecutionException e) {
if (excpet!=null) excpet.onFailure(e.toString());
} catch (ModbusTransportException e) {
if (excpet!=null) excpet.onFailure(e.toString());
} catch (ModbusInitException e) {
if (excpet!=null) excpet.onFailure(e.toString());
} catch (ModbusRespException e) {
if (excpet!=null) excpet.onFailure(e.toString());
}
}

public int GetAddress(String address) {
MessageLog.ShowInfo("GetAddress address="+address);
if (address == null) return -1;
if (address.length() > 0) {
address = address.trim();
try{
if (address.toUpperCase().contains("M") &&address.toUpperCase().contains(".")&& address.length() >= 4) {
String[] res = address.substring(1).split("[.]");
if (res != null && res.length == 2) {
int firstAdd = Integer.parseInt(res[0]);
int endAdd = Integer.parseInt(res[1]);
if (endAdd >= 0 && endAdd <= 7) {
return (firstAdd * 8) + 320 + endAdd;
}
}
} else if (address.toUpperCase().contains("I") && address.length() >= 4) {
String[] res = address.substring(1).split("[.]");
if (res != null && res.length == 2) {
int firstAdd = Integer.parseInt(res[0]);
int endAdd = Integer.parseInt(res[1]);
if (endAdd >= 0 && endAdd <= 7) {
return (firstAdd * 8) + endAdd;
}
}
} else if ((address.toUpperCase().contains("VW") || address.toUpperCase().contains("VD")) && address.length() >= 3) {
String res = address.substring(2);
if (res != null) {
int tempAdd = Integer.parseInt(res);
return (tempAdd / 2) + 100;
}
}else if (address.toUpperCase().contains("M")&&address.length() >=2){
return Integer.parseInt(address.substring(1));
}else if (address.toUpperCase().contains("X")&&address.length() >=2){
int xadd = Integer.parseInt( address.substring(1));
return (xadd / 10 * 8) + xadd % 10;
// return 42936+xadd;
}else if (address.toUpperCase().contains("Y")&&address.length() >=2){
int yadd = Integer.parseInt( address.substring(1));
return ((yadd / 10 * 8) + yadd % 10) + 300;
}else if (address.toUpperCase().contains("D")&&address.length() >=2){
return Integer.parseInt( address.substring(1));
}
else {
return Integer.parseInt(address);
}
}catch (Exception e){
MessageLog.ShowError(e);
}
}
return -1;
}
}

+ 15
- 0
app/src/main/java/com/bonait/bnframework/HBL/Communication/Modbus/IExceptionHandling.java Ver fichero

@@ -0,0 +1,15 @@
package com.bonait.bnframework.HBL.Communication.Modbus;

import com.licheedev.modbus4android.ModbusRespException;
import com.serotonin.modbus4j.exception.ModbusInitException;
import com.serotonin.modbus4j.exception.ModbusTransportException;

import java.util.concurrent.ExecutionException;

public interface IExceptionHandling {
void onSuccess(int add)throws InterruptedException, ExecutionException, ModbusTransportException,
ModbusInitException, ModbusRespException;


void onFailure(String error);
}

+ 10
- 0
app/src/main/java/com/bonait/bnframework/HBL/Communication/Modbus/IModbusMaster.java Ver fichero

@@ -0,0 +1,10 @@
package com.bonait.bnframework.HBL.Communication.Modbus;

import com.bonait.bnframework.HBL.Result.OperateResult;

public interface IModbusMaster {
OperateResult TcpConnect(String ip, int port);
OperateResult RtuConnect(String com, int baudRate);
boolean getConnected();

}

+ 24
- 0
app/src/main/java/com/bonait/bnframework/HBL/Communication/Modbus/IRead.java Ver fichero

@@ -0,0 +1,24 @@
package com.bonait.bnframework.HBL.Communication.Modbus;

import com.bonait.bnframework.HBL.Result.OperateResultT;

public interface IRead {

OperateResultT<boolean[]> ReadBool(String address, int length);
OperateResultT<Boolean> ReadBool(String address);
OperateResultT<boolean[]> ReadInputCoil(String address, int length);
OperateResultT<Boolean> ReadInputCoil(String address);

OperateResultT<short[]> ReadShort(String address, int length);
OperateResultT<Short> ReadShort(String address);

OperateResultT<int[]> ReadInt(String address, int length);
OperateResultT<Integer> ReadInt(String address);

OperateResultT<byte[]> ReadByte(String address, int length);

OperateResultT<String> ReadString(String address, int length);

OperateResultT<float[]> ReadFloat(String address, int length);
OperateResultT<Float> ReadFloat(String address);
}

+ 23
- 0
app/src/main/java/com/bonait/bnframework/HBL/Communication/Modbus/IWrite.java Ver fichero

@@ -0,0 +1,23 @@
package com.bonait.bnframework.HBL.Communication.Modbus;

import com.bonait.bnframework.HBL.Result.OperateResult;

public interface IWrite {
OperateResult WriteBool(String address, boolean value);
OperateResult WriteBool(String address, boolean[] value);
OperateResult WriteBool(String address, boolean[] value, int slaveId);

OperateResult WriteShort(String address, short value);
OperateResult WriteShort(String address, short[] value);
OperateResult WriteShort(String address, short[] value, int slaveId);

OperateResult WriteInt(String address, int value);
OperateResult WriteInt(String address, int[] value);
OperateResult WriteInt(String address, int[] value, int slaveId);

OperateResult WriteString(String address, String value, int slaveId);

OperateResult WriteFloat(String address, float value);
OperateResult WriteFloat(String address, float[] value);
OperateResult WriteFloat(String address, float[] value, int slaveId);
}

+ 727
- 0
app/src/main/java/com/bonait/bnframework/HBL/Communication/Modbus/ModbusMaster.java Ver fichero

@@ -0,0 +1,727 @@
package com.bonait.bnframework.HBL.Communication.Modbus;

import static com.bonait.bnframework.HBL.DataUtil.DataConvertLib.ByteToShort;

import com.apkfuns.logutils.LogUtils;
import com.bonait.bnframework.HBL.Communication.CommBase;
import com.bonait.bnframework.HBL.DataUtil.DataConvertLib;
import com.bonait.bnframework.HBL.DataUtil.FloatLib;
import com.bonait.bnframework.HBL.DataUtil.IntLib;
import com.bonait.bnframework.HBL.DataUtil.ShortLib;
import com.bonait.bnframework.HBL.Enum.DataFormat;
import com.bonait.bnframework.HBL.Logs.MessageLog;
import com.bonait.bnframework.HBL.Result.OperateResult;
import com.bonait.bnframework.HBL.Result.OperateResultT;
import com.bonait.bnframework.common.constant.ConfigName;
import com.licheedev.modbus4android.ModbusCallback;
import com.licheedev.modbus4android.ModbusParam;
import com.licheedev.modbus4android.ModbusRespException;
import com.licheedev.modbus4android.ModbusWorker;
import com.licheedev.modbus4android.param.SerialParam;
import com.licheedev.modbus4android.param.TcpParam;
import com.serotonin.modbus4j.exception.ModbusInitException;
import com.serotonin.modbus4j.exception.ModbusTransportException;
import com.serotonin.modbus4j.msg.ReadCoilsResponse;
import com.serotonin.modbus4j.msg.ReadDiscreteInputsResponse;
import com.serotonin.modbus4j.msg.ReadHoldingRegistersResponse;
import com.serotonin.modbus4j.msg.WriteCoilResponse;
import com.serotonin.modbus4j.msg.WriteRegistersResponse;

import java.io.UnsupportedEncodingException;
import java.util.Arrays;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.atomic.AtomicReference;

public class ModbusMaster implements IRead,IWrite ,IModbusMaster{
private final static String TAG = "ModbusMaster==>";
private boolean IsConnected=false;

private ModbusWorker mw = new ModbusWorker();

public void DisConnect(){
IsConnected = false;
IsReconnection = false;
mw.release(); }

public boolean IsReconnection=true;
public DataFormat WriteDataFormat= DataFormat.ABCD;

public DataFormat ReadDataFormat= DataFormat.BADC;

public int SlaveId=1;

@Override
public OperateResult TcpConnect(String ip, int port) {
try{
MessageLog.ShowInfo("开始验证网络:"+ip );
boolean status = false;
while (!status&&IsReconnection) {
try {
status =new CommBase().NetPing(ip,1,1);//status为0则代表通,为1则代表不通。
Thread.sleep(1000);
} catch (Exception e) {
MessageLog.ShowInfo("设备 " + ip + " 网络验证失败");
}
}
MessageLog.ShowInfo("开始连接Modbus TCP" );
ModbusParam param= TcpParam.create(ip, port).setTimeout(1000).setRetries(0).setEncapsulated(false).setKeepAlive(true);
AtomicReference<String> errorInfo=new AtomicReference<>("");
while (IsConnected==false)
{
errorInfo.set("");
mw.init(param, new ModbusCallback<com.serotonin.modbus4j.ModbusMaster>() {
@Override
public void onSuccess(com.serotonin.modbus4j.ModbusMaster modbusMaster) {
IsConnected=true;
MessageLog.ShowInfo("Modbus TCP 连接成功" );
}
@Override
public void onFailure(Throwable tr) {
IsConnected = false;
errorInfo.set(tr.getMessage());
MessageLog.ShowInfo("Modbus TCP 连接失败" );
}
@Override
public void onFinally() {

}
});
if(!IsReconnection)break;
if(IsConnected==false) Thread.sleep(5000);
}
if(IsConnected)return OperateResult.CreateSuccess();
else return OperateResult.CreateFailed(errorInfo.get());
}catch(Exception ex){
return OperateResult.CreateFailed(ex);
}
}

@Override
public OperateResult RtuConnect(String com, int baudRate) {
try{
IsReconnection = true;
MessageLog.ShowInfo("开始连接Modbus RTU" );
ModbusParam param= SerialParam.create(com, baudRate) // 串口地址和波特率
.setDataBits(8) // 数据位
.setParity(0) // 校验位
.setStopBits(1) // 停止位
.setTimeout(500).setRetries(0); // 不重试
AtomicReference<String> errorInfo=new AtomicReference<>("");
while (IsConnected==false)
{
mw.init(param, new ModbusCallback<com.serotonin.modbus4j.ModbusMaster>() {
@Override
public void onSuccess(com.serotonin.modbus4j.ModbusMaster modbusMaster) {
IsConnected=true;
MessageLog.ShowInfo("Modbus RTU 连接成功" );
ConfigName.getInstance().PlcIsConnect = true;
}
@Override
public void onFailure(Throwable tr) {
IsConnected = false;
ConfigName.getInstance().PlcIsConnect = false;
errorInfo.set(tr.getMessage());
MessageLog.ShowInfo("Modbus RTU 连接失败" );
}
@Override
public void onFinally() {

}
});
if(IsConnected==false) Thread.sleep(5000);
}
if(IsConnected)return OperateResult.CreateSuccess();
else return OperateResult.CreateFailed(errorInfo.get());
}catch(Exception ex){
return OperateResult.CreateFailed(ex);
}
}

@Override
public boolean getConnected() {
return IsConnected;
}

public <T> OperateResultT<T> Read(String address, int length){
// if(!getConnected()){ return OperateResultT.CreateFailedT("设备未连接");}
AtomicReference<OperateResultT<T>>resultValue=new AtomicReference<OperateResultT<T>>();
try{
String typeName= resultValue.get().Content.getClass().getCanonicalName();
switch(typeName){
case "java.lang.String":
resultValue.set((OperateResultT<T>)ReadString(address,length));
break;
case "java.lang.Byte":
resultValue.set((OperateResultT<T>)ReadByte(address,1));
break;
case "java.lang.Integer":
resultValue.set((OperateResultT<T>)ReadInt(address));
break;
case "java.lang.Float":
resultValue.set((OperateResultT<T>)ReadFloat(address));
break;
case "java.lang.Short":
resultValue.set((OperateResultT<T>)ReadShort(address));
break;
case "java.lang.Boolean":
resultValue.set((OperateResultT<T>)ReadBool(address));
break;
case "int[]":
resultValue.set((OperateResultT<T>)ReadInt(address,length));
break;
case "float[]":
resultValue.set((OperateResultT<T>)ReadFloat(address,length));
break;
case "short[]":
resultValue.set((OperateResultT<T>)ReadShort(address,length));
break;
case "boolean[]":
resultValue.set((OperateResultT<T>)ReadBool(address,length));
break;
default:
resultValue.set(OperateResultT.CreateFailedT("不匹配的数据类型:"+typeName));
break;
}
}catch(Exception ex){
resultValue.set(OperateResultT.CreateFailedT(ex));
}
// if(result!=null)result.Run(resultValue.get());
return resultValue.get();
}

public <T> OperateResultT<T> Read(String address){
// if(!getConnected()){ return OperateResultT.CreateFailedT("设备未连接");}
AtomicReference<OperateResultT<T>>resultValue=new AtomicReference<>();
resultValue.set(Read(address,1));
return resultValue.get();
}
public <T> OperateResult Write(String address,T value) {
if(!getConnected()){ return OperateResult.CreateFailed("设备未连接");}
AtomicReference<OperateResult> resultValue=new AtomicReference<>();
try{
String typeName= value.getClass().getCanonicalName();
switch(typeName){
case "java.lang.String":
resultValue.set(WriteString(address,value.toString(),SlaveId));
break;
case "java.lang.Integer":
resultValue.set(WriteInt(address,Integer.parseInt(value.toString())));
break;
case "java.lang.Float":
resultValue.set(WriteFloat(address,Float.parseFloat(value.toString())));
break;
case "java.lang.Short":
resultValue.set(WriteShort(address,Short.parseShort(value.toString())));
break;
case "java.lang.Boolean":
resultValue.set(WriteBool(address,Boolean.parseBoolean(value.toString())));
break;
case "int[]":
resultValue.set(WriteInt(address,(int[])value));
break;
case "float[]":
resultValue.set(WriteFloat(address,(float[])value));
break;
case "short[]":
resultValue.set(WriteShort(address,(short[])value));
break;
case "boolean[]":
resultValue.set(WriteBool(address,(boolean[])value));
break;
default:
resultValue.set(OperateResult.CreateFailed("不匹配的数据类型:"+typeName));
break;
}
}catch(Exception ex){
resultValue.set(OperateResult.CreateFailed(ex));
}
return resultValue.get();
}

@Override
public OperateResultT<boolean[]> ReadBool(String address, int length) {
if(address==null||address.isEmpty()){ return OperateResultT.CreateFailedT("无效的地址");}
if(!getConnected()){ return OperateResultT.CreateFailedT("设备未连接");}
AtomicReference<OperateResultT<boolean[]>>resultValue=new AtomicReference<>();
new ExceptionServer(address, length, new IExceptionHandling() {
@Override
public void onSuccess(int add) throws InterruptedException, ExecutionException, ModbusTransportException, ModbusInitException, ModbusRespException {
ReadCoilsResponse res = mw.syncReadCoil(SlaveId, add, length);
boolean[] data = res.getBooleanData();
boolean[] result = Arrays.copyOfRange(data, 0, length);
if(ConfigName.LOG_TEST){
LogUtils.d(TAG+"ReadBool address="+address+" 读操作 成功:data="+data.toString()+" bytes="+result);
}
resultValue.set(OperateResultT.CreateSuccess(result));
}

@Override
public void onFailure(String error){
resultValue.set(OperateResultT.CreateFailedT(address+",读取异常:"+error));
}
});
return resultValue.get();
}

@Override
public OperateResultT<Boolean> ReadBool(String address) {
if(address==null||address.isEmpty()){ return OperateResultT.CreateFailedT("无效的地址");}
if(!getConnected()){ return OperateResultT.CreateFailedT("设备未连接");}
AtomicReference<OperateResultT<Boolean>>resultValue=new AtomicReference<>();
ReadBool(address,1).OnSource((s)->{
resultValue.set(OperateResultT.CreateSuccess(s.Content[0]));
}).OnFailed(s->{
resultValue.set(OperateResultT.CreateFailedT(s.message));
});
return resultValue.get();
}

@Override
public OperateResultT<boolean[]> ReadInputCoil(String address, int length) {
if(address==null||address.isEmpty()){ return OperateResultT.CreateFailedT("无效的地址");}
if(!getConnected()){ return OperateResultT.CreateFailedT("设备未连接");}
AtomicReference<OperateResultT<boolean[]>>resultValue=new AtomicReference<>();
new ExceptionServer(address, length, new IExceptionHandling() {
@Override
public void onSuccess(int add) throws InterruptedException, ExecutionException, ModbusTransportException, ModbusInitException, ModbusRespException {
ReadDiscreteInputsResponse res = mw.syncReadDiscreteInput(SlaveId, add, length);
boolean[] data = res.getBooleanData();
boolean[] result = Arrays.copyOfRange(data, 0, length);
resultValue.set(OperateResultT.CreateSuccess(result));
}

@Override
public void onFailure(String error){
resultValue.set(OperateResultT.CreateFailedT(address+",读取异常:"+error));
}
});
return resultValue.get();
}

@Override
public OperateResultT<Boolean> ReadInputCoil(String address) {
if(address==null||address.isEmpty()){ return OperateResultT.CreateFailedT("无效的地址");}
if(!getConnected()){ return OperateResultT.CreateFailedT("设备未连接");}
AtomicReference<OperateResultT<Boolean>>resultValue=new AtomicReference<>();
ReadInputCoil(address,1).OnSource((s)->{
resultValue.set(OperateResultT.CreateSuccess(s.Content[0]));
}).OnFailed(s->{
resultValue.set(OperateResultT.CreateFailedT(s.message));
});
return resultValue.get();
}

@Override
public OperateResultT<short[]> ReadShort(String address, int length) {
if(address==null||address.isEmpty()){ return OperateResultT.CreateFailedT("无效的地址");}
if(!getConnected()){ return OperateResultT.CreateFailedT("设备未连接");}
AtomicReference<OperateResultT<short[]>>resultValue=new AtomicReference<>();
new ExceptionServer(address, length, new IExceptionHandling() {
@Override
public void onSuccess(int add) throws InterruptedException, ExecutionException, ModbusTransportException, ModbusInitException, ModbusRespException {
ReadHoldingRegistersResponse res = mw.syncReadHoldingRegisters(SlaveId, add, length);
short[] data = res.getShortData();
byte[] bytes = DataConvertLib.shorts2Bytes(data);
String result = DataConvertLib.bytesToString(bytes);
if(ConfigName.LOG_TEST){
LogUtils.d(TAG+"ReadShort address="+address+" 读操作 成功:data="+data.toString()+" bytes="+result);
}
if (data.length == length) {
resultValue.set(OperateResultT.CreateSuccess(data));
}
}

@Override
public void onFailure(String error){
if(ConfigName.LOG_TEST){
LogUtils.d(TAG+"ReadShort address="+address+"读操作 失败:"+error);
}
resultValue.set(OperateResultT.CreateFailedT(address+",读取异常:"+error));
}
});
return resultValue.get();
}

@Override
public OperateResultT<Short> ReadShort(String address) {
if(address==null||address.isEmpty()){ return OperateResultT.CreateFailedT("无效的地址");}
if(!getConnected()){ return OperateResultT.CreateFailedT("设备未连接");}
AtomicReference<OperateResultT<Short>>resultValue=new AtomicReference<>();
ReadShort(address,1).OnSource((s)->{
resultValue.set(OperateResultT.CreateSuccess(s.Content[0]));
}).OnFailed(s->{
resultValue.set(OperateResultT.CreateFailedT(s.message));
});
return resultValue.get();
}
@Override
public OperateResultT<int[]> ReadInt(String address, int length) {
if(address==null||address.isEmpty()){ return OperateResultT.CreateFailedT("无效的地址");}
if(!getConnected()){ return OperateResultT.CreateFailedT("设备未连接");}
AtomicReference<OperateResultT<int[]>>resultValue=new AtomicReference<>();
new ExceptionServer(address, length, new IExceptionHandling() {
@Override
public void onSuccess(int add) throws InterruptedException, ExecutionException, ModbusTransportException, ModbusInitException, ModbusRespException {
ReadHoldingRegistersResponse res = mw.syncReadHoldingRegisters(SlaveId, add, length * 2);
int[] tempValues= IntLib.ToInts(res.getData(),ReadDataFormat);
if(tempValues.length==length){
resultValue.set(OperateResultT.CreateSuccess(tempValues));
}else{
resultValue.set(OperateResultT.CreateFailedT(address+",读取失败,返回长度和实际读取长度不匹配"));
}
}

@Override
public void onFailure(String error){
resultValue.set(OperateResultT.CreateFailedT(address+",读取异常:"+error));
}
});
return resultValue.get();
}

@Override
public OperateResultT<Integer> ReadInt(String address) {
if(address==null||address.isEmpty()){ return OperateResultT.CreateFailedT("无效的地址");}
if(!getConnected()){ return OperateResultT.CreateFailedT("设备未连接");}
AtomicReference<OperateResultT<Integer>>resultValue=new AtomicReference<>();
ReadInt(address,1).OnSource((s)->{
resultValue.set(OperateResultT.CreateSuccess(s.Content[0]));
}).OnFailed(s->{
resultValue.set(OperateResultT.CreateFailedT(s.message));
});
return resultValue.get();
}

@Override
public OperateResultT<byte[]> ReadByte(String address, int length) {
if(address==null||address.isEmpty()){ return OperateResultT.CreateFailedT("无效的地址");}
if(!getConnected()){ return OperateResultT.CreateFailedT("设备未连接");}
AtomicReference<OperateResultT<byte[]>>resultValue=new AtomicReference<>();
new ExceptionServer(address, length, new IExceptionHandling() {
@Override
public void onSuccess(int add) throws InterruptedException, ExecutionException, ModbusTransportException, ModbusInitException, ModbusRespException {
int tempLength=length;
if (length%2!=0){
tempLength++;
}
ReadHoldingRegistersResponse res = mw.syncReadHoldingRegisters(SlaveId, add, tempLength );
byte[] data = res.getData();

String ress= DataConvertLib.bytesToString(data);
if(ConfigName.LOG_TEST){
LogUtils.d(TAG+"ReadShort address="+address+" 读操作 成功:data="+data.toString()+" bytes="+ress);
}
if(data.length==tempLength){
byte[] result = Arrays.copyOfRange(data, 0, length);
resultValue.set(OperateResultT.CreateSuccess(result));
}else{
resultValue.set(OperateResultT.CreateFailedT(address+",读取失败,返回长度和实际读取长度不匹配"));
}
}

@Override
public void onFailure(String error){
resultValue.set(OperateResultT.CreateFailedT(address+",读取异常:"+error));
}
});
return resultValue.get();
}

@Override
public OperateResultT<String> ReadString(String address, int length) {
if(address==null||address.isEmpty()){ return OperateResultT.CreateFailedT("无效的地址");}
if(!getConnected()){ return OperateResultT.CreateFailedT("设备未连接");}
AtomicReference<OperateResultT<String>>resultValue=new AtomicReference<>();
new ExceptionServer(address, length, new IExceptionHandling() {
@Override
public void onSuccess(int add) throws InterruptedException, ExecutionException, ModbusTransportException, ModbusInitException, ModbusRespException {
ReadHoldingRegistersResponse res = mw.syncReadHoldingRegisters(SlaveId, add, length);
byte[] data = res.getData();
try {
if (data.length ==length*2) {
resultValue.set(OperateResultT.CreateSuccess(new String(data, "UTF-8").trim()));
}
} catch (UnsupportedEncodingException ex) {
resultValue.set(OperateResultT.CreateFailedT(address+",读取失败,字符串解析失败:"+ex.toString()));
}
}

@Override
public void onFailure(String error){
resultValue.set(OperateResultT.CreateFailedT(address+",读取异常:"+error));
}
});
return resultValue.get();
}

@Override
public OperateResultT<float[]> ReadFloat(String address, int length) {
if(address==null||address.isEmpty()){ return OperateResultT.CreateFailedT("无效的地址");}
if(!getConnected()){ return OperateResultT.CreateFailedT("设备未连接");}
AtomicReference<OperateResultT<float[]>>resultValue=new AtomicReference<>();
new ExceptionServer(address, length, new IExceptionHandling() {
@Override
public void onSuccess(int add) throws InterruptedException, ExecutionException, ModbusTransportException, ModbusInitException, ModbusRespException {
ReadHoldingRegistersResponse res = mw.syncReadHoldingRegisters(SlaveId, add, length*2);
float[] tempValues = FloatLib.ToFloats(res.getData(),ReadDataFormat);
if (tempValues.length == length) {
resultValue.set(OperateResultT.CreateSuccess(tempValues));
}else{
resultValue.set(OperateResultT.CreateFailedT(address+",读取失败,返回长度和实际读取长度不匹配"));
}
}

@Override
public void onFailure(String error){
resultValue.set(OperateResultT.CreateFailedT(address+",读取异常:"+error));
}
});
return resultValue.get();
}

@Override
public OperateResultT<Float> ReadFloat(String address) {
if(address==null||address.isEmpty()){ return OperateResultT.CreateFailedT("无效的地址");}
if(!getConnected()){ return OperateResultT.CreateFailedT("设备未连接");}
AtomicReference<OperateResultT<Float>>resultValue=new AtomicReference<>();
ReadFloat(address,1).OnSource((s)->{
resultValue.set(OperateResultT.CreateSuccess(s.Content[0]));
}).OnFailed(s->{
resultValue.set(OperateResultT.CreateFailedT(s.message));
});
return resultValue.get();
}

@Override
public OperateResult WriteBool(String address, boolean value) {
if(address==null||address.isEmpty()){ return OperateResult.CreateFailed("无效的地址");}
if(!getConnected()){ return OperateResult.CreateFailed("设备未连接");}
AtomicReference<OperateResult>resultValue=new AtomicReference<>();
new ExceptionServer(address, 1, new IExceptionHandling() {
@Override
public void onSuccess(int add) throws InterruptedException, ExecutionException, ModbusTransportException, ModbusInitException, ModbusRespException {
WriteCoilResponse response = mw.syncWriteCoil(SlaveId, add, value);
LogUtils.d(TAG+"WriteBool address="+address+" response ="+response.toString());
resultValue.set(OperateResult.CreateSuccess());
}
@Override
public void onFailure(String error){
resultValue.set(OperateResult.CreateFailed(address+",写入异常:"+error));
}
});
return resultValue.get();
}

@Override
public OperateResult WriteBool(String address, boolean[] value) {
if(address==null||address.isEmpty()){ return OperateResult.CreateFailed("无效的地址");}
if(!getConnected()){ return OperateResult.CreateFailed("设备未连接");}
AtomicReference<OperateResult>resultValue=new AtomicReference<>();
new ExceptionServer(address, 1, new IExceptionHandling() {
@Override
public void onSuccess(int add) throws InterruptedException, ExecutionException, ModbusTransportException, ModbusInitException, ModbusRespException {
mw.syncWriteCoils(SlaveId, add, value);
LogUtils.d(TAG+"WriteBool address=");
resultValue.set(OperateResult.CreateSuccess());
}

@Override
public void onFailure(String error){
resultValue.set(OperateResult.CreateFailed(address+",写入异常:"+error));
}
});
return resultValue.get();
}

@Override
public OperateResult WriteBool(String address, boolean[] value, int slaveId) {
if(address==null||address.isEmpty()){ return OperateResult.CreateFailed("无效的地址");}
if(!getConnected()){ return OperateResult.CreateFailed("设备未连接");}
AtomicReference<OperateResult>resultValue=new AtomicReference<>();
new ExceptionServer(address, 1, new IExceptionHandling() {
@Override
public void onSuccess(int add) throws InterruptedException, ExecutionException, ModbusTransportException, ModbusInitException, ModbusRespException {
mw.syncWriteCoils(slaveId, add, value);
LogUtils.d(TAG+"WriteBool address="+address);
resultValue.set(OperateResult.CreateSuccess());
}

@Override
public void onFailure(String error){
resultValue.set(OperateResult.CreateFailed(address+",写入异常:"+error));
}
});
return resultValue.get();
}

@Override
public OperateResult WriteShort(String address, short value) {
if(address==null||address.isEmpty()){ return OperateResult.CreateFailed("无效的地址");}
if(!getConnected()){ return OperateResult.CreateFailed("设备未连接");}
return WriteShort(address, new short[]{value});
}

@Override
public OperateResult WriteShort(String address, short[] value) {
if(address==null||address.isEmpty()){ return OperateResult.CreateFailed("无效的地址");}
if(!getConnected()){ return OperateResult.CreateFailed("设备未连接");}
AtomicReference<OperateResult>resultValue=new AtomicReference<>();
new ExceptionServer(address, 1, new IExceptionHandling() {
@Override
public void onSuccess(int add) throws InterruptedException, ExecutionException, ModbusTransportException, ModbusInitException, ModbusRespException {
WriteRegistersResponse response = mw.syncWriteRegisters(SlaveId, add, value);
resultValue.set(OperateResult.CreateSuccess());
if(ConfigName.LOG_TEST){
LogUtils.d(TAG+"WriteShort address="+address+" response ="+response.toString());
}
}

@Override
public void onFailure(String error){
resultValue.set(OperateResult.CreateFailed(address+",写入异常:"+error));
}
});
return resultValue.get();
}

@Override
public OperateResult WriteShort(String address, short[] value, int slaveId) {
if(address==null||address.isEmpty()){ return OperateResult.CreateFailed("无效的地址");}
if(!getConnected()){ return OperateResult.CreateFailed("设备未连接");}
AtomicReference<OperateResult>resultValue=new AtomicReference<>();
new ExceptionServer(address, 1, new IExceptionHandling() {
@Override
public void onSuccess(int add) throws InterruptedException, ExecutionException, ModbusTransportException, ModbusInitException, ModbusRespException {
mw.syncWriteRegisters(slaveId, add, value);
resultValue.set(OperateResult.CreateSuccess());
}

@Override
public void onFailure(String error){
resultValue.set(OperateResult.CreateFailed(address+",写入异常:"+error));
}
});
return resultValue.get();
}

@Override
public OperateResult WriteInt(String address, int value) {
if(address==null||address.isEmpty()){ return OperateResult.CreateFailed("无效的地址");}
if(!getConnected()){ return OperateResult.CreateFailed("设备未连接");}
return WriteInt(address, new int[]{value});
}

@Override
public OperateResult WriteInt(String address, int[] value) {
if(address==null||address.isEmpty()){ return OperateResult.CreateFailed("无效的地址");}
if(!getConnected()){ return OperateResult.CreateFailed("设备未连接");}
AtomicReference<OperateResult>resultValue=new AtomicReference<>();
new ExceptionServer(address, 1, new IExceptionHandling() {
@Override
public void onSuccess(int add) throws InterruptedException, ExecutionException, ModbusTransportException, ModbusInitException, ModbusRespException {
short[] send=ShortLib.ToShorts(value,WriteDataFormat);
mw.syncWriteRegisters(SlaveId, add,send);
resultValue.set(OperateResult.CreateSuccess());
}

@Override
public void onFailure(String error){
resultValue.set(OperateResult.CreateFailed(address+",写入异常:"+error));
}
});
return resultValue.get();
}

@Override
public OperateResult WriteInt(String address, int[] value, int slaveId) {
if(address==null||address.isEmpty()){ return OperateResult.CreateFailed("无效的地址");}
if(!getConnected()){ return OperateResult.CreateFailed("设备未连接");}
AtomicReference<OperateResult>resultValue=new AtomicReference<>();
new ExceptionServer(address, 1, new IExceptionHandling() {
@Override
public void onSuccess(int add) throws InterruptedException, ExecutionException, ModbusTransportException, ModbusInitException, ModbusRespException {
short[] send=ShortLib.ToShorts(value,WriteDataFormat);
mw. syncWriteRegisters(slaveId, add,send);
resultValue.set(OperateResult.CreateSuccess());
}

@Override
public void onFailure(String error){
resultValue.set(OperateResult.CreateFailed(address+",写入异常:"+error));
}
});
return resultValue.get();
}

@Override
public OperateResult WriteString(String address, String value, int slaveId) {
if(address==null||address.isEmpty()){ return OperateResult.CreateFailed("无效的地址");}
if(!getConnected()){ return OperateResult.CreateFailed("设备未连接");}
AtomicReference<OperateResult>resultValue=new AtomicReference<>();
new ExceptionServer(address, 1, new IExceptionHandling() {
@Override
public void onSuccess(int add) throws InterruptedException, ExecutionException, ModbusTransportException, ModbusInitException, ModbusRespException {
byte[] bytes= value.getBytes();
short[] send =ByteToShort(bytes);
mw.syncWriteRegisters(slaveId, add, send);
resultValue.set(OperateResult.CreateSuccess());
}

@Override
public void onFailure(String error){
resultValue.set(OperateResult.CreateFailed(address+",写入异常:"+error));
}
});
return resultValue.get();
}

@Override
public OperateResult WriteFloat(String address, float value) {
if(address==null||address.isEmpty()){ return OperateResult.CreateFailed("无效的地址");}
if(!getConnected()){ return OperateResult.CreateFailed("设备未连接");}
return WriteFloat(address, new float[]{value});
}

@Override
public OperateResult WriteFloat(String address, float[] value) {
if(address==null||address.isEmpty()){ return OperateResult.CreateFailed("无效的地址");}
if(!getConnected()){ return OperateResult.CreateFailed("设备未连接");}
AtomicReference<OperateResult>resultValue=new AtomicReference<>();
new ExceptionServer(address, 1, new IExceptionHandling() {
@Override
public void onSuccess(int add) throws InterruptedException, ExecutionException, ModbusTransportException, ModbusInitException, ModbusRespException {
short[] send=ShortLib.ToShorts(value,WriteDataFormat);
mw.syncWriteRegisters(SlaveId, add, send);
resultValue.set(OperateResult.CreateSuccess());
}

@Override
public void onFailure(String error){
resultValue.set(OperateResult.CreateFailed(address+",写入异常:"+error));
}
});
return resultValue.get();
}

@Override
public OperateResult WriteFloat(String address, float[] value, int slaveId) {
if(address==null||address.isEmpty()){ return OperateResult.CreateFailed("无效的地址");}
if(!getConnected()){ return OperateResult.CreateFailed("设备未连接");}
AtomicReference<OperateResult>resultValue=new AtomicReference<>();
new ExceptionServer(address, 1, new IExceptionHandling() {
@Override
public void onSuccess(int add) throws InterruptedException, ExecutionException, ModbusTransportException, ModbusInitException, ModbusRespException {
short[] send=ShortLib.ToShorts(value,WriteDataFormat);
mw.syncWriteRegisters(slaveId, add, send);
resultValue.set(OperateResult.CreateSuccess());
}

@Override
public void onFailure(String error){
resultValue.set(OperateResult.CreateFailed(address+",写入异常:"+error));
}
});
return resultValue.get();
}

}

+ 157
- 0
app/src/main/java/com/bonait/bnframework/HBL/Communication/Siemens/CommHelper.java Ver fichero

@@ -0,0 +1,157 @@
package com.bonait.bnframework.HBL.Communication.Siemens;

import com.bonait.bnframework.HBL.DataUtil.Convert;
import com.bonait.bnframework.HBL.Interface.IRun;
import com.bonait.bnframework.HBL.Logs.MessageLog;
import com.bonait.bnframework.HBL.Result.OperateResult;
import com.bonait.bnframework.HBL.Result.OperateResultT;
import com.github.xingshuangs.iot.protocol.s7.enums.EPlcType;

public class CommHelper {

private static CommHelper mInstance; //实例变量设置私有,防止直接通过类名访问

private CommHelper() { //默认构造函数私有,防止类外直接new创建对象
}

public static synchronized CommHelper get() { //静态同步方法作为唯一的实例对象获取方式
if (mInstance == null) {
mInstance = new CommHelper();
}
return mInstance;
}
private String IPAddress="127.0.0.1";
public boolean IsConnected(){
return siemens.IsConnected;
}
public IRun ConnectOk;

public SiemensHelper siemens=new SiemensHelper(EPlcType.S200_SMART, IPAddress);

public void Connect(){
new Thread(new Runnable() {
@Override
public void run() {
MessageLog.ShowInfo("开始连接PLC");
int tempFlag=0;
while (!siemens.checkConnected()){
try{
tempFlag++;
siemens=new SiemensHelper(EPlcType.S200_SMART, IPAddress);
siemens.connect();
siemens.Delay(1000);
}catch (Exception e){
if(tempFlag==1)MessageLog.ShowInfo("PLC连接失败:"+e.getMessage());
siemens.Delay(1000);
}
}
if(ConnectOk!=null)ConnectOk.Run();
siemens.IsConnected=true;
MessageLog.ShowInfo("PLC连接成功");
}
}).start();
}



public void writePLC(String add,Object value){
if(!IsConnected()) {
MessageLog.ShowInfo(add+":写入数据失败,连接已断开");
return;
}
if(value==null) {
MessageLog.ShowInfo("writePLC:写入值为空");
return;
}
try{
if(add.toUpperCase().contains("VD")){
Float tempVD= Float.parseFloat(value.toString());
siemens.WriteFloat32(add,tempVD);
}
else if (add.toUpperCase().contains("VW")){
Integer tempVW= Integer.parseInt(value.toString());
siemens.WriteUInt16(add,tempVW);
}
else if (add.toUpperCase().contains("V")){
Boolean tempV= Boolean.parseBoolean(value.toString());
siemens.WriteBoolean(add,tempV);
}
}catch (Exception e){
MessageLog.ShowInfo("writePLC:写入失败,"+e.getMessage());
}

}

public Object readPLC(String add){
try{
if(add.toUpperCase().contains("VD")){
return siemens.ReadFloat32(add);
}
else if (add.toUpperCase().contains("VW")||add.toUpperCase().contains("IW")||add.toUpperCase().contains("QW")){
return siemens.ReadUInt16(add);
}
else if (add.toUpperCase().contains("V")){
return siemens.ReadBoolean(add);
}
}catch (Exception e){
MessageLog.ShowInfo("readPLC:读取失败,"+e.getMessage());
}
return new Object();
}

public <T> OperateResultT<T> Read(String add){
if(!IsConnected()) return OperateResultT.CreateFailedT(add+":读取数据失败,连接已断开");
OperateResultT<T> result = new OperateResultT<>();
String typeName=result.Content.getClass() .getName();
try{
if(typeName.contains("Boolean")){
return Convert.TryToGenericity(siemens.ReadBoolean(add));
}else if(typeName.contains("Integer")){
if(add.toUpperCase().contains("VD")){
return Convert.TryToGenericity(siemens.ReadInt32(add));
}
else if (add.toUpperCase().contains("VW")||add.toUpperCase().contains("IW")||add.toUpperCase().contains("QW")){
return Convert.TryToGenericity(siemens.ReadUInt16(add));
}
}else if(typeName.contains("Short")){
return Convert.TryToGenericity(siemens.ReadInt16(add));
}else if(typeName.contains("Float")){
return Convert.TryToGenericity(siemens.ReadFloat32(add));
}else{
return OperateResultT.CreateFailedT(typeName+" 暂不支持的数据类型");
}
}catch (Exception e){
return OperateResultT.CreateFailedT(e);
}
return result;
}

public <T> OperateResult Write(String add, T value){
if(!IsConnected()) return OperateResult.CreateFailed(add+":读取数据失败,连接已断开");
if(value ==null) return OperateResult.CreateFailed(add+":写入值无效");
String typeName=value.getClass() .getName();
try{

if(typeName.contains("Boolean")){
Convert.<Boolean>TryToGenericity(value).OnSource(s->{ siemens.WriteBoolean(add,s.Content);});
}else if(typeName.contains("Integer")){
if(add.toUpperCase().contains("VD")){
Convert.<Integer>TryToGenericity(value).OnSource(s->{ siemens.WriteInt32(add,s.Content);});
}
else if (add.toUpperCase().contains("VW")){
Convert.<Integer>TryToGenericity(value).OnSource(s->{ siemens.WriteUInt16(add,s.Content);});
}
}else if(typeName.contains("Short")){
Convert.<Short>TryToGenericity(value).OnSource(s->{ siemens.WriteInt16(add,s.Content);});
}else if(typeName.contains("Float")){
Convert.<Float>TryToGenericity(value).OnSource(s->{ siemens.WriteFloat32(add,s.Content);});
}else{
return OperateResult.CreateFailed(typeName+" 暂不支持的数据类型");
}
return OperateResult.CreateSuccess();
}catch (Exception e){
return OperateResult.CreateFailed(e);
}
}

}

+ 360
- 0
app/src/main/java/com/bonait/bnframework/HBL/Communication/Siemens/SiemensHelper.java Ver fichero

@@ -0,0 +1,360 @@
package com.bonait.bnframework.HBL.Communication.Siemens;

import android.util.Log;

import com.bonait.bnframework.HBL.Logs.MessageLog;
import com.github.xingshuangs.iot.exceptions.SocketRuntimeException;
import com.github.xingshuangs.iot.protocol.s7.enums.EPlcType;
import com.github.xingshuangs.iot.protocol.s7.model.DataItem;
import com.github.xingshuangs.iot.protocol.s7.service.S7PLC;
import com.github.xingshuangs.iot.protocol.s7.utils.AddressUtil;
import com.github.xingshuangs.iot.utils.FloatUtil;
import com.github.xingshuangs.iot.utils.IntegerUtil;
import com.github.xingshuangs.iot.utils.ShortUtil;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class SiemensHelper extends S7PLC {
public Boolean IsConnected=false;

public boolean CancelWrite=false;


public void Delay(long millis){
try{
Thread.sleep(millis);
}catch(InterruptedException e){

}
}

public boolean ReadBoolean(String address){
boolean result=false;
while(true){
try {
result=this.readBoolean(address);
IsConnected=true;
break;
}
catch(SocketRuntimeException ex){
this.close();
IsConnected=false;
Delay(1000);
}
}
return result;
}

public List<Boolean> ReadBoolean(String... address) {
List<Boolean> result=new ArrayList<>();
while(true){
try {
result=this.readBoolean(Arrays.asList(address));
IsConnected=true;
break;
}
catch(SocketRuntimeException ex){
this.close();
IsConnected=false;
Delay(1000);
}
}
return result;
}

public short ReadInt16(String address) {
short result=0;
while(true){
try {
DataItem dataItem = this.readS7Data(AddressUtil.parseByte(address, 2));
result= ShortUtil.toInt16(dataItem.getData());
IsConnected=true;
break;
}
catch(SocketRuntimeException ex){
this.close();
IsConnected=false;
Delay(1000);
}
}
return result;

}

public List<Short> ReadInt16(String... address) {
List<Short> result=new ArrayList<>();
while(true){
try {
result=this.readInt16(Arrays.asList(address));
IsConnected=true;
break;
}
catch(SocketRuntimeException ex){
this.close();
IsConnected=false;
Delay(1000);
}
}

return result;
}

public int ReadUInt16(String address) {
int result=0;
while(true){
try {
DataItem dataItem = this.readS7Data(AddressUtil.parseByte(address, 2));
result= ShortUtil.toUInt16(dataItem.getData());
IsConnected=true;
break;
}
catch(SocketRuntimeException ex){
this.close();
IsConnected=false;
Delay(1000);
}
}
return result;
}

public List<Integer> ReadUInt16(String... address) {
List<Integer> result=new ArrayList<>();
while(true){
try {
result=this.readUInt16(Arrays.asList(address));
IsConnected=true;
break;
}
catch(SocketRuntimeException ex){
this.close();
IsConnected=false;
Delay(1000);
}
}
return result;
}

public int ReadInt32(String address) {
int result=0;
while(true){
try {
DataItem dataItem = this.readS7Data(AddressUtil.parseByte(address, 4));
result= IntegerUtil.toInt32(dataItem.getData());
IsConnected=true;
break;
}
catch(SocketRuntimeException ex){
this.close();
IsConnected=false;
Delay(1000);
}
}
return result;
}

public List<Integer> ReadInt32(String... address) {
List<Integer> result=new ArrayList<>();
while(true){
try {
result=this.readInt32(Arrays.asList(address));
IsConnected=true;
break;
}
catch(SocketRuntimeException ex){
this.close();
IsConnected=false;
Delay(1000);
}
}
return result;
}

public float ReadFloat32(String address) {
float result=0f;
while(true){
try {
DataItem dataItem = this.readS7Data(AddressUtil.parseByte(address, 4));
result= FloatUtil.toFloat32(dataItem.getData());

IsConnected=true;
break;
}
catch(SocketRuntimeException ex){
this.close();
IsConnected=false;
Delay(1000);
}
}
return result;
}

public List<Float> ReadFloat32(String... address) {
List<Float> result=new ArrayList<>();
while(true){
try {
result=this.readFloat32(Arrays.asList(address));
IsConnected=true;
break;
}
catch(SocketRuntimeException ex){
this.close();
IsConnected=false;
Delay(1000);
}
}
return result;
}

public void WriteBoolean(String address, boolean data) {
if(!IsConnected){
MessageLog.ShowInfo(address+":写入数据失败,连接已断开");
return;
}
while (true) {
try {
this.writeS7Data(AddressUtil.parseBit(address), DataItem.createReqByBoolean(data));
IsConnected=true;
break;
}
catch(SocketRuntimeException ex){
this.close();
IsConnected=false;
Delay(100);
if(CancelWrite)break;
}
catch (Exception e){
MessageLog.ShowError("WriteBoolean 写入异常:"+e.toString());
break;
}
}
}

public void WriteUInt16(String address, int data) {
if(!IsConnected){
MessageLog.ShowInfo(address+":写入数据失败,连接已断开");
return;
}
while (true) {
try {
this.writeByte(address, ShortUtil.toByteArray(data));
IsConnected=true;
break;
}
catch(SocketRuntimeException ex){
this.close();
IsConnected=false;
Delay(100);
if(CancelWrite)break;
}
catch (Exception e){
MessageLog.ShowError("WriteUInt16 写入异常:"+e.toString());
break;
}
}
}

public void WriteInt16(String address, short data) {
if(!IsConnected){
MessageLog.ShowInfo(address+":写入数据失败,连接已断开");
return;
}
while (true) {
try {
Log.e("info","准备写入数据:"+data);
this.writeByte(address, ShortUtil.toByteArray(data));
IsConnected=true;
break;
}
catch(SocketRuntimeException ex){
Log.e("socketException","写入:"+data+"失败");
this.close();
IsConnected=false;
Delay(100);
if(CancelWrite)break;
}
catch (Exception e){
MessageLog.ShowError("WriteInt16 写入异常:"+e.toString());
break;
}
}
}

public void WriteUInt32(String address, long data) {
if(!IsConnected){
MessageLog.ShowInfo(address+":写入数据失败,连接已断开");
return;
}
while (true) {
try {
this.writeByte(address, IntegerUtil.toByteArray(data));
IsConnected=true;
break;
}
catch(SocketRuntimeException ex){
this.close();
IsConnected=false;
Delay(100);
if(CancelWrite)break;
}
catch (Exception e){
MessageLog.ShowError("WriteUInt32 写入异常:"+e.toString());
break;
}
}
}

public void WriteInt32(String address, int data) {
if(!IsConnected){
MessageLog.ShowInfo(address+":写入数据失败,连接已断开");
return;
}
while (true) {
try {
this.writeByte(address, IntegerUtil.toByteArray(data));
IsConnected=true;
break;
}
catch(SocketRuntimeException ex){
this.close();
IsConnected=false;
Delay(100);
if(CancelWrite)break;
}
catch (Exception e){
MessageLog.ShowError("WriteInt32 写入异常:"+e.toString());
break;
}
}
}

public void WriteFloat32(String address, float data) {
if(!IsConnected){
MessageLog.ShowInfo(address+":写入数据失败,连接已断开");
return;
}
while (true) {
try {
this.writeByte(address, FloatUtil.toByteArray(data));
IsConnected=true;
break;
}
catch(SocketRuntimeException ex){
this.close();
IsConnected=false;
Delay(100);
if(CancelWrite)break;
}
catch (Exception e){
MessageLog.ShowError("WriteFloat32 写入异常:"+e.toString());
break;
}
}
}

public SiemensHelper(EPlcType PlcType, String ip){
super(PlcType, ip);
}

}

+ 213
- 0
app/src/main/java/com/bonait/bnframework/HBL/CustomView/ShadowContainer.java Ver fichero

@@ -0,0 +1,213 @@
package com.bonait.bnframework.HBL.CustomView;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.RectF;
import android.os.Build;
import android.util.AttributeSet;
import android.view.View;
import android.view.ViewGroup;

import com.bonait.bnframework.R;


/**
* 阴影容器
* 需要在 res->values->attrs.xml中添加以下内容
* <declare-styleable name="ShadowContainer">
* <attr name="containerShadowColor" format="color" /><!--阴影颜色-->
* <attr name="containerShadowRadius" format="dimension" /><!--阴影半径-->
* <attr name="containerDeltaLength" format="dimension" /><!--子View到ShadowContainer的距离-->
* <attr name="containerCornerRadius" format="dimension" /><!--子View背景的圆角大小-->
* <attr name="deltaX" format="dimension" />
* <attr name="deltaY" format="dimension" />
* <attr name="enable" format="boolean" />
* </declare-styleable>
* Reference: https://github.com/cjlemon/Shadow
*/
public class ShadowContainer extends ViewGroup {

private final float deltaLength;
private final float cornerRadius;
private final Paint mShadowPaint;
private boolean drawShadow;

public ShadowContainer(Context context) {
this(context, null);
}

public ShadowContainer(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}

public ShadowContainer(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.ShadowContainer);
int shadowColor = a.getColor(R.styleable.ShadowContainer_containerShadowColor, Color.RED);
float shadowRadius = a.getDimension(R.styleable.ShadowContainer_containerShadowRadius, 0);
deltaLength = a.getDimension(R.styleable.ShadowContainer_containerDeltaLength, 0);
cornerRadius = a.getDimension(R.styleable.ShadowContainer_containerCornerRadius, 0);
float dx = a.getDimension(R.styleable.ShadowContainer_deltaX, 0);
float dy = a.getDimension(R.styleable.ShadowContainer_deltaY, 0);
drawShadow = a.getBoolean(R.styleable.ShadowContainer_enable, true);
a.recycle();
mShadowPaint = new Paint();
mShadowPaint.setStyle(Paint.Style.FILL);
mShadowPaint.setAntiAlias(true);
mShadowPaint.setColor(shadowColor);
mShadowPaint.setShadowLayer(shadowRadius, dx, dy, shadowColor);
}

@Override
protected void dispatchDraw(Canvas canvas) {
if (drawShadow) {
/*
setShadowLayer()/setMaskFilter is not support hardware acceleration, so using LAYER_TYPE_SOFTWARE, but software layers isn't always good.
LAYER_TYPE_SOFTWARE: software layers should be avoided when the affected view tree updates often.
*/
if (getLayerType() != LAYER_TYPE_SOFTWARE) {
setLayerType(LAYER_TYPE_SOFTWARE, null);
}
View child = getChildAt(0);
int left = child.getLeft();
int top = child.getTop();
int right = child.getRight();
int bottom = child.getBottom();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
canvas.drawRoundRect(left, top, right, bottom, cornerRadius, cornerRadius, mShadowPaint);
} else {
Path drawablePath = new Path();
drawablePath.moveTo(left + cornerRadius, top);
drawablePath.arcTo(new RectF(left, top, left + 2 * cornerRadius, top + 2 * cornerRadius), -90, -90, false);
drawablePath.lineTo(left, bottom - cornerRadius);
drawablePath.arcTo(new RectF(left, bottom - 2 * cornerRadius, left + 2 * cornerRadius, bottom), 180, -90, false);
drawablePath.lineTo(right - cornerRadius, bottom);
drawablePath.arcTo(new RectF(right - 2 * cornerRadius, bottom - 2 * cornerRadius, right, bottom), 90, -90, false);
drawablePath.lineTo(right, top + cornerRadius);
drawablePath.arcTo(new RectF(right - 2 * cornerRadius, top, right, top + 2 * cornerRadius), 0, -90, false);
drawablePath.close();
canvas.drawPath(drawablePath, mShadowPaint);
}
}
super.dispatchDraw(canvas);
}

/**
* setMeasuredDimension(): store the modified width and modified height.
*
* @param widthMeasureSpec the original width
* @param heightMeasureSpec the original height
*/
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
if (getChildCount() != 1) {
throw new IllegalStateException("Child View can have only one!!!");
}
int measuredWidth = getMeasuredWidth();
int measuredHeight = getMeasuredHeight();
int widthMode = MeasureSpec.getMode(widthMeasureSpec);
int heightMode = MeasureSpec.getMode(heightMeasureSpec);
View child = getChildAt(0);
MarginLayoutParams layoutParams = (MarginLayoutParams) child.getLayoutParams();
int childBottomMargin = (int) (Math.max(deltaLength, layoutParams.bottomMargin) + 1);
int childLeftMargin = (int) (Math.max(deltaLength, layoutParams.leftMargin) + 1);
int childRightMargin = (int) (Math.max(deltaLength, layoutParams.rightMargin) + 1);
int childTopMargin = (int) (Math.max(deltaLength, layoutParams.topMargin) + 1);
int widthMeasureSpecMode;
int widthMeasureSpecSize;
int heightMeasureSpecMode;
int heightMeasureSpecSize;
if (widthMode == MeasureSpec.UNSPECIFIED) {
widthMeasureSpecMode = MeasureSpec.UNSPECIFIED;
widthMeasureSpecSize = MeasureSpec.getSize(widthMeasureSpec);
} else {
if (layoutParams.width == MarginLayoutParams.MATCH_PARENT) {
widthMeasureSpecMode = MeasureSpec.EXACTLY;
widthMeasureSpecSize = measuredWidth - childLeftMargin - childRightMargin;
} else if (MarginLayoutParams.WRAP_CONTENT == layoutParams.width) {
widthMeasureSpecMode = MeasureSpec.AT_MOST;
widthMeasureSpecSize = measuredWidth - childLeftMargin - childRightMargin;
} else {
widthMeasureSpecMode = MeasureSpec.EXACTLY;
widthMeasureSpecSize = layoutParams.width;
}
}
if (heightMode == MeasureSpec.UNSPECIFIED) {
heightMeasureSpecMode = MeasureSpec.UNSPECIFIED;
heightMeasureSpecSize = MeasureSpec.getSize(heightMeasureSpec);
} else {
if (layoutParams.height == MarginLayoutParams.MATCH_PARENT) {
heightMeasureSpecMode = MeasureSpec.EXACTLY;
heightMeasureSpecSize = measuredHeight - childBottomMargin - childTopMargin;
} else if (MarginLayoutParams.WRAP_CONTENT == layoutParams.height) {
heightMeasureSpecMode = MeasureSpec.AT_MOST;
heightMeasureSpecSize = measuredHeight - childBottomMargin - childTopMargin;
} else {
heightMeasureSpecMode = MeasureSpec.EXACTLY;
heightMeasureSpecSize = layoutParams.height;
}
}
measureChild(child, MeasureSpec.makeMeasureSpec(widthMeasureSpecSize, widthMeasureSpecMode), MeasureSpec.makeMeasureSpec(heightMeasureSpecSize, heightMeasureSpecMode));
int parentWidthMeasureSpec = MeasureSpec.getMode(widthMeasureSpec);
int parentHeightMeasureSpec = MeasureSpec.getMode(heightMeasureSpec);
int height = measuredHeight;
int width = measuredWidth;
int childHeight = child.getMeasuredHeight();
int childWidth = child.getMeasuredWidth();
if (parentHeightMeasureSpec == MeasureSpec.AT_MOST) {
height = childHeight + childTopMargin + childBottomMargin;
}
if (parentWidthMeasureSpec == MeasureSpec.AT_MOST) {
width = childWidth + childRightMargin + childLeftMargin;
}
if (width < childWidth + 2 * deltaLength) {
width = (int) (childWidth + 2 * deltaLength);
}
if (height < childHeight + 2 * deltaLength) {
height = (int) (childHeight + 2 * deltaLength);
}
if (height != measuredHeight || width != measuredWidth) {
setMeasuredDimension(width, height);
}
}

@Override
protected void onLayout(boolean changed, int l, int t, int r, int b) {
View child = getChildAt(0);
int measuredWidth = getMeasuredWidth();
int measuredHeight = getMeasuredHeight();
int childMeasureWidth = child.getMeasuredWidth();
int childMeasureHeight = child.getMeasuredHeight();
child.layout((measuredWidth - childMeasureWidth) / 2, (measuredHeight - childMeasureHeight) / 2, (measuredWidth + childMeasureWidth) / 2, (measuredHeight + childMeasureHeight) / 2);
}

@Override
protected LayoutParams generateDefaultLayoutParams() {
return new MarginLayoutParams(MarginLayoutParams.WRAP_CONTENT, MarginLayoutParams.WRAP_CONTENT);
}

@Override
protected LayoutParams generateLayoutParams(LayoutParams p) {
return new MarginLayoutParams(p);
}

@Override
public LayoutParams generateLayoutParams(AttributeSet attrs) {
return new MarginLayoutParams(getContext(), attrs);
}

public void setDrawShadow(boolean drawShadow) {
if (this.drawShadow == drawShadow) {
return;
}
this.drawShadow = drawShadow;
postInvalidate();
}

}


+ 81
- 0
app/src/main/java/com/bonait/bnframework/HBL/DataUtil/ByteLib.java Ver fichero

@@ -0,0 +1,81 @@
package com.bonait.bnframework.HBL.DataUtil;


import com.bonait.bnframework.HBL.Enum.DataFormat;

public class ByteLib {

public static byte[] ToBytes(short value, DataFormat df) {
byte[] b = new byte[2];
b[0]=(byte)((value>>8)&0xff);
b[1]=(byte)((value>>0)&0xff);
return new ByteTransDataFormat().ByteTransDataFormat2(b,df,0);
}

public static byte[] ToBytes(short[] value,DataFormat df) {
byte[] b = new byte[value.length*2];
for (int i = 0; i < value.length; i++)
{
b[i*2]=(byte)((value[i]>>8)&0xff);
b[i*2+1]=(byte)((value[i]>>0)&0xff);
}
return new ByteTransDataFormat().ByteTransDataFormat2(b,df,0);
}

public static byte[] ToBytes(float value,DataFormat df) {
int tempValue = Float.floatToRawIntBits(value);
byte[] b = new byte[4];
b[0]=(byte)((tempValue>>24)&0xff);
b[1]=(byte)((tempValue>>16)&0xff);
b[2]=(byte)((tempValue>>8)&0xff);
b[3]=(byte)((tempValue>>0)&0xff);
return new ByteTransDataFormat().ByteTransDataFormat4(b,df,0);
}

public static byte[] ToBytes(float[] value,DataFormat df) {
byte[] b = new byte[value.length*4];
for (int i=0;i<value.length;i++)
{
int tempValue = Float.floatToRawIntBits(value[i]);
b[i*4]=(byte)((tempValue>>24)&0xff);
b[i*4+1]=(byte)((tempValue>>16)&0xff);
b[i*4+2]=(byte)((tempValue>>8)&0xff);
b[i*4+3]=(byte)((tempValue>>0)&0xff);
}
return new ByteTransDataFormat().ByteTransDataFormat4(b,df,0);
}

public static byte[] ToBytes(int value,DataFormat df) {
byte[] b = new byte[4];
b[0]=(byte)((value>>24)&0xff);
b[1]=(byte)((value>>16)&0xff);
b[2]=(byte)((value>>8)&0xff);
b[3]=(byte)((value>>0)&0xff);
return new ByteTransDataFormat().ByteTransDataFormat4(b,df,0);
}

public static byte[] ToBytes(int[] value,DataFormat df) {
byte[] b = new byte[value.length*4];
for (int i=0;i<value.length;i++)
{
b[i*4]=(byte)((value[i]>>24)&0xff);
b[i*4+1]=(byte)((value[i]>>16)&0xff);
b[i*4+2]=(byte)((value[i]>>8)&0xff);
b[i*4+3]=(byte)((value[i]>>0)&0xff);
}
return new ByteTransDataFormat().ByteTransDataFormat4(b,df,0);
}

public static boolean GetBit(byte value,int offset)
{
if (offset > 8 || offset < 1) return false;
return (value & 1 << offset - 1) == 0 ? false : true;
}

public static byte SetBit(byte value,int offset, boolean val)
{
if (offset > 8 || offset < 1) return value;
int ConvertValue = 1 << offset - 1;
return (byte)(val ? value | ConvertValue : value & ~ConvertValue);
}
}

+ 51
- 0
app/src/main/java/com/bonait/bnframework/HBL/DataUtil/ByteTransDataFormat.java Ver fichero

@@ -0,0 +1,51 @@
package com.bonait.bnframework.HBL.DataUtil;


import com.bonait.bnframework.HBL.Enum.DataFormat;

public class ByteTransDataFormat {
public byte[] ByteTransDataFormat2(byte[] data, DataFormat df, int offset ){
if (offset+2<2) return new byte[2];
byte[] numArray = new byte[2];
if (df==DataFormat.ABCD||df==DataFormat.BADC){
numArray[0] = data[offset+1];
numArray[1] = data[offset];
}
else {
numArray[0] = data[offset];
numArray[1] = data[offset+1];
}
return numArray;
}

public byte[] ByteTransDataFormat4(byte[] data, DataFormat df,int offset ){
if (offset+4<4) return new byte[4];
byte[] numArray = new byte[4];
if (df==DataFormat.ABCD){
numArray[0] = data[offset+3];
numArray[1] = data[offset+2];
numArray[2] = data[offset+1];
numArray[3] = data[offset];
}
else if (df==DataFormat.BADC){
numArray[0] = data[offset+2];
numArray[1] = data[offset+3];
numArray[2] = data[offset];
numArray[3] = data[offset+1];
}
else if(df==DataFormat.CDAB){
numArray[0] = data[offset+1];
numArray[1] = data[offset];
numArray[2] = data[offset+3];
numArray[3] = data[offset+2];
}
else if(df==DataFormat.DCBA){
numArray[0] = data[offset];
numArray[1] = data[offset+1];
numArray[2] = data[offset+2];
numArray[3] = data[offset+3];
}
return numArray;
}
}


+ 107
- 0
app/src/main/java/com/bonait/bnframework/HBL/DataUtil/Convert.java Ver fichero

@@ -0,0 +1,107 @@
package com.bonait.bnframework.HBL.DataUtil;


import com.bonait.bnframework.HBL.Result.OperateResultT;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

public class Convert {
public static OperateResultT<Boolean> TryToBoolean(Object value){
if(value==null) return OperateResultT.CreateFailedT("TryToBoolean:转换对象为空");
try{
return OperateResultT.CreateSuccess(Boolean.parseBoolean(value.toString()));
}catch (Exception e) {
return OperateResultT.CreateFailedT(e);
}
}

public static OperateResultT<Integer> TryToInt(Object value){
if(value==null) return OperateResultT.CreateFailedT("TryToInt:转换对象为空");
try{
return OperateResultT.CreateSuccess(Integer.parseInt(value.toString()));
}catch (Exception e) {
return OperateResultT.CreateFailedT(e);
}
}

public static OperateResultT<Short> TryToShort(Object value){
if(value==null) return OperateResultT.CreateFailedT("TryToShort:转换对象为空");
try{
return OperateResultT.CreateSuccess(Short.parseShort(value.toString()));
}catch (Exception e) {
return OperateResultT.CreateFailedT(e);
}
}

public static OperateResultT<Float> TryToFloat(Object value){
if(value==null) return OperateResultT.CreateFailedT("TryToFloat:转换对象为空");
try{
return OperateResultT.CreateSuccess(Float.parseFloat(value.toString()));
}catch (Exception e) {
return OperateResultT.CreateFailedT(e);
}
}

public static <T> OperateResultT<T> TryToGenericity( Object value){
if(value==null) return OperateResultT.CreateFailedT("TryToGenericity:转换对象为空");
try{
return OperateResultT.CreateSuccess((T)value);
}catch (Exception e) {
return OperateResultT.CreateFailedT(e);
}
}

// public static <T extends Number> OperateResultT<T> TryToNumber(Object value,Class<T> type){
// if(value==null) return OperateResultT.CreateFailedT("TryToGenericity:转换对象为空");
// try{
// String temp = value.toString();
// if(type==Integer.TYPE){
// return OperateResultT.CreateSuccess((T)Integer.valueOf(temp));
// }else if (type==Short.TYPE){
// return OperateResultT.CreateSuccess((T)Short.valueOf(temp));
// }else if (type==Byte.TYPE){
// return OperateResultT.CreateSuccess((T)Byte.valueOf(temp));
// }else if (type==Float.TYPE){
// return OperateResultT.CreateSuccess((T)Float.valueOf(temp));
// }else if (type==Long.TYPE){
// return OperateResultT.CreateSuccess((T)Long.valueOf(temp));
// }else if (type==Double.TYPE){
// return OperateResultT.CreateSuccess((T)Double.valueOf(temp));
// }else if (type.getName().contains(Boolean.TYPE.getName())){
// return OperateResultT.CreateSuccess((T)Boolean.valueOf(temp));
// }else if (type.getName().contains(String.class.getName())){
// return OperateResultT.CreateSuccess((T)temp);
// }
// return OperateResultT.CreateSuccess((T)value);
// }catch (Exception e) {
// return OperateResultT.CreateFailedT(e);
// }
// }

public static <T> OperateResultT<T> fromJson(Object value, Class<T> clazz) {
if(value==null) return OperateResultT.CreateFailedT("TryToBoolean:转换对象为空");
try{
Gson gson = new GsonBuilder().create();
String temp = gson.toJson(value);
T arr = gson.fromJson(temp, clazz);
if(arr!=null)return OperateResultT.CreateSuccess( arr );
else return OperateResultT.CreateFailedT("返回对象为空");
}catch (Exception e) {
return OperateResultT.CreateFailedT(e);
}
}

public static <T> OperateResultT<T> fromJson(String value, Class<T> clazz) {
if(value==null||value.isEmpty()) return OperateResultT.CreateFailedT("TryToBoolean:转换对象为空");
try{
Gson gson = new GsonBuilder().create();
T arr = gson.fromJson(value, clazz);
if(arr!=null)return OperateResultT.CreateSuccess( arr);
else return OperateResultT.CreateFailedT("返回对象为空");
}catch (Exception e) {
return OperateResultT.CreateFailedT(e);
}
}


}

+ 266
- 0
app/src/main/java/com/bonait/bnframework/HBL/DataUtil/DataConvertLib.java Ver fichero

@@ -0,0 +1,266 @@
package com.bonait.bnframework.HBL.DataUtil;




import com.bonait.bnframework.HBL.Enum.DataFormat;

import java.io.UnsupportedEncodingException;
import java.nio.ByteBuffer;

public class DataConvertLib {

/***
* 字节数组转换成浮点数
* @param ,需要转换的字节
* @param ,转换的数据格式
* @return
*/
public static Float BytesToFloat(byte[] buffers, DataFormat df) {
if (buffers.length == 4) {
byte[] bytes = new byte[4];
if (df == DataFormat.ABCD) {
bytes[0] = buffers[3];
bytes[1] = buffers[2];
bytes[2] = buffers[1];
bytes[3] = buffers[0];
} else if (df == DataFormat.CDAB) {
bytes[0] = buffers[1];
bytes[1] = buffers[0];
bytes[2] = buffers[3];
bytes[3] = buffers[2];
} else if (df == DataFormat.BADC) {
bytes[0] = buffers[2];
bytes[1] = buffers[3];
bytes[2] = buffers[0];
bytes[3] = buffers[1];
} else if (df == DataFormat.DCBA) {
bytes[0] = buffers[0];
bytes[1] = buffers[1];
bytes[2] = buffers[2];
bytes[3] = buffers[3];
}
return ByteBuffer.wrap(bytes).getFloat();
}
return 0.0f;
}

/**
* 字节数组转换成整形
* @param ,需要转换的字节数组
* @param ,转换的数据格式
* @return
*/
public static Integer BytesToInt(byte[] buffers, DataFormat df) {
if (buffers.length == 4) {
byte[] bytes = new byte[4];
if (df == DataFormat.ABCD) {
bytes[0] = buffers[3];
bytes[1] = buffers[2];
bytes[2] = buffers[1];
bytes[3] = buffers[0];
} else if (df == DataFormat.CDAB) {
bytes[0] = buffers[1];
bytes[1] = buffers[0];
bytes[2] = buffers[3];
bytes[3] = buffers[2];
} else if (df == DataFormat.BADC) {
bytes[0] = buffers[2];
bytes[1] = buffers[3];
bytes[2] = buffers[0];
bytes[3] = buffers[1];
} else if (df == DataFormat.DCBA) {
bytes[0] = buffers[0];
bytes[1] = buffers[1];
bytes[2] = buffers[2];
bytes[3] = buffers[3];
}
return ByteBuffer.wrap(bytes).getInt();
}
return 0;
}

/**
* 32位整数转换成字节
* @param ,number
* @return
*/
public static byte[] IntToByte(int number) {
int temp = number;
byte[] b = new byte[4];
for (int i = 0; i < b.length; i++) {
b[i] = new Integer(temp & 0xff).byteValue();// 将最低位保存在最低位
temp = temp >> 8; // 向右移8位
}
return b;
}

/**
* 32位整形转换成16位整数数组
* @param ,value
* @return
*/
public static short[] IntToShorts(int value) {
short[] res = new short[2];
int temp = value;
byte[] b = new byte[4];
for (int i = 0; i < b.length; i++) {
b[i] = new Integer(temp & 0xff).byteValue();// 将最低位保存在最低位
temp = temp >> 8; // 向右移8位
}
for (int i = 0; i < res.length; i++) {
short s0 = (short) (b[i * 2] & 0xff);// 最低位
short s1 = (short) (b[i * 2 + 1] & 0xff);
s1 <<= 8;
res[i] = (short) (s0 | s1);
}
return res;
}

public static String GetString(short[] src, int start, int len) throws UnsupportedEncodingException {
short[] temp = new short[len];
for (int i = 0; i < len; i++) {
temp[i] = src[i + start];
}
byte[] bytesTemp = shorts2Bytes(temp);
for (int i = 0; i < bytesTemp.length; i++) {
byte b = bytesTemp[i];
}
String str = new String(bytesTemp, "UTF-8");
return str;
}

public static short[] ByteToShort(byte[] bytes) {

int len=bytes.length;
if (bytes.length%2!=0) len++;
byte[] tempBytes=new byte[len];
short[] result = new short[len/2];
for (int i=0;i<len;i++){
if (i<bytes.length)tempBytes[i]=bytes[i];
}
for(int m=0;m<result.length;m++) {
result[m] = (short) ((tempBytes[m * 2] & 0xff) | ((tempBytes[m * 2 + 1] & 0xff) << 8));
}
return result;
}


public static byte[] shorts2Bytes(short[] data) {
byte[] byteValue = new byte[data.length * 2];
for (int i = 0; i < data.length; i++) {
byteValue[i * 2] = (byte) (data[i] & 0xff);
byteValue[i * 2 + 1] = (byte) ((data[i] & 0xff00) >> 8);
}
return byteValue;
}

public static int GetAddress(String address) {
if (address == null) return -1;
if (address.length() > 0) {
address = address.trim();
if (address.toUpperCase().contains("M") && address.length() >= 4) {
String[] res = address.substring(1).split("[.]");
if (res != null && res.length == 2) {
try {
int firstAdd = Integer.parseInt(res[0]);
int endAdd = Integer.parseInt(res[1]);
if (endAdd >= 0 && endAdd <= 7) {
return (firstAdd * 8) + 320 + endAdd;
}
} catch (NumberFormatException e) {
return -1;
}
}
} else if (address.toUpperCase().contains("I") && address.length() >= 4) {
String[] res = address.substring(1).split("[.]");
if (res != null && res.length == 2) {
try {
int firstAdd = Integer.parseInt(res[0]);
int endAdd = Integer.parseInt(res[1]);
if (endAdd >= 0 && endAdd <= 7) {
return (firstAdd * 8) + endAdd;
}
} catch (NumberFormatException e) {
return -1;
}
}
} else if ((address.toUpperCase().contains("VW") || address.toUpperCase().contains("VD")) && address.length() >= 3) {
String res = address.substring(2);
if (res != null) {
try {
int tempAdd = Integer.parseInt(res);
return (tempAdd / 2) + 100;
} catch (NumberFormatException e) {
return -1;
}
}
}else if (address.toUpperCase().contains("GI") &&address.length() >=3){
String res = address.substring(2);
if (res != null) {
try {
return Integer.parseInt(res);
} catch (NumberFormatException e) {
return -1;
}
}
}
else {
try {
return Integer.parseInt(address);
} catch (NumberFormatException e) {
return -1;
}
}
}
return -1;
}


/**
* 获取布尔位地址信息
* 列:M2.5 = getBitSingleAdd("M",2,5);
*
* @param Prefix 地址标头
* @param startAdd 起始地址编号
* @param num 要获取的第几位数量
* @return
*/
public static String getBitSingleAdd(String Prefix, int startAdd, int num) {
if (num > 0) {
int FirstAdd = num / 8;
int EndAdd = num % 8;
if (EndAdd == 0) {
FirstAdd--;
EndAdd = 7;
} else {
EndAdd--;
}
return Prefix + FirstAdd + startAdd + "." + EndAdd;
}
return "";
}

public static String bytesToString(byte[] bytes){
if (bytes == null) {
return null;
}
StringBuilder builder = new StringBuilder();
char[] hexArray = "0123456789ABCDEF".toCharArray();
for (byte aByte : bytes) {
int v = aByte & 0xFF;
builder.append(hexArray[v >>> 4]).append(hexArray[v & 0x0F]).append(" ");
}
return builder.toString();
}
public static int bytes2Int(byte[] bytes) {
int value = 0;
// 由高位到低位
for (int i = 0; i < 4; i++) {
int shift = (4 - 1 - i) * 8;
value += (bytes[i] & 0x000000FF) << shift;// 往高位游
}
return value;
}

}

+ 16
- 0
app/src/main/java/com/bonait/bnframework/HBL/DataUtil/DataType.java Ver fichero

@@ -0,0 +1,16 @@
package com.bonait.bnframework.HBL.DataUtil;

import java.io.Serializable;

public class DataType {
public static final String STRING="";
public static final byte BYTE=0;
public static final short SHORT=0;

public static final short[] SHORTS = new short[0];
public static final int INT=0;
public static final long LONG=0;
public static final float FLOAT=0f;
public static final double DOUBLE=0d;
public static final boolean BOOLEAN=false;
}

+ 46
- 0
app/src/main/java/com/bonait/bnframework/HBL/DataUtil/ErrorCodeManager.java Ver fichero

@@ -0,0 +1,46 @@
package com.bonait.bnframework.HBL.DataUtil;

import com.alibaba.fastjson.JSON;
import com.apkfuns.logutils.LogUtils;
import com.bonait.bnframework.MainApplication;
import com.bonait.bnframework.Model.ErrorCodeBean;
import com.bonait.bnframework.common.constant.DataBus;
import com.bonait.bnframework.common.utils.FileUtils;

import java.util.ArrayList;
import java.util.List;

/**
* 设备故障错误码
* */
public class ErrorCodeManager {
private static final String ERROR_CODE_FILE_NAME = "error_code.json";
private static volatile ErrorCodeManager mInstance = new ErrorCodeManager();
private List<ErrorCodeBean> mDataBeans = new ArrayList<>();
private ErrorCodeManager() {

}

public static ErrorCodeManager getInstance() {
if (mInstance==null) {
synchronized (ErrorCodeManager.class){
if(mInstance == null){
mInstance = new ErrorCodeManager();
}
}
}
return mInstance;
}

public void initData(){
if(mDataBeans.isEmpty()){
String cache = FileUtils.getJson("error_code.json", MainApplication.getContext());
mDataBeans = JSON.parseArray(cache,ErrorCodeBean.class);
LogUtils.d("ErrorCodeManager error_code.json ");
}
}

public List<ErrorCodeBean> getDataBeans() {
return mDataBeans;
}
}

+ 64
- 0
app/src/main/java/com/bonait/bnframework/HBL/DataUtil/ErrorCodeUtil.java Ver fichero

@@ -0,0 +1,64 @@
package com.bonait.bnframework.HBL.DataUtil;

import android.widget.Switch;

import androidx.annotation.NonNull;

public class ErrorCodeUtil {
public String errorCodeToString(int code) {
String result = "正常";
switch (code){
case 1:
break;
case 2:
break;
case 3:
break;
case 4:
break;
case 5:
break;
case 6:
break;
case 7:
break;
case 8:
break;
case 9:
break;
case 10:
break;
case 11:
break;
case 12:
break;
case 13:
break;
case 14:
break;
case 15:
break;
case 16:
break;
case 17:
break;
case 18:
break;
case 19:
break;
case 20:
break;
case 21:
break;
case 22:
break;
case 23:
break;
case 24:
break;
case 25:
break;
}
return result;
}
}

+ 31
- 0
app/src/main/java/com/bonait/bnframework/HBL/DataUtil/FloatLib.java Ver fichero

@@ -0,0 +1,31 @@
package com.bonait.bnframework.HBL.DataUtil;




import com.bonait.bnframework.HBL.Enum.DataFormat;

import java.nio.ByteBuffer;

public class FloatLib {
public static float ToFloat(byte[] bytes, DataFormat df) {
byte[] res= new ByteTransDataFormat().ByteTransDataFormat4(bytes,df,0);
return ByteBuffer.wrap(res).getFloat();
}

public static float[] ToFloats(byte[] bytes, DataFormat df) {
byte[] tempBytes=new byte[bytes.length];
if (bytes.length%4!=0)
{
int offset=4-bytes.length%4;
tempBytes=new byte[bytes.length+offset];
}
for (int i=0;i<bytes.length;i++){tempBytes[i]=bytes[i];}
float[] result = new float[tempBytes.length/4];
for (int i=0; i<result.length; i++){
byte[] res= new ByteTransDataFormat().ByteTransDataFormat4(tempBytes,df,i*4);
result[i]=ByteBuffer.wrap(res).getFloat();
}
return result;
}
}

+ 51
- 0
app/src/main/java/com/bonait/bnframework/HBL/DataUtil/IntLib.java Ver fichero

@@ -0,0 +1,51 @@
package com.bonait.bnframework.HBL.DataUtil;




import com.bonait.bnframework.HBL.Enum.DataFormat;

import java.nio.ByteBuffer;

public class IntLib {
public static int ToInt(byte[] bytes, DataFormat df) {
byte[] res= new ByteTransDataFormat().ByteTransDataFormat4(bytes,df,0);
return ByteBuffer.wrap(res).getInt();
}

public static int ToInt(short[] shorts, DataFormat df) {
if (shorts.length<2) return 0;
byte[] bytes= ByteLib.ToBytes(shorts,df);
if (bytes.length!=4) return 0;
return ByteBuffer.wrap(bytes).getInt();
}

public static int[] ToInts(byte[] bytes, DataFormat df) {
byte[] tempBytes=new byte[bytes.length];
if (bytes.length%4!=0)
{
int offset=4-bytes.length%4;
tempBytes=new byte[bytes.length+offset];
}
for (int i=0;i<bytes.length;i++){tempBytes[i]=bytes[i];}
int[] result = new int[tempBytes.length/4];
for (int i=0; i<result.length; i++){
byte[] res= new ByteTransDataFormat().ByteTransDataFormat4(tempBytes,df,i*4);
result[i]=ByteBuffer.wrap(res).getInt();
}
return result;
}

public static boolean GetBit(int value,int offset)
{
if (offset > 32 || offset < 1) return false;
return (value & 1 << offset - 1) == 0 ? false : true;
}

public static int SetBit(int value,int offset, boolean val)
{
if (offset > 32 || offset < 1) return value;
int ConvertValue =1 << offset - 1;
return val ? value | ConvertValue : value & ~ConvertValue;
}
}

+ 37
- 0
app/src/main/java/com/bonait/bnframework/HBL/DataUtil/NotifyPropVar.java Ver fichero

@@ -0,0 +1,37 @@
package com.bonait.bnframework.HBL.DataUtil;



import com.bonait.bnframework.HBL.Interface.IRunT;

import java.io.Serializable;
import java.util.LinkedHashMap;

public class NotifyPropVar<T extends Serializable> {

public NotifyPropVar(T defaultValue){
_value=defaultValue;
}
public IRunT<T> ChangeNotify;

private boolean IsFirst=false;
private LinkedHashMap<String,IRunT<T>> changedNotifys=new LinkedHashMap<>();

public void Register(String key,IRunT<T> notify){
// if(changedNotifys.containsKey(key))changedNotifys.remove(key);
changedNotifys.put(key,notify);
}

private T _value;
// public T getValue(){ return _value; }
public <T> T getValue(){ return (T) _value; }
public void setValue(T value){
if (value != null && !value.equals(_value) || !IsFirst) {
_value=value;
if(ChangeNotify!=null) ChangeNotify.Run(value);
changedNotifys.values().forEach(item->{if(item!=null) item.Run(value);});
IsFirst = true;
}
}
}


+ 51
- 0
app/src/main/java/com/bonait/bnframework/HBL/DataUtil/ShortLib.java Ver fichero

@@ -0,0 +1,51 @@
package com.bonait.bnframework.HBL.DataUtil;




import com.bonait.bnframework.HBL.Enum.DataFormat;

import java.nio.ByteBuffer;

public class ShortLib {
public static short ToShort(byte[] bytes, DataFormat df) {
byte[] res= new ByteTransDataFormat().ByteTransDataFormat2(bytes,df,0);
short result= ByteBuffer.wrap(res).getShort();
return result;
}

public static short[] ToShorts(byte[] bytes, DataFormat df) {
byte[] tempBytes=new byte[bytes.length];
if (bytes.length%2!=0){ tempBytes=new byte[bytes.length+1]; }
for (int i=0; i<bytes.length; i++){tempBytes[i]=bytes[i];}
short[] result = new short[tempBytes.length/2];
for (int i=0; i<result.length; i++){
byte[] res= new ByteTransDataFormat().ByteTransDataFormat2(tempBytes,df,i*2);
result[i]=ByteBuffer.wrap(res).getShort();
}
return result;
}

public static short[] ToShorts(float[] floats, DataFormat df) {
byte[] bytes = ByteLib.ToBytes(floats,df);
return ShortLib.ToShorts(bytes,df);
}

public static short[] ToShorts(int[] floats, DataFormat df) {
byte[] bytes = ByteLib.ToBytes(floats,df);
return ShortLib.ToShorts(bytes,df);
}

public static boolean GetBit(short value,int offset)
{
if (offset > 16 || offset < 1) return false;
return (value & 1 << offset - 1) == 0 ? false : true;
}

public static short SetBit(short value,int offset, boolean val)
{
if (offset > 16 || offset < 1) return value;
short ConvertValue = (short)(1 << offset - 1);
return (short)(val ? value | ConvertValue : value & ~ConvertValue);
}
}

+ 8
- 0
app/src/main/java/com/bonait/bnframework/HBL/Dialog/AlertDialogButton.java Ver fichero

@@ -0,0 +1,8 @@
package com.bonait.bnframework.HBL.Dialog;

public enum AlertDialogButton {
OK ,
OKCancel,
YesNoCancel,
YesNo,
}

+ 15
- 0
app/src/main/java/com/bonait/bnframework/HBL/Dialog/DialogActivity.java Ver fichero

@@ -0,0 +1,15 @@
package com.bonait.bnframework.HBL.Dialog;

import android.os.Bundle;

import androidx.appcompat.app.AppCompatActivity;

import com.bonait.bnframework.R;

public class DialogActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_dialog);
}
}

+ 309
- 0
app/src/main/java/com/bonait/bnframework/HBL/Dialog/DialogManager.java Ver fichero

@@ -0,0 +1,309 @@
package com.bonait.bnframework.HBL.Dialog;

import android.app.Activity;
import android.content.Context;
import android.view.View;
import android.widget.Button;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bonait.bnframework.HBL.Logs.MessageLog;
import com.bonait.bnframework.R;

/**
* 自定义弹框
* 需要在 res->values->styles.xml中添加 custom_dialog2样式
* 需要在layout中添加dialog布局页面
*/
public class DialogManager {

// private static DialogView dview;

private static Context mContext;

private static Activity mActivity;

public static void Init(Context context,Activity activity){
mContext = context;
mActivity=activity;
}

/**
* 对话框,自定义按钮,非阻塞
* */
private static void showDialog(String message, AlertDialogButton btn,DialogType dt, IDialogAction action) {
if(mContext==null) return;
try{
DialogView dview=new DialogView(mContext, R.layout.activity_dialog, R.style.custom_dialog2);
if (dview != null) {
if (!dview.isShowing()) {

String btnName1="确定";
String btnName2="取消";
if(btn==AlertDialogButton.YesNoCancel||btn==AlertDialogButton.YesNo){
btnName1="是";
btnName2="否";
}

dview.setCanceledOnTouchOutside(false);//禁用触摸其它区域关闭弹框
RelativeLayout rlTitle = (RelativeLayout) dview.findViewById(R.id.rl_title);
if(dt== DialogType.提示)rlTitle.setBackgroundResource(R.drawable.dialog_info_title_back);
if(dt== DialogType.警告)rlTitle.setBackgroundResource(R.drawable.dialog_warn_title_back);
if(dt== DialogType.错误)rlTitle.setBackgroundResource(R.drawable.dialog_error_title_back);
TextView Tv=(TextView)dview.findViewById(R.id.tv_Title);
TextView Info=(TextView)dview.findViewById(R.id.tv_Info);
Button ok = (Button)dview.findViewById(R.id.btn_ok);
Button cancel = (Button)dview.findViewById(R.id.btn_cancel);

Tv.setText(dt.toString());
Info.setText(message);
ok.setText(btnName1);
cancel.setText(btnName2);

if(btn==AlertDialogButton.OK)cancel.setVisibility(View.GONE);

ok.setOnClickListener(view->{
if(action!=null)action.ExitDialog(true);
hide(dview);
});

cancel.setOnClickListener(view->{
if(action!=null)action.ExitDialog(false);
hide(dview);
});
dview.show();
}
}
}catch(Exception e){
MessageLog.ShowError("打开弹框异常:"+e.toString());
}
}

/**
* 对话框,自定义按钮,非阻塞
* */
private static void showDialog(Context ct,String message, AlertDialogButton btn,DialogType dt, IDialogAction action) {
if(ct==null) return;
try{
DialogView dview=new DialogView(ct, R.layout.activity_dialog, R.style.custom_dialog2);
if (dview != null) {
if (!dview.isShowing()) {

String btnName1="确定";
String btnName2="取消";
if(btn==AlertDialogButton.YesNoCancel||btn==AlertDialogButton.YesNo){
btnName1="是";
btnName2="否";
}

dview.setCanceledOnTouchOutside(false);//禁用触摸其它区域关闭弹框
RelativeLayout rlTitle = (RelativeLayout) dview.findViewById(R.id.rl_title);
if(dt== DialogType.提示)rlTitle.setBackgroundResource(R.drawable.dialog_info_title_back);
if(dt== DialogType.警告)rlTitle.setBackgroundResource(R.drawable.dialog_warn_title_back);
if(dt== DialogType.错误)rlTitle.setBackgroundResource(R.drawable.dialog_error_title_back);
TextView Tv=(TextView)dview.findViewById(R.id.tv_Title);
TextView Info=(TextView)dview.findViewById(R.id.tv_Info);
Button ok = (Button)dview.findViewById(R.id.btn_ok);
Button cancel = (Button)dview.findViewById(R.id.btn_cancel);

Tv.setText(dt.toString());
Info.setText(message);
ok.setText(btnName1);
cancel.setText(btnName2);

if(btn==AlertDialogButton.OK)cancel.setVisibility(View.GONE);

ok.setOnClickListener(view->{
if(action!=null)action.ExitDialog(true);
hide(dview);
});

cancel.setOnClickListener(view->{
if(action!=null)action.ExitDialog(false);
hide(dview);
});
dview.show();
}
}
}catch(Exception e){
MessageLog.ShowError("打开弹框异常:"+e.toString());
}
}

/**
* 对话框,自定义按钮,非阻塞
* */
private static void showDialog(Activity activity,String message, AlertDialogButton btn,DialogType dt, IDialogAction action) {
if(activity==null) return;
try{
DialogView dview1=new DialogView(activity, R.layout.activity_dialog, R.style.custom_dialog2);
if (dview1 != null) {
if (!dview1.isShowing()) {

String btnName1="确定";
String btnName2="取消";
if(btn==AlertDialogButton.YesNoCancel||btn==AlertDialogButton.YesNo){
btnName1="是";
btnName2="否";
}

dview1.setCanceledOnTouchOutside(false);//禁用触摸其它区域关闭弹框
RelativeLayout rlTitle = (RelativeLayout) dview1.findViewById(R.id.rl_title);
if(dt== DialogType.提示)rlTitle.setBackgroundResource(R.drawable.dialog_info_title_back);
if(dt== DialogType.警告)rlTitle.setBackgroundResource(R.drawable.dialog_warn_title_back);
if(dt== DialogType.错误)rlTitle.setBackgroundResource(R.drawable.dialog_error_title_back);
TextView Tv=(TextView)dview1.findViewById(R.id.tv_Title);
TextView Info=(TextView)dview1.findViewById(R.id.tv_Info);
Button ok = (Button)dview1.findViewById(R.id.btn_ok);
Button cancel = (Button)dview1.findViewById(R.id.btn_cancel);

Tv.setText(dt.toString());
Info.setText(message);
ok.setText(btnName1);
cancel.setText(btnName2);

if(btn==AlertDialogButton.OK)cancel.setVisibility(View.GONE);

ok.setOnClickListener(view->{
if(action!=null)action.ExitDialog(true);
hide(dview1);
});

cancel.setOnClickListener(view->{
if(action!=null)action.ExitDialog(false);
hide(dview1);
});
dview1.show();
}
}
}catch(Exception e){
MessageLog.ShowError("打开弹框异常:"+e.toString());
}
}

/**
* 隐藏弹框
* @param view
*/
private static void hide(DialogView view) {
if (view != null) {
if (view.isShowing()) {
view.dismiss();
}
}
}

/**
* 信息提示框
* @param message 提示信息
* @param btn 显示按钮
* @param action 执行回调
*/
public static void showInfo(String message, AlertDialogButton btn, IDialogAction action) {
if(mActivity!=null)
mActivity.runOnUiThread(()->{showDialog(message,btn,DialogType.提示,action);});
else showDialog(message,btn,DialogType.提示,action);
}

/**
* 警告提示框
* @param message 警告信息
* @param btn 显示按钮
* @param action 执行回调
*/
public static void showWarn(String message, AlertDialogButton btn, IDialogAction action) {
if(mActivity!=null)
mActivity.runOnUiThread(()->{showDialog(message,btn,DialogType.警告,action);});
else showDialog(message,btn,DialogType.警告,action);
}

/**
* 错误提示框
* @param message 错误信息
* @param btn 显示按钮
* @param action 执行回调
*/
public static void showError(String message, AlertDialogButton btn, IDialogAction action) {
if(mActivity!=null)
mActivity.runOnUiThread(()->{showDialog(message,btn,DialogType.错误,action);});
else showDialog(message,btn,DialogType.错误,action);
}



/**
* 信息提示框
* @param message 提示信息
* @param btn 显示按钮
* @param action 执行回调
*/
public static void showInfo( Context ct,String message, AlertDialogButton btn, IDialogAction action) {
if(mActivity!=null)
mActivity.runOnUiThread(()->{showDialog(ct,message,btn,DialogType.提示,action);});
else showDialog(ct,message,btn,DialogType.提示,action);
}

/**
* 警告提示框
* @param message 警告信息
* @param btn 显示按钮
* @param action 执行回调
*/
public static void showWarn( Context ct,String message, AlertDialogButton btn, IDialogAction action) {
if(mActivity!=null)
mActivity.runOnUiThread(()->{showDialog(ct,message,btn,DialogType.警告,action);});
else showDialog(ct,message,btn,DialogType.警告,action);
}

/**
* 错误提示框
* @param message 错误信息
* @param btn 显示按钮
* @param action 执行回调
*/
public static void showError( Context ct,String message, AlertDialogButton btn, IDialogAction action) {
if(mActivity!=null)
mActivity.runOnUiThread(()->{showDialog(ct,message,btn,DialogType.错误,action);});
else showDialog(ct,message,btn,DialogType.错误,action);
}



/**
* 信息提示框
* @param message 提示信息
* @param btn 显示按钮
* @param action 执行回调
*/
public static void showInfo( Activity activity,String message, AlertDialogButton btn, IDialogAction action) {
if(activity!=null)
activity.runOnUiThread(()->{showDialog(activity,message,btn,DialogType.提示,action);});
else showDialog(activity,message,btn,DialogType.提示,action);
}

/**
* 警告提示框
* @param message 警告信息
* @param btn 显示按钮
* @param action 执行回调
*/
public static void showWarn(Activity activity,String message, AlertDialogButton btn, IDialogAction action) {
if(activity!=null)
activity.runOnUiThread(()->{showDialog(activity,message,btn,DialogType.警告,action);});
else showDialog(activity,message,btn,DialogType.警告,action);
}

/**
* 错误提示框
* @param message 错误信息
* @param btn 显示按钮
* @param action 执行回调
*/
public static void showError( Activity activity,String message, AlertDialogButton btn, IDialogAction action) {
if(activity!=null)
activity.runOnUiThread(()->{showDialog(activity,message,btn,DialogType.错误,action);});
else showDialog(activity,message,btn,DialogType.错误,action);
}

}


+ 7
- 0
app/src/main/java/com/bonait/bnframework/HBL/Dialog/DialogType.java Ver fichero

@@ -0,0 +1,7 @@
package com.bonait.bnframework.HBL.Dialog;

public enum DialogType {
警告,
提示,
错误
}

+ 35
- 0
app/src/main/java/com/bonait/bnframework/HBL/Dialog/DialogView.java Ver fichero

@@ -0,0 +1,35 @@
package com.bonait.bnframework.HBL.Dialog;

import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.view.Window;

import androidx.annotation.NonNull;

public class DialogView extends Dialog {

public DialogView(@NonNull Context context, int layout, int style, int gravity) {
super(context, style);
setContentView(layout);
Window mWindow = getWindow();
// WindowManager.LayoutParams params = mWindow.getAttributes();
// params.width = WindowManager.LayoutParams.MATCH_PARENT;
// params.height = WindowManager.LayoutParams.WRAP_CONTENT;
// params.gravity = gravity;
// mWindow.setAttributes(params);
}

public DialogView(@NonNull Context context, int layout, int style) {
super(context, style);
setContentView(layout);
Window mWindow = getWindow();
}

public DialogView(@NonNull Activity activity, int layout, int style) {
super(activity, style);
setContentView(layout);
Window mWindow = getWindow();
}

}

+ 6
- 0
app/src/main/java/com/bonait/bnframework/HBL/Dialog/IDialogAction.java Ver fichero

@@ -0,0 +1,6 @@
package com.bonait.bnframework.HBL.Dialog;

public interface IDialogAction {
void ExitDialog(boolean status);

}

+ 8
- 0
app/src/main/java/com/bonait/bnframework/HBL/Enum/DataFormat.java Ver fichero

@@ -0,0 +1,8 @@
package com.bonait.bnframework.HBL.Enum;

public enum DataFormat {
ABCD,
CDAB,
BADC,
DCBA
}

+ 40
- 0
app/src/main/java/com/bonait/bnframework/HBL/Executor.java Ver fichero

@@ -0,0 +1,40 @@
package com.bonait.bnframework.HBL;



import com.bonait.bnframework.HBL.Interface.IRun;
import com.bonait.bnframework.HBL.Logs.MessageLog;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
* 异步方法
*/
public class Executor {

private static Executor mInstance; //实例变量设置私有,防止直接通过类名访问

private Executor() { //默认构造函数私有,防止类外直接new创建对象
}

public static synchronized Executor get() { //静态同步方法作为唯一的实例对象获取方式
if (mInstance == null) {
mInstance = new Executor();
}
return mInstance;
}
private ExecutorService executor= Executors.newCachedThreadPool() ;

public void runThread(IRun run) {
executor.submit(()->{
try {
if(run!=null)run.Run();
}catch(Exception ex) {
MessageLog.ShowError("runThread 异常:"+ex.getMessage());
}
});
}


}

+ 5
- 0
app/src/main/java/com/bonait/bnframework/HBL/Interface/IRun.java Ver fichero

@@ -0,0 +1,5 @@
package com.bonait.bnframework.HBL.Interface;

public interface IRun {
void Run();
}

app/src/main/java/com/bonait/bnframework/common/helper/I/IRunT.java → app/src/main/java/com/bonait/bnframework/HBL/Interface/IRunT.java Ver fichero

@@ -1,5 +1,7 @@
package com.bonait.bnframework.common.helper.I;
package com.bonait.bnframework.HBL.Interface;

public interface IRunT<T> {
void Run(T t);
}



+ 5
- 0
app/src/main/java/com/bonait/bnframework/HBL/Interface/IRunT2.java Ver fichero

@@ -0,0 +1,5 @@
package com.bonait.bnframework.HBL.Interface;

public interface IRunT2<T1,T2> {
void Run(T1 t1, T2 t2);;
}

+ 7
- 0
app/src/main/java/com/bonait/bnframework/HBL/Logs/IMessageLogNotify.java Ver fichero

@@ -0,0 +1,7 @@
package com.bonait.bnframework.HBL.Logs;

public interface IMessageLogNotify {
void ErrorMsg(String msg);
void InfoMsg(String msg);
void WarnMsg(String msg);
}

+ 70
- 0
app/src/main/java/com/bonait/bnframework/HBL/Logs/MessageLog.java Ver fichero

@@ -0,0 +1,70 @@
package com.bonait.bnframework.HBL.Logs;

import android.util.Log;

import com.apkfuns.logutils.LogUtils;
import com.bonait.bnframework.HBL.Thread.ThreadManager;
import com.bonait.bnframework.common.constant.ConfigName;
import com.bonait.bnframework.common.db.QueryDB;
import com.bonait.bnframework.common.db.mode.BPA_ALERTLOG;

import java.util.concurrent.ConcurrentLinkedQueue;

public class MessageLog {
private static IMessageLogNotify MsgNotify;
private static ConcurrentLinkedQueue<String> msgQueue=new ConcurrentLinkedQueue<String>();
private static void Init(){
MsgNotify = new IMessageLogNotify() {
@Override
public void ErrorMsg(String msg) {
if(ConfigName.LOG_TEST){
Log.e("错误日志",msg);
}
}

@Override
public void InfoMsg(String msg) {
if(ConfigName.LOG_TEST){
Log.i("信息日志",msg);
}
}

@Override
public void WarnMsg(String msg) {
if(ConfigName.LOG_TEST){
Log.w("警告日志",msg);
}
}
};
ThreadManager.get().StartLong("日志信息保存",true,()->{
while(msgQueue.size()>0){
String msg= msgQueue.poll();
BPA_ALERTLOG log= new BPA_ALERTLOG();
log.text=msg;
QueryDB.AddAlertlog(log);
}
Thread.sleep(2000);
});
}

public static void ShowInfo(String msg) {
if (MsgNotify == null)Init();
MsgNotify.InfoMsg(msg);
}

public static void ShowWarning(String msg) {
if (MsgNotify == null)Init();
MsgNotify.WarnMsg(msg);
}

public static void ShowError(String msg) {
if (MsgNotify == null)Init();
MsgNotify.ErrorMsg(msg);
}

public static void ShowError(Exception e) {
if (MsgNotify == null)Init();
MsgNotify.ErrorMsg(e.toString());
}

}

+ 230
- 0
app/src/main/java/com/bonait/bnframework/HBL/NetworkUtils.java Ver fichero

@@ -0,0 +1,230 @@
package com.bonait.bnframework.HBL;


import android.content.Context;
import android.net.ConnectivityManager;
import android.net.Network;
import android.net.NetworkCapabilities;
import android.net.NetworkInfo;
import android.net.NetworkRequest;
import android.os.Build;
import android.util.Log;

import java.io.DataOutputStream;

/**
* Created by LY on 2019/1/4.
*/
public class NetworkUtils {
//判断网络连接是否可用(返回true表示网络可用,false为不可用)
public static boolean checkNetworkAvailable(Context context) {
//获取手机所有链接管理对象(包括对Wi-Fi,net等连接的管理)
ConnectivityManager manager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
if (manager == null) {
return false;
} else {
//获取NetworkInfo对象
NetworkInfo[] info = manager.getAllNetworkInfo();
if (info != null && info.length > 0) {
for (int i = 0; i < info.length; i++) {
System.out.println(i + "状态" + info[i].getState());
System.out.println(i + "类型" + info[i].getTypeName());
// 判断当前网络状态是否为连接状态
if (info[i].getState() == NetworkInfo.State.CONNECTED) {
return true;
}
}
}
}
return false;
}
/**
* 检测当的网络(WLAN、4G/3G/2G)状态,兼容Android 6.0以下
* @param context Context
* @return true 表示网络可用
*/
public static boolean isNetworkConnected(Context context) {
boolean result = false;
try {
ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (cm != null) {
NetworkCapabilities capabilities = cm.getNetworkCapabilities(cm.getActiveNetwork());
if (capabilities != null) {
if (capabilities.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)) {
result = true;
} else if (capabilities.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR)) {
result = true;
}
}
}
} else {
if (cm != null) {
NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
if (activeNetwork != null) {
// connected to the internet
if (activeNetwork.getType() == ConnectivityManager.TYPE_WIFI) {
result = true;
} else if (activeNetwork.getType() == ConnectivityManager.TYPE_MOBILE) {
result = true;
}
}
}
}

} catch (Exception e) {
return false;
}

return result;
}

/**
* 判断是否是移动网络连接
* */
public static boolean isActiveNetworkMobile(Context context) {
ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
if (connectivityManager != null) {
NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
return networkInfo != null && networkInfo.getType() == ConnectivityManager.TYPE_MOBILE;
}
return false;
}

/**
* 判断是否是wifi
* */
public static boolean isActiveNetworkWifi(Context context) {
ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
if (connectivityManager != null) {
NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
return networkInfo != null && networkInfo.getType() == ConnectivityManager.TYPE_WIFI;
}
return false;
}

/**
* @deprecated 请先使用 {@link NetworkUtils#isNetworkConnected(Context)} 方法
*
* 检测当的网络(WLAN、4G/3G/2G)状态
*
* @param context Context
* @return true 表示网络可用
*/
@Deprecated
public static boolean checkNet(Context context) {

try {
ConnectivityManager connectivity = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
if (connectivity != null) {

NetworkInfo info = connectivity.getActiveNetworkInfo();
if (info != null && info.isConnected()) {

/*if (info.getState() == NetworkInfo.State.CONNECTED) {
return true;
}*/
NetworkCapabilities networkCapabilities = connectivity.getNetworkCapabilities(connectivity.getActiveNetwork());
return networkCapabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_VALIDATED);
}
}
} catch (Exception e) {
return false;
}
return false;
}

/**
* 绑定有线网络
* @param context
*/
public static void connetEnternet(Context context)
{
ConnectivityManager connManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkRequest.Builder builder = new NetworkRequest.Builder();
builder.addTransportType(NetworkCapabilities.TRANSPORT_ETHERNET);
//builder.addTransportType(NetworkCapabilities.TRANSPORT_WIFI);
NetworkRequest networkRequest = builder.build();
connManager.requestNetwork(networkRequest, new ConnectivityManager.NetworkCallback() {
@Override
public void onAvailable(Network network) {
super.onAvailable(network);
connManager.bindProcessToNetwork(network); // 绑定应用程序到有线网络
}
});
}

/**
* 绑定有线网络
* @param context
*/
public static void connetWifi(Context context)
{
ConnectivityManager connManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkRequest.Builder builder = new NetworkRequest.Builder();
builder.addTransportType(NetworkCapabilities.TRANSPORT_WIFI);
NetworkRequest networkRequest = builder.build();
connManager.requestNetwork(networkRequest, new ConnectivityManager.NetworkCallback() {
@Override
public void onAvailable(Network network) {
super.onAvailable(network);
connManager.bindProcessToNetwork(network); // 绑定应用程序到有线网络
}
});
}

/**
* 同步时间
*/
public static void SynchronizationTime()
{
new Thread(new Runnable() {
@Override
public void run() {
try {
exec3("settings put global auto_time 0");
Thread.sleep(500);
exec3("settings put global auto_time 1");
} catch (InterruptedException e) {

}
}
}).start();
}
/**
* 发送
* @param cmds
*/
public static void exec3(String... cmds) {
StringBuffer command = new StringBuffer();
if (cmds.length <= 0) {
return;
}
for (String cmd : cmds) {
command.append(cmd).append("\n");
}
Process process = null;
DataOutputStream os = null;
try {
process = Runtime.getRuntime().exec("su");
// process = Runtime.getRuntime().exec("system/bin/su");
os = new DataOutputStream(process.getOutputStream());
os.write(command.toString().getBytes());
os.writeBytes("exit\n");
os.flush();
process.waitFor();
} catch (Exception e) {
e.printStackTrace();
Log.e("eeee",""+e.toString());
} finally {
try {
os.close();
} catch (Exception e) {
e.printStackTrace();
}
if(process!=null){
process.destroy();
}
}
}
}

+ 60
- 0
app/src/main/java/com/bonait/bnframework/HBL/NotifyEvent.java Ver fichero

@@ -0,0 +1,60 @@
package com.bonait.bnframework.HBL;

import com.bonait.bnframework.HBL.Interface.IRun;
import com.bonait.bnframework.HBL.Interface.IRunT;
import com.bonait.bnframework.HBL.Result.OperateResult;

import java.util.concurrent.ConcurrentHashMap;

public class NotifyEvent {
private static volatile NotifyEvent _instance;
public synchronized static NotifyEvent get(){
if(_instance == null)_instance = new NotifyEvent();
return _instance;
}
private NotifyEvent(){}
private ConcurrentHashMap<String, Object> _runMap = new ConcurrentHashMap<String, Object>();

public void Register(String name,IRun run){
_runMap.put(name,run);
}

public <T> void Register(String name, IRunT<T> run){
_runMap.put(name,run);
}

public OperateResult Send(String name){
try{
if(_runMap.containsKey(name)&&_runMap.get(name)!=null){
if(_runMap.get(name) instanceof IRun){
((IRun)_runMap.get(name)).Run();
return OperateResult.CreateSuccess();
}else{
return OperateResult.CreateFailed("注册类型和发送消息类型不匹配");
}
}else{
return OperateResult.CreateFailed(name+"消息未注册");
}
}catch(Exception e){
return OperateResult.CreateFailed(e);
}
}

public <T> OperateResult Send(String name, T value){
try{
if(_runMap.containsKey(name)&&_runMap.get(name)!=null){
if(_runMap.get(name) instanceof IRunT){
((IRunT)_runMap.get(name)).Run(value);
return OperateResult.CreateSuccess();
}else{
return OperateResult.CreateFailed("注册类型和发送消息类型不匹配");
}
}else{
return OperateResult.CreateFailed(name+"消息未注册");
}
}catch(Exception e){
return OperateResult.CreateFailed(e);
}
}

}

+ 39
- 0
app/src/main/java/com/bonait/bnframework/HBL/Result/IResult.java Ver fichero

@@ -0,0 +1,39 @@
package com.bonait.bnframework.HBL.Result;


public abstract class IResult {
/**
* 是否成功
*/
public boolean isSuccess ;

/**
* 返回消息
*/
public String message;

/**
* 操作代码
*/
public ResultCode resultCode = ResultCode.Default ;

abstract void setErrorMsg(String msg);

public boolean getIsSuccess(){
return resultCode==ResultCode.Success;
}

public void setIsSuccess(boolean tempSuccess){
isSuccess= tempSuccess;
resultCode = tempSuccess ? ResultCode.Success : ResultCode.Fail;
}

@Override
public String toString() {
return "IResult{" +
"isSuccess=" + isSuccess +
", message='" + message + '\'' +
", resultCode=" + resultCode +
'}';
}
}

+ 78
- 0
app/src/main/java/com/bonait/bnframework/HBL/Result/OperateResult.java Ver fichero

@@ -0,0 +1,78 @@
package com.bonait.bnframework.HBL.Result;

import com.bonait.bnframework.HBL.Interface.IRun;
import com.bonait.bnframework.HBL.Logs.MessageLog;

public class OperateResult extends IResult {

public OperateResult(){

}

public OperateResult(Exception ex){
message = ex.getMessage()+"\rException:"+ex.toString();
resultCode = ResultCode.Exception;
isSuccess=false;
}

public OperateResult(String msg, ResultCode rc)
{
message = msg;
resultCode = rc;
isSuccess=false;
}

public OperateResult(ResultCode rc)
{
resultCode = rc;
isSuccess=true;
}


@Override
public void setErrorMsg(String msg) {
message =message+ msg;
isSuccess=false;
resultCode = ResultCode.Fail;
}

public OperateResult OnSource(IRun action){
if(action!=null&&getIsSuccess())action.Run();
return this;
}

public OperateResult OnFailed(IRun action){
try{
if(action!=null&&!getIsSuccess())action.Run();
}catch(Exception e){
MessageLog.ShowError(e);
}
return this;
}

public OperateResult OnFinally(IRun action){
try{
if(action!=null)action.Run();
}catch(Exception e){
MessageLog.ShowError(e);
}
return this;
}

public static OperateResult CreateSuccess()
{
return new OperateResult(ResultCode.Success);
}

public static OperateResult CreateFailed(String msg)
{
MessageLog.ShowError(msg);
return new OperateResult(msg, ResultCode.Fail);
}

public static OperateResult CreateFailed(Exception ex)
{
MessageLog.ShowError(ex.toString());
return new OperateResult(ex);
}
}

+ 88
- 0
app/src/main/java/com/bonait/bnframework/HBL/Result/OperateResultT.java Ver fichero

@@ -0,0 +1,88 @@
package com.bonait.bnframework.HBL.Result;


import com.bonait.bnframework.HBL.Interface.IRunT;
import com.bonait.bnframework.HBL.Logs.MessageLog;

public class OperateResultT<T> extends IResult
{
public OperateResultT(){}
public OperateResultT(Exception ex) {
message = ex.getMessage()+"\rException:"+ex.toString();
resultCode = ResultCode.Exception;
isSuccess=false;
}

public OperateResultT(String msg, ResultCode rc ){
message = msg;
resultCode = rc;
isSuccess=false;
}

public OperateResultT(ResultCode rc){
resultCode = rc;
isSuccess=true;
}

@Override
public void setErrorMsg(String msg) {
message =message+ msg;
isSuccess=false;
resultCode = ResultCode.Fail;
}

public OperateResultT(T content, String msg, ResultCode rc){
Content = content;
message = msg;
resultCode = rc;
isSuccess=getIsSuccess();
}

public T Content ;

public void setContent(T value){
Content = value;
resultCode = ResultCode.Success;
isSuccess=true;
}

public OperateResultT<T> OnSource(IRunT<OperateResultT<T>> action){
try{
if(action!=null&&getIsSuccess())action.Run(this);
}catch(Exception e){
MessageLog.ShowError(e);
}
return this;
}

public OperateResultT<T> OnFailed(IRunT<OperateResultT<T>> action){
try{
if(action!=null&&!getIsSuccess())action.Run(this);
}catch(Exception e){
MessageLog.ShowError(e);
}
return this;
}

public OperateResultT<T> OnFinally(IRunT<OperateResultT<T>> action){
if(action!=null)action.Run(this);
return this;
}

public static <T> OperateResultT<T> CreateSuccess(T value)
{
return new OperateResultT<T>(value,"", ResultCode.Success);
}

public static <T> OperateResultT<T> CreateFailedT(String msg)
{
MessageLog.ShowError(msg);
return new OperateResultT<T>( msg, ResultCode.Fail);
}

public static <T> OperateResultT<T> CreateFailedT(Exception ex)
{
MessageLog.ShowError(ex.toString());
return new OperateResultT<T>(ex);
}
}

+ 38
- 0
app/src/main/java/com/bonait/bnframework/HBL/Result/ResultCode.java Ver fichero

@@ -0,0 +1,38 @@
package com.bonait.bnframework.HBL.Result;

public enum ResultCode {
/**
* 默认
*/
Default,

/**
* 错误
*/
Error,

/**
* 异常
*/
Exception,

/**
* 成功
*/
Success,

/**
* 失败
*/
Fail,

/**
* 操作超时
*/
Overtime,

/**
* 操作取消
*/
Canceled
}

+ 5
- 0
app/src/main/java/com/bonait/bnframework/HBL/Thread/IThread.java Ver fichero

@@ -0,0 +1,5 @@
package com.bonait.bnframework.HBL.Thread;

public interface IThread {
void Run() throws Exception;
}

+ 7
- 0
app/src/main/java/com/bonait/bnframework/HBL/Thread/IThreadComplete.java Ver fichero

@@ -0,0 +1,7 @@
package com.bonait.bnframework.HBL.Thread;

public interface IThreadComplete {
void Run() throws Exception;

void RunComplete() throws Exception;
}

+ 137
- 0
app/src/main/java/com/bonait/bnframework/HBL/Thread/ThreadManager.java Ver fichero

@@ -0,0 +1,137 @@
package com.bonait.bnframework.HBL.Thread;

import com.bonait.bnframework.HBL.Logs.MessageLog;

import java.util.HashMap;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class ThreadManager {
private static volatile ThreadManager _Instance;
private ExecutorService executorService;

public static ThreadManager get() {
if (_Instance == null){
synchronized (ThreadManager.class){
if (_Instance == null){
_Instance = new ThreadManager();
}
}
}
return _Instance;
}

private ThreadManager() {

}

public void inti(){
// int processors = Runtime.getRuntime().availableProcessors();
executorService = Executors.newCachedThreadPool();
}

public void execute(Runnable runnable){
try{
executorService.execute(runnable);
}catch (Exception e){
e.printStackTrace();
}
}

public void shutDown(){
executorService.shutdown();
}

public long RestartInterval = 3000;
ConcurrentHashMap<String, ThreadModel> tm = new ConcurrentHashMap<>();

private void Sleep(long millis) {
try {
Thread.sleep(millis);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}

public void StartLong(String Key, boolean IsRestart, IThreadComplete _thread) {
if (!tm.containsKey(Key)) {
tm.put(Key, new ThreadModel());
tm.get(Key).RunThread = _thread;
tm.get(Key).ThreadObj = new Thread(() -> {
MessageLog.ShowInfo("启动线程:" + Key);
while (!tm.get(Key).IsCancel) {
if (IsRestart) {
try {
tm.get(Key).RunThread.Run();
} catch (Exception ex) {
MessageLog.ShowError("多线程:[" + Key + "] 运行发生异常,已重启,错误信息:" + ex.toString());
Sleep(RestartInterval);
}
} else {
try {
tm.get(Key).RunThread.Run();
} catch (Exception e) {
MessageLog.ShowError("多线程:[" + Key + "] 运行发生异常,已重启,错误信息:" + e.toString());
}
}
}
try {
tm.get(Key).RunThread.RunComplete();
MessageLog.ShowInfo("线程:[" + Key + "]--执行完成");
} catch (Exception e) {
MessageLog.ShowError("多线程:[" + Key + "] 执行完成任务发生异常,已退出,错误信息:" + e.toString());
}
tm.remove(Key);
});
tm.get(Key).ThreadObj.setName(Key);
tm.get(Key).ThreadObj.start();
} else {
MessageLog.ShowWarning("任务-[" + Key + "]-已存在");
}
}

public void StartLong(String Key, boolean IsRestart, IThread _thread) {
if (!tm.containsKey(Key)) {
tm.put(Key, new ThreadModel());
tm.get(Key).Task = _thread;
tm.get(Key).ThreadObj = new Thread(() -> {
MessageLog.ShowInfo("启动线程:" + Key);
while (!tm.get(Key).IsCancel) {
if (IsRestart) {
try {
tm.get(Key).Task.Run();
} catch (Exception ex) {
MessageLog.ShowError("多线程:[" + Key + "] 运行发生异常,已重启,错误信息:" + ex.toString());
Sleep(RestartInterval);
}
} else {
try {
tm.get(Key).Task.Run();
} catch (Exception e) {
MessageLog.ShowError("多线程:[" + Key + "] 运行发生异常,已重启,错误信息:" + e.toString());
}
}
}
tm.remove(Key);
});
tm.get(Key).ThreadObj.setName(Key);
tm.get(Key).ThreadObj.start();
} else {
MessageLog.ShowWarning("任务-[" + Key + "]-已存在");
}
}

public void Stop(String Key) {
if (tm.containsKey(Key)) {
tm.get(Key).IsCancel = true;
}
}

public void release(){
for (HashMap.Entry<String, ThreadModel> entry : tm.entrySet()) {
entry.getValue().IsCancel = true;
}
}

}

+ 8
- 0
app/src/main/java/com/bonait/bnframework/HBL/Thread/ThreadModel.java Ver fichero

@@ -0,0 +1,8 @@
package com.bonait.bnframework.HBL.Thread;

public class ThreadModel {
public IThreadComplete RunThread;
public IThread Task;
public boolean IsCancel;
public Thread ThreadObj;
}

app/src/main/java/com/bonait/bnframework/common/helper/RTrig.java → app/src/main/java/com/bonait/bnframework/HBL/Trig/RTrig.java Ver fichero

@@ -1,6 +1,8 @@
package com.bonait.bnframework.common.helper;
package com.bonait.bnframework.HBL.Trig;

import com.bonait.bnframework.common.helper.I.IRun;


import com.bonait.bnframework.HBL.Interface.IRun;

import java.util.concurrent.ConcurrentHashMap;


+ 2
- 54
app/src/main/java/com/bonait/bnframework/MainApplication.java Ver fichero

@@ -1,66 +1,13 @@
package com.bonait.bnframework;


import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.Application;
import android.content.Context;
import android.content.pm.PackageManager;
import android.util.Log;

import androidx.core.content.ContextCompat;

import com.bonait.bnframework.business.ConfigData;
import com.bonait.bnframework.HBL.Thread.ThreadManager;
import com.bonait.bnframework.common.constant.ConfigName;
import com.bonait.bnframework.common.constant.DataBus;
import com.bonait.bnframework.common.db.QueryDB;
import com.bonait.bnframework.common.db.file.DBHelper;
import com.bonait.bnframework.common.db.mode.BPA_ALERTLOG;
import com.bonait.bnframework.common.db.mode.BPA_CLOUDDATA;
import com.bonait.bnframework.common.db.mode.BPA_GOODS;
import com.bonait.bnframework.common.db.mode.BPA_LOG;
import com.bonait.bnframework.common.db.mode.BPA_PLCADDRESS;
import com.bonait.bnframework.common.db.mode.BPA_PROCESS;
import com.bonait.bnframework.common.db.mode.BPA_PROCESSModel;
import com.bonait.bnframework.common.db.mode.BPA_SILOS;
import com.bonait.bnframework.common.db.mode.BPA_SILOSANDMATERIAL;
import com.bonait.bnframework.common.db.mode.BPA_USER;
import com.bonait.bnframework.common.db.res.AlertLogEnum;
import com.bonait.bnframework.common.db.res.UserLogEnum;
import com.bonait.bnframework.common.helper.CrashHandler;
import com.bonait.bnframework.common.helper.I.IMessageLogNotify;
import com.bonait.bnframework.common.helper.MessageLog;
import com.bonait.bnframework.common.helper.SdCart;
import com.bonait.bnframework.common.utils.NetworkUtils;
import com.bonait.bnframework.common.utils.ToastUtils;
import com.bonait.bnframework.manager.ActivityLifecycleManager;
import com.bonait.bnframework.common.constant.Constants;
import com.bonait.bnframework.common.notification.MainNotification;
import com.bonait.bnframework.common.utils.AppUtils;
import com.bonait.bnframework.common.utils.PreferenceUtils;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.cache.CacheEntity;
import com.lzy.okgo.cache.CacheMode;
import com.lzy.okgo.interceptor.HttpLoggingInterceptor;
import com.orhanobut.logger.AndroidLogAdapter;
import com.orhanobut.logger.FormatStrategy;
import com.orhanobut.logger.Logger;
import com.orhanobut.logger.PrettyFormatStrategy;
import com.qmuiteam.qmui.arch.QMUISwipeBackActivityManager;

import org.litepal.LitePal;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.IdentityHashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.logging.Level;

import okhttp3.OkHttpClient;
import pub.devrel.easypermissions.EasyPermissions;

/**
* Created by FYF on 2019/3/19.
@@ -82,5 +29,6 @@ public class MainApplication extends Application {
context = getApplicationContext();
ConfigName.getInstance().dishesCon = this;
ConfigName.getInstance().app = this;
ThreadManager.get().inti();
}
}

app/src/main/java/com/bonait/bnframework/modules/welcome/model/AppLoginPo.java → app/src/main/java/com/bonait/bnframework/Model/AppLoginPo.java Ver fichero

@@ -1,4 +1,4 @@
package com.bonait.bnframework.modules.welcome.model;
package com.bonait.bnframework.Model;

import java.util.List;


+ 34
- 0
app/src/main/java/com/bonait/bnframework/Model/ErrorCodeBean.java Ver fichero

@@ -0,0 +1,34 @@
package com.bonait.bnframework.Model;

import java.util.List;

public class ErrorCodeBean {

private int code;
private String name;
private String description;

public int getCode() {
return code;
}

public void setCode(int code) {
this.code = code;
}

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

public String getDescription() {
return description;
}

public void setDescription(String description) {
this.description = description;
}
}

app/src/main/java/com/bonait/bnframework/modules/mine/model/UpdateAppPo.java → app/src/main/java/com/bonait/bnframework/Model/UpdateAppPo.java Ver fichero

@@ -1,4 +1,4 @@
package com.bonait.bnframework.modules.mine.model;
package com.bonait.bnframework.Model;

import com.google.gson.annotations.SerializedName;


app/src/main/java/com/bonait/bnframework/modules/home/fragment/from/fragment/UserInfo.java → app/src/main/java/com/bonait/bnframework/Model/UserInfo.java Ver fichero

@@ -1,4 +1,4 @@
package com.bonait.bnframework.modules.home.fragment.from.fragment;
package com.bonait.bnframework.Model;

import com.bin.david.form.annotation.SmartColumn;
import com.bin.david.form.annotation.SmartTable;

+ 148
- 0
app/src/main/java/com/bonait/bnframework/Service/AnalogConvert.java Ver fichero

@@ -0,0 +1,148 @@
package com.bonait.bnframework.Service;

import android.content.Context;

import com.apkfuns.logutils.LogUtils;
import com.bonait.bnframework.common.constant.ConfigName;
import com.bonait.bnframework.common.helper.ConfigUtil;

/**
* 模拟量转换
*/
public class AnalogConvert {

/**
* 模拟量温度上限
*/
public static short et_Temperature_Analog_Upper_Limit=0;

/**
* 模拟量温度下限
*/
public static short et_Temperature_Analog_Lower_Limit=0;

/**
* 实际温度上限
*/
public static short et_Temperature_Upper_Limit=0;

/**
* 实际温度下限
*/
public static short et_Temperature_Lower_Limit=0;

/**
* 模拟量压力上限
*/
public static short et_Pressure_Analog_Upper_Limit=0;

/**
* 模拟量压力下限
*/
public static short et_Pressure_Analog_Lower_Limit=0;

/**
* 实际压力上限
*/
public static short et_Pressure_Upper_Limit=0;

/**
* 实际压力下限
*/
public static short et_Pressure_Lower_Limit=0;

public static int Scale(float InputValue, float InputMax, float InputMin, float OutMax, float OutMin){
try{
LogUtils.d("AnalogConvert measureCookTime InputValue="+InputValue+" InputMax="+InputMax+";InputMin="+InputMin+";OutMax="+OutMax+";OutMin="+OutMin);

if(InputValue<=0|| InputMax<=0||InputMin<=0){
return 0;
}
if(((InputMax - InputMin) + OutMin)==0){
return 0;
}
float tempValue = (OutMax - OutMin) * (InputValue - InputMin) / (InputMax - InputMin) + OutMin;
if(tempValue<=0){
tempValue = 0;
}
int num =(int)(tempValue*100);
// if (num > OutMax) return OutMax;
// if (num < OutMin) return OutMin;
return num;
}catch(Exception e){

}
return 0;
}

/**
// * 获取当前实际压力值
// * @param InputValue 当前实际压力的模拟量值
// * @return 当前实际压力值
// */
// public static short getCurrentPressure(short InputValue){
// return Scale(InputValue,et_Pressure_Analog_Upper_Limit,et_Pressure_Analog_Lower_Limit,et_Pressure_Upper_Limit,et_Pressure_Lower_Limit);
// }
//
// /**
// * 获取当前实际压力的模拟量值
// * @param InputValue 当前实际压力值
// * @return 对应的模拟量值
// */
// public static short getCurrentPressureAnalog(short InputValue){
// return Scale(InputValue,et_Pressure_Upper_Limit,et_Pressure_Lower_Limit,et_Pressure_Analog_Upper_Limit,et_Pressure_Analog_Lower_Limit);
// }
//
//
// /**
// * 获取当前实际温度值
// * @param InputValue 当前实际温度的模拟量值
// * @return 当前实际温度值
// */
// public static short getCurrentTemperature(short InputValue){
// return Scale(InputValue,et_Temperature_Analog_Upper_Limit,et_Temperature_Analog_Lower_Limit,et_Temperature_Upper_Limit,et_Temperature_Lower_Limit);
// }
//
// /**
// * 获取当前实际温度的模拟量值
// * @param InputValue 当前实际压力值
// * @return 对应的模拟量值
// */
// public static short getCurrentTemperatureAnalog(short InputValue){
// return Scale(InputValue,et_Temperature_Upper_Limit,et_Temperature_Lower_Limit,et_Temperature_Analog_Upper_Limit,et_Temperature_Analog_Lower_Limit);
// }

public static void SaveConfig(){
Context dishesCon = ConfigName.getInstance().dishesCon;
ConfigUtil.write(dishesCon, "et_Temperature_Analog_Upper_Limit",et_Temperature_Analog_Upper_Limit );
ConfigUtil.write(dishesCon, "et_Temperature_Analog_Lower_Limit",et_Temperature_Analog_Lower_Limit);
ConfigUtil.write(dishesCon, "et_Temperature_Upper_Limit",et_Temperature_Upper_Limit );
ConfigUtil.write(dishesCon, "et_Temperature_Lower_Limit",et_Temperature_Lower_Limit);
ConfigUtil.write(dishesCon, "et_Pressure_Analog_Upper_Limit",et_Pressure_Analog_Upper_Limit );
ConfigUtil.write(dishesCon, "et_Pressure_Analog_Lower_Limit",et_Pressure_Analog_Lower_Limit );
ConfigUtil.write(dishesCon, "et_Pressure_Upper_Limit",et_Pressure_Upper_Limit );
ConfigUtil.write(dishesCon, "et_Pressure_Lower_Limit",et_Pressure_Lower_Limit );
}

private static short getConfig(String key){
try{
Context dishesCon = ConfigName.getInstance().dishesCon;
return (short)ConfigUtil.read(dishesCon, key,0 );
}catch(Exception e){

}
return 0;
}

public static void ReadConfig(){
et_Temperature_Analog_Upper_Limit =getConfig("et_Temperature_Analog_Upper_Limit");
et_Temperature_Analog_Lower_Limit=getConfig("et_Temperature_Analog_Lower_Limit");
et_Temperature_Upper_Limit =getConfig("et_Temperature_Upper_Limit");
et_Temperature_Lower_Limit=getConfig("et_Temperature_Lower_Limit");
et_Pressure_Analog_Upper_Limit =getConfig("et_Pressure_Analog_Upper_Limit");
et_Pressure_Analog_Lower_Limit =getConfig("et_Pressure_Analog_Lower_Limit");
et_Pressure_Upper_Limit =getConfig("et_Pressure_Upper_Limit");
et_Pressure_Lower_Limit =getConfig("et_Pressure_Lower_Limit");
}

}

+ 52
- 0
app/src/main/java/com/bonait/bnframework/Service/ControlAdress.java Ver fichero

@@ -0,0 +1,52 @@
package com.bonait.bnframework.Service;

public enum ControlAdress {
心跳,//D0
掉线标志,//M100
急停按钮,//M101

状态读取启动,//M52
状态读取,//D52
加水,//M4
加水时间,//D1000
液体1,//M5
液体2,//M6
液体3,//M7
液体4,//M8
液体5,//M9
液体6,//M10
液体时间1,//D1001
液体时间2,//D1002
液体时间3,//D1003
液体时间4,//D1004
液体时间5,//D1005
液体时间6,//D1006
液体7,//M11
液体8,//M12
液体9,//M13
液体时间7,//D1007
液体时间8,//D1008
液体时间9,//D1009
勾芡,//M14
勾芡时间,//D1010
主料1,//M15
主料2,//M16
主料3,//M17
主料4,//M18
主料5,//M19
主料6,//M20
上升,//M21
下降,//M22
搅拌启动,//M23
搅拌停止,//M24
搅拌档位,//D50
启动加热,//M25 (启动时需判断是否正在加热状态)
停止加热,//M26
加热档位,//D51 0-100
炒制模式,//M102
//
// 搅拌检测,//X2
// 升降检测上限位,//X1
// 升降检测下限位,//X4

}

+ 24
- 0
app/src/main/java/com/bonait/bnframework/Service/Func.java Ver fichero

@@ -0,0 +1,24 @@
package com.bonait.bnframework.Service;

public enum Func {
/**
* 加热功能
* par:加热温度,加热档位
*/
加热,
/**
* 泄压功能
* par:泄压压力
*/
泄压,
/**
* 保温功能
* par:保温温度,保温时间
*/
保温,
/**
*烹饪功能
* par:烹饪温度,烹饪时间
*/
烹饪,
}

+ 530
- 0
app/src/main/java/com/bonait/bnframework/Service/ModbusHelper.java Ver fichero

@@ -0,0 +1,530 @@
package com.bonait.bnframework.Service;

import com.apkfuns.logutils.LogUtils;
import com.bonait.bnframework.HBL.Communication.Modbus.ModbusMaster;
import com.bonait.bnframework.HBL.DataUtil.DataType;
import com.bonait.bnframework.HBL.DataUtil.NotifyPropVar;
import com.bonait.bnframework.HBL.Executor;
import com.bonait.bnframework.HBL.Interface.IRunT;
import com.bonait.bnframework.HBL.Logs.MessageLog;
import com.bonait.bnframework.HBL.Result.OperateResultT;
import com.bonait.bnframework.HBL.Thread.ThreadManager;
import com.bonait.bnframework.business.ExecuteTheRecipe;
import com.bonait.bnframework.common.constant.ConfigName;
import com.bonait.bnframework.common.db.mode.BPA_SILOS_CALIBRATE;
import com.bonait.bnframework.common.utils.ToastUtils;

import java.util.ArrayList;
import java.util.concurrent.ConcurrentHashMap;

public class ModbusHelper extends ModbusMaster {
private final static String TAG = "ModbusHelper==>";
private static volatile ModbusHelper instance = null;
private boolean isDisconnect = true;
public synchronized static ModbusHelper get(){
if(instance==null){
synchronized (ModbusHelper.class){
if(instance==null){
instance=new ModbusHelper();
}
}
}
return instance;
}
private ModbusHelper(){}

public ConcurrentHashMap<ControlAdress, PLCModel> controlAddress=new ConcurrentHashMap<ControlAdress,PLCModel>(){{
put(ControlAdress.心跳,new PLCModel("D0", DataType.SHORT, OperationModel.W) );
put(ControlAdress.掉线标志,new PLCModel("M100",DataType.BOOLEAN,OperationModel.R));
put(ControlAdress.急停按钮,new PLCModel("M101",DataType.BOOLEAN,OperationModel.R));
put(ControlAdress.加热档位,new PLCModel("D51",DataType.SHORT,OperationModel.W));
put(ControlAdress.启动加热,new PLCModel("M25",DataType.BOOLEAN,OperationModel.RW));
put(ControlAdress.停止加热,new PLCModel("M26",DataType.BOOLEAN,OperationModel.RW));
put(ControlAdress.状态读取启动,new PLCModel("M27",DataType.BOOLEAN,OperationModel.W));
put(ControlAdress.状态读取,new PLCModel("D52",DataType.SHORTS,OperationModel.R));
put(ControlAdress.加水时间,new PLCModel("D1000",DataType.SHORT,OperationModel.W));
put(ControlAdress.加水,new PLCModel("M4",DataType.BOOLEAN,OperationModel.W));
put(ControlAdress.液体时间1,new PLCModel("D1001",DataType.SHORT,OperationModel.W));
put(ControlAdress.液体1,new PLCModel("M5",DataType.BOOLEAN,OperationModel.W));
put(ControlAdress.液体时间2,new PLCModel("D1002",DataType.SHORT,OperationModel.W));
put(ControlAdress.液体2,new PLCModel("M6",DataType.BOOLEAN,OperationModel.W));
put(ControlAdress.液体时间3,new PLCModel("D1003",DataType.SHORT,OperationModel.W));
put(ControlAdress.液体3,new PLCModel("M7",DataType.BOOLEAN,OperationModel.W));
put(ControlAdress.液体时间4,new PLCModel("D1004",DataType.SHORT,OperationModel.W));
put(ControlAdress.液体4,new PLCModel("M8",DataType.BOOLEAN,OperationModel.W));
put(ControlAdress.液体时间5,new PLCModel("D1005",DataType.SHORT,OperationModel.W));
put(ControlAdress.液体5,new PLCModel("M9",DataType.BOOLEAN,OperationModel.W));
put(ControlAdress.液体时间6,new PLCModel("D1006",DataType.SHORT,OperationModel.W));
put(ControlAdress.液体6,new PLCModel("M10",DataType.BOOLEAN,OperationModel.W));
put(ControlAdress.液体时间7,new PLCModel("D1007",DataType.SHORT,OperationModel.W));
put(ControlAdress.液体7,new PLCModel("M11",DataType.BOOLEAN,OperationModel.W));
put(ControlAdress.液体时间8,new PLCModel("D1008",DataType.SHORT,OperationModel.W));
put(ControlAdress.液体8,new PLCModel("M12",DataType.BOOLEAN,OperationModel.W));
put(ControlAdress.液体时间9,new PLCModel("D1009",DataType.SHORT,OperationModel.W));
put(ControlAdress.液体9,new PLCModel("M13",DataType.BOOLEAN,OperationModel.W));
put(ControlAdress.勾芡时间,new PLCModel("D1010",DataType.SHORT,OperationModel.W));
put(ControlAdress.勾芡,new PLCModel("M14",DataType.BOOLEAN,OperationModel.W));
put(ControlAdress.主料1,new PLCModel("M15",DataType.BOOLEAN,OperationModel.W));
put(ControlAdress.主料2,new PLCModel("M16",DataType.BOOLEAN,OperationModel.W));
put(ControlAdress.主料3,new PLCModel("M17",DataType.BOOLEAN,OperationModel.W));
put(ControlAdress.主料4,new PLCModel("M18",DataType.BOOLEAN,OperationModel.W));
put(ControlAdress.主料5,new PLCModel("M19",DataType.BOOLEAN,OperationModel.W));
put(ControlAdress.主料6,new PLCModel("M20",DataType.BOOLEAN,OperationModel.W));
put(ControlAdress.上升,new PLCModel("M21",DataType.BOOLEAN,OperationModel.W));
put(ControlAdress.下降,new PLCModel("M22",DataType.BOOLEAN,OperationModel.W));
put(ControlAdress.搅拌启动,new PLCModel("M23",DataType.BOOLEAN,OperationModel.W));
put(ControlAdress.搅拌停止,new PLCModel("M24",DataType.BOOLEAN,OperationModel.W));
put(ControlAdress.搅拌档位,new PLCModel("D50",DataType.SHORT,OperationModel.W));
put(ControlAdress.炒制模式,new PLCModel("M102",DataType.BOOLEAN,OperationModel.W));
// put(ControlAdress.搅拌档位,new PLCModel("M26",DataType.BOOLEAN,OperationModel.W));
// put(ControlAdress.升降检测上限位,new PLCModel("X2",DataType.BOOLEAN,OperationModel.W));
// put(ControlAdress.升降检测下限位,new PLCModel("X4",DataType.BOOLEAN,OperationModel.W));
}};

private ConcurrentHashMap<String, BPA_SILOS_CALIBRATE> calibrationParMap=new ConcurrentHashMap<>();
public void Add(ArrayList<BPA_SILOS_CALIBRATE> list){
if(list.isEmpty())return ;
list.forEach(item ->{
calibrationParMap.put(item.name,item);
});
}
private OperateResultT<BPA_SILOS_CALIBRATE> getCalibrationPar(String name){
if(calibrationParMap.containsKey(name)){
return OperateResultT.CreateSuccess(calibrationParMap.get(name));
}else{
return OperateResultT.CreateFailedT("不存在的校准参数:"+name);
}
}

private void Sleep(long millis) {
try {
Thread.sleep(millis);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}


/**
* 加热控制
* @param GearPosition 加热档位
* @param command 启动或停止
*/
public void Heating(int GearPosition,boolean command){
if(command){
WriteShort(getPLC(ControlAdress.加热档位).PlcAddress, (short) (command?GearPosition:0));
WriteBool(getPLC(ControlAdress.启动加热).PlcAddress,true);
}else {
WriteShort(getPLC(ControlAdress.加热档位).PlcAddress, (short) (command?GearPosition:0));
WriteBool(getPLC(ControlAdress.停止加热).PlcAddress,true);
}

MessageLog.ShowInfo("Heating GearPosition="+GearPosition + ";command="+command);
LogUtils.d(TAG+"加热控制 Heating GearPosition="+GearPosition+" command="+command);
}

/**
* 加水控制
* @param value
* @param isCalibration 是否是校准
*/
public void addWater(float value,boolean isCalibration){
LogUtils.d(TAG+"加水控制 addSeason ");
getCalibrationPar(ControlAdress.加水.toString()).OnSource(item->{
BPA_SILOS_CALIBRATE bean = (BPA_SILOS_CALIBRATE)item.Content;
short valueDeal;
if(isCalibration){
valueDeal = (short) (value*100);
}else {
valueDeal = (short) AnalogConvert.Scale( value, bean.inputWightMax, bean.inputWightMin,
bean.outputTimeMax, bean.outputTimeMin);
}
WriteShort(getPLC(ControlAdress.加水时间).PlcAddress, (short) (valueDeal));
WriteBool(getPLC(ControlAdress.加水).PlcAddress,true);
readWater();
LogUtils.d(TAG+TAG+"加水控制 addSeason value="+value + "valueDeal="+valueDeal);
}) ;
}

public boolean readWater(){
OperateResultT<Boolean> resultT = ReadBool(getPLC(ControlAdress.加水).PlcAddress);
LogUtils.d(TAG+"加水控制复位读取 readMaterial "+" resultT="+resultT.Content);
return resultT.Content;
}
/**
* 液体料控制
* @param value 量
* @param position 几号仓
* @param isCalibration 是否是校准
*/
public void addMaterial(float value, int position,boolean isCalibration){
ControlAdress controlAdress = ControlAdress.液体1;
ControlAdress controlTimeAdress = ControlAdress.液体时间1;
switch (position){
case 1:
controlAdress = ControlAdress.液体1;
controlTimeAdress = ControlAdress.液体时间1;
break;
case 2:
controlAdress = ControlAdress.液体2;
controlTimeAdress = ControlAdress.液体时间2;
break;
case 3:
controlAdress = ControlAdress.液体3;
controlTimeAdress = ControlAdress.液体时间3;
break;
case 4:
controlAdress = ControlAdress.液体4;
controlTimeAdress = ControlAdress.液体时间4;
break;
case 5:
controlAdress = ControlAdress.液体5;
controlTimeAdress = ControlAdress.液体时间5;
break;
case 6:
controlAdress = ControlAdress.液体6;
controlTimeAdress = ControlAdress.液体时间6;
break;
case 7:
controlAdress = ControlAdress.液体7;
controlTimeAdress = ControlAdress.液体时间7;
break;
case 8:
controlAdress = ControlAdress.液体8;
controlTimeAdress = ControlAdress.液体时间8;
break;
case 9:
controlAdress = ControlAdress.液体9;
controlTimeAdress = ControlAdress.液体时间9;
break;

}
ControlAdress finalControlTimeAdress = controlTimeAdress;
ControlAdress finalControlAdress = controlAdress;
LogUtils.d("<<--"+TAG+"液体料控制 addSeason value="+value+";position="+position);
getCalibrationPar(controlAdress.toString()).OnSource(item->{
BPA_SILOS_CALIBRATE bean = (BPA_SILOS_CALIBRATE)item.Content;
short valueDeal ;
if(isCalibration){
valueDeal = (short) (value*100);
}else {
valueDeal = (short) AnalogConvert.Scale(value, bean.inputWightMax, bean.inputWightMin,
bean.outputTimeMax, bean.outputTimeMin);
}
WriteShort(getPLC(finalControlTimeAdress).PlcAddress, (short) (valueDeal));
WriteBool(getPLC(finalControlAdress).PlcAddress,true);
LogUtils.d(TAG+"液体料控制 addSeason value="+value+" ;valueDeal="+valueDeal+";position="+position+"-->>");
}) ;
}

/**
* 液体料复位读取
*/
public boolean readMaterial(int position){
ControlAdress controlAdress = ControlAdress.液体1;
switch (position){
case 1:
controlAdress = ControlAdress.液体1;
break;
case 2:
controlAdress = ControlAdress.液体2;
break;
case 3:
controlAdress = ControlAdress.液体3;
break;
case 4:
controlAdress = ControlAdress.液体4;
break;
case 5:
controlAdress = ControlAdress.液体5;
break;
case 6:
controlAdress = ControlAdress.液体6;
break;
case 7:
controlAdress = ControlAdress.液体7;
break;
case 8:
controlAdress = ControlAdress.液体8;
break;
case 9:
controlAdress = ControlAdress.液体9;
break;
}
OperateResultT<Boolean> resultT = ReadBool(getPLC(controlAdress).PlcAddress);
LogUtils.d(TAG+"液体料复位读取 readMaterial position="+position+" resultT="+resultT.Content);
return resultT.Content;
}

/**
* 勾芡控制
* @param value
* * @param isCalibration 是否是校准
*/
public void addThickenWater(float value,boolean isCalibration){
getCalibrationPar(ControlAdress.勾芡.toString()).OnSource(item->{
BPA_SILOS_CALIBRATE bean = (BPA_SILOS_CALIBRATE)item.Content;
short scale;
if(isCalibration){
scale = (short) (value*100);
}else{
scale = (short) AnalogConvert.Scale( value, bean.inputWightMax, bean.inputWightMin,
bean.outputTimeMax, bean.outputTimeMin);
}
WriteShort(getPLC(ControlAdress.勾芡时间).PlcAddress, (short) (scale));
WriteBool(getPLC(ControlAdress.勾芡).PlcAddress,true);
LogUtils.d(TAG+"勾芡控制 addThickenWater value="+value+"scale="+scale);
}) ;
}

public boolean readThickenWater(){
OperateResultT<Boolean> resultT = ReadBool(getPLC(ControlAdress.勾芡).PlcAddress);
LogUtils.d(TAG+"勾芡控制复位读取 readMaterial "+" resultT="+resultT.Content);
return resultT.Content;
}

/**
* 主料控制
* @param position
*/
public void addMainFood(int position){
ControlAdress controlAdress = ControlAdress.主料1;
switch (position){
case 1:
controlAdress = ControlAdress.主料1;
break;
case 2:
controlAdress = ControlAdress.主料2;
break;
case 3:
controlAdress = ControlAdress.主料3;
break;
case 4:
controlAdress = ControlAdress.主料4;
break;
case 5:
controlAdress = ControlAdress.主料5;
break;
case 6:
controlAdress = ControlAdress.主料6;
break;
}
WriteBool(getPLC(controlAdress).PlcAddress,true);
LogUtils.d(TAG+"添加主料 addMainFood position="+position);
}

/**
* 主料复位读取
* @param position
*/
public boolean readMainFood(int position){
ControlAdress controlAdress = ControlAdress.主料1;
switch (position){
case 1:
controlAdress = ControlAdress.主料1;
break;
case 2:
controlAdress = ControlAdress.主料2;
break;
case 3:
controlAdress = ControlAdress.主料3;
break;
case 4:
controlAdress = ControlAdress.主料4;
break;
case 5:
controlAdress = ControlAdress.主料5;
break;
}
OperateResultT<Boolean> resultT = ReadBool(getPLC(controlAdress).PlcAddress);
LogUtils.d(TAG+"液体料复位读取 readMaterial position="+position+" resultT="+resultT.Content);
return resultT.Content;
}

/**
* 升降电机控制
* @param status 1 上升 2下降
*/
public void setUpdDownMotor(int status){
if(status == 2){
// WriteBool(getPLC(ControlAdress.上升).PlcAddress,false);
WriteBool(getPLC(ControlAdress.下降).PlcAddress,true);
}else {
// WriteBool(getPLC(ControlAdress.下降).PlcAddress,false);
WriteBool(getPLC(ControlAdress.上升).PlcAddress,true);
}
LogUtils.d(TAG+"升降电机控制 setUpdDownMotor status="+status);
}

/**
* 搅拌电机控制
* @param status 1 正转启动 2停止
*/
public void setStirMotor(int position,int status){
if(status == 2){
// WriteBool(getPLC(ControlAdress.搅拌正转).PlcAddress,false);
WriteBool(getPLC(ControlAdress.搅拌停止).PlcAddress,true);
}else {
//TODO 搅拌档位
WriteShort(getPLC(ControlAdress.搅拌档位).PlcAddress,(short) position);
WriteBool(getPLC(ControlAdress.搅拌启动).PlcAddress,true);
// WriteBool(getPLC(ControlAdress.搅拌停止).PlcAddress,false);
}
LogUtils.d(TAG+"搅拌电机控制 setStirMotor status="+status);
}



public PLCModel getPLC(ControlAdress func){
if(controlAddress.containsKey(func)){
return controlAddress.get(func);
}else{
MessageLog.ShowInfo("不存在控制地址:"+func.toString());
return new PLCModel();
}
}



public NotifyPropVar<Boolean> IsRunning=new NotifyPropVar<Boolean>(false);

public int CurrentTime=0;

public void RtuInit(String comName,int baudRate){
new Thread(()->{ RtuConnect(comName,baudRate).OnSource(()->{ GetLooperStatus();});}).start();
}


/**
* 设置变量监听通知
* @param func
* @param action
* @param <T>
*/
public <T> void setPLCNotify(ControlAdress func,String key, IRunT<T> action){
// if(controlAddress.containsKey(func)){
// controlAddress.get(func).Value.Register(key,action);
// }
}

/**
* 写布尔信号
* @param func
* @param value
*/
public void WriteBoolSingle(ControlAdress func, boolean value){
// if(controlAddress.containsKey(func)){
// Executor.get().runThread(()->{
// WriteBool(controlAddress.get(func).PlcAddress,value).OnSource(()->{
// MessageLog.ShowInfo("写入 "+controlAddress.get(func).PlcAddress+":"+value);
// });
// });
// }
}

/**
* 写脉冲信号
* @param func
*/
public void PulseSignal(ControlAdress func){
// if(controlAddress.containsKey(func)){
// Executor.get().runThread(()->{
// WriteBool(controlAddress.get(func).PlcAddress,true);
// Sleep(1000);
// WriteBool(controlAddress.get(func).PlcAddress,false);
// });
// }
}

public <T> void WriteAsync(String address,T value) {
Executor.get().runThread(()->{
Write(address,value);
});
}

public void reset(){
Executor.get().runThread(()->{
try {
Thread.sleep(200);
Heating(0,false);
setStirMotor(0,2);
setUpdDownMotor(1);
setCookStatus(false);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
});

}

/**
* 设置炒制模式
*/
public void setCookStatus(boolean isCooking){
Executor.get().runThread(()->{
WriteBool(getPLC(ControlAdress.炒制模式).PlcAddress,isCooking);
LogUtils.d(TAG+"炒制模式 Cooking isCooking="+isCooking);
});
}

/**
* 循环心跳
*/
private void GetLooperStatus(){
LogUtils.d(" 启动线程 Modbus变量状态 ");
ThreadManager.get().StartLong("Modbus变量状态",true,()->{


WriteShort(getPLC(ControlAdress.心跳).PlcAddress, (short) 0);

PLCModel<Boolean> statusModel1 = controlAddress.get(ControlAdress.掉线标志);
OperateResultT<Boolean> res1 = ReadBool(statusModel1.PlcAddress);
if(res1.isSuccess){
statusModel1.Value.setValue(res1.Content);
if(res1.Content){
WriteBool("M100",false);
LogUtils.d(" 设备掉线了");
if(!isDisconnect){
ToastUtils.info("设备掉线了");
}
isDisconnect = true;
}else {
isDisconnect = false;
}
}

PLCModel<Boolean> statusModel2 = controlAddress.get(ControlAdress.急停按钮);
OperateResultT<Boolean> res2 = ReadBool(statusModel2.PlcAddress);
LogUtils.d("M100 res3.Content="+res2.Content);
if(res2.isSuccess){
statusModel2.Value.setValue(res2.Content);
if(res2.Content){
if(ExecuteTheRecipe.IsStart){
LogUtils.d(" M100 res3.Conten");
ToastUtils.info("设备急停了!");
}
ExecuteTheRecipe.IsStart = false;
ExecuteTheRecipe.IsForcedEnd = true;
}else {

}
}



PLCModel<short[]> statusModel = controlAddress.get(ControlAdress.状态读取);
WriteBool(getPLC(ControlAdress.状态读取启动).PlcAddress,true);
OperateResultT<short[]> res = ReadShort(statusModel.PlcAddress,1);
if(res.isSuccess){
statusModel.Value.setValue(res.Content);
}


Thread.sleep(ConfigName.TEST?500:200);
});
}
}





+ 16
- 0
app/src/main/java/com/bonait/bnframework/Service/OperationModel.java Ver fichero

@@ -0,0 +1,16 @@
package com.bonait.bnframework.Service;

public enum OperationModel {
/**
* 只读
*/
R,
/**
* 只写
*/
W,
/**
* 可读可写
*/
RW
}

+ 23
- 0
app/src/main/java/com/bonait/bnframework/Service/PLCModel.java Ver fichero

@@ -0,0 +1,23 @@
package com.bonait.bnframework.Service;

import com.bonait.bnframework.HBL.DataUtil.NotifyPropVar;

import java.io.Serializable;

public class PLCModel<T extends Serializable> {
public String PlcAddress;
public NotifyPropVar<T> Value;
public <T> T getValue(){
return (T)Value.getValue();
}
public OperationModel operationModel;
public PLCModel(String add,T defaultValue,OperationModel om){
PlcAddress = add;
Value = new NotifyPropVar<>(defaultValue);
operationModel = om;
}

public PLCModel(){

}
}

app/src/main/java/com/bonait/bnframework/modules/home/activity/BottomNavigation2Activity.java → app/src/main/java/com/bonait/bnframework/ViewModel/ActivityViewModel/BottomNavigation2Activity.java Ver fichero

@@ -1,34 +1,28 @@
package com.bonait.bnframework.modules.home.activity;
package com.bonait.bnframework.ViewModel.ActivityViewModel;

import android.os.Bundle;
import androidx.annotation.NonNull;

import com.bonait.bnframework.business.ConfigData;
import com.bonait.bnframework.common.constant.ConfigName;
import com.bonait.bnframework.common.constant.DataBus;
import com.bonait.bnframework.common.helper.I.IThread;
import com.bonait.bnframework.common.helper.MessageLog;
import com.bonait.bnframework.common.helper.ThreadManager;
import com.bonait.bnframework.common.modbus.ModbusTcpServer;
import com.bonait.bnframework.common.utils.NetworkUtils;
import com.google.android.material.bottomnavigation.BottomNavigationView;
import androidx.viewpager.widget.ViewPager;

import android.util.Log;
import android.view.KeyEvent;
import android.view.MenuItem;

import androidx.annotation.NonNull;
import androidx.viewpager.widget.ViewPager;

import com.bonait.bnframework.HBL.Thread.ThreadManager;
import com.bonait.bnframework.R;
import com.bonait.bnframework.Service.ModbusHelper;
import com.bonait.bnframework.ViewModel.Adapter.FragmentAdapter;
import com.bonait.bnframework.ViewModel.FragmentViewModel.Home2Fragment;
import com.bonait.bnframework.ViewModel.FragmentViewModel.HomeDeviceFragment;
import com.bonait.bnframework.ViewModel.FragmentViewModel.MyFragment;
import com.bonait.bnframework.business.ConfigData;
import com.bonait.bnframework.common.base.BaseActivity;
import com.bonait.bnframework.common.constant.MessageName;
import com.bonait.bnframework.common.message.MessageLooper;
import com.bonait.bnframework.common.message.MessageManager;
import com.bonait.bnframework.manager.ActivityLifecycleManager;
import com.bonait.bnframework.common.base.BaseActivity;
import com.bonait.bnframework.common.utils.NetworkUtils;
import com.bonait.bnframework.common.utils.ToastUtils;
import com.bonait.bnframework.modules.home.fragment.Home1Fragment;
import com.bonait.bnframework.modules.home.fragment.Home2Fragment;
import com.bonait.bnframework.modules.home.adapter.FragmentAdapter;
import com.bonait.bnframework.modules.mine.fragment.MyFragment;
import com.bonait.bnframework.manager.ActivityLifecycleManager;
import com.google.android.material.bottomnavigation.BottomNavigationView;
import com.lzy.okgo.OkGo;
import com.qmuiteam.qmui.widget.QMUIViewPager;

@@ -63,6 +57,8 @@ public class BottomNavigation2Activity extends BaseActivity {
@Override
protected void onDestroy() {
ConfigData.getInstance().ColsePLC();
MessageManager.getInstance().unRegisterMessageReceiver(this);
ThreadManager.get().Stop("Modbus变量状态");
//AliyunIOTManager.getInstance().CloseDev();
super.onDestroy();
}
@@ -73,18 +69,34 @@ public class BottomNavigation2Activity extends BaseActivity {
private void initFragment() {
FragmentAdapter fragmentAdapter = new FragmentAdapter(getSupportFragmentManager());
fragmentAdapter.addFragment(new Home2Fragment());
fragmentAdapter.addFragment(new Home1Fragment());
// fragmentAdapter.addFragment(new Home1Fragment());
fragmentAdapter.addFragment(new HomeDeviceFragment());
fragmentAdapter.addFragment(new MyFragment());
viewPager.setAdapter(fragmentAdapter);

MessageManager.getInstance().registerMessageReceiver(this, MessageName.SelectZY, new MessageLooper.OnMessageListener() {
@Override
public void onMessage(Object msg) {
if (msg != null) {
viewPager.setCurrentItem(1);
int index = (int) msg;
viewPager.setCurrentItem(index);
}
}
});
viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
@Override
public void onPageScrolled(int i, float v, int i1) {

}

@Override
public void onPageSelected(int i) {
}

@Override
public void onPageScrollStateChanged(int i) {

}
});
}

//-------------------------配置viewPager与fragment关联----------------------------//
@@ -161,64 +173,20 @@ public class BottomNavigation2Activity extends BaseActivity {
/**
* 初始化
*/
public void Init()
{
public void Init() {
//1.同步时间
NetworkUtils.SynchronizationTime();
//主持
ConfigData.getInstance().GetOrganize(this);
//判断连接环境
ConfigData.getInstance().ToggleEnvironment();
//2.初始化PLC
ReconnectModbus();
//初始化modbus
// if(!ModbusHelper.get().getConnected()){
ModbusHelper.get().RtuInit("/dev/ttyCOM0",9600);
// }
//初始化阿里云连接
//AliyunIOTManager.getInstance().OpenDev(this);
}

/**
* 重新连接plc
*/
public void ReconnectModbus()
{
try {

ThreadManager.Get().StartLong("PLC断线重连线程", true, new IThread() {
@Override
public void Run() throws InterruptedException {
try {
if(ConfigName.getInstance().PlcIsConnect)
{
//ping 不通
boolean status = ModbusTcpServer.ping2(ConfigName.getInstance().Address,1,1);
if(!status) //ping 不通 连接
{
MessageLog.ShowInfo("PLC状态断开,尝试连接...");
ConfigName.getInstance().PlcIsConnect=false;
}
}else
{
boolean status = ModbusTcpServer.ping2(ConfigName.getInstance().Address,1,1);
if(status)
{
MessageLog.ShowInfo("设备 " + ConfigName.getInstance().Address + " PLC通讯正常,准备连接!");
ModbusTcpServer.ConnectPLC();
}else
{
MessageLog.ShowInfo("PLC状态断开,尝试连接...");
ConfigName.getInstance().PlcIsConnect=false;
}
}
Thread.sleep(10000);
} catch (Exception e) {
Log.i("PLC", "PLC重连接失败!"+e.getMessage());
}
}
@Override
public void RunComplete() throws InterruptedException {
}
});
}catch (Exception e) {
MessageLog.ShowInfo("重新连接Modbus异常," +e.getMessage());
}
}

}

+ 634
- 0
app/src/main/java/com/bonait/bnframework/ViewModel/ActivityViewModel/BottomNavigationNewActivity.java Ver fichero

@@ -0,0 +1,634 @@
package com.bonait.bnframework.ViewModel.ActivityViewModel;

import android.app.Activity;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.viewpager.widget.ViewPager;

import com.apkfuns.logutils.LogUtils;
import com.bonait.bnframework.HBL.Logs.MessageLog;
import com.bonait.bnframework.HBL.Thread.IThread;
import com.bonait.bnframework.HBL.Thread.ThreadManager;
import com.bonait.bnframework.R;
import com.bonait.bnframework.Service.ModbusHelper;
import com.bonait.bnframework.ViewModel.Adapter.FragmentAdapter;
import com.bonait.bnframework.ViewModel.FragmentViewModel.Home4Fragment;
import com.bonait.bnframework.ViewModel.FragmentViewModel.HomeDeviceFragment;
import com.bonait.bnframework.ViewModel.FragmentViewModel.HomeFragmentPR;
import com.bonait.bnframework.business.ConfigData;
import com.bonait.bnframework.business.ExecuteTheRecipe;
import com.bonait.bnframework.common.base.BaseActivity;
import com.bonait.bnframework.common.constant.ConfigName;
import com.bonait.bnframework.common.constant.MessageName;
import com.bonait.bnframework.common.db.QueryDB;
import com.bonait.bnframework.common.db.mode.BPA_GOODSRECIPE;
import com.bonait.bnframework.common.db.mode.BPA_GOODS_OLD;
import com.bonait.bnframework.common.helper.CountDownTimerExt;
import com.bonait.bnframework.common.helper.I.MyClickListener;
import com.bonait.bnframework.common.message.MessageLooper;
import com.bonait.bnframework.common.message.MessageManager;
import com.bonait.bnframework.common.utils.NetworkUtils;
import com.bonait.bnframework.common.utils.ToastUtils;
import com.bonait.bnframework.common.view.BottomNavigationBar;
import com.bonait.bnframework.manager.ActivityLifecycleManager;
import com.lzy.okgo.OkGo;
import com.qmuiteam.qmui.widget.QMUIViewPager;

import java.util.ArrayList;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class BottomNavigationNewActivity extends BaseActivity {

//region 变量
@BindView(R.id.navigation)
BottomNavigationBar bottomNavigationView;

@BindView(R.id.viewpager)
QMUIViewPager viewPager;

@BindView(R.id.cooking)
CookingNewActivity cooking;

@BindView(R.id.penrenzhong)
LinearLayout penrenzhong;

@BindView(R.id.penrenzhongtext)
TextView penrenzhongtext;
//endregion

//region 界面私立
public Activity activity;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_bottom_navigation_new);
ButterKnife.bind(this);
View decorView = getWindow().getDecorView();
int uiOptions = View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
| View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY
| View.SYSTEM_UI_FLAG_FULLSCREEN;
decorView.setSystemUiVisibility(uiOptions);
activity = this;
Init();
initFragment();
viewPager.addOnPageChangeListener(pageChangeListener);
// 设置viewPager缓存多少个fragment
viewPager.setOffscreenPageLimit(3);
bottomNavigationView.mListener = new MyClickListener() {
@Override
public void clickListener(View v, Object data) {
int index = (int) data;
viewPager.setCurrentItem(index);
}

@Override
public void clickListenerNew(View v, int k, Object data) {

}
};
viewPager.setCurrentItem(1);
}
@Override
protected void onDestroy() {
ExecuteTheRecipe.IsStart = false;
ModbusHelper.get().setCookStatus(false);
// 中断线程
mainTread.interrupt();
ConfigData.getInstance().ColsePLC();
isRelease = true;
myClickListener = null;
MessageManager.getInstance().unRegisterMessageReceiver(this);
ThreadManager.get().Stop("Modbus变量状态");
super.onDestroy();
}

@Override
protected boolean canDragBack() {
return viewPager.getCurrentItem() == 0;
}

//endregion

//region 私有函数

/**
* viewPager里添加fragment
*/
private void initFragment() {
FragmentAdapter fragmentAdapter = new FragmentAdapter(getSupportFragmentManager());
fragmentAdapter.addFragment(new HomeFragmentPR());
fragmentAdapter.addFragment(new Home4Fragment());
// fragmentAdapter.addFragment(new HomeFragmentSBKZ());
fragmentAdapter.addFragment(new HomeDeviceFragment());
viewPager.setAdapter(fragmentAdapter);

MessageManager.getInstance().registerMessageReceiver(this, MessageName.SelectZY, new MessageLooper.OnMessageListener() {
@Override
public void onMessage(Object msg) {
if (msg != null) {
int index = (int) msg;
viewPager.setCurrentItem(index);
cooking.setVisibility(View.GONE);
ShowMakeLoading();
}
}
});

//打开制作界面
MessageManager.getInstance().registerMessageReceiver(this, MessageName.OpenMakeGoodFrom, new MessageLooper.OnMessageListener() {
@Override
public void onMessage(Object msg) {
if (msg != null) {
String id = (String) msg;
goods = QueryDB.GetGoodsId(id);

assert goods != null;
LogUtils.d("registerMessageReceiver OpenMakeGoodFrom goods name= "+goods.name+" maketime="+goods.maketime);
cooking.initData(goods, activity, myClickListener);
cooking.setVisibility(View.VISIBLE);
}
}
});
}

/**
* 配置ViewPager监听器,手指滑动监听
*/
private ViewPager.OnPageChangeListener pageChangeListener = new ViewPager.OnPageChangeListener() {
@Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}

@Override
public void onPageSelected(int position) {
bottomNavigationView.SelectIndexTab(position);
}

@Override
public void onPageScrollStateChanged(int state) {

}
};

private long exitTime = 0;

/**
* 重写返回键,实现双击退出程序效果
*/
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
if (System.currentTimeMillis() - exitTime > 2000) {
ToastUtils.normal("再按一次退出程序");
exitTime = System.currentTimeMillis();
} else {
OkGo.getInstance().cancelAll();
overridePendingTransition(android.R.anim.fade_in, android.R.anim.fade_out);
ActivityLifecycleManager.get().appExit();
}
return true;
}
return super.onKeyDown(keyCode, event);
}

/**
* 点击事件
*
* @param view
*/
@OnClick({R.id.penrenzhong
})
public void onViewClicked(View view) {
switch (view.getId()) {
case R.id.penrenzhong:
if (goods != null) {
cooking.setVisibility(View.VISIBLE);
penrenzhong.setVisibility(View.GONE);
}
break;
}
}
//endregion

//region 公共函数

/**
* 是否显示制作中, 看菜谱 商品制作开始 商品制作结束
*/
public void ShowMakeLoading() {
if (cooking.getVisibility() == View.GONE && ExecuteTheRecipe.IsStart) {
penrenzhong.setVisibility(View.VISIBLE);
} else {
penrenzhong.setVisibility(View.GONE);
}
}

/**
* 初始化
*/
public void Init() {
//1.同步时间
NetworkUtils.SynchronizationTime();
//主持
ConfigData.getInstance().GetOrganize(this);
//判断连接环境
ConfigData.getInstance().ToggleEnvironment();
// //2.初始化PLC
// ReconnectModbus();
//初始化modbus
// if(!ModbusHelper.get().getConnected()){
ModbusHelper.get().RtuInit("/dev/ttyCOM0",9600);
// }
//制作线程
MakeThread();
//初始化阿里云连接
//AliyunIOTManager.getInstance().OpenDev(this);
}

/**
* 重新连接plc
*/
public void ReconnectModbus() {
try {

ThreadManager.get().StartLong("PLC断线重连线程", true, new IThread() {
@Override
public void Run() throws InterruptedException {
// try {
// if (ConfigName.getInstance().PlcIsConnect) {
// //ping 不通
// boolean status = ModbusTcpServer.ping2(ConfigName.getInstance().Address, 1, 1);
// if (!status) //ping 不通 连接
// {
// MessageLog.ShowInfo("PLC状态断开,尝试连接...");
// ConfigName.getInstance().PlcIsConnect = false;
// }
// } else {
// boolean status = ModbusTcpServer.ping2(ConfigName.getInstance().Address, 1, 1);
// if (status) {
// MessageLog.ShowInfo("设备 " + ConfigName.getInstance().Address + " PLC通讯正常,准备连接!");
// ModbusTcpServer.ConnectPLC();
// } else {
// MessageLog.ShowInfo("PLC状态断开,尝试连接...");
// ConfigName.getInstance().PlcIsConnect = false;
// }
// }
// Thread.sleep(10000);
// } catch (Exception e) {
// Log.i("PLC", "PLC重连接失败!" + e.getMessage());
// }
}


});
} catch (Exception e) {
MessageLog.ShowInfo("重新连接Modbus异常," + e.getMessage());
}
}
//endregion

//region 制作
int gongxuIndex = 10000;
ArrayList<BPA_GOODSRECIPE> goodsrecipesL = null;
BPA_GOODSRECIPE MakeCipe = null;
//商品
public BPA_GOODS_OLD goods = null;
private Thread mainTread = new Thread();
private boolean isRelease = false;

/**
* 商品制作线程
*/
private void MakeThread() {
LogUtils.d("MakeThread()");
ExecuteTheRecipe.context = this;
mainTread = new Thread(new Runnable() {
@Override
public void run() {
while (!Thread.currentThread().isInterrupted() && !isRelease) {
try {
if (ExecuteTheRecipe.IsStart && goods != null) {
long startTime= System.currentTimeMillis(); //起始时间
try {
//获取工艺
ArrayList<BPA_GOODSRECIPE> goodsrecipes = QueryDB.GetGoodsSrecipeID(goods.id);
LogUtils.d("制作线程 MakeThread 启动 ==》 菜品配方 goodsrecipes="+goodsrecipes.toString());
goodsrecipesL = goodsrecipes;
gongxuIndex = 1;
int m = 0;
ModbusHelper.get().setCookStatus(true);

for (BPA_GOODSRECIPE item : goodsrecipes) {
if( !ExecuteTheRecipe.IsStart){
ToastUtils.info("客官,当前菜品已停止炒制!!!");
break;
}
MakeCipe = item;
gongxuIndex++;
runOnUiThread(new Runnable() {
@Override
public void run() {
cooking.SetMiaoShu("正在执行:" + item.processms);
}
});
boolean status = ExecuteTheRecipe.Execute(item, goodsrecipes, m);
m++;
}
} catch (Exception ex) {
LogUtils.d("异常信息:" + ex.getMessage());
ToastUtils.error("异常信息:" + ex.getMessage());
} finally {
ConfigName.getInstance().IsOpenHuoLi = false;
ModbusHelper.get().reset();
gongxuIndex = 10000;
MakeCipe = null;
goodsrecipesL = null;
ExecuteTheRecipe.IsStart = false;

long endTime = System.currentTimeMillis(); //结束时间
int time=(int) ((endTime-startTime)/1000);
LogUtils.d("运行时长 "+String.format("方法使用时间 %d s",time));

if (!ExecuteTheRecipe.IsForcedEnd){
QueryDB.UpdateGoodsMakeTime(goods.id,time);
goods.maketime = time;
}

ExecuteTheRecipe.all_list=new ArrayList<>();
runOnUiThread(new Runnable() {
@Override
public void run() {
onRecordStop();
if (ExecuteTheRecipe.IsForcedEnd)//强制结束
{
ToastUtils.info("客官,当前菜品已强制结束!!!");
//初始化
// ExecuteTheRecipe.BottomClick("初始化");
}
}
});
}
}
Thread.sleep(1000);
} catch (InterruptedException e) {
LogUtils.d("异常信息:" + e.getMessage());
if(!isRelease){
ToastUtils.info("异常信息:" + e.getMessage());
}
}
}
ModbusHelper.get().setCookStatus(false);
}
});
mainTread.start();

// new Thread(new Runnable() {
// @Override
// public void run() {
// while (true) {
// try {
//
// if (ExecuteTheRecipe.IsStart && goods != null && gongxuIndex != 10000 && goodsrecipesL != null && MakeCipe != null) {
// try {
// if (ConfigName.getInstance().versionSelectionEnum.equals("大炒自动投料版本") || ConfigName.getInstance().versionSelectionEnum.equals("小炒版本")) {
// //获取工艺
// int k = 1;
// ArrayList<BPA_GOODSRECIPE> goodsrecipes = goodsrecipesL;
// BPA_GOODSRECIPE recipe = null;
// for (BPA_GOODSRECIPE item : goodsrecipes) {
// k++;
// if (k > gongxuIndex) {
// if (item.processname.contains("主料") && !MakeCipe.processname.equals("主料") && recipe == null) {
// recipe = item;
// }
// }
// }
//
// if (recipe != null) {
// HashMap<String, String> formulation = new HashMap<>();
// String text = recipe.processvalue;
// //region 获取仓号和值
// List<String> data = new ArrayList<>();
// if (text.contains("|")) {
// String[] res = text.split("[|]");
// for (int i = 0; i < res.length; i++) {
// data.add(res[i]);
// }
// } else {
// data.add(text);
// }
// for (String item : data) {
// if (!item.isEmpty() && item.contains(",")) {
// String[] wl = item.split("[,]");
// if (wl != null && wl.length == 2) {
// String name = wl[0];
// String val = wl[1];
// formulation.put(name, val);
// }
// }
// }
// //endregion
// boolean ishand = true;
//
// //region 判断是否手动
// if (ConfigName.getInstance().versionSelectionEnum.equals("大炒版本")) {
// ishand = true;
// } else {
// for (HashMap.Entry<String, String> entry : formulation.entrySet()) {
// String key = entry.getKey();
// String value = entry.getValue();
// if (key.contains("投料动作")) {
// if (value.contains("手动投料")) {
// ishand = true;
// } else {
// ishand = false;
// }
// }
// }
// }
// //endregion
//
// if (!ishand) {
// String writeValue = "1号位";
// for (HashMap.Entry<String, String> entry : formulation.entrySet()) {
// String key = entry.getKey();
// String value = entry.getValue();
// if (key.contains("主料位置")) {
// writeValue = value;
// }
// }
// ExecuteTheRecipe.BottomClick("平移-去" + writeValue);
// Log.d("移动去", writeValue);
// } else {
// ExecuteTheRecipe.BottomClick("平移-去1号位");
// Log.d("移动去", "1号位");
// }
// } else {
// if (!MakeCipe.processname.equals("主料")) {
// ExecuteTheRecipe.BottomClick("平移-去1号位");
// Log.d("移动去", "1号位");
// }
// }
// }
//
// } catch (Exception ex) {
// ToastUtils.error("异常信息:" + ex.getMessage());
// }
// }
// Thread.sleep(3000);
// } catch (InterruptedException e) {
// ToastUtils.info("异常信息:" + e.getMessage());
// }
// }
// }
// }).start();
}

/**
* 点击事件
*/
public MyClickListener myClickListener = new MyClickListener() {
@Override
public void clickListener(View v, Object data) {
boolean Status = (boolean) data;
switch (v.getId()) {
case R.id.start_goodmake://启动按钮
ExecuteTheRecipe.IsPause = false;
// ExecuteTheRecipe.WritePLC("暂停开关",false,null);
if (Status) {
onRecordStart();
}
// else {
// onRecordStop();
// }
break;
case R.id.zanting_goodmake://暂停按钮
ExecuteTheRecipe.IsPause = Status;
// ExecuteTheRecipe.WritePLC("暂停开关",Status,null);
if (Status) {
onRecordPause();
} else {
onRecordPauseStart();
}
break;
}
}

@Override
public void clickListenerNew(View v, int k, Object data) {

}
};

private CountDownTimerExt countDownTimer = null;//计时器

/**
* 启动
*/
public void onRecordStart() {
if (goods != null) {
cooking.SetReset();
cooking.SetZanTing(true);
int time = goods.maketime;
SetProcess(time, 0);
if (countDownTimer == null) {
countDownTimer = new CountDownTimerExt(time * 1000, 1000) {
@Override
public void onTimerTick(long value) {
int overtime = (int) ((value) / 1000);//剩余时间
SetProcess(time, time - overtime);
}

@Override
public void onTimerFinish() {
SetProcess(time, time);
}
};
}
countDownTimer.start();
ExecuteTheRecipe.IsStart = true;
}
}

/**
* 停止
*/
public void onRecordStop() {
if (goods != null) {
cooking.SetReset();
cooking.SetRest1();
SetProcess(goods.maketime, 0);
LogUtils.d("onRecordStop goods.maketime="+goods.maketime);

if (countDownTimer != null) {
countDownTimer.stop();
countDownTimer = null;
}
ExecuteTheRecipe.IsStart = false;
}
}

/**
* 暂停
*/
public void onRecordPause() {
countDownTimer.pause();
}

/**
* 继续
*/
public void onRecordPauseStart() {
countDownTimer.resume();
}

/**
* 设置进度条
*
* @param
*/
public void SetProcess(int alltime, int usertime) {
try {
penrenzhongtext.setText(formatTime((alltime - usertime)));
cooking.SetProcess(alltime, usertime);
} catch (Exception ex) {
LogUtils.d("异常信息:" + ex.getMessage());
ToastUtils.error("异常信息:" + ex.getMessage());
}
}

/**
* 将毫秒转化为 分钟:秒 的格式 100* 1000
*
* @param millisecond 毫秒
* @return
*/
public String formatTime(long millisecond) {
int minute;//分钟
int second;//秒数
minute = (int) ((millisecond / 1) / 60);
second = (int) ((millisecond / 1) % 60);
if (minute < 10) {
if (second < 10) {
return "0" + minute + " : " + "0" + second;
} else {
return "0" + minute + " : " + second;
}
} else {
if (second < 10) {
return minute + " : " + "0" + second;
} else {
return minute + " : " + second;
}
}
}
//endregion
}

+ 167
- 0
app/src/main/java/com/bonait/bnframework/ViewModel/ActivityViewModel/BunkerSetupActivity.java Ver fichero

@@ -0,0 +1,167 @@
package com.bonait.bnframework.ViewModel.ActivityViewModel;

import androidx.core.content.ContextCompat;

import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.view.View;

import com.bonait.bnframework.R;
import com.bonait.bnframework.business.ExecuteTheRecipe;
import com.bonait.bnframework.common.base.BaseActivity;
import com.bonait.bnframework.common.constant.DataBus;
import com.bonait.bnframework.common.db.QueryDB;
import com.bonait.bnframework.common.db.res.lcMode;
import com.bonait.bnframework.common.helper.I.MyClickListener;
import com.bonait.bnframework.common.utils.ToastUtils;
import com.bonait.bnframework.ViewModel.CustomView.add_silos_message;
import com.bonait.bnframework.ViewModel.CustomView.imagebuttom;
import com.bonait.bnframework.ViewModel.CustomView.jingdutiao1;
import com.qmuiteam.qmui.widget.QMUITopBarLayout;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class BunkerSetupActivity extends BaseActivity {

//region 变量
@BindView(R.id.topbar)
QMUITopBarLayout mTopBar;

@BindView(R.id.silos1)
jingdutiao1 silos1;

@BindView(R.id.silos2)
jingdutiao1 silos2;

@BindView(R.id.silos3)
jingdutiao1 silos3;

@BindView(R.id.quanchangqingxi)
imagebuttom quanchangqingxi;

@BindView(R.id.silos_control)
add_silos_message silos_control;
public Context context;
public Activity activity=null;
//endregion

//region 界面实例
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_bunkersetup);
ButterKnife.bind(this);
context = this;
activity=this;
initTopBar();
InitData();
}
//endregion

//region 私有方法

/**
* 初始化顶部弹框
*/
private void initTopBar() {
mTopBar.setBackgroundColor(ContextCompat.getColor(context, R.color.topbj1));
mTopBar.setTitle("料仓设置");
mTopBar.addLeftImageButton(R.mipmap.fanhui, R.id.topbar).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
ExecuteTheRecipe.WritePLC("料仓1手动开关", false, null);
ExecuteTheRecipe.WritePLC("料仓2手动开关", false, null);
ExecuteTheRecipe.WritePLC("料仓3手动开关", false, null);
finish();
}
});

/**
* 全仓清洗
*/
quanchangqingxi.mListener = new MyClickListener() {
@Override
public void clickListener(View v, Object data) {
boolean status = (boolean) data;
ExecuteTheRecipe.WritePLC("料仓1手动开关", status, null);
ExecuteTheRecipe.WritePLC("料仓2手动开关", status, null);
ExecuteTheRecipe.WritePLC("料仓3手动开关", status, null);
}

@Override
public void clickListenerNew(View v, int k, Object data) {

}
};

//关闭
silos_control.mListener = new MyClickListener() {
@Override
public void clickListener(View v, Object data) {
InitData();
silos_control.setVisibility(View.GONE);
}

@Override
public void clickListenerNew(View v, int k, Object data) {

}
};
}

/**
* 初始化数据
*/
public void InitData() {
DataBus.getInstance().GetLc();
for (lcMode item : DataBus.getInstance().lcModes) {
if (item.num == 1) {
silos1.SetValue(item, myClickListener);
} else if (item.num == 2) {
silos2.SetValue(item, myClickListener);
} else if (item.num == 3) {
silos3.SetValue(item, myClickListener);
}
}
}

/**
* 内部点击事件
*/
public MyClickListener myClickListener = new MyClickListener() {
@Override
public void clickListener(View v, Object data) {
if (data != null) {
lcMode mode = (lcMode) data;
silos_control.SetData(mode, activity);
silos_control.setVisibility(View.VISIBLE);
}
}
@Override
public void clickListenerNew(View v, int k, Object data) {

}
};

/**
* 点击事件
*
* @param view
*/
@OnClick({R.id.quanliaobuchong})
public void onViewClicked(View view) {
switch (view.getId()) {
case R.id.quanliaobuchong:
for (lcMode item : DataBus.getInstance().lcModes) {
QueryDB.UpdateYL(item.id, item.siloszl);
}
InitData();
ToastUtils.info("补充完成!");
break;
}
}
//endregion
}

+ 411
- 0
app/src/main/java/com/bonait/bnframework/ViewModel/ActivityViewModel/CookingActivity.java Ver fichero

@@ -0,0 +1,411 @@
package com.bonait.bnframework.ViewModel.ActivityViewModel;

import androidx.annotation.Nullable;
import androidx.core.content.ContextCompat;

import android.app.Activity;
import android.content.Context;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.apkfuns.logutils.LogUtils;
import com.bonait.bnframework.HBL.Interface.IRunT;
import com.bonait.bnframework.R;
import com.bonait.bnframework.business.ExecuteTheRecipe;
import com.bonait.bnframework.common.constant.ConfigName;
import com.bonait.bnframework.common.constant.DataBus;
import com.bonait.bnframework.common.constant.MessageName;
import com.bonait.bnframework.common.db.mode.BPA_GOODS_OLD;
import com.bonait.bnframework.common.helper.I.MyClickListener;
import com.bonait.bnframework.common.message.MessageManager;
import com.bonait.bnframework.common.utils.ToastUtils;
import com.bonait.bnframework.ViewModel.CustomView.imagebuttom;
import com.bonait.bnframework.ViewModel.CustomView.imagebuttom3;
import com.bonait.bnframework.ViewModel.CustomView.jingdutiao;
import com.bonait.bnframework.ViewModel.CustomView.newhuoli_control;
import com.qmuiteam.qmui.widget.QMUITopBarLayout;

import java.util.concurrent.ConcurrentHashMap;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class CookingActivity extends LinearLayout {

//region 变量
@BindView(R.id.device_image)
ImageView device_image;

@BindView(R.id.touliao_k)
LinearLayout touliao_k;

@BindView(R.id.touliao_m)
LinearLayout touliao_m;

@BindView(R.id.goodname)
TextView goodname;

@BindView(R.id.chaoguo_wendu)
TextView chaoguo_wendu;

@BindView(R.id.gongxumiaoshu)
TextView gongxumiaoshu;//工序描述

@BindView(R.id.start_goodmake)
imagebuttom start_goodmake;//开始

@BindView(R.id.zanting_goodmake)
public imagebuttom zanting_goodmake;//暂停
@BindView(R.id.runtime)
TextView runtime;//计时器 倒计时

@BindView(R.id.t_jindu)
jingdutiao t_jindu;//计时器

@BindView(R.id.topbar)
QMUITopBarLayout mTopBar;


@BindView(R.id.huoli)
newhuoli_control huoli;

@BindView(R.id.fanchaoshudu)
imagebuttom3 fanchaoshudu;


@BindView(R.id.guokoucaoxiang)
imagebuttom3 guokoucaoxiang;

@BindView(R.id.chushui)
imagebuttom3 chushui;

@BindView(R.id.touliao1)
imagebuttom3 touliao1;

@BindView(R.id.touliao2)
imagebuttom3 touliao2;

@BindView(R.id.touliao3)
imagebuttom3 touliao3;

@BindView(R.id.touliao4)
imagebuttom3 touliao4;

@BindView(R.id.yeliao1)
imagebuttom3 yeliao1;
@BindView(R.id.yeliao2)
imagebuttom3 yeliao2;
@BindView(R.id.yeliao3)
imagebuttom3 yeliao3;

private Context contextMian;
private View root;

public Activity activity = null;
//endregion

//region 界面实例
public CookingActivity(Context context, @Nullable AttributeSet attrs) {
super(context, attrs);
contextMian = context;
root = LayoutInflater.from(context).inflate(R.layout.activity_cooking, this);
ButterKnife.bind(this, root);
initTopBar();

SxUIThread();
}
//endregion

//region 公共方法

/**
* 初始化数据
*/
public void initData(BPA_GOODS_OLD goods, Activity ac, MyClickListener listener) {
//根据商品id查询
activity = ac;

yeliao1.setTag(ConfigName.getInstance().SilosDisplayMaterial.get(1)+"");
yeliao1.Init();

yeliao2.setTag(ConfigName.getInstance().SilosDisplayMaterial.get(2)+"");
yeliao2.Init();

yeliao3.setTag(ConfigName.getInstance().SilosDisplayMaterial.get(3)+"");
yeliao3.Init();

ConcurrentHashMap<Integer,String> resultData= DataBus.getInstance().GetMainDisplayText(goods.id);
touliao1.setTag(resultData.get(1)+"-按钮");
touliao1.Init();

touliao2.setTag(resultData.get(2)+"-按钮");
touliao2.Init();

touliao3.setTag(resultData.get(3)+"-按钮");
touliao3.Init();

touliao4.setTag(resultData.get(4)+"-按钮");
touliao4.Init();

goodname.setText(goods.name + "");
start_goodmake.mListener = listener;
zanting_goodmake.mListener = listener;
SetReset();
SetRest1();
SetProcess(goods.maketime, 0);
SetMiaoShu("等待开始...");
runtime.setText(formatTime(goods.maketime));

if (ConfigName.getInstance().versionSelectionEnum.equals("大炒版本")) {
touliao_k.setVisibility(View.GONE);
touliao_m.setVisibility(View.GONE);
device_image.setImageResource(R.mipmap.device00);
}else
{
touliao_k.setVisibility(View.VISIBLE);
touliao_m.setVisibility(View.VISIBLE);
device_image.setImageResource(R.mipmap.device1);
}
}

/**
* 设置描述
*
* @param text
*/
public void SetMiaoShu(String text) {
gongxumiaoshu.setText(text + "");
}

/**
* 设置进度条
*
* @param
*/
public void SetProcess(int alltime, int usertime) {
try {
t_jindu.SetValue((usertime * 100) / alltime);
runtime.setText(formatTime((alltime - usertime)));
} catch (Exception ex) {
LogUtils.d("异常信息:" + ex.getMessage());
ToastUtils.error("异常信息:" + ex.getMessage());
}
}

/**
* 复位
*/
public void SetReset() {
SetMiaoShu("等待开始...");
zanting_goodmake.SetStatus(false);
zanting_goodmake.setVisibility(View.GONE);
}

/**
* 复位
*/
public void SetZanTing(boolean data) {
zanting_goodmake.setVisibility(data ? View.VISIBLE : View.GONE);
}

public void SetRest1() {
start_goodmake.SetStatus(false);
if(flicker_buttom!=null)
{
flicker_buttom.setVisibility(View.VISIBLE);
flicker_buttom.SetStatusKK(false);
flicker_buttom=null;
}
huoli.SetLevel(0);
}
//endregion

//region 私有方法

/**
* 将毫秒转化为 分钟:秒 的格式 100* 1000
*
* @param millisecond 毫秒
* @return
*/
public String formatTime(long millisecond) {
int minute;//分钟
int second;//秒数
minute = (int) ((millisecond / 1) / 60);
second = (int) ((millisecond / 1) % 60);
if (minute < 10) {
if (second < 10) {
return "0" + minute + " : " + "0" + second;
} else {
return "0" + minute + " : " + second;
}
} else {
if (second < 10) {
return minute + " : " + "0" + second;
} else {
return minute + " : " + second;
}
}
}

/**
* 初始化顶部弹框
*/
private void initTopBar() {
mTopBar.setBackgroundColor(ContextCompat.getColor(getContext(), R.color.topbj1));
mTopBar.setTitle("菜谱烹饪");
mTopBar.addLeftImageButton(R.mipmap.fanhui, R.id.topbar).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if (ExecuteTheRecipe.IsStart) {
ToastUtils.warning("请等待制作完成后退出...");
return;
}
setVisibility(View.GONE);
}
});
}

/**
* 点击事件
*
* @param view
*/
@OnClick({R.id.kancaipu})
public void onViewClicked(View view) {
switch (view.getId()) {
case R.id.kancaipu://看菜谱
MessageManager.getInstance().sendMessage(MessageName.SelectZY, 0);
break;
}
}

/**
* 闪烁buttom
*/
public imagebuttom3 flicker_buttom=null;
/**
* 刷新UI界面
*/
public void SxUIThread() {
new Thread(new Runnable() {
@Override
public void run() {

while (true) {
try {
if (activity != null && getVisibility() == View.VISIBLE) {
activity.runOnUiThread(new Runnable() {
@Override
public void run() {
Object val_wd = ExecuteTheRecipe.getListingValue("当前锅底温度");
if (val_wd != null) {
chaoguo_wendu.setText(val_wd + "°C");
} else {
chaoguo_wendu.setText("??°C");
}

//闪烁
if (flicker_buttom != null) {
flicker_buttom.setVisibility(flicker_buttom.getVisibility() == View.VISIBLE ? View.INVISIBLE : View.VISIBLE);
}
}
});
}
Thread.sleep(1000);
} catch (InterruptedException e) {
LogUtils.d("异常信息:" + e.getMessage());
ToastUtils.info("异常信息:" + e.getMessage());
}
}
}
}).start();

ExecuteTheRecipe.ExecuteCurrentOperation=new IRunT() {
@Override
public void Run(Object o) {
String data=(String)o;
if (activity != null && getVisibility() == View.VISIBLE) {
activity.runOnUiThread(new Runnable() {
@Override
public void run() {
if(data.contains("|"))
{
String[] K= data.split("[|]");
if (K.length>=2)
{
String name=K[0];
String val=K[1];
if(flicker_buttom!=null)
{
flicker_buttom.setVisibility(View.VISIBLE);
flicker_buttom.SetStatusKK(false);
}
flicker_buttom=null;
switch (name) {
case "搅拌":
flicker_buttom=fanchaoshudu;
flicker_buttom.SetStatusKK(true);
break;
case "位置":
flicker_buttom=guokoucaoxiang;
flicker_buttom.SetStatusKK(true);
break;
case "加热":
huoli.SetLevel(Integer.parseInt(val));
break;
case "主料":
if(val.equals("1号位"))
{
flicker_buttom=touliao1;
}else if(val.equals("2号位"))
{
flicker_buttom=touliao2;
}else if(val.equals("3号位"))
{
flicker_buttom=touliao3;
}else if(val.equals("4号位"))
{
flicker_buttom=touliao4;
}
flicker_buttom.SetStatusKK(true);
break;
case "加水":
flicker_buttom=chushui;
flicker_buttom.SetStatusKK(true);
break;
case "液体料":
if(val.equals("1"))
{
flicker_buttom=yeliao1;
flicker_buttom.SetStatusKK(true);
}else if(val.equals("2"))
{
flicker_buttom=yeliao2;
flicker_buttom.SetStatusKK(true);
}else if(val.equals("3"))
{
flicker_buttom=yeliao3;
flicker_buttom.SetStatusKK(true);
}
break;
}
}
}
}
});
}
}
};
}
//endregion

//region 外部调用
//endregion

}

+ 417
- 0
app/src/main/java/com/bonait/bnframework/ViewModel/ActivityViewModel/CookingNewActivity.java Ver fichero

@@ -0,0 +1,417 @@
package com.bonait.bnframework.ViewModel.ActivityViewModel;

import android.app.Activity;
import android.content.Context;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.core.content.ContextCompat;

import com.apkfuns.logutils.LogUtils;
import com.bonait.bnframework.HBL.Interface.IRunT;
import com.bonait.bnframework.R;
import com.bonait.bnframework.ViewModel.CustomView.imagebuttom;
import com.bonait.bnframework.ViewModel.CustomView.imagebuttom3;
import com.bonait.bnframework.ViewModel.CustomView.jingdutiao;
import com.bonait.bnframework.business.ExecuteTheRecipe;
import com.bonait.bnframework.common.constant.MessageName;
import com.bonait.bnframework.common.db.mode.BPA_GOODS_OLD;
import com.bonait.bnframework.common.helper.I.MyClickListener;
import com.bonait.bnframework.common.message.MessageManager;
import com.bonait.bnframework.common.utils.ToastUtils;
import com.qmuiteam.qmui.widget.QMUITopBarLayout;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class CookingNewActivity extends LinearLayout {

//region 变量
@BindView(R.id.device_image)
ImageView device_image;

// @BindView(R.id.touliao_k)
// LinearLayout touliao_k;
//
// @BindView(R.id.touliao_m)
// LinearLayout touliao_m;

@BindView(R.id.goodname)
TextView goodname;
//
// @BindView(R.id.chaoguo_wendu)
// TextView chaoguo_wendu;

@BindView(R.id.gongxumiaoshu)
TextView gongxumiaoshu;//工序描述

@BindView(R.id.start_goodmake)
imagebuttom start_goodmake;//开始

@BindView(R.id.zanting_goodmake)
public imagebuttom zanting_goodmake;//暂停
@BindView(R.id.runtime)
TextView runtime;//计时器 倒计时

@BindView(R.id.t_jindu)
jingdutiao t_jindu;//计时器

@BindView(R.id.topbar)
QMUITopBarLayout mTopBar;
@BindView(R.id.test1)
TextView text1;



// @BindView(R.id.huoli)
// newhuoli_control huoli;
//
// @BindView(R.id.fanchaoshudu)
// imagebuttom3 fanchaoshudu;
//
//
// @BindView(R.id.guokoucaoxiang)
// imagebuttom3 guokoucaoxiang;
//
// @BindView(R.id.chushui)
// imagebuttom3 chushui;
//
// @BindView(R.id.touliao1)
// imagebuttom3 touliao1;
//
// @BindView(R.id.touliao2)
// imagebuttom3 touliao2;
//
// @BindView(R.id.touliao3)
// imagebuttom3 touliao3;
//
// @BindView(R.id.touliao4)
// imagebuttom3 touliao4;
//
// @BindView(R.id.yeliao1)
// imagebuttom3 yeliao1;
// @BindView(R.id.yeliao2)
// imagebuttom3 yeliao2;
// @BindView(R.id.yeliao3)
// imagebuttom3 yeliao3;

private Context contextMian;
private View root;
private StringBuffer stringBuffer1 = new StringBuffer();

public Activity activity = null;
//endregion

//region 界面实例
public CookingNewActivity(Context context, @Nullable AttributeSet attrs) {
super(context, attrs);
contextMian = context;
root = LayoutInflater.from(context).inflate(R.layout.activity_cooking_new, this);
ButterKnife.bind(this, root);
initTopBar();

SxUIThread();
}
//endregion

//region 公共方法

/**
* 初始化数据
*/
public void initData(BPA_GOODS_OLD goods, Activity ac, MyClickListener listener) {
//根据商品id查询
activity = ac;

// yeliao1.setTag(ConfigName.getInstance().SilosDisplayMaterial.get(1)+"");
// yeliao1.Init();
//
// yeliao2.setTag(ConfigName.getInstance().SilosDisplayMaterial.get(2)+"");
// yeliao2.Init();
//
// yeliao3.setTag(ConfigName.getInstance().SilosDisplayMaterial.get(3)+"");
// yeliao3.Init();
//
// ConcurrentHashMap<Integer,String> resultData= DataBus.getInstance().GetMainDisplayText(goods.id);
// touliao1.setTag(resultData.get(1)+"-按钮");
// touliao1.Init();
//
// touliao2.setTag(resultData.get(2)+"-按钮");
// touliao2.Init();
//
// touliao3.setTag(resultData.get(3)+"-按钮");
// touliao3.Init();
//
// touliao4.setTag(resultData.get(4)+"-按钮");
// touliao4.Init();

goodname.setText(goods.name + "");
start_goodmake.mListener = listener;
// zanting_goodmake.mListener = listener;
SetReset();
SetRest1();
SetProcess(goods.maketime, 0);
SetMiaoShu("等待开始...");
LogUtils.d("制作时长goods.maketime="+goods.maketime);
runtime.setText(formatTime(goods.maketime));

// if (ConfigName.getInstance().versionSelectionEnum.equals("大炒版本")) {
// touliao_k.setVisibility(View.GONE);
// touliao_m.setVisibility(View.GONE);
// device_image.setImageResource(R.mipmap.device00);
// }else
// {
// touliao_k.setVisibility(View.VISIBLE);
// touliao_m.setVisibility(View.VISIBLE);
// device_image.setImageResource(R.mipmap.device1);
// }
}

/**
* 设置描述
*
* @param text
*/
public void SetMiaoShu(String text) {
gongxumiaoshu.setText(text + "");
stringBuffer1.append(" \n工序:"+text);
text1.setText(stringBuffer1+"");
}

/**
* 设置进度条
*
* @param
*/
public void SetProcess(int alltime, int usertime) {
try {
if(alltime!=0){
t_jindu.SetValue((usertime * 100) / alltime);
}
runtime.setText(formatTime((alltime - usertime)));
} catch (Exception ex) {
LogUtils.d("异常信息:" + ex.getMessage());
ToastUtils.error("异常信息:" + ex.getMessage());
}
}

/**
* 复位
*/
public void SetReset() {
SetMiaoShu("等待开始...");
stringBuffer1 = new StringBuffer();
// zanting_goodmake.SetStatus(false);
// zanting_goodmake.setVisibility(View.GONE);
}

/**
* 复位
*/
public void SetZanTing(boolean data) {
// zanting_goodmake.setVisibility(data ? View.VISIBLE : View.GONE);
}

public void SetRest1() {
stringBuffer1 = new StringBuffer();
start_goodmake.SetStatus(false);
if(flicker_buttom!=null)
{
flicker_buttom.setVisibility(View.VISIBLE);
flicker_buttom.SetStatusKK(false);
flicker_buttom=null;
}
// huoli.SetLevel(0);
}
//endregion

//region 私有方法

/**
* 将毫秒转化为 分钟:秒 的格式 100* 1000
*
* @param millisecond 毫秒
* @return
*/
public String formatTime(long millisecond) {
int minute;//分钟
int second;//秒数
minute = (int) ((millisecond / 1) / 60);
second = (int) ((millisecond / 1) % 60);
if (minute < 10) {
if (second < 10) {
return "0" + minute + " : " + "0" + second;
} else {
return "0" + minute + " : " + second;
}
} else {
if (second < 10) {
return minute + " : " + "0" + second;
} else {
return minute + " : " + second;
}
}
}

/**
* 初始化顶部弹框
*/
private void initTopBar() {
mTopBar.setBackgroundColor(ContextCompat.getColor(getContext(), R.color.topbj1));
mTopBar.setTitle("菜谱烹饪");
mTopBar.addLeftImageButton(R.mipmap.fanhui, R.id.topbar).setOnClickListener(new OnClickListener() {
@Override
public void onClick(View view) {
if (ExecuteTheRecipe.IsStart) {
ToastUtils.warning("请等待制作完成后退出...");
return;
}
setVisibility(View.GONE);
}
});
}

/**
* 点击事件
*
* @param view
*/
@OnClick({R.id.kancaipu})
public void onViewClicked(View view) {
switch (view.getId()) {
case R.id.kancaipu://看菜谱
MessageManager.getInstance().sendMessage(MessageName.SelectZY, 0);
break;
}
}

/**
* 闪烁buttom
*/
public imagebuttom3 flicker_buttom=null;
/**
* 刷新UI界面
*/
public void SxUIThread() {
new Thread(new Runnable() {
@Override
public void run() {

while (true) {
try {
if (activity != null && getVisibility() == View.VISIBLE) {
activity.runOnUiThread(new Runnable() {
@Override
public void run() {
Object val_wd = ExecuteTheRecipe.getListingValue("当前锅底温度");
if (val_wd != null) {
// chaoguo_wendu.setText(val_wd + "°C");
} else {
// chaoguo_wendu.setText("??°C");
}

//闪烁
if (flicker_buttom != null) {
flicker_buttom.setVisibility(flicker_buttom.getVisibility() == View.VISIBLE ? View.INVISIBLE : View.VISIBLE);
}
}
});
}
Thread.sleep(1000);
} catch (InterruptedException e) {
LogUtils.d("异常信息:" + e.getMessage());
ToastUtils.info("异常信息:" + e.getMessage());
}
}
}
}).start();

ExecuteTheRecipe.ExecuteCurrentOperation=new IRunT() {
@Override
public void Run(Object o) {
String data=(String)o;
if (activity != null && getVisibility() == View.VISIBLE) {
activity.runOnUiThread(new Runnable() {
@Override
public void run() {
if(data.contains("|"))
{
String[] K= data.split("[|]");
if (K.length>=2)
{
String name=K[0];
String val=K[1];
if(flicker_buttom!=null)
{
flicker_buttom.setVisibility(View.VISIBLE);
flicker_buttom.SetStatusKK(false);
}
flicker_buttom=null;
// switch (name) {
// case "搅拌":
// flicker_buttom=fanchaoshudu;
// flicker_buttom.SetStatusKK(true);
// break;
// case "位置":
// flicker_buttom=guokoucaoxiang;
// flicker_buttom.SetStatusKK(true);
// break;
// case "加热":
// huoli.SetLevel(Integer.parseInt(val));
// break;
// case "主料":
// if(val.equals("1号位"))
// {
// flicker_buttom=touliao1;
// }else if(val.equals("2号位"))
// {
// flicker_buttom=touliao2;
// }else if(val.equals("3号位"))
// {
// flicker_buttom=touliao3;
// }else if(val.equals("4号位"))
// {
// flicker_buttom=touliao4;
// }
// flicker_buttom.SetStatusKK(true);
// break;
// case "加水":
// flicker_buttom=chushui;
// flicker_buttom.SetStatusKK(true);
// break;
// case "液体料":
// if(val.equals("1"))
// {
// flicker_buttom=yeliao1;
// flicker_buttom.SetStatusKK(true);
// }else if(val.equals("2"))
// {
// flicker_buttom=yeliao2;
// flicker_buttom.SetStatusKK(true);
// }else if(val.equals("3"))
// {
// flicker_buttom=yeliao3;
// flicker_buttom.SetStatusKK(true);
// }
// break;
// }
}
}
}
});
}
}
};
}
//endregion

//region 外部调用
//endregion

}

+ 609
- 0
app/src/main/java/com/bonait/bnframework/ViewModel/ActivityViewModel/CookingSimulatedActivity.java Ver fichero

@@ -0,0 +1,609 @@
package com.bonait.bnframework.ViewModel.ActivityViewModel;

import static com.bonait.bnframework.MainApplication.getContext;

import androidx.core.content.ContextCompat;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bonait.bnframework.R;
import com.bonait.bnframework.business.ExecuteTheRecipe;
import com.bonait.bnframework.common.base.BaseActivity;
import com.bonait.bnframework.common.constant.ConfigName;
import com.bonait.bnframework.common.constant.DataBus;
import com.bonait.bnframework.common.db.QueryDB;
import com.bonait.bnframework.common.db.mode.BPA_GOODS_OLD;
import com.bonait.bnframework.common.db.mode.BPA_GOODSRECIPE;
import com.bonait.bnframework.common.db.mode.BPA_SILOS;
import com.bonait.bnframework.common.helper.CountDownTimerExt;
import com.bonait.bnframework.common.utils.ToastUtils;
import com.bonait.bnframework.ViewModel.CustomView.imagebuttom3;
import com.bonait.bnframework.ViewModel.CustomView.jingdutiao;
import com.bonait.bnframework.ViewModel.CustomView.newhuoli_control;
import com.qmuiteam.qmui.widget.QMUITopBarLayout;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class CookingSimulatedActivity extends BaseActivity {
//region 变量
@BindView(R.id.device_image)
ImageView device_image;

@BindView(R.id.touliao_k)
LinearLayout touliao_k;

@BindView(R.id.touliao_m)
LinearLayout touliao_m;

@BindView(R.id.goodname)
TextView goodname;

@BindView(R.id.gongxumiaoshu)
TextView gongxumiaoshu;//工序描述

@BindView(R.id.runtime)
TextView runtime;//计时器 倒计时

@BindView(R.id.t_jindu)
jingdutiao t_jindu;//计时器

@BindView(R.id.topbar)
QMUITopBarLayout mTopBar;

@BindView(R.id.huoli)
newhuoli_control huoli;

@BindView(R.id.fanchaoshudu)
imagebuttom3 fanchaoshudu;


@BindView(R.id.guokoucaoxiang)
imagebuttom3 guokoucaoxiang;

@BindView(R.id.chushui)
imagebuttom3 chushui;

@BindView(R.id.touliao1)
imagebuttom3 touliao1;

@BindView(R.id.touliao2)
imagebuttom3 touliao2;

@BindView(R.id.touliao3)
imagebuttom3 touliao3;

@BindView(R.id.touliao4)
imagebuttom3 touliao4;

@BindView(R.id.yeliao1)
imagebuttom3 yeliao1;
@BindView(R.id.yeliao2)
imagebuttom3 yeliao2;
@BindView(R.id.yeliao3)
imagebuttom3 yeliao3;

@BindView(R.id.showbuttomtop)
RelativeLayout showbuttomtop;

public BPA_GOODS_OLD goods = new BPA_GOODS_OLD();
public ArrayList<BPA_GOODSRECIPE> goodsrecipes = new ArrayList<>();
//endregion

//region 界面实例

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_cookingsimulated);
ButterKnife.bind(this);
initTopBar();

Intent intent = getIntent();
String id = intent.getStringExtra("id");
if (!id.isEmpty()) {
goods = QueryDB.GetGoodsId(id);
if (goods != null) {
goodsrecipes = QueryDB.GetGoodsSrecipeID(goods.id);
}
}
initData();
SxUIThread();
}
//endregion

//region 公共方法

/**
* 初始化数据
*/
public void initData() {
if (ConfigName.getInstance().versionSelectionEnum.equals("大炒版本")) {
touliao_k.setVisibility(View.GONE);
touliao_m.setVisibility(View.GONE);
device_image.setImageResource(R.mipmap.device00);
}else
{
touliao_k.setVisibility(View.VISIBLE);
touliao_m.setVisibility(View.VISIBLE);
device_image.setImageResource(R.mipmap.device1);
}

yeliao1.setTag(ConfigName.getInstance().SilosDisplayMaterial.get(1) + "");
yeliao1.Init();

yeliao2.setTag(ConfigName.getInstance().SilosDisplayMaterial.get(2) + "");
yeliao2.Init();

yeliao3.setTag(ConfigName.getInstance().SilosDisplayMaterial.get(3) + "");
yeliao3.Init();

ConcurrentHashMap<Integer, String> resultData = DataBus.getInstance().GetMainDisplayText(goods.id);
touliao1.setTag(resultData.get(1) + "-按钮");
touliao1.Init();

touliao2.setTag(resultData.get(2) + "-按钮");
touliao2.Init();

touliao3.setTag(resultData.get(3) + "-按钮");
touliao3.Init();

touliao4.setTag(resultData.get(4) + "-按钮");
touliao4.Init();

goodname.setText(goods.name + "");
runtime.setText(formatTime(goods.maketime));
showbuttomtop.setVisibility(View.VISIBLE);
Stop();
}

/**
* 设置描述
*
* @param text
*/
public void SetMiaoShu(String text) {
gongxumiaoshu.setText(text + "");
}

/**
* 设置进度条
*
* @param
*/
public void SetProcess(int alltime, int usertime) {
try {
t_jindu.SetValue((usertime * 100) / alltime);
runtime.setText(formatTime((alltime - usertime)));
} catch (Exception ex) {
ToastUtils.error("异常信息:" + ex.getMessage());
}
}


public void Stop() {
if (flicker_buttom != null) {
flicker_buttom.setVisibility(View.VISIBLE);
flicker_buttom.SetStatusKK(false);
flicker_buttom = null;
}
huoli.SetLevel(0);
SetMiaoShu("等待开始...");
SetProcess(goods.maketime, 0);
}
//endregion

//region 私有方法

/**
* 将毫秒转化为 分钟:秒 的格式 100* 1000
*
* @param millisecond 毫秒
* @return
*/
public String formatTime(long millisecond) {
int minute;//分钟
int second;//秒数
minute = (int) ((millisecond / 1) / 60);
second = (int) ((millisecond / 1) % 60);
if (minute < 10) {
if (second < 10) {
return "0" + minute + " : " + "0" + second;
} else {
return "0" + minute + " : " + second;
}
} else {
if (second < 10) {
return minute + " : " + "0" + second;
} else {
return minute + " : " + second;
}
}
}

/**
* 初始化顶部弹框
*/
private void initTopBar() {
mTopBar.setBackgroundColor(ContextCompat.getColor(getContext(), R.color.topbj1));
mTopBar.setTitle("模拟炒制");
mTopBar.addLeftImageButton(R.mipmap.fanhui, R.id.topbar).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
finish();
}
});
}

/**
* 点击事件
*
* @param view
*/
@OnClick({R.id.kaishimoni, R.id.jieshutuichu, R.id.tuichu})
public void onViewClicked(View view) {
switch (view.getId()) {
case R.id.kaishimoni:
StartSimulated();
break;
case R.id.tuichu:
case R.id.jieshutuichu:
finish();
break;
}
}

/**
* 闪烁buttom
*/
public imagebuttom3 flicker_buttom = null;

/**
* 刷新UI界面
*/
public void SxUIThread() {
new Thread(new Runnable() {
@Override
public void run() {

while (true) {
try {
runOnUiThread(new Runnable() {
@Override
public void run() {
//闪烁
if (flicker_buttom != null) {
flicker_buttom.setVisibility(flicker_buttom.getVisibility() == View.VISIBLE ? View.INVISIBLE : View.VISIBLE);
}
}
});
Thread.sleep(1000);
} catch (InterruptedException e) {
ToastUtils.info("异常信息:" + e.getMessage());
}
}
}
}).start();
}
//endregion

//region 外部调用
private CountDownTimerExt countDownTimer = null;//计时器

/**
* 启动
*/
public void onRecordStart() {
if (goods != null) {
int time = goods.maketime;
SetProcess(time, 0);
if (countDownTimer == null) {
countDownTimer = new CountDownTimerExt(time * 1000, 1000) {
@Override
public void onTimerTick(long value) {
int overtime = (int) ((value) / 1000);//剩余时间
SetProcess(time, time - overtime);
}

@Override
public void onTimerFinish() {
SetProcess(time, time);
}
};
}
countDownTimer.start();
}
}

/**
* 停止
*/
public void onRecordStop() {
if (goods != null) {
SetProcess(goods.maketime, 0);
SetMiaoShu("等待开始...");
if (countDownTimer != null) {
countDownTimer.stop();
countDownTimer = null;
}
Stop();
}
}

/**
* 启动模拟播放
*/
public void StartSimulated() {
showbuttomtop.setVisibility(View.GONE);
onRecordStart();
new Thread(new Runnable() {
@Override
public void run() {
for (BPA_GOODSRECIPE recipe : goodsrecipes) {
runOnUiThread(new Runnable() {
@Override
public void run() {
SetMiaoShu("正在执行:" + recipe.processms);
}
});

try {
String ms = "";
String text = recipe.processvalue;
if (recipe.materialType == 0)//正常物料
{
runOnUiThread(new Runnable() {
@Override
public void run() {
CarryOut("位置|抽料位");
}
});
Thread.sleep(2000);
if (!text.isEmpty()) {
//仓号 值
HashMap<Integer, Integer> formulation = new HashMap<>();
//region 获取仓号和值
List<String> data = new ArrayList<>();
if (text.contains("|")) {
String[] res = text.split("[|]");
for (int i = 0; i < res.length; i++) {
data.add(res[i]);
}
} else {
data.add(text);
}
for (String item : data) {
if (!item.isEmpty() && item.contains(",")) {
String[] wl = item.split("[,]");
if (wl != null && wl.length == 2) {
String name = wl[0];
int val = (int) Math.round((Double.parseDouble(wl[1]) * 10));
//int val = Integer.parseInt(wl[1]);
List<BPA_SILOS> bpa_silos = QueryDB.GetSolisByMaterialName(name);
if (bpa_silos.size() > 0 && val > 0) {
BPA_SILOS silos = bpa_silos.get(0);
formulation.put(silos.num, val);
}
}
}
}
//endregion
//写入PLC,直接出料,不用等待
for (Map.Entry<Integer, Integer> entry : formulation.entrySet()) {
Integer key = entry.getKey();
Integer value = entry.getValue();
runOnUiThread(new Runnable() {
@Override
public void run() {
CarryOut("液体料|" + key);
}
});
Thread.sleep(2000);
}
}
} else if (recipe.materialType == 1)//工序模型
{
if (recipe.processname.equals("抽水")) {
runOnUiThread(new Runnable() {
@Override
public void run() {
CarryOut("位置|抽料位");
}
});
Thread.sleep(2000);
} else if (recipe.processname.equals("主料")) {
runOnUiThread(new Runnable() {
@Override
public void run() {
CarryOut("位置|炒菜位1");
}
});
Thread.sleep(2000);
}

//工序名称和值
HashMap<String, String> formulation = new HashMap<>();
//region 获取仓号和值
List<String> data = new ArrayList<>();
if (text.contains("|")) {
String[] res = text.split("[|]");
for (int i = 0; i < res.length; i++) {
data.add(res[i]);
}
} else {
data.add(text);
}
for (String item : data) {
if (!item.isEmpty() && item.contains(",")) {
String[] wl = item.split("[,]");
if (wl != null && wl.length == 2) {
String name = wl[0];
String val = wl[1];
formulation.put(name, val);
}
}
}
//endregion

switch (recipe.processname) {
case "搅拌":
case "位置":
case "加水":
runOnUiThread(new Runnable() {
@Override
public void run() {
CarryOut(recipe.processname + "|未知");
}
});
Thread.sleep(2000);
break;
case "加热":
int val = 0;
for (HashMap.Entry<String, String> entry : formulation.entrySet()) {
String key = entry.getKey();
String value = entry.getValue();
if (key.contains("(秒)")) {
val = Integer.parseInt(value);
} else {
ToastUtils.info("工序:" + key + "," + value);
int writeValue = ExecuteTheRecipe.GetMXValue(key, value);
runOnUiThread(new Runnable() {
@Override
public void run() {
CarryOut(recipe.processname + "|" + writeValue);
}
});
Thread.sleep(2000);
}
}

if (val > 0) {
Thread.sleep(val * 1000);
}
break;
case "主料":
String writeValue = "1号位";
val = 0;

for (HashMap.Entry<String, String> entry : formulation.entrySet()) {
String key = entry.getKey();
String value = entry.getValue();
if (key.contains("主料位置")) {
writeValue = value;
String finalWriteValue = writeValue;
runOnUiThread(new Runnable() {
@Override
public void run() {
CarryOut(recipe.processname + "|" + finalWriteValue);
}
});
Thread.sleep(2000);
} else if (key.contains("(秒)")) {
val = Integer.parseInt(value);
}
}

if (val > 0) {
Thread.sleep(val * 1000);
}
break;
case "延迟":
for (HashMap.Entry<String, String> entry : formulation.entrySet()) {
String key = entry.getKey();
String value = entry.getValue();
ToastUtils.info("工序:" + key + "," + value);
if (key.contains("(秒)")) {
int val11 = Integer.parseInt(value);
Thread.sleep(val11 * 1000);
}
}
break;
}

}
Thread.sleep(1000);
} catch (InterruptedException e) {
}
}

runOnUiThread(new Runnable() {
@Override
public void run() {
onRecordStop();
showbuttomtop.setVisibility(View.VISIBLE);
}
});
}
}).start();
}

public void CarryOut(String data) {
if (data.contains("|")) {
String[] K = data.split("[|]");
if (K.length >= 2) {
String name = K[0];
String val = K[1];
if (flicker_buttom != null) {
flicker_buttom.setVisibility(View.VISIBLE);
flicker_buttom.SetStatusKK(false);
}
flicker_buttom = null;
switch (name) {
case "搅拌":
flicker_buttom = fanchaoshudu;
flicker_buttom.SetStatusKK(true);
break;
case "位置":
flicker_buttom = guokoucaoxiang;
flicker_buttom.SetStatusKK(true);
break;
case "加热":
huoli.SetLevel(Integer.parseInt(val));
break;
case "主料":
if (val.equals("1号位")) {
flicker_buttom = touliao1;
} else if (val.equals("2号位")) {
flicker_buttom = touliao2;
} else if (val.equals("3号位")) {
flicker_buttom = touliao3;
} else if (val.equals("4号位")) {
flicker_buttom = touliao4;
}
flicker_buttom.SetStatusKK(true);
break;
case "加水":
flicker_buttom = chushui;
flicker_buttom.SetStatusKK(true);
break;
case "液体料":
if (val.equals("1")) {
flicker_buttom = yeliao1;
flicker_buttom.SetStatusKK(true);
} else if (val.equals("2")) {
flicker_buttom = yeliao2;
flicker_buttom.SetStatusKK(true);
} else if (val.equals("3")) {
flicker_buttom = yeliao3;
flicker_buttom.SetStatusKK(true);
}
break;
}
}
}
}
//endregion
}

app/src/main/java/com/bonait/bnframework/modules/home/fragment/from/CpActivity.java → app/src/main/java/com/bonait/bnframework/ViewModel/ActivityViewModel/CpActivity.java Ver fichero

@@ -1,41 +1,34 @@
package com.bonait.bnframework.modules.home.fragment.from;
package com.bonait.bnframework.ViewModel.ActivityViewModel;

import static com.bonait.bnframework.MainApplication.getContext;

import androidx.appcompat.app.AppCompatActivity;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;

import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.os.Handler;
import android.os.Message;
import android.view.View;

import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.bonait.bnframework.R;
import com.bonait.bnframework.ViewModel.CustomView.QDListSectionAdapter;
import com.bonait.bnframework.ViewModel.CustomView.SectionHeader;
import com.bonait.bnframework.ViewModel.CustomView.SectionItem;
import com.bonait.bnframework.business.ConfigData;
import com.bonait.bnframework.common.base.BaseActivity;
import com.bonait.bnframework.common.constant.ConfigName;
import com.bonait.bnframework.common.constant.MessageName;
import com.bonait.bnframework.common.db.QueryDB;
import com.bonait.bnframework.common.db.mode.BPA_GOODS;
import com.bonait.bnframework.common.db.mode.BPA_GOODSRECIPE;
import com.bonait.bnframework.common.db.mode.BPA_PLCADDRESS;
import com.bonait.bnframework.common.db.mode.BPA_GOODS_OLD;
import com.bonait.bnframework.common.message.MessageLooper;
import com.bonait.bnframework.common.message.MessageManager;
import com.bonait.bnframework.common.model.mode.CloudGood;
import com.bonait.bnframework.common.utils.AlertDialogUtils;
import com.bonait.bnframework.common.utils.ScreenUtils;
import com.bonait.bnframework.common.utils.ToastUtils;
import com.bonait.bnframework.modules.home.fragment.mode.QDListSectionAdapter;
import com.bonait.bnframework.modules.home.fragment.mode.SectionHeader;
import com.bonait.bnframework.modules.home.fragment.mode.SectionItem;
import com.bonait.bnframework.modules.home.fragment.mode.fragment_plc;
import com.qmuiteam.qmui.widget.QMUITopBar;
import com.qmuiteam.qmui.widget.QMUITopBarLayout;
import com.qmuiteam.qmui.widget.dialog.QMUIDialog;
import com.qmuiteam.qmui.widget.dialog.QMUIDialogAction;
@@ -206,7 +199,7 @@ public class CpActivity extends BaseActivity {
*/
private static ArrayList<QMUISection<SectionHeader, SectionItem>> getList() {
ArrayList<QMUISection<SectionHeader, SectionItem>> list = new ArrayList<>();
ArrayList<BPA_GOODS> good = QueryDB.GetGoodsALL();
ArrayList<BPA_GOODS_OLD> good = QueryDB.GetGoodsALL();
List<String> Bendi_id = new ArrayList<>();

SectionHeader header_bdcp = new SectionHeader("本地菜谱", "", "");
@@ -218,7 +211,7 @@ public class CpActivity extends BaseActivity {
SectionHeader header_ydcp = new SectionHeader("云端菜谱", "", "");
ArrayList<SectionItem> contents_ydcp = new ArrayList<>();

for (BPA_GOODS item : good) {
for (BPA_GOODS_OLD item : good) {
if (item.url == null) {
item.url = "未知";
}
@@ -264,9 +257,9 @@ public class CpActivity extends BaseActivity {

if(ConfigName.getInstance().cloudGoods!=null && ConfigName.getInstance().cloudGoods.size()>0)
{
ArrayList<BPA_GOODS> goods= QueryDB.GetGoodsALL();
ArrayList<BPA_GOODS_OLD> goods= QueryDB.GetGoodsALL();
ArrayList<BPA_GOODSRECIPE> rec= QueryDB.GetGoodsSrecipeALL();
for (BPA_GOODS good:goods)
for (BPA_GOODS_OLD good:goods)
{
QueryDB.DeleteGoods(good);
}

app/src/main/java/com/bonait/bnframework/modules/home/fragment/from/CpxzActivity.java → app/src/main/java/com/bonait/bnframework/ViewModel/ActivityViewModel/CpxzActivity.java Ver fichero

@@ -1,20 +1,19 @@
package com.bonait.bnframework.modules.home.fragment.from;
package com.bonait.bnframework.ViewModel.ActivityViewModel;

import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import androidx.recyclerview.widget.RecyclerView;
import androidx.appcompat.widget.SearchView;
import android.view.View;

import com.apkfuns.logutils.LogUtils;
import com.bonait.bnframework.R;
import com.bonait.bnframework.common.base.BaseActivity;
import com.bonait.bnframework.common.constant.DataBus;
import com.bonait.bnframework.common.db.mode.BPA_GOODS;
import com.bonait.bnframework.common.db.mode.BPA_GOODS_OLD;
import com.bonait.bnframework.common.helper.I.MyClickListener;
import com.bonait.bnframework.common.utils.ToastUtils;
import com.bonait.bnframework.common.view.MyLayoutManager;
import com.bonait.bnframework.modules.home.adapter.sp_adapter;
import com.qmuiteam.qmui.widget.QMUITopBar;
import com.bonait.bnframework.ViewModel.Adapter.sp_adapter;
import com.qmuiteam.qmui.widget.QMUITopBarLayout;

import butterknife.BindView;
@@ -77,7 +76,7 @@ public class CpxzActivity extends BaseActivity {
DataBus.getInstance().spadapter.mListener=new MyClickListener() {
@Override
public void clickListener(View v, Object data) {
BPA_GOODS good=(BPA_GOODS)data;
BPA_GOODS_OLD good=(BPA_GOODS_OLD)data;
DataBus.getInstance().SelectGood=good;
if( DataBus.getInstance().mListener!=null)
{
@@ -92,6 +91,7 @@ public class CpxzActivity extends BaseActivity {
}
};
}catch(Exception e){
LogUtils.d("异常信息:" + e.getMessage());
ToastUtils.info("异常信息:"+e.getMessage());
}
}

+ 1370
- 0
app/src/main/java/com/bonait/bnframework/ViewModel/ActivityViewModel/DishTestActivity.java
La diferencia del archivo ha sido suprimido porque es demasiado grande
Ver fichero


app/src/main/java/com/bonait/bnframework/modules/home/fragment/from/DiyActivity.java → app/src/main/java/com/bonait/bnframework/ViewModel/ActivityViewModel/DiyActivity.java Ver fichero

@@ -1,22 +1,15 @@
package com.bonait.bnframework.modules.home.fragment.from;
package com.bonait.bnframework.ViewModel.ActivityViewModel;

import static com.bonait.bnframework.MainApplication.getContext;

import androidx.appcompat.app.AppCompatActivity;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.util.AttributeSet;
import android.util.Xml;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
@@ -29,35 +22,25 @@ import com.bonait.bnframework.common.base.BaseActivity;
import com.bonait.bnframework.common.constant.DataBus;
import com.bonait.bnframework.common.constant.MessageName;
import com.bonait.bnframework.common.db.QueryDB;
import com.bonait.bnframework.common.db.mode.BPA_GOODS;
import com.bonait.bnframework.common.db.mode.BPA_GOODS_OLD;
import com.bonait.bnframework.common.db.mode.BPA_GOODSRECIPE;
import com.bonait.bnframework.common.db.mode.BPA_MATERIAL;
import com.bonait.bnframework.common.db.mode.BPA_PROCESS;
import com.bonait.bnframework.common.db.mode.BPA_PROCESSModel;
import com.bonait.bnframework.common.helper.I.MyClickListener;
import com.bonait.bnframework.common.helper.MyImage;
import com.bonait.bnframework.common.image.MyBitmapUtils;
import com.bonait.bnframework.common.message.MessageLooper;
import com.bonait.bnframework.common.message.MessageManager;
import com.bonait.bnframework.common.utils.AlertDialogUtils;
import com.bonait.bnframework.common.utils.ToastUtils;
import com.bonait.bnframework.modules.home.adapter.gongxubuzhou_adapter;
import com.bonait.bnframework.modules.home.adapter.lcsz_adapter;
import com.bonait.bnframework.modules.home.fragment.mode.fragment_gx;
import com.bonait.bnframework.modules.home.fragment.mode.item_gx;
import com.qmuiteam.qmui.widget.QMUITopBar;
import com.bonait.bnframework.ViewModel.Adapter.gongxubuzhou_adapter;
import com.bonait.bnframework.ViewModel.CustomView.fragment_gx;
import com.bonait.bnframework.ViewModel.CustomView.item_gx;
import com.qmuiteam.qmui.widget.QMUITopBarLayout;
import com.qmuiteam.qmui.widget.dialog.QMUIDialog;
import com.qmuiteam.qmui.widget.dialog.QMUIDialogAction;
import com.youth.banner.Banner;

import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.IdentityHashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
@@ -180,6 +163,23 @@ public class DiyActivity extends BaseActivity {
}
}
});

//DIY 刷新
MessageManager.getInstance().registerMessageReceiver(this, MessageName.DIY, new MessageLooper.OnMessageListener() {
@Override
public void onMessage(Object msg) {
if (msg != null) {
bpa_goodsrecipes.clear();
for(BPA_GOODSRECIPE item:DataBus.getInstance().bpa_goodsrecipes)
{
bpa_goodsrecipes.add(item);
}
zzsc.setText(DataBus.getInstance().TimeOut+"");
gxbz_adapter.notifyDataSetChanged();
}
}
});

getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);
}

@@ -449,8 +449,10 @@ public class DiyActivity extends BaseActivity {
ToastUtils.info("已经最底部!");
}
break;
case R.id.caozuomoshi://操作模式
ToastUtils.info("操作模式");
case R.id.caozuomoshi://操作模式,打开自动记忆模式
Intent intent1 = new Intent(getContext(), DiyMemoryActivity.class);
intent1.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent1);
break;
case R.id.shengchengcaipu://生成菜谱
String name = edittext.getText().toString();
@@ -476,8 +478,8 @@ public class DiyActivity extends BaseActivity {
sc = Integer.parseInt(zzsc.getText().toString());
}

ArrayList<BPA_GOODS> goods = QueryDB.GetGoodsALL();
BPA_GOODS good = new BPA_GOODS();
ArrayList<BPA_GOODS_OLD> goods = QueryDB.GetGoodsALL();
BPA_GOODS_OLD good = new BPA_GOODS_OLD();
good.name = name;
good.status = 1;
good.sort = goods.size() + 1;

+ 681
- 0
app/src/main/java/com/bonait/bnframework/ViewModel/ActivityViewModel/DiyMemoryActivity.java Ver fichero

@@ -0,0 +1,681 @@
package com.bonait.bnframework.ViewModel.ActivityViewModel;

import androidx.annotation.NonNull;

import android.content.Context;
import android.graphics.Color;
import android.os.Bundle;
import android.os.SystemClock;
import android.util.DisplayMetrics;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.Chronometer;
import android.widget.ImageView;
import android.widget.LinearLayout;

import com.apkfuns.logutils.LogUtils;
import com.bonait.bnframework.HBL.Interface.IRun;
import com.bonait.bnframework.R;
import com.bonait.bnframework.business.ExecuteTheRecipe;
import com.bonait.bnframework.common.base.BaseActivity;
import com.bonait.bnframework.common.constant.ConfigName;
import com.bonait.bnframework.common.constant.DataBus;
import com.bonait.bnframework.common.constant.MessageName;
import com.bonait.bnframework.common.db.QueryDB;
import com.bonait.bnframework.common.db.mode.BPA_GOODSRECIPE;
import com.bonait.bnframework.common.db.mode.BPA_MATERIAL;
import com.bonait.bnframework.common.helper.I.MyClickListener;
import com.bonait.bnframework.common.message.MessageManager;
import com.bonait.bnframework.common.utils.AlertDialogUtils;
import com.bonait.bnframework.common.utils.ToastUtils;
import com.bonait.bnframework.ViewModel.CustomView.fragment_gx;
import com.bonait.bnframework.ViewModel.CustomView.huoli_control;
import com.bonait.bnframework.ViewModel.CustomView.item_gx;
import com.litao.slider.NiftySlider;
import com.qmuiteam.qmui.widget.QMUITopBarLayout;
import com.qmuiteam.qmui.widget.dialog.QMUIDialog;
import com.qmuiteam.qmui.widget.dialog.QMUIDialogAction;

import java.util.ArrayList;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class DiyMemoryActivity extends BaseActivity {

@BindView(R.id.topbar)
QMUITopBarLayout mTopBar;

@BindView(R.id.gxchid)
LinearLayout gxchid;//工序子集

@BindView(R.id.start_bj)
LinearLayout start_bj;//背景

@BindView(R.id.startbutton)
ImageView startbutton;//启动停止

public boolean isRun = false;

@BindView(R.id.runtime)
Chronometer runtime;//运行时间

@BindView(R.id.huoli)
huoli_control huoli;//火力 控件

@BindView(R.id.nifty_slider2)
NiftySlider nifty_slider2;//搅拌挡位

// @BindView(R.id.nifty_slider3)
// NiftySlider nifty_slider3;//移动挡位

private Context context;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_diy_memory);
ButterKnife.bind(this);
initTopBar();
initData();
}

/**
* 初始化数据
*/
private void initData() {
try {
DataBus.getInstance().bpa_goodsrecipes.clear();
gxchid.removeAllViews();
ArrayList<BPA_MATERIAL> materials = QueryDB.GetMaterialALL();
for (BPA_MATERIAL item2 : materials) {
item_gx gx = new item_gx();
gx.datatype = 0;//液体料都是数字
gx.name = item2.name;
gx.IsWL = true;
fragment_gx gongxu = new fragment_gx(this, null, gx);
gxchid.addView(gongxu);
}
} catch (Exception ex) {
}
}

private void initTopBar() {
mTopBar.setTitle("手动操作模式");
mTopBar.addLeftImageButton(R.mipmap.fanhui, R.id.topbar).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if (isRun) {
ToastUtils.warning("请先结束烹饪!!!");
}else
{
finish();
}
}
});
//为Chronomter绑定事件监听器,超过一小时自动日内告知
runtime.setOnChronometerTickListener(new Chronometer.OnChronometerTickListener() {
@Override
public void onChronometerTick(Chronometer chronometer) {
//如果计时到现在超过了一小时秒
if (SystemClock.elapsedRealtime() - runtime.getBase() > 3600 * 1000) {
runtime.stop();
}
}
});

nifty_slider2.setOnValueChangeListener(new NiftySlider.OnValueChangeListener() {
@Override
public void onValueChange(@NonNull NiftySlider niftySlider, float v, boolean b) {
nifty_slider2.setThumbText((int) v + "");
}
});

// nifty_slider3.setOnValueChangeListener(new NiftySlider.OnValueChangeListener() {
// @Override
// public void onValueChange(@NonNull NiftySlider niftySlider, float v, boolean b) {
// nifty_slider3.setThumbText((int) v + "");
// }
// });
nifty_slider2.setValue(0, true);
// nifty_slider3.setValue(0, true);

huoli.mListener = new MyClickListener() {
@Override
public void clickListener(View v, Object data) {
if(isRunClick())
{
long elapsedMillis = SystemClock.elapsedRealtime() - runtime.getBase();
int time = (int) (elapsedMillis / 1000);//当前点击多少秒
int time_c=time-ClikTime;

if(time_c>0)//如果大于0,那么加一个延迟
{
DataBus.getInstance().bpa_goodsrecipes.add(Get延迟(time_c));
}

String sdstr= Get挡位((int) data);
BPA_GOODSRECIPE data1=Get加热(sdstr);
DataBus.getInstance().bpa_goodsrecipes.add(data1);
ClikTime=time;
ExecuteTheRecipe.Write_PLC_HuoLI((int) data);
}

}

@Override
public void clickListenerNew(View v, int k, Object data) {

}
};
}


public int TimeOut=0;//当前运行总时长
public int ClikTime=0;//上一次点击时间

@OnClick({R.id.startbutton, R.id.querendangwei,
R.id.chuliao, R.id.touliao1,R.id.touliao0,
R.id.touliao2, R.id.touliao3,
R.id.touliao4
, R.id.ydw, R.id.dcw, R.id.clw
, R.id.qxw, R.id.ccw1, R.id.ccw2, R.id.ccw3
,R.id.zidongchucan})
public void onViewClicked(View view) {
long elapsedMillis = SystemClock.elapsedRealtime() - runtime.getBase();
int time = (int) (elapsedMillis / 1000);//当前点击多少秒
int time_c=time-ClikTime;

switch (view.getId()) {
case R.id.startbutton://启动 停止
if (isRun) {
String title = "停止操作提示!";
String message = "请问客官确定要停止制作吗,小菠萝会生气的,啊啊啊啊啊啊啊...我的饭饭?";
AlertDialogUtils.showDialog(view.getContext(), title, message, new QMUIDialogAction.ActionListener() {
@Override
public void onClick(QMUIDialog dialog, int index) {
StopTime();
dialog.dismiss();
}
});
} else {

String title = "开始操作提示!";
String message = "请问客官确定要开始制作吗,小菠萝好开心呀,马上就有好吃的耶?";
AlertDialogUtils.showDialog(view.getContext(), title, message, new QMUIDialogAction.ActionListener() {
@Override
public void onClick(QMUIDialog dialog, int index) {
StartTime();
dialog.dismiss();
}
});
}
break;
case R.id.querendangwei://确认搅拌挡位
if(isRunClick())
{
if(time_c>0)//如果大于0,那么加一个延迟
{
DataBus.getInstance().bpa_goodsrecipes.add(Get延迟(time_c));
}

int sd = (int) nifty_slider2.getValue();
String sdstr= Get速度(sd);
BPA_GOODSRECIPE data=Get搅拌(sdstr);
DataBus.getInstance().bpa_goodsrecipes.add(data);
ExecuteTheRecipe.WritePLC("搅拌速度", sd, ()->{
if (sd == 0) {
ExecuteTheRecipe.WritePLC("搅拌", false, null);
} else {
ExecuteTheRecipe.WritePLC("搅拌", true, null);
}
});
ClikTime=time;
}
break;
case R.id.chuliao://出料
if(isRunClick())
{
BPA_GOODSRECIPE data = GetSelectItemFromValue();
if (data != null) {
DataBus.getInstance().bpa_goodsrecipes.add(data);
MakeRecipe(data);
ClikTime=time;
}
}
break;
case R.id.touliao0://主料1
if(isRunClick())
{
ExecuteTheRecipe.BottomClick("平移-去1号位");
}
break;
case R.id.touliao1://主料1
ClickZL(time,time_c,1);
break;
case R.id.touliao2://主料2
ClickZL(time,time_c,2);
break;
case R.id.touliao3://主料3
ClickZL(time,time_c,3);
break;
case R.id.touliao4://主料4
ClickZL(time,time_c,4);
break;
case R.id.ydw://原点位
final float scale = getResources().getDisplayMetrics().density;
int width = ((Button)findViewById(R.id.ydw)).getWidth();
int width2 = ((LinearLayout)findViewById(R.id.start_bj)).getWidth();
int height = ((Button)findViewById(R.id.ydw)).getWidth();
WindowManager wm = (WindowManager) (getSystemService(Context.WINDOW_SERVICE));
DisplayMetrics dm = new DisplayMetrics();
wm.getDefaultDisplay().getMetrics(dm);
int mScreenWidth = dm.widthPixels;
LogUtils.d(" 屏幕分辨率 width="+width+";scale="+scale+";width2="+width2+";height="+height+";mScreenWidth="+mScreenWidth);
ClickWZ(time,time_c,"原点位");
break;
case R.id.dcw://到菜位
ClickWZ(time,time_c,"倒菜位");
break;
case R.id.clw://出料位置
ClickWZ(time,time_c,"抽料位");
break;
case R.id.qxw://清洗位置
ClickWZ(time,time_c,"清洗位");
break;
case R.id.ccw1://炒菜位1
ClickWZ(time,time_c,"炒菜位1");
break;
case R.id.ccw2://炒菜位2
ClickWZ(time,time_c,"炒菜位2");
break;
case R.id.ccw3://炒菜位3
ClickWZ(time,time_c,"炒菜位3");
break;
case R.id.zidongchucan://自动出餐
if(isRunClick())
{
BPA_GOODSRECIPE data1=Get出菜(time_c);
DataBus.getInstance().bpa_goodsrecipes.add(data1);
MakeRecipe(data1);
ClikTime=time;
}
break;
}
}

//region 常用函数

/**
* 是否运行
* @return
*/
public boolean isRunClick()
{
if (!isRun) {
ToastUtils.warning("请先开始计时器!!!");
return false;
}

if (isMake) {
ToastUtils.warning("请等待上一步骤结束!!!");
return false;
}


// if (!isRun) {
// ToastUtils.info("请先开始计时器!!!");
// return false;
// }

return true;
}
public void ClickZL(int time,int time_c,int num)
{
// Object sb = ExecuteTheRecipe.ReadPLC("平移轴在1号位");
// if (sb != null) {
// if ((boolean) (sb)) {
//
// } else {
// ToastUtils.warning("平移轴未复位!!!");
// }
// } else {
// ToastUtils.warning("PLC未连接!!!");
// }

if(isRunClick())
{
if(time_c>0)//如果大于0,那么加一个延迟
{
DataBus.getInstance().bpa_goodsrecipes.add(Get延迟(time_c));
}

//控制去炒菜位
BPA_GOODSRECIPE data1=Get位置("最高","炒菜位1");
DataBus.getInstance().bpa_goodsrecipes.add(data1);

BPA_GOODSRECIPE data=Get主料(num);
DataBus.getInstance().bpa_goodsrecipes.add(data);
MakeRecipe(data);//执行主料
ClikTime=time;
}

}
public void ClickWZ(int time,int time_c,String name)
{
if(isRunClick())
{
if(time_c>0)//如果大于0,那么加一个延迟
{
DataBus.getInstance().bpa_goodsrecipes.add(Get延迟(time_c));
}

// int sd = (int) nifty_slider3.getValue();
// String sdstr= Get速度(sd);
BPA_GOODSRECIPE data=Get位置("最高",name);
DataBus.getInstance().bpa_goodsrecipes.add(data);
MakeRecipe(data);
ClikTime=time;
}
}

public boolean isMake=false;
public void MakeRecipe(BPA_GOODSRECIPE recipe)
{
isMake=true;
new Thread(new Runnable() {
@Override
public void run() {
if (recipe.materialType == 0)//正常物料
{
BPA_GOODSRECIPE data1=Get位置("最高","抽料位");
ExecuteTheRecipe.ExecuteOperationSteps(data1.processname,data1.processvalue);

ExecuteTheRecipe.ExecuteMaterialIssuance(recipe.processvalue);
} else if (recipe.materialType == 1)//工序模型
{
if(recipe.processname.equals("主料"))
{
BPA_GOODSRECIPE data1=Get位置("最高","炒菜位1");
ExecuteTheRecipe.ExecuteOperationSteps(data1.processname,data1.processvalue);

ExecuteTheRecipe.ExecuteOperationSteps(recipe.processname,recipe.processvalue);
}else
{
ExecuteTheRecipe.ExecuteOperationSteps(recipe.processname,recipe.processvalue);
}
}
isMake=false;
}
}).start();
}

/**
* 获取选中行的变量
*
* @return
*/
public BPA_GOODSRECIPE GetSelectItemFromValue() {
BPA_GOODSRECIPE pf = new BPA_GOODSRECIPE();
try {
boolean IsVerify = true;
String description = "";
// 延迟,100|延迟,100|延迟,100|延迟,100|
String data = "";
String desc = "";

pf.materialType = 0;
for (int i = 0; i < gxchid.getChildCount(); i++) {
fragment_gx gongxu = (fragment_gx) gxchid.getChildAt(i);
String values = gongxu.GetValues();
if (!values.isEmpty()) {
data += gongxu.model.name + "," + values + "|";
desc += values + ",";
}
}

if (data.isEmpty()) {
IsVerify = false;
description += "物料-不能为空,请勾选一个物料\n";
}


if (IsVerify) {
pf.processname = "液体料";
pf.processms = "液体料" + "(" + desc.substring(0, desc.length() - 1) + ")";
pf.processvalue = data.substring(0, data.length() - 1);
return pf;
} else {
ToastUtils.error("数据验证失败,原因:" + description);
return null;
}
} catch (Exception ex) {
return null;
}
}

/**
* 获取延迟
* @param time
* @return
*/
public BPA_GOODSRECIPE Get延迟(int time)
{
BPA_GOODSRECIPE pf = new BPA_GOODSRECIPE();
pf.materialType=1;
pf.processname="延迟";
pf.processms="延迟("+time+")";
pf.processvalue="延迟(秒),"+time;
return pf;
}

/**
* 获取主料
* @param wz
* @return
*/
public BPA_GOODSRECIPE Get主料(int wz)
{
BPA_GOODSRECIPE pf = new BPA_GOODSRECIPE();
pf.materialType=1;
pf.processname="主料";
pf.processms="主料(未知,"+wz+"号位,0,直接投出,0)";
pf.processvalue="主料名称,未知|主料位置,"+wz+"号位|主料重量,0|投料动作,直接投出|烹饪(秒),0";
return pf;
}

/**
* 获取位置
* @param sd
* @return
*/
public BPA_GOODSRECIPE Get位置(String sd,String name)
{
BPA_GOODSRECIPE pf = new BPA_GOODSRECIPE();
pf.materialType=1;
pf.processname="位置";
pf.processms="位置("+sd+","+name+",0)";
pf.processvalue="转动速度,"+sd+"|位置动作,"+name+"|延迟(秒),0";
return pf;
}

/**
* 获取搅拌
* @param sd
* @return
*/
public BPA_GOODSRECIPE Get搅拌(String sd)
{
BPA_GOODSRECIPE pf = new BPA_GOODSRECIPE();
pf.materialType=1;
pf.processname="搅拌";
pf.processms="搅拌("+sd+",0)";
pf.processvalue="搅拌速度,"+sd+"|延迟(秒),0";
return pf;
}

/**
* 获取加热
* @param sd
* @return
*/
public BPA_GOODSRECIPE Get加热(String sd)
{
BPA_GOODSRECIPE pf = new BPA_GOODSRECIPE();
pf.materialType=1;
pf.processname="加热";
pf.processms="加热("+sd+",0)";
pf.processvalue="加热功率,"+sd+"|延迟(秒),0";
return pf;
}

/**
* 获取出菜
* @return
*/
public BPA_GOODSRECIPE Get出菜(int k)
{
BPA_GOODSRECIPE pf = new BPA_GOODSRECIPE();
pf.materialType=1;
pf.processname="出菜";
pf.processms="出菜("+k+")";
pf.processvalue="等待(秒),"+k;
return pf;
}

/**
* 获取速度
* @return
*/
public String Get速度(int speed)
{
if(speed>=0 && speed<5)
{
return "停止";
}else if(speed>=5 && speed<15)
{
return "最低";
}else if(speed>=15 && speed<25)
{
return "低速";
}else if(speed>=25 && speed<35)
{
return "中速";
}else if(speed>=35 && speed<45)
{
return "高速";
}else if(speed>=45 && speed<55)
{
return "最高";
}else
{
return "极高";
}
}

/**
* 获取挡位
* @return
*/
public String Get挡位(int speed)
{
if(speed==0)
{
return "停止";
}else if(speed==1)
{
return "一档";
}else if(speed==2)
{
return "二档";
}else if(speed==3)
{
return "三档";
}else if(speed==4)
{
return "四档";
}else if(speed==5)
{
return "五档";
}else if(speed==6)
{
return "六档";
}else if(speed==7)
{
return "七档";
}else
{
return "八档";
}
}

/**
* 启动定时器
*/
public void StartTime() {
runOnUiThread(new Runnable() {
@Override
public void run() {
//设置开始计时时间
runtime.setBase(SystemClock.elapsedRealtime());
//启动计时器
runtime.start();
isRun = true;
startbutton.setImageResource(R.mipmap.stop_js);
//5700FF22
//25FF9800
start_bj.setBackgroundColor(Color.parseColor("#5700FF22"));

DataBus.getInstance().bpa_goodsrecipes.clear();//清空所有工序
TimeOut=0;
ClikTime=0;
}
});

}

/**
* 停止定时器
*/
public void StopTime() {
runOnUiThread(new Runnable() {
@Override
public void run() {
//启动计时器
runtime.stop();
isRun = false;
startbutton.setImageResource(R.mipmap.start_js);

start_bj.setBackgroundColor(Color.parseColor("#25FF9800"));

long elapsedMillis = SystemClock.elapsedRealtime() - runtime.getBase();
TimeOut = (int) (elapsedMillis / 1000);//当前点击多少秒
DataBus.getInstance().TimeOut=TimeOut;
if(DataBus.getInstance().bpa_goodsrecipes.size()>=0)
{
MessageManager.getInstance().sendMessage(MessageName.DIY,"DIY");
}

ExecuteTheRecipe.WritePLC("搅拌", false, null);
ExecuteTheRecipe.WritePLC("加热", false, null);
ConfigName.getInstance().IsOpenHuoLi= false;
ExecuteTheRecipe.BottomClick("平移-去1号位");
}
});

}
//endregion


@Override
public void onDestroy() {
super.onDestroy();
}

@Override
protected boolean canDragBack() {
return false;
}
}

+ 777
- 0
app/src/main/java/com/bonait/bnframework/ViewModel/ActivityViewModel/DiyUpdate1Activity.java Ver fichero

@@ -0,0 +1,777 @@
package com.bonait.bnframework.ViewModel.ActivityViewModel;

import static com.bonait.bnframework.MainApplication.getContext;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.Spinner;
import android.widget.TextView;

import androidx.core.content.ContextCompat;

import com.apkfuns.logutils.LogUtils;
import com.bonait.bnframework.HBL.Logs.MessageLog;
import com.bonait.bnframework.R;
import com.bonait.bnframework.ViewModel.Adapter.gongxubuzhou_adapter;
import com.bonait.bnframework.ViewModel.CustomView.XComDialog;
import com.bonait.bnframework.ViewModel.CustomView.fragment_gx;
import com.bonait.bnframework.ViewModel.CustomView.item_gx;
import com.bonait.bnframework.common.base.BaseActivity;
import com.bonait.bnframework.common.constant.DataBus;
import com.bonait.bnframework.common.constant.MessageName;
import com.bonait.bnframework.common.db.QueryDB;
import com.bonait.bnframework.common.db.mode.BPA_GOODS_OLD;
import com.bonait.bnframework.common.db.mode.BPA_GOODSRECIPE;
import com.bonait.bnframework.common.db.mode.BPA_MATERIAL;
import com.bonait.bnframework.common.db.mode.BPA_PROCESS;
import com.bonait.bnframework.common.db.mode.BPA_PROCESSModel;
import com.bonait.bnframework.common.image.MyBitmapUtils;
import com.bonait.bnframework.common.message.MessageLooper;
import com.bonait.bnframework.common.message.MessageManager;
import com.bonait.bnframework.common.utils.AlertDialogUtils;
import com.bonait.bnframework.common.utils.CookTimeUtils;
import com.bonait.bnframework.common.utils.DisplayManager;
import com.bonait.bnframework.common.utils.ToastUtils;
import com.bonait.bnframework.common.view.CircleImageView;
import com.qmuiteam.qmui.widget.QMUITopBarLayout;
import com.qmuiteam.qmui.widget.QMUIWindowInsetLayout;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class DiyUpdate1Activity extends BaseActivity {
@BindView(R.id.topbar)
QMUITopBarLayout mTopBar;
@BindView(R.id.edittext)
EditText edittext;//菜谱名称
@BindView(R.id.cpfm)
CircleImageView cpfm;//菜谱封面
@BindView(R.id.zzsc)
EditText zzsc;//制作时长
@BindView(R.id.check)
CheckBox check;//默认收藏
@BindView(R.id.hrgx)
Spinner hrgx;//工序
Map<String, String> hrgx_map = new LinkedHashMap<>();
Map<String, Integer> hrgx_map_index = new LinkedHashMap<>();
@BindView(R.id.gxchid)
LinearLayout gxchid;//工序子集
@BindView(R.id.datatab_gxbz)
ListView datatab_gxbz;//工序步骤
@BindView(R.id.text1)
TextView text1;
@BindView(R.id.text2)
TextView text2;
@BindView(R.id.ll_gx)
LinearLayout ll_gx;
@BindView(R.id.scrollView)
ScrollView scrollView;
@BindView(R.id.ll_content)
LinearLayout ll_content;
@BindView(R.id.rl_buzou)
RelativeLayout rl_buzou;
@BindView(R.id.rl_buzou1)
RelativeLayout rl_buzou1;
@BindView(R.id.shengchengcaipu)
TextView shengchengcaipu;
@BindView(R.id.shengchengnewcaipu)
TextView shengchengnewcaipu;
@BindView(R.id.caozuomoshi)
TextView caozuomoshi;
@BindView(R.id.add_hrgx)
TextView add_hrgx;
@BindView(R.id.update_gx)
TextView update_gx;
@BindView(R.id.delete_gx)
TextView delete_gx;
@BindView(R.id.add_up)
TextView add_up;
@BindView(R.id.add_down)
TextView add_down;
@BindView(R.id.shangyi)
ImageView shangyi;

@BindView(R.id.xiayi)
ImageView xiayi;
@BindView(R.id.root)
QMUIWindowInsetLayout root;




public gongxubuzhou_adapter gxbz_adapter = null;
/**
* 工序步骤
*/
public ArrayList<BPA_GOODSRECIPE> bpa_goodsrecipes = new ArrayList<>();

/**
* 是否人工单击
*/
public boolean isUserClicked = false;
/**
* 当前商品
*/
public BPA_GOODS_OLD good = null;

/**
* 图片地址
*/
private String picUrl = "";

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_diy_update1);
ButterKnife.bind(this);
initView();
initTopBar();
initData();
SetGood();
}

private void initView(){
DisplayManager.scaleViewGroup(root);

// hrgx.setDropDownVerticalOffset((int) (DisplayManager.getWidthScaleRate()*50));
}

private void initData() {
//1.初始化轮播图
//Drawable_Get(Banner_list);
//2.初始化工序
ArrayList<BPA_PROCESS> data = QueryDB.GetProcessALL();
int i = 0;
String id = "";
for (BPA_PROCESS item : data) {
hrgx_map.put(item.name, item.id);
hrgx_map_index.put(item.name, i);
if (i == 0) {
id = item.id;
}
i++;
}
ArrayAdapter<String> adapter_kk = new ArrayAdapter<>(getContext(), R.layout.spinner_text_item, new ArrayList<>(hrgx_map.keySet()));
adapter_kk.setDropDownViewResource(R.layout.spinner_dropdown_item);
hrgx.setAdapter(adapter_kk);

hrgx.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View view, MotionEvent motionEvent) {
isUserClicked = true;
view.performClick();
return false;
}
});
hrgx.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
if (isUserClicked)//不是用户点击返回
{
String id = hrgx_map.get(hrgx.getSelectedItem().toString());
SelectItemFrom(id);
isUserClicked = false;
}
}

@Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
});
SelectItemFrom(id);
//3.工序步骤
gxbz_adapter = new gongxubuzhou_adapter(getContext(), R.layout.gx_item1, (List<BPA_GOODSRECIPE>) bpa_goodsrecipes, null);
datatab_gxbz.setAdapter(gxbz_adapter);
datatab_gxbz.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long l) {
// TODO Auto-generated method stub
gxbz_adapter.setSelectedPosition(position);
gxbz_adapter.notifyDataSetInvalidated();

SetSelectGX(bpa_goodsrecipes.get(position));//单击工序行,显示变量
}
});
//图标选择
MessageManager.getInstance().registerMessageReceiver(this, MessageName.ClickImage, new MessageLooper.OnMessageListener() {
@Override
public void onMessage(Object msg) {
if (msg != null) {
picUrl = (String) msg;
new MyBitmapUtils().disPlay(cpfm, picUrl);
}
}
});

//图标选择
MessageManager.getInstance().registerMessageReceiver(this, MessageName.DIY, new MessageLooper.OnMessageListener() {
@Override
public void onMessage(Object msg) {
MessageLog.ShowInfo("onMessage 图标选择 msg="+msg);
if (msg != null) {
bpa_goodsrecipes.clear();
for (BPA_GOODSRECIPE item : DataBus.getInstance().bpa_goodsrecipes) {
bpa_goodsrecipes.add(item);
}
LogUtils.e("图标选择 bpa_goodsrecipes="+bpa_goodsrecipes.toString());
zzsc.setText(DataBus.getInstance().TimeOut + "");
gxbz_adapter.notifyDataSetChanged();
}
}
});
}

/**
* 根据选中步骤显示变量
*
* @param goodsrecipe
*/
public void SetSelectGX(BPA_GOODSRECIPE goodsrecipe) {
try {
//1.根据工序名称显示工序集合
hrgx.setSelection(hrgx_map_index.get(goodsrecipe.processname));
String id = hrgx_map.get(hrgx.getSelectedItem().toString());
SelectItemFrom(id);

//2.根据工序变量集合-获取变量名称和值
final HashMap<String, String> formulation = new HashMap<>();
//region 获取变量名称和值
String text = goodsrecipe.processvalue;
List<String> data = new ArrayList<>();
if (text.contains("|")) {
String[] res = text.split("[|]");
for (int i = 0; i < res.length; i++) {
data.add(res[i]);
}
} else {
data.add(text);
}
for (String item : data) {
if (!item.isEmpty() && item.contains(",")) {
String[] wl = item.split("[,]");
if (wl != null && wl.length == 2) {
String name = wl[0];
String val = wl[1];
formulation.put(name, val);
}
}
}
//endregion

//3.查询子集-填充变量
for (Map.Entry<String, String> entry : formulation.entrySet()) {
String key = entry.getKey();
String value = entry.getValue();
String STR = formulation.get(key);
}

for (int i = 0; i < gxchid.getChildCount(); i++) {
fragment_gx gongxu = (fragment_gx) gxchid.getChildAt(i);
String res = formulation.get(gongxu.model.name);
if (res != null) {
gongxu.SetValues(res);
}
}
LogUtils.e("SetSelectGX formulation="+formulation.toString());
} catch (Exception ex) {
}
}

/**
* 设置当前商品
*
* @param
*/
public void SetGood() {
try {
Intent intent = getIntent();
String id = intent.getStringExtra("id");
if (!id.isEmpty()) {
good = QueryDB.GetGoodsId(id);
picUrl = good.url;
if (good != null) {
bpa_goodsrecipes.clear();
ArrayList<BPA_GOODSRECIPE> goodsrecipes = QueryDB.GetGoodsSrecipeID(good.id);
for (BPA_GOODSRECIPE item : goodsrecipes) {
bpa_goodsrecipes.add(item);
}
LogUtils.e("SetGood bpa_goodsrecipes="+bpa_goodsrecipes.toString());
edittext.setText(good.name);
check.setChecked(good.issc == 1);
zzsc.setText(good.maketime + "");
gxbz_adapter.notifyDataSetChanged();//刷新商品配方
new MyBitmapUtils().disPlay(cpfm, picUrl);
}
}
getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);
} catch (Exception ex) {

}
}

/**
* 根据选中工序id显示集合
*
* @param id
*/
public void SelectItemFrom(String id) {
try {
gxchid.removeAllViews();
ArrayList<BPA_PROCESSModel> mode = QueryDB.GetProcessModelProcessID(id);
if (mode.size() > 0)//工序
{
for (BPA_PROCESSModel item : mode) {
item_gx gx = new item_gx();
gx.datatype = item.datatype;
gx.name = item.name;
gx.data = item.data;
gx.IsWL = false;
fragment_gx gongxu = new fragment_gx(this, null, gx);
LogUtils.d("SelectItemFrom gx="+gx.toString());
gxchid.addView(gongxu);
}
} else //物料
{
ArrayList<BPA_MATERIAL> materials = QueryDB.GetMaterialALL();
for (BPA_MATERIAL item2 : materials) {
item_gx gx = new item_gx();
gx.datatype = 0;//液体料都是数字
gx.name = item2.name;
gx.IsWL = true;
fragment_gx gongxu = new fragment_gx(this, null, gx);
LogUtils.d("SelectItemFrom gx="+gx.toString());
gxchid.addView(gongxu);
}
}
} catch (Exception ex) {
}
}

/**
* 获取选中行的变量
*
* @return
*/
public BPA_GOODSRECIPE GetSelectItemFromValue() {
BPA_GOODSRECIPE pf = new BPA_GOODSRECIPE();
try {
String name = hrgx.getSelectedItem().toString();
boolean IsVerify = true;
String description = "";
// 延迟,100|延迟,100|延迟,100|延迟,100|
String data = "";
String desc = "";
if (name.contains("液体料")) {
pf.materialType = 0;
for (int i = 0; i < gxchid.getChildCount(); i++) {
fragment_gx gongxu = (fragment_gx) gxchid.getChildAt(i);
String values = gongxu.GetValues();
if (!values.isEmpty()) {
data += gongxu.model.name + "," + values + "|";
desc += values + ",";
}
}

if (data.isEmpty()) {
IsVerify = false;
description += "物料-不能为空,请勾选一个物料\n";
}
} else {
pf.materialType = 1;
for (int i = 0; i < gxchid.getChildCount(); i++) {
fragment_gx gongxu = (fragment_gx) gxchid.getChildAt(i);
String values = gongxu.GetValues();
if (values.isEmpty()) {
IsVerify = false;
description += gongxu.model.name + "-不能为空\n";
} else {
data += gongxu.model.name + "," + values + "|";
desc += values + ",";
}
}
}
if (IsVerify) {
pf.processname = name;
pf.processms = name + "(" + desc.substring(0, desc.length() - 1) + ")";
pf.processvalue = data.substring(0, data.length() - 1);
LogUtils.d("修改工序 pf="+pf.toString());
return pf;
} else {
ToastUtils.info("数据验证失败,原因:" + description);
return null;
}
} catch (Exception ex) {
return null;
}
}
private void initTopBar() {
mTopBar.setBackgroundColor(ContextCompat.getColor(getContext(), R.color.topbj1));
mTopBar.setTitle("编辑菜谱");
mTopBar.addLeftImageButton(R.mipmap.fanhui, R.id.topbar).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
finish();
}
});
}

/**
* 点击事件
*
* @param view
*/
@SuppressLint("NonConstantResourceId")
@OnClick({R.id.add_hrgx, R.id.update_gx, R.id.delete_gx, R.id.shangyi, R.id.xiayi, R.id.caozuomoshi, R.id.shengchengcaipu, R.id.shengchengnewcaipu, R.id.cpfm,R.id.add_up,R.id.add_down})
public void onViewClicked(View view) {
switch (view.getId()) {
case R.id.cpfm://菜谱封面
// 跳转到登录页面
Intent intent = new Intent(getContext(), ImageChooseActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
break;
case R.id.add_hrgx://添加工序
BPA_GOODSRECIPE goodsrecipe = GetSelectItemFromValue();
if (goodsrecipe != null) {
bpa_goodsrecipes.add(GetSelectItemFromValue());
gxbz_adapter.setSelectedPosition(bpa_goodsrecipes.size()-1);
gxbz_adapter.notifyDataSetChanged();
datatab_gxbz.smoothScrollToPosition(bpa_goodsrecipes.size()-1);
}
break;
case R.id.add_up://向上添加工序
BPA_GOODSRECIPE goodSrecipeUp = GetSelectItemFromValue();
if (goodSrecipeUp != null) {
int index_update = gxbz_adapter.getSelectedPosition();
if (index_update >= 0 && bpa_goodsrecipes.size()>0) {
bpa_goodsrecipes.add(index_update,GetSelectItemFromValue());
gxbz_adapter.setSelectedPosition(index_update+1);
gxbz_adapter.notifyDataSetChanged();
datatab_gxbz.smoothScrollToPosition(index_update+1);
}else {
ToastUtils.info("请先选择步骤!");
}
}
break;
case R.id.add_down://向下添加工序
BPA_GOODSRECIPE goodSrecipeDown = GetSelectItemFromValue();
if (goodSrecipeDown != null) {
int index_update = gxbz_adapter.getSelectedPosition();
if (index_update >= 0 && bpa_goodsrecipes.size()>0 ) {
bpa_goodsrecipes.add(index_update+1,GetSelectItemFromValue());
gxbz_adapter.notifyDataSetChanged();
datatab_gxbz.smoothScrollToPosition(index_update+1);
}else {
ToastUtils.info("请先选择步骤!");
}
}
break;
case R.id.update_gx://修改工序
int index_update = gxbz_adapter.getSelectedPosition();
if (index_update >= 0 && index_update < bpa_goodsrecipes.size()) {
BPA_GOODSRECIPE obj_update = (BPA_GOODSRECIPE) bpa_goodsrecipes.get(index_update);
String selectname = hrgx.getSelectedItem().toString();
if (!obj_update.processname.equals(selectname)) {
ToastUtils.info("请先选择工序!");
return;
}
bpa_goodsrecipes.set(index_update, GetSelectItemFromValue());
gxbz_adapter.notifyDataSetChanged();
ToastUtils.info("修改步骤" + (index_update + 1) + ":" + obj_update.processname + "成功!");
} else {
ToastUtils.info("请先选择步骤!");
}
break;
case R.id.delete_gx://删除工序
int index_delete = gxbz_adapter.getSelectedPosition();
if (index_delete >= 0 && index_delete < bpa_goodsrecipes.size()) {
BPA_GOODSRECIPE obj_delete = (BPA_GOODSRECIPE) bpa_goodsrecipes.get(index_delete);
bpa_goodsrecipes.remove(obj_delete);
gxbz_adapter.notifyDataSetChanged();

//移动光标
if (index_delete - 1 >= 0) {
SetSelectPos(index_delete - 1);
}
ToastUtils.info("删除工序" + obj_delete.processname + "成功!");
} else {
ToastUtils.info("请先选择工序!");
}
break;
case R.id.shangyi://上移
int index_up = gxbz_adapter.getSelectedPosition();
;
if (index_up > 0) {
BPA_GOODSRECIPE obj_up = (BPA_GOODSRECIPE) bpa_goodsrecipes.get(index_up);
bpa_goodsrecipes.remove(obj_up);
bpa_goodsrecipes.add(index_up - 1, obj_up);
gxbz_adapter.notifyDataSetChanged();
datatab_gxbz.smoothScrollToPosition(index_up - 1);
//移动光标
SetSelectPos(index_up - 1);
} else {
ToastUtils.info("已经最顶部!");
}
break;
case R.id.xiayi://下移
int index_down = gxbz_adapter.getSelectedPosition();
if (index_down < bpa_goodsrecipes.size() - 1 && index_down >= 0) {
BPA_GOODSRECIPE obj_down = (BPA_GOODSRECIPE) bpa_goodsrecipes.get(index_down);
bpa_goodsrecipes.remove(obj_down);
bpa_goodsrecipes.add(index_down + 1, obj_down);
gxbz_adapter.notifyDataSetChanged();
datatab_gxbz.smoothScrollToPosition(index_down + 1);
//移动光标
SetSelectPos(index_down + 1);
} else {
ToastUtils.info("已经最底部!");
}
break;
case R.id.caozuomoshi://操作模式
AlertDialogUtils.showTipDialog(this,"温馨提示!","功能暂未开通哦...",null);
// Intent intent1 = new Intent(getContext(), DiyMemoryActivity.class);
// intent1.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
// startActivity(intent1);
break;
case R.id.shengchengnewcaipu:
String name1 = edittext.getText().toString();
if (name1.isEmpty()) {
ToastUtils.info("菜谱名称不能为空!");
return;
} else {
boolean isSucess = QueryDB.GetGoodsIs(name1);
if (isSucess) {
ToastUtils.info("菜谱名称已存在!");
return;
}
//按钮点击
String title = "生成菜谱操作提示!";
String message = "请问客官确定要生成[" + name1 + "]菜谱吗?";
// AlertDialogUtils.showDialog(view.getContext(), title, message, new QMUIDialogAction.ActionListener() {
// @Override
// public void onClick(QMUIDialog dialog, int index) {
// int sc = 60 * 3;
// if (!zzsc.getText().toString().isEmpty() && !zzsc.getText().toString().equals("0")) {
// sc = Integer.parseInt(zzsc.getText().toString());
// }
//
// ArrayList<BPA_GOODS> goods = QueryDB.GetGoodsALL();
// BPA_GOODS good1 = new BPA_GOODS();
// good1.name = name1;
// good1.status = 1;
// good1.sort = goods.size() + 1;
// good1.maketime = sc;
// good1.issc = check.isChecked() ? 1 : 0;
// good1.url = good.url;
// QueryDB.AddGoods(good1);
// for (int k = 0; k < bpa_goodsrecipes.size(); k++) {
// BPA_GOODSRECIPE item = bpa_goodsrecipes.get(k);
// item.id = java.util.UUID.randomUUID().toString();
// item.goodsID = good1.id;
// item.sort = k + 1;
// QueryDB.AddGoodsSrecipe(item);
// }
// ToastUtils.info("菜谱复刻成功!");
// dialog.dismiss();
// MessageManager.getInstance().sendMessage(MessageName.ScGood, "Good");
// finish();
// }
// });
AlertDialogUtils.showCancelAndConfirmDialog(this,R.layout.dialog_with_cancel_confirm, new XComDialog.OnDialogListener(){

@Override
public void onDialogClick(View layoutView, XComDialog xCom) {
TextView tvTitle = layoutView.findViewById(R.id.tv_title);
TextView tvContent = layoutView.findViewById(R.id.tv_content);
TextView tvCancel = layoutView.findViewById(R.id.tv_cancel);
TextView tvConfirm = layoutView.findViewById(R.id.tv_confirm);
// DisplayManager.scaleView(layoutView.findViewById(R.id.fl_content));
DisplayManager.scaleView(layoutView.findViewById(R.id.rl_btn));
DisplayManager.scaleView(tvTitle);
DisplayManager.scaleView(tvContent);
DisplayManager.scaleView(tvCancel);
DisplayManager.scaleView(tvConfirm);

tvTitle.setText(getString(R.string.tip_create_menu_title));
tvContent.setText(getString(R.string.tip_create_menu_content,name1));
tvCancel.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
xCom.dismissX();
}
});
tvConfirm.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
int sc = 60 * 3;
if (!zzsc.getText().toString().isEmpty() && !zzsc.getText().toString().equals("0")) {
sc = Integer.parseInt(zzsc.getText().toString());
}

ArrayList<BPA_GOODS_OLD> goods = QueryDB.GetGoodsALL();
BPA_GOODS_OLD good1 = new BPA_GOODS_OLD();
good1.name = name1;
good1.status = 1;
good1.sort = goods.size() + 1;
good1.maketime = sc;
good1.issc = check.isChecked() ? 1 : 0;
good1.url = picUrl;
QueryDB.AddGoods(good1);
for (int k = 0; k < bpa_goodsrecipes.size(); k++) {
BPA_GOODSRECIPE item = bpa_goodsrecipes.get(k);
item.id = java.util.UUID.randomUUID().toString();
item.goodsID = good1.id;
item.sort = k + 1;
QueryDB.AddGoodsSrecipe(item);
}
QueryDB.UpdateGoodsMakeTime(good1.id, CookTimeUtils.measureCookTime(bpa_goodsrecipes));
ToastUtils.info("菜谱复刻成功!");
xCom.dismissX();
MessageManager.getInstance().sendMessage(MessageName.ScGood, "Good");
finish();
}
});
}
});
}
break;
case R.id.shengchengcaipu://修改菜谱
String name = edittext.getText().toString();
if (name.isEmpty()) {
ToastUtils.info("菜谱名称不能为空!");
return;
} else {
if(good == null){
ToastUtils.info("请先生成菜谱!");
return;
}
boolean isSucess = QueryDB.GetGoodsIs(name, good.id);
if (isSucess) {
ToastUtils.info("菜谱名称已存在!");
return;
}
//按钮点击
// String title = "保存菜谱操作提示!";
// String message = "请问客官确定要保存[" + name + "]菜谱吗?";
// AlertDialogUtils.showDialog(view.getContext(), title, message, new QMUIDialogAction.ActionListener() {
// @Override
// public void onClick(QMUIDialog dialog, int index) {
// int sc = 60 * 3;
// if (!zzsc.getText().toString().isEmpty() && !zzsc.getText().toString().equals("0")) {
// sc = Integer.parseInt(zzsc.getText().toString());
// }
// good.maketime = sc;
// good.issc = check.isChecked() ? 1 : 0;
// good.name = name;
// QueryDB.UpdateGoods(good);
// ArrayList<BPA_GOODSRECIPE> pe = QueryDB.GetGoodsSrecipeID(good.id);
// for (BPA_GOODSRECIPE item : pe) {
// QueryDB.DeleteGoodsSrecipe(item);
// }
// for (int k = 0; k < bpa_goodsrecipes.size(); k++) {
// BPA_GOODSRECIPE item = bpa_goodsrecipes.get(k);
// item.goodsID = good.id;
// item.sort = k + 1;
// QueryDB.AddGoodsSrecipe(item);
// }
// ToastUtils.info("菜谱修改成功!");
// dialog.dismiss();
// MessageManager.getInstance().sendMessage(MessageName.ScGood, "Good");
// finish();
// }
// });
AlertDialogUtils.showCancelAndConfirmDialog(this,R.layout.dialog_with_cancel_confirm, new XComDialog.OnDialogListener(){

@Override
public void onDialogClick(View layoutView, XComDialog xCom) {
TextView tvTitle = layoutView.findViewById(R.id.tv_title);
TextView tvContent = layoutView.findViewById(R.id.tv_content);
TextView tvCancel = layoutView.findViewById(R.id.tv_cancel);
TextView tvConfirm = layoutView.findViewById(R.id.tv_confirm);
DisplayManager.scaleView(layoutView.findViewById(R.id.rl_btn));
DisplayManager.scaleView(tvTitle);
DisplayManager.scaleView(tvContent);
DisplayManager.scaleView(tvCancel);
DisplayManager.scaleView(tvConfirm);

tvTitle.setText(getString(R.string.tip_save_menu_title));
tvContent.setText(getString(R.string.tip_save_menu_content,name));
tvCancel.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
xCom.dismissX();
}
});
tvConfirm.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
int sc = 60 * 3;
if (!zzsc.getText().toString().isEmpty() && !zzsc.getText().toString().equals("0")) {
sc = Integer.parseInt(zzsc.getText().toString());
}
good.maketime = sc;
good.issc = check.isChecked() ? 1 : 0;
good.name = name;
QueryDB.UpdateGoods(good);
ArrayList<BPA_GOODSRECIPE> pe = QueryDB.GetGoodsSrecipeID(good.id);
for (BPA_GOODSRECIPE item : pe) {
QueryDB.DeleteGoodsSrecipe(item);
}
for (int k = 0; k < bpa_goodsrecipes.size(); k++) {
BPA_GOODSRECIPE item = bpa_goodsrecipes.get(k);
item.goodsID = good.id;
item.sort = k + 1;
QueryDB.AddGoodsSrecipe(item);
}
QueryDB.UpdateGoodsMakeTime(good.id, CookTimeUtils.measureCookTime(bpa_goodsrecipes));
ToastUtils.info("菜谱修改成功!");
xCom.dismissX();
MessageManager.getInstance().sendMessage(MessageName.ScGood, "Good");
finish();
}
});
}
});
}
break;
}
}

public void SetSelectPos(int index) {
//移动光标
gxbz_adapter.setSelectedPosition(index);
gxbz_adapter.notifyDataSetInvalidated();
}

@Override
public void onDestroy() {
super.onDestroy();
MessageManager.getInstance().unRegisterMessageReceiver(this);
}

@Override
protected boolean canDragBack() {
return false;
}

}

app/src/main/java/com/bonait/bnframework/modules/home/fragment/from/DiyUpdateActivity.java → app/src/main/java/com/bonait/bnframework/ViewModel/ActivityViewModel/DiyUpdateActivity.java Ver fichero

@@ -1,9 +1,7 @@
package com.bonait.bnframework.modules.home.fragment.from;
package com.bonait.bnframework.ViewModel.ActivityViewModel;

import static com.bonait.bnframework.MainApplication.getContext;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
@@ -21,30 +19,26 @@ import android.widget.Spinner;

import com.bonait.bnframework.R;
import com.bonait.bnframework.common.base.BaseActivity;
import com.bonait.bnframework.common.constant.DataBus;
import com.bonait.bnframework.common.constant.MessageName;
import com.bonait.bnframework.common.db.QueryDB;
import com.bonait.bnframework.common.db.mode.BPA_GOODS;
import com.bonait.bnframework.common.db.mode.BPA_GOODS_OLD;
import com.bonait.bnframework.common.db.mode.BPA_GOODSRECIPE;
import com.bonait.bnframework.common.db.mode.BPA_MATERIAL;
import com.bonait.bnframework.common.db.mode.BPA_PROCESS;
import com.bonait.bnframework.common.db.mode.BPA_PROCESSModel;
import com.bonait.bnframework.common.helper.I.MyClickListener;
import com.bonait.bnframework.common.helper.MyImage;
import com.bonait.bnframework.common.image.MyBitmapUtils;
import com.bonait.bnframework.common.message.MessageLooper;
import com.bonait.bnframework.common.message.MessageManager;
import com.bonait.bnframework.common.utils.AlertDialogUtils;
import com.bonait.bnframework.common.utils.ToastUtils;
import com.bonait.bnframework.modules.home.adapter.gongxubuzhou_adapter;
import com.bonait.bnframework.modules.home.fragment.mode.fragment_gx;
import com.bonait.bnframework.modules.home.fragment.mode.item_gx;
import com.qmuiteam.qmui.widget.QMUITopBar;
import com.bonait.bnframework.ViewModel.Adapter.gongxubuzhou_adapter;
import com.bonait.bnframework.ViewModel.CustomView.fragment_gx;
import com.bonait.bnframework.ViewModel.CustomView.item_gx;
import com.qmuiteam.qmui.widget.QMUITopBarLayout;
import com.qmuiteam.qmui.widget.dialog.QMUIDialog;
import com.qmuiteam.qmui.widget.dialog.QMUIDialogAction;
import com.youth.banner.Banner;

import java.net.IDN;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
@@ -95,7 +89,7 @@ public class DiyUpdateActivity extends BaseActivity {
/**
* 当前商品
*/
public BPA_GOODS good=null;
public BPA_GOODS_OLD good=null;

@Override
protected void onCreate(Bundle savedInstanceState) {
@@ -173,6 +167,22 @@ public class DiyUpdateActivity extends BaseActivity {
}
}
});

//图标选择
MessageManager.getInstance().registerMessageReceiver(this, MessageName.DIY, new MessageLooper.OnMessageListener() {
@Override
public void onMessage(Object msg) {
if (msg != null) {
bpa_goodsrecipes.clear();
for(BPA_GOODSRECIPE item: DataBus.getInstance().bpa_goodsrecipes)
{
bpa_goodsrecipes.add(item);
}
zzsc.setText(DataBus.getInstance().TimeOut+"");
gxbz_adapter.notifyDataSetChanged();
}
}
});
}

/**
@@ -501,7 +511,9 @@ public class DiyUpdateActivity extends BaseActivity {
}
break;
case R.id.caozuomoshi://操作模式
ToastUtils.info("操作模式");
Intent intent1 = new Intent(getContext(), DiyMemoryActivity.class);
intent1.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent1);
break;
case R.id.shengchengnewcaipu:
String name1=edittext.getText().toString();
@@ -529,8 +541,8 @@ public class DiyUpdateActivity extends BaseActivity {
sc=Integer.parseInt(zzsc.getText().toString());
}

ArrayList<BPA_GOODS> goods=QueryDB.GetGoodsALL();
BPA_GOODS good1=new BPA_GOODS();
ArrayList<BPA_GOODS_OLD> goods=QueryDB.GetGoodsALL();
BPA_GOODS_OLD good1=new BPA_GOODS_OLD();
good1.name=name1;
good1.status=1;
good1.sort=goods.size()+1;

app/src/main/java/com/bonait/bnframework/modules/home/fragment/from/FileActivity.java → app/src/main/java/com/bonait/bnframework/ViewModel/ActivityViewModel/FileActivity.java Ver fichero

@@ -1,4 +1,4 @@
package com.bonait.bnframework.modules.home.fragment.from;
package com.bonait.bnframework.ViewModel.ActivityViewModel;

import androidx.appcompat.app.AppCompatActivity;
import androidx.core.content.ContextCompat;

app/src/main/java/com/bonait/bnframework/modules/home/fragment/from/ImageChooseActivity.java → app/src/main/java/com/bonait/bnframework/ViewModel/ActivityViewModel/ImageChooseActivity.java Ver fichero

@@ -1,7 +1,5 @@
package com.bonait.bnframework.modules.home.fragment.from;
package com.bonait.bnframework.ViewModel.ActivityViewModel;

import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.SearchView;
import androidx.recyclerview.widget.RecyclerView;

import android.os.Bundle;
@@ -10,18 +8,13 @@ import android.view.View;

import com.bonait.bnframework.R;
import com.bonait.bnframework.common.base.BaseActivity;
import com.bonait.bnframework.common.constant.DataBus;
import com.bonait.bnframework.common.constant.MessageName;
import com.bonait.bnframework.common.db.mode.BPA_GOODS;
import com.bonait.bnframework.common.helper.AES;
import com.bonait.bnframework.common.helper.I.MyClickListener;
import com.bonait.bnframework.common.message.MessageManager;
import com.bonait.bnframework.common.utils.ToastUtils;
import com.bonait.bnframework.common.view.MyLayoutManager;
import com.bonait.bnframework.modules.home.adapter.image_sp_adapter;
import com.bonait.bnframework.modules.home.adapter.sp_adapter;
import com.bonait.bnframework.modules.home.fragment.mode.image_sp;
import com.qmuiteam.qmui.widget.QMUITopBar;
import com.bonait.bnframework.ViewModel.Adapter.image_sp_adapter;
import com.bonait.bnframework.ViewModel.CustomView.image_sp;
import com.qmuiteam.qmui.widget.QMUITopBarLayout;

import java.io.File;

app/src/main/java/com/bonait/bnframework/modules/welcome/activity/LoginActivity.java → app/src/main/java/com/bonait/bnframework/ViewModel/ActivityViewModel/LoginActivity.java Ver fichero

@@ -1,4 +1,4 @@
package com.bonait.bnframework.modules.welcome.activity;
package com.bonait.bnframework.ViewModel.ActivityViewModel;

import android.animation.ObjectAnimator;
import android.annotation.SuppressLint;
@@ -25,23 +25,20 @@ import android.widget.RelativeLayout;
import com.bonait.bnframework.R;
import com.bonait.bnframework.business.ConfigData;
import com.bonait.bnframework.common.base.BaseActivity;
import com.bonait.bnframework.common.bg.SnowView;
import com.bonait.bnframework.common.constant.ConfigName;
import com.bonait.bnframework.common.constant.Constants;
import com.bonait.bnframework.common.constant.SPConstants;
import com.bonait.bnframework.common.db.QueryDB;
import com.bonait.bnframework.common.db.mode.BPA_USER;
import com.bonait.bnframework.common.helper.ActiveMax;
import com.bonait.bnframework.common.utils.AlertDialogUtils;
import com.bonait.bnframework.common.utils.AnimationToolUtils;
import com.bonait.bnframework.common.utils.AppUtils;
import com.bonait.bnframework.common.utils.Des3Utils;
import com.bonait.bnframework.common.utils.DisplayManager;
import com.bonait.bnframework.common.utils.KeyboardToolUtils;
import com.bonait.bnframework.common.utils.PreferenceUtils;
import com.bonait.bnframework.common.utils.ToastUtils;
import com.bonait.bnframework.manager.ActivityLifecycleManager;
import com.bonait.bnframework.modules.home.activity.BottomNavigation2Activity;
import com.bonait.bnframework.modules.welcome.model.AppLoginPo;
import com.bonait.bnframework.Model.AppLoginPo;
import com.bonait.bnframework.test.TestActivity;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.model.HttpParams;
@@ -62,8 +59,8 @@ import butterknife.OnClick;

public class LoginActivity extends BaseActivity implements Validator.ValidationListener {

@BindView(R.id.logo)
ImageView mLogo;
// @BindView(R.id.logo)
// ImageView mLogo;

@Order(1)
@NotEmpty(message = "用户名不能为空")
@@ -89,6 +86,12 @@ public class LoginActivity extends BaseActivity implements Validator.ValidationL
LinearLayout mContent;
@BindView(R.id.scrollView)
NestedScrollView mScrollView;
@BindView(R.id.imgAccount)
ImageView imgAccount;
@BindView(R.id.imgPass)
ImageView imgPass;
@BindView(R.id.rl_title)
RelativeLayout rl_title;

private long exitTime = 0;
private int screenHeight = 0;//屏幕高度
@@ -107,7 +110,7 @@ public class LoginActivity extends BaseActivity implements Validator.ValidationL
ButterKnife.bind(this);

QMUIStatusBarHelper.setStatusBarLightMode(this);
initView();
validator = new Validator(this);
validator.setValidationListener(this);

@@ -116,6 +119,23 @@ public class LoginActivity extends BaseActivity implements Validator.ValidationL
initData();
}

/**
* 初始化视图
* 对布局进行缩放
*/
private void initView(){
DisplayManager.scaleView(mEtAccount);
DisplayManager.scaleView(mEtPassword);
DisplayManager.scaleView(mCleanPassword);
DisplayManager.scaleView(mIvCleanAccount);
DisplayManager.scaleView(mIvShowPwd);
DisplayManager.scaleView(cbCheckbox);
DisplayManager.scaleView(mContent);
DisplayManager.scaleView(imgAccount);
DisplayManager.scaleView(imgPass);
DisplayManager.scaleView(rl_title);
}

/**
* 设置
*/
@@ -124,17 +144,17 @@ public class LoginActivity extends BaseActivity implements Validator.ValidationL
mEtAccount.requestFocus();
getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);

if(ConfigName.getInstance().IsPortraitScreen)//竖屏
{
RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(mScrollView.getLayoutParams());
lp.setMargins(15, 80, 15, 0);
mScrollView.setLayoutParams(lp);
}else
{
RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(mScrollView.getLayoutParams());
lp.setMargins(15, 40, 15, 0);
mScrollView.setLayoutParams(lp);
}
// if(ConfigName.getInstance().IsPortraitScreen)//竖屏
// {
// RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(mScrollView.getLayoutParams());
// lp.setMargins(15, 80, 15, 0);
// mScrollView.setLayoutParams(lp);
// }else
// {
// RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(mScrollView.getLayoutParams());
// lp.setMargins(15, 40, 15, 0);
// mScrollView.setLayoutParams(lp);
// }
}

@OnClick({R.id.iv_clean_account, R.id.clean_password, R.id.iv_show_pwd,R.id.forget_password, R.id.btn_login})
@@ -331,7 +351,7 @@ public class LoginActivity extends BaseActivity implements Validator.ValidationL
// 退出界面之前把状态栏还原为白色字体与图标
QMUIStatusBarHelper.setStatusBarDarkMode(LoginActivity.this);
Intent intent = new Intent(LoginActivity.this, TestActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP|Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
// 结束所有Activity
ActivityLifecycleManager.get().finishAllActivity();
@@ -345,9 +365,20 @@ public class LoginActivity extends BaseActivity implements Validator.ValidationL
KeyboardToolUtils.hideSoftInput(LoginActivity.this);
// 退出界面之前把状态栏还原为白色字体与图标
QMUIStatusBarHelper.setStatusBarDarkMode(LoginActivity.this);
Intent intent = new Intent(LoginActivity.this, BottomNavigation2Activity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);


if(ConfigName.getInstance().user.name.equals("admin") || ConfigName.getInstance().user.account.equals("admin") || ConfigName.getInstance().user.userID.equals("超级管理员"))
{
Intent intent = new Intent(LoginActivity.this, BottomNavigation2Activity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP|Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
}else
{
Intent intent = new Intent(LoginActivity.this, BottomNavigationNewActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP|Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
}
ToastUtils.info("登录成功!");
// 结束所有Activity
ActivityLifecycleManager.get().finishAllActivity();
}
@@ -430,7 +461,7 @@ public class LoginActivity extends BaseActivity implements Validator.ValidationL
mAnimatorTranslateY.setDuration(300);
mAnimatorTranslateY.setInterpolator(new LinearInterpolator());
mAnimatorTranslateY.start();
AnimationToolUtils.zoomIn(mLogo, scale, dist);
//AnimationToolUtils.zoomIn(mLogo, scale, dist);
}

} else if (oldBottom != 0 && bottom != 0 && (bottom - oldBottom > keyHeight)) {
@@ -440,7 +471,7 @@ public class LoginActivity extends BaseActivity implements Validator.ValidationL
mAnimatorTranslateY.setInterpolator(new LinearInterpolator());
mAnimatorTranslateY.start();
//键盘收回后,logo恢复原来大小,位置同样回到初始位置
AnimationToolUtils.zoomOut(mLogo, scale);
//AnimationToolUtils.zoomOut(mLogo, scale);
}
}
}

app/src/main/java/com/bonait/bnframework/modules/mine/fragment/from/NoticeActivity.java → app/src/main/java/com/bonait/bnframework/ViewModel/ActivityViewModel/NoticeActivity.java Ver fichero

@@ -1,4 +1,4 @@
package com.bonait.bnframework.modules.mine.fragment.from;
package com.bonait.bnframework.ViewModel.ActivityViewModel;

import androidx.core.content.ContextCompat;
import androidx.appcompat.app.AppCompatActivity;

app/src/main/java/com/bonait/bnframework/modules/home/fragment/from/SzActivity.java → app/src/main/java/com/bonait/bnframework/ViewModel/ActivityViewModel/SzActivity.java Ver fichero

@@ -1,21 +1,27 @@
package com.bonait.bnframework.modules.home.fragment.from;
package com.bonait.bnframework.ViewModel.ActivityViewModel;

import androidx.annotation.NonNull;

import com.bonait.bnframework.common.constant.ConfigName;
import com.bonait.bnframework.common.utils.DisplayManager;
import com.bonait.bnframework.common.utils.ToastUtils;
import com.google.android.material.bottomnavigation.BottomNavigationView;
import androidx.viewpager.widget.ViewPager;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RelativeLayout;

import com.bonait.bnframework.R;
import com.bonait.bnframework.common.base.BaseActivity;
import com.bonait.bnframework.modules.home.adapter.FragmentAdapter;
import com.bonait.bnframework.modules.home.fragment.from.fragment.SystemDeviceinFragment;
import com.bonait.bnframework.modules.home.fragment.from.fragment.SystemSeasoningsetFragment;
import com.bonait.bnframework.modules.home.fragment.from.fragment.SystemSystemsetFragment;
import com.bonait.bnframework.modules.home.fragment.from.fragment.systeminternetfragment;
import com.qmuiteam.qmui.widget.QMUITopBar;
import com.bonait.bnframework.ViewModel.Adapter.FragmentAdapter;
import com.bonait.bnframework.ViewModel.FragmentViewModel.SystemDeviceinFragment;
import com.bonait.bnframework.ViewModel.FragmentViewModel.SystemSeasoningsetFragment;
import com.bonait.bnframework.ViewModel.FragmentViewModel.SystemSystemsetFragment;
import com.bonait.bnframework.ViewModel.FragmentViewModel.systeminternetfragment;
import com.qmuiteam.qmui.widget.QMUITopBarLayout;
import com.qmuiteam.qmui.widget.QMUIViewPager;

@@ -29,12 +35,21 @@ public class SzActivity extends BaseActivity {
BottomNavigationView bottomNavigationView;
@BindView(R.id.viewpager)
QMUIViewPager viewPager;

@BindView(R.id.quanxian)
RelativeLayout quanxian;//权限显示
@BindView(R.id.edittext_quanxian)
EditText edittext_quanxian;//权限密码
@BindView(R.id.quanxianmima)
Button quanxianmima;//权限密码

private MenuItem menuItem;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sz);//属性绑定
ButterKnife.bind(this);
initView();
initTopBar();

initFragment();
@@ -43,6 +58,15 @@ public class SzActivity extends BaseActivity {
viewPager.setOffscreenPageLimit(4);
bottomNavigationView.setOnNavigationItemSelectedListener(mOnNavigationItemSelectedListener);
}

private void initView(){
DisplayManager.scaleView(edittext_quanxian);
DisplayManager.scaleView(quanxianmima);
if(ConfigName.TEST){
edittext_quanxian.setText("123456");
}
}

private void initTopBar() {
mTopBar.setTitle("系统设置");
mTopBar.addLeftImageButton(R.mipmap.fanhui,R.id.topbar).setOnClickListener(new View.OnClickListener() {
@@ -51,6 +75,27 @@ public class SzActivity extends BaseActivity {
finish();
}
});

quanxianmima.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
String s=edittext_quanxian.getText().toString();
if (s==null ||s.isEmpty())
{
ToastUtils.warning("权限密码不能为空!");
}else
{
if(s.equals(ConfigName.getInstance().user.pass))
{
quanxian.setVisibility(View.GONE);
viewPager.setVisibility(View.VISIBLE);
}else
{
ToastUtils.warning("权限密码不正确!");
}
}
}
});
}

/**

+ 338
- 0
app/src/main/java/com/bonait/bnframework/ViewModel/ActivityViewModel/UserActivity.java Ver fichero

@@ -0,0 +1,338 @@
package com.bonait.bnframework.ViewModel.ActivityViewModel;

import android.content.DialogInterface;
import android.os.Bundle;
import android.text.InputType;
import android.view.View;
import android.widget.Button;
import android.widget.ListView;

import com.bonait.bnframework.R;
import com.bonait.bnframework.common.base.BaseActivity;
import com.bonait.bnframework.common.constant.ConfigName;
import com.bonait.bnframework.common.db.QueryDB;
import com.bonait.bnframework.common.db.mode.BPA_USER;
import com.bonait.bnframework.common.helper.I.MyClickListener;
import com.bonait.bnframework.common.utils.AlertDialogUtils;
import com.bonait.bnframework.common.utils.ToastUtils;
import com.bonait.bnframework.common.view.AddUserDialog;
import com.bonait.bnframework.ViewModel.Adapter.user_adapter;
import com.qmuiteam.qmui.widget.QMUITopBarLayout;
import com.qmuiteam.qmui.widget.dialog.QMUIDialog;
import com.qmuiteam.qmui.widget.dialog.QMUIDialogAction;

import java.util.ArrayList;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class UserActivity extends BaseActivity implements MyClickListener {
@BindView(R.id.topbar)
QMUITopBarLayout mTopBar;

@BindView(R.id.add_wl)
Button add_wl;
@BindView(R.id.datatab)
ListView datatab;
/**
* 用户数据
*/
ArrayList<BPA_USER> bpa_users = new ArrayList<>();

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_user);
//属性绑定
ButterKnife.bind(this);
initTopBar();
InitView();
}

private void initTopBar() {
mTopBar.setTitle("账户管理");
mTopBar.addLeftImageButton(R.mipmap.fanhui, R.id.topbar).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
finish();
}
});
}

/**
* 初始化界面
*/
public void InitView() {
Initdata();
}

@OnClick({R.id.add_wl, R.id.synchronous})
public void onViewClicked(View view) {
switch (view.getId()) {
case R.id.add_wl://新增用户

final AddUserDialog editDialog = new AddUserDialog(this);
editDialog.setTitle("角色列表");
editDialog.setYesOnclickListener("确定", new AddUserDialog.onYesOnclickListener() {
@Override
public void onYesClick(String name, String acc, String pass, String qx) {

if (name.toString().equals("admin") || acc.toString().equals("admin")) {
ToastUtils.warning("不能设置账号为admin!");
return;
}

BPA_USER bpa_user = new BPA_USER();
bpa_user.name = name;
bpa_user.account = acc;
bpa_user.pass = pass;
bpa_user.deviceID = ConfigName.getInstance().DeviceId;
bpa_user.userID =qx;//更改为,用户权限 // 一般用户 研发用户 超级管理员
if(QueryDB.GetUserIsCZ(bpa_user.account,bpa_user.name))
{
ToastUtils.warning("已有该账户,请重新填写账户信息!");
return;
}
QueryDB.AddUser(bpa_user);
ToastUtils.info("新增成功");
Initdata();
editDialog.dismiss();
}
});
editDialog.setNoOnclickListener("取消", new AddUserDialog.onNoOnclickListener() {
@Override
public void onNoClick() {
editDialog.dismiss();
}
});
editDialog.show();
break;

case R.id.synchronous://新增用户

String title = "温馨提示!";
String message = "客官确定要恢复出厂账户吗?";
AlertDialogUtils.showDialog(this, title, message, new QMUIDialogAction.ActionListener() {
@Override
public void onClick(QMUIDialog dialog, int index) {
ArrayList<BPA_USER> users=QueryDB.GetUserALL();
for (BPA_USER item:users)
{
QueryDB.DeleteUser(item);
}
BPA_USER user = new BPA_USER();
user.id = "20230415-fyf";
user.name = "管理员";
user.account = "admin";
user.pass = "123456";
user.deviceID = ConfigName.getInstance().DeviceId;
user.userID = "超级管理员";
user.exp = "管理员";
QueryDB.AddUser(user);

BPA_USER user1 = new BPA_USER();
user1.name = "一般用户";
user1.account = "ybyh";
user1.pass = "123456";
user1.deviceID = ConfigName.getInstance().DeviceId;
user1.userID = "一般用户";
user1.exp = "一般用户";
QueryDB.AddUser(user1);


BPA_USER user2 = new BPA_USER();
user2.name = "研发用户";
user2.account = "yfyh";
user2.pass = "123456";
user2.deviceID = ConfigName.getInstance().DeviceId;
user2.userID = "研发用户";
user2.exp = "研发用户";
QueryDB.AddUser(user2);

ToastUtils.info("恢复出厂成功!");
Initdata();
dialog.dismiss();
}
});
break;
}
}


/**
* 初始化数据加载
*/
public void Initdata() {
try {
bpa_users = QueryDB.GetUserALL();
user_adapter adapter = new user_adapter(getBaseContext(), R.layout.user_item, bpa_users, this);
datatab.setAdapter(adapter);
} catch (Exception e) {

}
}

@Override
public void clickListener(View v, Object data) {
String name = ((BPA_USER) data).name;
String ac = ((BPA_USER) data).account;
if (name.equals("admin") || ac.equals("admin")) {
ToastUtils.warning("对不起,admin账户禁止操作!");
return;
}
switch (v.getId()) {
case R.id.name://修改物料名称按钮
final QMUIDialog.EditTextDialogBuilder builder = new QMUIDialog.EditTextDialogBuilder(this);
builder.setTitle("用户名称")
.setPlaceholder("在此输入用户名称")
.setDefaultText(((BPA_USER) data).name)
.setInputType(InputType.TYPE_CLASS_TEXT)
.addAction("取消", new QMUIDialogAction.ActionListener() {
@Override
public void onClick(QMUIDialog dialog, int index) {
dialog.dismiss();
}
})
.addAction("确定", new QMUIDialogAction.ActionListener() {
@Override
public void onClick(QMUIDialog dialog, int index) {
CharSequence text = builder.getEditText().getText();
if (text != null && text.length() > 0) {
if (text.toString().equals("admin")) {
ToastUtils.warning("不能设置账号为admin!");
return;
}

if(QueryDB.GetUserIsCZ(((BPA_USER) data).account,text.toString()))
{
ToastUtils.warning("已有该账户,请重新填写账户信息!");
return;
}
QueryDB.UpdateUserName(((BPA_USER) data).id, text.toString());
Initdata();
ToastUtils.info("修改成功");
dialog.dismiss();
} else {
//请填入昵称
ToastUtils.warning("不能为空!");
}
}
})
.show();
break;
case R.id.zhanghao://修改物料名称按钮
final QMUIDialog.EditTextDialogBuilder builder1 = new QMUIDialog.EditTextDialogBuilder(this);
builder1.setTitle("用户账号")
.setPlaceholder("在此输入用户账号")
.setDefaultText(((BPA_USER) data).account)
.setInputType(InputType.TYPE_CLASS_TEXT)
.addAction("取消", new QMUIDialogAction.ActionListener() {
@Override
public void onClick(QMUIDialog dialog, int index) {
dialog.dismiss();
}
})
.addAction("确定", new QMUIDialogAction.ActionListener() {
@Override
public void onClick(QMUIDialog dialog, int index) {
CharSequence text = builder1.getEditText().getText();
if (text != null && text.length() > 0) {
if (text.toString().equals("admin")) {
ToastUtils.warning("不能设置账号为admin!");
return;
}
if(QueryDB.GetUserIsCZ(text.toString(),((BPA_USER) data).name))
{
ToastUtils.warning("已有该账户,请重新填写账户信息!");
return;
}

QueryDB.UpdateAccount(((BPA_USER) data).id, text.toString());
Initdata();
ToastUtils.info("修改成功");
dialog.dismiss();
} else {
//请填入昵称
ToastUtils.info("不能为空!");
}
}
})
.show();
break;
case R.id.mima://修改物料名称按钮
final QMUIDialog.EditTextDialogBuilder builder2 = new QMUIDialog.EditTextDialogBuilder(this);
builder2.setTitle("用户密码")
.setPlaceholder("在此输入用户密码")
.setDefaultText(((BPA_USER) data).pass)
.setInputType(InputType.TYPE_CLASS_TEXT)
.addAction("取消", new QMUIDialogAction.ActionListener() {
@Override
public void onClick(QMUIDialog dialog, int index) {
dialog.dismiss();
}
})
.addAction("确定", new QMUIDialogAction.ActionListener() {
@Override
public void onClick(QMUIDialog dialog, int index) {
CharSequence text = builder2.getEditText().getText();
if (text != null && text.length() > 0) {
QueryDB.UpdateUserPass(((BPA_USER) data).id, text.toString());
Initdata();
ToastUtils.info("修改成功");
dialog.dismiss();
} else {
//请填入昵称
ToastUtils.info("不能为空!");
}
}
})
.show();
break;

case R.id.quanxian://修改物料名称按钮
final String [] items=ConfigName.getInstance().UserRole.toArray(new String[0]);
int checkIndex=1;
String qx=((BPA_USER) data).userID;
for (int k=0;k<ConfigName.getInstance().UserRole.size();k++)
{
if(qx!=null && !qx.isEmpty() && qx.contains(items[k]))
{
checkIndex=k;
}
}
new QMUIDialog.CheckableDialogBuilder(this)
.addItems(items, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
String names=items[which];
if (names != null && !names.isEmpty()) {
QueryDB.UpdateUserRole(((BPA_USER) data).id, names);
Initdata();
ToastUtils.info("修改成功");
dialog.dismiss();
} else {
//请填入昵称
ToastUtils.info("不能为空!");
return;
}
dialog.dismiss();
}
})
.setCheckedIndex(checkIndex)
.show();
break;

case R.id.button_item://删除按钮
QueryDB.DeleteUser((BPA_USER) data);
Initdata();
ToastUtils.info("删除成功");
break;
}
}

@Override
public void clickListenerNew(View v, int k, Object data) {

}
}

app/src/main/java/com/bonait/bnframework/modules/welcome/activity/WelcomeActivity.java → app/src/main/java/com/bonait/bnframework/ViewModel/ActivityViewModel/WelcomeActivity.java Ver fichero

@@ -1,4 +1,4 @@
package com.bonait.bnframework.modules.welcome.activity;
package com.bonait.bnframework.ViewModel.ActivityViewModel;

import android.Manifest;
import android.content.Intent;
@@ -6,24 +6,30 @@ import android.os.Bundle;
import android.os.Handler;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.GridLayoutManager;

import android.util.DisplayMetrics;
import android.view.KeyEvent;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.apkfuns.logutils.LogUtils;
import com.bonait.bnframework.HBL.DataUtil.ErrorCodeManager;
import com.bonait.bnframework.R;
import com.bonait.bnframework.business.MainInit;
import com.bonait.bnframework.common.base.BaseActivity;
import com.bonait.bnframework.common.constant.ConfigName;
import com.bonait.bnframework.common.constant.Constants;
import com.bonait.bnframework.common.utils.DisplayManager;
import com.bonait.bnframework.common.utils.ScreenUtils;
import com.bonait.bnframework.manager.ActivityLifecycleManager;
import com.bonait.bnframework.modules.home.activity.BottomNavigation2Activity;
import com.bonait.bnframework.test.TestActivity;
import com.lzy.okgo.OkGo;
import com.qmuiteam.qmui.widget.QMUILoadingView;

import org.w3c.dom.Text;

import butterknife.BindView;
import okhttp3.OkHttpClient;
import pub.devrel.easypermissions.AfterPermissionGranted;
import pub.devrel.easypermissions.EasyPermissions;

public class WelcomeActivity extends BaseActivity {
@@ -37,13 +43,45 @@ public class WelcomeActivity extends BaseActivity {
private final static int SELECT_MODE = 2;
private OkHttpClient.Builder builder;

@BindView(R.id.loading)
QMUILoadingView loading;
@BindView(R.id.desc)
TextView desc;


@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_welcome);
DisplayMetrics dm = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(dm);
int miDisplayWidth = dm.widthPixels;
int miDisplayHeight = dm.heightPixels;
float mfFontDensity = dm.scaledDensity;
float mfScreenDensity = dm.density;
LogUtils.d(" 屏幕宽高 "+"miDisplayWidth=" + miDisplayWidth + ",miDisplayHeight="
+ miDisplayHeight+ "mfFontDensity=" + mfFontDensity+ "mfScreenDensity=" + mfScreenDensity+"densityDpi=" + dm.densityDpi);
initScaleViewDefaultValue();
initView();
initWelcome();
}

private void initView(){
DisplayManager.scaleView(loading);
DisplayManager.scaleView(desc);
}

/**
* 初始化应用界面视图适配基准值
* 应用适配参考值设置尽量提早设置多次设置,避免适配基准失效
*/
private void initScaleViewDefaultValue()
{
DisplayManager.setReferenceMaxWidthHeight(800, 1208);
DisplayManager.updateDisplayInfo(this);
}


private void initWelcome() {
switch (WelcomeActivity.SELECT_MODE) {
case 1:

app/src/main/java/com/bonait/bnframework/modules/home/fragment/from/WhActivity.java → app/src/main/java/com/bonait/bnframework/ViewModel/ActivityViewModel/WhActivity.java Ver fichero

@@ -1,8 +1,10 @@
package com.bonait.bnframework.modules.home.fragment.from;
package com.bonait.bnframework.ViewModel.ActivityViewModel;

import androidx.annotation.NonNull;

import com.bonait.bnframework.modules.home.fragment.from.fragment.SystemCsPLCFragment;
import com.bonait.bnframework.common.constant.ConfigName;
import com.bonait.bnframework.common.utils.ToastUtils;
import com.bonait.bnframework.ViewModel.FragmentViewModel.SystemCsPLCFragment;
import com.google.android.material.bottomnavigation.BottomNavigationView;

import androidx.viewpager.widget.ViewPager;
@@ -10,14 +12,16 @@ import androidx.viewpager.widget.ViewPager;
import android.os.Bundle;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RelativeLayout;

import com.bonait.bnframework.R;
import com.bonait.bnframework.common.base.BaseActivity;
import com.bonait.bnframework.modules.home.adapter.FragmentAdapter;
import com.bonait.bnframework.modules.home.fragment.from.fragment.SystemCsFltlFragment;
import com.bonait.bnframework.modules.home.fragment.from.fragment.SystemCsControlFragment;
import com.bonait.bnframework.modules.home.fragment.from.fragment.SystemCsMonitorFragment;
import com.qmuiteam.qmui.widget.QMUITopBar;
import com.bonait.bnframework.ViewModel.Adapter.FragmentAdapter;
import com.bonait.bnframework.ViewModel.FragmentViewModel.SystemCsFltlFragment;
import com.bonait.bnframework.ViewModel.FragmentViewModel.SystemCsControlFragment;
import com.bonait.bnframework.ViewModel.FragmentViewModel.SystemCsMonitorFragment;
import com.qmuiteam.qmui.widget.QMUITopBarLayout;
import com.qmuiteam.qmui.widget.QMUIViewPager;

@@ -31,6 +35,14 @@ public class WhActivity extends BaseActivity {
BottomNavigationView bottomNavigationView;
@BindView(R.id.viewpager)
QMUIViewPager viewPager;

@BindView(R.id.quanxian)
RelativeLayout quanxian;//权限显示
@BindView(R.id.edittext_quanxian)
EditText edittext_quanxian;//权限密码
@BindView(R.id.quanxianmima)
Button quanxianmima;//权限密码

private MenuItem menuItem;
@Override
protected void onCreate(Bundle savedInstanceState) {
@@ -59,6 +71,27 @@ public class WhActivity extends BaseActivity {
finish();
}
});

quanxianmima.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
String s=edittext_quanxian.getText().toString();
if (s==null ||s.isEmpty())
{
ToastUtils.warning("权限密码不能为空!");
}else
{
if(s.equals(ConfigName.getInstance().user.pass))
{
quanxian.setVisibility(View.GONE);
viewPager.setVisibility(View.VISIBLE);
}else
{
ToastUtils.warning("权限密码不正确!");
}
}
}
});
}
FragmentAdapter fragmentAdapter=null;
/**

app/src/main/java/com/bonait/bnframework/modules/home/adapter/FragmentAdapter.java → app/src/main/java/com/bonait/bnframework/ViewModel/Adapter/FragmentAdapter.java Ver fichero

@@ -1,4 +1,4 @@
package com.bonait.bnframework.modules.home.adapter;
package com.bonait.bnframework.ViewModel.Adapter;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;

app/src/main/java/com/bonait/bnframework/modules/home/adapter/gongxubuzhou_adapter.java → app/src/main/java/com/bonait/bnframework/ViewModel/Adapter/gongxubuzhou_adapter.java Ver fichero

@@ -1,4 +1,4 @@
package com.bonait.bnframework.modules.home.adapter;
package com.bonait.bnframework.ViewModel.Adapter;

import android.content.Context;
import android.graphics.Color;
@@ -15,6 +15,7 @@ import com.bonait.bnframework.R;
import com.bonait.bnframework.common.db.mode.BPA_GOODSRECIPE;
import com.bonait.bnframework.common.db.res.lcMode;
import com.bonait.bnframework.common.helper.I.MyClickListener;
import com.bonait.bnframework.common.utils.DisplayManager;

import java.util.List;

@@ -53,7 +54,8 @@ public class gongxubuzhou_adapter extends ArrayAdapter<BPA_GOODSRECIPE> {
//分别获取 image view 和 textview 的实例

TextView text = view.findViewById(R.id.text);
text.setText((position+1)+"、"+lc.processms);
DisplayManager.scaleView(text);
text.setText((position+1)+"、"+lc.processname);

if (selectedPosition == position) {
text.setSelected(true);

+ 67
- 0
app/src/main/java/com/bonait/bnframework/ViewModel/Adapter/gongxubuzhou_adapter1.java Ver fichero

@@ -0,0 +1,67 @@
package com.bonait.bnframework.ViewModel.Adapter;

import android.content.Context;
import android.graphics.Color;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.bonait.bnframework.R;
import com.bonait.bnframework.common.constant.DataBus;
import com.bonait.bnframework.common.db.mode.BPA_GOODSRECIPE;
import com.bonait.bnframework.common.helper.I.MyClickListener;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;

public class gongxubuzhou_adapter1 extends ArrayAdapter<BPA_GOODSRECIPE> {
/**
* 内部点击事件
*/
private ArrayList<BPA_GOODSRECIPE> datas= new ArrayList<>();

private int selectedPosition = -1;// 选中的位置
int resource1;
public gongxubuzhou_adapter1(@NonNull Context context, int resource, @NonNull ArrayList<BPA_GOODSRECIPE> objects) {
super(context, resource, objects);
datas=objects;
this.resource1=resource;
}

public int getSelectedPosition()
{
return selectedPosition;
}

public void setSelectedPosition(int position) {
selectedPosition = position;
}
//每个子项被滚动到屏幕内的时候会被调用
@NonNull
@Override
public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
BPA_GOODSRECIPE lc = (BPA_GOODSRECIPE) getItem(position);//得到当前项选中item实例
//为每一个子项加载设定的布局
View view = LayoutInflater.from(getContext()).inflate(resource1, parent, false);
//分别获取 image view 和 textview 的实例

TextView text = view.findViewById(R.id.text);

if(lc.processname.equals("液体料"))
{
text.setText((new DecimalFormat("00").format(datas.size()- position))
+"、"+lc.processname+" " +lc.processvalue);
}else
{
text.setText((new DecimalFormat("00").format(datas.size()- position))
+"、"+lc.processname+" "+" " +lc.processvalue);
}
return view;
}
}

+ 56
- 0
app/src/main/java/com/bonait/bnframework/ViewModel/Adapter/gongxubuzhou_adapter2.java Ver fichero

@@ -0,0 +1,56 @@
package com.bonait.bnframework.ViewModel.Adapter;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.bonait.bnframework.R;
import com.bonait.bnframework.common.db.mode.BPA_GOODSRECIPE;

import java.util.ArrayList;

public class gongxubuzhou_adapter2 extends ArrayAdapter<BPA_GOODSRECIPE> {
/**
* 内部点击事件
*/
private ArrayList<BPA_GOODSRECIPE> datas= new ArrayList<>();

private int selectedPosition = -1;// 选中的位置
int resource1;
public gongxubuzhou_adapter2(@NonNull Context context, int resource, @NonNull ArrayList<BPA_GOODSRECIPE> objects) {
super(context, resource, objects);
datas=objects;
this.resource1=resource;
}

public int getSelectedPosition()
{
return selectedPosition;
}

public void setSelectedPosition(int position) {
selectedPosition = position;
}
//每个子项被滚动到屏幕内的时候会被调用
@NonNull
@Override
public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
BPA_GOODSRECIPE lc = (BPA_GOODSRECIPE) getItem(position);//得到当前项选中item实例
//为每一个子项加载设定的布局
View view = LayoutInflater.from(getContext()).inflate(resource1, parent, false);
//分别获取 image view 和 textview 的实例
TextView num = view.findViewById(R.id.num);
TextView name = view.findViewById(R.id.name);
TextView text = view.findViewById(R.id.text);
num.setText((position+1)+"");
name.setText(lc.processname+"");
text.setText(lc.processvalue+"");
return view;
}
}

+ 248
- 0
app/src/main/java/com/bonait/bnframework/ViewModel/Adapter/good_adapter.java Ver fichero

@@ -0,0 +1,248 @@
package com.bonait.bnframework.ViewModel.Adapter;

import android.app.Activity;
import android.content.Context;
import android.content.ContextWrapper;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.bonait.bnframework.R;
import com.bonait.bnframework.business.ConfigData;
import com.bonait.bnframework.common.constant.ConfigName;
import com.bonait.bnframework.common.db.QueryDB;
import com.bonait.bnframework.common.helper.I.MyClickListener;
import com.bonait.bnframework.common.image.MyBitmapUtils;
import com.bonait.bnframework.common.utils.AlertDialogUtils;
import com.bonait.bnframework.common.utils.ToastUtils;
import com.bonait.bnframework.ViewModel.CustomView.SectionItem;
import com.qmuiteam.qmui.widget.dialog.QMUIDialog;
import com.qmuiteam.qmui.widget.dialog.QMUIDialogAction;

import java.util.ArrayList;

public class good_adapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
//图标
private MyBitmapUtils myBitmapUtils = new MyBitmapUtils();
private final LayoutInflater mLayoutInflater;

private Context context;

ArrayList<SectionItem> liaos = new ArrayList<>();

/**
* 点击事件
*/
public MyClickListener mListener = null;

public good_adapter(Context context, ArrayList<SectionItem> data, MyClickListener _mListener) {
this.context = context;
mLayoutInflater = LayoutInflater.from(context);
liaos = data;
mListener = _mListener;
}

@NonNull
@Override
public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View inflate = mLayoutInflater.inflate(R.layout.good_show, parent, false);
return new MyLCViewHolder1(inflate);
}

@Override
public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, int position) {
try {
if (holder instanceof MyLCViewHolder1) {
MyLCViewHolder1 myViewHolder = (MyLCViewHolder1) holder;

SectionItem mode = (SectionItem) liaos.get(position);
String name = mode.getTag();
myViewHolder.IsSC = mode.getIsSC();
String id = mode.getAccount();
String url = mode.getAddress();
boolean isCloud = mode.getIsCloud();//是否云端商品

if (isCloud) {
myViewHolder.Sc_text.setText("下载");
myViewHolder.sc_layout.setImageResource(R.mipmap.yxz);
myViewHolder.delete_text.setVisibility(View.GONE);
myViewHolder.sc_image.setVisibility(View.GONE);
if (mode.getIsdownload()) {
myViewHolder.Sc_text.setVisibility(View.GONE);
myViewHolder.sc_layout.setVisibility(View.GONE);
}
} else {
myViewHolder.Sc_text.setText("上传");
myViewHolder.sc_layout.setImageResource(R.mipmap.ysc);

if (ConfigName.getInstance().user.userID.equals("研发用户")) {
myViewHolder.sc_image.setVisibility(View.GONE);
myViewHolder.delete_text.setVisibility(View.VISIBLE);
myViewHolder.Sc_text.setVisibility(View.VISIBLE);
myViewHolder.sc_layout.setVisibility(View.VISIBLE);

}else
{
myViewHolder.sc_image.setVisibility(View.GONE);
myViewHolder.delete_text.setVisibility(View.GONE);
myViewHolder.Sc_text.setVisibility(View.GONE);
myViewHolder.sc_layout.setVisibility(View.GONE);
}
}
myViewHolder.tvTag.setText(name);
myViewHolder.tvNote.setText("时间:" + mode.getNote() + "秒");
//设置图片
if(url!=null && !url.isEmpty() &&!url.equals("未知"))
{
myBitmapUtils.disPlay(myViewHolder.ImageUrl, url);
}
//上传按钮点击
myViewHolder.shangchuang.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if (isCloud) {
ConfigData.getInstance().GetGoodProcess(holder.itemView.getContext(), id, true);
} else {
ConfigData.getInstance().UploadGoods(holder.itemView.getContext(), id);
}
}
});
//删除按钮点击
myViewHolder.delete_text.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
//按钮点击
String title = "删除菜品操作提示!";
String message = "请问客官确定要删除[" + name + "]菜品吗?";
AlertDialogUtils.showDialog(holder.itemView.getContext(), title, message, new QMUIDialogAction.ActionListener() {
@Override
public void onClick(QMUIDialog dialog, int index) {
if (mListener != null) {
mListener.clickListenerNew(view, 1, mode);
}
dialog.dismiss();
}
});
}
});
SetImage(myViewHolder.sc_image, myViewHolder.IsSC);
//收藏按钮点击
myViewHolder.sc_image.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
myViewHolder.IsSC = mode.getIsSC();
//按钮点击
String title = "收藏菜品操作提示!";
String message = "请问客官确定要[" + (myViewHolder.IsSC ? "取消收藏" : "收藏") + "]菜品吗?";
AlertDialogUtils.showDialog(holder.itemView.getContext(), title, message, new QMUIDialogAction.ActionListener() {
@Override
public void onClick(QMUIDialog dialog, int index) {
myViewHolder.IsSC = !myViewHolder.IsSC;
mode.SetIsSC(myViewHolder.IsSC);
SetImage(myViewHolder.sc_image, myViewHolder.IsSC);
notifyDataSetChanged();

SectionItem item = mode;
QueryDB.UpdateGoodsSC(item.getAccount(), item.getIsSC() ? 1 : 0);
mListener.clickListenerNew(view, 2, mode);
dialog.dismiss();
}
});
}
});
//点击查看当前商品信息
myViewHolder.ImageUrl.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if (isCloud) {
ToastUtils.warning("请先下载该商品!");
} else {
if (mListener!=null)
{
mListener.clickListenerNew(view, 4, mode);
}
}
}
});
}
} catch (Exception e) {
e.printStackTrace();
}
}

public void SetImage(ImageView image, boolean isxz) {
if (isxz) {
image.setImageResource(R.mipmap.sc_yes1);
} else {
image.setImageResource(R.mipmap.sc_no1);
}
}

private Activity findActivity(@NonNull Context context) {
if (context instanceof Activity) {
return (Activity) context;
} else if (context instanceof ContextWrapper) {
return findActivity(((ContextWrapper) context).getBaseContext());
} else {
return null;
}
}

/**
* 刷新
*
* @param
*/
public void refresh() {
Activity activity = findActivity(context);
if (activity != null) {
activity.runOnUiThread(new Runnable() {
@Override
public void run() {
try {
notifyDataSetChanged();
} catch (Exception e) {

}
}
});
}
}

@Override
public int getItemCount() {
return liaos.size();
}

public static class MyLCViewHolder1 extends RecyclerView.ViewHolder {
private TextView tvTag, tvNote, tvAccount, Sc_text;

public RelativeLayout delete_text,shangchuang;
private ImageView ImageUrl,sc_layout;//图片

private ImageView sc_image;//是否收藏

public boolean IsSC = false;


public MyLCViewHolder1(View view) {
super(view);
tvTag = view.findViewById(R.id.Tag_text);
tvNote = view.findViewById(R.id.Note_text);
Sc_text = view.findViewById(R.id.Sc_text);
sc_layout=view.findViewById(R.id.sc_layout);
delete_text = view.findViewById(R.id.delete_text);
sc_image = view.findViewById(R.id.sc_image);//收藏
ImageUrl = view.findViewById(R.id.ImageUrl);//图片
shangchuang= view.findViewById(R.id.shangchuang);
}
}
}



app/src/main/java/com/bonait/bnframework/modules/home/adapter/image_sp_adapter.java → app/src/main/java/com/bonait/bnframework/ViewModel/Adapter/image_sp_adapter.java Ver fichero

@@ -1,4 +1,4 @@
package com.bonait.bnframework.modules.home.adapter;
package com.bonait.bnframework.ViewModel.Adapter;

import android.app.Activity;
import android.content.Context;
@@ -7,21 +7,17 @@ import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.RelativeLayout;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.bonait.bnframework.R;
import com.bonait.bnframework.common.constant.DataBus;
import com.bonait.bnframework.common.db.mode.BPA_GOODS;
import com.bonait.bnframework.common.helper.I.MyClickListener;
import com.bonait.bnframework.common.image.MyBitmapUtils;
import com.bonait.bnframework.common.utils.AlertDialogUtils;
import com.bonait.bnframework.modules.home.fragment.mode.image_sp;
import com.bonait.bnframework.ViewModel.CustomView.image_sp;
import com.qmuiteam.qmui.widget.dialog.QMUIDialog;
import com.qmuiteam.qmui.widget.dialog.QMUIDialogAction;
import com.qmuiteam.qmui.widget.textview.QMUILinkTextView;

import java.util.ArrayList;
import java.util.List;

app/src/main/java/com/bonait/bnframework/modules/home/adapter/lc_adapter.java → app/src/main/java/com/bonait/bnframework/ViewModel/Adapter/lc_adapter.java Ver fichero

@@ -1,4 +1,4 @@
package com.bonait.bnframework.modules.home.adapter;
package com.bonait.bnframework.ViewModel.Adapter;

import android.annotation.SuppressLint;
import android.app.Activity;
@@ -16,7 +16,6 @@ import com.bonait.bnframework.R;
import com.bonait.bnframework.business.ExecuteTheRecipe;
import com.bonait.bnframework.common.constant.DataBus;
import com.bonait.bnframework.common.db.res.lcMode;
import com.bonait.bnframework.common.helper.I.IWriteCallBack;
import com.bonait.bnframework.common.utils.AlertDialogUtils;
import com.bonait.bnframework.common.utils.ToastUtils;
import com.qmuiteam.qmui.widget.dialog.QMUIDialog;
@@ -87,7 +86,7 @@ public class lc_adapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
myViewHolder.imageView.setTag(finalKg);
myViewHolder.imageView.setImageDrawable(context.getResources().getDrawable(R.mipmap.shuiguan_g));

ExecuteTheRecipe.WritePLC("料仓"+(position+1)+"手动开关", true, null);
// ExecuteTheRecipe.WritePLC("料仓"+(position+1)+"手动开关", true, null);
ToastUtils.info("料仓"+(position+1)+"开关," + finalKg);
}else
{
@@ -95,7 +94,7 @@ public class lc_adapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
myViewHolder.imageView.setTag(finalKg);
myViewHolder.imageView.setImageDrawable(context.getResources().getDrawable(R.mipmap.shuiguan_k2));

ExecuteTheRecipe.WritePLC("料仓"+(position+1)+"手动开关", false, null);
// ExecuteTheRecipe.WritePLC("料仓"+(position+1)+"手动开关", false, null);
ToastUtils.info("料仓"+(position+1)+"开关," + finalKg);
}
// AlertDialogUtils.showDialog(context, title, message, new QMUIDialogAction.ActionListener() {
@@ -129,7 +128,7 @@ public class lc_adapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
myViewHolder.imageView.setTag(finalKg);
myViewHolder.imageView.setImageDrawable(context.getResources().getDrawable(R.mipmap.shuiguan_g));

ExecuteTheRecipe.WritePLC("料仓"+(position+1)+"手动开关", true, null);
ExecuteTheRecipe.WritePLC("料仓"+(position+1)+"手动开关", true,null);
ToastUtils.info("料仓"+(position+1)+"开关," + finalKg);
}else
{
@@ -137,7 +136,7 @@ public class lc_adapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
myViewHolder.imageView.setTag(finalKg);
myViewHolder.imageView.setImageDrawable(context.getResources().getDrawable(R.mipmap.shuiguan_k2));

ExecuteTheRecipe.WritePLC("料仓"+(position+1)+"手动开关", false, null);
ExecuteTheRecipe.WritePLC("料仓"+(position+1)+"手动开关", false,null);
ToastUtils.info("料仓"+(position+1)+"开关," + finalKg);
}
// AlertDialogUtils.showDialog(context, title, message, new QMUIDialogAction.ActionListener() {
@@ -171,7 +170,7 @@ public class lc_adapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
myViewHolder.imageView.setTag(finalKg);
myViewHolder.imageView.setImageDrawable(context.getResources().getDrawable(R.mipmap.shuiguan_g));

ExecuteTheRecipe.WritePLC("料仓"+(position+1)+"手动开关", true, null);
ExecuteTheRecipe.WritePLC("料仓"+(position+1)+"手动开关", true,null);
ToastUtils.info("料仓"+(position+1)+"开关," + finalKg);
}else
{
@@ -179,7 +178,7 @@ public class lc_adapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
myViewHolder.imageView.setTag(finalKg);
myViewHolder.imageView.setImageDrawable(context.getResources().getDrawable(R.mipmap.shuiguan_k2));

ExecuteTheRecipe.WritePLC("料仓"+(position+1)+"手动开关", false, null);
ExecuteTheRecipe.WritePLC("料仓"+(position+1)+"手动开关", false,null);
ToastUtils.info("料仓"+(position+1)+"开关," + finalKg);
}
// AlertDialogUtils.showDialog(context, title, message, new QMUIDialogAction.ActionListener() {

app/src/main/java/com/bonait/bnframework/modules/home/adapter/monitor_adapter.java → app/src/main/java/com/bonait/bnframework/ViewModel/Adapter/monitor_adapter.java Ver fichero

@@ -1,4 +1,4 @@
package com.bonait.bnframework.modules.home.adapter;
package com.bonait.bnframework.ViewModel.Adapter;

import android.app.Activity;
import android.content.Context;

app/src/main/java/com/bonait/bnframework/modules/home/adapter/process_adapter.java → app/src/main/java/com/bonait/bnframework/ViewModel/Adapter/process_adapter.java Ver fichero

@@ -1,4 +1,4 @@
package com.bonait.bnframework.modules.home.adapter;
package com.bonait.bnframework.ViewModel.Adapter;

import android.content.Context;
import android.view.LayoutInflater;
@@ -15,7 +15,6 @@ import com.bonait.bnframework.R;
import com.bonait.bnframework.common.db.QueryDB;
import com.bonait.bnframework.common.db.mode.BPA_PROCESS;
import com.bonait.bnframework.common.db.mode.BPA_PROCESSModel;
import com.bonait.bnframework.common.db.res.lcMode;
import com.bonait.bnframework.common.helper.I.MyClickListener;

import java.util.ArrayList;

app/src/main/java/com/bonait/bnframework/modules/home/adapter/processchid_adapter.java → app/src/main/java/com/bonait/bnframework/ViewModel/Adapter/processchid_adapter.java Ver fichero

@@ -1,4 +1,4 @@
package com.bonait.bnframework.modules.home.adapter;
package com.bonait.bnframework.ViewModel.Adapter;

import android.content.Context;
import android.view.LayoutInflater;

+ 116
- 0
app/src/main/java/com/bonait/bnframework/ViewModel/Adapter/silos_calibrate_adapter.java Ver fichero

@@ -0,0 +1,116 @@
package com.bonait.bnframework.ViewModel.Adapter;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.bonait.bnframework.R;
import com.bonait.bnframework.common.db.mode.BPA_SILOS_CALIBRATE;
import com.bonait.bnframework.common.db.res.lcMode;
import com.bonait.bnframework.common.helper.I.MyClickListener;
import com.bonait.bnframework.common.utils.DisplayManager;

import java.util.List;


/**
* 料仓校准表
*/
public class silos_calibrate_adapter extends ArrayAdapter<BPA_SILOS_CALIBRATE> {
/**
* 内部点击事件
*/
private MyClickListener mListener;
private List<BPA_SILOS_CALIBRATE> datas;
int resource1;
public silos_calibrate_adapter(@NonNull Context context, int resource, @NonNull List<BPA_SILOS_CALIBRATE> objects, MyClickListener listener) {
super(context, resource, objects);
mListener = listener;
datas=objects;
this.resource1=resource;
}
//每个子项被滚动到屏幕内的时候会被调用
@NonNull
@Override
public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
BPA_SILOS_CALIBRATE bean = (BPA_SILOS_CALIBRATE) getItem(position);//得到当前项选中item实例
//为每一个子项加载设定的布局
View view = LayoutInflater.from(getContext()).inflate(resource1, parent, false);
//分别获取 image view 和 textview 的实例

TextView num = view.findViewById(R.id.tv_num);
TextView desc = view.findViewById(R.id.tv_desc);
TextView outputMax = view.findViewById(R.id.tv_output_max);
TextView outputMin = view.findViewById(R.id.tv_output_min);
TextView inputMax = view.findViewById(R.id.tv_intput_max);
TextView inputMin = view.findViewById(R.id.tv_intput_min);
DisplayManager.scaleView(view.findViewById(R.id.root));
DisplayManager.scaleView(num);
DisplayManager.scaleView(desc);
DisplayManager.scaleView(outputMax);
DisplayManager.scaleView(outputMin);
DisplayManager.scaleView(inputMax);
DisplayManager.scaleView(inputMin);
// 设置要显示的图片和文字
num.setText(bean.num+"");
String name = bean.name+"";
switch (position){
case 0:
case 1:
case 2:
case 3:
case 4:
case 5:
name += "(隔膜泵"+(position+1)+")";
break;
case 6:
case 7:
case 8:
name += "(外置仓"+(position-5)+")";
break;
case 9:
name += "(加水阀1)";
break;
case 10:
name += "(勾芡泵1)";
break;

}
desc.setText(name);
outputMax.setText(bean.outputTimeMax+"");
outputMin.setText(bean.outputTimeMin+"");
inputMax.setText(bean.inputWightMax+"");
inputMin.setText(bean.inputWightMin+"");
outputMax.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if(mListener!=null) mListener.clickListenerNew(view,position,bean);
}
});
outputMin.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if(mListener!=null) mListener.clickListenerNew(view,position,bean);
}
});
inputMax.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if(mListener!=null) mListener.clickListenerNew(view,position,bean);
}
});
inputMin.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if(mListener!=null) mListener.clickListenerNew(view,position,bean);
}
});
return view;
}
}

Algunos archivos no se mostraron porque demasiados archivos cambiaron en este cambio

Cargando…
Cancelar
Guardar