Compare commits

...

Author SHA1 Message Date
  liup b2cb85bcfd 接口数据修改 2 months ago
  liup 4bbe37ef88 微调 3 months ago
  liup 2588b1e898 修改料仓设置界面 3 months ago
  liup 6c2961ff2f 修改料仓设置界面 3 months ago
  liup 200a28d286 修改料仓设置界面 3 months ago
  liup 350df9ff64 添加料仓设置图 3 months ago
  liup 194972d430 料仓图 3 months ago
  liup 04a7c0e479 修改重复点击弹窗问题 3 months ago
  liup bdcc39d270 修改bug 3 months ago
  liup 009728ab46 修改新建配方 3 months ago
  liup ebbc03060d 修改新建配方 3 months ago
  liup 5531e190bd 修改新建配方 3 months ago
  liup c7bdfdf502 修改UI细节需求;属性分类提出来 3 months ago
  liup 6f48b90887 提交修改,定版 3 months ago
  liup 716810fbdd 优化同步数据时间 4 months ago
  liup b6f22cb1a6 提示修改 4 months ago
  liup 7b8a55d815 缓存提示 4 months ago
  liup 77c4e7c1b9 修改buglist 4 months ago
  liup acb42ec8fe 修改现场bug 4 months ago
  liup cac5e7645a 修改配方匹配 4 months ago
  liup 8cb86b1d77 修改配方匹配,订单统计 4 months ago
  liup a1e3f23a29 修改基础数据滚动刷新 4 months ago
  liup 16d16a0f27 料仓删除滚动问题 4 months ago
  pry a4914b3e52 Merge remote-tracking branch 'origin/调味吧台' into 调味吧台 4 months ago
  pry 459a02b66a 接口调用修改 4 months ago
  liup 2f480d5c45 子属性删除问题 4 months ago
  liup 2d4889472e 同步数据修改 4 months ago
  pry d04ed5335b 修改删除崩溃问题 4 months ago
  liup 4576011ed3 修改bug 4 months ago
  liup 7d103b7779 Merge branch '调味吧台' of http://10.2.1.24:10244/fyf/AndroidSmartClient into 调味吧台 4 months ago
  liup e0522f06a8 修改buglist 4 months ago
  pry f0b53833ad 修改删除崩溃问题 4 months ago
  pry fe5f8af58c 配方明细表修改 4 months ago
  pry 9b2ae300ad 配方明细表修改 4 months ago
  pry 11e1e878c7 Merge remote-tracking branch 'origin/调味吧台' into 调味吧台 4 months ago
  pry b98392c6c0 配方明细表修改 4 months ago
  liup c375fbf7af 内存优化 4 months ago
  liup 17ad24cd4a 使用glide加载图片 4 months ago
  liup 47ddd87978 修改 4 months ago
  liup 0499b43aed Merge branch '调味吧台' of http://10.2.1.24:10244/fyf/AndroidSmartClient into 调味吧台 4 months ago
  liup b4f9100c71 屏幕适配工具 4 months ago
  liup f817d44ad7 添加bugly检测 4 months ago
  pry 0128f6e8c9 配方明细表修改 4 months ago
  pry 47967e35b4 Merge remote-tracking branch 'origin/调味吧台' into 调味吧台 4 months ago
  pry 8054ab445a 忽略文件修改 4 months ago
  liup be23228a35 微调 4 months ago
  liup ff1cee63f1 微调 4 months ago
  liup 24e7a66afc 修改UI刷新错乱问题;修复校准弹窗内存泄漏 4 months ago
  liup 00a95d7126 修改 4 months ago
  liup e20ca95947 优化 4 months ago
  liup 128befe2e6 释放资源,避免内存泄漏 4 months ago
  liup 206ec99911 修改称重校准 4 months ago
  pry 73af779989 清洗调整 4 months ago
  pry 7a6dd3d298 清洗调整 4 months ago
  pry 8245d4043b 配料吧台调试 4 months ago
  pry 54d64ae59d 配料吧台业务开发 4 months ago
  pry dc0c12a114 配料吧台新后台更新 4 months ago
  pry 5f8f60899f 配料吧台新后台更新 4 months ago
  lyw 2cc1c273a3 lyw 上传 5 months ago
  lyw a62b0ee444 lyw 上传 5 months ago
  lyw cdcee5e2fd cypf 6 months ago
  pry 9812d2c886 串口通讯 6 months ago
  pry 2197263737 串口通讯 6 months ago
  pry 8e4e04c875 串口 6 months ago
  lyw 77f6671e03 cypf 6 months ago
  fyf e1b6a5ee7e 内存清理 7 months ago
  fyf d8011d8182 测试 7 months ago
100 changed files with 7058 additions and 550 deletions
Split View
  1. +5
    -0
      .gitignore
  2. +18
    -0
      .idea/deploymentTargetSelector.xml
  3. +15
    -0
      .idea/git_toolbox_prj.xml
  4. +2
    -3
      .idea/gradle.xml
  5. +6
    -0
      .idea/inspectionProfiles/Project_Default.xml
  6. +10
    -0
      .idea/migrations.xml
  7. +8
    -2
      .idea/misc.xml
  8. +43
    -9
      app/build.gradle
  9. BIN
     
  10. BIN
     
  11. +3
    -0
      app/proguard-rules.pro
  12. +12
    -5
      app/src/main/AndroidManifest.xml
  13. +647
    -0
      app/src/main/java/com/bonait/bnframework/HBL/API/APIHelper.java
  14. +21
    -0
      app/src/main/java/com/bonait/bnframework/HBL/API/APIResult.java
  15. +21
    -0
      app/src/main/java/com/bonait/bnframework/HBL/API/APIResultT.java
  16. +57
    -0
      app/src/main/java/com/bonait/bnframework/HBL/API/Utils.java
  17. +44
    -0
      app/src/main/java/com/bonait/bnframework/HBL/Communication/CommBase.java
  18. +88
    -0
      app/src/main/java/com/bonait/bnframework/HBL/Communication/Modbus/ExceptionServer.java
  19. +15
    -0
      app/src/main/java/com/bonait/bnframework/HBL/Communication/Modbus/IExceptionHandling.java
  20. +10
    -0
      app/src/main/java/com/bonait/bnframework/HBL/Communication/Modbus/IModbusMaster.java
  21. +24
    -0
      app/src/main/java/com/bonait/bnframework/HBL/Communication/Modbus/IRead.java
  22. +23
    -0
      app/src/main/java/com/bonait/bnframework/HBL/Communication/Modbus/IWrite.java
  23. +683
    -0
      app/src/main/java/com/bonait/bnframework/HBL/Communication/Modbus/ModbusMaster.java
  24. +157
    -0
      app/src/main/java/com/bonait/bnframework/HBL/Communication/Siemens/CommHelper.java
  25. +360
    -0
      app/src/main/java/com/bonait/bnframework/HBL/Communication/Siemens/SiemensHelper.java
  26. +213
    -0
      app/src/main/java/com/bonait/bnframework/HBL/CustomView/ShadowContainer.java
  27. +81
    -0
      app/src/main/java/com/bonait/bnframework/HBL/DataUtil/ByteLib.java
  28. +51
    -0
      app/src/main/java/com/bonait/bnframework/HBL/DataUtil/ByteTransDataFormat.java
  29. +107
    -0
      app/src/main/java/com/bonait/bnframework/HBL/DataUtil/Convert.java
  30. +244
    -0
      app/src/main/java/com/bonait/bnframework/HBL/DataUtil/DataConvertLib.java
  31. +31
    -0
      app/src/main/java/com/bonait/bnframework/HBL/DataUtil/FloatLib.java
  32. +51
    -0
      app/src/main/java/com/bonait/bnframework/HBL/DataUtil/IntLib.java
  33. +37
    -0
      app/src/main/java/com/bonait/bnframework/HBL/DataUtil/NotifyPropVar.java
  34. +51
    -0
      app/src/main/java/com/bonait/bnframework/HBL/DataUtil/ShortLib.java
  35. +8
    -0
      app/src/main/java/com/bonait/bnframework/HBL/Dialog/AlertDialogButton.java
  36. +15
    -0
      app/src/main/java/com/bonait/bnframework/HBL/Dialog/DialogActivity.java
  37. +327
    -0
      app/src/main/java/com/bonait/bnframework/HBL/Dialog/DialogManager.java
  38. +7
    -0
      app/src/main/java/com/bonait/bnframework/HBL/Dialog/DialogType.java
  39. +35
    -0
      app/src/main/java/com/bonait/bnframework/HBL/Dialog/DialogView.java
  40. +6
    -0
      app/src/main/java/com/bonait/bnframework/HBL/Dialog/IDialogAction.java
  41. +75
    -0
      app/src/main/java/com/bonait/bnframework/HBL/Dialog/WaitDialog.java
  42. +8
    -0
      app/src/main/java/com/bonait/bnframework/HBL/Enum/DataFormat.java
  43. +43
    -0
      app/src/main/java/com/bonait/bnframework/HBL/Executor.java
  44. +5
    -0
      app/src/main/java/com/bonait/bnframework/HBL/Interface/IFunc.java
  45. +5
    -0
      app/src/main/java/com/bonait/bnframework/HBL/Interface/IRun.java
  46. +5
    -0
      app/src/main/java/com/bonait/bnframework/HBL/Interface/IRunT.java
  47. +7
    -0
      app/src/main/java/com/bonait/bnframework/HBL/Logs/IMessageLogNotify.java
  48. +62
    -0
      app/src/main/java/com/bonait/bnframework/HBL/Logs/MessageLog.java
  49. +230
    -0
      app/src/main/java/com/bonait/bnframework/HBL/NetworkUtils.java
  50. +30
    -0
      app/src/main/java/com/bonait/bnframework/HBL/Result/IResult.java
  51. +79
    -0
      app/src/main/java/com/bonait/bnframework/HBL/Result/OperateResult.java
  52. +88
    -0
      app/src/main/java/com/bonait/bnframework/HBL/Result/OperateResultT.java
  53. +38
    -0
      app/src/main/java/com/bonait/bnframework/HBL/Result/ResultCode.java
  54. +5
    -0
      app/src/main/java/com/bonait/bnframework/HBL/Thread/IThread.java
  55. +7
    -0
      app/src/main/java/com/bonait/bnframework/HBL/Thread/IThreadComplete.java
  56. +126
    -0
      app/src/main/java/com/bonait/bnframework/HBL/Thread/ThreadManager.java
  57. +8
    -0
      app/src/main/java/com/bonait/bnframework/HBL/Thread/ThreadModel.java
  58. +55
    -0
      app/src/main/java/com/bonait/bnframework/HBL/Trig/RTrig.java
  59. +53
    -0
      app/src/main/java/com/bonait/bnframework/HBL/Trig/TTrig.java
  60. +106
    -0
      app/src/main/java/com/bonait/bnframework/HBL/Unity.java
  61. +341
    -0
      app/src/main/java/com/bonait/bnframework/HttpModel/APIService.java
  62. +27
    -0
      app/src/main/java/com/bonait/bnframework/HttpModel/BatchingInfo.java
  63. +34
    -0
      app/src/main/java/com/bonait/bnframework/HttpModel/DeviceGoodInfo.java
  64. +153
    -0
      app/src/main/java/com/bonait/bnframework/HttpModel/DeviceInfoBean.java
  65. +8
    -0
      app/src/main/java/com/bonait/bnframework/HttpModel/FuncModel.java
  66. +21
    -0
      app/src/main/java/com/bonait/bnframework/HttpModel/GoodsAttributeList.java
  67. +17
    -0
      app/src/main/java/com/bonait/bnframework/HttpModel/GoodsAttributeValueList.java
  68. +29
    -0
      app/src/main/java/com/bonait/bnframework/HttpModel/GoodsData.java
  69. +26
    -0
      app/src/main/java/com/bonait/bnframework/HttpModel/GoodsInfoList.java
  70. +72
    -0
      app/src/main/java/com/bonait/bnframework/HttpModel/GoodsTechnologyActionList.java
  71. +8
    -0
      app/src/main/java/com/bonait/bnframework/HttpModel/MaterialData.java
  72. +9
    -0
      app/src/main/java/com/bonait/bnframework/HttpModel/MaterialModel.java
  73. +10
    -0
      app/src/main/java/com/bonait/bnframework/HttpModel/MaterialRequestPar.java
  74. +8
    -0
      app/src/main/java/com/bonait/bnframework/HttpModel/testModel.java
  75. +70
    -0
      app/src/main/java/com/bonait/bnframework/MainApplication.java
  76. +16
    -0
      app/src/main/java/com/bonait/bnframework/ShaomaActivity.java
  77. +18
    -11
      app/src/main/java/com/bonait/bnframework/business/ConfigData.java
  78. +361
    -225
      app/src/main/java/com/bonait/bnframework/business/ExecuteTheRecipe.java
  79. +24
    -14
      app/src/main/java/com/bonait/bnframework/business/MainInit.java
  80. +16
    -18
      app/src/main/java/com/bonait/bnframework/business/OrderServer.java
  81. +5
    -0
      app/src/main/java/com/bonait/bnframework/business/PLCControl.java
  82. +13
    -0
      app/src/main/java/com/bonait/bnframework/business/PLCName.java
  83. +7
    -0
      app/src/main/java/com/bonait/bnframework/common/base/BaseActivity.java
  84. +139
    -247
      app/src/main/java/com/bonait/bnframework/common/constant/ConfigName.java
  85. +56
    -6
      app/src/main/java/com/bonait/bnframework/common/constant/DataBus.java
  86. +269
    -0
      app/src/main/java/com/bonait/bnframework/common/cookie/Cookie.java
  87. +180
    -0
      app/src/main/java/com/bonait/bnframework/common/cookie/CookieBar.java
  88. +84
    -0
      app/src/main/java/com/bonait/bnframework/common/cookie/CookieHelper.java
  89. +10
    -0
      app/src/main/java/com/bonait/bnframework/common/cookie/OnActionClickListener.java
  90. +26
    -0
      app/src/main/java/com/bonait/bnframework/common/cookie/ThemeResolver.java
  91. +306
    -7
      app/src/main/java/com/bonait/bnframework/common/db/QueryDB.java
  92. +5
    -1
      app/src/main/java/com/bonait/bnframework/common/db/file/DBHelper.java
  93. +11
    -0
      app/src/main/java/com/bonait/bnframework/common/db/mode/BPA_GOODPROPERTY.java
  94. +16
    -0
      app/src/main/java/com/bonait/bnframework/common/db/mode/BPA_GOODS.java
  95. +9
    -0
      app/src/main/java/com/bonait/bnframework/common/db/mode/BPA_GOODSRECIPENAME.java
  96. +53
    -0
      app/src/main/java/com/bonait/bnframework/common/db/mode/BPA_SILOS_CALIBRATE.java
  97. +1
    -1
      app/src/main/java/com/bonait/bnframework/common/db/mode/BPA_SUBORDER.java
  98. +1
    -0
      app/src/main/java/com/bonait/bnframework/common/db/res/MakeStatus.java
  99. +12
    -1
      app/src/main/java/com/bonait/bnframework/common/db/res/ResGoodProperty.java
  100. +16
    -0
      app/src/main/java/com/bonait/bnframework/common/db/res/ResGoodsMake.java

+ 5
- 0
.gitignore View File

@@ -11,3 +11,8 @@
/build
/captures
.externalNativeBuild
/app/release/app-release.apk
/.idea/deploymentTargetDropDown.xml
/.idea/migrations.xml
/app/release/output-metadata.json
/app/src/main/res/mipmap-xxxhdpi/yxz.png

+ 18
- 0
.idea/deploymentTargetSelector.xml View File

@@ -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-06-17T03:40:11.626864500Z">
<Target type="DEFAULT_BOOT">
<handle>
<DeviceId pluginId="Default" identifier="serial=127.0.0.1:7555;connection=36578987" />
</handle>
</Target>
</DropdownSelection>
<DialogSelection />
</SelectionState>
</selectionStates>
</component>
</project>

+ 15
- 0
.idea/git_toolbox_prj.xml View File

@@ -0,0 +1,15 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="GitToolBoxProjectSettings">
<option name="commitMessageIssueKeyValidationOverride">
<BoolValueOverride>
<option name="enabled" value="true" />
</BoolValueOverride>
</option>
<option name="commitMessageValidationEnabledOverride">
<BoolValueOverride>
<option name="enabled" value="true" />
</BoolValueOverride>
</option>
</component>
</project>

+ 2
- 3
.idea/gradle.xml View File

@@ -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="Android Studio default 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>

+ 6
- 0
.idea/inspectionProfiles/Project_Default.xml View File

@@ -0,0 +1,6 @@
<component name="InspectionProjectProfileManager">
<profile version="1.0">
<option name="myName" value="Project Default" />
<inspection_tool class="AndroidLintUnsafeImplicitIntentLaunch" enabled="false" level="ERROR" enabled_by_default="false" />
</profile>
</component>

+ 10
- 0
.idea/migrations.xml View File

@@ -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>

+ 8
- 2
.idea/misc.xml View File

@@ -1,4 +1,10 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ProjectRootManager" version="2" languageLevel="JDK_11" default="true" project-jdk-name="Android Studio default JDK" project-jdk-type="JavaSDK" />
<component name="ProjectRootManager" version="2" languageLevel="JDK_11" default="true" project-jdk-name="corretto-11" project-jdk-type="JavaSDK" />
<component name="VisualizationToolProject">
<option name="state">
<ProjectState>
<option name="scale" value="0.5" />
</ProjectState>
</option>
</component>
</project>

+ 43
- 9
app/build.gradle View File

@@ -1,6 +1,12 @@
import java.text.DateFormat
import java.text.SimpleDateFormat

apply plugin: 'com.android.application'
//apply plugin: 'com.jakewharton.butterknife'

def releaseTime() {
DateFormat df = new SimpleDateFormat("yyyyMMddHHmm")
return df.format(Calendar.getInstance(Locale.CHINA).getTime())
}

android {
compileSdk rootProject.ext.compileSdkVersion
@@ -13,6 +19,10 @@ android {
versionName rootProject.ext.versionName
testInstrumentationRunner 'androidx.test.runner.AndroidJUnitRunner'
multiDexEnabled true
ndk {
// 设置支持的SO库架构
abiFilters 'armeabi' //, 'x86', 'armeabi-v7a', 'x86_64', 'arm64-v8a'
}
}
buildTypes {
release {
@@ -34,6 +44,7 @@ android {
}

compileOptions {
coreLibraryDesugaringEnabled true
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
@@ -50,11 +61,23 @@ android {

}
}
applicationVariants.all { variant ->
variant.outputs.all {
outputFileName = "boluo-peiliaobatai-v${defaultConfig.versionCode}-${releaseTime()}"+"-unsigned-${variant.name}.apk"
}
}
buildFeatures {
viewBinding = true
}
}

dependencies {
implementation fileTree(include: ['*.jar'], dir: 'libs')

implementation files('libs\\PC_RFID.jar')
implementation files('libs\\sdkapi.jar')
compileOnly files('libs/sdkapi.jar')

//测试相关
testImplementation 'junit:junit:4.13-beta-2'
androidTestImplementation 'androidx.test.ext:junit:1.1.3'
@@ -111,14 +134,9 @@ dependencies {
// log日志框架
implementation 'com.orhanobut:logger:2.2.0'

// leak 内存泄漏检测
// debugImplementation 'com.squareup.leakcanary:leakcanary-android:1.6.3'
// releaseImplementation 'com.squareup.leakcanary:leakcanary-android-no-op:1.6.3'
// // Optional, if you use support library fragments:
// debugImplementation 'com.squareup.leakcanary:leakcanary-support-fragment:1.6.3'
// implementation files('libs/commons-codec-1.6.jar')


//leak 内存泄漏检测
// debugImplementation 'com.squareup.leakcanary:leakcanary-android:2.0-alpha-3'

//Modbus
implementation 'com.github.licheedev:Modbus4Android:2.0.2'
@@ -155,6 +173,22 @@ dependencies {

//基类
implementation 'com.github.CymChad:BaseRecyclerViewAdapterHelper:3.0.4'
coreLibraryDesugaring 'com.android.tools:desugar_jdk_libs:1.1.6'
implementation 'com.contrarywind:Android-PickerView:3.2.6'

implementation 'com.github.xingshuangs:iot-communication:1.5.0'

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

//腾讯bugly
//sdk地址 https://bugly.qq.com/docs/user-guide/instruction-manual-android/?v=1.0.0
implementation 'com.tencent.bugly:crashreport:latest.release' //其中latest.release指代最新Bugly SDK版本号,也可以指定明确的版本号,例如4.0.3

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'
}

BIN
View File


BIN
View File


+ 3
- 0
app/proguard-rules.pro View File

@@ -19,3 +19,6 @@
# If you keep the line number information, uncomment this to
# hide the original source file name.
#-renamesourcefileattribute SourceFile

-dontwarn com.tencent.bugly.**
-keep public class com.tencent.bugly.**{*;}

+ 12
- 5
app/src/main/AndroidManifest.xml View File

@@ -18,6 +18,7 @@
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />
<uses-permission android:name="android.permission.USB_PERMISSION" />

<application
android:name=".MainApplication"
@@ -29,10 +30,14 @@
android:networkSecurityConfig="@xml/network_security_config"
android:roundIcon="@mipmap/boluo"
android:supportsRtl="true"
android:usesCleartextTraffic="true"
android:theme="@style/AppTheme"
tools:ignore="GoogleAppIndexingWarning"
tools:node="merge"
tools:replace="android:icon">
<activity
android:name=".ShaomaActivity"
android:exported="false" />
<activity
android:name=".modules.home.fragment.mode.Silos_item_fragment"
android:exported="false"
@@ -43,7 +48,6 @@
<activity
android:name=".modules.mine.fragment.from.UserActivity"
android:exported="false" />

<activity
android:name=".modules.home.fragment.from.fragment.JiaoYan_sdkz_fragment"
android:exported="false"
@@ -56,7 +60,6 @@
android:name=".modules.home.fragment.from.WdszActivity"
android:exported="false"
tools:ignore="Instantiatable" />

<activity
android:name=".modules.home.fragment.from.DzcjyActivity"
android:exported="false"
@@ -143,7 +146,10 @@
tools:ignore="Instantiatable" />
<activity
android:name=".modules.home.activity.BottomNavigationMainActivity"
android:exported="false" />
android:exported="false"
android:launchMode="singleTask"
android:windowSoftInputMode="stateHidden|stateAlwaysHidden"
/>
<activity
android:name=".modules.home.fragment.from.FileActivity"
android:exported="false" />
@@ -174,8 +180,8 @@
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".modules.welcome.activity.LoginActivity">
</activity>
<activity android:name=".modules.welcome.activity.LoginActivity"></activity>

<receiver
android:name=".common.base.BootReceiver"
@@ -186,6 +192,7 @@
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</receiver>

</application>

</manifest>

+ 647
- 0
app/src/main/java/com/bonait/bnframework/HBL/API/APIHelper.java View File

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

import com.bonait.bnframework.HBL.Interface.IRunT;
import com.bonait.bnframework.HBL.Logs.MessageLog;
import com.bonait.bnframework.HBL.Result.OperateResultT;
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;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;

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 <T> OperateResultT<T> PostT(String url, Object body, String signkey , TypeReference<APIResultT<T>> defaultValue) {
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 {
return OperateResultT.CreateFailed("服务器返回错误,状态码:" + statusCode);
}
}catch (Exception e){
return OperateResultT.CreateFailed("POST 请求异常:"+e.toString());
}finally {
try{
// 关闭连接和流
if (reader != null) reader.close();
if (inputStream != null) inputStream.close();
if (connection != null) connection.disconnect();
}catch(Exception e){
return OperateResultT.CreateFailed("POST 请求异常:"+e.toString());
}
}
try{

APIResultT<T> res = JSON.parseObject(buffer.toString(),defaultValue);
if(res!=null && res.succeeded.toUpperCase().equals("TRUE")){
return OperateResultT.CreateSuccess(res.data);
}else {
return OperateResultT.CreateFailed("内容解析失败");
}
}catch(Exception e){
return OperateResultT.CreateFailed("POST请求返回值解析异常,"+e.toString());
}
// return OperateResultT.CreateFailed("无效的请求");
}


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();
}

public static <T> OperateResultT<T> GetT(String path, Map<String,String> params, TypeReference<APIResultT<T>> defaultValue) {
try {
String ResponseAdd = BuildUrlWithParams(path,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();
APIResultT<T> res = JSON.parseObject(s,defaultValue);
if(res!=null && res.succeeded.toUpperCase().equals("TRUE")){
return OperateResultT.CreateSuccess(res.data);
}else {
return OperateResultT.CreateFailed("内容解析失败");
}
} else {
MessageLog.ShowError("get 请求失败");
return OperateResultT.CreateFailed("get 请求失败");
}
} catch (Exception e) {
MessageLog.ShowError(e);
return OperateResultT.CreateFailed("POST 请求异常");
}
}


/**
* 请求参数拼接
* @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 View File

@@ -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 View File

@@ -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 long timestamp ;

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

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

@@ -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 View File

@@ -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;

}

}

+ 88
- 0
app/src/main/java/com/bonait/bnframework/HBL/Communication/Modbus/ExceptionServer.java View File

@@ -0,0 +1,88 @@
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);
if (add < 0) {
MessageLog.ShowError("地址解析失败=" + Address);
return;
}
if (excpet!=null) excpet.onSuccess(add);
} catch (InterruptedException e) {
MessageLog.ShowError("onFailure,Address=" + Address + ",length=" + length + ",msg:" + e.toString());
if (excpet!=null) excpet.onFailure(e.toString());
} catch (ExecutionException e) {
MessageLog.ShowError("onFailure,Address=" + Address + ",length=" + length + ",msg:" + e.toString());
if (excpet!=null) excpet.onFailure(e.toString());
} catch (ModbusTransportException e) {
MessageLog.ShowError("onFailure,Address=" + Address + ",length=" + length + ",msg:" + e.toString());
if (excpet!=null) excpet.onFailure(e.toString());
} catch (ModbusInitException e) {
MessageLog.ShowError("onFailure,Address=" + Address + ",length=" + length + ",msg:" + e.toString());
if (excpet!=null) excpet.onFailure(e.toString());
} catch (ModbusRespException e) {
MessageLog.ShowError("onFailure,Address=" + Address + ",length=" + length + ",msg:" + e.toString());
if (excpet!=null) excpet.onFailure(e.toString());
}
}

public int GetAddress(String 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))+4000;
}else if (address.toUpperCase().contains("X")&&address.length() >=2){
int xadd = Integer.parseInt( address.substring(1));
return (xadd / 10 * 8) + xadd % 10;
}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 View File

@@ -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 View File

@@ -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 View File

@@ -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 View File

@@ -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);
}

+ 683
- 0
app/src/main/java/com/bonait/bnframework/HBL/Communication/Modbus/ModbusMaster.java View File

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

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

import com.bonait.bnframework.HBL.Communication.CommBase;
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.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 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 boolean IsConnected=false;

private ModbusWorker mw = new ModbusWorker();

public void DisConnect(){ 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{
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 连接成功" );
}
@Override
public void onFailure(Throwable tr) {
IsConnected = false;
errorInfo.set(tr.getMessage());
MessageLog.ShowInfo("Modbus RTU 连接失败" );
}
@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 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.CreateFailed("不匹配的数据类型:"+typeName));
break;
}
}catch(Exception ex){
resultValue.set(OperateResultT.CreateFailed(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.CreateFailed("无效的地址");}
if(!getConnected()){ return OperateResultT.CreateFailed("设备未连接");}
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);
resultValue.set(OperateResultT.CreateSuccess(result));
}

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

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

@Override
public OperateResultT<boolean[]> ReadInputCoil(String address, int length) {
if(address==null||address.isEmpty()){ return OperateResultT.CreateFailed("无效的地址");}
if(!getConnected()){ return OperateResultT.CreateFailed("设备未连接");}
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.CreateFailed(address+",读取异常:"+error));
}
});
return resultValue.get();
}

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

@Override
public OperateResultT<short[]> ReadShort(String address, int length) {
if(address==null||address.isEmpty()){ return OperateResultT.CreateFailed("无效的地址");}
if(!getConnected()){ return OperateResultT.CreateFailed("设备未连接");}
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();
if (data.length == length) {
resultValue.set(OperateResultT.CreateSuccess(data));
}
}

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

@Override
public OperateResultT<Short> ReadShort(String address) {
if(address==null||address.isEmpty()){ return OperateResultT.CreateFailed("无效的地址");}
if(!getConnected()){ return OperateResultT.CreateFailed("设备未连接");}
AtomicReference<OperateResultT<Short>>resultValue=new AtomicReference<>();
ReadShort(address,1).OnSource((s)->{
resultValue.set(OperateResultT.CreateSuccess(s.Content[0]));
}).OnFailed(s->{
resultValue.set(OperateResultT.CreateFailed(s.message));
});
return resultValue.get();
}
@Override
public OperateResultT<int[]> ReadInt(String address, int length) {
if(address==null||address.isEmpty()){ return OperateResultT.CreateFailed("无效的地址");}
if(!getConnected()){ return OperateResultT.CreateFailed("设备未连接");}
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.CreateFailed(address+",读取失败,返回长度和实际读取长度不匹配"));
}
}

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

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

@Override
public OperateResultT<byte[]> ReadByte(String address, int length) {
if(address==null||address.isEmpty()){ return OperateResultT.CreateFailed("无效的地址");}
if(!getConnected()){ return OperateResultT.CreateFailed("设备未连接");}
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();
if(data.length==tempLength){
byte[] result = Arrays.copyOfRange(data, 0, length);
resultValue.set(OperateResultT.CreateSuccess(result));
}else{
resultValue.set(OperateResultT.CreateFailed(address+",读取失败,返回长度和实际读取长度不匹配"));
}
}

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

@Override
public OperateResultT<String> ReadString(String address, int length) {
if(address==null||address.isEmpty()){ return OperateResultT.CreateFailed("无效的地址");}
if(!getConnected()){ return OperateResultT.CreateFailed("设备未连接");}
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.CreateFailed(address+",读取失败,字符串解析失败:"+ex.toString()));
}
}

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

@Override
public OperateResultT<float[]> ReadFloat(String address, int length) {
if(address==null||address.isEmpty()){ return OperateResultT.CreateFailed("无效的地址");}
if(!getConnected()){ return OperateResultT.CreateFailed("设备未连接");}
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.CreateFailed(address+",读取失败,返回长度和实际读取长度不匹配"));
}
}

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

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

@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);
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);
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 {
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 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 View File

@@ -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.CreateFailed(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.CreateFailed(typeName+" 暂不支持的数据类型");
}
}catch (Exception e){
return OperateResultT.CreateFailed(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 View File

@@ -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 View File

@@ -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 View File

@@ -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 View File

@@ -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 View File

@@ -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.CreateFailed("TryToBoolean:转换对象为空");
try{
return OperateResultT.CreateSuccess(Boolean.parseBoolean(value.toString()));
}catch (Exception e) {
return OperateResultT.CreateFailed(e);
}
}

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

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

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

public static <T> OperateResultT<T> TryToGenericity( Object value){
if(value==null) return OperateResultT.CreateFailed("TryToGenericity:转换对象为空");
try{
return OperateResultT.CreateSuccess((T)value);
}catch (Exception e) {
return OperateResultT.CreateFailed(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.CreateFailed("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.CreateFailed("返回对象为空");
}catch (Exception e) {
return OperateResultT.CreateFailed(e);
}
}

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


}

+ 244
- 0
app/src/main/java/com/bonait/bnframework/HBL/DataUtil/DataConvertLib.java View File

@@ -0,0 +1,244 @@
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 "";
}

}

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

@@ -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 View File

@@ -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 View File

@@ -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 void setValue(T value){
if (value != null && !value.equals(_value) || !IsFirst)
{
_value=value;
if(ChangeNotify!=null) ChangeNotify.Run(value);
changedNotifys.values().forEach(item->{item.Run(value);});
IsFirst = true;
}
}
}


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

@@ -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 View File

@@ -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 View File

@@ -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);
}
}

+ 327
- 0
app/src/main/java/com/bonait/bnframework/HBL/Dialog/DialogManager.java View File

@@ -0,0 +1,327 @@
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 if(mContext!=null) 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 if(mContext!=null) 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 if(mContext!=null) showDialog(message,btn,DialogType.错误,action);
}



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

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

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

}


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

@@ -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 View File

@@ -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 View File

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

public interface IDialogAction {
void ExitDialog(boolean status);

}

+ 75
- 0
app/src/main/java/com/bonait/bnframework/HBL/Dialog/WaitDialog.java View File

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

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;

import com.bonait.bnframework.R;
import com.bonait.bnframework.common.constant.DataBus;

import java.lang.ref.WeakReference;

public class WaitDialog {

private WeakReference<Activity> activityWeakReference;
private WeakReference<Context> contextWeakReference;
private ProgressDialog progressDialog;
private static WaitDialog mInstance; //实例变量设置私有,防止直接通过类名访问

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

public static synchronized WaitDialog getInstance() { //静态同步方法作为唯一的实例对象获取方式
if (mInstance==null) {
synchronized (WaitDialog.class ){
if(mInstance==null){
mInstance = new WaitDialog();
}
}
}
return mInstance;
}
//end

public void Show(String title,String msg,Context _context,Activity _activity){
contextWeakReference=new WeakReference<>(_context);
activityWeakReference = new WeakReference<>(_activity);
if(_context==null) return;
if(progressDialog!=null){
progressDialog.dismiss();
}
progressDialog = new ProgressDialog(_context);
progressDialog.setTitle(title);
progressDialog.setCancelable(false);
progressDialog.setMessage(msg);
progressDialog.show();
}

public void AddText(String info){
if(contextWeakReference.get()==null) return;
if(activityWeakReference.get()==null) return;
if(progressDialog==null) return;
activityWeakReference.get().runOnUiThread(()->{ progressDialog.setMessage(info);});
}

public void Dismiss(){
if(activityWeakReference.get()==null) return;
if(progressDialog==null) return;
activityWeakReference.get().runOnUiThread(()->{
if(progressDialog!=null){
progressDialog.dismiss();
}
});
}

public void TimeOut(String info){
if(activityWeakReference.get()==null) return;
if(progressDialog==null) return;
Dismiss();
DialogManager.showError(activityWeakReference.get(),info,AlertDialogButton.OK,null);
}


}

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

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

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

+ 43
- 0
app/src/main/java/com/bonait/bnframework/HBL/Executor.java View File

@@ -0,0 +1,43 @@
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(new Runnable(){
@Override
public void run() {
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/IFunc.java View File

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

public interface IFunc {
boolean Run();
}

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

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

public interface IRun {
void Run();
}

+ 5
- 0
app/src/main/java/com/bonait/bnframework/HBL/Interface/IRunT.java View File

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

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

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

@@ -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);
}

+ 62
- 0
app/src/main/java/com/bonait/bnframework/HBL/Logs/MessageLog.java View File

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

import android.util.Log;

import com.bonait.bnframework.HBL.Thread.ThreadManager;
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) {
Log.e("错误日志",msg);
}

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

@Override
public void WarnMsg(String msg) {
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 View File

@@ -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();
}
}
}
}

+ 30
- 0
app/src/main/java/com/bonait/bnframework/HBL/Result/IResult.java View File

@@ -0,0 +1,30 @@
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;
}
}

+ 79
- 0
app/src/main/java/com/bonait/bnframework/HBL/Result/OperateResult.java View File

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

import com.bonait.bnframework.HBL.Interface.IRun;
import com.bonait.bnframework.HBL.Interface.IRunT;
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(IRunT<String> action){
try{
if(action!=null&&!getIsSuccess())action.Run(message);
}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 View File

@@ -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> CreateFailed(String msg)
{
MessageLog.ShowError(msg);
return new OperateResultT<T>( msg, ResultCode.Fail);
}

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

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

@@ -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 View File

@@ -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 View File

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

public interface IThreadComplete {
void Run() throws Exception;

void RunComplete() throws Exception;
}

+ 126
- 0
app/src/main/java/com/bonait/bnframework/HBL/Thread/ThreadManager.java View File

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

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

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 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;
}
}

}

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

@@ -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;
}

+ 55
- 0
app/src/main/java/com/bonait/bnframework/HBL/Trig/RTrig.java View File

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



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

import java.util.concurrent.ConcurrentHashMap;

/**
* 上升沿操作
*/
public class RTrig {
private static volatile ConcurrentHashMap<String, RTrig> _Instance;

public static RTrig get(String name) {
if (_Instance == null)
_Instance = new ConcurrentHashMap<String, RTrig>();
if (!_Instance.containsKey(name))
_Instance.put(name, new RTrig());
return _Instance.get(name);
}

public static void Remove(String name){
if(_Instance!=null&&_Instance.containsKey(name)){
_Instance.remove(name);
}
}

private RTrig() {
}

private boolean flag=false;
private boolean Q=false;

public boolean getQ() {
return Q;
}

private void setIN(boolean falag) {
Q = falag && !flag;
flag = falag;
}

public boolean Start(boolean IN, IRun callback) {
setIN(IN);
if (Q&&callback!=null)callback.Run();
return Q;
}

public boolean Start(boolean IN) {
setIN(IN);
return Q;
}

}

+ 53
- 0
app/src/main/java/com/bonait/bnframework/HBL/Trig/TTrig.java View File

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

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

import java.util.concurrent.ConcurrentHashMap;

/**
* 下降沿操作类
*/
public class TTrig {
private static volatile ConcurrentHashMap<String, TTrig> _Instance;

public static TTrig get(String name) {
if (_Instance == null)
_Instance = new ConcurrentHashMap<String, TTrig>();
if (!_Instance.containsKey(name))
_Instance.put(name, new TTrig());
return _Instance.get(name);
}

public static void Remove(String name){
if(_Instance!=null&&_Instance.containsKey(name)){
_Instance.remove(name);
}
}

private TTrig() {
}

private boolean flag=false;
private boolean Q=false;

public boolean getQ() {
return Q;
}

private void setIN(boolean falag) {
Q = !falag && flag;
flag = falag;
}

public boolean Start(boolean IN, IRun callback) {
setIN(IN);
if (Q&&callback!=null)callback.Run();
return Q;
}

public boolean Start(boolean IN) {
setIN(IN);
return Q;
}

}

+ 106
- 0
app/src/main/java/com/bonait/bnframework/HBL/Unity.java View File

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

import com.bonait.bnframework.HBL.Dialog.AlertDialogButton;
import com.bonait.bnframework.HBL.Dialog.DialogManager;
import com.bonait.bnframework.HBL.Interface.IFunc;
import com.bonait.bnframework.HBL.Logs.MessageLog;
import com.bonait.bnframework.HBL.Result.OperateResult;

public class Unity {

public static void Delay(long miss){
try{
Thread.sleep(miss);
}catch (Exception e){}
}

/**
* 阻塞等待条件满足
* @param func
* @param timeOut
* @return
*/
public static OperateResult Wait(IFunc func, int timeOut){
long startTime = System.currentTimeMillis();
if(func==null) return OperateResult.CreateFailed("条件为空");
boolean tag=false;
while(!tag){
tag=func.Run();
Delay(100);
if(timeOut>0&&(System.currentTimeMillis()-startTime)>timeOut) break;
}
if(!tag) MessageLog.ShowInfo("任务超时,超时时间:"+String.valueOf(timeOut)+"/"+String.valueOf(System.currentTimeMillis()-startTime));

// System.out.println("任务超时,超时时间:"+String.valueOf(timeOut)+"/"+String.valueOf(System.currentTimeMillis()-startTime));
return tag?OperateResult.CreateSuccess():OperateResult.CreateFailed("任务超时");
}

/**
* 地址拼接
* @param Prefix 地址标头
* @param num 地址偏移量
* @param StartAdd 起始地址
* @return 例如:M6.6=GetSiemensBitSingleAdd("M",15,5)
*/
public static String GetSiemensBitSingleAdd(String Prefix, int num, int StartAdd)
{
String result = "";
if (num > 0) {
int FirstAdd = num / 8;
int EndAdd = num % 8;
if (EndAdd == 0)
{
FirstAdd--;
EndAdd = 7;
}
else EndAdd--;
result =Prefix+(FirstAdd + StartAdd)+"."+ EndAdd;
return result;
}
return result;
}


/**
* 整形数据缩放
* @param InputValue 需要缩放的值
* @param InputMax 需要缩放的最大值
* @param InputMin 需要缩放的最小值
* @param OutMax 缩放后的最大值
* @param OutMin 缩放后的最下值
* @return
*/
public static int Scale( int InputValue, int InputMax, int InputMin, int OutMax, int OutMin)
{
int value = ((OutMax - OutMin) * (InputValue - InputMin)) / (InputMax - InputMin) + OutMin;
return value;
}

/**
* 浮点数据缩放
* @param InputValue 需要缩放的值
* @param InputMax 需要缩放的最大值
* @param InputMin 需要缩放的最小值
* @param OutMax 缩放后的最大值
* @param OutMin 缩放后的最下值
* @return
*/
public static float Scale( float InputValue, float InputMax, float InputMin, float OutMax, float OutMin)
{
MessageLog.ShowInfo("AnalogConvert measureCookTime InputValue="+InputValue+" InputMax="+InputMax+";InputMin="+InputMin+";OutMax="+OutMax+";OutMin="+OutMin);

if(InputValue<=0|| InputMax<=0){
return 0;
}
if(((InputMax - InputMin) + OutMin)==0){
return 0;
}
float value = ((OutMax - OutMin) * (InputValue - InputMin)) / (InputMax - InputMin) + OutMin;
if(value<=0){
value = 0;
}
String formattedNum = String.format("%.2f", value);
return Float.parseFloat(formattedNum);
}

}

+ 341
- 0
app/src/main/java/com/bonait/bnframework/HttpModel/APIService.java View File

@@ -0,0 +1,341 @@
package com.bonait.bnframework.HttpModel;

import com.alibaba.fastjson.TypeReference;
import com.apkfuns.logutils.LogUtils;
import com.bonait.bnframework.HBL.API.APIHelper;
import com.bonait.bnframework.HBL.API.APIResultT;
import com.bonait.bnframework.HBL.API.Utils;
import com.bonait.bnframework.MainApplication;
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.db.file.DBHelper;
import com.bonait.bnframework.common.db.mode.BPA_GOODPROPERTY;
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_GOODSRECIPENAME;
import com.bonait.bnframework.common.db.mode.BPA_GOODSTYPE;
import com.bonait.bnframework.common.db.mode.BPA_MATERIAL;
import com.bonait.bnframework.common.db.mode.BPA_PLCADDRESS;

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicReference;
import java.util.stream.Stream;

public class APIService {
private static List<DeviceGoodInfo> deviceGoodInfo = new ArrayList<DeviceGoodInfo>();
private static MaterialData materialModels = new MaterialData();
public static List<DeviceGoodInfo> GetGoodInfo(){
return deviceGoodInfo;
}
public static MaterialData GetMaterialModels(){ return materialModels; }
private static long lastTime = System.currentTimeMillis();

public static void MainInit(){
Utils.disableSSLCertChecking();
CleanData();
GetMaterialInfo();
// GetGoodsInfo();
}

private static void GetGoodsInfo(){
String autoKey = ConfigName.getInstance().DeviceAutoKey;
String url = "https://cfv.black-pa.com/kitchbase/api/goods/Getdevicegoods?deviceId="+autoKey;
long curTime = System.currentTimeMillis();
LogUtils.d(" GetGoodsInfo1 usetime="+(curTime-lastTime));
lastTime = curTime;
APIHelper.PostT(url,null,null,new TypeReference<APIResultT<GoodsData>>(){}).OnSource(s->{
long curTime2 = System.currentTimeMillis();
LogUtils.d(" GetGoodsInfo11 usetime="+(curTime2-lastTime));
lastTime = curTime2;
if(s.Content!=null){
deviceGoodInfo=s.Content.getGoodsInfoList();
}
UpdateLocalGoodsInfo();
});
curTime = System.currentTimeMillis();
LogUtils.d(" GetGoodsInfo2 usetime="+(curTime-lastTime));
lastTime = curTime;
}

private static void GetMaterialInfo(){
String url = "https://cfv.black-pa.com/saasbase/api/ExternalPlatform/Material/GetMaterialPageList";
String key ="2c39bc05-25c2-46c4-b5c6-dba349058492";
long curTime = System.currentTimeMillis();
LogUtils.d(" GetMaterialInfo1 usetime="+(curTime-lastTime));
lastTime = curTime;
APIHelper.PostT(url,new MaterialRequestPar(1,100),key,new TypeReference<APIResultT<MaterialData>>(){}).OnSource(s->{
long curTime2 = System.currentTimeMillis();
LogUtils.d(" GetMaterialInfo11 usetime="+(curTime2-lastTime));
lastTime = curTime2;
materialModels=s.Content;
UpdateLocalMaterial();
});
curTime = System.currentTimeMillis();
LogUtils.d(" GetMaterialInfo2 usetime="+(curTime-lastTime));
lastTime = curTime;
}

private static void CleanData(){
long curTime = System.currentTimeMillis();
LogUtils.d(" CleanData1 usetime="+(curTime-lastTime));
lastTime = curTime;

DBHelper.getInstance(MainApplication.getContext()).DeleteCreateTables(BPA_MATERIAL.class,"id");
DBHelper.getInstance(MainApplication.getContext()).DeleteCreateTables(BPA_GOODS.class,null);
DBHelper.getInstance(MainApplication.getContext()).DeleteCreateTables(BPA_GOODSRECIPE.class,null);
DBHelper.getInstance(MainApplication.getContext()).DeleteCreateTables(BPA_GOODSTYPE.class,null);
DBHelper.getInstance(MainApplication.getContext()).DeleteCreateTables(BPA_GOODPROPERTY.class,null);
DBHelper.getInstance(MainApplication.getContext()).DeleteCreateTables(BPA_GOODSRECIPENAME.class,null);

// List<BPA_MATERIAL> materials = QueryDB.GetMaterialALL();
// materials.forEach(data->{QueryDB.DeleteMaterial(data);});

// List<BPA_GOODS> goods = QueryDB.GetGoodsALL();//获取所有商品
// goods.forEach(data->{QueryDB.DeleteGoods(data);});
//
// List<BPA_GOODSRECIPE> goodSrecipes= QueryDB.GetGoodsSrecipeALL();
// goodSrecipes.forEach(data->{QueryDB.DeleteGoodsSrecipe(data);});
//
// List<BPA_GOODSTYPE> goodTypes = QueryDB.GetGoodsTypeALL();//获取所有商品分类
// goodTypes.forEach(data->{QueryDB.DeleteGoodsType(data);});
//
// List<BPA_GOODPROPERTY> goodProperties = QueryDB.GetGoodsSubPropertyALL();//获取所有规格
// goodProperties.forEach(data->{ QueryDB.DeleteGoodsProperty(data);});
//
// List<BPA_GOODSRECIPENAME> goodReciepeNames = QueryDB.GetGoodsSrecipeNameALL();//获取所有配方信息
// goodReciepeNames.forEach(data->{QueryDB.DeleteGoodsRecipeName(data);});
curTime = System.currentTimeMillis();
LogUtils.d(" CleanData2 usetime="+(curTime-lastTime));
lastTime = curTime;
}

private static void UpdateLocalMaterial(){
long curTime = System.currentTimeMillis();
LogUtils.d(" UpdateLocalMaterial1 usetime="+(curTime-lastTime));
lastTime = curTime;
List<BPA_MATERIAL> datas = new ArrayList<>();
materialModels.data.forEach(item->{
if(item.name!=null){
BPA_MATERIAL bpa_material =new BPA_MATERIAL();
bpa_material.name = item.name;
bpa_material.id = item.id;
datas.add(bpa_material);
}
});
QueryDB.AddMaterialList(datas);

LogUtils.d(" UpdateLocalMaterial2 usetime="+(curTime-lastTime));
lastTime = curTime;
GetGoodsInfo();
}

private static void UpdateLocalGoodsInfo(){
long curTime = System.currentTimeMillis();
LogUtils.d(" UpdateLocalGoodsInfo1 usetime="+(curTime-lastTime));
lastTime = curTime;
// List<BPA_GOODS> goods = QueryDB.GetGoodsALL();//获取所有商品
// List<BPA_GOODSTYPE> goodTypes = QueryDB.GetGoodsTypeALL();//获取所有商品分类
// List<BPA_GOODPROPERTY> goodProperties = QueryDB.GetGoodsPropertyALL();//获取所有规格
// List<BPA_GOODSRECIPENAME> goodReciepeNames = QueryDB.GetGoodsSrecipeNameALL();//获取所有配方信息
GoodTypeSynchronous();
GoodPropSynchronous();//同步云端商品属性
GoodInfoSynchronous();//同步云端商品信息
GoodRecipeSynchronous();

curTime = System.currentTimeMillis();
LogUtils.d(" UpdateLocalGoodsInfo3 usetime="+(curTime-lastTime));
lastTime = curTime;
}

/**
* 同步云端商品分类到本地
*/
private static void GoodTypeSynchronous(){
LogUtils.d("GoodTypeSynchronous1");
List<BPA_GOODSTYPE> datas = new ArrayList<>();
for(DeviceGoodInfo item : deviceGoodInfo){
BPA_GOODSTYPE bpa_goodstype = new BPA_GOODSTYPE();
bpa_goodstype.name = item.goodsTypeName;
bpa_goodstype.id = item.goodsTypeId;
bpa_goodstype.userID="超级管理员";
datas.add(bpa_goodstype);
}
QueryDB.AddGoodsTypeList(datas);
}

/**
* 同步云端商品属性到本地
*/
private static void GoodPropSynchronous(){
LogUtils.d("GoodPropSynchronous");
List<BPA_GOODPROPERTY> datas = new ArrayList<>();
for(DeviceGoodInfo item : deviceGoodInfo){
if(item.goodsAttributeList!=null){
for(int n=0;n<item.goodsAttributeList.size();n++){
//属性添加
BPA_GOODPROPERTY bpa_goodproperty = new BPA_GOODPROPERTY();
bpa_goodproperty.name = item.goodsAttributeList.get(n).goodsAttributeName;
bpa_goodproperty.parentid ="0";
bpa_goodproperty.sort =n+1;
bpa_goodproperty.id = item.goodsAttributeList.get(n).goodsAttributeId;
bpa_goodproperty.userID="超级管理员";
bpa_goodproperty.GoodsTypeId=item.goodsTypeId;
datas.add(bpa_goodproperty);

//子属性添加
if(item.goodsAttributeList.get(n).goodsAttributeValueList!=null){
for(int i=0;i<item.goodsAttributeList.get(n).goodsAttributeValueList.size();i++){
BPA_GOODPROPERTY bpa_goodpropertySub = new BPA_GOODPROPERTY();
bpa_goodpropertySub.name = item.goodsAttributeList.get(n).goodsAttributeValueList.get(i).attributeValue;
bpa_goodpropertySub.parentid = item.goodsAttributeList.get(n).goodsAttributeId;
bpa_goodpropertySub.id = item.goodsAttributeList.get(n).goodsAttributeValueList.get(i).goodsAttributeValueId;
bpa_goodpropertySub.sort = i+1;
bpa_goodpropertySub.userID="超级管理员";
datas.add(bpa_goodpropertySub);
}
}
}
}

}
QueryDB.AddGoodsPropertyList(datas);
}

/**
* 同步云端商品信息到本地
*/
private static void GoodInfoSynchronous(){
LogUtils.d("GoodInfoSynchronous");
List<BPA_GOODS> datas = new ArrayList<>();
for(DeviceGoodInfo item : deviceGoodInfo){
if(item.goodsInfoList!=null){
for(int i=0;i<item.goodsInfoList.size();i++){
BPA_GOODS bpa_goods =new BPA_GOODS();
bpa_goods.id = item.goodsInfoList.get(i).goodsId;
bpa_goods.name = item.goodsInfoList.get(i).goodsName;
bpa_goods.materialids = getMaterialids(item.goodsInfoList.get(i));
bpa_goods.goodtype=item.goodsTypeId;
bpa_goods.status=1;
bpa_goods.issc=1;
bpa_goods.maketime = 180;
bpa_goods.url=item.goodsInfoList.get(i).imgUrl==null?"":item.goodsInfoList.get(i).imgUrl;
bpa_goods.sort= i+1;
bpa_goods.foreignKeyRe="";
datas.add(bpa_goods);
}
}
}
QueryDB.AddGoodsList(datas);

}

/**
* 获取商品工艺物料组合
* @param goodinfo
* @return
*/
private static String getMaterialids(GoodsInfoList goodinfo){
StringBuffer materialSB = new StringBuffer();
List<BPA_MATERIAL> bpaMaterials = QueryDB.GetMaterialALL();
goodinfo.goodsTechnologyActionList.forEach(material->{
material.GetFuncModel().OnSource(action->{
FuncModel func= action.Content.stream().filter(p->p.actionName.equals("主料名称")).findFirst().get();
BPA_MATERIAL bpaMaterial= bpaMaterials.stream().filter(p->p.name.equals(func.actionValue)).findFirst().get();
materialSB.append(bpaMaterial.id).append(",");
});
});
if(materialSB.toString().length()<=0)return "";
return materialSB.toString().substring(0,materialSB.length()-1);
}

/**
* 同步云端配方详细信息到本地
*/
private static void GoodRecipeSynchronous() {
LogUtils.d("GoodRecipeSynchronous");
List<BPA_GOODSRECIPENAME> datas1 = new ArrayList<>();
List<BPA_GOODSRECIPE> datas2 = new ArrayList<>();
for(DeviceGoodInfo item : deviceGoodInfo){
if(item.goodsInfoList!=null){
List<BPA_GOODPROPERTY> goodProps = QueryDB.GetGoodsSubPropertyALL();
List<BPA_MATERIAL> bpaMaterials = QueryDB.GetMaterialALL();
item.goodsInfoList.forEach(goodinfo->{
try {
ConcurrentHashMap<String,List<GoodsTechnologyActionList>> recipes = new ConcurrentHashMap<>();
goodinfo.goodsTechnologyActionList.forEach(material->{
if(!recipes.containsKey(material.goodsAttributeId))recipes.put(material.goodsAttributeId,new ArrayList<>());
recipes.get(material.goodsAttributeId).add(material);
});

recipes.forEach((key,value)->{
//添加配方
BPA_GOODSRECIPENAME bpa_goodsrecipename = new BPA_GOODSRECIPENAME();
bpa_goodsrecipename.name =GetRecipeName(goodinfo.goodsName, value.get(0).goodsAttributeId,goodProps);
bpa_goodsrecipename.goodsID= goodinfo.goodsId;
bpa_goodsrecipename.design=key;
datas1.add(bpa_goodsrecipename);

//遍历工艺步骤
value.forEach(material->{
material.GetFuncModel().OnSource(action->{
FuncModel func= action.Content.stream().filter(p->p.actionName.equals("主料名称")).findFirst().get();
BPA_MATERIAL bpaMaterial= bpaMaterials.stream().filter(p->p.name.equals(func.actionValue)).findFirst().get();
FuncModel weight= action.Content.stream().filter(p->p.actionName.equals("主料重量")).findFirst().get();
FuncModel sort= action.Content.stream().filter(p->p.actionName.equals("执行步骤")).findFirst().get();
if(bpaMaterial!=null){
BPA_GOODSRECIPE bpa_goodsrecipe = new BPA_GOODSRECIPE();
bpa_goodsrecipe.goodsID = goodinfo.goodsId;
bpa_goodsrecipe.materialID = bpaMaterial.id;
bpa_goodsrecipe.value =weight.actionValue;
bpa_goodsrecipe.sort = Integer.parseInt(sort.actionValue);
bpa_goodsrecipe.recipeID=bpa_goodsrecipename.id;
datas2.add(bpa_goodsrecipe);
}
});
});
});
}catch (Exception e){
LogUtils.d("GoodRecipeSynchronous 5"+goodinfo.goodsId);
e.printStackTrace();
}

});
}
}
LogUtils.d("GoodRecipeSynchronous6");
QueryDB.AddGoodsRecipeNameList(datas1);
LogUtils.d("GoodRecipeSynchronous7");
QueryDB.AddGoodsSrecipeList(datas2);
LogUtils.d("GoodRecipeSynchronous8");
}

/**
* 获取子商品名称
* @param goodsName
* @param goodsAttributeId
* @param goodProps
* @return
*/
private static String GetRecipeName(String goodsName,String goodsAttributeId, List<BPA_GOODPROPERTY> goodProps){
String[] props = goodsAttributeId.split("[,]");
StringBuffer recpipeNameTemp = new StringBuffer();
recpipeNameTemp.append(goodsName).append("_");
try{
for(int i=0;i<props.length;i++){
String id = props[i];
BPA_GOODPROPERTY tempGoodProp = goodProps.stream().filter(p->p.id.equals(id)).findFirst().get();
if(tempGoodProp!=null) recpipeNameTemp.append(tempGoodProp.name).append("_") ;
}
}catch (Exception e){
LogUtils.d(" GetRecipeName goodsAttributeId="+goodsAttributeId);
}


return recpipeNameTemp.toString().substring(0, recpipeNameTemp.length() - 1);
}

}

+ 27
- 0
app/src/main/java/com/bonait/bnframework/HttpModel/BatchingInfo.java View File

@@ -0,0 +1,27 @@
package com.bonait.bnframework.HttpModel;

/**
* 物料信息
*/
public class BatchingInfo {
/**
* 物料Id
*/
public String id;
/**
* 物料名称
*/
public String name;
/**
* 物料类型
*/
public String typename;
/**
* 物料类型Id
*/
public String typeid;
/**
* 创建时间
*/
public String createAt;
}

+ 34
- 0
app/src/main/java/com/bonait/bnframework/HttpModel/DeviceGoodInfo.java View File

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

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

public class DeviceGoodInfo {
/**
* 商品分类ID
*/
public String goodsTypeId;

/**
* 商品分类名称
*/
public String goodsTypeName;

/**
* 商品属性列表
*/
public List<GoodsAttributeList> goodsAttributeList=new ArrayList();

/**
* 商品信息列表
*/
public List<GoodsInfoList> goodsInfoList = new ArrayList();

public DeviceGoodInfo(){}

public DeviceGoodInfo(String mgoodsTypeId, String mgoodsTypeName){
goodsTypeId=mgoodsTypeId;
goodsTypeName=mgoodsTypeName;
}

}

+ 153
- 0
app/src/main/java/com/bonait/bnframework/HttpModel/DeviceInfoBean.java View File

@@ -0,0 +1,153 @@
package com.bonait.bnframework.HttpModel;

/**
* @author: liup
* @description:
* @date: 2024/7/9 11:21.
*/
public class DeviceInfoBean {
private String id;
private String deviceName;
private String deviceTypeId;
private String orgId;
private String productId;
private String productName;
private String productCode;
private int autoKey;
private String productVersionId;
private String orgKey;
private String productVersionName;
private int technologyOrBom;
private String groupId;
private String stopId;
private String stopName;
private String address;

public String getId() {
return id;
}

public void setId(String id) {
this.id = id;
}

public String getDeviceName() {
return deviceName;
}

public void setDeviceName(String deviceName) {
this.deviceName = deviceName;
}

public String getDeviceTypeId() {
return deviceTypeId;
}

public void setDeviceTypeId(String deviceTypeId) {
this.deviceTypeId = deviceTypeId;
}

public String getOrgId() {
return orgId;
}

public void setOrgId(String orgId) {
this.orgId = orgId;
}

public String getProductId() {
return productId;
}

public void setProductId(String productId) {
this.productId = productId;
}

public String getProductName() {
return productName;
}

public void setProductName(String productName) {
this.productName = productName;
}

public String getProductCode() {
return productCode;
}

public void setProductCode(String productCode) {
this.productCode = productCode;
}

public int getAutoKey() {
return autoKey;
}

public void setAutoKey(int autoKey) {
this.autoKey = autoKey;
}

public String getProductVersionId() {
return productVersionId;
}

public void setProductVersionId(String productVersionId) {
this.productVersionId = productVersionId;
}

public String getOrgKey() {
return orgKey;
}

public void setOrgKey(String orgKey) {
this.orgKey = orgKey;
}

public String getProductVersionName() {
return productVersionName;
}

public void setProductVersionName(String productVersionName) {
this.productVersionName = productVersionName;
}

public int getTechnologyOrBom() {
return technologyOrBom;
}

public void setTechnologyOrBom(int technologyOrBom) {
this.technologyOrBom = technologyOrBom;
}

public String getGroupId() {
return groupId;
}

public void setGroupId(String groupId) {
this.groupId = groupId;
}

public String getStopId() {
return stopId;
}

public void setStopId(String stopId) {
this.stopId = stopId;
}

public String getStopName() {
return stopName;
}

public void setStopName(String stopName) {
this.stopName = stopName;
}

public String getAddress() {
return address;
}

public void setAddress(String address) {
this.address = address;
}
}

+ 8
- 0
app/src/main/java/com/bonait/bnframework/HttpModel/FuncModel.java View File

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

public class FuncModel {
public String actionName;
public String actionValue;
public String technologyactionId;
public int index;
}

+ 21
- 0
app/src/main/java/com/bonait/bnframework/HttpModel/GoodsAttributeList.java View File

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

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

public class GoodsAttributeList {
/**
* 商品属性ID
*/
public String goodsAttributeId;

/**
* 商品属性名称
*/
public String goodsAttributeName;

/**
* 商品属性值列表
*/
public List<GoodsAttributeValueList> goodsAttributeValueList=new ArrayList<>();
}

+ 17
- 0
app/src/main/java/com/bonait/bnframework/HttpModel/GoodsAttributeValueList.java View File

@@ -0,0 +1,17 @@
package com.bonait.bnframework.HttpModel;

public class GoodsAttributeValueList {
/**
* 商品属性ID
*/
public String goodsAttributeId;
/**
* 商品属性值ID
*/
public String goodsAttributeValueId;
/**
* 商品属性值
*/
public String attributeValue;

}

+ 29
- 0
app/src/main/java/com/bonait/bnframework/HttpModel/GoodsData.java View File

@@ -0,0 +1,29 @@
package com.bonait.bnframework.HttpModel;

import java.util.List;

/**
* @author: liup
* @description:
* @date: 2024/7/9 11:19.
*/
public class GoodsData {
private List<DeviceGoodInfo> goodsInfoList;
private List<DeviceInfoBean> deviceInfo;

public List<DeviceGoodInfo> getGoodsInfoList() {
return goodsInfoList;
}

public void setGoodsInfoList(List<DeviceGoodInfo> goodsInfoList) {
this.goodsInfoList = goodsInfoList;
}

public List<DeviceInfoBean> getDeviceInfo() {
return deviceInfo;
}

public void setDeviceInfo(List<DeviceInfoBean> deviceInfo) {
this.deviceInfo = deviceInfo;
}
}

+ 26
- 0
app/src/main/java/com/bonait/bnframework/HttpModel/GoodsInfoList.java View File

@@ -0,0 +1,26 @@
package com.bonait.bnframework.HttpModel;

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

public class GoodsInfoList {
/**
* 商品ID
*/
public String goodsId;

/**
* 商品名称
*/
public String goodsName;

/**
* 商品图片
*/
public String imgUrl;

/**
* 商品工艺列表
*/
public List<GoodsTechnologyActionList> goodsTechnologyActionList=new ArrayList();
}

+ 72
- 0
app/src/main/java/com/bonait/bnframework/HttpModel/GoodsTechnologyActionList.java View File

@@ -0,0 +1,72 @@
package com.bonait.bnframework.HttpModel;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.bonait.bnframework.HBL.Result.OperateResultT;

import java.util.List;

public class GoodsTechnologyActionList {
/**
* 步骤名称
*/
public String stepName;

/**
* 工艺步骤值
*/
public String actionJson;

/**
* 商品属性ID
*/
public String goodsAttributeId;

/**
* 是否批量
*/
public boolean isBatch;

public String chnologyId;

/**
* 分组ID
*/
public String groupId;

/**
* 排序
*/
public int sort;

/**
* 商品ID
*/
public String goodsId;

/**
* 设备ID
*/
public String deviceId;

/**
* 模板ID
*/
public String warehousrTemplateId;

/**
* 获取工艺信息
* @return
*/
public OperateResultT<List<FuncModel>> GetFuncModel(){
if(actionJson == null || actionJson.isEmpty())return OperateResultT.CreateFailed("工艺步骤值为空");
try{
List<FuncModel> res = JSON.parseObject(actionJson,new TypeReference<List<FuncModel>>(){});
if(res!=null) return OperateResultT.CreateSuccess(res);
else return OperateResultT.CreateFailed("工艺步骤值解析失败");
}catch(Exception e){
return OperateResultT.CreateFailed(e.getMessage());
}
}

}

+ 8
- 0
app/src/main/java/com/bonait/bnframework/HttpModel/MaterialData.java View File

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

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

public class MaterialData {
public List<MaterialModel> data=new ArrayList<>();
}

+ 9
- 0
app/src/main/java/com/bonait/bnframework/HttpModel/MaterialModel.java View File

@@ -0,0 +1,9 @@
package com.bonait.bnframework.HttpModel;

public class MaterialModel {
public String id;
public String code;
public String name;
public String typeName;
public String uintName;
}

+ 10
- 0
app/src/main/java/com/bonait/bnframework/HttpModel/MaterialRequestPar.java View File

@@ -0,0 +1,10 @@
package com.bonait.bnframework.HttpModel;

public class MaterialRequestPar {
public int current=1;
public int pageSize=100;
public MaterialRequestPar(int Current,int PageSize){
current=Current;
pageSize=PageSize;
}
}

+ 8
- 0
app/src/main/java/com/bonait/bnframework/HttpModel/testModel.java View File

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

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

public class testModel {
public List<DeviceGoodInfo> data= new ArrayList();
}

+ 70
- 0
app/src/main/java/com/bonait/bnframework/MainApplication.java View File

@@ -7,10 +7,13 @@ import android.app.Activity;
import android.app.Application;
import android.content.Context;
import android.content.pm.PackageManager;
import android.text.TextUtils;
import android.util.Log;

import androidx.core.content.ContextCompat;

import com.apkfuns.logutils.LogUtils;
import com.bonait.bnframework.HBL.Thread.ThreadManager;
import com.bonait.bnframework.business.ConfigData;
import com.bonait.bnframework.common.constant.ConfigName;
import com.bonait.bnframework.common.constant.DataBus;
@@ -28,6 +31,7 @@ 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.glide.GlideApp;
import com.bonait.bnframework.common.helper.CrashHandler;
import com.bonait.bnframework.common.helper.I.IMessageLogNotify;
import com.bonait.bnframework.common.helper.MessageLog;
@@ -48,9 +52,13 @@ import com.orhanobut.logger.FormatStrategy;
import com.orhanobut.logger.Logger;
import com.orhanobut.logger.PrettyFormatStrategy;
import com.qmuiteam.qmui.arch.QMUISwipeBackActivityManager;
import com.tencent.bugly.crashreport.CrashReport;

import org.litepal.LitePal;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.IdentityHashMap;
@@ -82,5 +90,67 @@ public class MainApplication extends Application {
context = getApplicationContext();
ConfigName.getInstance().dishesCon = this;
ConfigName.getInstance().app = this;
// if(ConfigName.TEST){
initBugly();
// }
ThreadManager.get().inti();
}

@Override
public void onLowMemory() {
LogUtils.d("MainApplication onLowMemory");
super.onLowMemory();
GlideApp.get(this).clearMemory();
}

/**
* 腾讯bugly 异常检测上班
*/
public void initBugly() {
Context context = getApplicationContext();
// 获取当前包名
String packageName = context.getPackageName();
// 获取当前进程名
String processName = getProcessName(android.os.Process.myPid());
// 设置是否为上报进程
CrashReport.UserStrategy strategy = new CrashReport.UserStrategy(context);
strategy.setUploadProcess(processName == null || processName.equals(packageName));
// 初始化Bugly
CrashReport.initCrashReport(getApplicationContext(), "0ccad7391a", true);
}

/**
* 获取进程号对应的进程名
*
* @param pid 进程号
* @return 进程名
*/
private static String getProcessName(int pid) {
BufferedReader reader = null;
try {
reader = new BufferedReader(new FileReader("/proc/" + pid + "/cmdline"));
String processName = reader.readLine();
if (!TextUtils.isEmpty(processName)) {
processName = processName.trim();
}
return processName;
} catch (Throwable throwable) {
throwable.printStackTrace();
} finally {
try {
if (reader != null) {
reader.close();
}
} catch (IOException exception) {
exception.printStackTrace();
}
}
return null;
}

@Override
protected void attachBaseContext(Context base) {
super.attachBaseContext(base);
// MultiDex.install(this);
}
}

+ 16
- 0
app/src/main/java/com/bonait/bnframework/ShaomaActivity.java View File

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

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.widget.Button;

import com.bonait.bnframework.common.base.BaseActivity;

public class ShaomaActivity extends BaseActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_shaoma);
}
}

+ 18
- 11
app/src/main/java/com/bonait/bnframework/business/ConfigData.java View File

@@ -1,6 +1,7 @@
package com.bonait.bnframework.business;

import android.content.Context;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Handler;
@@ -879,17 +880,22 @@ public class ConfigData {
* 增加本地图片
*/
public void AddImage(Context context) {
BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = 2;//宽高压缩为原来的1/2
Bitmap bitmap1 = BitmapFactory.decodeResource(context.getResources(), R.mipmap.image1, options);
Bitmap bitmap2 = BitmapFactory.decodeResource(context.getResources(), R.mipmap.image2, options);
Bitmap bitmap3 = BitmapFactory.decodeResource(context.getResources(), R.mipmap.image3, options);
Bitmap bitmap4 = BitmapFactory.decodeResource(context.getResources(), R.mipmap.image4, options);
LocalCacheUtils localCacheUtils = new LocalCacheUtils();
localCacheUtils.setBitmapToLocal("image1.png", bitmap1);
localCacheUtils.setBitmapToLocal("image2.png", bitmap2);
localCacheUtils.setBitmapToLocal("image3.png", bitmap3);
localCacheUtils.setBitmapToLocal("image4.png", bitmap4);
if(ConfigUtil.read(context,"fisrtLoadPic",true)){
BitmapFactory.Options options = new BitmapFactory.Options();
//options.inSampleSize = 2;//宽高压缩为原来的1/2
//options.inPreferredConfig=Bitmap.Config.ARGB_4444;
Bitmap bitmap1 = BitmapFactory.decodeResource(context.getResources(), R.mipmap.image1, options);
Bitmap bitmap2 = BitmapFactory.decodeResource(context.getResources(), R.mipmap.image2, options);
Bitmap bitmap3 = BitmapFactory.decodeResource(context.getResources(), R.mipmap.image3, options);
Bitmap bitmap4 = BitmapFactory.decodeResource(context.getResources(), R.mipmap.image4, options);
Bitmap bitmap5 = BitmapFactory.decodeResource(context.getResources(), R.mipmap.image5, options);
LocalCacheUtils.Get().setBitmapToLocal("image1.png", bitmap1);
LocalCacheUtils.Get().setBitmapToLocal("image2.png", bitmap2);
LocalCacheUtils.Get().setBitmapToLocal("image3.png", bitmap3);
LocalCacheUtils.Get().setBitmapToLocal("image4.png", bitmap4);
LocalCacheUtils.Get().setBitmapToLocal("image5.png", bitmap5);
}
ConfigUtil.write(context,"fisrtLoadPic",false);
}

/**
@@ -997,6 +1003,7 @@ public class ConfigData {


}

//endregion
}


+ 361
- 225
app/src/main/java/com/bonait/bnframework/business/ExecuteTheRecipe.java View File

@@ -4,12 +4,15 @@ import android.app.Activity;
import android.content.Context;
import android.content.ContextWrapper;
import android.media.MediaPlayer;
import android.net.wifi.rtt.WifiRttManager;
import android.os.Handler;
import android.os.Looper;
import android.util.Log;

import androidx.annotation.NonNull;

import com.apkfuns.logutils.LogUtils;
import com.bonait.bnframework.HBL.Unity;
import com.bonait.bnframework.R;
import com.bonait.bnframework.common.constant.ConfigName;
import com.bonait.bnframework.common.constant.DataBus;
@@ -18,6 +21,7 @@ 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_PLCADDRESS;
import com.bonait.bnframework.common.db.mode.BPA_SILOS;
import com.bonait.bnframework.common.db.mode.BPA_SILOS_CALIBRATE;
import com.bonait.bnframework.common.db.res.AlertLogEnum;
import com.bonait.bnframework.common.db.res.ResGoodsMake;
import com.bonait.bnframework.common.db.res.ResGoodsRecipe;
@@ -185,26 +189,48 @@ public class ExecuteTheRecipe {
* @param name m名称
* @param time 时间 毫秒
*/
public static void BottomClick(String name,long time)
{
try
{
WritePLC(name,true,null);
new Handler(Looper.getMainLooper()).postDelayed(new Runnable() {
@Override
public void run() {
ExecuteTheRecipe.WritePLC(name, false, null);
}
}, time);
}catch (Exception ex)
{
}
}
// public static void BottomClick(String name,long time)
// {
// try
// {
// WritePLC(name,true,null);
// new Handler(Looper.getMainLooper()).postDelayed(new Runnable() {
// @Override
// public void run() {
// ExecuteTheRecipe.WritePLC(name, false, null);
// }
// }, time);
// }catch (Exception ex)
// {
//
// }
// }
//endregion

//region PLC监听线程
static List<String> names=new ArrayList<>();
/**
* 心跳标志
*/
static boolean HeartbeatMarkers=false;
static long StartTime=0;
static void Heart(){
if(!HeartbeatMarkers&&(System.currentTimeMillis()-StartTime)>=3000) {
Write("心跳",true,null);
HeartbeatMarkers=true;
StartTime=System.currentTimeMillis();
}

if(HeartbeatMarkers&&(System.currentTimeMillis()-StartTime)>=3000){
Write("心跳",false,null);
HeartbeatMarkers=false;
StartTime=System.currentTimeMillis();
}

Write("掉线标志",false,null);
}


public static void Listening() {

ConfigName.getInstance().PLC_Address.clear();
@@ -215,48 +241,50 @@ public class ExecuteTheRecipe {
}
}

names.clear();
if (ConfigName.getInstance().versionSelectionEnum.equals("配料吧台")) {
names.add("水池温度");
}else if (ConfigName.getInstance().versionSelectionEnum.equals("奶茶机"))
{
names.add("水池温度");
names.add("果糖左温度");
names.add("果糖右温度");
}
new Thread(new Runnable() {
@Override
public void run() {
//1.自动模式
ExecuteTheRecipe.WritePLC("手自切换",true,null);
//1.清除开关
for (int i=1;i<=20;i++)
{
ExecuteTheRecipe.WritePLC("通道"+i+"校准开关",false,null);
}
for (int i=1;i<=20;i++)
{
ExecuteTheRecipe.WritePLC("手动控制"+i,false,null);
}
}
}).start();
// names.clear();
// if (ConfigName.getInstance().versionSelectionEnum.equals("配料吧台")) {
// names.add("水池温度");
// }else if (ConfigName.getInstance().versionSelectionEnum.equals("奶茶机"))
// {
// names.add("水池温度");
// names.add("果糖左温度");
// names.add("果糖右温度");
// }
// new Thread(new Runnable() {
// @Override
// public void run() {
// //1.自动模式
// ExecuteTheRecipe.WritePLC("手自切换",true,null);
// //1.清除开关
// for (int i=1;i<=20;i++)
// {
// ExecuteTheRecipe.WritePLC("通道"+i+"校准开关",false,null);
// }
//
// for (int i=1;i<=20;i++)
// {
// ExecuteTheRecipe.WritePLC("手动控制"+i,false,null);
// }
// }
// }).start();

ThreadManager.Get().StartLong("PLC设备数据监听", true, new IThread() {
@Override
public void Run() throws InterruptedException {
try {
//region 临时屏蔽实时数据
// for (String item : ConfigName.getInstance().PLC_Address.keySet()) {
// String key = item;
// BPA_PLCADDRESS plcaddress = ConfigName.getInstance().PLC_Address.get(item);
// if (plcaddress.isread == 1) {
// Object val = ReadPLC(key);
// ListeningValue.put(key, val);
// }
// }
//endregion

//状态读取
for (String item : ConfigName.getInstance().PLC_Address.keySet()) {
String key = item;
BPA_PLCADDRESS plcaddress = ConfigName.getInstance().PLC_Address.get(item);
if (plcaddress.isread == 1) {
Object val = ReadPLC(key);
ListeningValue.put(key, val);
}
}

Heart();//心跳处理

if(!IsMakeGood)
{
@@ -266,9 +294,9 @@ public class ExecuteTheRecipe {
ReadPLCStatus();
}
} catch (Exception ex) {
ToastUtils.error("异常信息:" + ex.getMessage());
ToastUtils.error("PLC设备数据监听异常:" + ex.getMessage());
}
Thread.sleep(500);
Thread.sleep(50);
}

@Override
@@ -277,71 +305,71 @@ public class ExecuteTheRecipe {
}
});

ThreadManager.Get().StartLong("PLC设备-温度重量", true, new IThread() {
@Override
public void Run() throws InterruptedException {
try {
if(!IsMakeGood)
{
Object zl= ExecuteTheRecipe.ReadPLC("称当前重量");
OutletWeigh=zl==null?0:(int)zl;
Object bz= ExecuteTheRecipe.ReadPLC("出料口检测");
IsCup=bz==null?false:(boolean) bz;
Object obj1= ExecuteTheRecipe.ReadPLC("水池温度");
WaterTemp=obj1==null?0:(int)obj1;
if (ConfigName.getInstance().versionSelectionEnum.equals("奶茶机"))
{
Object obj2= ExecuteTheRecipe.ReadPLC("果糖左温度");
Object obj3= ExecuteTheRecipe.ReadPLC("果糖右温度");
SugarTempLeft=obj2==null?0:(int)obj2;
SugarTempRight=obj3==null?0:(int)obj3;
Object obj21= ExecuteTheRecipe.ReadPLC("果糖左温度设置");
Object obj31= ExecuteTheRecipe.ReadPLC("果糖右温度设置");
SugarTempLeft_SZ=obj21==null?0:(int)obj21;
SugarTempRight_SZ=obj31==null?0:(int)obj31;
}
if (WeighComplete!=null)
{
WeighComplete.Run();
}
if (TempComplete!=null)
{
TempComplete.Run();
}
}
} catch (Exception ex) {
ToastUtils.error("异常信息:" + ex.getMessage());
}
Thread.sleep(200);
}
@Override
public void RunComplete() throws InterruptedException {
}
});
ThreadManager.Get().StartLong("PLC设备-自动加热补水", true, new IThread() {
@Override
public void Run() throws InterruptedException {
try {
if(!IsMakeGood)
{
AutoJR();
}
} catch (Exception ex) {
ToastUtils.error("异常信息:" + ex.getMessage());
}
Thread.sleep(5000);
}
@Override
public void RunComplete() throws InterruptedException {
}
});
// ThreadManager.Get().StartLong("PLC设备-温度重量", true, new IThread() {
// @Override
// public void Run() throws InterruptedException {
// try {
// if(!IsMakeGood)
// {
// Object zl= ExecuteTheRecipe.ReadPLC("称当前重量");
// OutletWeigh=zl==null?0:(int)zl;
// Object bz= ExecuteTheRecipe.ReadPLC("出料口检测");
// IsCup=bz==null?false:(boolean) bz;
// Object obj1= ExecuteTheRecipe.ReadPLC("水池温度");
// WaterTemp=obj1==null?0:(int)obj1;
//
// if (ConfigName.getInstance().versionSelectionEnum.equals("奶茶机"))
// {
// Object obj2= ExecuteTheRecipe.ReadPLC("果糖左温度");
// Object obj3= ExecuteTheRecipe.ReadPLC("果糖右温度");
// SugarTempLeft=obj2==null?0:(int)obj2;
// SugarTempRight=obj3==null?0:(int)obj3;
//
// Object obj21= ExecuteTheRecipe.ReadPLC("果糖左温度设置");
// Object obj31= ExecuteTheRecipe.ReadPLC("果糖右温度设置");
// SugarTempLeft_SZ=obj21==null?0:(int)obj21;
// SugarTempRight_SZ=obj31==null?0:(int)obj31;
// }
//
// if (WeighComplete!=null)
// {
// WeighComplete.Run();
// }
// if (TempComplete!=null)
// {
// TempComplete.Run();
// }
// }
// } catch (Exception ex) {
// ToastUtils.error("异常信息:" + ex.getMessage());
// }
// Thread.sleep(200);
// }
// @Override
// public void RunComplete() throws InterruptedException {
//
// }
// });
// ThreadManager.Get().StartLong("PLC设备-自动加热补水", true, new IThread() {
// @Override
// public void Run() throws InterruptedException {
// try {
// if(!IsMakeGood)
// {
// AutoJR();
// }
// } catch (Exception ex) {
// ToastUtils.error("异常信息:" + ex.getMessage());
// }
// Thread.sleep(5000);
// }
//
// @Override
// public void RunComplete() throws InterruptedException {
//
// }
// });

ThreadManager.Get().StartLong("PLC设备数据监听-信号检测", true, new IThread() {
@Override
@@ -365,7 +393,7 @@ public class ExecuteTheRecipe {
try {
if(IsMakeGood && GoodMake!=null)
{
LogUtils.d("商品制作线程 GoodMake = "+GoodMake.toString());
ArrayList<ResGoodsRecipe> recipes= GoodMake.recipes;

//region 根据物料配方排序Sort步骤分组
@@ -378,6 +406,8 @@ public class ExecuteTheRecipe {
//endregion

int count = 0;
boolean isError = false;

for (LinkedHashMap.Entry<Integer, List<ResGoodsRecipe>> entry : rgrs.entrySet()) {
WritePLC("配料完成", false,null);

@@ -392,9 +422,13 @@ public class ExecuteTheRecipe {
}
count=2;
DataBus.getInstance().UpdateGoodsMake(GoodMake.subOrder.id, "步骤【" + key + "】准备下发物料:" + RecipesNames, count, key, false);

//等待配料完成,一直等待
final boolean[] IsComplete = {false};
float outValue;
for (int m = 0; m < goodsRecipes.size(); m++) {
ResGoodsRecipe recipe = goodsRecipes.get(m);
LogUtils.d("商品制作线程 recipe = "+recipe);

final String message = "[" + GoodMake.good.name + "]步骤【" + key + "】下发【" + recipe.materialName + "】";

//获取物料关联的料仓信息
@@ -404,28 +438,42 @@ public class ExecuteTheRecipe {
if(silos==null)
silos = item;
}
//等待配料完成,一直等待
if (silos == null) {
MessageLog.ShowUserMessage(UserLogEnum.订单处理日志, message + "下发失败!物料没有管理料仓!");
MessageLog.ShowUserMessage(UserLogEnum.订单处理日志, message + "下发失败!物料没有绑定料仓!");
Thread.sleep(2000);
IsComplete[0] = true;
isError = true;
} else {
//MessageLog.ShowUserMessage(UserLogEnum.订单处理日志, message + "准备下发【" + silos.num + "】号料仓PLC控制命令,需求量:=" + recipe.value);
int _val = (int)Math.round((Double.parseDouble(recipe.value) * 10));
WritePLC("需求值" + silos.num, (short) _val, null);

//減去料仓数量
int otherG=silos.silosmargin-(_val/10);
QueryDB.UpdateYL(silos.id,otherG>=0?otherG:0);
float _val = Float.parseFloat(recipe.value);
BPA_SILOS_CALIBRATE res = QueryDB.GetSilosCalibrateByNum(silos.num);
if(res!=null){
String name = silos.name+silos.num+"出料时间";
outValue = Unity.Scale(_val,res.inputWightMax,res.inputWightMin,res.outputTimeMax,res.outputTimeMin);
// MessageLog.ShowUserMessage(UserLogEnum.订单处理日志, "写入地址:"+name+"地址值:"+outValue*100);
LogUtils.d("商品制作线程 name="+name+"; outValue="+outValue);
WritePLC(name, (short) (outValue*100), null);
//減去料仓数量
int otherG=silos.silosmargin-(int)(_val);
QueryDB.UpdateYL(silos.id,otherG>=0?otherG:0);
LogUtils.d("商品制作线程 _val="+_val+" ;otherG = "+otherG+";silos.silosmargin="+silos.silosmargin);
}else{
MessageLog.ShowUserMessage(UserLogEnum.订单处理日志, message + "下发失败!物料没有对应的校准值!");
Thread.sleep(2000);
IsComplete[0] = true;
isError = true;
}
}
}
MessageLog.ShowInfo(RecipesNames + "下发成功!");
// MessageLog.ShowInfo(RecipesNames + "下发成功!");
//endregion

//等待配料完成,一直等待
final boolean[] IsComplete = {false};
OnChargeMixtureCompleteNotify = new IRun() {
@Override
public void Run() {
IsComplete[0] = true;
MessageLog.ShowUserMessage(UserLogEnum.订单处理日志, "[" + GoodMake.good.name + "]步骤【" + key + "】配料完成!");
if(GoodMake!=null&& GoodMake.good!=null){
// MessageLog.ShowUserMessage(UserLogEnum.订单处理日志, "[" + GoodMake.good.name + "]步骤【" + key + "】配料完成!");
}
}
};

@@ -433,19 +481,20 @@ public class ExecuteTheRecipe {
WritePLC("配料启动",true,new IWriteCallBack() {
@Override
public void onSuccess() {
MessageLog.ShowInfo("[" + GoodMake.good.name + "]步骤【" + key + "】启动配料成功!");
// MessageLog.ShowInfo("[" + GoodMake.good.name + "]步骤【" + key + "】启动配料成功!");
}

@Override
public void onFailure(String ErrorMsg) {
MessageLog.ShowInfo("[" + GoodMake.good.name + "]步骤【" + key + "】启动配料失败!");
MessageLog.ShowAlertMessage(AlertLogEnum.异常订单未制作日志, "[" + GoodMake.good.name + "]步骤【" + key + "】启动配料失败!");
IsComplete[0] = true;
}
});

long a = System.currentTimeMillis();
while (!IsComplete[0]) {
if ((System.currentTimeMillis() - a) > 1000 * 60) {
if ((System.currentTimeMillis() - a) > 1000 * 30) {
break;
}
Thread.sleep(100);//10 *6
@@ -453,15 +502,23 @@ public class ExecuteTheRecipe {
//更新缓存商品制作列表状态
count += goodsRecipes.size();
DataBus.getInstance().UpdateGoodsMake(GoodMake.subOrder.id, "步骤【" + key + "】:" + RecipesNames + "-配料完成!", count, key, true);
MessageLog.ShowUserMessage(UserLogEnum.订单处理日志, "[" + GoodMake.good.name + "]步骤【" + key + "】下发" + RecipesNames + "执行完成!");
// MessageLog.ShowUserMessage(UserLogEnum.订单处理日志, "[" + GoodMake.good.name + "]步骤【" + key + "】下发" + RecipesNames + "执行完成!");
}

DataBus.getInstance().DeleteGoodsMake(GoodMake.subOrder.id);
MessageLog.ShowUserMessage(UserLogEnum.订单处理日志, "[" + GoodMake.good.name + "]-订单执行完成,请取餐!");
DataBus.getInstance().DeleteGoodsMake(GoodMake.subOrder.id,isError);
if(isError){
MessageLog.ShowUserMessage(UserLogEnum.订单处理日志, "[" + GoodMake.good.name + "]-订单执行失败!");
}else {
MessageLog.ShowUserMessage(UserLogEnum.订单处理日志, "[" + GoodMake.good.name + "]-订单执行完成,请取餐!");

}

GoodMake=null;
IsMakeGood=false;
OnChargeMixtureCompleteNotify = null;
}

IsMakeGood=false;
} catch (Exception ex) {
ToastUtils.error("异常信息:" + ex.getMessage());
IsMakeGood=false;
@@ -474,6 +531,12 @@ public class ExecuteTheRecipe {
}
});
}

public static void releaseListening(){
ThreadManager.Get().Stop("PLC设备数据监听");
ThreadManager.Get().Stop("PLC设备数据监听-信号检测");
ThreadManager.Get().Stop("商品制作线程");
}
//endregion

//region PLC基础控制类
@@ -485,9 +548,12 @@ public class ExecuteTheRecipe {
* @param value
*/
public static void WritePLC(String name, Object value, IWriteCallBack callback) {
MessageLog.ShowInfo("WritePLC name="+name +";value="+value.toString());
try {
if (ConfigName.getInstance().PLC_Address.containsKey(name)) {
BPA_PLCADDRESS plcaddress = ConfigName.getInstance().PLC_Address.get(name);
MessageLog.ShowInfo("WritePLC name="+name + ";plcaddress.address="+plcaddress.address.toString()+";value="+value.toString());

if (!plcaddress.address.isEmpty() && ConfigName.getInstance().PlcIsConnect) {
if (plcaddress.address.toUpperCase().startsWith("VD"))//int
{
@@ -527,6 +593,11 @@ public class ExecuteTheRecipe {
}
}

public static void Write(Object plcName,Object value,IWriteCallBack callBack){
MessageLog.ShowInfo("WritePLC plcName=" +plcName.toString() +";value="+value.toString());
WritePLC(plcName.toString(),value,callBack);
}

/**
* 读PLC数据
*
@@ -534,10 +605,12 @@ public class ExecuteTheRecipe {
* @return
*/
public static Object ReadPLC(String name) {

final Object[] ReturnsVariable = {null};
try {
if (ConfigName.getInstance().PLC_Address.containsKey(name)) {
BPA_PLCADDRESS plcaddress = ConfigName.getInstance().PLC_Address.get(name);
// MessageLog.ShowInfo("ReadPLC name=" +name +" plcaddress="+plcaddress.address.toString());
if (!plcaddress.address.isEmpty() && ConfigName.getInstance().PlcIsConnect) {
if (plcaddress.address.toUpperCase().startsWith("VD"))//int
{
@@ -572,15 +645,65 @@ public class ExecuteTheRecipe {
ReturnsVariable[0] = val[0];
});
}
if ((plcaddress.address.toUpperCase().equals("VW82"))){
// MessageLog.ShowInfo("ReadPLC 称当前重量 name=" +name+" ReturnsVariable[0]="+ReturnsVariable[0] );
OutletWeigh = (short)ReturnsVariable[0];

}
}
}
} catch (Exception ex) {
ToastUtils.error("异常信息:" + ex.getMessage());
// ToastUtils.error("异常信息:" + ex.getMessage());
LogUtils.d("异常信息:" + ex.getMessage());
} finally {
// MessageLog.ShowInfo("ReadPLC name=" +name+" ReturnsVariable[0]="+ReturnsVariable[0] );
return ReturnsVariable[0];
}
}

public static boolean ReadBool(Object plcName){
MessageLog.ShowInfo("ReadBool plcName=" +plcName.toString() );
try{
if(ListeningValue.containsKey(plcName)){
return Boolean.parseBoolean(ListeningValue.get(plcName).toString());
}else{
return Boolean.parseBoolean(ReadPLC(plcName.toString()).toString());
}
}catch(Exception e){
return false;
}
}

public static short ReadShort(Object plcName){
MessageLog.ShowInfo("ReadShort "+plcName.toString());
try{
if(ListeningValue.containsKey(plcName)){
short result = Short.parseShort(ListeningValue.get(plcName).toString());
MessageLog.ShowInfo(plcName.toString()+" result="+result);
return result;
}else{
short result = Short.parseShort(ReadPLC(plcName.toString()).toString());
MessageLog.ShowInfo(plcName.toString()+" result="+result);
return result;
}
}catch(Exception e){
return 0;
}
}

public static int ReadInt(Object plcName){
try{
if(ListeningValue.containsKey(plcName)){
return Integer.parseInt(ListeningValue.get(plcName).toString());
}else{
return Integer.parseInt(ReadPLC(plcName.toString()).toString());
}

}catch(Exception e){
return 0;
}
}

/**
* 读PLC数据
*
@@ -710,13 +833,13 @@ public class ExecuteTheRecipe {
if (ConfigName.getInstance().PLC_Address.containsKey("扫码数据")) {
BPA_PLCADDRESS plcaddress = ConfigName.getInstance().PLC_Address.get("扫码数据");
if (!plcaddress.address.isEmpty() && ConfigName.getInstance().PlcIsConnect) {
ModbusTcpServer.get().ReadString(plcaddress.address, 40, (data) -> {
ModbusTcpServer.get().ReadString(plcaddress.address, 39, (data) -> {

if(!data.isEmpty() && !Code.equals(data) && OnScanTheCodeInformationT != null)
{
Log.d("信息", "扫码数据: "+data);
OnScanTheCodeInformationT.Run(data);
ModbusTcpServer.get().WriteString(plcaddress.address, 40, null);
ModbusTcpServer.get().WriteString(plcaddress.address, 39, null);
}

//记录上一次读取PLC 扫码数据
@@ -769,77 +892,77 @@ public class ExecuteTheRecipe {
/**
* 自动加热
*/
public static void AutoJR() {
try {
if(ConfigName.getInstance().PlcIsConnect)
{
for (String item:names)
{
boolean isopen=false;
if(item.equals("水池温度"))
{
isopen=ConfigName.getInstance().AutomaticHeating;
}else if(item.equals("果糖左温度"))
{
isopen=ConfigName.getInstance().GT1_AutomaticHeating;
}else if(item.equals("果糖右温度"))
{
isopen=ConfigName.getInstance().GT2_AutomaticHeating;
}
if(isopen)
{
Object sc= ReadPLC(item);
Object scsz= ReadPLC(item+"设置");
int sx_temp=sc==null?0:(int)sc;//水箱温度
int sx_temp_sz=scsz==null?0:(int)scsz;//水箱温度设置值
if(sx_temp_sz>0)
{
if(sx_temp>=sx_temp_sz)
{
WritePLC(item+"加热",false,null);
}else
{
WritePLC(item+"加热",true,null);
}
}
}
}
//自动补水
if(ConfigName.getInstance().AutomaticWaterRefill)
{
Object yw= ReadPLC("水池液位检测");
boolean isopen=yw==null?false:(boolean) yw;
if(!isopen)
{
WritePLC("水池进水阀",true,null);
}else
{
if(yw!=null )
{
Object jsf= ReadPLC("水池进水阀");
if(jsf!=null && (boolean)jsf)
{
new Handler(Looper.getMainLooper()).postDelayed(new Runnable() {
@Override
public void run() {
WritePLC("水池进水阀",false,null);
}
}, (int)Math.round((Double.parseDouble(ConfigName.getInstance().AutomaticWaterRefillTime) * 1000)));
}
}
}
}
}
} catch (Exception ex) {
ToastUtils.error("异常信息:" + ex.getMessage());
} finally {
}
}
// public static void AutoJR() {
// try {
//
// if(ConfigName.getInstance().PlcIsConnect)
// {
//
// for (String item:names)
// {
// boolean isopen=false;
// if(item.equals("水池温度"))
// {
// isopen=ConfigName.getInstance().AutomaticHeating;
// }else if(item.equals("果糖左温度"))
// {
// isopen=ConfigName.getInstance().GT1_AutomaticHeating;
// }else if(item.equals("果糖右温度"))
// {
// isopen=ConfigName.getInstance().GT2_AutomaticHeating;
// }
//
// if(isopen)
// {
// Object sc= ReadPLC(item);
// Object scsz= ReadPLC(item+"设置");
//
// int sx_temp=sc==null?0:(int)sc;//水箱温度
// int sx_temp_sz=scsz==null?0:(int)scsz;//水箱温度设置值
// if(sx_temp_sz>0)
// {
// if(sx_temp>=sx_temp_sz)
// {
// WritePLC(item+"加热",false,null);
// }else
// {
// WritePLC(item+"加热",true,null);
// }
// }
// }
// }
//
// //自动补水
// if(ConfigName.getInstance().AutomaticWaterRefill)
// {
// Object yw= ReadPLC("水池液位检测");
// boolean isopen=yw==null?false:(boolean) yw;
// if(!isopen)
// {
// WritePLC("水池进水阀",true,null);
// }else
// {
// if(yw!=null )
// {
// Object jsf= ReadPLC("水池进水阀");
// if(jsf!=null && (boolean)jsf)
// {
// new Handler(Looper.getMainLooper()).postDelayed(new Runnable() {
// @Override
// public void run() {
// WritePLC("水池进水阀",false,null);
// }
// }, (int)Math.round((Double.parseDouble(ConfigName.getInstance().AutomaticWaterRefillTime) * 1000)));
// }
// }
// }
// }
// }
// } catch (Exception ex) {
// ToastUtils.error("异常信息:" + ex.getMessage());
// } finally {
// }
// }

/**
* 完成信号监听
@@ -848,17 +971,30 @@ public class ExecuteTheRecipe {
* @param callback 执行委托
*/
private static void CompleteListen(String name, IRun callback) {
if (ConfigName.getInstance().PLC_Address.containsKey(name)) {
BPA_PLCADDRESS plcaddress = ConfigName.getInstance().PLC_Address.get(name);
if (!plcaddress.address.isEmpty() && ConfigName.getInstance().PlcIsConnect) {
ModbusTcpServer.get().ReadBool(plcaddress.address, 1, booleans -> {
RTrig.get(name).Start(booleans[0], () -> {
if (callback != null)
callback.Run();
});
});
// if (ConfigName.getInstance().PLC_Address.containsKey(name)) {
// BPA_PLCADDRESS plcaddress = ConfigName.getInstance().PLC_Address.get(name);
// if (!plcaddress.address.isEmpty() && ConfigName.getInstance().PlcIsConnect) {
// ModbusTcpServer.get().ReadBool(plcaddress.address, 1, booleans -> {
// RTrig.get(name).Start(booleans[0], () -> {
// if (callback != null)
// callback.Run();
// });
// });
// }
// }

if(ListeningValue.containsKey(name)){
if(!name.equals("配料完成")){
boolean res = Boolean.parseBoolean(ListeningValue.get(name).toString());
RTrig.get(name).Start(res,()->{if(callback!=null)callback.Run();});
}else {
boolean res = Boolean.parseBoolean(ListeningValue.get(name).toString());
if(res){
if(callback!=null)callback.Run();
}
}
}

}
//endregion

@@ -874,7 +1010,7 @@ public class ExecuteTheRecipe {
final boolean[] issucess3 = {false};

//写校准模式
WritePLC("砝码校准模式", true, new IWriteCallBack() {
WritePLC("校准模式", true, new IWriteCallBack() {
@Override
public void onSuccess() {
issucess1[0] =true;
@@ -918,7 +1054,7 @@ public class ExecuteTheRecipe {
final boolean[] issucess2 = {false};

//写校准模式
WritePLC("砝码校准模式", false, new IWriteCallBack() {
WritePLC("校准模式", false, new IWriteCallBack() {
@Override
public void onSuccess() {
issucess1[0] =true;


+ 24
- 14
app/src/main/java/com/bonait/bnframework/business/MainInit.java View File

@@ -3,24 +3,20 @@ package com.bonait.bnframework.business;
import android.app.Activity;
import android.app.Application;
import android.util.Log;
import android.widget.Toast;

import com.bonait.bnframework.BuildConfig;
import com.bonait.bnframework.HttpModel.APIService;
import com.bonait.bnframework.common.constant.ConfigName;
import com.bonait.bnframework.common.constant.Constants;
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_GOODSRECIPE;
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_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.ResGoodsRecipe;
import com.bonait.bnframework.common.db.res.UserLogEnum;
import com.bonait.bnframework.common.helper.CrashHandler;
import com.bonait.bnframework.common.helper.I.IMessageLogNotify;
@@ -29,10 +25,8 @@ import com.bonait.bnframework.common.helper.SdCart;
import com.bonait.bnframework.common.modbus.ModbusTcpHelper;
import com.bonait.bnframework.common.notification.MainNotification;
import com.bonait.bnframework.common.utils.AppUtils;
import com.bonait.bnframework.common.utils.NetworkUtils;
import com.bonait.bnframework.common.utils.PreferenceUtils;
import com.bonait.bnframework.common.utils.ToastUtils;
import com.bonait.bnframework.common.utils.WifiInterceptor;
import com.bonait.bnframework.manager.ActivityLifecycleManager;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.cache.CacheEntity;
@@ -49,7 +43,6 @@ import org.litepal.LitePal;
import java.util.ArrayList;
import java.util.concurrent.TimeUnit;
import java.util.logging.Level;

import okhttp3.OkHttpClient;

public class MainInit {
@@ -90,7 +83,7 @@ public class MainInit {
MainNotification.initNotificationChannel(app);

// 内存泄漏检测
initLeakCanary(false);
initLeakCanary(true,app);

// Log日志打印框架
initLogCat();
@@ -106,6 +99,8 @@ public class MainInit {

//设置连接到有线网络
// NetworkUtils.connetEnternet(app);

// APIService.MainInit();
}


@@ -206,10 +201,17 @@ public class MainInit {
// DBHelper.getInstance(this).DeleteCreateTables(BPA_PLCADDRESS.class,null);
}

// public static StringBuffer toastString = new StringBuffer();

// public static void initToastString(){
// toastString.setLength(0);
// }

/**
* 初始化消息日志接收打印
*/
public static void InitMsgLog(){
// initToastString();
MessageLog.MsgNotify = new IMessageLogNotify() {
@Override
public void ErrorMsg(String msg) {
@@ -238,7 +240,13 @@ public class MainInit {
public void UserMsg(UserLogEnum type, String msg) {
BPA_LOG log = new BPA_LOG();
log.userID = ConfigName.getInstance().user.userID;
ToastUtils.info(msg);
if(msg.contains("登录")){
ToastUtils.info(msg, Toast.LENGTH_SHORT);
}else {
// toastString.append(msg).append("|");
// ToastUtils.info(toastString.subSequence(0,toastString.length()-1).toString(), Toast.LENGTH_LONG);
ToastUtils.info(msg, Toast.LENGTH_SHORT);
}
switch (type.toString())
{
case "登录日志":log.type=1;
@@ -280,13 +288,15 @@ public class MainInit {
/**
* 内存泄漏检测,根据flag来判断要不要初始化
*/
private static void initLeakCanary(boolean flag) {
private static void initLeakCanary(boolean flag, Application context) {
if (flag) {
// leak 内存检测注册
// if (LeakCanary.isInAnalyzerProcess(this)) {
// if (LeakCanary.isInAnalyzerProcess(context)) {
// // This process is dedicated to LeakCanary for heap analysis.
// // You should not init your app in this process.
// return;
// }
// LeakCanary.install(this);
// LeakCanary.install(context);
}
}



+ 16
- 18
app/src/main/java/com/bonait/bnframework/business/OrderServer.java View File

@@ -77,31 +77,28 @@ public class OrderServer {
public void MqttInit()
{
//消息回调
MQTT.get().callback=new IMessage() {
@Override
public void MessageRecive(String topic, String Message) {
try {
if(!Message.isEmpty())
MQTT.get().callback=(topic,Message)->{
try {
if(!Message.isEmpty())
{
String msg= new AES().Decrypt(Message);
if(!msg.isEmpty())
{
String msg= new AES().Decrypt(Message);
if(!msg.isEmpty())
Log.d("远程数据更新", msg);
BPAPackage model=new Json<BPAPackage>().jsonToobject(BPAPackage.class,((String)msg));
if((model.ClientId+"").equals(ConfigName.getInstance().DeviceAutoKey) && model.ClientType==9)
{
Log.d("远程数据更新", msg);
BPAPackage model=new Json<BPAPackage>().jsonToobject(BPAPackage.class,((String)msg));
if((model.ClientId+"").equals(ConfigName.getInstance().DeviceAutoKey) && model.ClientType==9)
{

MessageLog.ShowInfo("收到远程更新数据通知!");
RefreshTheData(model.Message);
}

MessageLog.ShowInfo("收到远程更新数据通知!");
RefreshTheData(model.Message);
}
}
} catch (Exception e) {
Log.d("1", "MessageRecive: ");
}
} catch (Exception e) {
Log.d("1", "MessageRecive: ");
}
};

//连接成功标志
MQTT.get().ConnectOk=new IRun() {
@Override
@@ -109,6 +106,7 @@ public class OrderServer {

String[] Str={ConfigName.getInstance().mqtt_topic+ ConfigName.getInstance().ClientAutoKey};
MQTT.get().Subscrib(Str);
MQTT.get().Subscrib(new String[]{"/120078739409565e0/v1/257/defaul/batvhingpush"});
MessageLog.ShowInfo("订阅主题:" + Str);

}


+ 5
- 0
app/src/main/java/com/bonait/bnframework/business/PLCControl.java View File

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

public class PLCControl {

}

+ 13
- 0
app/src/main/java/com/bonait/bnframework/business/PLCName.java View File

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

public enum PLCName {
重量清零,
称当前重量,
外置仓1出料时间,
外置仓2出料时间,
外置仓3出料时间,
外置仓4出料时间,
外置仓5出料时间,


}

+ 7
- 0
app/src/main/java/com/bonait/bnframework/common/base/BaseActivity.java View File

@@ -16,6 +16,7 @@ import com.bonait.bnframework.common.constant.ConfigName;
import com.bonait.bnframework.common.constant.Constants;
import com.bonait.bnframework.common.helper.ActiveMax;
import com.bonait.bnframework.common.helper.MediaPlayerHelper;
import com.bonait.bnframework.common.image.utils.LocalCacheUtils;
import com.bonait.bnframework.common.utils.AlertDialogUtils;
import com.bonait.bnframework.common.utils.ToastUtils;
import com.qmuiteam.qmui.arch.QMUIActivity;
@@ -48,6 +49,12 @@ public class BaseActivity extends QMUIActivity implements EasyPermissions.Permis
return QMUIDisplayHelper.dp2px(MainApplication.getContext(), 100);
}

@Override
protected void onDestroy() {
super.onDestroy();
ActiveMax.destroy(this);
/*LocalCacheUtils.Get().ClearBitmapFile();*/
}

/**
* 跳转界面


+ 139
- 247
app/src/main/java/com/bonait/bnframework/common/constant/ConfigName.java View File

@@ -6,6 +6,7 @@ import android.content.Context;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;

import com.bonait.bnframework.HBL.Unity;
import com.bonait.bnframework.R;
import com.bonait.bnframework.common.db.mode.BPA_PLCADDRESS;
import com.bonait.bnframework.common.db.mode.BPA_SILOS;
@@ -45,6 +46,8 @@ import java.util.concurrent.ConcurrentHashMap;
* 配置文件
*/
public class ConfigName {
public static final boolean TEST = false;
public static final boolean TEST2 = false;
//region 单例模式
private static ConfigName mInstance; //实例变量设置私有,防止直接通过类名访问

@@ -92,7 +95,7 @@ public class ConfigName {
/**
* 店铺设备号
*/
public String DeviceAutoKey = "159";
public String DeviceAutoKey = "249";
/**
* 设备id
*/
@@ -187,6 +190,8 @@ public class ConfigName {
public String GetStore = "kitchen/api/StoreHelper/GetStoreInfoById?storeId=";
//获取设备信息分页 Get
public String GetDeviceInformation = "kitchen/api/CommInteface/GetDeviceInfo?storeId=%s&autoKey=%s";


//获取 获取基础信息(所有物料信息、设备工序模型、菜谱列表、商品小类、商品大类、单位数据
public String GetBaseDataModel = "kitchen/api/CommInteface/GetBaseDataModel?storeId=%s&autoKey=%s";
//获取 商品
@@ -554,260 +559,147 @@ public class ConfigName {
*/
public List<Res_PLCADDRESS> PlcAddress_配料吧台 = new ArrayList<Res_PLCADDRESS>() {{

//通道校准
add(new Res_PLCADDRESS("通道校准", "-------------", 0, 0));
add(new Res_PLCADDRESS("校准值1", "VW0", 1, 1));
add(new Res_PLCADDRESS("校准值2", "VW2", 1, 1));
add(new Res_PLCADDRESS("校准值3", "VW4", 1, 1));
add(new Res_PLCADDRESS("校准值4", "VW6", 1, 1));
add(new Res_PLCADDRESS("校准值5", "VW8", 1, 1));
add(new Res_PLCADDRESS("校准值6", "VW10", 1, 1));
add(new Res_PLCADDRESS("校准值7", "VW12", 1, 1));
add(new Res_PLCADDRESS("校准值8", "VW14", 1, 1));
add(new Res_PLCADDRESS("校准值9", "VW16", 1, 1));
add(new Res_PLCADDRESS("校准值10", "VW18", 1, 1));
add(new Res_PLCADDRESS("校准值11", "VW20", 1, 1));
add(new Res_PLCADDRESS("校准值12", "VW22", 1, 1));
add(new Res_PLCADDRESS("校准值13", "VW24", 1, 1));
add(new Res_PLCADDRESS("校准值14", "VW26", 1, 1));
add(new Res_PLCADDRESS("校准值15", "VW28", 1, 1));
add(new Res_PLCADDRESS("校准值16", "VW30", 1, 1));
add(new Res_PLCADDRESS("校准值17", "VW32", 1, 1));
add(new Res_PLCADDRESS("校准值18", "VW34", 1, 1));
add(new Res_PLCADDRESS("校准值19", "VW36", 1, 1));
add(new Res_PLCADDRESS("校准值20", "VW38", 1, 1));

add(new Res_PLCADDRESS("通道1校准开关", "M2.0", 1, 1));
add(new Res_PLCADDRESS("通道2校准开关", "M2.1", 1, 1));
add(new Res_PLCADDRESS("通道3校准开关", "M2.2", 1, 1));
add(new Res_PLCADDRESS("通道4校准开关", "M2.3", 1, 1));
add(new Res_PLCADDRESS("通道5校准开关", "M2.4", 1, 1));
add(new Res_PLCADDRESS("通道6校准开关", "M2.5", 1, 1));
add(new Res_PLCADDRESS("通道7校准开关", "M2.6", 1, 1));
add(new Res_PLCADDRESS("通道8校准开关", "M2.7", 1, 1));
add(new Res_PLCADDRESS("通道9校准开关", "M3.0", 1, 1));
add(new Res_PLCADDRESS("通道10校准开关", "M3.1", 1, 1));
add(new Res_PLCADDRESS("通道11校准开关", "M3.2", 1, 1));
add(new Res_PLCADDRESS("通道12校准开关", "M3.3", 1, 1));
add(new Res_PLCADDRESS("通道13校准开关", "M3.4", 1, 1));
add(new Res_PLCADDRESS("通道14校准开关", "M3.5", 1, 1));
add(new Res_PLCADDRESS("通道15校准开关", "M3.6", 1, 1));
add(new Res_PLCADDRESS("通道16校准开关", "M3.7", 1, 1));
add(new Res_PLCADDRESS("通道17校准开关", "M4.0", 1, 1));
add(new Res_PLCADDRESS("通道18校准开关", "M4.1", 1, 1));
add(new Res_PLCADDRESS("通道19校准开关", "M4.2", 1, 1));
add(new Res_PLCADDRESS("通道20校准开关", "M4.3", 1, 1));

add(new Res_PLCADDRESS("配料次数", "VD90", 1, 1));
add(new Res_PLCADDRESS("反转时间", "VW94", 1, 1));//pl
//add(new Res_PLCADDRESS("基准时间", "VW96", 1, 1));
add(new Res_PLCADDRESS("基准时间", "VW98", 1, 1));

add(new Res_PLCADDRESS("通道校准", "M0.0", 0, 1));
add(new Res_PLCADDRESS("校准完成", "M0.7", 1, 0));

// add(new Res_PLCADDRESS("出料系数1", "VR400", 1, 1));
// add(new Res_PLCADDRESS("出料系数2", "VR404", 1, 1));
// add(new Res_PLCADDRESS("出料系数3", "VR408", 1, 1));
// add(new Res_PLCADDRESS("出料系数4", "VR412", 1, 1));
// add(new Res_PLCADDRESS("出料系数5", "VR416", 1, 1));
// add(new Res_PLCADDRESS("出料系数6", "VR420", 1, 1));
// add(new Res_PLCADDRESS("出料系数7", "VR424", 1, 1));
// add(new Res_PLCADDRESS("出料系数8", "VR428", 1, 1));
// add(new Res_PLCADDRESS("出料系数9", "VR432", 1, 1));
// add(new Res_PLCADDRESS("出料系数10", "VR436", 1, 1));
// add(new Res_PLCADDRESS("出料系数11", "VR440", 1, 1));
// add(new Res_PLCADDRESS("出料系数12", "VR444", 1, 1));
// add(new Res_PLCADDRESS("出料系数13", "VR448", 1, 1));
// add(new Res_PLCADDRESS("出料系数14", "VR452", 1, 1));
// add(new Res_PLCADDRESS("出料系数15", "VR456", 1, 1));
// add(new Res_PLCADDRESS("出料系数16", "VR460", 1, 1));
// add(new Res_PLCADDRESS("出料系数17", "VR464", 1, 1));
// add(new Res_PLCADDRESS("出料系数18", "VR468", 1, 1));
// add(new Res_PLCADDRESS("出料系数19", "VR472", 1, 1));
// add(new Res_PLCADDRESS("出料系数20", "VR476", 1, 1));

//模拟出料
add(new Res_PLCADDRESS("模拟出料", "-------------", 0, 0));
add(new Res_PLCADDRESS("需求值1", "VW100", 1, 1));
add(new Res_PLCADDRESS("需求值2", "VW102", 1, 1));
add(new Res_PLCADDRESS("需求值3", "VW104", 1, 1));
add(new Res_PLCADDRESS("需求值4", "VW106", 1, 1));
add(new Res_PLCADDRESS("需求值5", "VW108", 1, 1));
add(new Res_PLCADDRESS("需求值6", "VW110", 1, 1));
add(new Res_PLCADDRESS("需求值7", "VW112", 1, 1));
add(new Res_PLCADDRESS("需求值8", "VW114", 1, 1));
add(new Res_PLCADDRESS("需求值9", "VW116", 1, 1));
add(new Res_PLCADDRESS("需求值10", "VW118", 1, 1));
add(new Res_PLCADDRESS("需求值11", "VW120", 1, 1));
add(new Res_PLCADDRESS("需求值12", "VW122", 1, 1));
add(new Res_PLCADDRESS("需求值13", "VW124", 1, 1));
add(new Res_PLCADDRESS("需求值14", "VW126", 1, 1));
add(new Res_PLCADDRESS("需求值15", "VW128", 1, 1));
add(new Res_PLCADDRESS("需求值16", "VW130", 1, 1));
add(new Res_PLCADDRESS("需求值17", "VW132", 1, 1));
add(new Res_PLCADDRESS("需求值18", "VW134", 1, 1));
add(new Res_PLCADDRESS("需求值19", "VW136", 1, 1));
add(new Res_PLCADDRESS("需求值20", "VW138", 1, 1));
add(new Res_PLCADDRESS("配料启动", "M0.1", 0, 1));
add(new Res_PLCADDRESS("手自切换", "M0.2", 1, 1));
add(new Res_PLCADDRESS("配料完成", "M0.3", 1, 0));
add(new Res_PLCADDRESS("按钮启动", "M0.5", 1, 0));

//出料算法补偿
add(new Res_PLCADDRESS("出料算法补偿", "-------------", 0, 0));
add(new Res_PLCADDRESS("低系数1", "VW44", 1, 1));
add(new Res_PLCADDRESS("低系数2", "VW46", 1, 1));
add(new Res_PLCADDRESS("低系数3", "VW48", 1, 1));
add(new Res_PLCADDRESS("低系数4", "VW50", 1, 1));
add(new Res_PLCADDRESS("低系数5", "VW52", 1, 1));
add(new Res_PLCADDRESS("低系数6", "VW54", 1, 1));

add(new Res_PLCADDRESS("高系数1", "VW144", 1, 1));
add(new Res_PLCADDRESS("高系数2", "VW146", 1, 1));
add(new Res_PLCADDRESS("高系数3", "VW148", 1, 1));
add(new Res_PLCADDRESS("高系数4", "VW150", 1, 1));
add(new Res_PLCADDRESS("高系数5", "VW152", 1, 1));
add(new Res_PLCADDRESS("高系数6", "VW154", 1, 1));


add(new Res_PLCADDRESS("补偿1时间", "VW168", 1, 1));
add(new Res_PLCADDRESS("补偿2时间", "VW170", 1, 1));
add(new Res_PLCADDRESS("补偿3时间", "VW172", 1, 1));
add(new Res_PLCADDRESS("补偿4时间", "VW174", 1, 1));
add(new Res_PLCADDRESS("补偿5时间", "VW176", 1, 1));
add(new Res_PLCADDRESS("补偿6时间", "VW178", 1, 1));

add(new Res_PLCADDRESS("通道1补偿开关", "VW194.0", 1, 1));
add(new Res_PLCADDRESS("通道2补偿开关", "VW194.1", 1, 1));
add(new Res_PLCADDRESS("通道3补偿开关", "VW194.2", 1, 1));
add(new Res_PLCADDRESS("通道4补偿开关", "VW194.3", 1, 1));
add(new Res_PLCADDRESS("通道5补偿开关", "VW194.4", 1, 1));
add(new Res_PLCADDRESS("通道6补偿开关", "VW194.5", 1, 1));

//电子秤校验
add(new Res_PLCADDRESS("电子秤校验", "-------------", 0, 0));
add(new Res_PLCADDRESS("称当前重量", "VD344", 1, 0));
//add(new Res_PLCADDRESS("砝码值", "VW94", 1, 1));
add(new Res_PLCADDRESS("砝码值", "VW96", 1, 1));
add(new Res_PLCADDRESS("砝码校准模式", "M1.0", 1, 1));
add(new Res_PLCADDRESS("重量清零", "M1.1", 0, 1));
add(new Res_PLCADDRESS("关闭写保护", "M1.2", 0, 1));
add(new Res_PLCADDRESS("零点校准", "M1.3", 0, 1));
add(new Res_PLCADDRESS("砝码值写入", "M1.4", 0, 1));
add(new Res_PLCADDRESS("打开写保护", "M1.5", 0, 1));
add(new Res_PLCADDRESS("清洗状态", "M1.6", 1, 0));

//温度监控
add(new Res_PLCADDRESS("温度控制", "-------------", 0, 0));
// add(new Res_PLCADDRESS("水池温度", "VD354", 1, 0));
// add(new Res_PLCADDRESS("水池温度设置", "VD378", 1, 1));
// add(new Res_PLCADDRESS("水池温度加热", "M104.1", 1, 0));
add(new Res_PLCADDRESS("配料信号", "-------------", 0, 0));
add(new Res_PLCADDRESS("配料启动", "M0.0", 0, 1));
add(new Res_PLCADDRESS("配料完成", "M0.3", 1, 1));
add(new Res_PLCADDRESS("按钮配料启动", "I0.0", 1, 0));
add(new Res_PLCADDRESS("清洗模式", "M1.0", 0, 1));

add(new Res_PLCADDRESS("通道", "-------------", 0, 0));
add(new Res_PLCADDRESS("通道1启停控制", "M10.0", 0, 1));
add(new Res_PLCADDRESS("通道1出料时间", "VW100", 1, 1));
add(new Res_PLCADDRESS("通道2启停控制", "M10.1", 0, 1));
add(new Res_PLCADDRESS("通道2出料时间", "VW102", 1, 1));
add(new Res_PLCADDRESS("通道3启停控制", "M10.2", 0, 1));
add(new Res_PLCADDRESS("通道3出料时间", "VW104", 1, 1));
add(new Res_PLCADDRESS("通道4启停控制", "M10.3", 0, 1));
add(new Res_PLCADDRESS("通道4出料时间", "VW106", 1, 1));
add(new Res_PLCADDRESS("通道5启停控制", "M10.4", 0, 1));
add(new Res_PLCADDRESS("通道5出料时间", "VW108", 1, 1));
add(new Res_PLCADDRESS("通道6启停控制", "M10.5", 0, 1));
add(new Res_PLCADDRESS("通道6出料时间", "VW110", 1, 1));
add(new Res_PLCADDRESS("通道7启停控制", "M10.6", 0, 1));
add(new Res_PLCADDRESS("通道7出料时间", "VW112", 1, 1));
add(new Res_PLCADDRESS("通道8启停控制", "M10.7", 0, 1));
add(new Res_PLCADDRESS("通道8出料时间", "VW114", 1, 1));

add(new Res_PLCADDRESS("通道9启停控制", "M11.0", 0, 1));
add(new Res_PLCADDRESS("通道9出料时间", "VW116", 1, 1));
add(new Res_PLCADDRESS("通道10启停控制", "M11.1", 0, 1));
add(new Res_PLCADDRESS("通道10出料时间", "VW118", 1, 1));
add(new Res_PLCADDRESS("通道11启停控制", "M11.2", 0, 1));
add(new Res_PLCADDRESS("通道11出料时间", "VW120", 1, 1));
add(new Res_PLCADDRESS("通道12启停控制", "M11.3", 0, 1));
add(new Res_PLCADDRESS("通道12出料时间", "VW122", 1, 1));
add(new Res_PLCADDRESS("通道13启停控制", "M11.4", 0, 1));
add(new Res_PLCADDRESS("通道13出料时间", "VW124", 1, 1));
add(new Res_PLCADDRESS("通道14启停控制", "M11.5", 0, 1));
add(new Res_PLCADDRESS("通道14出料时间", "VW126", 1, 1));

add(new Res_PLCADDRESS("通道15启停控制", "M11.6", 0, 1));
add(new Res_PLCADDRESS("通道15出料时间", "VW128", 1, 1));
add(new Res_PLCADDRESS("通道16启停控制", "M11.7", 0, 1));
add(new Res_PLCADDRESS("通道16出料时间", "VW130", 1, 1));
add(new Res_PLCADDRESS("通道17启停控制", "M12.0", 0, 1));
add(new Res_PLCADDRESS("通道17出料时间", "VW132", 1, 1));
add(new Res_PLCADDRESS("通道18启停控制", "M12.1", 0, 1));
add(new Res_PLCADDRESS("通道18出料时间", "VW134", 1, 1));
add(new Res_PLCADDRESS("通道19启停控制", "M12.2", 0, 1));
add(new Res_PLCADDRESS("通道19出料时间", "VW136", 1, 1));
add(new Res_PLCADDRESS("通道20启停控制", "M12.3", 0, 1));
add(new Res_PLCADDRESS("通道20出料时间", "VW138", 1, 1));
add(new Res_PLCADDRESS("通道21启停控制", "M12.4", 0, 1));
add(new Res_PLCADDRESS("通道21出料时间", "VW140", 1, 1));

add(new Res_PLCADDRESS("通道22启停控制", "M12.5", 0, 1));
add(new Res_PLCADDRESS("通道22出料时间", "VW142", 1, 1));
add(new Res_PLCADDRESS("通道23启停控制", "M12.6", 0, 1));
add(new Res_PLCADDRESS("通道23出料时间", "VW144", 1, 1));
add(new Res_PLCADDRESS("通道24启停控制", "M12.7", 0, 1));
add(new Res_PLCADDRESS("通道24出料时间", "VW146", 1, 1));
add(new Res_PLCADDRESS("通道25启停控制", "M13.0", 0, 1));
add(new Res_PLCADDRESS("通道25出料时间", "VW148", 1, 1));
add(new Res_PLCADDRESS("通道26启停控制", "M13.1", 0, 1));
add(new Res_PLCADDRESS("通道26出料时间", "VW150", 1, 1));



// add(new Res_PLCADDRESS("外置仓", "-------------", 0, 0));
// for (int i=1;i<=5;i++){
// add(new Res_PLCADDRESS("外置仓"+i+"出料时间", "VW"+(98+(i*2)), 0, 1));
// add(new Res_PLCADDRESS("外置仓"+i+"启停控制", "M10."+(i-1), 1, 1));
// }
//
// add(new Res_PLCADDRESS("果糖左温度", "VD358", 1, 0));
// add(new Res_PLCADDRESS("果糖左温度设置", "VD382", 1, 1));
// add(new Res_PLCADDRESS("果糖左温度加热", "M103.7", 1, 0));
// add(new Res_PLCADDRESS("加热仓", "-------------", 0, 0));
// add(new Res_PLCADDRESS("加热仓16出料时间", "VW110", 0, 1));
// add(new Res_PLCADDRESS("加热仓16启停控制", "M10.5", 1, 1));
// add(new Res_PLCADDRESS("加热仓17出料时间", "VW112", 0, 1));
// add(new Res_PLCADDRESS("加热仓17启停控制", "M10.6", 1, 1));
//
// add(new Res_PLCADDRESS("果糖右温度", "VD362", 1, 0));
// add(new Res_PLCADDRESS("果糖右温度设置", "VD386", 1, 1));
// add(new Res_PLCADDRESS("果糖右温度加热", "M104.0", 1, 0));

add(new Res_PLCADDRESS("水池温度", "VD352", 1, 0));
add(new Res_PLCADDRESS("水池温度设置", "VD360", 1, 1));
add(new Res_PLCADDRESS("水池温度加热", "M104.0", 1, 0));

//自动清洗
add(new Res_PLCADDRESS("自动清洗", "-------------", 0, 0));
add(new Res_PLCADDRESS("排水阀排水时间", "VW244", 1, 1));
add(new Res_PLCADDRESS("循环清洗时间", "VW246", 1, 1));
add(new Res_PLCADDRESS("加热时间", "VW248", 1, 1));
add(new Res_PLCADDRESS("自动补水延迟时间", "VW250", 1, 1));


add(new Res_PLCADDRESS("清洗模式", "M0.4", 1, 1));
add(new Res_PLCADDRESS("自动清洗开始", "M0.5", 1, 1));
add(new Res_PLCADDRESS("自动清洗完成", "M0.6", 1, 1));


//手动控制
add(new Res_PLCADDRESS("手动控制", "-------------", 0, 0));
add(new Res_PLCADDRESS("手动控制1", "M50.0", 1, 1));
add(new Res_PLCADDRESS("手动控制2", "M50.1", 1, 1));
add(new Res_PLCADDRESS("手动控制3", "M50.2", 1, 1));
add(new Res_PLCADDRESS("手动控制4", "M50.3", 1, 1));
add(new Res_PLCADDRESS("手动控制5", "M50.4", 1, 1));
add(new Res_PLCADDRESS("手动控制6", "M50.5", 1, 1));
add(new Res_PLCADDRESS("手动控制7", "M51.4", 1, 1));
add(new Res_PLCADDRESS("手动控制8", "M51.5", 1, 1));
add(new Res_PLCADDRESS("手动控制9", "M51.6", 1, 1));
add(new Res_PLCADDRESS("手动控制10", "M51.7", 1, 1));
add(new Res_PLCADDRESS("手动控制11", "M52.0", 1, 1));
add(new Res_PLCADDRESS("手动控制12", "M52.1", 1, 1));
add(new Res_PLCADDRESS("手动控制13", "M52.2", 1, 1));
add(new Res_PLCADDRESS("手动控制14", "M52.3", 1, 1));
add(new Res_PLCADDRESS("手动控制15", "M52.4", 1, 1));
add(new Res_PLCADDRESS("手动控制16", "M52.5", 1, 1));


add(new Res_PLCADDRESS("M_外置仓1反转", "M50.6", 1, 1));
add(new Res_PLCADDRESS("M_外置仓2反转", "M50.7", 1, 1));
add(new Res_PLCADDRESS("M_外置仓3反转", "M51.0", 1, 1));
add(new Res_PLCADDRESS("M_外置仓4反转", "M51.1", 1, 1));
add(new Res_PLCADDRESS("M_外置仓5反转", "M51.2", 1, 1));
add(new Res_PLCADDRESS("M_外置仓6反转", "M51.3", 1, 1));


add(new Res_PLCADDRESS("保温池进水阀", "M103.4", 1, 1));
add(new Res_PLCADDRESS("保温池排水阀", "M103.5", 1, 1));
add(new Res_PLCADDRESS("猪油管道保温", "M103.6", 1, 1));
add(new Res_PLCADDRESS("牛油管道保温", "M103.7", 1, 1));
add(new Res_PLCADDRESS("保温池加热", "M104.0", 1, 1));
add(new Res_PLCADDRESS("三色灯-绿", "M104.1", 1, 1));
add(new Res_PLCADDRESS("三色灯-红", "M104.2", 1, 1));

// add(new Res_PLCADDRESS("M_保温池进水阀", "M53.4", 1, 1));
// add(new Res_PLCADDRESS("M_保温池排水阀", "M53.5", 1, 1));
// add(new Res_PLCADDRESS("M_猪油管道保温", "M53.6", 1, 1));
// add(new Res_PLCADDRESS("M_牛油管道保温", "M53.7", 1, 1));
// add(new Res_PLCADDRESS("M_保温池加热", "M54.0", 1, 1));
// add(new Res_PLCADDRESS("M_三色灯-绿", "M54.1", 1, 1));
// add(new Res_PLCADDRESS("M_三色灯-红", "M54.2", 1, 1));

add(new Res_PLCADDRESS("扫码数据读取", "-------------", 0, 0));
add(new Res_PLCADDRESS("扫码数据", "VW702", 1, 0));

add(new Res_PLCADDRESS("实时状态读取", "-------------", 0, 0));
add(new Res_PLCADDRESS("实时状态", "VW500", 1, 0));
add(new Res_PLCADDRESS("水池液位检测", "M5.2", 1, 0));
add(new Res_PLCADDRESS("出料口检测", "M5.3", 1, 0));
add(new Res_PLCADDRESS("水池进水阀", "M103.4", 1, 1));
add(new Res_PLCADDRESS("水池排水阀-开", "M103.5", 1, 1));
add(new Res_PLCADDRESS("水池排水阀-关", "M103.5", 1, 1));

add(new Res_PLCADDRESS("管道自动排水", "M5.4", 1, 1));
add(new Res_PLCADDRESS("管道自动排水完成", "M5.5", 1, 1));
// add(new Res_PLCADDRESS("粉料仓", "-------------", 0, 0));
// for (int i=1;i<=6;i++){
// add(new Res_PLCADDRESS("粉料仓"+(i+5)+"出料时间", "VW"+(112+(i*2)), 0, 1));
// add(new Res_PLCADDRESS("粉料仓"+(i+5)+"启停控制", Unity.GetSiemensBitSingleAdd("M",7+i,10), 1, 1));
// }
//
// add(new Res_PLCADDRESS("液体仓", "-------------", 0, 0));
// for (int i=1;i<=4;i++){
// add(new Res_PLCADDRESS("液体仓"+(i+11)+"出料时间", "VW"+(124+(i*2)), 0, 1));
// add(new Res_PLCADDRESS("液体仓"+(i+11)+"启停控制", Unity.GetSiemensBitSingleAdd("M",5+i,11), 1, 1));
// }
//
// add(new Res_PLCADDRESS("备用仓", "-------------", 0, 0));
// for (int i=1;i<=9;i++){
// add(new Res_PLCADDRESS("备用仓"+i+"出料时间", "VW"+(132+(i*2)), 0, 1));
// add(new Res_PLCADDRESS("备用仓"+i+"启停控制", Unity.GetSiemensBitSingleAdd("M",1+i,12), 1, 1));
// }

//电子秤校验
add(new Res_PLCADDRESS("电子秤", "-------------", 0, 0));
add(new Res_PLCADDRESS("称当前重量", "VW82", 1, 0));
add(new Res_PLCADDRESS("砝码值", "VW86", 1, 1));
add(new Res_PLCADDRESS("重量清零", "M20.0", 0, 1));
add(new Res_PLCADDRESS("校准模式", "M20.1", 0, 1));
add(new Res_PLCADDRESS("关闭写保护", "M20.2", 0, 1));
add(new Res_PLCADDRESS("零点校准", "M20.3", 0, 1));
add(new Res_PLCADDRESS("砝码值写入", "M20.4", 0, 1));
add(new Res_PLCADDRESS("打开写保护", "M20.5", 0, 1));

add(new Res_PLCADDRESS("其它数据", "-------------", 0, 0));
add(new Res_PLCADDRESS("扫码数据", "VW2", 1, 0));
add(new Res_PLCADDRESS("掉线标志", "M100.0", 1, 1));
add(new Res_PLCADDRESS("心跳", "M100.1", 1, 1));
}};
/**
* 配料吧台料仓模型
*/
public List<ResSilosModel> Silos_配料吧台 = new ArrayList<ResSilosModel>() {{
add(new ResSilosModel("外置仓",1 , 1 ));
add(new ResSilosModel("外置仓",2 , 2 ));
add(new ResSilosModel("外置仓",3 , 3 ));
add(new ResSilosModel("外置仓",4 , 4 ));
add(new ResSilosModel("外置仓",5 , 5 ));
add(new ResSilosModel("外置仓",6 , 6 ));
add(new ResSilosModel("粉料仓",7 , 7 ));
add(new ResSilosModel("粉料仓",8 , 8 ));
add(new ResSilosModel("粉料仓",9 , 9 ));
add(new ResSilosModel("液料仓",13, 10));
add(new ResSilosModel("液料仓",14, 11));
add(new ResSilosModel("加热仓",15, 12));
add(new ResSilosModel("加热仓",16, 13));
add(new ResSilosModel("粉料仓",10, 14));
add(new ResSilosModel("粉料仓",11, 15));
add(new ResSilosModel("粉料仓",12, 16));
int num=0;
for(int i=1;i<=26;i++){
num++;
add(new ResSilosModel("通道",num , num ));
}

// int num=0;
// for(int i=1;i<=5;i++){
// num++;
// add(new ResSilosModel("外置仓",num , num ));
// }
//
// for(int i=1;i<=6;i++){
// num++;
// add(new ResSilosModel("粉料仓",num, num ));
// }
//
// for(int i=1;i<=4;i++){
// num++;
// add(new ResSilosModel("液体仓",num, num ));
// }
//
// for(int i=1;i<=2;i++){
// num++;
// add(new ResSilosModel("加热仓",num, num ));
// }
}};

/**


+ 56
- 6
app/src/main/java/com/bonait/bnframework/common/constant/DataBus.java View File

@@ -64,6 +64,17 @@ public class DataBus {
//endregion

//region 数据中心
public long lastTimeClick;

public boolean doubleClick(){
long currentTime = System.currentTimeMillis();
if(currentTime - lastTimeClick < 350){
return true;
}
lastTimeClick = currentTime;
return false;
}

/**
* 料仓数据
*/
@@ -173,7 +184,10 @@ public class DataBus {
ArrayList<BPA_SUBORDER> suborders= QueryDB.GetSubOrdersTodayNoMake();
for (BPA_SUBORDER item:suborders)
{
AddGoodsMake(item);
if(QueryDB.GetGoodsId(item.goodsID)!=null) // ---> // --->
{
AddGoodsMake(item);
}
}

ExecuteTheRecipe.MakeGoodCount= QueryDB.GetSuOrderTodanCount();
@@ -191,14 +205,14 @@ public class DataBus {
ArrayList<String> suorderlist=new ArrayList<>();
for (ResGoodsMake item:GoodsMake)
{
if(item.makeStatus==MakeStatus.制作完成)
if(item.makeStatus==MakeStatus.制作完成 || item.makeStatus==MakeStatus.取消)
{
suorderlist.add(item.subOrder.id);
}
}
for (String item:suorderlist)
{
DeleteGoodsMake(item);
DeleteGoodsMake(item,false);
}

ResGoodsMake make=new ResGoodsMake();
@@ -291,7 +305,7 @@ public class DataBus {
/**
* 根据子订单id,设置订单制作完成
*/
public void DeleteGoodsMake(String suborderID)
public void DeleteGoodsMake(String suborderID ,boolean isError)
{
try
{
@@ -303,7 +317,7 @@ public class DataBus {
item.makeStatus=MakeStatus.制作完成;
item.makeMs="";
item.makeProcess=100;
item.subOrder.status=2;
item.subOrder.status=isError?5:2;
QueryDB.UpdateSubOrder(item.subOrder);
good=item;
}
@@ -323,6 +337,43 @@ public class DataBus {
}catch(Exception e){
}
}

/**
* 根据子订单id,设置订单制作完成
*/
public void cancelGoodsMake(String suborderID)
{
try
{
ResGoodsMake good=null;
for (ResGoodsMake item:GoodsMake)
{
if(item.subOrder.id.equals(suborderID))
{
item.makeStatus=MakeStatus.取消;
item.makeMs="";
item.makeProcess=100;
item.subOrder.status=4;
QueryDB.UpdateSubOrder(item.subOrder);
good=item;
}
}

if(good!=null)
{
GoodsMake.remove(good);
}

if(loadinggoodAdapter!=null)
{
loadinggoodAdapter.Speak(R.raw.plwc);
loadinggoodAdapter.refresh();
}
ExecuteTheRecipe.GoodMake = null;
ExecuteTheRecipe.IsMakeGood = false;
}catch(Exception e){
}
}
//endregion

//region 配方数据
@@ -334,7 +385,6 @@ public class DataBus {
* 属性数据
*/
public ArrayList<ResGoodProperty> bpa_goodproperties = new ArrayList<>();
public pfsx_adapter sxadapter=null;
/**
* 加载商品配方
*/


+ 269
- 0
app/src/main/java/com/bonait/bnframework/common/cookie/Cookie.java View File

@@ -0,0 +1,269 @@
package com.bonait.bnframework.common.cookie;

import android.content.Context;
import android.graphics.Color;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewParent;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

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

import com.bonait.bnframework.R;

/**
* Created by Eric on 2017/3/2.
*/
final class Cookie extends LinearLayout {

private Animation slideInAnimation;
private Animation slideOutAnimation;

private LinearLayout layoutCookie;
private TextView tvTitle;
private TextView tvMessage;
private ImageView ivIcon;
private TextView btnAction;
private ImageView btnActionWithIcon;
private long duration = 2000;
private int layoutGravity = Gravity.BOTTOM;

public Cookie(@NonNull final Context context) {
this(context, null);
}

public Cookie(@NonNull final Context context, @Nullable final AttributeSet attrs) {
this(context, attrs, 0);
}

public Cookie(@NonNull final Context context, @Nullable final AttributeSet attrs,
final int defStyleAttr) {
super(context, attrs, defStyleAttr);
initViews(context);
}

public int getLayoutGravity() {
return layoutGravity;
}

private void initViews(Context context) {
inflate(getContext(), R.layout.layout_cookie, this);

layoutCookie = (LinearLayout) findViewById(R.id.cookie);
tvTitle = (TextView) findViewById(R.id.tv_title);
tvMessage = (TextView) findViewById(R.id.tv_message);
ivIcon = (ImageView) findViewById(R.id.iv_icon);
btnAction = (TextView) findViewById(R.id.btn_action);
btnActionWithIcon = (ImageView) findViewById(R.id.btn_action_with_icon);
initDefaultStyle(context);
}

/**
* Init the default text color or background color. You can change the default style by set the
* Theme's attributes.
*
* <pre>
* <style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
* <item name="cookieTitleColor">@color/default_title_color</item>
* <item name="cookieMessageColor">@color/default_message_color</item>
* <item name="cookieActionColor">@color/default_action_color</item>
* <item name="cookieBackgroundColor">@color/default_bg_color</item>
* </style>
* </pre>
*/
private void initDefaultStyle(Context context) {
//Custom the default style of a cookie
int titleColor = ThemeResolver.getColor(context, R.attr.cookieTitleColor, Color.WHITE);
int messageColor = ThemeResolver.getColor(context, R.attr.cookieMessageColor, Color.WHITE);
int actionColor = ThemeResolver.getColor(context, R.attr.cookieActionColor, Color.WHITE);
int backgroundColor = ThemeResolver.getColor(context, R.attr.cookieBackgroundColor,
ContextCompat.getColor(context, R.color.default_bg_color));

tvTitle.setTextColor(titleColor);
tvMessage.setTextColor(messageColor);
btnAction.setTextColor(actionColor);
layoutCookie.setBackgroundColor(backgroundColor);
}

public void setParams(final CookieBar.Params params) {
if (params != null) {
duration = params.duration;
layoutGravity = params.layoutGravity;

//Icon
if (params.iconResId != 0) {
ivIcon.setVisibility(VISIBLE);
ivIcon.setBackgroundResource(params.iconResId);
}

//Title
if (!TextUtils.isEmpty(params.title)) {
tvTitle.setVisibility(VISIBLE);
tvTitle.setText(params.title);
if (params.titleColor != 0) {
tvTitle.setTextColor(ContextCompat.getColor(getContext(), params.titleColor));
}
}

//Message
if (!TextUtils.isEmpty(params.message)) {
tvMessage.setVisibility(VISIBLE);
tvMessage.setText(params.message);
if (params.messageColor != 0) {
tvMessage.setTextColor(ContextCompat.getColor(getContext(), params.messageColor));
}

if (TextUtils.isEmpty(params.title)) {
LayoutParams layoutParams = (LayoutParams) tvMessage
.getLayoutParams();
layoutParams.topMargin = 0;
}
}

//Action
if ((!TextUtils.isEmpty(params.action) || params.actionIcon != 0)
&& params.onActionClickListener != null) {
btnAction.setVisibility(VISIBLE);
btnAction.setText(params.action);
btnAction.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View view) {
params.onActionClickListener.onClick();
dismiss();
}
});

//Action Color
if (params.actionColor != 0) {
btnAction.setTextColor(ContextCompat.getColor(getContext(), params.actionColor));
}
}

if (params.actionIcon != 0 && params.onActionClickListener != null) {
btnAction.setVisibility(GONE);
btnActionWithIcon.setVisibility(VISIBLE);
btnActionWithIcon.setBackgroundResource(params.actionIcon);
btnActionWithIcon.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View view) {
params.onActionClickListener.onClick();
dismiss();
}
});
}

//Background
if (params.backgroundColor != 0) {
layoutCookie
.setBackgroundColor(ContextCompat.getColor(getContext(), params.backgroundColor));
}

int padding = getContext().getResources().getDimensionPixelSize(R.dimen.default_padding);
if (layoutGravity == Gravity.BOTTOM) {
layoutCookie.setPadding(padding, padding, padding, padding);
}

createInAnim();
createOutAnim();
}
}

@Override
protected void onLayout(boolean changed, int l, int t, int r, int b) {
if (layoutGravity == Gravity.TOP) {
super.onLayout(changed, l, 0, r, layoutCookie.getMeasuredHeight());
} else {
super.onLayout(changed, l, t, r, b);
}
}

private void createInAnim() {
slideInAnimation = AnimationUtils.loadAnimation(getContext(),
layoutGravity == Gravity.BOTTOM ? R.anim.slide_in_from_bottom : R.anim.slide_in_from_top);
slideInAnimation.setAnimationListener(new Animation.AnimationListener() {
@Override
public void onAnimationStart(Animation animation) {

}

@Override
public void onAnimationEnd(Animation animation) {
postDelayed(new Runnable() {
@Override
public void run() {
dismiss();
}
}, duration);
}

@Override
public void onAnimationRepeat(Animation animation) {

}
});

setAnimation(slideInAnimation);
}

private void createOutAnim() {
slideOutAnimation = AnimationUtils.loadAnimation(getContext(),
layoutGravity == Gravity.BOTTOM ? R.anim.slide_out_to_bottom : R.anim.slide_out_to_top);
slideOutAnimation.setAnimationListener(new Animation.AnimationListener() {
@Override
public void onAnimationStart(Animation animation) {

}

@Override
public void onAnimationEnd(Animation animation) {

}

@Override
public void onAnimationRepeat(Animation animation) {

}
});
}

private void dismiss() {
slideOutAnimation.setAnimationListener(new Animation.AnimationListener() {
@Override
public void onAnimationStart(final Animation animation) {
}

@Override
public void onAnimationEnd(final Animation animation) {
destroy();
}

@Override
public void onAnimationRepeat(final Animation animation) {
}
});
startAnimation(slideOutAnimation);
}

private void destroy() {
postDelayed(new Runnable() {
@Override
public void run() {
ViewParent parent = getParent();
if (parent != null) {
Cookie.this.clearAnimation();
((ViewGroup) parent).removeView(Cookie.this);
}
}
}, 200);
}

}

+ 180
- 0
app/src/main/java/com/bonait/bnframework/common/cookie/CookieBar.java View File

@@ -0,0 +1,180 @@
package com.bonait.bnframework.common.cookie;

import android.app.Activity;
import android.view.Gravity;
import android.view.ViewGroup;

import androidx.annotation.ColorRes;
import androidx.annotation.DrawableRes;
import androidx.annotation.StringRes;

/**
* CookieBar is a lightweight library for showing a brief message at the top or bottom of the
* screen. <p>
* <pre>
* new CookieBar
* .Builder(MainActivity.this)
* .setTitle("TITLE")
* .setMessage("MESSAGE")
* .setAction("ACTION", new OnActionClickListener() {})
* .show();
* </pre>
* <p> Created by Eric on 2017/3/2.
*/
public class CookieBar {

private static final String TAG = "cookie";

private Cookie cookieView;
private Activity context;

private CookieBar() {
}

private CookieBar(Activity context, Params params) {
this.context = context;
cookieView = new Cookie(context);
cookieView.setParams(params);
}

public void show() {
if (cookieView != null) {
final ViewGroup decorView = (ViewGroup) context.getWindow().getDecorView();
final ViewGroup content = (ViewGroup) decorView.findViewById(android.R.id.content);
if (cookieView.getParent() == null) {
if (cookieView.getLayoutGravity() == Gravity.BOTTOM) {
content.addView(cookieView);
} else {
decorView.addView(cookieView);
}
}
}
}

public static class Builder {

private Params params = new Params();

public Activity context;

/**
* Create a builder for an cookie.
*/
public Builder(Activity activity) {
this.context = activity;
}

public Builder setIcon(@DrawableRes int iconResId) {
params.iconResId = iconResId;
return this;
}

public Builder setTitle(String title) {
params.title = title;
return this;
}

public Builder setTitle(@StringRes int resId) {
params.title = context.getString(resId);
return this;
}

public Builder setMessage(String message) {
params.message = message;
return this;
}

public Builder setMessage(@StringRes int resId) {
params.message = context.getString(resId);
return this;
}

public Builder setDuration(long duration) {
params.duration = duration;
return this;
}

public Builder setTitleColor(@ColorRes int titleColor) {
params.titleColor = titleColor;
return this;
}

public Builder setMessageColor(@ColorRes int messageColor) {
params.messageColor = messageColor;
return this;
}

public Builder setBackgroundColor(@ColorRes int backgroundColor) {
params.backgroundColor = backgroundColor;
return this;
}

public Builder setActionColor(@ColorRes int actionColor) {
params.actionColor = actionColor;
return this;
}

public Builder setAction(String action, OnActionClickListener onActionClickListener) {
params.action = action;
params.onActionClickListener = onActionClickListener;
return this;
}

public Builder setAction(@StringRes int resId, OnActionClickListener onActionClickListener) {
params.action = context.getString(resId);
params.onActionClickListener = onActionClickListener;
return this;
}

public Builder setActionWithIcon(@DrawableRes int resId,
OnActionClickListener onActionClickListener) {
params.actionIcon = resId;
params.onActionClickListener = onActionClickListener;
return this;
}

public Builder setLayoutGravity(int layoutGravity) {
params.layoutGravity = layoutGravity;
return this;
}

public CookieBar create() {
CookieBar cookie = new CookieBar(context, params);
return cookie;
}

public CookieBar show() {
final CookieBar cookie = create();
cookie.show();
return cookie;
}
}

final static class Params {

public String title;

public String message;

public String action;

public OnActionClickListener onActionClickListener;

public int iconResId;

public int backgroundColor;

public int titleColor;

public int messageColor;

public int actionColor;

public long duration = 2000;

public int layoutGravity = Gravity.TOP;

public int actionIcon;
}

}

+ 84
- 0
app/src/main/java/com/bonait/bnframework/common/cookie/CookieHelper.java View File

@@ -0,0 +1,84 @@
package com.bonait.bnframework.common.cookie;

import android.app.Activity;
import android.widget.Toast;

import com.bonait.bnframework.R;

public class CookieHelper {
public static int Mode = 0;
public static int ShowTime = 10000;

/**
* 显示消息
* @param title
* @param message
*/
public static void Show(Activity activity, String title, String message) {
if (Mode == 1) {
new CookieBar.Builder(activity)
.setBackgroundColor(R.color.app_color_blue)
.setActionColor(android.R.color.white)
.setTitleColor(R.color.white)
.setTitle(title)
.setMessage(message)
.setDuration(ShowTime)
.setActionWithIcon(R.mipmap.ic_action_close, new OnActionClickListener() {
@Override
public void onClick() {

}
})
.show();
} else {
new CookieBar.Builder(activity)
.setTitle(title)
.setMessage(message)
.setDuration(ShowTime)
.setBackgroundColor(R.color.app_color_blue)
.setActionColor(android.R.color.white)
.setTitleColor(R.color.white)
.setAction("已读确认关闭", new OnActionClickListener() {
@Override
public void onClick() {

}
})
.show();
}
}

public static void Show(Activity activity, String title, String message,int showTime) {
if (Mode == 1) {
new CookieBar.Builder(activity)
.setBackgroundColor(R.color.app_color_blue)
.setActionColor(android.R.color.white)
.setTitleColor(R.color.white)
.setTitle(title)
.setMessage(message)
.setDuration(showTime)
.setActionWithIcon(R.mipmap.ic_action_close, new OnActionClickListener() {
@Override
public void onClick() {

}
})
.show();
} else {
new CookieBar.Builder(activity)
.setTitle(title)
.setMessage(message)
.setDuration(showTime)
.setBackgroundColor(R.color.app_color_blue)
.setActionColor(android.R.color.white)
.setTitleColor(R.color.white)
.setAction("已读确认关闭", new OnActionClickListener() {
@Override
public void onClick() {

}
})
.show();
}
}
}

+ 10
- 0
app/src/main/java/com/bonait/bnframework/common/cookie/OnActionClickListener.java View File

@@ -0,0 +1,10 @@
package com.bonait.bnframework.common.cookie;

/**
* Created by Eric on 2017/3/3.
*/
public interface OnActionClickListener {

void onClick();

}

+ 26
- 0
app/src/main/java/com/bonait/bnframework/common/cookie/ThemeResolver.java View File

@@ -0,0 +1,26 @@
package com.bonait.bnframework.common.cookie;

import android.content.Context;
import android.content.res.TypedArray;

import androidx.annotation.AttrRes;

/**
* Created by Eric on 2017/3/21.
*/
public class ThemeResolver {

public static int getColor(Context context, @AttrRes int attr) {
return getColor(context, attr, 0);
}

public static int getColor(Context context, @AttrRes int attr, int defaultColor) {
TypedArray a = context.getTheme().obtainStyledAttributes(new int[]{attr});
try {
return a.getColor(0, defaultColor);
} finally {
a.recycle();
}
}

}

+ 306
- 7
app/src/main/java/com/bonait/bnframework/common/db/QueryDB.java View File

@@ -5,6 +5,7 @@ import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;

import com.apkfuns.logutils.LogUtils;
import com.bonait.bnframework.common.constant.ConfigName;
import com.bonait.bnframework.common.db.file.DBHelper;
import com.bonait.bnframework.common.db.mode.BPA_CLOUDDATA;
@@ -12,14 +13,12 @@ import com.bonait.bnframework.common.db.mode.BPA_GOODPROPERTY;
import com.bonait.bnframework.common.db.mode.BPA_GOODSRECIPENAME;
import com.bonait.bnframework.common.db.mode.BPA_GOODSTYPE;
import com.bonait.bnframework.common.db.mode.BPA_MATERIAL;
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_CRAFT;
import com.bonait.bnframework.common.db.mode.BPA_CRAFTPROCESS;
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_LOG;
import com.bonait.bnframework.common.db.mode.BPA_MATERIAL;
import com.bonait.bnframework.common.db.mode.BPA_MENU;
import com.bonait.bnframework.common.db.mode.BPA_MENUANDUSER;
import com.bonait.bnframework.common.db.mode.BPA_ORDER;
@@ -30,6 +29,7 @@ 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_SILOS_CALIBRATE;
import com.bonait.bnframework.common.db.mode.BPA_SUBORDER;
import com.bonait.bnframework.common.db.mode.BPA_SUGAR;
import com.bonait.bnframework.common.db.mode.BPA_SYSTEMSET;
@@ -38,10 +38,9 @@ import com.bonait.bnframework.common.db.mode.ModeBase;
import com.bonait.bnframework.common.db.res.ResAlertLog;
import com.bonait.bnframework.common.db.res.ResGoodsRecipe;
import com.bonait.bnframework.common.db.res.ResLog;
import com.bonait.bnframework.common.db.res.ResSilosMode;
import com.bonait.bnframework.common.db.res.ResSubOrder;
import com.bonait.bnframework.common.db.util.ListAddUtil;
import com.bonait.bnframework.common.helper.Tools;
import com.bonait.bnframework.common.utils.PreferenceUtils;

import java.lang.reflect.Field;
import java.text.SimpleDateFormat;
@@ -49,20 +48,30 @@ import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;


//数据库操作说明
//https://blog.csdn.net/hdhhd/article/details/127774316

/**
* 数据库数据访问类库
* add fengyoufu 20230413
*/
public class QueryDB {

private QueryDB() {
List<BPA_MATERIAL> items = new ArrayList<>();
List<BPA_MATERIAL> res = items.stream().filter(p->p.name.equals("tt")).collect(Collectors.toList());
}

//region 成员变量
/**
* 数据库链接
*/
private static DBHelper helper = DBHelper.getInstance(ConfigName.getInstance().dishesCon);
public static DBHelper helper = DBHelper.getInstance(ConfigName.getInstance().dishesCon);

/**
* 时间倒序
@@ -97,6 +106,11 @@ public class QueryDB {
return Add(BPA_MATERIAL.class, data);
}

public static boolean AddMaterialList(List<BPA_MATERIAL> data) {

return ListAddUtil.AddMATERIALList(BPA_MATERIAL.class, data);
}

/**
* 修改物料数据
* add fengyoufu 20230413
@@ -712,6 +726,13 @@ public class QueryDB {
return Add(BPA_GOODS.class, data);
}

/**
* 新增商品表
*/
public static boolean AddGoodsList(List<BPA_GOODS> data) {
return ListAddUtil.AddGoodsList(BPA_GOODS.class, data);
}

/**
* 修改商品
* add fengyoufu 20230413
@@ -1000,6 +1021,17 @@ public class QueryDB {
return Add(BPA_GOODSTYPE.class, data);
}

/**
* 新增
* add fengyoufu 20230413
*
* @param data
* @return 是否成功
*/
public static boolean AddGoodsTypeList(List<BPA_GOODSTYPE> data) {
return ListAddUtil.AddGOODSTYPEList(BPA_GOODSTYPE.class, data);
}

/**
* 修改
* add fengyoufu 20230413
@@ -1071,6 +1103,15 @@ public class QueryDB {
return Add(BPA_GOODPROPERTY.class, data);
}

/**
* 批量新增
* @param data
* @return
*/
public static boolean AddGoodsPropertyList(List<BPA_GOODPROPERTY> data) {
return ListAddUtil.AddGoodsPropertyList(BPA_GOODPROPERTY.class, data);
}

/**
* 修改
* add fengyoufu 20230413
@@ -1109,6 +1150,23 @@ public class QueryDB {
return data;
}

/**
* 获取所有子属性
*
* @return
*/
public static ArrayList<BPA_GOODPROPERTY> GetGoodsSubPropertyALL() {
String orderby = Desc_Time_Up;//先按排序 创建时间倒序
String where = "isDelete=?";
String[] args = new String[]{"0"};
ArrayList<BPA_GOODPROPERTY> data = new ArrayList<>();
ArrayList<Object> obj = Get(BPA_GOODPROPERTY.class, where, args, orderby);
for (Object k : obj) {
data.add((BPA_GOODPROPERTY) k);
}
return data;
}

/**
* 获取所有父级
*
@@ -1126,6 +1184,23 @@ public class QueryDB {
return data;
}

/**
* 获取分类下的父属性
*
* @return
*/
public static ArrayList<BPA_GOODPROPERTY> GetGoodsPropertyByTypeId(String GoodsTypeId) {
String orderby = Desc_Sort_Up + ',' +Desc_Time_Up;//先按排序 创建时间倒序
String where = "isDelete=? and GoodsTypeId=?";
String[] args = new String[]{"0", GoodsTypeId};
ArrayList<BPA_GOODPROPERTY> data = new ArrayList<>();
ArrayList<Object> obj = Get(BPA_GOODPROPERTY.class, where, args, orderby);
for (Object k : obj) {
data.add((BPA_GOODPROPERTY) k);
}
return data;
}

/**
* 判断是否存在
*
@@ -1215,6 +1290,10 @@ public class QueryDB {
return Add(BPA_GOODSRECIPENAME.class, data);
}

public static boolean AddGoodsRecipeNameList(List<BPA_GOODSRECIPENAME> data) {
return ListAddUtil.AddGoodsRecipeNameList(BPA_GOODSRECIPENAME.class, data);
}

/**
* 修改
* add fengyoufu 20230413
@@ -1269,6 +1348,7 @@ public class QueryDB {
for (Object k : obj) {
data.add((BPA_GOODSRECIPENAME) k);
}
LogUtils.d("GetGoodsRecipeNameGoodId data="+data.toString());
return data;
} catch (Exception e) {
Log.d("商品ID查询配方信息", "商品ID查询配方信息异常: " + e.getMessage());
@@ -1305,7 +1385,7 @@ public class QueryDB {
* @param
* @return
*/
public static BPA_GOODSRECIPENAME GetGoodsRecipeNameDesignId(String zfid,String goodid) {
public static BPA_GOODSRECIPENAME GetGoodsRecipeNameDesignId2(String zfid,String goodid) {
try {
String orderby = Desc_Time_Up;//出料顺序
String where = "isDelete=? and design=? and goodsID=?";
@@ -1321,6 +1401,55 @@ public class QueryDB {
return null;
}
}

/**
* 做法ID查询配方关联表
*
* @param
* @return
*/
public static BPA_GOODSRECIPENAME GetGoodsRecipeNameDesignId(String zfid,String goodid) {
try {
boolean exist = false;
String orderby = Desc_Time_Up;//出料顺序
String where = "isDelete=? and goodsID=?";
String[] args = new String[]{"0",goodid};
ArrayList<BPA_GOODSRECIPENAME> data = new ArrayList<>();
ArrayList<Object> obj = Get(BPA_GOODSRECIPENAME.class, where, args, orderby);
for (Object k : obj) {
BPA_GOODSRECIPENAME bean = (BPA_GOODSRECIPENAME) k;
if (zfid.isEmpty()) {
if(bean.design == null || bean.design.isEmpty()){
return bean;
}
} else if (bean.design.contains(",") && zfid.contains(",")) {
String[] res = bean.design.split(",");
String[] res2 = zfid.split(",");
if (res.length == res2.length) {
boolean xx = true;
for (String s : res) {
if (!zfid.contains(s)) {
xx = false;
}
}
if (xx) {
return bean;
}
}
}else{
if(!bean.design.isEmpty()){
if(zfid.equals(bean.design)){
return bean;
}
}
}
}
return null;
} catch (Exception e) {
Log.d("商品ID查询配方信息", "商品ID查询配方信息异常: " + e.getMessage());
return null;
}
}
//endregion

//region BPA_GOODSRECIPE 商品配方明细表
@@ -1336,6 +1465,10 @@ public class QueryDB {
return Add(BPA_GOODSRECIPE.class, data);
}

public static boolean AddGoodsSrecipeList(List<BPA_GOODSRECIPE> data) {
return ListAddUtil.AddGoodsSrecipeList(BPA_GOODSRECIPE.class, data);
}

/**
* 修改商品配方明细
* add fengyoufu 20230413
@@ -1510,6 +1643,7 @@ public class QueryDB {
data.add(par);
}
}
LogUtils.d("GetGoodsSrecipeList 根据商品id查询配方信息 data.size="+data.size());
return data;
}

@@ -1764,6 +1898,9 @@ public class QueryDB {
case 3:
sub.statusText = "已超时";
break;
case 4:
sub.statusText = "已取消";
break;
}
}

@@ -3043,6 +3180,100 @@ public class QueryDB {
}
//endregion

//region 料仓校准表
/**
* 新增料仓校准
* add liup 20240418
*
* @param data
* @return 是否成功
*/
public static boolean AddSilosCalibrate(BPA_SILOS_CALIBRATE data) {
return Add(BPA_SILOS_CALIBRATE.class, data);
}

/**
* 查询所有料仓校准
* add liup 20240418
* @return
*/
public static ArrayList<BPA_SILOS_CALIBRATE> GetSilosCalibrateAll() {
String orderby = "num";//先按排序 创建时间倒序
String where = "isDelete=?";
String[] args = new String[]{"0"};
ArrayList<BPA_SILOS_CALIBRATE> data = new ArrayList<>();
ArrayList<Object> obj = Get(BPA_SILOS_CALIBRATE.class, where, args, orderby);
for (Object k : obj) {
data.add((BPA_SILOS_CALIBRATE) k);
}
// LogUtils.d(" GetSilosCalibrateLIst 查询所有料仓校准 data="+data.toString());
return data;
}

/**
* 根据ID查询料仓校准
*
* @return
*/
public static BPA_SILOS_CALIBRATE GetSilosCalibrate(String id) {
BPA_SILOS_CALIBRATE data = null;
String orderby = "null";//先按排序 创建时间倒序
String where = "isDelete=? and id=?";
String[] args = new String[]{"0", id};
ArrayList<Object> obj = Get(BPA_SILOS_CALIBRATE.class, where, args, orderby);
for (Object k : obj) {
data = (BPA_SILOS_CALIBRATE) k;
}
return data;
}

/**
* 根据名称序号料仓校准
*
* @return
*/
public static BPA_SILOS_CALIBRATE GetSilosCalibrateByNum(int num) {
BPA_SILOS_CALIBRATE data = null;
String orderby = "num";//先按排序 创建时间倒序
String where = "isDelete=? and num=?";
String[] args = new String[]{"0", num+""};
ArrayList<Object> obj = Get(BPA_SILOS_CALIBRATE.class, where, args, orderby);
for (Object k : obj) {
data = (BPA_SILOS_CALIBRATE) k;
}
return data;
}

/**
* 修改料仓校准
*
* @param id
* @param outputMax
* @param outputMin
* @param inputMax
* @param inputMin
*/
public static boolean UpdateSilosCalibrate(String id, float outputMax,float outputMin,float inputMax,float inputMin) {
BPA_SILOS_CALIBRATE silos = GetSilosCalibrate(id);
if (silos != null) {
if(outputMax>=0){
silos.outputTimeMax = outputMax;
}
if(outputMin>=0){
silos.outputTimeMin = outputMin;
}
if(inputMax>=0){
silos.inputWightMax = inputMax;
}
if(inputMin>=0){
silos.inputWightMin = inputMin;
}
return Update(BPA_SILOS_CALIBRATE.class, silos);
}
return false;
}
//endregion

//region 私有

/**
@@ -3093,6 +3324,64 @@ public class QueryDB {
return isSucess;
}

/**
* 批量新增
* @param c
* @param list
* @return
*/
private static boolean AddList(Class c, List<Object> list) {
if(list.isEmpty()){
return false;
}
lock.lock();
boolean isSucess = false;
SQLiteDatabase db = helper.getWritableDatabase();
try {
long insert=-1;
db.beginTransaction();
for(int i = 0; i < list.size(); i++){
ContentValues cv = new ContentValues();

Map<String, Object> map = Tools.getObjValue(list.get(i));
if (map.get("id").toString().isEmpty())
return false;
for (String key : map.keySet()) {
Object value = map.get(key);
if (value instanceof String) {
cv.put(key, (String) value);
} else if (value instanceof Integer) {
cv.put(key, ((Integer) value).intValue());
} else if (value instanceof Double) {
cv.put(key, ((Double) value).doubleValue());
} else if (value instanceof Float) {
cv.put(key, ((Float) value).floatValue());
} else if (value instanceof Long) {
cv.put(key, ((Long) value).longValue());
} else if (value instanceof Boolean) {
cv.put(key, ((Boolean) value).booleanValue());
}
}
insert = db.insertOrThrow(c.getSimpleName(), null, cv);
if (insert == -1) {
throw new Exception("Failed to insert data at index " + i);
}
}

db.setTransactionSuccessful();

isSucess = insert > 0;
} catch (Exception e) {
// db.close();
isSucess = false;
} finally {
db.endTransaction();
db.close();
lock.unlock();
}
return isSucess;
}

/**
* 修改
*
@@ -3230,7 +3519,7 @@ public class QueryDB {
* @param orderby "date("+COLUMN_DATE+") desc" "TYPE desc"; desc 倒序
* @return
*/
private static ArrayList<Object> Get(Class c, String whereClause, String[] Args, String orderby) {
public static ArrayList<Object> Get(Class c, String whereClause, String[] Args, String orderby) {
lock.lock();
ArrayList<Object> rlts = new ArrayList<Object>();
SQLiteDatabase db = helper.getReadableDatabase();
@@ -3457,6 +3746,16 @@ public class QueryDB {
((BPA_PLCADDRESS) data).isread = cursor.getInt((int) cursor.getColumnIndex("isread"));
((BPA_PLCADDRESS) data).iswrite = cursor.getInt((int) cursor.getColumnIndex("iswrite"));
break;
case "BPA_SILOS_CALIBRATE":
data = new BPA_SILOS_CALIBRATE();
//私有
((BPA_SILOS_CALIBRATE) data).name = cursor.getString((int) cursor.getColumnIndex("name"));
((BPA_SILOS_CALIBRATE) data).inputWightMin = cursor.getFloat((int) cursor.getColumnIndex("inputWightMin"));
((BPA_SILOS_CALIBRATE) data).inputWightMax = cursor.getFloat((int) cursor.getColumnIndex("inputWightMax"));
((BPA_SILOS_CALIBRATE) data).outputTimeMin = cursor.getFloat((int) cursor.getColumnIndex("outputTimeMin"));
((BPA_SILOS_CALIBRATE) data).outputTimeMax = cursor.getFloat((int) cursor.getColumnIndex("outputTimeMax"));
((BPA_SILOS_CALIBRATE) data).num = cursor.getInt((int) cursor.getColumnIndex("num"));
break;
}
((ModeBase) data).id = cursor.getString((int) cursor.getColumnIndex("id"));
((ModeBase) data).createTime = cursor.getString((int) cursor.getColumnIndex("createTime"));


+ 5
- 1
app/src/main/java/com/bonait/bnframework/common/db/file/DBHelper.java View File

@@ -27,6 +27,7 @@ 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_SILOS_CALIBRATE;
import com.bonait.bnframework.common.db.mode.BPA_SUBORDER;
import com.bonait.bnframework.common.db.mode.BPA_SUGAR;
import com.bonait.bnframework.common.db.mode.BPA_SYSTEMSET;
@@ -131,13 +132,15 @@ public class DBHelper extends SQLiteOpenHelper {
CreateTablesAll(BPA_CLOUDDATA.class,null);//云端表
CreateTablesAll(BPA_PLCADDRESS.class,null);//PLC地址模型表

CreateTablesAll(BPA_SILOS_CALIBRATE.class,null);//料仓校准表

ForeignKeys();
}
/**
* 创建数据库表
* @param c
*/
private void CreateTablesAll(Class c,String premarykey)
public void CreateTablesAll(Class c,String premarykey)
{
if (premarykey == null){

@@ -240,6 +243,7 @@ public class DBHelper extends SQLiteOpenHelper {
}
db.setTransactionSuccessful();
db.endTransaction();
db.close();
}
/**


+ 11
- 0
app/src/main/java/com/bonait/bnframework/common/db/mode/BPA_GOODPROPERTY.java View File

@@ -19,4 +19,15 @@ public class BPA_GOODPROPERTY extends ModeBase {
* 商品类型id
*/
public String GoodsTypeId;

@Override
public String toString() {
return "BPA_GOODPROPERTY{" +
"name='" + name + '\'' +
", foreignKeyRe='" + foreignKeyRe + '\'' +
", parentid='" + parentid + '\'' +
", sort=" + sort +
", GoodsTypeId='" + GoodsTypeId + '\'' +
'}';
}
}

+ 16
- 0
app/src/main/java/com/bonait/bnframework/common/db/mode/BPA_GOODS.java View File

@@ -25,4 +25,20 @@ public class BPA_GOODS extends ModeBase {
public String materialids;
//外键集合
public String foreignKeyRe;//商品外键id

@Override
public String toString() {
return "BPA_GOODS{" +
"name='" + name + '\'' +
", url='" + url + '\'' +
", sort=" + sort +
", status=" + status +
", maketime=" + maketime +
", issc=" + issc +
", gyid='" + gyid + '\'' +
", goodtype='" + goodtype + '\'' +
", materialids='" + materialids + '\'' +
", foreignKeyRe='" + foreignKeyRe + '\'' +
'}';
}
}

+ 9
- 0
app/src/main/java/com/bonait/bnframework/common/db/mode/BPA_GOODSRECIPENAME.java View File

@@ -12,4 +12,13 @@ public class BPA_GOODSRECIPENAME extends ModeBase {
public String name;
//规格集合 ids
public String design;//商品规格

@Override
public String toString() {
return "BPA_GOODSRECIPENAME{" +
"goodsID='" + goodsID + '\'' +
", name='" + name + '\'' +
", design='" + design + '\'' +
'}';
}
}

+ 53
- 0
app/src/main/java/com/bonait/bnframework/common/db/mode/BPA_SILOS_CALIBRATE.java View File

@@ -0,0 +1,53 @@
package com.bonait.bnframework.common.db.mode;

/**
* BPA_SILOS[料仓管理表]
* 创建人:fengyoufu add 20230412
*/
public class BPA_SILOS_CALIBRATE extends ModeBase {
//料仓名称
public String name;
//料仓编号
public int num;
//输出时间最大值:s
public float outputTimeMax;
//输出时间最小值:s
public float outputTimeMin;
//输入重量最大值: g
public float inputWightMax;
//输入重量最小值: g
public float inputWightMin;

public BPA_SILOS_CALIBRATE(String _nmae,int _num,float _OutMax,float _OutMin,float _InputMax,float _InputMin){
name=_nmae;
num=_num;
outputTimeMax=_OutMax;
outputTimeMin=_OutMin;
inputWightMax=_InputMax;
inputWightMin=_InputMin;
}

public BPA_SILOS_CALIBRATE(){

}

@Override
public String toString() {
return "BPA_SILOS_CALIBRATE{" +
"name='" + name + '\'' +
"num='" + num + '\'' +
", outputTimeMax=" + outputTimeMax +
", outputTimeMin=" + outputTimeMin +
", inputWightMax=" + inputWightMax +
", inputWightMin=" + inputWightMin +
", id='" + id + '\'' +
", createTime='" + createTime + '\'' +
", updateTime='" + updateTime + '\'' +
", deleteTime='" + deleteTime + '\'' +
", deviceID='" + deviceID + '\'' +
", userID='" + userID + '\'' +
", isDelete=" + isDelete +
", exp='" + exp + '\'' +
'}';
}
}

+ 1
- 1
app/src/main/java/com/bonait/bnframework/common/db/mode/BPA_SUBORDER.java View File

@@ -13,7 +13,7 @@ public class BPA_SUBORDER extends ModeBase{
public String recipeID;
//数量:例如 *1 *2
public int number;
//状态:0 未开始 1 制作中 2 已制作 3 已超时
//状态:0 未开始 1 制作中 2 已制作 3 已超时 4 取消
public int status;
//商品图片
public String goodImg;


+ 1
- 0
app/src/main/java/com/bonait/bnframework/common/db/res/MakeStatus.java View File

@@ -3,5 +3,6 @@ package com.bonait.bnframework.common.db.res;
public enum MakeStatus {
等待中,
制作中,
取消,
制作完成
}

+ 12
- 1
app/src/main/java/com/bonait/bnframework/common/db/res/ResGoodProperty.java View File

@@ -10,6 +10,17 @@ import java.util.List;
* 查询
*/
public class ResGoodProperty extends BPA_GOODPROPERTY {
public Boolean isSelect;
public Boolean isSelect = false;
public ArrayList<ResGoodProperty> child;

@Override
public String toString() {
return "ResGoodProperty==>{" +
"isSelect=" + isSelect +
", child=" + child +
", id='" + id + '\'' +
", parentid='" + parentid + '\'' +
", name='" + name + '\'' +
'}';
}
}

+ 16
- 0
app/src/main/java/com/bonait/bnframework/common/db/res/ResGoodsMake.java View File

@@ -59,5 +59,21 @@ public class ResGoodsMake {
Gt1=false;
Gt2=false;
}

@Override
public String toString() {
return "ResGoodsMake{" +
"good=" + good +
", goodsrecipename=" + goodsrecipename +
", recipes=" + recipes +
", subOrder=" + subOrder +
", makeStatus=" + makeStatus +
", makeMs='" + makeMs + '\'' +
", makeProcess=" + makeProcess +
", IsMake=" + IsMake +
", Gt1=" + Gt1 +
", Gt2=" + Gt2 +
'}';
}
}


Some files were not shown because too many files changed in this diff

Loading…
Cancel
Save